[multiple changes]
[gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c o
6 @c GNAT DOCUMENTATION o
7 @c o
8 @c G N A T _ U G N o
9 @c o
10 @c Copyright (C) 1992-2013, Free Software Foundation, Inc. o
11 @c o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c GNAT_UGN Style Guide
31 @c
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
34 @c
35 @c @chapter
36 @c @section
37 @c @subsection
38 @c @subsubsection
39 @c @subsubsubsection
40 @c
41 @c @end smallexample
42 @c @end itemize
43 @c @end enumerate
44 @c
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
60 @c
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
63 @c
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
66 @c
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c or "ali".
69 @c
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
72 @c
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
76 @c
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
79 @c Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @set TITLESUFFIX
98 @end ifset
99
100 @ifset vms
101 @set PLATFORM OpenVMS
102 @set TITLESUFFIX for OpenVMS
103 @end ifset
104
105 @c @ovar(ARG)
106 @c ----------
107 @c The ARG is an optional argument. To be used for macro arguments in
108 @c their documentation (@defmac).
109 @macro ovar{varname}
110 @r{[}@var{\varname\}@r{]}@c
111 @end macro
112 @c Status as of November 2009:
113 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
114 @c differently, and faulty output is produced by one or the other
115 @c depending on whether the "@c" is present or absent.
116 @c As a result, the @ovar macro is not used, and all invocations
117 @c of the @ovar macro have been expanded inline.
118
119
120 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
121 @dircategory GNU Ada tools
122 @direntry
123 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @end direntry
125
126 @include gcc-common.texi
127
128 @setchapternewpage odd
129 @syncodeindex fn cp
130 @c %**end of header
131
132 @titlepage
133 @title @value{EDITION} User's Guide
134 @ifset vms
135 @sp 1
136 @flushright
137 @titlefont{@i{@value{PLATFORM}}}
138 @end flushright
139 @end ifset
140
141 @sp 2
142
143 @subtitle GNAT, The GNU Ada Compiler
144 @versionsubtitle
145 @author AdaCore
146
147 @page
148 @vskip 0pt plus 1filll
149
150 @insertcopying
151
152 @end titlepage
153
154 @ifnottex
155 @node Top, About This Guide, (dir), (dir)
156 @top @value{EDITION} User's Guide
157
158 @noindent
159 @value{EDITION} User's Guide @value{PLATFORM}
160
161 @noindent
162 GNAT, The GNU Ada Compiler@*
163 GCC version @value{version-GCC}@*
164
165 @noindent
166 AdaCore@*
167
168 @menu
169 * About This Guide::
170 * Getting Started with GNAT::
171 * The GNAT Compilation Model::
172 * Compiling Using gcc::
173 * Binding Using gnatbind::
174 * Linking Using gnatlink::
175 * The GNAT Make Program gnatmake::
176 * Improving Performance::
177 * Renaming Files Using gnatchop::
178 * Configuration Pragmas::
179 * Handling Arbitrary File Naming Conventions Using gnatname::
180 * GNAT Project Manager::
181 * Tools Supporting Project Files::
182 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
184 * The GNAT Metric Tool gnatmetric::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying Properties Using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Creating Unit Tests Using gnattest::
198 * Performing Dimensionality Analysis in GNAT::
199 * Generating Ada Bindings for C and C++ headers::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 @ifset vms
206 * Compatibility with HP Ada::
207 @end ifset
208 * Platform-Specific Information for the Run-Time Libraries::
209 * Example of Binder Output File::
210 * Elaboration Order Handling in GNAT::
211 * Overflow Check Handling in GNAT::
212 * Conditional Compilation::
213 * Inline Assembler::
214 * Compatibility and Porting Guide::
215 * Microsoft Windows Topics::
216 * Mac OS Topics::
217 * GNU Free Documentation License::
218 * Index::
219
220 --- The Detailed Node Listing ---
221
222 About This Guide
223
224 * What This Guide Contains::
225 * What You Should Know before Reading This Guide::
226 * Related Information::
227 * Conventions::
228
229 Getting Started with GNAT
230
231 * Running GNAT::
232 * Running a Simple Ada Program::
233 * Running a Program with Multiple Units::
234 * Using the gnatmake Utility::
235 @ifset vms
236 * Editing with Emacs::
237 @end ifset
238 @ifclear vms
239 * Introduction to GPS::
240 @end ifclear
241
242 The GNAT Compilation Model
243
244 * Source Representation::
245 * Foreign Language Representation::
246 * File Naming Rules::
247 * Using Other File Names::
248 * Alternative File Naming Schemes::
249 * Generating Object Files::
250 * Source Dependencies::
251 * The Ada Library Information Files::
252 * Binding an Ada Program::
253 * Mixed Language Programming::
254 @ifclear vms
255 * Building Mixed Ada & C++ Programs::
256 * Comparison between GNAT and C/C++ Compilation Models::
257 @end ifclear
258 * Comparison between GNAT and Conventional Ada Library Models::
259 @ifset vms
260 * Placement of temporary files::
261 @end ifset
262
263 Foreign Language Representation
264
265 * Latin-1::
266 * Other 8-Bit Codes::
267 * Wide Character Encodings::
268
269 Compiling Ada Programs With gcc
270
271 * Compiling Programs::
272 * Switches for gcc::
273 * Search Paths and the Run-Time Library (RTL)::
274 * Order of Compilation Issues::
275 * Examples::
276
277 Switches for gcc
278
279 * Output and Error Message Control::
280 * Warning Message Control::
281 * Debugging and Assertion Control::
282 * Validity Checking::
283 * Style Checking::
284 * Run-Time Checks::
285 * Using gcc for Syntax Checking::
286 * Using gcc for Semantic Checking::
287 * Compiling Different Versions of Ada::
288 * Character Set Control::
289 * File Naming Control::
290 * Subprogram Inlining Control::
291 * Auxiliary Output Control::
292 * Debugging Control::
293 * Exception Handling Control::
294 * Units to Sources Mapping Files::
295 * Integrated Preprocessing::
296 @ifset vms
297 * Return Codes::
298 @end ifset
299
300 Binding Ada Programs With gnatbind
301
302 * Running gnatbind::
303 * Switches for gnatbind::
304 * Command-Line Access::
305 * Search Paths for gnatbind::
306 * Examples of gnatbind Usage::
307
308 Switches for gnatbind
309
310 * Consistency-Checking Modes::
311 * Binder Error Message Control::
312 * Elaboration Control::
313 * Output Control::
314 * Binding with Non-Ada Main Programs::
315 * Binding Programs with No Main Subprogram::
316
317 Linking Using gnatlink
318
319 * Running gnatlink::
320 * Switches for gnatlink::
321
322 The GNAT Make Program gnatmake
323
324 * Running gnatmake::
325 * Switches for gnatmake::
326 * Mode Switches for gnatmake::
327 * Notes on the Command Line::
328 * How gnatmake Works::
329 * Examples of gnatmake Usage::
330
331 Improving Performance
332 * Performance Considerations::
333 * Text_IO Suggestions::
334 * Reducing Size of Ada Executables with gnatelim::
335 * Reducing Size of Executables with unused subprogram/data elimination::
336
337 Performance Considerations
338 * Controlling Run-Time Checks::
339 * Use of Restrictions::
340 * Optimization Levels::
341 * Debugging Optimized Code::
342 * Inlining of Subprograms::
343 * Vectorization of loops::
344 * Other Optimization Switches::
345 * Optimization and Strict Aliasing::
346 @ifset vms
347 * Coverage Analysis::
348 @end ifset
349
350 Reducing Size of Ada Executables with gnatelim
351 * About gnatelim::
352 * Running gnatelim::
353 * Processing Precompiled Libraries::
354 * Correcting the List of Eliminate Pragmas::
355 * Making Your Executables Smaller::
356 * Summary of the gnatelim Usage Cycle::
357
358 Reducing Size of Executables with unused subprogram/data elimination
359 * About unused subprogram/data elimination::
360 * Compilation options::
361
362 Renaming Files Using gnatchop
363
364 * Handling Files with Multiple Units::
365 * Operating gnatchop in Compilation Mode::
366 * Command Line for gnatchop::
367 * Switches for gnatchop::
368 * Examples of gnatchop Usage::
369
370 Configuration Pragmas
371
372 * Handling of Configuration Pragmas::
373 * The Configuration Pragmas Files::
374
375 Handling Arbitrary File Naming Conventions Using gnatname
376
377 * Arbitrary File Naming Conventions::
378 * Running gnatname::
379 * Switches for gnatname::
380 * Examples of gnatname Usage::
381
382 The Cross-Referencing Tools gnatxref and gnatfind
383
384 * Switches for gnatxref::
385 * Switches for gnatfind::
386 * Project Files for gnatxref and gnatfind::
387 * Regular Expressions in gnatfind and gnatxref::
388 * Examples of gnatxref Usage::
389 * Examples of gnatfind Usage::
390
391 The GNAT Pretty-Printer gnatpp
392
393 * Switches for gnatpp::
394 * Formatting Rules::
395
396 The GNAT Metrics Tool gnatmetric
397
398 * Switches for gnatmetric::
399
400 File Name Krunching Using gnatkr
401
402 * About gnatkr::
403 * Using gnatkr::
404 * Krunching Method::
405 * Examples of gnatkr Usage::
406
407 Preprocessing Using gnatprep
408 * Preprocessing Symbols::
409 * Using gnatprep::
410 * Switches for gnatprep::
411 * Form of Definitions File::
412 * Form of Input Text for gnatprep::
413
414 The GNAT Library Browser gnatls
415
416 * Running gnatls::
417 * Switches for gnatls::
418 * Examples of gnatls Usage::
419
420 Cleaning Up Using gnatclean
421
422 * Running gnatclean::
423 * Switches for gnatclean::
424 @c * Examples of gnatclean Usage::
425
426 @ifclear vms
427
428 GNAT and Libraries
429
430 * Introduction to Libraries in GNAT::
431 * General Ada Libraries::
432 * Stand-alone Ada Libraries::
433 * Rebuilding the GNAT Run-Time Library::
434
435 Using the GNU make Utility
436
437 * Using gnatmake in a Makefile::
438 * Automatically Creating a List of Directories::
439 * Generating the Command Line Switches::
440 * Overcoming Command Line Length Limits::
441 @end ifclear
442
443 Memory Management Issues
444
445 * Some Useful Memory Pools::
446 * The GNAT Debug Pool Facility::
447 @ifclear vms
448 * The gnatmem Tool::
449 @end ifclear
450
451 Stack Related Facilities
452
453 * Stack Overflow Checking::
454 * Static Stack Usage Analysis::
455 * Dynamic Stack Usage Analysis::
456
457 Verifying Properties Using gnatcheck
458
459 Sample Bodies Using gnatstub
460
461 * Running gnatstub::
462 * Switches for gnatstub::
463
464 Creating Unit Tests Using gnattest
465
466 * Running gnattest::
467 * Switches for gnattest::
468 * Project Attributes for gnattest::
469 * Simple Example::
470 * Setting Up and Tearing Down the Testing Environment::
471 * Regenerating Tests::
472 * Default Test Behavior::
473 * Testing Primitive Operations of Tagged Types::
474 * Testing Inheritance::
475 * Tagged Types Substitutability Testing::
476 * Testing with Contracts::
477 * Additional Tests::
478 @ifclear vms
479 * Support for other platforms/run-times::
480 @end ifclear
481 * Current Limitations::
482
483 Other Utility Programs
484
485 * Using Other Utility Programs with GNAT::
486 * The External Symbol Naming Scheme of GNAT::
487 * Converting Ada Files to html with gnathtml::
488
489 @ifclear vms
490 Code Coverage and Profiling
491
492 * Code Coverage of Ada Programs using gcov::
493 * Profiling an Ada Program using gprof::
494 @end ifclear
495
496 Running and Debugging Ada Programs
497
498 * The GNAT Debugger GDB::
499 * Running GDB::
500 * Introduction to GDB Commands::
501 * Using Ada Expressions::
502 * Calling User-Defined Subprograms::
503 * Using the Next Command in a Function::
504 * Ada Exceptions::
505 * Ada Tasks::
506 * Debugging Generic Units::
507 * Remote Debugging using gdbserver::
508 * GNAT Abnormal Termination or Failure to Terminate::
509 * Naming Conventions for GNAT Source Files::
510 * Getting Internal Debugging Information::
511 * Stack Traceback::
512
513 @ifset vms
514 * LSE::
515 @end ifset
516
517 @ifset vms
518 Compatibility with HP Ada
519
520 * Ada Language Compatibility::
521 * Differences in the Definition of Package System::
522 * Language-Related Features::
523 * The Package STANDARD::
524 * The Package SYSTEM::
525 * Tasking and Task-Related Features::
526 * Pragmas and Pragma-Related Features::
527 * Library of Predefined Units::
528 * Bindings::
529 * Main Program Definition::
530 * Implementation-Defined Attributes::
531 * Compiler and Run-Time Interfacing::
532 * Program Compilation and Library Management::
533 * Input-Output::
534 * Implementation Limits::
535 * Tools and Utilities::
536
537 Language-Related Features
538
539 * Integer Types and Representations::
540 * Floating-Point Types and Representations::
541 * Pragmas Float_Representation and Long_Float::
542 * Fixed-Point Types and Representations::
543 * Record and Array Component Alignment::
544 * Address Clauses::
545 * Other Representation Clauses::
546
547 Tasking and Task-Related Features
548
549 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
550 * Assigning Task IDs::
551 * Task IDs and Delays::
552 * Task-Related Pragmas::
553 * Scheduling and Task Priority::
554 * The Task Stack::
555 * External Interrupts::
556
557 Pragmas and Pragma-Related Features
558
559 * Restrictions on the Pragma INLINE::
560 * Restrictions on the Pragma INTERFACE::
561 * Restrictions on the Pragma SYSTEM_NAME::
562
563 Library of Predefined Units
564
565 * Changes to DECLIB::
566
567 Bindings
568
569 * Shared Libraries and Options Files::
570 * Interfaces to C::
571 @end ifset
572
573 Platform-Specific Information for the Run-Time Libraries
574
575 * Summary of Run-Time Configurations::
576 * Specifying a Run-Time Library::
577 * Choosing the Scheduling Policy::
578 * Solaris-Specific Considerations::
579 * Linux-Specific Considerations::
580 * AIX-Specific Considerations::
581 * RTX-Specific Considerations::
582 * HP-UX-Specific Considerations::
583
584 Example of Binder Output File
585
586 Elaboration Order Handling in GNAT
587
588 * Elaboration Code::
589 * Checking the Elaboration Order::
590 * Controlling the Elaboration Order::
591 * Controlling Elaboration in GNAT - Internal Calls::
592 * Controlling Elaboration in GNAT - External Calls::
593 * Default Behavior in GNAT - Ensuring Safety::
594 * Treatment of Pragma Elaborate::
595 * Elaboration Issues for Library Tasks::
596 * Mixing Elaboration Models::
597 * What to Do If the Default Elaboration Behavior Fails::
598 * Elaboration for Dispatching Calls::
599 * Summary of Procedures for Elaboration Control::
600 * Other Elaboration Order Considerations::
601
602 Overflow Check Handling in GNAT
603 * Background::
604 * Overflow Checking Modes in GNAT::
605 * Specifying the Desired Mode::
606 * Default Settings::
607 * Implementation Notes::
608
609 Conditional Compilation
610 * Use of Boolean Constants::
611 * Debugging - A Special Case::
612 * Conditionalizing Declarations::
613 * Use of Alternative Implementations::
614 * Preprocessing::
615
616 Inline Assembler
617
618 * Basic Assembler Syntax::
619 * A Simple Example of Inline Assembler::
620 * Output Variables in Inline Assembler::
621 * Input Variables in Inline Assembler::
622 * Inlining Inline Assembler Code::
623 * Other Asm Functionality::
624
625 Compatibility and Porting Guide
626
627 * Compatibility with Ada 83::
628 * Compatibility between Ada 95 and Ada 2005::
629 * Implementation-dependent characteristics::
630 @ifclear vms
631 @c This brief section is only in the non-VMS version
632 @c The complete chapter on HP Ada issues is in the VMS version
633 * Compatibility with HP Ada 83::
634 @end ifclear
635 * Compatibility with Other Ada Systems::
636 * Representation Clauses::
637 @ifset vms
638 * Transitioning to 64-Bit GNAT for OpenVMS::
639 @end ifset
640
641 Microsoft Windows Topics
642
643 @ifclear FSFEDITION
644 * Installing from the Command Line::
645 @end ifclear
646 * Using GNAT on Windows::
647 * Using a network installation of GNAT::
648 * CONSOLE and WINDOWS subsystems::
649 * Temporary Files::
650 * Mixed-Language Programming on Windows::
651 * Windows Calling Conventions::
652 * Introduction to Dynamic Link Libraries (DLLs)::
653 * Using DLLs with GNAT::
654 * Building DLLs with GNAT::
655 * GNAT and Windows Resources::
656 * Debugging a DLL::
657 * Setting Stack Size from gnatlink::
658 * Setting Heap Size from gnatlink::
659
660 Mac OS Topics
661
662 * Codesigning the Debugger::
663
664 * Index::
665 @end menu
666 @end ifnottex
667
668 @node About This Guide
669 @unnumbered About This Guide
670
671 @noindent
672 @ifset vms
673 This guide describes the use of @value{EDITION},
674 a compiler and software development toolset for the full Ada
675 programming language, implemented on OpenVMS for HP's Alpha and
676 Integrity server (I64) platforms.
677 @end ifset
678 @ifclear vms
679 This guide describes the use of @value{EDITION},
680 a compiler and software development
681 toolset for the full Ada programming language.
682 @end ifclear
683 It documents the features of the compiler and tools, and explains
684 how to use them to build Ada applications.
685
686 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
687 Ada 83 compatibility mode.
688 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
689 but you can override with a compiler switch
690 (@pxref{Compiling Different Versions of Ada})
691 to explicitly specify the language version.
692 Throughout this manual, references to ``Ada'' without a year suffix
693 apply to both the Ada 95 and Ada 2005 versions of the language.
694
695
696 @ifclear FSFEDITION
697 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
698 ``GNAT'' in the remainder of this document.
699 @end ifclear
700
701
702
703
704 @menu
705 * What This Guide Contains::
706 * What You Should Know before Reading This Guide::
707 * Related Information::
708 * Conventions::
709 @end menu
710
711 @node What This Guide Contains
712 @unnumberedsec What This Guide Contains
713
714 @noindent
715 This guide contains the following chapters:
716 @itemize @bullet
717
718 @item
719 @ref{Getting Started with GNAT}, describes how to get started compiling
720 and running Ada programs with the GNAT Ada programming environment.
721 @item
722 @ref{The GNAT Compilation Model}, describes the compilation model used
723 by GNAT.
724
725 @item
726 @ref{Compiling Using gcc}, describes how to compile
727 Ada programs with @command{gcc}, the Ada compiler.
728
729 @item
730 @ref{Binding Using gnatbind}, describes how to
731 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
732 utility.
733
734 @item
735 @ref{Linking Using gnatlink},
736 describes @command{gnatlink}, a
737 program that provides for linking using the GNAT run-time library to
738 construct a program. @command{gnatlink} can also incorporate foreign language
739 object units into the executable.
740
741 @item
742 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
743 utility that automatically determines the set of sources
744 needed by an Ada compilation unit, and executes the necessary compilations
745 binding and link.
746
747 @item
748 @ref{Improving Performance}, shows various techniques for making your
749 Ada program run faster or take less space.
750 It discusses the effect of the compiler's optimization switch and
751 also describes the @command{gnatelim} tool and unused subprogram/data
752 elimination.
753
754 @item
755 @ref{Renaming Files Using gnatchop}, describes
756 @code{gnatchop}, a utility that allows you to preprocess a file that
757 contains Ada source code, and split it into one or more new files, one
758 for each compilation unit.
759
760 @item
761 @ref{Configuration Pragmas}, describes the configuration pragmas
762 handled by GNAT.
763
764 @item
765 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
766 shows how to override the default GNAT file naming conventions,
767 either for an individual unit or globally.
768
769 @item
770 @ref{GNAT Project Manager}, describes how to use project files
771 to organize large projects.
772
773 @item
774 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
775 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
776 way to navigate through sources.
777
778 @item
779 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
780 version of an Ada source file with control over casing, indentation,
781 comment placement, and other elements of program presentation style.
782
783 @item
784 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
785 metrics for an Ada source file, such as the number of types and subprograms,
786 and assorted complexity measures.
787
788 @item
789 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
790 file name krunching utility, used to handle shortened
791 file names on operating systems with a limit on the length of names.
792
793 @item
794 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
795 preprocessor utility that allows a single source file to be used to
796 generate multiple or parameterized source files by means of macro
797 substitution.
798
799 @item
800 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
801 utility that displays information about compiled units, including dependences
802 on the corresponding sources files, and consistency of compilations.
803
804 @item
805 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
806 to delete files that are produced by the compiler, binder and linker.
807
808 @ifclear vms
809 @item
810 @ref{GNAT and Libraries}, describes the process of creating and using
811 Libraries with GNAT. It also describes how to recompile the GNAT run-time
812 library.
813
814 @item
815 @ref{Using the GNU make Utility}, describes some techniques for using
816 the GNAT toolset in Makefiles.
817 @end ifclear
818
819 @item
820 @ref{Memory Management Issues}, describes some useful predefined storage pools
821 and in particular the GNAT Debug Pool facility, which helps detect incorrect
822 memory references.
823 @ifclear vms
824 It also describes @command{gnatmem}, a utility that monitors dynamic
825 allocation and deallocation and helps detect ``memory leaks''.
826 @end ifclear
827
828 @item
829 @ref{Stack Related Facilities}, describes some useful tools associated with
830 stack checking and analysis.
831
832 @item
833 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
834 a utility that checks Ada code against a set of rules.
835
836 @item
837 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
838 a utility that generates empty but compilable bodies for library units.
839
840 @item
841 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
842 a utility that generates unit testing templates for library units.
843
844 @item
845 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
846 facilities used in GNAT to declare dimensioned objects, and to verify that
847 uses of these objects are consistent with their given physical dimensions
848 (so that meters cannot be assigned to kilograms, and so on).
849
850 @item
851 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
852 generate automatically Ada bindings from C and C++ headers.
853
854 @item
855 @ref{Other Utility Programs}, discusses several other GNAT utilities,
856 including @code{gnathtml}.
857
858 @ifclear vms
859 @item
860 @ref{Code Coverage and Profiling}, describes how to perform a structural
861 coverage and profile the execution of Ada programs.
862 @end ifclear
863
864 @item
865 @ref{Running and Debugging Ada Programs}, describes how to run and debug
866 Ada programs.
867
868 @ifset vms
869 @item
870 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
871 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
872 developed by Digital Equipment Corporation and currently supported by HP.}
873 for OpenVMS Alpha. This product was formerly known as DEC Ada,
874 @cindex DEC Ada
875 and for
876 historical compatibility reasons, the relevant libraries still use the
877 DEC prefix.
878 @end ifset
879
880 @item
881 @ref{Platform-Specific Information for the Run-Time Libraries},
882 describes the various run-time
883 libraries supported by GNAT on various platforms and explains how to
884 choose a particular library.
885
886 @item
887 @ref{Example of Binder Output File}, shows the source code for the binder
888 output file for a sample program.
889
890 @item
891 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
892 you deal with elaboration order issues.
893
894 @item
895 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
896 you deal with arithmetic overflow issues.
897
898 @item
899 @ref{Conditional Compilation}, describes how to model conditional compilation,
900 both with Ada in general and with GNAT facilities in particular.
901
902 @item
903 @ref{Inline Assembler}, shows how to use the inline assembly facility
904 in an Ada program.
905
906 @item
907 @ref{Compatibility and Porting Guide}, contains sections on compatibility
908 of GNAT with other Ada development environments (including Ada 83 systems),
909 to assist in porting code from those environments.
910
911 @ifset unw
912 @item
913 @ref{Microsoft Windows Topics}, presents information relevant to the
914 Microsoft Windows platform.
915
916 @item
917 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
918 platform.
919 @end ifset
920 @end itemize
921
922 @c *************************************************
923 @node What You Should Know before Reading This Guide
924 @c *************************************************
925 @unnumberedsec What You Should Know before Reading This Guide
926
927 @cindex Ada 95 Language Reference Manual
928 @cindex Ada 2005 Language Reference Manual
929 @noindent
930 This guide assumes a basic familiarity with the Ada 95 language, as
931 described in the International Standard ANSI/ISO/IEC-8652:1995, January
932 1995.
933 It does not require knowledge of the new features introduced by Ada 2005,
934 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
935 and Amendment 1).
936 Both reference manuals are included in the GNAT documentation
937 package.
938
939 @node Related Information
940 @unnumberedsec Related Information
941
942 @noindent
943 For further information about related tools, refer to the following
944 documents:
945
946 @itemize @bullet
947 @item
948 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
949 Reference Manual}, which contains all reference material for the GNAT
950 implementation of Ada.
951
952 @ifset unw
953 @item
954 @cite{Using the GNAT Programming Studio}, which describes the GPS
955 Integrated Development Environment.
956
957 @item
958 @cite{GNAT Programming Studio Tutorial}, which introduces the
959 main GPS features through examples.
960 @end ifset
961
962 @item
963 @cite{Ada 95 Reference Manual}, which contains reference
964 material for the Ada 95 programming language.
965
966 @item
967 @cite{Ada 2005 Reference Manual}, which contains reference
968 material for the Ada 2005 programming language.
969
970 @item
971 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
972 @ifset vms
973 in the GNU:[DOCS] directory,
974 @end ifset
975 for all details on the use of the GNU source-level debugger.
976
977 @item
978 @xref{Top,, The extensible self-documenting text editor, emacs,
979 GNU Emacs Manual},
980 @ifset vms
981 located in the GNU:[DOCS] directory if the EMACS kit is installed,
982 @end ifset
983 for full information on the extensible editor and programming
984 environment Emacs.
985
986 @end itemize
987
988 @c **************
989 @node Conventions
990 @unnumberedsec Conventions
991 @cindex Conventions
992 @cindex Typographical conventions
993
994 @noindent
995 Following are examples of the typographical and graphic conventions used
996 in this guide:
997
998 @itemize @bullet
999 @item
1000 @code{Functions}, @command{utility program names}, @code{standard names},
1001 and @code{classes}.
1002
1003 @item
1004 @option{Option flags}
1005
1006 @item
1007 @file{File names}, @samp{button names}, and @samp{field names}.
1008
1009 @item
1010 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1011 variables}.
1012
1013 @item
1014 @emph{Emphasis}.
1015
1016 @item
1017 @r{[}optional information or parameters@r{]}
1018
1019 @item
1020 Examples are described by text
1021 @smallexample
1022 and then shown this way.
1023 @end smallexample
1024 @end itemize
1025
1026 @noindent
1027 Commands that are entered by the user are preceded in this manual by the
1028 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1029 uses this sequence as a prompt, then the commands will appear exactly as
1030 you see them in the manual. If your system uses some other prompt, then
1031 the command will appear with the @code{$} replaced by whatever prompt
1032 character you are using.
1033
1034 @ifset unw
1035 Full file names are shown with the ``@code{/}'' character
1036 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1037 If you are using GNAT on a Windows platform, please note that
1038 the ``@code{\}'' character should be used instead.
1039 @end ifset
1040
1041 @c ****************************
1042 @node Getting Started with GNAT
1043 @chapter Getting Started with GNAT
1044
1045 @noindent
1046 This chapter describes some simple ways of using GNAT to build
1047 executable Ada programs.
1048 @ifset unw
1049 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1050 show how to use the command line environment.
1051 @ref{Introduction to GPS}, provides a brief
1052 introduction to the GNAT Programming Studio, a visually-oriented
1053 Integrated Development Environment for GNAT.
1054 GPS offers a graphical ``look and feel'', support for development in
1055 other programming languages, comprehensive browsing features, and
1056 many other capabilities.
1057 For information on GPS please refer to
1058 @cite{Using the GNAT Programming Studio}.
1059 @end ifset
1060
1061 @menu
1062 * Running GNAT::
1063 * Running a Simple Ada Program::
1064 * Running a Program with Multiple Units::
1065 * Using the gnatmake Utility::
1066 @ifset vms
1067 * Editing with Emacs::
1068 @end ifset
1069 @ifclear vms
1070 * Introduction to GPS::
1071 @end ifclear
1072 @end menu
1073
1074 @node Running GNAT
1075 @section Running GNAT
1076
1077 @noindent
1078 Three steps are needed to create an executable file from an Ada source
1079 file:
1080
1081 @enumerate
1082 @item
1083 The source file(s) must be compiled.
1084 @item
1085 The file(s) must be bound using the GNAT binder.
1086 @item
1087 All appropriate object files must be linked to produce an executable.
1088 @end enumerate
1089
1090 @noindent
1091 All three steps are most commonly handled by using the @command{gnatmake}
1092 utility program that, given the name of the main program, automatically
1093 performs the necessary compilation, binding and linking steps.
1094
1095 @node Running a Simple Ada Program
1096 @section Running a Simple Ada Program
1097
1098 @noindent
1099 Any text editor may be used to prepare an Ada program.
1100 (If @code{Emacs} is
1101 used, the optional Ada mode may be helpful in laying out the program.)
1102 The
1103 program text is a normal text file. We will assume in our initial
1104 example that you have used your editor to prepare the following
1105 standard format text file:
1106
1107 @smallexample @c ada
1108 @cartouche
1109 with Ada.Text_IO; use Ada.Text_IO;
1110 procedure Hello is
1111 begin
1112 Put_Line ("Hello WORLD!");
1113 end Hello;
1114 @end cartouche
1115 @end smallexample
1116
1117 @noindent
1118 This file should be named @file{hello.adb}.
1119 With the normal default file naming conventions, GNAT requires
1120 that each file
1121 contain a single compilation unit whose file name is the
1122 unit name,
1123 with periods replaced by hyphens; the
1124 extension is @file{ads} for a
1125 spec and @file{adb} for a body.
1126 You can override this default file naming convention by use of the
1127 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1128 Alternatively, if you want to rename your files according to this default
1129 convention, which is probably more convenient if you will be using GNAT
1130 for all your compilations, then the @code{gnatchop} utility
1131 can be used to generate correctly-named source files
1132 (@pxref{Renaming Files Using gnatchop}).
1133
1134 You can compile the program using the following command (@code{$} is used
1135 as the command prompt in the examples in this document):
1136
1137 @smallexample
1138 $ gcc -c hello.adb
1139 @end smallexample
1140
1141 @noindent
1142 @command{gcc} is the command used to run the compiler. This compiler is
1143 capable of compiling programs in several languages, including Ada and
1144 C. It assumes that you have given it an Ada program if the file extension is
1145 either @file{.ads} or @file{.adb}, and it will then call
1146 the GNAT compiler to compile the specified file.
1147
1148 @ifclear vms
1149 The @option{-c} switch is required. It tells @command{gcc} to only do a
1150 compilation. (For C programs, @command{gcc} can also do linking, but this
1151 capability is not used directly for Ada programs, so the @option{-c}
1152 switch must always be present.)
1153 @end ifclear
1154
1155 This compile command generates a file
1156 @file{hello.o}, which is the object
1157 file corresponding to your Ada program. It also generates
1158 an ``Ada Library Information'' file @file{hello.ali},
1159 which contains additional information used to check
1160 that an Ada program is consistent.
1161 To build an executable file,
1162 use @code{gnatbind} to bind the program
1163 and @command{gnatlink} to link it. The
1164 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1165 @file{ALI} file, but the default extension of @file{.ali} can
1166 be omitted. This means that in the most common case, the argument
1167 is simply the name of the main program:
1168
1169 @smallexample
1170 $ gnatbind hello
1171 $ gnatlink hello
1172 @end smallexample
1173
1174 @noindent
1175 A simpler method of carrying out these steps is to use
1176 @command{gnatmake},
1177 a master program that invokes all the required
1178 compilation, binding and linking tools in the correct order. In particular,
1179 @command{gnatmake} automatically recompiles any sources that have been
1180 modified since they were last compiled, or sources that depend
1181 on such modified sources, so that ``version skew'' is avoided.
1182 @cindex Version skew (avoided by @command{gnatmake})
1183
1184 @smallexample
1185 $ gnatmake hello.adb
1186 @end smallexample
1187
1188 @noindent
1189 The result is an executable program called @file{hello}, which can be
1190 run by entering:
1191
1192 @smallexample
1193 $ ^hello^RUN HELLO^
1194 @end smallexample
1195
1196 @noindent
1197 assuming that the current directory is on the search path
1198 for executable programs.
1199
1200 @noindent
1201 and, if all has gone well, you will see
1202
1203 @smallexample
1204 Hello WORLD!
1205 @end smallexample
1206
1207 @noindent
1208 appear in response to this command.
1209
1210 @c ****************************************
1211 @node Running a Program with Multiple Units
1212 @section Running a Program with Multiple Units
1213
1214 @noindent
1215 Consider a slightly more complicated example that has three files: a
1216 main program, and the spec and body of a package:
1217
1218 @smallexample @c ada
1219 @cartouche
1220 @group
1221 package Greetings is
1222 procedure Hello;
1223 procedure Goodbye;
1224 end Greetings;
1225
1226 with Ada.Text_IO; use Ada.Text_IO;
1227 package body Greetings is
1228 procedure Hello is
1229 begin
1230 Put_Line ("Hello WORLD!");
1231 end Hello;
1232
1233 procedure Goodbye is
1234 begin
1235 Put_Line ("Goodbye WORLD!");
1236 end Goodbye;
1237 end Greetings;
1238 @end group
1239
1240 @group
1241 with Greetings;
1242 procedure Gmain is
1243 begin
1244 Greetings.Hello;
1245 Greetings.Goodbye;
1246 end Gmain;
1247 @end group
1248 @end cartouche
1249 @end smallexample
1250
1251 @noindent
1252 Following the one-unit-per-file rule, place this program in the
1253 following three separate files:
1254
1255 @table @file
1256 @item greetings.ads
1257 spec of package @code{Greetings}
1258
1259 @item greetings.adb
1260 body of package @code{Greetings}
1261
1262 @item gmain.adb
1263 body of main program
1264 @end table
1265
1266 @noindent
1267 To build an executable version of
1268 this program, we could use four separate steps to compile, bind, and link
1269 the program, as follows:
1270
1271 @smallexample
1272 $ gcc -c gmain.adb
1273 $ gcc -c greetings.adb
1274 $ gnatbind gmain
1275 $ gnatlink gmain
1276 @end smallexample
1277
1278 @noindent
1279 Note that there is no required order of compilation when using GNAT.
1280 In particular it is perfectly fine to compile the main program first.
1281 Also, it is not necessary to compile package specs in the case where
1282 there is an accompanying body; you only need to compile the body. If you want
1283 to submit these files to the compiler for semantic checking and not code
1284 generation, then use the
1285 @option{-gnatc} switch:
1286
1287 @smallexample
1288 $ gcc -c greetings.ads -gnatc
1289 @end smallexample
1290
1291 @noindent
1292 Although the compilation can be done in separate steps as in the
1293 above example, in practice it is almost always more convenient
1294 to use the @command{gnatmake} tool. All you need to know in this case
1295 is the name of the main program's source file. The effect of the above four
1296 commands can be achieved with a single one:
1297
1298 @smallexample
1299 $ gnatmake gmain.adb
1300 @end smallexample
1301
1302 @noindent
1303 In the next section we discuss the advantages of using @command{gnatmake} in
1304 more detail.
1305
1306 @c *****************************
1307 @node Using the gnatmake Utility
1308 @section Using the @command{gnatmake} Utility
1309
1310 @noindent
1311 If you work on a program by compiling single components at a time using
1312 @command{gcc}, you typically keep track of the units you modify. In order to
1313 build a consistent system, you compile not only these units, but also any
1314 units that depend on the units you have modified.
1315 For example, in the preceding case,
1316 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1317 you edit @file{greetings.ads}, you must recompile both
1318 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1319 units that depend on @file{greetings.ads}.
1320
1321 @code{gnatbind} will warn you if you forget one of these compilation
1322 steps, so that it is impossible to generate an inconsistent program as a
1323 result of forgetting to do a compilation. Nevertheless it is tedious and
1324 error-prone to keep track of dependencies among units.
1325 One approach to handle the dependency-bookkeeping is to use a
1326 makefile. However, makefiles present maintenance problems of their own:
1327 if the dependencies change as you change the program, you must make
1328 sure that the makefile is kept up-to-date manually, which is also an
1329 error-prone process.
1330
1331 The @command{gnatmake} utility takes care of these details automatically.
1332 Invoke it using either one of the following forms:
1333
1334 @smallexample
1335 $ gnatmake gmain.adb
1336 $ gnatmake ^gmain^GMAIN^
1337 @end smallexample
1338
1339 @noindent
1340 The argument is the name of the file containing the main program;
1341 you may omit the extension. @command{gnatmake}
1342 examines the environment, automatically recompiles any files that need
1343 recompiling, and binds and links the resulting set of object files,
1344 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1345 In a large program, it
1346 can be extremely helpful to use @command{gnatmake}, because working out by hand
1347 what needs to be recompiled can be difficult.
1348
1349 Note that @command{gnatmake}
1350 takes into account all the Ada rules that
1351 establish dependencies among units. These include dependencies that result
1352 from inlining subprogram bodies, and from
1353 generic instantiation. Unlike some other
1354 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1355 found by the compiler on a previous compilation, which may possibly
1356 be wrong when sources change. @command{gnatmake} determines the exact set of
1357 dependencies from scratch each time it is run.
1358
1359 @ifset vms
1360 @node Editing with Emacs
1361 @section Editing with Emacs
1362 @cindex Emacs
1363
1364 @noindent
1365 Emacs is an extensible self-documenting text editor that is available in a
1366 separate VMSINSTAL kit.
1367
1368 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1369 click on the Emacs Help menu and run the Emacs Tutorial.
1370 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1371 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1372
1373 Documentation on Emacs and other tools is available in Emacs under the
1374 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1375 use the middle mouse button to select a topic (e.g.@: Emacs).
1376
1377 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1378 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1379 get to the Emacs manual.
1380 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1381 prompt.
1382
1383 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1384 which is sufficiently extensible to provide for a complete programming
1385 environment and shell for the sophisticated user.
1386 @end ifset
1387
1388 @ifclear vms
1389 @node Introduction to GPS
1390 @section Introduction to GPS
1391 @cindex GPS (GNAT Programming Studio)
1392 @cindex GNAT Programming Studio (GPS)
1393 @noindent
1394 Although the command line interface (@command{gnatmake}, etc.) alone
1395 is sufficient, a graphical Interactive Development
1396 Environment can make it easier for you to compose, navigate, and debug
1397 programs. This section describes the main features of GPS
1398 (``GNAT Programming Studio''), the GNAT graphical IDE.
1399 You will see how to use GPS to build and debug an executable, and
1400 you will also learn some of the basics of the GNAT ``project'' facility.
1401
1402 GPS enables you to do much more than is presented here;
1403 e.g., you can produce a call graph, interface to a third-party
1404 Version Control System, and inspect the generated assembly language
1405 for a program.
1406 Indeed, GPS also supports languages other than Ada.
1407 Such additional information, and an explanation of all of the GPS menu
1408 items. may be found in the on-line help, which includes
1409 a user's guide and a tutorial (these are also accessible from the GNAT
1410 startup menu).
1411
1412 @menu
1413 * Building a New Program with GPS::
1414 * Simple Debugging with GPS::
1415 @end menu
1416
1417 @node Building a New Program with GPS
1418 @subsection Building a New Program with GPS
1419 @noindent
1420 GPS invokes the GNAT compilation tools using information
1421 contained in a @emph{project} (also known as a @emph{project file}):
1422 a collection of properties such
1423 as source directories, identities of main subprograms, tool switches, etc.,
1424 and their associated values.
1425 See @ref{GNAT Project Manager} for details.
1426 In order to run GPS, you will need to either create a new project
1427 or else open an existing one.
1428
1429 This section will explain how you can use GPS to create a project,
1430 to associate Ada source files with a project, and to build and run
1431 programs.
1432
1433 @enumerate
1434 @item @emph{Creating a project}
1435
1436 Invoke GPS, either from the command line or the platform's IDE.
1437 After it starts, GPS will display a ``Welcome'' screen with three
1438 radio buttons:
1439
1440 @itemize @bullet
1441 @item
1442 @code{Start with default project in directory}
1443
1444 @item
1445 @code{Create new project with wizard}
1446
1447 @item
1448 @code{Open existing project}
1449 @end itemize
1450
1451 @noindent
1452 Select @code{Create new project with wizard} and press @code{OK}.
1453 A new window will appear. In the text box labeled with
1454 @code{Enter the name of the project to create}, type @file{sample}
1455 as the project name.
1456 In the next box, browse to choose the directory in which you
1457 would like to create the project file.
1458 After selecting an appropriate directory, press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Version Control System Configuration}.
1462 Simply press @code{Forward}.
1463
1464 A window will appear with the title
1465 @code{Please select the source directories for this project}.
1466 The directory that you specified for the project file will be selected
1467 by default as the one to use for sources; simply press @code{Forward}.
1468
1469 A window will appear with the title
1470 @code{Please select the build directory for this project}.
1471 The directory that you specified for the project file will be selected
1472 by default for object files and executables;
1473 simply press @code{Forward}.
1474
1475 A window will appear with the title
1476 @code{Please select the main units for this project}.
1477 You will supply this information later, after creating the source file.
1478 Simply press @code{Forward} for now.
1479
1480 A window will appear with the title
1481 @code{Please select the switches to build the project}.
1482 Press @code{Apply}. This will create a project file named
1483 @file{sample.prj} in the directory that you had specified.
1484
1485 @item @emph{Creating and saving the source file}
1486
1487 After you create the new project, a GPS window will appear, which is
1488 partitioned into two main sections:
1489
1490 @itemize @bullet
1491 @item
1492 A @emph{Workspace area}, initially greyed out, which you will use for
1493 creating and editing source files
1494
1495 @item
1496 Directly below, a @emph{Messages area}, which initially displays a
1497 ``Welcome'' message.
1498 (If the Messages area is not visible, drag its border upward to expand it.)
1499 @end itemize
1500
1501 @noindent
1502 Select @code{File} on the menu bar, and then the @code{New} command.
1503 The Workspace area will become white, and you can now
1504 enter the source program explicitly.
1505 Type the following text
1506
1507 @smallexample @c ada
1508 @group
1509 with Ada.Text_IO; use Ada.Text_IO;
1510 procedure Hello is
1511 begin
1512 Put_Line("Hello from GPS!");
1513 end Hello;
1514 @end group
1515 @end smallexample
1516
1517 @noindent
1518 Select @code{File}, then @code{Save As}, and enter the source file name
1519 @file{hello.adb}.
1520 The file will be saved in the same directory you specified as the
1521 location of the default project file.
1522
1523 @item @emph{Updating the project file}
1524
1525 You need to add the new source file to the project.
1526 To do this, select
1527 the @code{Project} menu and then @code{Edit project properties}.
1528 Click the @code{Main files} tab on the left, and then the
1529 @code{Add} button.
1530 Choose @file{hello.adb} from the list, and press @code{Open}.
1531 The project settings window will reflect this action.
1532 Click @code{OK}.
1533
1534 @item @emph{Building and running the program}
1535
1536 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1537 and select @file{hello.adb}.
1538 The Messages window will display the resulting invocations of @command{gcc},
1539 @command{gnatbind}, and @command{gnatlink}
1540 (reflecting the default switch settings from the
1541 project file that you created) and then a ``successful compilation/build''
1542 message.
1543
1544 To run the program, choose the @code{Build} menu, then @code{Run}, and
1545 select @command{hello}.
1546 An @emph{Arguments Selection} window will appear.
1547 There are no command line arguments, so just click @code{OK}.
1548
1549 The Messages window will now display the program's output (the string
1550 @code{Hello from GPS}), and at the bottom of the GPS window a status
1551 update is displayed (@code{Run: hello}).
1552 Close the GPS window (or select @code{File}, then @code{Exit}) to
1553 terminate this GPS session.
1554 @end enumerate
1555
1556 @node Simple Debugging with GPS
1557 @subsection Simple Debugging with GPS
1558 @noindent
1559 This section illustrates basic debugging techniques (setting breakpoints,
1560 examining/modifying variables, single stepping).
1561
1562 @enumerate
1563 @item @emph{Opening a project}
1564
1565 Start GPS and select @code{Open existing project}; browse to
1566 specify the project file @file{sample.prj} that you had created in the
1567 earlier example.
1568
1569 @item @emph{Creating a source file}
1570
1571 Select @code{File}, then @code{New}, and type in the following program:
1572
1573 @smallexample @c ada
1574 @group
1575 with Ada.Text_IO; use Ada.Text_IO;
1576 procedure Example is
1577 Line : String (1..80);
1578 N : Natural;
1579 begin
1580 Put_Line("Type a line of text at each prompt; an empty line to exit");
1581 loop
1582 Put(": ");
1583 Get_Line (Line, N);
1584 Put_Line (Line (1..N) );
1585 exit when N=0;
1586 end loop;
1587 end Example;
1588 @end group
1589 @end smallexample
1590
1591 @noindent
1592 Select @code{File}, then @code{Save as}, and enter the file name
1593 @file{example.adb}.
1594
1595 @item @emph{Updating the project file}
1596
1597 Add @code{Example} as a new main unit for the project:
1598 @enumerate a
1599 @item
1600 Select @code{Project}, then @code{Edit Project Properties}.
1601
1602 @item
1603 Select the @code{Main files} tab, click @code{Add}, then
1604 select the file @file{example.adb} from the list, and
1605 click @code{Open}.
1606 You will see the file name appear in the list of main units
1607
1608 @item
1609 Click @code{OK}
1610 @end enumerate
1611
1612 @item @emph{Building/running the executable}
1613
1614 To build the executable
1615 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1616
1617 Run the program to see its effect (in the Messages area).
1618 Each line that you enter is displayed; an empty line will
1619 cause the loop to exit and the program to terminate.
1620
1621 @item @emph{Debugging the program}
1622
1623 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1624 which are required for debugging, are on by default when you create
1625 a new project.
1626 Thus unless you intentionally remove these settings, you will be able
1627 to debug any program that you develop using GPS.
1628
1629 @enumerate a
1630 @item @emph{Initializing}
1631
1632 Select @code{Debug}, then @code{Initialize}, then @file{example}
1633
1634 @item @emph{Setting a breakpoint}
1635
1636 After performing the initialization step, you will observe a small
1637 icon to the right of each line number.
1638 This serves as a toggle for breakpoints; clicking the icon will
1639 set a breakpoint at the corresponding line (the icon will change to
1640 a red circle with an ``x''), and clicking it again
1641 will remove the breakpoint / reset the icon.
1642
1643 For purposes of this example, set a breakpoint at line 10 (the
1644 statement @code{Put_Line@ (Line@ (1..N));}
1645
1646 @item @emph{Starting program execution}
1647
1648 Select @code{Debug}, then @code{Run}. When the
1649 @code{Program Arguments} window appears, click @code{OK}.
1650 A console window will appear; enter some line of text,
1651 e.g.@: @code{abcde}, at the prompt.
1652 The program will pause execution when it gets to the
1653 breakpoint, and the corresponding line is highlighted.
1654
1655 @item @emph{Examining a variable}
1656
1657 Move the mouse over one of the occurrences of the variable @code{N}.
1658 You will see the value (5) displayed, in ``tool tip'' fashion.
1659 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1660 You will see information about @code{N} appear in the @code{Debugger Data}
1661 pane, showing the value as 5.
1662
1663 @item @emph{Assigning a new value to a variable}
1664
1665 Right click on the @code{N} in the @code{Debugger Data} pane, and
1666 select @code{Set value of N}.
1667 When the input window appears, enter the value @code{4} and click
1668 @code{OK}.
1669 This value does not automatically appear in the @code{Debugger Data}
1670 pane; to see it, right click again on the @code{N} in the
1671 @code{Debugger Data} pane and select @code{Update value}.
1672 The new value, 4, will appear in red.
1673
1674 @item @emph{Single stepping}
1675
1676 Select @code{Debug}, then @code{Next}.
1677 This will cause the next statement to be executed, in this case the
1678 call of @code{Put_Line} with the string slice.
1679 Notice in the console window that the displayed string is simply
1680 @code{abcd} and not @code{abcde} which you had entered.
1681 This is because the upper bound of the slice is now 4 rather than 5.
1682
1683 @item @emph{Removing a breakpoint}
1684
1685 Toggle the breakpoint icon at line 10.
1686
1687 @item @emph{Resuming execution from a breakpoint}
1688
1689 Select @code{Debug}, then @code{Continue}.
1690 The program will reach the next iteration of the loop, and
1691 wait for input after displaying the prompt.
1692 This time, just hit the @kbd{Enter} key.
1693 The value of @code{N} will be 0, and the program will terminate.
1694 The console window will disappear.
1695 @end enumerate
1696 @end enumerate
1697 @end ifclear
1698
1699 @node The GNAT Compilation Model
1700 @chapter The GNAT Compilation Model
1701 @cindex GNAT compilation model
1702 @cindex Compilation model
1703
1704 @menu
1705 * Source Representation::
1706 * Foreign Language Representation::
1707 * File Naming Rules::
1708 * Using Other File Names::
1709 * Alternative File Naming Schemes::
1710 * Generating Object Files::
1711 * Source Dependencies::
1712 * The Ada Library Information Files::
1713 * Binding an Ada Program::
1714 * Mixed Language Programming::
1715 @ifclear vms
1716 * Building Mixed Ada & C++ Programs::
1717 * Comparison between GNAT and C/C++ Compilation Models::
1718 @end ifclear
1719 * Comparison between GNAT and Conventional Ada Library Models::
1720 @ifset vms
1721 * Placement of temporary files::
1722 @end ifset
1723 @end menu
1724
1725 @noindent
1726 This chapter describes the compilation model used by GNAT. Although
1727 similar to that used by other languages, such as C and C++, this model
1728 is substantially different from the traditional Ada compilation models,
1729 which are based on a library. The model is initially described without
1730 reference to the library-based model. If you have not previously used an
1731 Ada compiler, you need only read the first part of this chapter. The
1732 last section describes and discusses the differences between the GNAT
1733 model and the traditional Ada compiler models. If you have used other
1734 Ada compilers, this section will help you to understand those
1735 differences, and the advantages of the GNAT model.
1736
1737 @node Source Representation
1738 @section Source Representation
1739 @cindex Latin-1
1740
1741 @noindent
1742 Ada source programs are represented in standard text files, using
1743 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1744 7-bit ASCII set, plus additional characters used for
1745 representing foreign languages (@pxref{Foreign Language Representation}
1746 for support of non-USA character sets). The format effector characters
1747 are represented using their standard ASCII encodings, as follows:
1748
1749 @table @code
1750 @item VT
1751 @findex VT
1752 Vertical tab, @code{16#0B#}
1753
1754 @item HT
1755 @findex HT
1756 Horizontal tab, @code{16#09#}
1757
1758 @item CR
1759 @findex CR
1760 Carriage return, @code{16#0D#}
1761
1762 @item LF
1763 @findex LF
1764 Line feed, @code{16#0A#}
1765
1766 @item FF
1767 @findex FF
1768 Form feed, @code{16#0C#}
1769 @end table
1770
1771 @noindent
1772 Source files are in standard text file format. In addition, GNAT will
1773 recognize a wide variety of stream formats, in which the end of
1774 physical lines is marked by any of the following sequences:
1775 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1776 in accommodating files that are imported from other operating systems.
1777
1778 @cindex End of source file
1779 @cindex Source file, end
1780 @findex SUB
1781 The end of a source file is normally represented by the physical end of
1782 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1783 recognized as signalling the end of the source file. Again, this is
1784 provided for compatibility with other operating systems where this
1785 code is used to represent the end of file.
1786
1787 Each file contains a single Ada compilation unit, including any pragmas
1788 associated with the unit. For example, this means you must place a
1789 package declaration (a package @dfn{spec}) and the corresponding body in
1790 separate files. An Ada @dfn{compilation} (which is a sequence of
1791 compilation units) is represented using a sequence of files. Similarly,
1792 you will place each subunit or child unit in a separate file.
1793
1794 @node Foreign Language Representation
1795 @section Foreign Language Representation
1796
1797 @noindent
1798 GNAT supports the standard character sets defined in Ada as well as
1799 several other non-standard character sets for use in localized versions
1800 of the compiler (@pxref{Character Set Control}).
1801 @menu
1802 * Latin-1::
1803 * Other 8-Bit Codes::
1804 * Wide Character Encodings::
1805 @end menu
1806
1807 @node Latin-1
1808 @subsection Latin-1
1809 @cindex Latin-1
1810
1811 @noindent
1812 The basic character set is Latin-1. This character set is defined by ISO
1813 standard 8859, part 1. The lower half (character codes @code{16#00#}
1814 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1815 half is used to represent additional characters. These include extended letters
1816 used by European languages, such as French accents, the vowels with umlauts
1817 used in German, and the extra letter A-ring used in Swedish.
1818
1819 @findex Ada.Characters.Latin_1
1820 For a complete list of Latin-1 codes and their encodings, see the source
1821 file of library unit @code{Ada.Characters.Latin_1} in file
1822 @file{a-chlat1.ads}.
1823 You may use any of these extended characters freely in character or
1824 string literals. In addition, the extended characters that represent
1825 letters can be used in identifiers.
1826
1827 @node Other 8-Bit Codes
1828 @subsection Other 8-Bit Codes
1829
1830 @noindent
1831 GNAT also supports several other 8-bit coding schemes:
1832
1833 @table @asis
1834 @item ISO 8859-2 (Latin-2)
1835 @cindex Latin-2
1836 @cindex ISO 8859-2
1837 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1838 equivalence.
1839
1840 @item ISO 8859-3 (Latin-3)
1841 @cindex Latin-3
1842 @cindex ISO 8859-3
1843 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1844 equivalence.
1845
1846 @item ISO 8859-4 (Latin-4)
1847 @cindex Latin-4
1848 @cindex ISO 8859-4
1849 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1850 equivalence.
1851
1852 @item ISO 8859-5 (Cyrillic)
1853 @cindex ISO 8859-5
1854 @cindex Cyrillic
1855 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1856 lowercase equivalence.
1857
1858 @item ISO 8859-15 (Latin-9)
1859 @cindex ISO 8859-15
1860 @cindex Latin-9
1861 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1862 lowercase equivalence
1863
1864 @item IBM PC (code page 437)
1865 @cindex code page 437
1866 This code page is the normal default for PCs in the U.S. It corresponds
1867 to the original IBM PC character set. This set has some, but not all, of
1868 the extended Latin-1 letters, but these letters do not have the same
1869 encoding as Latin-1. In this mode, these letters are allowed in
1870 identifiers with uppercase and lowercase equivalence.
1871
1872 @item IBM PC (code page 850)
1873 @cindex code page 850
1874 This code page is a modification of 437 extended to include all the
1875 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1876 mode, all these letters are allowed in identifiers with uppercase and
1877 lowercase equivalence.
1878
1879 @item Full Upper 8-bit
1880 Any character in the range 80-FF allowed in identifiers, and all are
1881 considered distinct. In other words, there are no uppercase and lowercase
1882 equivalences in this range. This is useful in conjunction with
1883 certain encoding schemes used for some foreign character sets (e.g.,
1884 the typical method of representing Chinese characters on the PC).
1885
1886 @item No Upper-Half
1887 No upper-half characters in the range 80-FF are allowed in identifiers.
1888 This gives Ada 83 compatibility for identifier names.
1889 @end table
1890
1891 @noindent
1892 For precise data on the encodings permitted, and the uppercase and lowercase
1893 equivalences that are recognized, see the file @file{csets.adb} in
1894 the GNAT compiler sources. You will need to obtain a full source release
1895 of GNAT to obtain this file.
1896
1897 @node Wide Character Encodings
1898 @subsection Wide Character Encodings
1899
1900 @noindent
1901 GNAT allows wide character codes to appear in character and string
1902 literals, and also optionally in identifiers, by means of the following
1903 possible encoding schemes:
1904
1905 @table @asis
1906
1907 @item Hex Coding
1908 In this encoding, a wide character is represented by the following five
1909 character sequence:
1910
1911 @smallexample
1912 ESC a b c d
1913 @end smallexample
1914
1915 @noindent
1916 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1917 characters (using uppercase letters) of the wide character code. For
1918 example, ESC A345 is used to represent the wide character with code
1919 @code{16#A345#}.
1920 This scheme is compatible with use of the full Wide_Character set.
1921
1922 @item Upper-Half Coding
1923 @cindex Upper-Half Coding
1924 The wide character with encoding @code{16#abcd#} where the upper bit is on
1925 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1926 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1927 character, but is not required to be in the upper half. This method can
1928 be also used for shift-JIS or EUC, where the internal coding matches the
1929 external coding.
1930
1931 @item Shift JIS Coding
1932 @cindex Shift JIS Coding
1933 A wide character is represented by a two-character sequence,
1934 @code{16#ab#} and
1935 @code{16#cd#}, with the restrictions described for upper-half encoding as
1936 described above. The internal character code is the corresponding JIS
1937 character according to the standard algorithm for Shift-JIS
1938 conversion. Only characters defined in the JIS code set table can be
1939 used with this encoding method.
1940
1941 @item EUC Coding
1942 @cindex EUC Coding
1943 A wide character is represented by a two-character sequence
1944 @code{16#ab#} and
1945 @code{16#cd#}, with both characters being in the upper half. The internal
1946 character code is the corresponding JIS character according to the EUC
1947 encoding algorithm. Only characters defined in the JIS code set table
1948 can be used with this encoding method.
1949
1950 @item UTF-8 Coding
1951 A wide character is represented using
1952 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1953 10646-1/Am.2. Depending on the character value, the representation
1954 is a one, two, or three byte sequence:
1955 @smallexample
1956 @iftex
1957 @leftskip=.7cm
1958 @end iftex
1959 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1960 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1961 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1962
1963 @end smallexample
1964
1965 @noindent
1966 where the @var{xxx} bits correspond to the left-padded bits of the
1967 16-bit character value. Note that all lower half ASCII characters
1968 are represented as ASCII bytes and all upper half characters and
1969 other wide characters are represented as sequences of upper-half
1970 (The full UTF-8 scheme allows for encoding 31-bit characters as
1971 6-byte sequences, but in this implementation, all UTF-8 sequences
1972 of four or more bytes length will be treated as illegal).
1973 @item Brackets Coding
1974 In this encoding, a wide character is represented by the following eight
1975 character sequence:
1976
1977 @smallexample
1978 [ " a b c d " ]
1979 @end smallexample
1980
1981 @noindent
1982 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1983 characters (using uppercase letters) of the wide character code. For
1984 example, [``A345''] is used to represent the wide character with code
1985 @code{16#A345#}. It is also possible (though not required) to use the
1986 Brackets coding for upper half characters. For example, the code
1987 @code{16#A3#} can be represented as @code{[``A3'']}.
1988
1989 This scheme is compatible with use of the full Wide_Character set,
1990 and is also the method used for wide character encoding in the standard
1991 ACVC (Ada Compiler Validation Capability) test suite distributions.
1992
1993 @end table
1994
1995 @noindent
1996 Note: Some of these coding schemes do not permit the full use of the
1997 Ada character set. For example, neither Shift JIS, nor EUC allow the
1998 use of the upper half of the Latin-1 set.
1999
2000 @node File Naming Rules
2001 @section File Naming Rules
2002
2003 @noindent
2004 The default file name is determined by the name of the unit that the
2005 file contains. The name is formed by taking the full expanded name of
2006 the unit and replacing the separating dots with hyphens and using
2007 ^lowercase^uppercase^ for all letters.
2008
2009 An exception arises if the file name generated by the above rules starts
2010 with one of the characters
2011 @ifset vms
2012 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2013 @end ifset
2014 @ifclear vms
2015 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2016 @end ifclear
2017 and the second character is a
2018 minus. In this case, the character ^tilde^dollar sign^ is used in place
2019 of the minus. The reason for this special rule is to avoid clashes with
2020 the standard names for child units of the packages System, Ada,
2021 Interfaces, and GNAT, which use the prefixes
2022 @ifset vms
2023 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2024 @end ifset
2025 @ifclear vms
2026 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2027 @end ifclear
2028 respectively.
2029
2030 The file extension is @file{.ads} for a spec and
2031 @file{.adb} for a body. The following list shows some
2032 examples of these rules.
2033
2034 @table @file
2035 @item main.ads
2036 Main (spec)
2037 @item main.adb
2038 Main (body)
2039 @item arith_functions.ads
2040 Arith_Functions (package spec)
2041 @item arith_functions.adb
2042 Arith_Functions (package body)
2043 @item func-spec.ads
2044 Func.Spec (child package spec)
2045 @item func-spec.adb
2046 Func.Spec (child package body)
2047 @item main-sub.adb
2048 Sub (subunit of Main)
2049 @item ^a~bad.adb^A$BAD.ADB^
2050 A.Bad (child package body)
2051 @end table
2052
2053 @noindent
2054 Following these rules can result in excessively long
2055 file names if corresponding
2056 unit names are long (for example, if child units or subunits are
2057 heavily nested). An option is available to shorten such long file names
2058 (called file name ``krunching''). This may be particularly useful when
2059 programs being developed with GNAT are to be used on operating systems
2060 with limited file name lengths. @xref{Using gnatkr}.
2061
2062 Of course, no file shortening algorithm can guarantee uniqueness over
2063 all possible unit names; if file name krunching is used, it is your
2064 responsibility to ensure no name clashes occur. Alternatively you
2065 can specify the exact file names that you want used, as described
2066 in the next section. Finally, if your Ada programs are migrating from a
2067 compiler with a different naming convention, you can use the gnatchop
2068 utility to produce source files that follow the GNAT naming conventions.
2069 (For details @pxref{Renaming Files Using gnatchop}.)
2070
2071 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2072 systems, case is not significant. So for example on @code{Windows XP}
2073 if the canonical name is @code{main-sub.adb}, you can use the file name
2074 @code{Main-Sub.adb} instead. However, case is significant for other
2075 operating systems, so for example, if you want to use other than
2076 canonically cased file names on a Unix system, you need to follow
2077 the procedures described in the next section.
2078
2079 @node Using Other File Names
2080 @section Using Other File Names
2081 @cindex File names
2082
2083 @noindent
2084 In the previous section, we have described the default rules used by
2085 GNAT to determine the file name in which a given unit resides. It is
2086 often convenient to follow these default rules, and if you follow them,
2087 the compiler knows without being explicitly told where to find all
2088 the files it needs.
2089
2090 However, in some cases, particularly when a program is imported from
2091 another Ada compiler environment, it may be more convenient for the
2092 programmer to specify which file names contain which units. GNAT allows
2093 arbitrary file names to be used by means of the Source_File_Name pragma.
2094 The form of this pragma is as shown in the following examples:
2095 @cindex Source_File_Name pragma
2096
2097 @smallexample @c ada
2098 @cartouche
2099 pragma Source_File_Name (My_Utilities.Stacks,
2100 Spec_File_Name => "myutilst_a.ada");
2101 pragma Source_File_name (My_Utilities.Stacks,
2102 Body_File_Name => "myutilst.ada");
2103 @end cartouche
2104 @end smallexample
2105
2106 @noindent
2107 As shown in this example, the first argument for the pragma is the unit
2108 name (in this example a child unit). The second argument has the form
2109 of a named association. The identifier
2110 indicates whether the file name is for a spec or a body;
2111 the file name itself is given by a string literal.
2112
2113 The source file name pragma is a configuration pragma, which means that
2114 normally it will be placed in the @file{gnat.adc}
2115 file used to hold configuration
2116 pragmas that apply to a complete compilation environment.
2117 For more details on how the @file{gnat.adc} file is created and used
2118 see @ref{Handling of Configuration Pragmas}.
2119 @cindex @file{gnat.adc}
2120
2121 @ifclear vms
2122 GNAT allows completely arbitrary file names to be specified using the
2123 source file name pragma. However, if the file name specified has an
2124 extension other than @file{.ads} or @file{.adb} it is necessary to use
2125 a special syntax when compiling the file. The name in this case must be
2126 preceded by the special sequence @option{-x} followed by a space and the name
2127 of the language, here @code{ada}, as in:
2128
2129 @smallexample
2130 $ gcc -c -x ada peculiar_file_name.sim
2131 @end smallexample
2132 @end ifclear
2133
2134 @noindent
2135 @command{gnatmake} handles non-standard file names in the usual manner (the
2136 non-standard file name for the main program is simply used as the
2137 argument to gnatmake). Note that if the extension is also non-standard,
2138 then it must be included in the @command{gnatmake} command, it may not
2139 be omitted.
2140
2141 @node Alternative File Naming Schemes
2142 @section Alternative File Naming Schemes
2143 @cindex File naming schemes, alternative
2144 @cindex File names
2145
2146 In the previous section, we described the use of the @code{Source_File_Name}
2147 pragma to allow arbitrary names to be assigned to individual source files.
2148 However, this approach requires one pragma for each file, and especially in
2149 large systems can result in very long @file{gnat.adc} files, and also create
2150 a maintenance problem.
2151
2152 GNAT also provides a facility for specifying systematic file naming schemes
2153 other than the standard default naming scheme previously described. An
2154 alternative scheme for naming is specified by the use of
2155 @code{Source_File_Name} pragmas having the following format:
2156 @cindex Source_File_Name pragma
2157
2158 @smallexample @c ada
2159 pragma Source_File_Name (
2160 Spec_File_Name => FILE_NAME_PATTERN
2161 @r{[},Casing => CASING_SPEC@r{]}
2162 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2163
2164 pragma Source_File_Name (
2165 Body_File_Name => FILE_NAME_PATTERN
2166 @r{[},Casing => CASING_SPEC@r{]}
2167 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2168
2169 pragma Source_File_Name (
2170 Subunit_File_Name => FILE_NAME_PATTERN
2171 @r{[},Casing => CASING_SPEC@r{]}
2172 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2173
2174 FILE_NAME_PATTERN ::= STRING_LITERAL
2175 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2176 @end smallexample
2177
2178 @noindent
2179 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2180 It contains a single asterisk character, and the unit name is substituted
2181 systematically for this asterisk. The optional parameter
2182 @code{Casing} indicates
2183 whether the unit name is to be all upper-case letters, all lower-case letters,
2184 or mixed-case. If no
2185 @code{Casing} parameter is used, then the default is all
2186 ^lower-case^upper-case^.
2187
2188 The optional @code{Dot_Replacement} string is used to replace any periods
2189 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2190 argument is used then separating dots appear unchanged in the resulting
2191 file name.
2192 Although the above syntax indicates that the
2193 @code{Casing} argument must appear
2194 before the @code{Dot_Replacement} argument, but it
2195 is also permissible to write these arguments in the opposite order.
2196
2197 As indicated, it is possible to specify different naming schemes for
2198 bodies, specs, and subunits. Quite often the rule for subunits is the
2199 same as the rule for bodies, in which case, there is no need to give
2200 a separate @code{Subunit_File_Name} rule, and in this case the
2201 @code{Body_File_name} rule is used for subunits as well.
2202
2203 The separate rule for subunits can also be used to implement the rather
2204 unusual case of a compilation environment (e.g.@: a single directory) which
2205 contains a subunit and a child unit with the same unit name. Although
2206 both units cannot appear in the same partition, the Ada Reference Manual
2207 allows (but does not require) the possibility of the two units coexisting
2208 in the same environment.
2209
2210 The file name translation works in the following steps:
2211
2212 @itemize @bullet
2213
2214 @item
2215 If there is a specific @code{Source_File_Name} pragma for the given unit,
2216 then this is always used, and any general pattern rules are ignored.
2217
2218 @item
2219 If there is a pattern type @code{Source_File_Name} pragma that applies to
2220 the unit, then the resulting file name will be used if the file exists. If
2221 more than one pattern matches, the latest one will be tried first, and the
2222 first attempt resulting in a reference to a file that exists will be used.
2223
2224 @item
2225 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2226 for which the corresponding file exists, then the standard GNAT default
2227 naming rules are used.
2228
2229 @end itemize
2230
2231 @noindent
2232 As an example of the use of this mechanism, consider a commonly used scheme
2233 in which file names are all lower case, with separating periods copied
2234 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2235 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2236 two pragmas appear:
2237
2238 @smallexample @c ada
2239 pragma Source_File_Name
2240 (Spec_File_Name => "*.1.ada");
2241 pragma Source_File_Name
2242 (Body_File_Name => "*.2.ada");
2243 @end smallexample
2244
2245 @noindent
2246 The default GNAT scheme is actually implemented by providing the following
2247 default pragmas internally:
2248
2249 @smallexample @c ada
2250 pragma Source_File_Name
2251 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2252 pragma Source_File_Name
2253 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2254 @end smallexample
2255
2256 @noindent
2257 Our final example implements a scheme typically used with one of the
2258 Ada 83 compilers, where the separator character for subunits was ``__''
2259 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2260 by adding @file{.ADA}, and subunits by
2261 adding @file{.SEP}. All file names were
2262 upper case. Child units were not present of course since this was an
2263 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2264 the same double underscore separator for child units.
2265
2266 @smallexample @c ada
2267 pragma Source_File_Name
2268 (Spec_File_Name => "*_.ADA",
2269 Dot_Replacement => "__",
2270 Casing = Uppercase);
2271 pragma Source_File_Name
2272 (Body_File_Name => "*.ADA",
2273 Dot_Replacement => "__",
2274 Casing = Uppercase);
2275 pragma Source_File_Name
2276 (Subunit_File_Name => "*.SEP",
2277 Dot_Replacement => "__",
2278 Casing = Uppercase);
2279 @end smallexample
2280
2281 @node Generating Object Files
2282 @section Generating Object Files
2283
2284 @noindent
2285 An Ada program consists of a set of source files, and the first step in
2286 compiling the program is to generate the corresponding object files.
2287 These are generated by compiling a subset of these source files.
2288 The files you need to compile are the following:
2289
2290 @itemize @bullet
2291 @item
2292 If a package spec has no body, compile the package spec to produce the
2293 object file for the package.
2294
2295 @item
2296 If a package has both a spec and a body, compile the body to produce the
2297 object file for the package. The source file for the package spec need
2298 not be compiled in this case because there is only one object file, which
2299 contains the code for both the spec and body of the package.
2300
2301 @item
2302 For a subprogram, compile the subprogram body to produce the object file
2303 for the subprogram. The spec, if one is present, is as usual in a
2304 separate file, and need not be compiled.
2305
2306 @item
2307 @cindex Subunits
2308 In the case of subunits, only compile the parent unit. A single object
2309 file is generated for the entire subunit tree, which includes all the
2310 subunits.
2311
2312 @item
2313 Compile child units independently of their parent units
2314 (though, of course, the spec of all the ancestor unit must be present in order
2315 to compile a child unit).
2316
2317 @item
2318 @cindex Generics
2319 Compile generic units in the same manner as any other units. The object
2320 files in this case are small dummy files that contain at most the
2321 flag used for elaboration checking. This is because GNAT always handles generic
2322 instantiation by means of macro expansion. However, it is still necessary to
2323 compile generic units, for dependency checking and elaboration purposes.
2324 @end itemize
2325
2326 @noindent
2327 The preceding rules describe the set of files that must be compiled to
2328 generate the object files for a program. Each object file has the same
2329 name as the corresponding source file, except that the extension is
2330 @file{.o} as usual.
2331
2332 You may wish to compile other files for the purpose of checking their
2333 syntactic and semantic correctness. For example, in the case where a
2334 package has a separate spec and body, you would not normally compile the
2335 spec. However, it is convenient in practice to compile the spec to make
2336 sure it is error-free before compiling clients of this spec, because such
2337 compilations will fail if there is an error in the spec.
2338
2339 GNAT provides an option for compiling such files purely for the
2340 purposes of checking correctness; such compilations are not required as
2341 part of the process of building a program. To compile a file in this
2342 checking mode, use the @option{-gnatc} switch.
2343
2344 @node Source Dependencies
2345 @section Source Dependencies
2346
2347 @noindent
2348 A given object file clearly depends on the source file which is compiled
2349 to produce it. Here we are using @dfn{depends} in the sense of a typical
2350 @code{make} utility; in other words, an object file depends on a source
2351 file if changes to the source file require the object file to be
2352 recompiled.
2353 In addition to this basic dependency, a given object may depend on
2354 additional source files as follows:
2355
2356 @itemize @bullet
2357 @item
2358 If a file being compiled @code{with}'s a unit @var{X}, the object file
2359 depends on the file containing the spec of unit @var{X}. This includes
2360 files that are @code{with}'ed implicitly either because they are parents
2361 of @code{with}'ed child units or they are run-time units required by the
2362 language constructs used in a particular unit.
2363
2364 @item
2365 If a file being compiled instantiates a library level generic unit, the
2366 object file depends on both the spec and body files for this generic
2367 unit.
2368
2369 @item
2370 If a file being compiled instantiates a generic unit defined within a
2371 package, the object file depends on the body file for the package as
2372 well as the spec file.
2373
2374 @item
2375 @findex Inline
2376 @cindex @option{-gnatn} switch
2377 If a file being compiled contains a call to a subprogram for which
2378 pragma @code{Inline} applies and inlining is activated with the
2379 @option{-gnatn} switch, the object file depends on the file containing the
2380 body of this subprogram as well as on the file containing the spec. Note
2381 that for inlining to actually occur as a result of the use of this switch,
2382 it is necessary to compile in optimizing mode.
2383
2384 @cindex @option{-gnatN} switch
2385 The use of @option{-gnatN} activates inlining optimization
2386 that is performed by the front end of the compiler. This inlining does
2387 not require that the code generation be optimized. Like @option{-gnatn},
2388 the use of this switch generates additional dependencies.
2389
2390 When using a gcc-based back end (in practice this means using any version
2391 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2392 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2393 Historically front end inlining was more extensive than the gcc back end
2394 inlining, but that is no longer the case.
2395
2396 @item
2397 If an object file @file{O} depends on the proper body of a subunit through
2398 inlining or instantiation, it depends on the parent unit of the subunit.
2399 This means that any modification of the parent unit or one of its subunits
2400 affects the compilation of @file{O}.
2401
2402 @item
2403 The object file for a parent unit depends on all its subunit body files.
2404
2405 @item
2406 The previous two rules meant that for purposes of computing dependencies and
2407 recompilation, a body and all its subunits are treated as an indivisible whole.
2408
2409 @noindent
2410 These rules are applied transitively: if unit @code{A} @code{with}'s
2411 unit @code{B}, whose elaboration calls an inlined procedure in package
2412 @code{C}, the object file for unit @code{A} will depend on the body of
2413 @code{C}, in file @file{c.adb}.
2414
2415 The set of dependent files described by these rules includes all the
2416 files on which the unit is semantically dependent, as dictated by the
2417 Ada language standard. However, it is a superset of what the
2418 standard describes, because it includes generic, inline, and subunit
2419 dependencies.
2420
2421 An object file must be recreated by recompiling the corresponding source
2422 file if any of the source files on which it depends are modified. For
2423 example, if the @code{make} utility is used to control compilation,
2424 the rule for an Ada object file must mention all the source files on
2425 which the object file depends, according to the above definition.
2426 The determination of the necessary
2427 recompilations is done automatically when one uses @command{gnatmake}.
2428 @end itemize
2429
2430 @node The Ada Library Information Files
2431 @section The Ada Library Information Files
2432 @cindex Ada Library Information files
2433 @cindex @file{ALI} files
2434
2435 @noindent
2436 Each compilation actually generates two output files. The first of these
2437 is the normal object file that has a @file{.o} extension. The second is a
2438 text file containing full dependency information. It has the same
2439 name as the source file, but an @file{.ali} extension.
2440 This file is known as the Ada Library Information (@file{ALI}) file.
2441 The following information is contained in the @file{ALI} file.
2442
2443 @itemize @bullet
2444 @item
2445 Version information (indicates which version of GNAT was used to compile
2446 the unit(s) in question)
2447
2448 @item
2449 Main program information (including priority and time slice settings,
2450 as well as the wide character encoding used during compilation).
2451
2452 @item
2453 List of arguments used in the @command{gcc} command for the compilation
2454
2455 @item
2456 Attributes of the unit, including configuration pragmas used, an indication
2457 of whether the compilation was successful, exception model used etc.
2458
2459 @item
2460 A list of relevant restrictions applying to the unit (used for consistency)
2461 checking.
2462
2463 @item
2464 Categorization information (e.g.@: use of pragma @code{Pure}).
2465
2466 @item
2467 Information on all @code{with}'ed units, including presence of
2468 @code{Elaborate} or @code{Elaborate_All} pragmas.
2469
2470 @item
2471 Information from any @code{Linker_Options} pragmas used in the unit
2472
2473 @item
2474 Information on the use of @code{Body_Version} or @code{Version}
2475 attributes in the unit.
2476
2477 @item
2478 Dependency information. This is a list of files, together with
2479 time stamp and checksum information. These are files on which
2480 the unit depends in the sense that recompilation is required
2481 if any of these units are modified.
2482
2483 @item
2484 Cross-reference data. Contains information on all entities referenced
2485 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2486 provide cross-reference information.
2487
2488 @end itemize
2489
2490 @noindent
2491 For a full detailed description of the format of the @file{ALI} file,
2492 see the source of the body of unit @code{Lib.Writ}, contained in file
2493 @file{lib-writ.adb} in the GNAT compiler sources.
2494
2495 @node Binding an Ada Program
2496 @section Binding an Ada Program
2497
2498 @noindent
2499 When using languages such as C and C++, once the source files have been
2500 compiled the only remaining step in building an executable program
2501 is linking the object modules together. This means that it is possible to
2502 link an inconsistent version of a program, in which two units have
2503 included different versions of the same header.
2504
2505 The rules of Ada do not permit such an inconsistent program to be built.
2506 For example, if two clients have different versions of the same package,
2507 it is illegal to build a program containing these two clients.
2508 These rules are enforced by the GNAT binder, which also determines an
2509 elaboration order consistent with the Ada rules.
2510
2511 The GNAT binder is run after all the object files for a program have
2512 been created. It is given the name of the main program unit, and from
2513 this it determines the set of units required by the program, by reading the
2514 corresponding ALI files. It generates error messages if the program is
2515 inconsistent or if no valid order of elaboration exists.
2516
2517 If no errors are detected, the binder produces a main program, in Ada by
2518 default, that contains calls to the elaboration procedures of those
2519 compilation unit that require them, followed by
2520 a call to the main program. This Ada program is compiled to generate the
2521 object file for the main program. The name of
2522 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2523 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2524 main program unit.
2525
2526 Finally, the linker is used to build the resulting executable program,
2527 using the object from the main program from the bind step as well as the
2528 object files for the Ada units of the program.
2529
2530 @node Mixed Language Programming
2531 @section Mixed Language Programming
2532 @cindex Mixed Language Programming
2533
2534 @noindent
2535 This section describes how to develop a mixed-language program,
2536 specifically one that comprises units in both Ada and C.
2537
2538 @menu
2539 * Interfacing to C::
2540 * Calling Conventions::
2541 @end menu
2542
2543 @node Interfacing to C
2544 @subsection Interfacing to C
2545 @noindent
2546 Interfacing Ada with a foreign language such as C involves using
2547 compiler directives to import and/or export entity definitions in each
2548 language---using @code{extern} statements in C, for instance, and the
2549 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2550 A full treatment of these topics is provided in Appendix B, section 1
2551 of the Ada Reference Manual.
2552
2553 There are two ways to build a program using GNAT that contains some Ada
2554 sources and some foreign language sources, depending on whether or not
2555 the main subprogram is written in Ada. Here is a source example with
2556 the main subprogram in Ada:
2557
2558 @smallexample
2559 /* file1.c */
2560 #include <stdio.h>
2561
2562 void print_num (int num)
2563 @{
2564 printf ("num is %d.\n", num);
2565 return;
2566 @}
2567
2568 /* file2.c */
2569
2570 /* num_from_Ada is declared in my_main.adb */
2571 extern int num_from_Ada;
2572
2573 int get_num (void)
2574 @{
2575 return num_from_Ada;
2576 @}
2577 @end smallexample
2578
2579 @smallexample @c ada
2580 -- my_main.adb
2581 procedure My_Main is
2582
2583 -- Declare then export an Integer entity called num_from_Ada
2584 My_Num : Integer := 10;
2585 pragma Export (C, My_Num, "num_from_Ada");
2586
2587 -- Declare an Ada function spec for Get_Num, then use
2588 -- C function get_num for the implementation.
2589 function Get_Num return Integer;
2590 pragma Import (C, Get_Num, "get_num");
2591
2592 -- Declare an Ada procedure spec for Print_Num, then use
2593 -- C function print_num for the implementation.
2594 procedure Print_Num (Num : Integer);
2595 pragma Import (C, Print_Num, "print_num");
2596
2597 begin
2598 Print_Num (Get_Num);
2599 end My_Main;
2600 @end smallexample
2601
2602 @enumerate
2603 @item
2604 To build this example, first compile the foreign language files to
2605 generate object files:
2606 @smallexample
2607 ^gcc -c file1.c^gcc -c FILE1.C^
2608 ^gcc -c file2.c^gcc -c FILE2.C^
2609 @end smallexample
2610
2611 @item
2612 Then, compile the Ada units to produce a set of object files and ALI
2613 files:
2614 @smallexample
2615 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2616 @end smallexample
2617
2618 @item
2619 Run the Ada binder on the Ada main program:
2620 @smallexample
2621 gnatbind my_main.ali
2622 @end smallexample
2623
2624 @item
2625 Link the Ada main program, the Ada objects and the other language
2626 objects:
2627 @smallexample
2628 gnatlink my_main.ali file1.o file2.o
2629 @end smallexample
2630 @end enumerate
2631
2632 The last three steps can be grouped in a single command:
2633 @smallexample
2634 gnatmake my_main.adb -largs file1.o file2.o
2635 @end smallexample
2636
2637 @cindex Binder output file
2638 @noindent
2639 If the main program is in a language other than Ada, then you may have
2640 more than one entry point into the Ada subsystem. You must use a special
2641 binder option to generate callable routines that initialize and
2642 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2643 Calls to the initialization and finalization routines must be inserted
2644 in the main program, or some other appropriate point in the code. The
2645 call to initialize the Ada units must occur before the first Ada
2646 subprogram is called, and the call to finalize the Ada units must occur
2647 after the last Ada subprogram returns. The binder will place the
2648 initialization and finalization subprograms into the
2649 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2650 sources. To illustrate, we have the following example:
2651
2652 @smallexample
2653 /* main.c */
2654 extern void adainit (void);
2655 extern void adafinal (void);
2656 extern int add (int, int);
2657 extern int sub (int, int);
2658
2659 int main (int argc, char *argv[])
2660 @{
2661 int a = 21, b = 7;
2662
2663 adainit();
2664
2665 /* Should print "21 + 7 = 28" */
2666 printf ("%d + %d = %d\n", a, b, add (a, b));
2667 /* Should print "21 - 7 = 14" */
2668 printf ("%d - %d = %d\n", a, b, sub (a, b));
2669
2670 adafinal();
2671 @}
2672 @end smallexample
2673
2674 @smallexample @c ada
2675 -- unit1.ads
2676 package Unit1 is
2677 function Add (A, B : Integer) return Integer;
2678 pragma Export (C, Add, "add");
2679 end Unit1;
2680
2681 -- unit1.adb
2682 package body Unit1 is
2683 function Add (A, B : Integer) return Integer is
2684 begin
2685 return A + B;
2686 end Add;
2687 end Unit1;
2688
2689 -- unit2.ads
2690 package Unit2 is
2691 function Sub (A, B : Integer) return Integer;
2692 pragma Export (C, Sub, "sub");
2693 end Unit2;
2694
2695 -- unit2.adb
2696 package body Unit2 is
2697 function Sub (A, B : Integer) return Integer is
2698 begin
2699 return A - B;
2700 end Sub;
2701 end Unit2;
2702 @end smallexample
2703
2704 @enumerate
2705 @item
2706 The build procedure for this application is similar to the last
2707 example's. First, compile the foreign language files to generate object
2708 files:
2709 @smallexample
2710 ^gcc -c main.c^gcc -c main.c^
2711 @end smallexample
2712
2713 @item
2714 Next, compile the Ada units to produce a set of object files and ALI
2715 files:
2716 @smallexample
2717 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2718 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2719 @end smallexample
2720
2721 @item
2722 Run the Ada binder on every generated ALI file. Make sure to use the
2723 @option{-n} option to specify a foreign main program:
2724 @smallexample
2725 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2726 @end smallexample
2727
2728 @item
2729 Link the Ada main program, the Ada objects and the foreign language
2730 objects. You need only list the last ALI file here:
2731 @smallexample
2732 gnatlink unit2.ali main.o -o exec_file
2733 @end smallexample
2734
2735 This procedure yields a binary executable called @file{exec_file}.
2736 @end enumerate
2737
2738 @noindent
2739 Depending on the circumstances (for example when your non-Ada main object
2740 does not provide symbol @code{main}), you may also need to instruct the
2741 GNAT linker not to include the standard startup objects by passing the
2742 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2743
2744 @node Calling Conventions
2745 @subsection Calling Conventions
2746 @cindex Foreign Languages
2747 @cindex Calling Conventions
2748 GNAT follows standard calling sequence conventions and will thus interface
2749 to any other language that also follows these conventions. The following
2750 Convention identifiers are recognized by GNAT:
2751
2752 @table @code
2753 @cindex Interfacing to Ada
2754 @cindex Other Ada compilers
2755 @cindex Convention Ada
2756 @item Ada
2757 This indicates that the standard Ada calling sequence will be
2758 used and all Ada data items may be passed without any limitations in the
2759 case where GNAT is used to generate both the caller and callee. It is also
2760 possible to mix GNAT generated code and code generated by another Ada
2761 compiler. In this case, the data types should be restricted to simple
2762 cases, including primitive types. Whether complex data types can be passed
2763 depends on the situation. Probably it is safe to pass simple arrays, such
2764 as arrays of integers or floats. Records may or may not work, depending
2765 on whether both compilers lay them out identically. Complex structures
2766 involving variant records, access parameters, tasks, or protected types,
2767 are unlikely to be able to be passed.
2768
2769 Note that in the case of GNAT running
2770 on a platform that supports HP Ada 83, a higher degree of compatibility
2771 can be guaranteed, and in particular records are layed out in an identical
2772 manner in the two compilers. Note also that if output from two different
2773 compilers is mixed, the program is responsible for dealing with elaboration
2774 issues. Probably the safest approach is to write the main program in the
2775 version of Ada other than GNAT, so that it takes care of its own elaboration
2776 requirements, and then call the GNAT-generated adainit procedure to ensure
2777 elaboration of the GNAT components. Consult the documentation of the other
2778 Ada compiler for further details on elaboration.
2779
2780 However, it is not possible to mix the tasking run time of GNAT and
2781 HP Ada 83, All the tasking operations must either be entirely within
2782 GNAT compiled sections of the program, or entirely within HP Ada 83
2783 compiled sections of the program.
2784
2785 @cindex Interfacing to Assembly
2786 @cindex Convention Assembler
2787 @item Assembler
2788 Specifies assembler as the convention. In practice this has the
2789 same effect as convention Ada (but is not equivalent in the sense of being
2790 considered the same convention).
2791
2792 @cindex Convention Asm
2793 @findex Asm
2794 @item Asm
2795 Equivalent to Assembler.
2796
2797 @cindex Interfacing to COBOL
2798 @cindex Convention COBOL
2799 @findex COBOL
2800 @item COBOL
2801 Data will be passed according to the conventions described
2802 in section B.4 of the Ada Reference Manual.
2803
2804 @findex C
2805 @cindex Interfacing to C
2806 @cindex Convention C
2807 @item C
2808 Data will be passed according to the conventions described
2809 in section B.3 of the Ada Reference Manual.
2810
2811 A note on interfacing to a C ``varargs'' function:
2812 @findex C varargs function
2813 @cindex Interfacing to C varargs function
2814 @cindex varargs function interfaces
2815
2816 @itemize @bullet
2817 @item
2818 In C, @code{varargs} allows a function to take a variable number of
2819 arguments. There is no direct equivalent in this to Ada. One
2820 approach that can be used is to create a C wrapper for each
2821 different profile and then interface to this C wrapper. For
2822 example, to print an @code{int} value using @code{printf},
2823 create a C function @code{printfi} that takes two arguments, a
2824 pointer to a string and an int, and calls @code{printf}.
2825 Then in the Ada program, use pragma @code{Import} to
2826 interface to @code{printfi}.
2827
2828 @item
2829 It may work on some platforms to directly interface to
2830 a @code{varargs} function by providing a specific Ada profile
2831 for a particular call. However, this does not work on
2832 all platforms, since there is no guarantee that the
2833 calling sequence for a two argument normal C function
2834 is the same as for calling a @code{varargs} C function with
2835 the same two arguments.
2836 @end itemize
2837
2838 @cindex Convention Default
2839 @findex Default
2840 @item Default
2841 Equivalent to C.
2842
2843 @cindex Convention External
2844 @findex External
2845 @item External
2846 Equivalent to C.
2847
2848 @ifclear vms
2849 @findex C++
2850 @cindex Interfacing to C++
2851 @cindex Convention C++
2852 @item C_Plus_Plus (or CPP)
2853 This stands for C++. For most purposes this is identical to C.
2854 See the separate description of the specialized GNAT pragmas relating to
2855 C++ interfacing for further details.
2856 @end ifclear
2857
2858 @findex Fortran
2859 @cindex Interfacing to Fortran
2860 @cindex Convention Fortran
2861 @item Fortran
2862 Data will be passed according to the conventions described
2863 in section B.5 of the Ada Reference Manual.
2864
2865 @item Intrinsic
2866 This applies to an intrinsic operation, as defined in the Ada
2867 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2868 this means that the body of the subprogram is provided by the compiler itself,
2869 usually by means of an efficient code sequence, and that the user does not
2870 supply an explicit body for it. In an application program, the pragma may
2871 be applied to the following sets of names:
2872
2873 @itemize @bullet
2874 @item
2875 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2876 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2877 two formal parameters. The
2878 first one must be a signed integer type or a modular type with a binary
2879 modulus, and the second parameter must be of type Natural.
2880 The return type must be the same as the type of the first argument. The size
2881 of this type can only be 8, 16, 32, or 64.
2882
2883 @item
2884 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2885 The corresponding operator declaration must have parameters and result type
2886 that have the same root numeric type (for example, all three are long_float
2887 types). This simplifies the definition of operations that use type checking
2888 to perform dimensional checks:
2889
2890 @smallexample @c ada
2891 type Distance is new Long_Float;
2892 type Time is new Long_Float;
2893 type Velocity is new Long_Float;
2894 function "/" (D : Distance; T : Time)
2895 return Velocity;
2896 pragma Import (Intrinsic, "/");
2897 @end smallexample
2898
2899 @noindent
2900 This common idiom is often programmed with a generic definition and an
2901 explicit body. The pragma makes it simpler to introduce such declarations.
2902 It incurs no overhead in compilation time or code size, because it is
2903 implemented as a single machine instruction.
2904
2905 @item
2906 General subprogram entities, to bind an Ada subprogram declaration to
2907 a compiler builtin by name with back-ends where such interfaces are
2908 available. A typical example is the set of ``__builtin'' functions
2909 exposed by the GCC back-end, as in the following example:
2910
2911 @smallexample @c ada
2912 function builtin_sqrt (F : Float) return Float;
2913 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2914 @end smallexample
2915
2916 Most of the GCC builtins are accessible this way, and as for other
2917 import conventions (e.g. C), it is the user's responsibility to ensure
2918 that the Ada subprogram profile matches the underlying builtin
2919 expectations.
2920 @end itemize
2921
2922 @noindent
2923
2924 @ifset unw
2925 @findex Stdcall
2926 @cindex Convention Stdcall
2927 @item Stdcall
2928 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2929 and specifies that the @code{Stdcall} calling sequence will be used,
2930 as defined by the NT API. Nevertheless, to ease building
2931 cross-platform bindings this convention will be handled as a @code{C} calling
2932 convention on non-Windows platforms.
2933
2934 @findex DLL
2935 @cindex Convention DLL
2936 @item DLL
2937 This is equivalent to @code{Stdcall}.
2938
2939 @findex Win32
2940 @cindex Convention Win32
2941 @item Win32
2942 This is equivalent to @code{Stdcall}.
2943 @end ifset
2944
2945 @findex Stubbed
2946 @cindex Convention Stubbed
2947 @item Stubbed
2948 This is a special convention that indicates that the compiler
2949 should provide a stub body that raises @code{Program_Error}.
2950 @end table
2951
2952 @noindent
2953 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2954 that can be used to parameterize conventions and allow additional synonyms
2955 to be specified. For example if you have legacy code in which the convention
2956 identifier Fortran77 was used for Fortran, you can use the configuration
2957 pragma:
2958
2959 @smallexample @c ada
2960 pragma Convention_Identifier (Fortran77, Fortran);
2961 @end smallexample
2962
2963 @noindent
2964 And from now on the identifier Fortran77 may be used as a convention
2965 identifier (for example in an @code{Import} pragma) with the same
2966 meaning as Fortran.
2967
2968 @ifclear vms
2969 @node Building Mixed Ada & C++ Programs
2970 @section Building Mixed Ada and C++ Programs
2971
2972 @noindent
2973 A programmer inexperienced with mixed-language development may find that
2974 building an application containing both Ada and C++ code can be a
2975 challenge. This section gives a few
2976 hints that should make this task easier. The first section addresses
2977 the differences between interfacing with C and interfacing with C++.
2978 The second section
2979 looks into the delicate problem of linking the complete application from
2980 its Ada and C++ parts. The last section gives some hints on how the GNAT
2981 run-time library can be adapted in order to allow inter-language dispatching
2982 with a new C++ compiler.
2983
2984 @menu
2985 * Interfacing to C++::
2986 * Linking a Mixed C++ & Ada Program::
2987 * A Simple Example::
2988 * Interfacing with C++ constructors::
2989 * Interfacing with C++ at the Class Level::
2990 @end menu
2991
2992 @node Interfacing to C++
2993 @subsection Interfacing to C++
2994
2995 @noindent
2996 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2997 generating code that is compatible with the G++ Application Binary
2998 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2999
3000 @noindent
3001 Interfacing can be done at 3 levels: simple data, subprograms, and
3002 classes. In the first two cases, GNAT offers a specific @code{Convention
3003 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3004 Usually, C++ mangles the names of subprograms. To generate proper mangled
3005 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3006 This problem can also be addressed manually in two ways:
3007
3008 @itemize @bullet
3009 @item
3010 by modifying the C++ code in order to force a C convention using
3011 the @code{extern "C"} syntax.
3012
3013 @item
3014 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3015 Link_Name argument of the pragma import.
3016 @end itemize
3017
3018 @noindent
3019 Interfacing at the class level can be achieved by using the GNAT specific
3020 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3021 gnat_rm, GNAT Reference Manual}, for additional information.
3022
3023 @node Linking a Mixed C++ & Ada Program
3024 @subsection Linking a Mixed C++ & Ada Program
3025
3026 @noindent
3027 Usually the linker of the C++ development system must be used to link
3028 mixed applications because most C++ systems will resolve elaboration
3029 issues (such as calling constructors on global class instances)
3030 transparently during the link phase. GNAT has been adapted to ease the
3031 use of a foreign linker for the last phase. Three cases can be
3032 considered:
3033 @enumerate
3034
3035 @item
3036 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3037 The C++ linker can simply be called by using the C++ specific driver
3038 called @code{g++}.
3039
3040 Note that if the C++ code uses inline functions, you will need to
3041 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3042 order to provide an existing function implementation that the Ada code can
3043 link with.
3044
3045 @smallexample
3046 $ g++ -c -fkeep-inline-functions file1.C
3047 $ g++ -c -fkeep-inline-functions file2.C
3048 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3049 @end smallexample
3050
3051 @item
3052 Using GNAT and G++ from two different GCC installations: If both
3053 compilers are on the @env{PATH}, the previous method may be used. It is
3054 important to note that environment variables such as
3055 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3056 @env{GCC_ROOT} will affect both compilers
3057 at the same time and may make one of the two compilers operate
3058 improperly if set during invocation of the wrong compiler. It is also
3059 very important that the linker uses the proper @file{libgcc.a} GCC
3060 library -- that is, the one from the C++ compiler installation. The
3061 implicit link command as suggested in the @command{gnatmake} command
3062 from the former example can be replaced by an explicit link command with
3063 the full-verbosity option in order to verify which library is used:
3064 @smallexample
3065 $ gnatbind ada_unit
3066 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3067 @end smallexample
3068 If there is a problem due to interfering environment variables, it can
3069 be worked around by using an intermediate script. The following example
3070 shows the proper script to use when GNAT has not been installed at its
3071 default location and g++ has been installed at its default location:
3072
3073 @smallexample
3074 $ cat ./my_script
3075 #!/bin/sh
3076 unset BINUTILS_ROOT
3077 unset GCC_ROOT
3078 c++ $*
3079 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3080 @end smallexample
3081
3082 @item
3083 Using a non-GNU C++ compiler: The commands previously described can be
3084 used to insure that the C++ linker is used. Nonetheless, you need to add
3085 a few more parameters to the link command line, depending on the exception
3086 mechanism used.
3087
3088 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3089 to the libgcc libraries are required:
3090
3091 @smallexample
3092 $ cat ./my_script
3093 #!/bin/sh
3094 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3095 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3096 @end smallexample
3097
3098 Where CC is the name of the non-GNU C++ compiler.
3099
3100 If the @code{zero cost} exception mechanism is used, and the platform
3101 supports automatic registration of exception tables (e.g.@: Solaris),
3102 paths to more objects are required:
3103
3104 @smallexample
3105 $ cat ./my_script
3106 #!/bin/sh
3107 CC `gcc -print-file-name=crtbegin.o` $* \
3108 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3109 `gcc -print-file-name=crtend.o`
3110 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3111 @end smallexample
3112
3113 If the @code{zero cost} exception mechanism is used, and the platform
3114 doesn't support automatic registration of exception tables (e.g.@: HP-UX
3115 or AIX), the simple approach described above will not work and
3116 a pre-linking phase using GNAT will be necessary.
3117
3118 @end enumerate
3119
3120 Another alternative is to use the @command{gprbuild} multi-language builder
3121 which has a large knowledge base and knows how to link Ada and C++ code
3122 together automatically in most cases.
3123
3124 @node A Simple Example
3125 @subsection A Simple Example
3126 @noindent
3127 The following example, provided as part of the GNAT examples, shows how
3128 to achieve procedural interfacing between Ada and C++ in both
3129 directions. The C++ class A has two methods. The first method is exported
3130 to Ada by the means of an extern C wrapper function. The second method
3131 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3132 a limited record with a layout comparable to the C++ class. The Ada
3133 subprogram, in turn, calls the C++ method. So, starting from the C++
3134 main program, the process passes back and forth between the two
3135 languages.
3136
3137 @noindent
3138 Here are the compilation commands:
3139 @smallexample
3140 $ gnatmake -c simple_cpp_interface
3141 $ g++ -c cpp_main.C
3142 $ g++ -c ex7.C
3143 $ gnatbind -n simple_cpp_interface
3144 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3145 -lstdc++ ex7.o cpp_main.o
3146 @end smallexample
3147
3148 @noindent
3149 Here are the corresponding sources:
3150 @smallexample
3151
3152 //cpp_main.C
3153
3154 #include "ex7.h"
3155
3156 extern "C" @{
3157 void adainit (void);
3158 void adafinal (void);
3159 void method1 (A *t);
3160 @}
3161
3162 void method1 (A *t)
3163 @{
3164 t->method1 ();
3165 @}
3166
3167 int main ()
3168 @{
3169 A obj;
3170 adainit ();
3171 obj.method2 (3030);
3172 adafinal ();
3173 @}
3174
3175 //ex7.h
3176
3177 class Origin @{
3178 public:
3179 int o_value;
3180 @};
3181 class A : public Origin @{
3182 public:
3183 void method1 (void);
3184 void method2 (int v);
3185 A();
3186 int a_value;
3187 @};
3188
3189 //ex7.C
3190
3191 #include "ex7.h"
3192 #include <stdio.h>
3193
3194 extern "C" @{ void ada_method2 (A *t, int v);@}
3195
3196 void A::method1 (void)
3197 @{
3198 a_value = 2020;
3199 printf ("in A::method1, a_value = %d \n",a_value);
3200
3201 @}
3202
3203 void A::method2 (int v)
3204 @{
3205 ada_method2 (this, v);
3206 printf ("in A::method2, a_value = %d \n",a_value);
3207
3208 @}
3209
3210 A::A(void)
3211 @{
3212 a_value = 1010;
3213 printf ("in A::A, a_value = %d \n",a_value);
3214 @}
3215 @end smallexample
3216
3217 @smallexample @c ada
3218 -- Ada sources
3219 package body Simple_Cpp_Interface is
3220
3221 procedure Ada_Method2 (This : in out A; V : Integer) is
3222 begin
3223 Method1 (This);
3224 This.A_Value := V;
3225 end Ada_Method2;
3226
3227 end Simple_Cpp_Interface;
3228
3229 with System;
3230 package Simple_Cpp_Interface is
3231 type A is limited
3232 record
3233 Vptr : System.Address;
3234 O_Value : Integer;
3235 A_Value : Integer;
3236 end record;
3237 pragma Convention (C, A);
3238
3239 procedure Method1 (This : in out A);
3240 pragma Import (C, Method1);
3241
3242 procedure Ada_Method2 (This : in out A; V : Integer);
3243 pragma Export (C, Ada_Method2);
3244
3245 end Simple_Cpp_Interface;
3246 @end smallexample
3247
3248 @node Interfacing with C++ constructors
3249 @subsection Interfacing with C++ constructors
3250 @noindent
3251
3252 In order to interface with C++ constructors GNAT provides the
3253 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3254 gnat_rm, GNAT Reference Manual}, for additional information).
3255 In this section we present some common uses of C++ constructors
3256 in mixed-languages programs in GNAT.
3257
3258 Let us assume that we need to interface with the following
3259 C++ class:
3260
3261 @smallexample
3262 @b{class} Root @{
3263 @b{public}:
3264 int a_value;
3265 int b_value;
3266 @b{virtual} int Get_Value ();
3267 Root(); // Default constructor
3268 Root(int v); // 1st non-default constructor
3269 Root(int v, int w); // 2nd non-default constructor
3270 @};
3271 @end smallexample
3272
3273 For this purpose we can write the following package spec (further
3274 information on how to build this spec is available in
3275 @ref{Interfacing with C++ at the Class Level} and
3276 @ref{Generating Ada Bindings for C and C++ headers}).
3277
3278 @smallexample @c ada
3279 with Interfaces.C; use Interfaces.C;
3280 package Pkg_Root is
3281 type Root is tagged limited record
3282 A_Value : int;
3283 B_Value : int;
3284 end record;
3285 pragma Import (CPP, Root);
3286
3287 function Get_Value (Obj : Root) return int;
3288 pragma Import (CPP, Get_Value);
3289
3290 function Constructor return Root;
3291 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3292
3293 function Constructor (v : Integer) return Root;
3294 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3295
3296 function Constructor (v, w : Integer) return Root;
3297 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3298 end Pkg_Root;
3299 @end smallexample
3300
3301 On the Ada side the constructor is represented by a function (whose
3302 name is arbitrary) that returns the classwide type corresponding to
3303 the imported C++ class. Although the constructor is described as a
3304 function, it is typically a procedure with an extra implicit argument
3305 (the object being initialized) at the implementation level. GNAT
3306 issues the appropriate call, whatever it is, to get the object
3307 properly initialized.
3308
3309 Constructors can only appear in the following contexts:
3310
3311 @itemize @bullet
3312 @item
3313 On the right side of an initialization of an object of type @var{T}.
3314 @item
3315 On the right side of an initialization of a record component of type @var{T}.
3316 @item
3317 In an Ada 2005 limited aggregate.
3318 @item
3319 In an Ada 2005 nested limited aggregate.
3320 @item
3321 In an Ada 2005 limited aggregate that initializes an object built in
3322 place by an extended return statement.
3323 @end itemize
3324
3325 @noindent
3326 In a declaration of an object whose type is a class imported from C++,
3327 either the default C++ constructor is implicitly called by GNAT, or
3328 else the required C++ constructor must be explicitly called in the
3329 expression that initializes the object. For example:
3330
3331 @smallexample @c ada
3332 Obj1 : Root;
3333 Obj2 : Root := Constructor;
3334 Obj3 : Root := Constructor (v => 10);
3335 Obj4 : Root := Constructor (30, 40);
3336 @end smallexample
3337
3338 The first two declarations are equivalent: in both cases the default C++
3339 constructor is invoked (in the former case the call to the constructor is
3340 implicit, and in the latter case the call is explicit in the object
3341 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3342 that takes an integer argument, and @code{Obj4} is initialized by the
3343 non-default C++ constructor that takes two integers.
3344
3345 Let us derive the imported C++ class in the Ada side. For example:
3346
3347 @smallexample @c ada
3348 type DT is new Root with record
3349 C_Value : Natural := 2009;
3350 end record;
3351 @end smallexample
3352
3353 In this case the components DT inherited from the C++ side must be
3354 initialized by a C++ constructor, and the additional Ada components
3355 of type DT are initialized by GNAT. The initialization of such an
3356 object is done either by default, or by means of a function returning
3357 an aggregate of type DT, or by means of an extension aggregate.
3358
3359 @smallexample @c ada
3360 Obj5 : DT;
3361 Obj6 : DT := Function_Returning_DT (50);
3362 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3363 @end smallexample
3364
3365 The declaration of @code{Obj5} invokes the default constructors: the
3366 C++ default constructor of the parent type takes care of the initialization
3367 of the components inherited from Root, and GNAT takes care of the default
3368 initialization of the additional Ada components of type DT (that is,
3369 @code{C_Value} is initialized to value 2009). The order of invocation of
3370 the constructors is consistent with the order of elaboration required by
3371 Ada and C++. That is, the constructor of the parent type is always called
3372 before the constructor of the derived type.
3373
3374 Let us now consider a record that has components whose type is imported
3375 from C++. For example:
3376
3377 @smallexample @c ada
3378 type Rec1 is limited record
3379 Data1 : Root := Constructor (10);
3380 Value : Natural := 1000;
3381 end record;
3382
3383 type Rec2 (D : Integer := 20) is limited record
3384 Rec : Rec1;
3385 Data2 : Root := Constructor (D, 30);
3386 end record;
3387 @end smallexample
3388
3389 The initialization of an object of type @code{Rec2} will call the
3390 non-default C++ constructors specified for the imported components.
3391 For example:
3392
3393 @smallexample @c ada
3394 Obj8 : Rec2 (40);
3395 @end smallexample
3396
3397 Using Ada 2005 we can use limited aggregates to initialize an object
3398 invoking C++ constructors that differ from those specified in the type
3399 declarations. For example:
3400
3401 @smallexample @c ada
3402 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3403 others => <>),
3404 others => <>);
3405 @end smallexample
3406
3407 The above declaration uses an Ada 2005 limited aggregate to
3408 initialize @code{Obj9}, and the C++ constructor that has two integer
3409 arguments is invoked to initialize the @code{Data1} component instead
3410 of the constructor specified in the declaration of type @code{Rec1}. In
3411 Ada 2005 the box in the aggregate indicates that unspecified components
3412 are initialized using the expression (if any) available in the component
3413 declaration. That is, in this case discriminant @code{D} is initialized
3414 to value @code{20}, @code{Value} is initialized to value 1000, and the
3415 non-default C++ constructor that handles two integers takes care of
3416 initializing component @code{Data2} with values @code{20,30}.
3417
3418 In Ada 2005 we can use the extended return statement to build the Ada
3419 equivalent to C++ non-default constructors. For example:
3420
3421 @smallexample @c ada
3422 function Constructor (V : Integer) return Rec2 is
3423 begin
3424 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3425 others => <>),
3426 others => <>) do
3427 -- Further actions required for construction of
3428 -- objects of type Rec2
3429 ...
3430 end record;
3431 end Constructor;
3432 @end smallexample
3433
3434 In this example the extended return statement construct is used to
3435 build in place the returned object whose components are initialized
3436 by means of a limited aggregate. Any further action associated with
3437 the constructor can be placed inside the construct.
3438
3439 @node Interfacing with C++ at the Class Level
3440 @subsection Interfacing with C++ at the Class Level
3441 @noindent
3442 In this section we demonstrate the GNAT features for interfacing with
3443 C++ by means of an example making use of Ada 2005 abstract interface
3444 types. This example consists of a classification of animals; classes
3445 have been used to model our main classification of animals, and
3446 interfaces provide support for the management of secondary
3447 classifications. We first demonstrate a case in which the types and
3448 constructors are defined on the C++ side and imported from the Ada
3449 side, and latter the reverse case.
3450
3451 The root of our derivation will be the @code{Animal} class, with a
3452 single private attribute (the @code{Age} of the animal) and two public
3453 primitives to set and get the value of this attribute.
3454
3455 @smallexample
3456 @b{class} Animal @{
3457 @b{public}:
3458 @b{virtual} void Set_Age (int New_Age);
3459 @b{virtual} int Age ();
3460 @b{private}:
3461 int Age_Count;
3462 @};
3463 @end smallexample
3464
3465 Abstract interface types are defined in C++ by means of classes with pure
3466 virtual functions and no data members. In our example we will use two
3467 interfaces that provide support for the common management of @code{Carnivore}
3468 and @code{Domestic} animals:
3469
3470 @smallexample
3471 @b{class} Carnivore @{
3472 @b{public}:
3473 @b{virtual} int Number_Of_Teeth () = 0;
3474 @};
3475
3476 @b{class} Domestic @{
3477 @b{public}:
3478 @b{virtual void} Set_Owner (char* Name) = 0;
3479 @};
3480 @end smallexample
3481
3482 Using these declarations, we can now say that a @code{Dog} is an animal that is
3483 both Carnivore and Domestic, that is:
3484
3485 @smallexample
3486 @b{class} Dog : Animal, Carnivore, Domestic @{
3487 @b{public}:
3488 @b{virtual} int Number_Of_Teeth ();
3489 @b{virtual} void Set_Owner (char* Name);
3490
3491 Dog(); // Constructor
3492 @b{private}:
3493 int Tooth_Count;
3494 char *Owner;
3495 @};
3496 @end smallexample
3497
3498 In the following examples we will assume that the previous declarations are
3499 located in a file named @code{animals.h}. The following package demonstrates
3500 how to import these C++ declarations from the Ada side:
3501
3502 @smallexample @c ada
3503 with Interfaces.C.Strings; use Interfaces.C.Strings;
3504 package Animals is
3505 type Carnivore is interface;
3506 pragma Convention (C_Plus_Plus, Carnivore);
3507 function Number_Of_Teeth (X : Carnivore)
3508 return Natural is abstract;
3509
3510 type Domestic is interface;
3511 pragma Convention (C_Plus_Plus, Set_Owner);
3512 procedure Set_Owner
3513 (X : in out Domestic;
3514 Name : Chars_Ptr) is abstract;
3515
3516 type Animal is tagged record
3517 Age : Natural := 0;
3518 end record;
3519 pragma Import (C_Plus_Plus, Animal);
3520
3521 procedure Set_Age (X : in out Animal; Age : Integer);
3522 pragma Import (C_Plus_Plus, Set_Age);
3523
3524 function Age (X : Animal) return Integer;
3525 pragma Import (C_Plus_Plus, Age);
3526
3527 type Dog is new Animal and Carnivore and Domestic with record
3528 Tooth_Count : Natural;
3529 Owner : String (1 .. 30);
3530 end record;
3531 pragma Import (C_Plus_Plus, Dog);
3532
3533 function Number_Of_Teeth (A : Dog) return Integer;
3534 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3535
3536 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3537 pragma Import (C_Plus_Plus, Set_Owner);
3538
3539 function New_Dog return Dog;
3540 pragma CPP_Constructor (New_Dog);
3541 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3542 end Animals;
3543 @end smallexample
3544
3545 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3546 interfacing with these C++ classes is easy. The only requirement is that all
3547 the primitives and components must be declared exactly in the same order in
3548 the two languages.
3549
3550 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3551 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3552 the arguments to the called primitives will be the same as for C++. For the
3553 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3554 to indicate that they have been defined on the C++ side; this is required
3555 because the dispatch table associated with these tagged types will be built
3556 in the C++ side and therefore will not contain the predefined Ada primitives
3557 which Ada would otherwise expect.
3558
3559 As the reader can see there is no need to indicate the C++ mangled names
3560 associated with each subprogram because it is assumed that all the calls to
3561 these primitives will be dispatching calls. The only exception is the
3562 constructor, which must be registered with the compiler by means of
3563 @code{pragma CPP_Constructor} and needs to provide its associated C++
3564 mangled name because the Ada compiler generates direct calls to it.
3565
3566 With the above packages we can now declare objects of type Dog on the Ada side
3567 and dispatch calls to the corresponding subprograms on the C++ side. We can
3568 also extend the tagged type Dog with further fields and primitives, and
3569 override some of its C++ primitives on the Ada side. For example, here we have
3570 a type derivation defined on the Ada side that inherits all the dispatching
3571 primitives of the ancestor from the C++ side.
3572
3573 @smallexample
3574 @b{with} Animals; @b{use} Animals;
3575 @b{package} Vaccinated_Animals @b{is}
3576 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3577 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3578 @b{end} Vaccinated_Animals;
3579 @end smallexample
3580
3581 It is important to note that, because of the ABI compatibility, the programmer
3582 does not need to add any further information to indicate either the object
3583 layout or the dispatch table entry associated with each dispatching operation.
3584
3585 Now let us define all the types and constructors on the Ada side and export
3586 them to C++, using the same hierarchy of our previous example:
3587
3588 @smallexample @c ada
3589 with Interfaces.C.Strings;
3590 use Interfaces.C.Strings;
3591 package Animals is
3592 type Carnivore is interface;
3593 pragma Convention (C_Plus_Plus, Carnivore);
3594 function Number_Of_Teeth (X : Carnivore)
3595 return Natural is abstract;
3596
3597 type Domestic is interface;
3598 pragma Convention (C_Plus_Plus, Set_Owner);
3599 procedure Set_Owner
3600 (X : in out Domestic;
3601 Name : Chars_Ptr) is abstract;
3602
3603 type Animal is tagged record
3604 Age : Natural := 0;
3605 end record;
3606 pragma Convention (C_Plus_Plus, Animal);
3607
3608 procedure Set_Age (X : in out Animal; Age : Integer);
3609 pragma Export (C_Plus_Plus, Set_Age);
3610
3611 function Age (X : Animal) return Integer;
3612 pragma Export (C_Plus_Plus, Age);
3613
3614 type Dog is new Animal and Carnivore and Domestic with record
3615 Tooth_Count : Natural;
3616 Owner : String (1 .. 30);
3617 end record;
3618 pragma Convention (C_Plus_Plus, Dog);
3619
3620 function Number_Of_Teeth (A : Dog) return Integer;
3621 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3622
3623 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3624 pragma Export (C_Plus_Plus, Set_Owner);
3625
3626 function New_Dog return Dog'Class;
3627 pragma Export (C_Plus_Plus, New_Dog);
3628 end Animals;
3629 @end smallexample
3630
3631 Compared with our previous example the only difference is the use of
3632 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3633 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3634 nothing else to be done; as explained above, the only requirement is that all
3635 the primitives and components are declared in exactly the same order.
3636
3637 For completeness, let us see a brief C++ main program that uses the
3638 declarations available in @code{animals.h} (presented in our first example) to
3639 import and use the declarations from the Ada side, properly initializing and
3640 finalizing the Ada run-time system along the way:
3641
3642 @smallexample
3643 @b{#include} "animals.h"
3644 @b{#include} <iostream>
3645 @b{using namespace} std;
3646
3647 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3648 void Check_Domestic (Domestic *obj) @{@dots{}@}
3649 void Check_Animal (Animal *obj) @{@dots{}@}
3650 void Check_Dog (Dog *obj) @{@dots{}@}
3651
3652 @b{extern} "C" @{
3653 void adainit (void);
3654 void adafinal (void);
3655 Dog* new_dog ();
3656 @}
3657
3658 void test ()
3659 @{
3660 Dog *obj = new_dog(); // Ada constructor
3661 Check_Carnivore (obj); // Check secondary DT
3662 Check_Domestic (obj); // Check secondary DT
3663 Check_Animal (obj); // Check primary DT
3664 Check_Dog (obj); // Check primary DT
3665 @}
3666
3667 int main ()
3668 @{
3669 adainit (); test(); adafinal ();
3670 return 0;
3671 @}
3672 @end smallexample
3673
3674 @node Comparison between GNAT and C/C++ Compilation Models
3675 @section Comparison between GNAT and C/C++ Compilation Models
3676
3677 @noindent
3678 The GNAT model of compilation is close to the C and C++ models. You can
3679 think of Ada specs as corresponding to header files in C. As in C, you
3680 don't need to compile specs; they are compiled when they are used. The
3681 Ada @code{with} is similar in effect to the @code{#include} of a C
3682 header.
3683
3684 One notable difference is that, in Ada, you may compile specs separately
3685 to check them for semantic and syntactic accuracy. This is not always
3686 possible with C headers because they are fragments of programs that have
3687 less specific syntactic or semantic rules.
3688
3689 The other major difference is the requirement for running the binder,
3690 which performs two important functions. First, it checks for
3691 consistency. In C or C++, the only defense against assembling
3692 inconsistent programs lies outside the compiler, in a makefile, for
3693 example. The binder satisfies the Ada requirement that it be impossible
3694 to construct an inconsistent program when the compiler is used in normal
3695 mode.
3696
3697 @cindex Elaboration order control
3698 The other important function of the binder is to deal with elaboration
3699 issues. There are also elaboration issues in C++ that are handled
3700 automatically. This automatic handling has the advantage of being
3701 simpler to use, but the C++ programmer has no control over elaboration.
3702 Where @code{gnatbind} might complain there was no valid order of
3703 elaboration, a C++ compiler would simply construct a program that
3704 malfunctioned at run time.
3705 @end ifclear
3706
3707 @node Comparison between GNAT and Conventional Ada Library Models
3708 @section Comparison between GNAT and Conventional Ada Library Models
3709
3710 @noindent
3711 This section is intended for Ada programmers who have
3712 used an Ada compiler implementing the traditional Ada library
3713 model, as described in the Ada Reference Manual.
3714
3715 @cindex GNAT library
3716 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3717 source files themselves acts as the library. Compiling Ada programs does
3718 not generate any centralized information, but rather an object file and
3719 a ALI file, which are of interest only to the binder and linker.
3720 In a traditional system, the compiler reads information not only from
3721 the source file being compiled, but also from the centralized library.
3722 This means that the effect of a compilation depends on what has been
3723 previously compiled. In particular:
3724
3725 @itemize @bullet
3726 @item
3727 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3728 to the version of the unit most recently compiled into the library.
3729
3730 @item
3731 Inlining is effective only if the necessary body has already been
3732 compiled into the library.
3733
3734 @item
3735 Compiling a unit may obsolete other units in the library.
3736 @end itemize
3737
3738 @noindent
3739 In GNAT, compiling one unit never affects the compilation of any other
3740 units because the compiler reads only source files. Only changes to source
3741 files can affect the results of a compilation. In particular:
3742
3743 @itemize @bullet
3744 @item
3745 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3746 to the source version of the unit that is currently accessible to the
3747 compiler.
3748
3749 @item
3750 @cindex Inlining
3751 Inlining requires the appropriate source files for the package or
3752 subprogram bodies to be available to the compiler. Inlining is always
3753 effective, independent of the order in which units are complied.
3754
3755 @item
3756 Compiling a unit never affects any other compilations. The editing of
3757 sources may cause previous compilations to be out of date if they
3758 depended on the source file being modified.
3759 @end itemize
3760
3761 @noindent
3762 The most important result of these differences is that order of compilation
3763 is never significant in GNAT. There is no situation in which one is
3764 required to do one compilation before another. What shows up as order of
3765 compilation requirements in the traditional Ada library becomes, in
3766 GNAT, simple source dependencies; in other words, there is only a set
3767 of rules saying what source files must be present when a file is
3768 compiled.
3769
3770 @ifset vms
3771 @node Placement of temporary files
3772 @section Placement of temporary files
3773 @cindex Temporary files (user control over placement)
3774
3775 @noindent
3776 GNAT creates temporary files in the directory designated by the environment
3777 variable @env{TMPDIR}.
3778 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3779 for detailed information on how environment variables are resolved.
3780 For most users the easiest way to make use of this feature is to simply
3781 define @env{TMPDIR} as a job level logical name).
3782 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3783 for compiler temporary files, then you can include something like the
3784 following command in your @file{LOGIN.COM} file:
3785
3786 @smallexample
3787 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3788 @end smallexample
3789
3790 @noindent
3791 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3792 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3793 designated by @env{TEMP}.
3794 If none of these environment variables are defined then GNAT uses the
3795 directory designated by the logical name @code{SYS$SCRATCH:}
3796 (by default the user's home directory). If all else fails
3797 GNAT uses the current directory for temporary files.
3798 @end ifset
3799
3800 @c *************************
3801 @node Compiling Using gcc
3802 @chapter Compiling Using @command{gcc}
3803
3804 @noindent
3805 This chapter discusses how to compile Ada programs using the @command{gcc}
3806 command. It also describes the set of switches
3807 that can be used to control the behavior of the compiler.
3808 @menu
3809 * Compiling Programs::
3810 * Switches for gcc::
3811 * Search Paths and the Run-Time Library (RTL)::
3812 * Order of Compilation Issues::
3813 * Examples::
3814 @end menu
3815
3816 @node Compiling Programs
3817 @section Compiling Programs
3818
3819 @noindent
3820 The first step in creating an executable program is to compile the units
3821 of the program using the @command{gcc} command. You must compile the
3822 following files:
3823
3824 @itemize @bullet
3825 @item
3826 the body file (@file{.adb}) for a library level subprogram or generic
3827 subprogram
3828
3829 @item
3830 the spec file (@file{.ads}) for a library level package or generic
3831 package that has no body
3832
3833 @item
3834 the body file (@file{.adb}) for a library level package
3835 or generic package that has a body
3836
3837 @end itemize
3838
3839 @noindent
3840 You need @emph{not} compile the following files
3841
3842 @itemize @bullet
3843
3844 @item
3845 the spec of a library unit which has a body
3846
3847 @item
3848 subunits
3849 @end itemize
3850
3851 @noindent
3852 because they are compiled as part of compiling related units. GNAT
3853 package specs
3854 when the corresponding body is compiled, and subunits when the parent is
3855 compiled.
3856
3857 @cindex cannot generate code
3858 If you attempt to compile any of these files, you will get one of the
3859 following error messages (where @var{fff} is the name of the file you
3860 compiled):
3861
3862 @smallexample
3863 cannot generate code for file @var{fff} (package spec)
3864 to check package spec, use -gnatc
3865
3866 cannot generate code for file @var{fff} (missing subunits)
3867 to check parent unit, use -gnatc
3868
3869 cannot generate code for file @var{fff} (subprogram spec)
3870 to check subprogram spec, use -gnatc
3871
3872 cannot generate code for file @var{fff} (subunit)
3873 to check subunit, use -gnatc
3874 @end smallexample
3875
3876 @noindent
3877 As indicated by the above error messages, if you want to submit
3878 one of these files to the compiler to check for correct semantics
3879 without generating code, then use the @option{-gnatc} switch.
3880
3881 The basic command for compiling a file containing an Ada unit is
3882
3883 @smallexample
3884 @c $ gcc -c @ovar{switches} @file{file name}
3885 @c Expanding @ovar macro inline (explanation in macro def comments)
3886 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3887 @end smallexample
3888
3889 @noindent
3890 where @var{file name} is the name of the Ada file (usually
3891 having an extension
3892 @file{.ads} for a spec or @file{.adb} for a body).
3893 @ifclear vms
3894 You specify the
3895 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3896 @end ifclear
3897 The result of a successful compilation is an object file, which has the
3898 same name as the source file but an extension of @file{.o} and an Ada
3899 Library Information (ALI) file, which also has the same name as the
3900 source file, but with @file{.ali} as the extension. GNAT creates these
3901 two output files in the current directory, but you may specify a source
3902 file in any directory using an absolute or relative path specification
3903 containing the directory information.
3904
3905 @findex gnat1
3906 @command{gcc} is actually a driver program that looks at the extensions of
3907 the file arguments and loads the appropriate compiler. For example, the
3908 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3909 These programs are in directories known to the driver program (in some
3910 configurations via environment variables you set), but need not be in
3911 your path. The @command{gcc} driver also calls the assembler and any other
3912 utilities needed to complete the generation of the required object
3913 files.
3914
3915 It is possible to supply several file names on the same @command{gcc}
3916 command. This causes @command{gcc} to call the appropriate compiler for
3917 each file. For example, the following command lists two separate
3918 files to be compiled:
3919
3920 @smallexample
3921 $ gcc -c x.adb y.adb
3922 @end smallexample
3923
3924 @noindent
3925 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3926 @file{y.adb}.
3927 The compiler generates two object files @file{x.o} and @file{y.o}
3928 and the two ALI files @file{x.ali} and @file{y.ali}.
3929 Any switches apply to all the files ^listed,^listed.^
3930
3931 @node Switches for gcc
3932 @section Switches for @command{gcc}
3933
3934 @noindent
3935 The @command{gcc} command accepts switches that control the
3936 compilation process. These switches are fully described in this section.
3937 First we briefly list all the switches, in alphabetical order, then we
3938 describe the switches in more detail in functionally grouped sections.
3939
3940 More switches exist for GCC than those documented here, especially
3941 for specific targets. However, their use is not recommended as
3942 they may change code generation in ways that are incompatible with
3943 the Ada run-time library, or can cause inconsistencies between
3944 compilation units.
3945
3946 @menu
3947 * Output and Error Message Control::
3948 * Warning Message Control::
3949 * Debugging and Assertion Control::
3950 * Validity Checking::
3951 * Style Checking::
3952 * Run-Time Checks::
3953 * Using gcc for Syntax Checking::
3954 * Using gcc for Semantic Checking::
3955 * Compiling Different Versions of Ada::
3956 * Character Set Control::
3957 * File Naming Control::
3958 * Subprogram Inlining Control::
3959 * Auxiliary Output Control::
3960 * Debugging Control::
3961 * Exception Handling Control::
3962 * Units to Sources Mapping Files::
3963 * Integrated Preprocessing::
3964 * Code Generation Control::
3965 @ifset vms
3966 * Return Codes::
3967 @end ifset
3968 @end menu
3969
3970 @table @option
3971 @c !sort!
3972 @ifclear vms
3973 @cindex @option{-b} (@command{gcc})
3974 @item -b @var{target}
3975 Compile your program to run on @var{target}, which is the name of a
3976 system configuration. You must have a GNAT cross-compiler built if
3977 @var{target} is not the same as your host system.
3978
3979 @item -B@var{dir}
3980 @cindex @option{-B} (@command{gcc})
3981 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3982 from @var{dir} instead of the default location. Only use this switch
3983 when multiple versions of the GNAT compiler are available.
3984 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3985 GNU Compiler Collection (GCC)}, for further details. You would normally
3986 use the @option{-b} or @option{-V} switch instead.
3987
3988 @item -c
3989 @cindex @option{-c} (@command{gcc})
3990 Compile. Always use this switch when compiling Ada programs.
3991
3992 Note: for some other languages when using @command{gcc}, notably in
3993 the case of C and C++, it is possible to use
3994 use @command{gcc} without a @option{-c} switch to
3995 compile and link in one step. In the case of GNAT, you
3996 cannot use this approach, because the binder must be run
3997 and @command{gcc} cannot be used to run the GNAT binder.
3998 @end ifclear
3999
4000 @item -fcallgraph-info@r{[}=su,da@r{]}
4001 @cindex @option{-fcallgraph-info} (@command{gcc})
4002 Makes the compiler output callgraph information for the program, on a
4003 per-file basis. The information is generated in the VCG format. It can
4004 be decorated with additional, per-node and/or per-edge information, if a
4005 list of comma-separated markers is additionally specified. When the
4006 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
4007 marker is specified, the callgraph is decorated with information about
4008 dynamically allocated objects.
4009
4010 @item -fdump-scos
4011 @cindex @option{-fdump-scos} (@command{gcc})
4012 Generates SCO (Source Coverage Obligation) information in the ALI file.
4013 This information is used by advanced coverage tools. See unit @file{SCOs}
4014 in the compiler sources for details in files @file{scos.ads} and
4015 @file{scos.adb}.
4016
4017 @item -flto@r{[}=n@r{]}
4018 @cindex @option{-flto} (@command{gcc})
4019 Enables Link Time Optimization. This switch must be used in conjunction
4020 with the traditional @option{-Ox} switches and instructs the compiler to
4021 defer most optimizations until the link stage. The advantage of this
4022 approach is that the compiler can do a whole-program analysis and choose
4023 the best interprocedural optimization strategy based on a complete view
4024 of the program, instead of a fragmentary view with the usual approach.
4025 This can also speed up the compilation of huge programs and reduce the
4026 size of the final executable, compared with a per-unit compilation with
4027 full inlining across modules enabled with the @option{-gnatn2} switch.
4028 The drawback of this approach is that it may require much more memory.
4029 The switch, as well as the accompanying @option{-Ox} switches, must be
4030 specified both for the compilation and the link phases.
4031 If the @var{n} parameter is specified, the optimization and final code
4032 generation at link time are executed using @var{n} parallel jobs by
4033 means of an installed @command{make} program.
4034
4035 @item -fno-inline
4036 @cindex @option{-fno-inline} (@command{gcc})
4037 Suppresses all inlining, even if other optimization or inlining
4038 switches are set. This includes suppression of inlining that
4039 results from the use of the pragma @code{Inline_Always}.
4040 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4041 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4042 effects if this switch is present. Note that inlining can also
4043 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
4044
4045 @item -fno-inline-functions
4046 @cindex @option{-fno-inline-functions} (@command{gcc})
4047 Suppresses automatic inlining of subprograms, which is enabled
4048 if @option{-O3} is used.
4049
4050 @item -fno-inline-small-functions
4051 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4052 Suppresses automatic inlining of small subprograms, which is enabled
4053 if @option{-O2} is used.
4054
4055 @item -fno-inline-functions-called-once
4056 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4057 Suppresses inlining of subprograms local to the unit and called once
4058 from within it, which is enabled if @option{-O1} is used.
4059
4060 @item -fno-ivopts
4061 @cindex @option{-fno-ivopts} (@command{gcc})
4062 Suppresses high-level loop induction variable optimizations, which are
4063 enabled if @option{-O1} is used. These optimizations are generally
4064 profitable but, for some specific cases of loops with numerous uses
4065 of the iteration variable that follow a common pattern, they may end
4066 up destroying the regularity that could be exploited at a lower level
4067 and thus producing inferior code.
4068
4069 @item -fno-strict-aliasing
4070 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4071 Causes the compiler to avoid assumptions regarding non-aliasing
4072 of objects of different types. See
4073 @ref{Optimization and Strict Aliasing} for details.
4074
4075 @item -fstack-check
4076 @cindex @option{-fstack-check} (@command{gcc})
4077 Activates stack checking.
4078 See @ref{Stack Overflow Checking} for details.
4079
4080 @item -fstack-usage
4081 @cindex @option{-fstack-usage} (@command{gcc})
4082 Makes the compiler output stack usage information for the program, on a
4083 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4084
4085 @item ^-g^/DEBUG^
4086 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4087 Generate debugging information. This information is stored in the object
4088 file and copied from there to the final executable file by the linker,
4089 where it can be read by the debugger. You must use the
4090 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4091
4092 @item -gnat83
4093 @cindex @option{-gnat83} (@command{gcc})
4094 Enforce Ada 83 restrictions.
4095
4096 @item -gnat95
4097 @cindex @option{-gnat95} (@command{gcc})
4098 Enforce Ada 95 restrictions.
4099
4100 @item -gnat05
4101 @cindex @option{-gnat05} (@command{gcc})
4102 Allow full Ada 2005 features.
4103
4104 @item -gnat2005
4105 @cindex @option{-gnat2005} (@command{gcc})
4106 Allow full Ada 2005 features (same as @option{-gnat05})
4107
4108 @item -gnat12
4109 @cindex @option{-gnat12} (@command{gcc})
4110
4111 @item -gnat2012
4112 @cindex @option{-gnat2012} (@command{gcc})
4113 Allow full Ada 2012 features (same as @option{-gnat12})
4114
4115 @item -gnata
4116 @cindex @option{-gnata} (@command{gcc})
4117 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4118 activated. Note that these pragmas can also be controlled using the
4119 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4120 It also activates pragmas @code{Check}, @code{Precondition}, and
4121 @code{Postcondition}. Note that these pragmas can also be controlled
4122 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
4123 also activates all assertions defined in the RM as aspects: preconditions,
4124 postconditions, type invariants and (sub)type predicates. In all Ada modes,
4125 corresponding pragmas for type invariants and (sub)type predicates are
4126 also activated.
4127
4128 @item -gnatA
4129 @cindex @option{-gnatA} (@command{gcc})
4130 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4131 it will be ignored.
4132
4133 @item -gnatb
4134 @cindex @option{-gnatb} (@command{gcc})
4135 Generate brief messages to @file{stderr} even if verbose mode set.
4136
4137 @item -gnatB
4138 @cindex @option{-gnatB} (@command{gcc})
4139 Assume no invalid (bad) values except for 'Valid attribute use
4140 (@pxref{Validity Checking}).
4141
4142 @item -gnatc
4143 @cindex @option{-gnatc} (@command{gcc})
4144 Check syntax and semantics only (no code generation attempted). When the
4145 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
4146 only given to the compiler (after @option{-cargs} or in package Compiler of
4147 the project file, @command{gnatmake} will fail because it will not find the
4148 object file after compilation. If @command{gnatmake} is called with
4149 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
4150 Builder of the project file) then @command{gnatmake} will not fail because
4151 it will not look for the object files after compilation, and it will not try
4152 to build and link.
4153
4154 @item -gnatC
4155 @cindex @option{-gnatC} (@command{gcc})
4156 Generate CodePeer information (no code generation attempted).
4157 This switch will generate an intermediate representation suitable for
4158 use by CodePeer (@file{.scil} files). This switch is not compatible with
4159 code generation (it will, among other things, disable some switches such
4160 as -gnatn, and enable others such as -gnata).
4161
4162 @item -gnatd
4163 @cindex @option{-gnatd} (@command{gcc})
4164 Specify debug options for the compiler. The string of characters after
4165 the @option{-gnatd} specify the specific debug options. The possible
4166 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4167 compiler source file @file{debug.adb} for details of the implemented
4168 debug options. Certain debug options are relevant to applications
4169 programmers, and these are documented at appropriate points in this
4170 users guide.
4171
4172 @ifclear vms
4173 @item -gnatD
4174 @cindex @option{-gnatD[nn]} (@command{gcc})
4175 @end ifclear
4176 @ifset vms
4177 @item /XDEBUG /LXDEBUG=nnn
4178 @end ifset
4179 Create expanded source files for source level debugging. This switch
4180 also suppress generation of cross-reference information
4181 (see @option{-gnatx}).
4182
4183 @item ^-gnateA^/ALIASING_CHECK^
4184 @cindex @option{-gnateA} (@command{gcc})
4185 Check that there is no aliasing between two parameters of the same subprogram.
4186
4187 @item -gnatec=@var{path}
4188 @cindex @option{-gnatec} (@command{gcc})
4189 Specify a configuration pragma file
4190 @ifclear vms
4191 (the equal sign is optional)
4192 @end ifclear
4193 (@pxref{The Configuration Pragmas Files}).
4194
4195 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
4196 @cindex @option{-gnated} (@command{gcc})
4197 Disable atomic synchronization
4198
4199 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4200 @cindex @option{-gnateD} (@command{gcc})
4201 Defines a symbol, associated with @var{value}, for preprocessing.
4202 (@pxref{Integrated Preprocessing}).
4203
4204 @item -gnateE
4205 @cindex @option{-gnateE} (@command{gcc})
4206 Generate extra information in exception messages. In particular, display
4207 extra column information and the value and range associated with index and
4208 range check failures, and extra column information for access checks.
4209 In cases where the compiler is able to determine at compile time that
4210 a check will fail, it gives a warning, and the extra information is not
4211 produced at run time.
4212
4213 @item -gnatef
4214 @cindex @option{-gnatef} (@command{gcc})
4215 Display full source path name in brief error messages.
4216
4217 @item -gnateF
4218 @cindex @option{-gnateF} (@command{gcc})
4219 Check for overflow on all floating-point operations, including those
4220 for unconstrained predefined types. See description of pragma
4221 @code{Check_Float_Overflow} in GNAT RM.
4222
4223 @item -gnateG
4224 @cindex @option{-gnateG} (@command{gcc})
4225 Save result of preprocessing in a text file.
4226
4227 @item -gnatei@var{nnn}
4228 @cindex @option{-gnatei} (@command{gcc})
4229 Set maximum number of instantiations during compilation of a single unit to
4230 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
4231 the rare case when a single unit legitimately exceeds this limit.
4232
4233 @item -gnateI@var{nnn}
4234 @cindex @option{-gnateI} (@command{gcc})
4235 Indicates that the source is a multi-unit source and that the index of the
4236 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4237 to be a valid index in the multi-unit source.
4238
4239 @item -gnatem=@var{path}
4240 @cindex @option{-gnatem} (@command{gcc})
4241 Specify a mapping file
4242 @ifclear vms
4243 (the equal sign is optional)
4244 @end ifclear
4245 (@pxref{Units to Sources Mapping Files}).
4246
4247 @item -gnatep=@var{file}
4248 @cindex @option{-gnatep} (@command{gcc})
4249 Specify a preprocessing data file
4250 @ifclear vms
4251 (the equal sign is optional)
4252 @end ifclear
4253 (@pxref{Integrated Preprocessing}).
4254
4255 @item -gnateP
4256 @cindex @option{-gnateP} (@command{gcc})
4257 Turn categorization dependency errors into warnings.
4258 Ada requires that units that WITH one another have compatible categories, for
4259 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4260 these errors become warnings (which can be ignored, or suppressed in the usual
4261 manner). This can be useful in some specialized circumstances such as the
4262 temporary use of special test software.
4263
4264 @item -gnateS
4265 @cindex @option{-gnateS} (@command{gcc})
4266 Synonym of @option{-fdump-scos}, kept for backards compatibility.
4267
4268 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
4269 @cindex @option{-gnatet} (@command{gcc})
4270 Generate target dependent information.
4271
4272 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4273 @cindex @option{-gnateV} (@command{gcc})
4274 Check validity of subprogram parameters.
4275
4276 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4277 @cindex @option{-gnateY} (@command{gcc})
4278 Ignore all STYLE_CHECKS pragmas. Full legality checks
4279 are still carried out, but the pragmas have no effect
4280 on what style checks are active. This allows all style
4281 checking options to be controlled from the command line.
4282
4283 @item -gnatE
4284 @cindex @option{-gnatE} (@command{gcc})
4285 Full dynamic elaboration checks.
4286
4287 @item -gnatf
4288 @cindex @option{-gnatf} (@command{gcc})
4289 Full errors. Multiple errors per line, all undefined references, do not
4290 attempt to suppress cascaded errors.
4291
4292 @item -gnatF
4293 @cindex @option{-gnatF} (@command{gcc})
4294 Externals names are folded to all uppercase.
4295
4296 @item ^-gnatg^/GNAT_INTERNAL^
4297 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4298 Internal GNAT implementation mode. This should not be used for
4299 applications programs, it is intended only for use by the compiler
4300 and its run-time library. For documentation, see the GNAT sources.
4301 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4302 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4303 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4304 so that all standard warnings and all standard style options are turned on.
4305 All warnings and style messages are treated as errors.
4306
4307 @ifclear vms
4308 @item -gnatG=nn
4309 @cindex @option{-gnatG[nn]} (@command{gcc})
4310 @end ifclear
4311 @ifset vms
4312 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4313 @end ifset
4314 List generated expanded code in source form.
4315
4316 @item ^-gnath^/HELP^
4317 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4318 Output usage information. The output is written to @file{stdout}.
4319
4320 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4321 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4322 Identifier character set
4323 @ifclear vms
4324 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4325 @end ifclear
4326 For details of the possible selections for @var{c},
4327 see @ref{Character Set Control}.
4328
4329 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4330 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4331 Ignore representation clauses. When this switch is used,
4332 representation clauses are treated as comments. This is useful
4333 when initially porting code where you want to ignore rep clause
4334 problems, and also for compiling foreign code (particularly
4335 for use with ASIS). The representation clauses that are ignored
4336 are: enumeration_representation_clause, record_representation_clause,
4337 and attribute_definition_clause for the following attributes:
4338 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4339 Object_Size, Size, Small, Stream_Size, and Value_Size.
4340 Note that this option should be used only for compiling -- the
4341 code is likely to malfunction at run time.
4342
4343 @item -gnatjnn
4344 @cindex @option{-gnatjnn} (@command{gcc})
4345 Reformat error messages to fit on nn character lines
4346
4347 @item -gnatk=@var{n}
4348 @cindex @option{-gnatk} (@command{gcc})
4349 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4350
4351 @item -gnatl
4352 @cindex @option{-gnatl} (@command{gcc})
4353 Output full source listing with embedded error messages.
4354
4355 @item -gnatL
4356 @cindex @option{-gnatL} (@command{gcc})
4357 Used in conjunction with -gnatG or -gnatD to intersperse original
4358 source lines (as comment lines with line numbers) in the expanded
4359 source output.
4360
4361 @item -gnatm=@var{n}
4362 @cindex @option{-gnatm} (@command{gcc})
4363 Limit number of detected error or warning messages to @var{n}
4364 where @var{n} is in the range 1..999999. The default setting if
4365 no switch is given is 9999. If the number of warnings reaches this
4366 limit, then a message is output and further warnings are suppressed,
4367 but the compilation is continued. If the number of error messages
4368 reaches this limit, then a message is output and the compilation
4369 is abandoned. The equal sign here is optional. A value of zero
4370 means that no limit applies.
4371
4372 @item -gnatn[12]
4373 @cindex @option{-gnatn} (@command{gcc})
4374 Activate inlining for subprograms for which pragma @code{Inline} is
4375 specified. This inlining is performed by the GCC back-end. An optional
4376 digit sets the inlining level: 1 for moderate inlining across modules
4377 or 2 for full inlining across modules. If no inlining level is specified,
4378 the compiler will pick it based on the optimization level.
4379
4380 @item -gnatN
4381 @cindex @option{-gnatN} (@command{gcc})
4382 Activate front end inlining for subprograms for which
4383 pragma @code{Inline} is specified. This inlining is performed
4384 by the front end and will be visible in the
4385 @option{-gnatG} output.
4386
4387 When using a gcc-based back end (in practice this means using any version
4388 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4389 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4390 Historically front end inlining was more extensive than the gcc back end
4391 inlining, but that is no longer the case.
4392
4393 @item -gnato??
4394 @cindex @option{-gnato??} (@command{gcc})
4395 Set default mode for handling generation of code to avoid intermediate
4396 arithmetic overflow. Here `@code{??}' is two digits, a
4397 single digit, or nothing. Each digit is one of the digits `@code{1}'
4398 through `@code{3}':
4399
4400 @itemize @bullet
4401 @item @code{1}:
4402 all intermediate overflows checked against base type (@code{STRICT})
4403 @item @code{2}:
4404 minimize intermediate overflows (@code{MINIMIZED})
4405 @item @code{3}:
4406 eliminate intermediate overflows (@code{ELIMINATED})
4407 @end itemize
4408
4409 If only one digit appears then it applies to all
4410 cases; if two digits are given, then the first applies outside
4411 assertions, and the second within assertions.
4412
4413 If no digits follow the @option{-gnato}, then it is equivalent to
4414 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4415 causing all intermediate overflows to be handled in strict mode.
4416
4417 This switch also causes arithmetic overflow checking to be performed
4418 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4419
4420 The default if no option @option{-gnato} is given is that overflow handling
4421 is in @code{STRICT} mode (computations done using the base type), and that
4422 overflow checking is suppressed.
4423
4424 Note that division by zero is a separate check that is not
4425 controlled by this switch (division by zero checking is on by default).
4426
4427 See also @ref{Specifying the Desired Mode}.
4428
4429 @item -gnatp
4430 @cindex @option{-gnatp} (@command{gcc})
4431 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4432 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4433
4434 @item -gnat-p
4435 @cindex @option{-gnat-p} (@command{gcc})
4436 Cancel effect of previous @option{-gnatp} switch.
4437
4438 @item -gnatP
4439 @cindex @option{-gnatP} (@command{gcc})
4440 Enable polling. This is required on some systems (notably Windows NT) to
4441 obtain asynchronous abort and asynchronous transfer of control capability.
4442 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4443 details.
4444
4445 @item -gnatq
4446 @cindex @option{-gnatq} (@command{gcc})
4447 Don't quit. Try semantics, even if parse errors.
4448
4449 @item -gnatQ
4450 @cindex @option{-gnatQ} (@command{gcc})
4451 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4452
4453 @item -gnatr
4454 @cindex @option{-gnatr} (@command{gcc})
4455 Treat pragma Restrictions as Restriction_Warnings.
4456
4457 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4458 @cindex @option{-gnatR} (@command{gcc})
4459 Output representation information for declared types and objects.
4460
4461 @item -gnats
4462 @cindex @option{-gnats} (@command{gcc})
4463 Syntax check only.
4464
4465 @item -gnatS
4466 @cindex @option{-gnatS} (@command{gcc})
4467 Print package Standard.
4468
4469 @item -gnatt
4470 @cindex @option{-gnatt} (@command{gcc})
4471 Generate tree output file.
4472
4473 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4474 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4475 All compiler tables start at @var{nnn} times usual starting size.
4476
4477 @item -gnatu
4478 @cindex @option{-gnatu} (@command{gcc})
4479 List units for this compilation.
4480
4481 @item -gnatU
4482 @cindex @option{-gnatU} (@command{gcc})
4483 Tag all error messages with the unique string ``error:''
4484
4485 @item -gnatv
4486 @cindex @option{-gnatv} (@command{gcc})
4487 Verbose mode. Full error output with source lines to @file{stdout}.
4488
4489 @item -gnatV
4490 @cindex @option{-gnatV} (@command{gcc})
4491 Control level of validity checking (@pxref{Validity Checking}).
4492
4493 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4494 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4495 Warning mode where
4496 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4497 the exact warnings that
4498 are enabled or disabled (@pxref{Warning Message Control}).
4499
4500 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4501 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4502 Wide character encoding method
4503 @ifclear vms
4504 (@var{e}=n/h/u/s/e/8).
4505 @end ifclear
4506 @ifset vms
4507 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4508 @end ifset
4509
4510 @item -gnatx
4511 @cindex @option{-gnatx} (@command{gcc})
4512 Suppress generation of cross-reference information.
4513
4514 @item -gnatX
4515 @cindex @option{-gnatX} (@command{gcc})
4516 Enable GNAT implementation extensions and latest Ada version.
4517
4518 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4519 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4520 Enable built-in style checks (@pxref{Style Checking}).
4521
4522 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4523 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4524 Distribution stub generation and compilation
4525 @ifclear vms
4526 (@var{m}=r/c for receiver/caller stubs).
4527 @end ifclear
4528 @ifset vms
4529 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4530 to be generated and compiled).
4531 @end ifset
4532
4533 @item ^-I^/SEARCH=^@var{dir}
4534 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4535 @cindex RTL
4536 Direct GNAT to search the @var{dir} directory for source files needed by
4537 the current compilation
4538 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4539
4540 @item ^-I-^/NOCURRENT_DIRECTORY^
4541 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4542 @cindex RTL
4543 Except for the source file named in the command line, do not look for source
4544 files in the directory containing the source file named in the command line
4545 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4546
4547 @ifclear vms
4548 @item -mbig-switch
4549 @cindex @option{-mbig-switch} (@command{gcc})
4550 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4551 This standard gcc switch causes the compiler to use larger offsets in its
4552 jump table representation for @code{case} statements.
4553 This may result in less efficient code, but is sometimes necessary
4554 (for example on HP-UX targets)
4555 @cindex HP-UX and @option{-mbig-switch} option
4556 in order to compile large and/or nested @code{case} statements.
4557
4558 @item -o @var{file}
4559 @cindex @option{-o} (@command{gcc})
4560 This switch is used in @command{gcc} to redirect the generated object file
4561 and its associated ALI file. Beware of this switch with GNAT, because it may
4562 cause the object file and ALI file to have different names which in turn
4563 may confuse the binder and the linker.
4564 @end ifclear
4565
4566 @item -nostdinc
4567 @cindex @option{-nostdinc} (@command{gcc})
4568 Inhibit the search of the default location for the GNAT Run Time
4569 Library (RTL) source files.
4570
4571 @item -nostdlib
4572 @cindex @option{-nostdlib} (@command{gcc})
4573 Inhibit the search of the default location for the GNAT Run Time
4574 Library (RTL) ALI files.
4575
4576 @ifclear vms
4577 @c @item -O@ovar{n}
4578 @c Expanding @ovar macro inline (explanation in macro def comments)
4579 @item -O@r{[}@var{n}@r{]}
4580 @cindex @option{-O} (@command{gcc})
4581 @var{n} controls the optimization level.
4582
4583 @table @asis
4584 @item n = 0
4585 No optimization, the default setting if no @option{-O} appears
4586
4587 @item n = 1
4588 Normal optimization, the default if you specify @option{-O} without
4589 an operand. A good compromise between code quality and compilation
4590 time.
4591
4592 @item n = 2
4593 Extensive optimization, may improve execution time, possibly at the cost of
4594 substantially increased compilation time.
4595
4596 @item n = 3
4597 Same as @option{-O2}, and also includes inline expansion for small subprograms
4598 in the same unit.
4599
4600 @item n = s
4601 Optimize space usage
4602 @end table
4603
4604 @noindent
4605 See also @ref{Optimization Levels}.
4606 @end ifclear
4607
4608 @ifset vms
4609 @item /NOOPTIMIZE
4610 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4611 Equivalent to @option{/OPTIMIZE=NONE}.
4612 This is the default behavior in the absence of an @option{/OPTIMIZE}
4613 qualifier.
4614
4615 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4616 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4617 Selects the level of optimization for your program. The supported
4618 keywords are as follows:
4619 @table @code
4620 @item ALL
4621 Perform most optimizations, including those that
4622 are expensive.
4623 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4624 without keyword options.
4625
4626 @item NONE
4627 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4628
4629 @item SOME
4630 Perform some optimizations, but omit ones that are costly.
4631
4632 @item DEVELOPMENT
4633 Same as @code{SOME}.
4634
4635 @item INLINING
4636 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4637 automatic inlining of small subprograms within a unit
4638
4639 @item UNROLL_LOOPS
4640 Try to unroll loops. This keyword may be specified together with
4641 any keyword above other than @code{NONE}. Loop unrolling
4642 usually, but not always, improves the performance of programs.
4643
4644 @item SPACE
4645 Optimize space usage
4646 @end table
4647
4648 @noindent
4649 See also @ref{Optimization Levels}.
4650 @end ifset
4651
4652 @ifclear vms
4653 @item -pass-exit-codes
4654 @cindex @option{-pass-exit-codes} (@command{gcc})
4655 Catch exit codes from the compiler and use the most meaningful as
4656 exit status.
4657 @end ifclear
4658
4659 @item --RTS=@var{rts-path}
4660 @cindex @option{--RTS} (@command{gcc})
4661 Specifies the default location of the runtime library. Same meaning as the
4662 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4663
4664 @item ^-S^/ASM^
4665 @cindex @option{^-S^/ASM^} (@command{gcc})
4666 ^Used in place of @option{-c} to^Used to^
4667 cause the assembler source file to be
4668 generated, using @file{^.s^.S^} as the extension,
4669 instead of the object file.
4670 This may be useful if you need to examine the generated assembly code.
4671
4672 @item ^-fverbose-asm^/VERBOSE_ASM^
4673 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4674 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4675 to cause the generated assembly code file to be annotated with variable
4676 names, making it significantly easier to follow.
4677
4678 @item ^-v^/VERBOSE^
4679 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4680 Show commands generated by the @command{gcc} driver. Normally used only for
4681 debugging purposes or if you need to be sure what version of the
4682 compiler you are executing.
4683
4684 @ifclear vms
4685 @item -V @var{ver}
4686 @cindex @option{-V} (@command{gcc})
4687 Execute @var{ver} version of the compiler. This is the @command{gcc}
4688 version, not the GNAT version.
4689 @end ifclear
4690
4691 @item ^-w^/NO_BACK_END_WARNINGS^
4692 @cindex @option{-w} (@command{gcc})
4693 Turn off warnings generated by the back end of the compiler. Use of
4694 this switch also causes the default for front end warnings to be set
4695 to suppress (as though @option{-gnatws} had appeared at the start of
4696 the options).
4697
4698 @end table
4699
4700 @ifclear vms
4701 @c Combining qualifiers does not work on VMS
4702 You may combine a sequence of GNAT switches into a single switch. For
4703 example, the combined switch
4704
4705 @cindex Combining GNAT switches
4706 @smallexample
4707 -gnatofi3
4708 @end smallexample
4709
4710 @noindent
4711 is equivalent to specifying the following sequence of switches:
4712
4713 @smallexample
4714 -gnato -gnatf -gnati3
4715 @end smallexample
4716 @end ifclear
4717
4718 @noindent
4719 The following restrictions apply to the combination of switches
4720 in this manner:
4721
4722 @itemize @bullet
4723 @item
4724 The switch @option{-gnatc} if combined with other switches must come
4725 first in the string.
4726
4727 @item
4728 The switch @option{-gnats} if combined with other switches must come
4729 first in the string.
4730
4731 @item
4732 The switches
4733 ^^@option{/DISTRIBUTION_STUBS=},^
4734 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4735 switches, and only one of them may appear in the command line.
4736
4737 @item
4738 The switch @option{-gnat-p} may not be combined with any other switch.
4739
4740 @ifclear vms
4741 @item
4742 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4743 switch), then all further characters in the switch are interpreted
4744 as style modifiers (see description of @option{-gnaty}).
4745
4746 @item
4747 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4748 switch), then all further characters in the switch are interpreted
4749 as debug flags (see description of @option{-gnatd}).
4750
4751 @item
4752 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4753 switch), then all further characters in the switch are interpreted
4754 as warning mode modifiers (see description of @option{-gnatw}).
4755
4756 @item
4757 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4758 switch), then all further characters in the switch are interpreted
4759 as validity checking options (@pxref{Validity Checking}).
4760
4761 @item
4762 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4763 a combined list of options.
4764 @end ifclear
4765 @end itemize
4766
4767 @node Output and Error Message Control
4768 @subsection Output and Error Message Control
4769 @findex stderr
4770
4771 @noindent
4772 The standard default format for error messages is called ``brief format''.
4773 Brief format messages are written to @file{stderr} (the standard error
4774 file) and have the following form:
4775
4776 @smallexample
4777 e.adb:3:04: Incorrect spelling of keyword "function"
4778 e.adb:4:20: ";" should be "is"
4779 @end smallexample
4780
4781 @noindent
4782 The first integer after the file name is the line number in the file,
4783 and the second integer is the column number within the line.
4784 @ifclear vms
4785 @code{GPS} can parse the error messages
4786 and point to the referenced character.
4787 @end ifclear
4788 The following switches provide control over the error message
4789 format:
4790
4791 @table @option
4792 @c !sort!
4793 @item -gnatv
4794 @cindex @option{-gnatv} (@command{gcc})
4795 @findex stdout
4796 @ifclear vms
4797 The v stands for verbose.
4798 @end ifclear
4799 The effect of this setting is to write long-format error
4800 messages to @file{stdout} (the standard output file.
4801 The same program compiled with the
4802 @option{-gnatv} switch would generate:
4803
4804 @smallexample
4805 @cartouche
4806 3. funcion X (Q : Integer)
4807 |
4808 >>> Incorrect spelling of keyword "function"
4809 4. return Integer;
4810 |
4811 >>> ";" should be "is"
4812 @end cartouche
4813 @end smallexample
4814
4815 @noindent
4816 The vertical bar indicates the location of the error, and the @samp{>>>}
4817 prefix can be used to search for error messages. When this switch is
4818 used the only source lines output are those with errors.
4819
4820 @item -gnatl
4821 @cindex @option{-gnatl} (@command{gcc})
4822 @ifclear vms
4823 The @code{l} stands for list.
4824 @end ifclear
4825 This switch causes a full listing of
4826 the file to be generated. In the case where a body is
4827 compiled, the corresponding spec is also listed, along
4828 with any subunits. Typical output from compiling a package
4829 body @file{p.adb} might look like:
4830
4831 @smallexample @c ada
4832 @cartouche
4833 Compiling: p.adb
4834
4835 1. package body p is
4836 2. procedure a;
4837 3. procedure a is separate;
4838 4. begin
4839 5. null
4840 |
4841 >>> missing ";"
4842
4843 6. end;
4844
4845 Compiling: p.ads
4846
4847 1. package p is
4848 2. pragma Elaborate_Body
4849 |
4850 >>> missing ";"
4851
4852 3. end p;
4853
4854 Compiling: p-a.adb
4855
4856 1. separate p
4857 |
4858 >>> missing "("
4859
4860 2. procedure a is
4861 3. begin
4862 4. null
4863 |
4864 >>> missing ";"
4865
4866 5. end;
4867 @end cartouche
4868 @end smallexample
4869
4870 @noindent
4871 @findex stderr
4872 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4873 standard output is redirected, a brief summary is written to
4874 @file{stderr} (standard error) giving the number of error messages and
4875 warning messages generated.
4876
4877 @item ^-gnatl^/OUTPUT_FILE^=file
4878 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4879 This has the same effect as @option{-gnatl} except that the output is
4880 written to a file instead of to standard output. If the given name
4881 @file{fname} does not start with a period, then it is the full name
4882 of the file to be written. If @file{fname} is an extension, it is
4883 appended to the name of the file being compiled. For example, if
4884 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4885 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4886
4887 @item -gnatU
4888 @cindex @option{-gnatU} (@command{gcc})
4889 This switch forces all error messages to be preceded by the unique
4890 string ``error:''. This means that error messages take a few more
4891 characters in space, but allows easy searching for and identification
4892 of error messages.
4893
4894 @item -gnatb
4895 @cindex @option{-gnatb} (@command{gcc})
4896 @ifclear vms
4897 The @code{b} stands for brief.
4898 @end ifclear
4899 This switch causes GNAT to generate the
4900 brief format error messages to @file{stderr} (the standard error
4901 file) as well as the verbose
4902 format message or full listing (which as usual is written to
4903 @file{stdout} (the standard output file).
4904
4905 @item -gnatm=@var{n}
4906 @cindex @option{-gnatm} (@command{gcc})
4907 @ifclear vms
4908 The @code{m} stands for maximum.
4909 @end ifclear
4910 @var{n} is a decimal integer in the
4911 range of 1 to 999999 and limits the number of error or warning
4912 messages to be generated. For example, using
4913 @option{-gnatm2} might yield
4914
4915 @smallexample
4916 e.adb:3:04: Incorrect spelling of keyword "function"
4917 e.adb:5:35: missing ".."
4918 fatal error: maximum number of errors detected
4919 compilation abandoned
4920 @end smallexample
4921
4922 @noindent
4923 The default setting if
4924 no switch is given is 9999. If the number of warnings reaches this
4925 limit, then a message is output and further warnings are suppressed,
4926 but the compilation is continued. If the number of error messages
4927 reaches this limit, then a message is output and the compilation
4928 is abandoned. A value of zero means that no limit applies.
4929
4930 @noindent
4931 Note that the equal sign is optional, so the switches
4932 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4933
4934 @item -gnatf
4935 @cindex @option{-gnatf} (@command{gcc})
4936 @cindex Error messages, suppressing
4937 @ifclear vms
4938 The @code{f} stands for full.
4939 @end ifclear
4940 Normally, the compiler suppresses error messages that are likely to be
4941 redundant. This switch causes all error
4942 messages to be generated. In particular, in the case of
4943 references to undefined variables. If a given variable is referenced
4944 several times, the normal format of messages is
4945 @smallexample
4946 e.adb:7:07: "V" is undefined (more references follow)
4947 @end smallexample
4948
4949 @noindent
4950 where the parenthetical comment warns that there are additional
4951 references to the variable @code{V}. Compiling the same program with the
4952 @option{-gnatf} switch yields
4953
4954 @smallexample
4955 e.adb:7:07: "V" is undefined
4956 e.adb:8:07: "V" is undefined
4957 e.adb:8:12: "V" is undefined
4958 e.adb:8:16: "V" is undefined
4959 e.adb:9:07: "V" is undefined
4960 e.adb:9:12: "V" is undefined
4961 @end smallexample
4962
4963 @noindent
4964 The @option{-gnatf} switch also generates additional information for
4965 some error messages. Some examples are:
4966
4967 @itemize @bullet
4968 @item
4969 Details on possibly non-portable unchecked conversion
4970 @item
4971 List possible interpretations for ambiguous calls
4972 @item
4973 Additional details on incorrect parameters
4974 @end itemize
4975
4976 @item -gnatjnn
4977 @cindex @option{-gnatjnn} (@command{gcc})
4978 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4979 with continuation lines are treated as though the continuation lines were
4980 separate messages (and so a warning with two continuation lines counts as
4981 three warnings, and is listed as three separate messages).
4982
4983 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4984 messages are output in a different manner. A message and all its continuation
4985 lines are treated as a unit, and count as only one warning or message in the
4986 statistics totals. Furthermore, the message is reformatted so that no line
4987 is longer than nn characters.
4988
4989 @item -gnatq
4990 @cindex @option{-gnatq} (@command{gcc})
4991 @ifclear vms
4992 The @code{q} stands for quit (really ``don't quit'').
4993 @end ifclear
4994 In normal operation mode, the compiler first parses the program and
4995 determines if there are any syntax errors. If there are, appropriate
4996 error messages are generated and compilation is immediately terminated.
4997 This switch tells
4998 GNAT to continue with semantic analysis even if syntax errors have been
4999 found. This may enable the detection of more errors in a single run. On
5000 the other hand, the semantic analyzer is more likely to encounter some
5001 internal fatal error when given a syntactically invalid tree.
5002
5003 @item -gnatQ
5004 @cindex @option{-gnatQ} (@command{gcc})
5005 In normal operation mode, the @file{ALI} file is not generated if any
5006 illegalities are detected in the program. The use of @option{-gnatQ} forces
5007 generation of the @file{ALI} file. This file is marked as being in
5008 error, so it cannot be used for binding purposes, but it does contain
5009 reasonably complete cross-reference information, and thus may be useful
5010 for use by tools (e.g., semantic browsing tools or integrated development
5011 environments) that are driven from the @file{ALI} file. This switch
5012 implies @option{-gnatq}, since the semantic phase must be run to get a
5013 meaningful ALI file.
5014
5015 In addition, if @option{-gnatt} is also specified, then the tree file is
5016 generated even if there are illegalities. It may be useful in this case
5017 to also specify @option{-gnatq} to ensure that full semantic processing
5018 occurs. The resulting tree file can be processed by ASIS, for the purpose
5019 of providing partial information about illegal units, but if the error
5020 causes the tree to be badly malformed, then ASIS may crash during the
5021 analysis.
5022
5023 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
5024 being in error, @command{gnatmake} will attempt to recompile the source when it
5025 finds such an @file{ALI} file, including with switch @option{-gnatc}.
5026
5027 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
5028 since ALI files are never generated if @option{-gnats} is set.
5029
5030 @end table
5031
5032 @node Warning Message Control
5033 @subsection Warning Message Control
5034 @cindex Warning messages
5035 @noindent
5036 In addition to error messages, which correspond to illegalities as defined
5037 in the Ada Reference Manual, the compiler detects two kinds of warning
5038 situations.
5039
5040 First, the compiler considers some constructs suspicious and generates a
5041 warning message to alert you to a possible error. Second, if the
5042 compiler detects a situation that is sure to raise an exception at
5043 run time, it generates a warning message. The following shows an example
5044 of warning messages:
5045 @smallexample
5046 e.adb:4:24: warning: creation of object may raise Storage_Error
5047 e.adb:10:17: warning: static value out of range
5048 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
5049 @end smallexample
5050
5051 @noindent
5052 GNAT considers a large number of situations as appropriate
5053 for the generation of warning messages. As always, warnings are not
5054 definite indications of errors. For example, if you do an out-of-range
5055 assignment with the deliberate intention of raising a
5056 @code{Constraint_Error} exception, then the warning that may be
5057 issued does not indicate an error. Some of the situations for which GNAT
5058 issues warnings (at least some of the time) are given in the following
5059 list. This list is not complete, and new warnings are often added to
5060 subsequent versions of GNAT. The list is intended to give a general idea
5061 of the kinds of warnings that are generated.
5062
5063 @itemize @bullet
5064 @item
5065 Possible infinitely recursive calls
5066
5067 @item
5068 Out-of-range values being assigned
5069
5070 @item
5071 Possible order of elaboration problems
5072
5073 @item
5074 Assertions (pragma Assert) that are sure to fail
5075
5076 @item
5077 Unreachable code
5078
5079 @item
5080 Address clauses with possibly unaligned values, or where an attempt is
5081 made to overlay a smaller variable with a larger one.
5082
5083 @item
5084 Fixed-point type declarations with a null range
5085
5086 @item
5087 Direct_IO or Sequential_IO instantiated with a type that has access values
5088
5089 @item
5090 Variables that are never assigned a value
5091
5092 @item
5093 Variables that are referenced before being initialized
5094
5095 @item
5096 Task entries with no corresponding @code{accept} statement
5097
5098 @item
5099 Duplicate accepts for the same task entry in a @code{select}
5100
5101 @item
5102 Objects that take too much storage
5103
5104 @item
5105 Unchecked conversion between types of differing sizes
5106
5107 @item
5108 Missing @code{return} statement along some execution path in a function
5109
5110 @item
5111 Incorrect (unrecognized) pragmas
5112
5113 @item
5114 Incorrect external names
5115
5116 @item
5117 Allocation from empty storage pool
5118
5119 @item
5120 Potentially blocking operation in protected type
5121
5122 @item
5123 Suspicious parenthesization of expressions
5124
5125 @item
5126 Mismatching bounds in an aggregate
5127
5128 @item
5129 Attempt to return local value by reference
5130
5131 @item
5132 Premature instantiation of a generic body
5133
5134 @item
5135 Attempt to pack aliased components
5136
5137 @item
5138 Out of bounds array subscripts
5139
5140 @item
5141 Wrong length on string assignment
5142
5143 @item
5144 Violations of style rules if style checking is enabled
5145
5146 @item
5147 Unused @code{with} clauses
5148
5149 @item
5150 @code{Bit_Order} usage that does not have any effect
5151
5152 @item
5153 @code{Standard.Duration} used to resolve universal fixed expression
5154
5155 @item
5156 Dereference of possibly null value
5157
5158 @item
5159 Declaration that is likely to cause storage error
5160
5161 @item
5162 Internal GNAT unit @code{with}'ed by application unit
5163
5164 @item
5165 Values known to be out of range at compile time
5166
5167 @item
5168 Unreferenced labels and variables
5169
5170 @item
5171 Address overlays that could clobber memory
5172
5173 @item
5174 Unexpected initialization when address clause present
5175
5176 @item
5177 Bad alignment for address clause
5178
5179 @item
5180 Useless type conversions
5181
5182 @item
5183 Redundant assignment statements and other redundant constructs
5184
5185 @item
5186 Useless exception handlers
5187
5188 @item
5189 Accidental hiding of name by child unit
5190
5191 @item
5192 Access before elaboration detected at compile time
5193
5194 @item
5195 A range in a @code{for} loop that is known to be null or might be null
5196
5197 @end itemize
5198
5199 @noindent
5200 The following section lists compiler switches that are available
5201 to control the handling of warning messages. It is also possible
5202 to exercise much finer control over what warnings are issued and
5203 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5204 gnat_rm, GNAT Reference manual}.
5205
5206 @table @option
5207 @c !sort!
5208 @item -gnatwa
5209 @emph{Activate most optional warnings.}
5210 @cindex @option{-gnatwa} (@command{gcc})
5211 This switch activates most optional warning messages. See the remaining list
5212 in this section for details on optional warning messages that can be
5213 individually controlled. The warnings that are not turned on by this
5214 switch are
5215 @option{-gnatwd} (implicit dereferencing),
5216 @option{-gnatwh} (hiding),
5217 @ifclear vms
5218 @option{-gnatw.d} (tag warnings with -gnatw switch)
5219 @end ifclear
5220 @option{-gnatw.h} (holes (gaps) in record layouts)
5221 @option{-gnatw.i} (overlapping actuals),
5222 @option{-gnatw.k} (redefinition of names in standard),
5223 @option{-gnatwl} (elaboration warnings),
5224 @option{-gnatw.l} (inherited aspects),
5225 @option{-gnatw.o} (warn on values set by out parameters ignored),
5226 @option{-gnatwt} (tracking of deleted conditional code)
5227 and @option{-gnatw.u} (unordered enumeration),
5228 All other optional warnings are turned on.
5229
5230 @item -gnatwA
5231 @emph{Suppress all optional errors.}
5232 @cindex @option{-gnatwA} (@command{gcc})
5233 This switch suppresses all optional warning messages, see remaining list
5234 in this section for details on optional warning messages that can be
5235 individually controlled. Note that unlike switch @option{-gnatws}, the
5236 use of switch @option{-gnatwA} does not suppress warnings that are
5237 normally given unconditionally and cannot be individually controlled
5238 (for example, the warning about a missing exit path in a function).
5239 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5240 the use of switch @option{-gnatwA} can be individually turned back
5241 on. For example the use of switch @option{-gnatwA} followed by
5242 switch @option{-gnatwd} will suppress all optional warnings except
5243 the warnings for implicit dereferencing.
5244
5245 @item -gnatw.a
5246 @emph{Activate warnings on failing assertions.}
5247 @cindex @option{-gnatw.a} (@command{gcc})
5248 @cindex Assert failures
5249 This switch activates warnings for assertions where the compiler can tell at
5250 compile time that the assertion will fail. Note that this warning is given
5251 even if assertions are disabled. The default is that such warnings are
5252 generated.
5253
5254 @item -gnatw.A
5255 @emph{Suppress warnings on failing assertions.}
5256 @cindex @option{-gnatw.A} (@command{gcc})
5257 @cindex Assert failures
5258 This switch suppresses warnings for assertions where the compiler can tell at
5259 compile time that the assertion will fail.
5260
5261 @item -gnatwb
5262 @emph{Activate warnings on bad fixed values.}
5263 @cindex @option{-gnatwb} (@command{gcc})
5264 @cindex Bad fixed values
5265 @cindex Fixed-point Small value
5266 @cindex Small value
5267 This switch activates warnings for static fixed-point expressions whose
5268 value is not an exact multiple of Small. Such values are implementation
5269 dependent, since an implementation is free to choose either of the multiples
5270 that surround the value. GNAT always chooses the closer one, but this is not
5271 required behavior, and it is better to specify a value that is an exact
5272 multiple, ensuring predictable execution. The default is that such warnings
5273 are not generated.
5274
5275 @item -gnatwB
5276 @emph{Suppress warnings on bad fixed values.}
5277 @cindex @option{-gnatwB} (@command{gcc})
5278 This switch suppresses warnings for static fixed-point expressions whose
5279 value is not an exact multiple of Small.
5280
5281 @item -gnatw.b
5282 @emph{Activate warnings on biased representation.}
5283 @cindex @option{-gnatw.b} (@command{gcc})
5284 @cindex Biased representation
5285 This switch activates warnings when a size clause, value size clause, component
5286 clause, or component size clause forces the use of biased representation for an
5287 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5288 to represent 10/11). The default is that such warnings are generated.
5289
5290 @item -gnatw.B
5291 @emph{Suppress warnings on biased representation.}
5292 @cindex @option{-gnatwB} (@command{gcc})
5293 This switch suppresses warnings for representation clauses that force the use
5294 of biased representation.
5295
5296 @item -gnatwc
5297 @emph{Activate warnings on conditionals.}
5298 @cindex @option{-gnatwc} (@command{gcc})
5299 @cindex Conditionals, constant
5300 This switch activates warnings for conditional expressions used in
5301 tests that are known to be True or False at compile time. The default
5302 is that such warnings are not generated.
5303 Note that this warning does
5304 not get issued for the use of boolean variables or constants whose
5305 values are known at compile time, since this is a standard technique
5306 for conditional compilation in Ada, and this would generate too many
5307 false positive warnings.
5308
5309 This warning option also activates a special test for comparisons using
5310 the operators ``>='' and`` <=''.
5311 If the compiler can tell that only the equality condition is possible,
5312 then it will warn that the ``>'' or ``<'' part of the test
5313 is useless and that the operator could be replaced by ``=''.
5314 An example would be comparing a @code{Natural} variable <= 0.
5315
5316 This warning option also generates warnings if
5317 one or both tests is optimized away in a membership test for integer
5318 values if the result can be determined at compile time. Range tests on
5319 enumeration types are not included, since it is common for such tests
5320 to include an end point.
5321
5322 This warning can also be turned on using @option{-gnatwa}.
5323
5324 @item -gnatwC
5325 @emph{Suppress warnings on conditionals.}
5326 @cindex @option{-gnatwC} (@command{gcc})
5327 This switch suppresses warnings for conditional expressions used in
5328 tests that are known to be True or False at compile time.
5329
5330 @item -gnatw.c
5331 @emph{Activate warnings on missing component clauses.}
5332 @cindex @option{-gnatw.c} (@command{gcc})
5333 @cindex Component clause, missing
5334 This switch activates warnings for record components where a record
5335 representation clause is present and has component clauses for the
5336 majority, but not all, of the components. A warning is given for each
5337 component for which no component clause is present.
5338
5339 This warning can also be turned on using @option{-gnatwa}.
5340
5341 @item -gnatw.C
5342 @emph{Suppress warnings on missing component clauses.}
5343 @cindex @option{-gnatwC} (@command{gcc})
5344 This switch suppresses warnings for record components that are
5345 missing a component clause in the situation described above.
5346
5347 @item -gnatwd
5348 @emph{Activate warnings on implicit dereferencing.}
5349 @cindex @option{-gnatwd} (@command{gcc})
5350 If this switch is set, then the use of a prefix of an access type
5351 in an indexed component, slice, or selected component without an
5352 explicit @code{.all} will generate a warning. With this warning
5353 enabled, access checks occur only at points where an explicit
5354 @code{.all} appears in the source code (assuming no warnings are
5355 generated as a result of this switch). The default is that such
5356 warnings are not generated.
5357 Note that @option{-gnatwa} does not affect the setting of
5358 this warning option.
5359
5360 @item -gnatwD
5361 @emph{Suppress warnings on implicit dereferencing.}
5362 @cindex @option{-gnatwD} (@command{gcc})
5363 @cindex Implicit dereferencing
5364 @cindex Dereferencing, implicit
5365 This switch suppresses warnings for implicit dereferences in
5366 indexed components, slices, and selected components.
5367
5368 @ifclear vms
5369 @item -gnatw.d
5370 @emph{Activate tagging of warning messages.}
5371 @cindex @option{-gnatw.d} (@command{gcc})
5372 If this switch is set, then warning messages are tagged, either with
5373 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5374 or with ``[enabled by default]'' if the warning is not under control of a
5375 specific @option{-gnatw?} switch. This mode is off by default, and is not
5376 affected by the use of @code{-gnatwa}.
5377
5378 @item -gnatw.D
5379 @emph{Deactivate tagging of warning messages.}
5380 @cindex @option{-gnatw.d} (@command{gcc})
5381 If this switch is set, then warning messages return to the default
5382 mode in which warnings are not tagged as described above for
5383 @code{-gnatw.d}.
5384 @end ifclear
5385
5386 @item -gnatwe
5387 @emph{Treat warnings and style checks as errors.}
5388 @cindex @option{-gnatwe} (@command{gcc})
5389 @cindex Warnings, treat as error
5390 This switch causes warning messages and style check messages to be
5391 treated as errors.
5392 The warning string still appears, but the warning messages are counted
5393 as errors, and prevent the generation of an object file. Note that this
5394 is the only -gnatw switch that affects the handling of style check messages.
5395
5396 @item -gnatw.e
5397 @emph{Activate every optional warning}
5398 @cindex @option{-gnatw.e} (@command{gcc})
5399 @cindex Warnings, activate every optional warning
5400 This switch activates all optional warnings, including those which
5401 are not activated by @code{-gnatwa}. The use of this switch is not
5402 recommended for normal use. If you turn this switch on, it is almost
5403 certain that you will get large numbers of useless warnings. The
5404 warnings that are excluded from @code{-gnatwa} are typically highly
5405 specialized warnings that are suitable for use only in code that has
5406 been specifically designed according to specialized coding rules.
5407
5408 @item -gnatwf
5409 @emph{Activate warnings on unreferenced formals.}
5410 @cindex @option{-gnatwf} (@command{gcc})
5411 @cindex Formals, unreferenced
5412 This switch causes a warning to be generated if a formal parameter
5413 is not referenced in the body of the subprogram. This warning can
5414 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5415 default is that these warnings are not generated.
5416
5417 @item -gnatwF
5418 @emph{Suppress warnings on unreferenced formals.}
5419 @cindex @option{-gnatwF} (@command{gcc})
5420 This switch suppresses warnings for unreferenced formal
5421 parameters. Note that the
5422 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5423 effect of warning on unreferenced entities other than subprogram
5424 formals.
5425
5426 @item -gnatwg
5427 @emph{Activate warnings on unrecognized pragmas.}
5428 @cindex @option{-gnatwg} (@command{gcc})
5429 @cindex Pragmas, unrecognized
5430 This switch causes a warning to be generated if an unrecognized
5431 pragma is encountered. Apart from issuing this warning, the
5432 pragma is ignored and has no effect. This warning can
5433 also be turned on using @option{-gnatwa}. The default
5434 is that such warnings are issued (satisfying the Ada Reference
5435 Manual requirement that such warnings appear).
5436
5437 @item -gnatwG
5438 @emph{Suppress warnings on unrecognized pragmas.}
5439 @cindex @option{-gnatwG} (@command{gcc})
5440 This switch suppresses warnings for unrecognized pragmas.
5441
5442 @item -gnatwh
5443 @emph{Activate warnings on hiding.}
5444 @cindex @option{-gnatwh} (@command{gcc})
5445 @cindex Hiding of Declarations
5446 This switch activates warnings on hiding declarations.
5447 A declaration is considered hiding
5448 if it is for a non-overloadable entity, and it declares an entity with the
5449 same name as some other entity that is directly or use-visible. The default
5450 is that such warnings are not generated.
5451 Note that @option{-gnatwa} does not affect the setting of this warning option.
5452
5453 @item -gnatwH
5454 @emph{Suppress warnings on hiding.}
5455 @cindex @option{-gnatwH} (@command{gcc})
5456 This switch suppresses warnings on hiding declarations.
5457
5458 @item -gnatw.h
5459 @emph{Activate warnings on holes/gaps in records.}
5460 @cindex @option{-gnatw.h} (@command{gcc})
5461 @cindex Record Representation (gaps)
5462 This switch activates warnings on component clauses in record
5463 representation clauses that leave holes (gaps) in the record layout.
5464 If this warning option is active, then record representation clauses
5465 should specify a contiguous layout, adding unused fill fields if needed.
5466 Note that @option{-gnatwa} does not affect the setting of this warning option.
5467
5468 @item -gnatw.H
5469 @emph{Suppress warnings on holes/gaps in records.}
5470 @cindex @option{-gnatw.H} (@command{gcc})
5471 This switch suppresses warnings on component clauses in record
5472 representation clauses that leave holes (haps) in the record layout.
5473
5474 @item -gnatwi
5475 @emph{Activate warnings on implementation units.}
5476 @cindex @option{-gnatwi} (@command{gcc})
5477 This switch activates warnings for a @code{with} of an internal GNAT
5478 implementation unit, defined as any unit from the @code{Ada},
5479 @code{Interfaces}, @code{GNAT},
5480 ^^@code{DEC},^ or @code{System}
5481 hierarchies that is not
5482 documented in either the Ada Reference Manual or the GNAT
5483 Programmer's Reference Manual. Such units are intended only
5484 for internal implementation purposes and should not be @code{with}'ed
5485 by user programs. The default is that such warnings are generated
5486 This warning can also be turned on using @option{-gnatwa}.
5487
5488 @item -gnatwI
5489 @emph{Disable warnings on implementation units.}
5490 @cindex @option{-gnatwI} (@command{gcc})
5491 This switch disables warnings for a @code{with} of an internal GNAT
5492 implementation unit.
5493
5494 @item -gnatw.i
5495 @emph{Activate warnings on overlapping actuals.}
5496 @cindex @option{-gnatw.i} (@command{gcc})
5497 This switch enables a warning on statically detectable overlapping actuals in
5498 a subprogram call, when one of the actuals is an in-out parameter, and the
5499 types of the actuals are not by-copy types. The warning is off by default,
5500 and is not included under -gnatwa.
5501
5502 @item -gnatw.I
5503 @emph{Disable warnings on overlapping actuals.}
5504 @cindex @option{-gnatw.I} (@command{gcc})
5505 This switch disables warnings on overlapping actuals in a call..
5506
5507 @item -gnatwj
5508 @emph{Activate warnings on obsolescent features (Annex J).}
5509 @cindex @option{-gnatwj} (@command{gcc})
5510 @cindex Features, obsolescent
5511 @cindex Obsolescent features
5512 If this warning option is activated, then warnings are generated for
5513 calls to subprograms marked with @code{pragma Obsolescent} and
5514 for use of features in Annex J of the Ada Reference Manual. In the
5515 case of Annex J, not all features are flagged. In particular use
5516 of the renamed packages (like @code{Text_IO}) and use of package
5517 @code{ASCII} are not flagged, since these are very common and
5518 would generate many annoying positive warnings. The default is that
5519 such warnings are not generated. This warning is also turned on by
5520 the use of @option{-gnatwa}.
5521
5522 In addition to the above cases, warnings are also generated for
5523 GNAT features that have been provided in past versions but which
5524 have been superseded (typically by features in the new Ada standard).
5525 For example, @code{pragma Ravenscar} will be flagged since its
5526 function is replaced by @code{pragma Profile(Ravenscar)}, and
5527 @code{pragma Interface_Name} will be flagged since its function
5528 is replaced by @code{pragma Import}.
5529
5530 Note that this warning option functions differently from the
5531 restriction @code{No_Obsolescent_Features} in two respects.
5532 First, the restriction applies only to annex J features.
5533 Second, the restriction does flag uses of package @code{ASCII}.
5534
5535 @item -gnatwJ
5536 @emph{Suppress warnings on obsolescent features (Annex J).}
5537 @cindex @option{-gnatwJ} (@command{gcc})
5538 This switch disables warnings on use of obsolescent features.
5539
5540 @item -gnatwk
5541 @emph{Activate warnings on variables that could be constants.}
5542 @cindex @option{-gnatwk} (@command{gcc})
5543 This switch activates warnings for variables that are initialized but
5544 never modified, and then could be declared constants. The default is that
5545 such warnings are not given.
5546 This warning can also be turned on using @option{-gnatwa}.
5547
5548 @item -gnatwK
5549 @emph{Suppress warnings on variables that could be constants.}
5550 @cindex @option{-gnatwK} (@command{gcc})
5551 This switch disables warnings on variables that could be declared constants.
5552
5553 @item -gnatw.k
5554 @emph{Activate warnings on redefinition of names in standard.}
5555 @cindex @option{-gnatw.k} (@command{gcc})
5556 This switch activates warnings for declarations that declare a name that
5557 is defined in package Standard. Such declarations can be confusing,
5558 especially since the names in package Standard continue to be directly
5559 visible, meaning that use visibiliy on such redeclared names does not
5560 work as expected. Names of discriminants and components in records are
5561 not included in this check.
5562 This warning is not part of the warnings activated by @option{-gnatwa}.
5563 It must be explicitly activated.
5564
5565 @item -gnatw.K
5566 @emph{Suppress warnings on variables that could be constants.}
5567 @cindex @option{-gnatwK} (@command{gcc})
5568 This switch activates warnings for declarations that declare a name that
5569 is defined in package Standard.
5570
5571 @item -gnatwl
5572 @emph{Activate warnings for elaboration pragmas.}
5573 @cindex @option{-gnatwl} (@command{gcc})
5574 @cindex Elaboration, warnings
5575 This switch activates warnings on missing
5576 @code{Elaborate_All} and @code{Elaborate} pragmas.
5577 See the section in this guide on elaboration checking for details on
5578 when such pragmas should be used. In dynamic elaboration mode, this switch
5579 generations warnings about the need to add elaboration pragmas. Note however,
5580 that if you blindly follow these warnings, and add @code{Elaborate_All}
5581 warnings wherever they are recommended, you basically end up with the
5582 equivalent of the static elaboration model, which may not be what you want for
5583 legacy code for which the static model does not work.
5584
5585 For the static model, the messages generated are labeled "info:" (for
5586 information messages). They are not warnings to add elaboration pragmas,
5587 merely informational messages showing what implicit elaboration pragmas
5588 have been added, for use in analyzing elaboration circularity problems.
5589
5590 Warnings are also generated if you
5591 are using the static mode of elaboration, and a @code{pragma Elaborate}
5592 is encountered. The default is that such warnings
5593 are not generated.
5594 This warning is not automatically turned on by the use of @option{-gnatwa}.
5595
5596 @item -gnatwL
5597 @emph{Suppress warnings for elaboration pragmas.}
5598 @cindex @option{-gnatwL} (@command{gcc})
5599 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5600 See the section in this guide on elaboration checking for details on
5601 when such pragmas should be used.
5602
5603 @item -gnatw.l
5604 @emph{List inherited aspects.}
5605 @cindex @option{-gnatw.l} (@command{gcc})
5606 This switch causes the compiler to list inherited invariants,
5607 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5608 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5609 These messages are not automatically turned on by the use of @option{-gnatwa}.
5610
5611 @item -gnatw.L
5612 @emph{Suppress listing of inherited aspects.}
5613 @cindex @option{-gnatw.L} (@command{gcc})
5614 This switch suppresses listing of inherited aspects.
5615
5616 @item -gnatwm
5617 @emph{Activate warnings on modified but unreferenced variables.}
5618 @cindex @option{-gnatwm} (@command{gcc})
5619 This switch activates warnings for variables that are assigned (using
5620 an initialization value or with one or more assignment statements) but
5621 whose value is never read. The warning is suppressed for volatile
5622 variables and also for variables that are renamings of other variables
5623 or for which an address clause is given.
5624 This warning can also be turned on using @option{-gnatwa}.
5625 The default is that these warnings are not given.
5626
5627 @item -gnatwM
5628 @emph{Disable warnings on modified but unreferenced variables.}
5629 @cindex @option{-gnatwM} (@command{gcc})
5630 This switch disables warnings for variables that are assigned or
5631 initialized, but never read.
5632
5633 @item -gnatw.m
5634 @emph{Activate warnings on suspicious modulus values.}
5635 @cindex @option{-gnatw.m} (@command{gcc})
5636 This switch activates warnings for modulus values that seem suspicious.
5637 The cases caught are where the size is the same as the modulus (e.g.
5638 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5639 with no size clause. The guess in both cases is that 2**x was intended
5640 rather than x. In addition expressions of the form 2*x for small x
5641 generate a warning (the almost certainly accurate guess being that
5642 2**x was intended). The default is that these warnings are given.
5643
5644 @item -gnatw.M
5645 @emph{Disable warnings on suspicious modulus values.}
5646 @cindex @option{-gnatw.M} (@command{gcc})
5647 This switch disables warnings for suspicious modulus values.
5648
5649 @item -gnatwn
5650 @emph{Set normal warnings mode.}
5651 @cindex @option{-gnatwn} (@command{gcc})
5652 This switch sets normal warning mode, in which enabled warnings are
5653 issued and treated as warnings rather than errors. This is the default
5654 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5655 an explicit @option{-gnatws} or
5656 @option{-gnatwe}. It also cancels the effect of the
5657 implicit @option{-gnatwe} that is activated by the
5658 use of @option{-gnatg}.
5659
5660 @item -gnatwo
5661 @emph{Activate warnings on address clause overlays.}
5662 @cindex @option{-gnatwo} (@command{gcc})
5663 @cindex Address Clauses, warnings
5664 This switch activates warnings for possibly unintended initialization
5665 effects of defining address clauses that cause one variable to overlap
5666 another. The default is that such warnings are generated.
5667 This warning can also be turned on using @option{-gnatwa}.
5668
5669 @item -gnatwO
5670 @emph{Suppress warnings on address clause overlays.}
5671 @cindex @option{-gnatwO} (@command{gcc})
5672 This switch suppresses warnings on possibly unintended initialization
5673 effects of defining address clauses that cause one variable to overlap
5674 another.
5675
5676 @item -gnatw.o
5677 @emph{Activate warnings on modified but unreferenced out parameters.}
5678 @cindex @option{-gnatw.o} (@command{gcc})
5679 This switch activates warnings for variables that are modified by using
5680 them as actuals for a call to a procedure with an out mode formal, where
5681 the resulting assigned value is never read. It is applicable in the case
5682 where there is more than one out mode formal. If there is only one out
5683 mode formal, the warning is issued by default (controlled by -gnatwu).
5684 The warning is suppressed for volatile
5685 variables and also for variables that are renamings of other variables
5686 or for which an address clause is given.
5687 The default is that these warnings are not given. Note that this warning
5688 is not included in -gnatwa, it must be activated explicitly.
5689
5690 @item -gnatw.O
5691 @emph{Disable warnings on modified but unreferenced out parameters.}
5692 @cindex @option{-gnatw.O} (@command{gcc})
5693 This switch suppresses warnings for variables that are modified by using
5694 them as actuals for a call to a procedure with an out mode formal, where
5695 the resulting assigned value is never read.
5696
5697 @item -gnatwp
5698 @emph{Activate warnings on ineffective pragma Inlines.}
5699 @cindex @option{-gnatwp} (@command{gcc})
5700 @cindex Inlining, warnings
5701 This switch activates warnings for failure of front end inlining
5702 (activated by @option{-gnatN}) to inline a particular call. There are
5703 many reasons for not being able to inline a call, including most
5704 commonly that the call is too complex to inline. The default is
5705 that such warnings are not given.
5706 This warning can also be turned on using @option{-gnatwa}.
5707 Warnings on ineffective inlining by the gcc back-end can be activated
5708 separately, using the gcc switch -Winline.
5709
5710 @item -gnatwP
5711 @emph{Suppress warnings on ineffective pragma Inlines.}
5712 @cindex @option{-gnatwP} (@command{gcc})
5713 This switch suppresses warnings on ineffective pragma Inlines. If the
5714 inlining mechanism cannot inline a call, it will simply ignore the
5715 request silently.
5716
5717 @item -gnatw.p
5718 @emph{Activate warnings on parameter ordering.}
5719 @cindex @option{-gnatw.p} (@command{gcc})
5720 @cindex Parameter order, warnings
5721 This switch activates warnings for cases of suspicious parameter
5722 ordering when the list of arguments are all simple identifiers that
5723 match the names of the formals, but are in a different order. The
5724 warning is suppressed if any use of named parameter notation is used,
5725 so this is the appropriate way to suppress a false positive (and
5726 serves to emphasize that the "misordering" is deliberate). The
5727 default is
5728 that such warnings are not given.
5729 This warning can also be turned on using @option{-gnatwa}.
5730
5731 @item -gnatw.P
5732 @emph{Suppress warnings on parameter ordering.}
5733 @cindex @option{-gnatw.P} (@command{gcc})
5734 This switch suppresses warnings on cases of suspicious parameter
5735 ordering.
5736
5737 @item -gnatwq
5738 @emph{Activate warnings on questionable missing parentheses.}
5739 @cindex @option{-gnatwq} (@command{gcc})
5740 @cindex Parentheses, warnings
5741 This switch activates warnings for cases where parentheses are not used and
5742 the result is potential ambiguity from a readers point of view. For example
5743 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5744 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5745 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5746 follow the rule of always parenthesizing to make the association clear, and
5747 this warning switch warns if such parentheses are not present. The default
5748 is that these warnings are given.
5749 This warning can also be turned on using @option{-gnatwa}.
5750
5751 @item -gnatwQ
5752 @emph{Suppress warnings on questionable missing parentheses.}
5753 @cindex @option{-gnatwQ} (@command{gcc})
5754 This switch suppresses warnings for cases where the association is not
5755 clear and the use of parentheses is preferred.
5756
5757 @item -gnatwr
5758 @emph{Activate warnings on redundant constructs.}
5759 @cindex @option{-gnatwr} (@command{gcc})
5760 This switch activates warnings for redundant constructs. The following
5761 is the current list of constructs regarded as redundant:
5762
5763 @itemize @bullet
5764 @item
5765 Assignment of an item to itself.
5766 @item
5767 Type conversion that converts an expression to its own type.
5768 @item
5769 Use of the attribute @code{Base} where @code{typ'Base} is the same
5770 as @code{typ}.
5771 @item
5772 Use of pragma @code{Pack} when all components are placed by a record
5773 representation clause.
5774 @item
5775 Exception handler containing only a reraise statement (raise with no
5776 operand) which has no effect.
5777 @item
5778 Use of the operator abs on an operand that is known at compile time
5779 to be non-negative
5780 @item
5781 Comparison of boolean expressions to an explicit True value.
5782 @end itemize
5783
5784 This warning can also be turned on using @option{-gnatwa}.
5785 The default is that warnings for redundant constructs are not given.
5786
5787 @item -gnatwR
5788 @emph{Suppress warnings on redundant constructs.}
5789 @cindex @option{-gnatwR} (@command{gcc})
5790 This switch suppresses warnings for redundant constructs.
5791
5792 @item -gnatw.r
5793 @emph{Activate warnings for object renaming function.}
5794 @cindex @option{-gnatw.r} (@command{gcc})
5795 This switch activates warnings for an object renaming that renames a
5796 function call, which is equivalent to a constant declaration (as
5797 opposed to renaming the function itself). The default is that these
5798 warnings are given. This warning can also be turned on using
5799 @option{-gnatwa}.
5800
5801 @item -gnatw.R
5802 @emph{Suppress warnings for object renaming function.}
5803 @cindex @option{-gnatwT} (@command{gcc})
5804 This switch suppresses warnings for object renaming function.
5805
5806 @item -gnatws
5807 @emph{Suppress all warnings.}
5808 @cindex @option{-gnatws} (@command{gcc})
5809 This switch completely suppresses the
5810 output of all warning messages from the GNAT front end, including
5811 both warnings that can be controlled by switches described in this
5812 section, and those that are normally given unconditionally. The
5813 effect of this suppress action can only be cancelled by a subsequent
5814 use of the switch @option{-gnatwn}.
5815
5816 Note that switch @option{-gnatws} does not suppress
5817 warnings from the @command{gcc} back end.
5818 To suppress these back end warnings as well, use the switch @option{-w}
5819 in addition to @option{-gnatws}. Also this switch has no effect on the
5820 handling of style check messages.
5821
5822 @item -gnatw.s
5823 @emph{Activate warnings on overridden size clauses.}
5824 @cindex @option{-gnatw.s} (@command{gcc})
5825 @cindex Record Representation (component sizes)
5826 This switch activates warnings on component clauses in record
5827 representation clauses where the length given overrides that
5828 specified by an explicit size clause for the component type. A
5829 warning is similarly given in the array case if a specified
5830 component size overrides an explicit size clause for the array
5831 component type.
5832 Note that @option{-gnatwa} does not affect the setting of this warning option.
5833
5834 @item -gnatw.S
5835 @emph{Suppress warnings on overridden size clauses.}
5836 @cindex @option{-gnatw.S} (@command{gcc})
5837 This switch suppresses warnings on component clauses in record
5838 representation clauses that override size clauses, and similar
5839 warnings when an array component size overrides a size clause.
5840
5841 @item -gnatwt
5842 @emph{Activate warnings for tracking of deleted conditional code.}
5843 @cindex @option{-gnatwt} (@command{gcc})
5844 @cindex Deactivated code, warnings
5845 @cindex Deleted code, warnings
5846 This switch activates warnings for tracking of code in conditionals (IF and
5847 CASE statements) that is detected to be dead code which cannot be executed, and
5848 which is removed by the front end. This warning is off by default, and is not
5849 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5850 useful for detecting deactivated code in certified applications.
5851
5852 @item -gnatwT
5853 @emph{Suppress warnings for tracking of deleted conditional code.}
5854 @cindex @option{-gnatwT} (@command{gcc})
5855 This switch suppresses warnings for tracking of deleted conditional code.
5856
5857 @item -gnatw.t
5858 @emph{Activate warnings on suspicious contracts.}
5859 @cindex @option{-gnatw.t} (@command{gcc})
5860 This switch activates warnings on suspicious postconditions (whether a
5861 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5862 and suspicious contract cases (pragma @code{Contract_Case}). A
5863 function postcondition or contract case is suspicious when no postcondition
5864 or contract case for this function mentions the result of the function.
5865 A procedure postcondition or contract case is suspicious when it only
5866 refers to the pre-state of the procedure, because in that case it should
5867 rather be expressed as a precondition. The default is that such warnings
5868 are not generated. This warning can also be turned on using @option{-gnatwa}.
5869
5870 @item -gnatw.T
5871 @emph{Suppress warnings on suspicious contracts.}
5872 @cindex @option{-gnatw.T} (@command{gcc})
5873 This switch suppresses warnings on suspicious postconditions.
5874
5875 @item -gnatwu
5876 @emph{Activate warnings on unused entities.}
5877 @cindex @option{-gnatwu} (@command{gcc})
5878 This switch activates warnings to be generated for entities that
5879 are declared but not referenced, and for units that are @code{with}'ed
5880 and not
5881 referenced. In the case of packages, a warning is also generated if
5882 no entities in the package are referenced. This means that if a with'ed
5883 package is referenced but the only references are in @code{use}
5884 clauses or @code{renames}
5885 declarations, a warning is still generated. A warning is also generated
5886 for a generic package that is @code{with}'ed but never instantiated.
5887 In the case where a package or subprogram body is compiled, and there
5888 is a @code{with} on the corresponding spec
5889 that is only referenced in the body,
5890 a warning is also generated, noting that the
5891 @code{with} can be moved to the body. The default is that
5892 such warnings are not generated.
5893 This switch also activates warnings on unreferenced formals
5894 (it includes the effect of @option{-gnatwf}).
5895 This warning can also be turned on using @option{-gnatwa}.
5896
5897 @item -gnatwU
5898 @emph{Suppress warnings on unused entities.}
5899 @cindex @option{-gnatwU} (@command{gcc})
5900 This switch suppresses warnings for unused entities and packages.
5901 It also turns off warnings on unreferenced formals (and thus includes
5902 the effect of @option{-gnatwF}).
5903
5904 @item -gnatw.u
5905 @emph{Activate warnings on unordered enumeration types.}
5906 @cindex @option{-gnatw.u} (@command{gcc})
5907 This switch causes enumeration types to be considered as conceptually
5908 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5909 The effect is to generate warnings in clients that use explicit comparisons
5910 or subranges, since these constructs both treat objects of the type as
5911 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5912 which the type is declared, or its body or subunits.) Please refer to
5913 the description of pragma @code{Ordered} in the
5914 @cite{@value{EDITION} Reference Manual} for further details.
5915 The default is that such warnings are not generated.
5916 This warning is not automatically turned on by the use of @option{-gnatwa}.
5917
5918 @item -gnatw.U
5919 @emph{Deactivate warnings on unordered enumeration types.}
5920 @cindex @option{-gnatw.U} (@command{gcc})
5921 This switch causes all enumeration types to be considered as ordered, so
5922 that no warnings are given for comparisons or subranges for any type.
5923
5924 @item -gnatwv
5925 @emph{Activate warnings on unassigned variables.}
5926 @cindex @option{-gnatwv} (@command{gcc})
5927 @cindex Unassigned variable warnings
5928 This switch activates warnings for access to variables which
5929 may not be properly initialized. The default is that
5930 such warnings are generated.
5931 This warning can also be turned on using @option{-gnatwa}.
5932
5933 @item -gnatwV
5934 @emph{Suppress warnings on unassigned variables.}
5935 @cindex @option{-gnatwV} (@command{gcc})
5936 This switch suppresses warnings for access to variables which
5937 may not be properly initialized.
5938 For variables of a composite type, the warning can also be suppressed in
5939 Ada 2005 by using a default initialization with a box. For example, if
5940 Table is an array of records whose components are only partially uninitialized,
5941 then the following code:
5942
5943 @smallexample @c ada
5944 Tab : Table := (others => <>);
5945 @end smallexample
5946
5947 will suppress warnings on subsequent statements that access components
5948 of variable Tab.
5949
5950 @item -gnatw.v
5951 @emph{Activate info messages for non-default bit order.}
5952 @cindex @option{-gnatw.v} (@command{gcc})
5953 @cindex bit order warnings
5954 This switch activates messages (labeled "info", they are not warnings,
5955 just informational messages) about the effects of non-default bit-order
5956 on records to which a component clause is applied. The effect of specifying
5957 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5958 these messages, which are given by default, are useful in understanding the
5959 exact consequences of using this feature. These messages
5960 can also be turned on using @option{-gnatwa}
5961
5962 @item -gnatw.V
5963 @emph{Suppress info messages for non-default bit order.}
5964 @cindex @option{-gnatw.V} (@command{gcc})
5965 This switch suppresses information messages for the effects of specifying
5966 non-default bit order on record components with component clauses.
5967
5968 @item -gnatww
5969 @emph{Activate warnings on wrong low bound assumption.}
5970 @cindex @option{-gnatww} (@command{gcc})
5971 @cindex String indexing warnings
5972 This switch activates warnings for indexing an unconstrained string parameter
5973 with a literal or S'Length. This is a case where the code is assuming that the
5974 low bound is one, which is in general not true (for example when a slice is
5975 passed). The default is that such warnings are generated.
5976 This warning can also be turned on using @option{-gnatwa}.
5977
5978 @item -gnatwW
5979 @emph{Suppress warnings on wrong low bound assumption.}
5980 @cindex @option{-gnatwW} (@command{gcc})
5981 This switch suppresses warnings for indexing an unconstrained string parameter
5982 with a literal or S'Length. Note that this warning can also be suppressed
5983 in a particular case by adding an
5984 assertion that the lower bound is 1,
5985 as shown in the following example.
5986
5987 @smallexample @c ada
5988 procedure K (S : String) is
5989 pragma Assert (S'First = 1);
5990 @dots{}
5991 @end smallexample
5992
5993 @item -gnatw.w
5994 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5995 @cindex @option{-gnatw.w} (@command{gcc})
5996 @cindex Warnings Off control
5997 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5998 where either the pragma is entirely useless (because it suppresses no
5999 warnings), or it could be replaced by @code{pragma Unreferenced} or
6000 @code{pragma Unmodified}. The default is that these warnings are not given.
6001 Note that this warning is not included in -gnatwa, it must be
6002 activated explicitly.
6003
6004 @item -gnatw.W
6005 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
6006 @cindex @option{-gnatw.W} (@command{gcc})
6007 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
6008
6009 @item -gnatwx
6010 @emph{Activate warnings on Export/Import pragmas.}
6011 @cindex @option{-gnatwx} (@command{gcc})
6012 @cindex Export/Import pragma warnings
6013 This switch activates warnings on Export/Import pragmas when
6014 the compiler detects a possible conflict between the Ada and
6015 foreign language calling sequences. For example, the use of
6016 default parameters in a convention C procedure is dubious
6017 because the C compiler cannot supply the proper default, so
6018 a warning is issued. The default is that such warnings are
6019 generated.
6020 This warning can also be turned on using @option{-gnatwa}.
6021
6022 @item -gnatwX
6023 @emph{Suppress warnings on Export/Import pragmas.}
6024 @cindex @option{-gnatwX} (@command{gcc})
6025 This switch suppresses warnings on Export/Import pragmas.
6026 The sense of this is that you are telling the compiler that
6027 you know what you are doing in writing the pragma, and it
6028 should not complain at you.
6029
6030 @item -gnatw.x
6031 @emph{Activate warnings for No_Exception_Propagation mode.}
6032 @cindex @option{-gnatwm} (@command{gcc})
6033 This switch activates warnings for exception usage when pragma Restrictions
6034 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
6035 explicit exception raises which are not covered by a local handler, and for
6036 exception handlers which do not cover a local raise. The default is that these
6037 warnings are not given.
6038
6039 @item -gnatw.X
6040 @emph{Disable warnings for No_Exception_Propagation mode.}
6041 This switch disables warnings for exception usage when pragma Restrictions
6042 (No_Exception_Propagation) is in effect.
6043
6044 @item -gnatwy
6045 @emph{Activate warnings for Ada compatibility issues.}
6046 @cindex @option{-gnatwy} (@command{gcc})
6047 @cindex Ada compatibility issues warnings
6048 For the most part, newer versions of Ada are upwards compatible
6049 with older versions. For example, Ada 2005 programs will almost
6050 always work when compiled as Ada 2012.
6051 However there are some exceptions (for example the fact that
6052 @code{some} is now a reserved word in Ada 2012). This
6053 switch activates several warnings to help in identifying
6054 and correcting such incompatibilities. The default is that
6055 these warnings are generated. Note that at one point Ada 2005
6056 was called Ada 0Y, hence the choice of character.
6057 This warning can also be turned on using @option{-gnatwa}.
6058
6059 @item -gnatwY
6060 @emph{Disable warnings for Ada compatibility issues.}
6061 @cindex @option{-gnatwY} (@command{gcc})
6062 @cindex Ada compatibility issues warnings
6063 This switch suppresses the warnings intended to help in identifying
6064 incompatibilities between Ada language versions.
6065
6066 @item -gnatwz
6067 @emph{Activate warnings on unchecked conversions.}
6068 @cindex @option{-gnatwz} (@command{gcc})
6069 @cindex Unchecked_Conversion warnings
6070 This switch activates warnings for unchecked conversions
6071 where the types are known at compile time to have different
6072 sizes. The default
6073 is that such warnings are generated. Warnings are also
6074 generated for subprogram pointers with different conventions,
6075 and, on VMS only, for data pointers with different conventions.
6076 This warning can also be turned on using @option{-gnatwa}.
6077
6078 @item -gnatwZ
6079 @emph{Suppress warnings on unchecked conversions.}
6080 @cindex @option{-gnatwZ} (@command{gcc})
6081 This switch suppresses warnings for unchecked conversions
6082 where the types are known at compile time to have different
6083 sizes or conventions.
6084
6085 @item ^-Wunused^WARNINGS=UNUSED^
6086 @cindex @option{-Wunused}
6087 The warnings controlled by the @option{-gnatw} switch are generated by
6088 the front end of the compiler. The @option{GCC} back end can provide
6089 additional warnings and they are controlled by the @option{-W} switch.
6090 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
6091 warnings for entities that are declared but not referenced.
6092
6093 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
6094 @cindex @option{-Wuninitialized}
6095 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
6096 the back end warning for uninitialized variables. This switch must be
6097 used in conjunction with an optimization level greater than zero.
6098
6099 @item -Wstack-usage=@var{len}
6100 @cindex @option{-Wstack-usage}
6101 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
6102 See @ref{Static Stack Usage Analysis} for details.
6103
6104 @item ^-Wall^/ALL_BACK_END_WARNINGS^
6105 @cindex @option{-Wall}
6106 This switch enables most warnings from the @option{GCC} back end.
6107 The code generator detects a number of warning situations that are missed
6108 by the @option{GNAT} front end, and this switch can be used to activate them.
6109 The use of this switch also sets the default front end warning mode to
6110 @option{-gnatwa}, that is, most front end warnings activated as well.
6111
6112 @item ^-w^/NO_BACK_END_WARNINGS^
6113 @cindex @option{-w}
6114 Conversely, this switch suppresses warnings from the @option{GCC} back end.
6115 The use of this switch also sets the default front end warning mode to
6116 @option{-gnatws}, that is, front end warnings suppressed as well.
6117
6118 @end table
6119
6120 @noindent
6121 @ifclear vms
6122 A string of warning parameters can be used in the same parameter. For example:
6123
6124 @smallexample
6125 -gnatwaGe
6126 @end smallexample
6127
6128 @noindent
6129 will turn on all optional warnings except for unrecognized pragma warnings,
6130 and also specify that warnings should be treated as errors.
6131 @end ifclear
6132
6133 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
6134
6135 @table @option
6136 @c !sort!
6137 @item -gnatw.a
6138 @item -gnatwB
6139 @item -gnatw.b
6140 @item -gnatwC
6141 @item -gnatw.C
6142 @item -gnatwD
6143 @item -gnatwF
6144 @item -gnatwg
6145 @item -gnatwH
6146 @item -gnatwi
6147 @item -gnatw.I
6148 @item -gnatwJ
6149 @item -gnatwK
6150 @item -gnatwL
6151 @item -gnatw.L
6152 @item -gnatwM
6153 @item -gnatw.m
6154 @item -gnatwn
6155 @item -gnatwo
6156 @item -gnatw.O
6157 @item -gnatwP
6158 @item -gnatw.P
6159 @item -gnatwq
6160 @item -gnatwR
6161 @item -gnatw.R
6162 @item -gnatw.S
6163 @item -gnatwT
6164 @item -gnatw.T
6165 @item -gnatwU
6166 @item -gnatwv
6167 @item -gnatww
6168 @item -gnatw.W
6169 @item -gnatwx
6170 @item -gnatw.X
6171 @item -gnatwy
6172 @item -gnatwz
6173
6174 @end table
6175
6176 @node Debugging and Assertion Control
6177 @subsection Debugging and Assertion Control
6178
6179 @table @option
6180 @item -gnata
6181 @cindex @option{-gnata} (@command{gcc})
6182 @findex Assert
6183 @findex Debug
6184 @cindex Assertions
6185
6186 @noindent
6187 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6188 are ignored. This switch, where @samp{a} stands for assert, causes
6189 @code{Assert} and @code{Debug} pragmas to be activated.
6190
6191 The pragmas have the form:
6192
6193 @smallexample
6194 @cartouche
6195 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6196 @var{static-string-expression}@r{]})
6197 @b{pragma} Debug (@var{procedure call})
6198 @end cartouche
6199 @end smallexample
6200
6201 @noindent
6202 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6203 If the result is @code{True}, the pragma has no effect (other than
6204 possible side effects from evaluating the expression). If the result is
6205 @code{False}, the exception @code{Assert_Failure} declared in the package
6206 @code{System.Assertions} is
6207 raised (passing @var{static-string-expression}, if present, as the
6208 message associated with the exception). If no string expression is
6209 given the default is a string giving the file name and line number
6210 of the pragma.
6211
6212 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6213 @code{pragma Debug} may appear within a declaration sequence, allowing
6214 debugging procedures to be called between declarations.
6215
6216 @ifset vms
6217 @item /DEBUG@r{[}=debug-level@r{]}
6218 @itemx /NODEBUG
6219 Specifies how much debugging information is to be included in
6220 the resulting object file where 'debug-level' is one of the following:
6221 @table @code
6222 @item TRACEBACK
6223 Include both debugger symbol records and traceback
6224 the object file.
6225 This is the default setting.
6226 @item ALL
6227 Include both debugger symbol records and traceback in
6228 object file.
6229 @item NONE
6230 Excludes both debugger symbol records and traceback
6231 the object file. Same as /NODEBUG.
6232 @item SYMBOLS
6233 Includes only debugger symbol records in the object
6234 file. Note that this doesn't include traceback information.
6235 @end table
6236 @end ifset
6237 @end table
6238
6239 @node Validity Checking
6240 @subsection Validity Checking
6241 @findex Validity Checking
6242
6243 @noindent
6244 The Ada Reference Manual defines the concept of invalid values (see
6245 RM 13.9.1). The primary source of invalid values is uninitialized
6246 variables. A scalar variable that is left uninitialized may contain
6247 an invalid value; the concept of invalid does not apply to access or
6248 composite types.
6249
6250 It is an error to read an invalid value, but the RM does not require
6251 run-time checks to detect such errors, except for some minimal
6252 checking to prevent erroneous execution (i.e. unpredictable
6253 behavior). This corresponds to the @option{-gnatVd} switch below,
6254 which is the default. For example, by default, if the expression of a
6255 case statement is invalid, it will raise Constraint_Error rather than
6256 causing a wild jump, and if an array index on the left-hand side of an
6257 assignment is invalid, it will raise Constraint_Error rather than
6258 overwriting an arbitrary memory location.
6259
6260 The @option{-gnatVa} may be used to enable additional validity checks,
6261 which are not required by the RM. These checks are often very
6262 expensive (which is why the RM does not require them). These checks
6263 are useful in tracking down uninitialized variables, but they are
6264 not usually recommended for production builds.
6265
6266 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6267 control; you can enable whichever validity checks you desire. However,
6268 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6269 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6270 sufficient for non-debugging use.
6271
6272 The @option{-gnatB} switch tells the compiler to assume that all
6273 values are valid (that is, within their declared subtype range)
6274 except in the context of a use of the Valid attribute. This means
6275 the compiler can generate more efficient code, since the range
6276 of values is better known at compile time. However, an uninitialized
6277 variable can cause wild jumps and memory corruption in this mode.
6278
6279 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6280 checking mode as described below.
6281 @ifclear vms
6282 The @code{x} argument is a string of letters that
6283 indicate validity checks that are performed or not performed in addition
6284 to the default checks required by Ada as described above.
6285 @end ifclear
6286 @ifset vms
6287 The options allowed for this qualifier
6288 indicate validity checks that are performed or not performed in addition
6289 to the default checks required by Ada as described above.
6290 @end ifset
6291
6292 @table @option
6293 @c !sort!
6294 @item -gnatVa
6295 @emph{All validity checks.}
6296 @cindex @option{-gnatVa} (@command{gcc})
6297 All validity checks are turned on.
6298 @ifclear vms
6299 That is, @option{-gnatVa} is
6300 equivalent to @option{gnatVcdfimorst}.
6301 @end ifclear
6302
6303 @item -gnatVc
6304 @emph{Validity checks for copies.}
6305 @cindex @option{-gnatVc} (@command{gcc})
6306 The right hand side of assignments, and the initializing values of
6307 object declarations are validity checked.
6308
6309 @item -gnatVd
6310 @emph{Default (RM) validity checks.}
6311 @cindex @option{-gnatVd} (@command{gcc})
6312 Some validity checks are done by default following normal Ada semantics
6313 (RM 13.9.1 (9-11)).
6314 A check is done in case statements that the expression is within the range
6315 of the subtype. If it is not, Constraint_Error is raised.
6316 For assignments to array components, a check is done that the expression used
6317 as index is within the range. If it is not, Constraint_Error is raised.
6318 Both these validity checks may be turned off using switch @option{-gnatVD}.
6319 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6320 switch @option{-gnatVd} will leave the checks turned on.
6321 Switch @option{-gnatVD} should be used only if you are sure that all such
6322 expressions have valid values. If you use this switch and invalid values
6323 are present, then the program is erroneous, and wild jumps or memory
6324 overwriting may occur.
6325
6326 @item -gnatVe
6327 @emph{Validity checks for elementary components.}
6328 @cindex @option{-gnatVe} (@command{gcc})
6329 In the absence of this switch, assignments to record or array components are
6330 not validity checked, even if validity checks for assignments generally
6331 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6332 require valid data, but assignment of individual components does. So for
6333 example, there is a difference between copying the elements of an array with a
6334 slice assignment, compared to assigning element by element in a loop. This
6335 switch allows you to turn off validity checking for components, even when they
6336 are assigned component by component.
6337
6338 @item -gnatVf
6339 @emph{Validity checks for floating-point values.}
6340 @cindex @option{-gnatVf} (@command{gcc})
6341 In the absence of this switch, validity checking occurs only for discrete
6342 values. If @option{-gnatVf} is specified, then validity checking also applies
6343 for floating-point values, and NaNs and infinities are considered invalid,
6344 as well as out of range values for constrained types. Note that this means
6345 that standard IEEE infinity mode is not allowed. The exact contexts
6346 in which floating-point values are checked depends on the setting of other
6347 options. For example,
6348 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6349 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6350 (the order does not matter) specifies that floating-point parameters of mode
6351 @code{in} should be validity checked.
6352
6353 @item -gnatVi
6354 @emph{Validity checks for @code{in} mode parameters}
6355 @cindex @option{-gnatVi} (@command{gcc})
6356 Arguments for parameters of mode @code{in} are validity checked in function
6357 and procedure calls at the point of call.
6358
6359 @item -gnatVm
6360 @emph{Validity checks for @code{in out} mode parameters.}
6361 @cindex @option{-gnatVm} (@command{gcc})
6362 Arguments for parameters of mode @code{in out} are validity checked in
6363 procedure calls at the point of call. The @code{'m'} here stands for
6364 modify, since this concerns parameters that can be modified by the call.
6365 Note that there is no specific option to test @code{out} parameters,
6366 but any reference within the subprogram will be tested in the usual
6367 manner, and if an invalid value is copied back, any reference to it
6368 will be subject to validity checking.
6369
6370 @item -gnatVn
6371 @emph{No validity checks.}
6372 @cindex @option{-gnatVn} (@command{gcc})
6373 This switch turns off all validity checking, including the default checking
6374 for case statements and left hand side subscripts. Note that the use of
6375 the switch @option{-gnatp} suppresses all run-time checks, including
6376 validity checks, and thus implies @option{-gnatVn}. When this switch
6377 is used, it cancels any other @option{-gnatV} previously issued.
6378
6379 @item -gnatVo
6380 @emph{Validity checks for operator and attribute operands.}
6381 @cindex @option{-gnatVo} (@command{gcc})
6382 Arguments for predefined operators and attributes are validity checked.
6383 This includes all operators in package @code{Standard},
6384 the shift operators defined as intrinsic in package @code{Interfaces}
6385 and operands for attributes such as @code{Pos}. Checks are also made
6386 on individual component values for composite comparisons, and on the
6387 expressions in type conversions and qualified expressions. Checks are
6388 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6389
6390 @item -gnatVp
6391 @emph{Validity checks for parameters.}
6392 @cindex @option{-gnatVp} (@command{gcc})
6393 This controls the treatment of parameters within a subprogram (as opposed
6394 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6395 of parameters on a call. If either of these call options is used, then
6396 normally an assumption is made within a subprogram that the input arguments
6397 have been validity checking at the point of call, and do not need checking
6398 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6399 is not made, and parameters are not assumed to be valid, so their validity
6400 will be checked (or rechecked) within the subprogram.
6401
6402 @item -gnatVr
6403 @emph{Validity checks for function returns.}
6404 @cindex @option{-gnatVr} (@command{gcc})
6405 The expression in @code{return} statements in functions is validity
6406 checked.
6407
6408 @item -gnatVs
6409 @emph{Validity checks for subscripts.}
6410 @cindex @option{-gnatVs} (@command{gcc})
6411 All subscripts expressions are checked for validity, whether they appear
6412 on the right side or left side (in default mode only left side subscripts
6413 are validity checked).
6414
6415 @item -gnatVt
6416 @emph{Validity checks for tests.}
6417 @cindex @option{-gnatVt} (@command{gcc})
6418 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6419 statements are checked, as well as guard expressions in entry calls.
6420
6421 @end table
6422
6423 @noindent
6424 The @option{-gnatV} switch may be followed by
6425 ^a string of letters^a list of options^
6426 to turn on a series of validity checking options.
6427 For example,
6428 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6429 specifies that in addition to the default validity checking, copies and
6430 function return expressions are to be validity checked.
6431 In order to make it easier
6432 to specify the desired combination of effects,
6433 @ifclear vms
6434 the upper case letters @code{CDFIMORST} may
6435 be used to turn off the corresponding lower case option.
6436 @end ifclear
6437 @ifset vms
6438 the prefix @code{NO} on an option turns off the corresponding validity
6439 checking:
6440 @itemize @bullet
6441 @item @code{NOCOPIES}
6442 @item @code{NODEFAULT}
6443 @item @code{NOFLOATS}
6444 @item @code{NOIN_PARAMS}
6445 @item @code{NOMOD_PARAMS}
6446 @item @code{NOOPERANDS}
6447 @item @code{NORETURNS}
6448 @item @code{NOSUBSCRIPTS}
6449 @item @code{NOTESTS}
6450 @end itemize
6451 @end ifset
6452 Thus
6453 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6454 turns on all validity checking options except for
6455 checking of @code{@b{in out}} procedure arguments.
6456
6457 The specification of additional validity checking generates extra code (and
6458 in the case of @option{-gnatVa} the code expansion can be substantial).
6459 However, these additional checks can be very useful in detecting
6460 uninitialized variables, incorrect use of unchecked conversion, and other
6461 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6462 is useful in conjunction with the extra validity checking, since this
6463 ensures that wherever possible uninitialized variables have invalid values.
6464
6465 See also the pragma @code{Validity_Checks} which allows modification of
6466 the validity checking mode at the program source level, and also allows for
6467 temporary disabling of validity checks.
6468
6469 @node Style Checking
6470 @subsection Style Checking
6471 @findex Style checking
6472
6473 @noindent
6474 The @option{-gnaty^x^(option,option,@dots{})^} switch
6475 @cindex @option{-gnaty} (@command{gcc})
6476 causes the compiler to
6477 enforce specified style rules. A limited set of style rules has been used
6478 in writing the GNAT sources themselves. This switch allows user programs
6479 to activate all or some of these checks. If the source program fails a
6480 specified style check, an appropriate message is given, preceded by
6481 the character sequence ``(style)''. This message does not prevent
6482 successful compilation (unless the @option{-gnatwe} switch is used).
6483
6484 Note that this is by no means intended to be a general facility for
6485 checking arbitrary coding standards. It is simply an embedding of the
6486 style rules we have chosen for the GNAT sources. If you are starting
6487 a project which does not have established style standards, you may
6488 find it useful to adopt the entire set of GNAT coding standards, or
6489 some subset of them. If you already have an established set of coding
6490 standards, then it may be that selected style checking options do
6491 indeed correspond to choices you have made, but for general checking
6492 of an existing set of coding rules, you should look to the gnatcheck
6493 tool, which is designed for that purpose.
6494
6495 @ifset vms
6496 @code{(option,option,@dots{})} is a sequence of keywords
6497 @end ifset
6498 @ifclear vms
6499 The string @var{x} is a sequence of letters or digits
6500 @end ifclear
6501 indicating the particular style
6502 checks to be performed. The following checks are defined:
6503
6504 @table @option
6505 @c !sort!
6506 @item 0-9
6507 @emph{Specify indentation level.}
6508 If a digit from 1-9 appears
6509 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6510 then proper indentation is checked, with the digit indicating the
6511 indentation level required. A value of zero turns off this style check.
6512 The general style of required indentation is as specified by
6513 the examples in the Ada Reference Manual. Full line comments must be
6514 aligned with the @code{--} starting on a column that is a multiple of
6515 the alignment level, or they may be aligned the same way as the following
6516 non-blank line (this is useful when full line comments appear in the middle
6517 of a statement.
6518
6519 @item ^a^ATTRIBUTE^
6520 @emph{Check attribute casing.}
6521 Attribute names, including the case of keywords such as @code{digits}
6522 used as attributes names, must be written in mixed case, that is, the
6523 initial letter and any letter following an underscore must be uppercase.
6524 All other letters must be lowercase.
6525
6526 @item ^A^ARRAY_INDEXES^
6527 @emph{Use of array index numbers in array attributes.}
6528 When using the array attributes First, Last, Range,
6529 or Length, the index number must be omitted for one-dimensional arrays
6530 and is required for multi-dimensional arrays.
6531
6532 @item ^b^BLANKS^
6533 @emph{Blanks not allowed at statement end.}
6534 Trailing blanks are not allowed at the end of statements. The purpose of this
6535 rule, together with h (no horizontal tabs), is to enforce a canonical format
6536 for the use of blanks to separate source tokens.
6537
6538 @item ^B^BOOLEAN_OPERATORS^
6539 @emph{Check Boolean operators.}
6540 The use of AND/OR operators is not permitted except in the cases of modular
6541 operands, array operands, and simple stand-alone boolean variables or
6542 boolean constants. In all other cases @code{and then}/@code{or else} are
6543 required.
6544
6545 @item ^c^COMMENTS^
6546 @emph{Check comments, double space.}
6547 Comments must meet the following set of rules:
6548
6549 @itemize @bullet
6550
6551 @item
6552 The ``@code{--}'' that starts the column must either start in column one,
6553 or else at least one blank must precede this sequence.
6554
6555 @item
6556 Comments that follow other tokens on a line must have at least one blank
6557 following the ``@code{--}'' at the start of the comment.
6558
6559 @item
6560 Full line comments must have at least two blanks following the
6561 ``@code{--}'' that starts the comment, with the following exceptions.
6562
6563 @item
6564 A line consisting only of the ``@code{--}'' characters, possibly preceded
6565 by blanks is permitted.
6566
6567 @item
6568 A comment starting with ``@code{--x}'' where @code{x} is a special character
6569 is permitted.
6570 This allows proper processing of the output generated by specialized tools
6571 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6572 annotation
6573 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6574 special character is defined as being in one of the ASCII ranges
6575 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6576 Note that this usage is not permitted
6577 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6578
6579 @item
6580 A line consisting entirely of minus signs, possibly preceded by blanks, is
6581 permitted. This allows the construction of box comments where lines of minus
6582 signs are used to form the top and bottom of the box.
6583
6584 @item
6585 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6586 least one blank follows the initial ``@code{--}''. Together with the preceding
6587 rule, this allows the construction of box comments, as shown in the following
6588 example:
6589 @smallexample
6590 ---------------------------
6591 -- This is a box comment --
6592 -- with two text lines. --
6593 ---------------------------
6594 @end smallexample
6595 @end itemize
6596
6597 @item ^C^COMMENTS1^
6598 @emph{Check comments, single space.}
6599 This is identical to @code{^c^COMMENTS^} except that only one space
6600 is required following the @code{--} of a comment instead of two.
6601
6602 @item ^d^DOS_LINE_ENDINGS^
6603 @emph{Check no DOS line terminators present.}
6604 All lines must be terminated by a single ASCII.LF
6605 character (in particular the DOS line terminator sequence CR/LF is not
6606 allowed).
6607
6608 @item ^e^END^
6609 @emph{Check end/exit labels.}
6610 Optional labels on @code{end} statements ending subprograms and on
6611 @code{exit} statements exiting named loops, are required to be present.
6612
6613 @item ^f^VTABS^
6614 @emph{No form feeds or vertical tabs.}
6615 Neither form feeds nor vertical tab characters are permitted
6616 in the source text.
6617
6618 @item ^g^GNAT^
6619 @emph{GNAT style mode.}
6620 The set of style check switches is set to match that used by the GNAT sources.
6621 This may be useful when developing code that is eventually intended to be
6622 incorporated into GNAT. For further details, see GNAT sources.
6623
6624 @item ^h^HTABS^
6625 @emph{No horizontal tabs.}
6626 Horizontal tab characters are not permitted in the source text.
6627 Together with the b (no blanks at end of line) check, this
6628 enforces a canonical form for the use of blanks to separate
6629 source tokens.
6630
6631 @item ^i^IF_THEN^
6632 @emph{Check if-then layout.}
6633 The keyword @code{then} must appear either on the same
6634 line as corresponding @code{if}, or on a line on its own, lined
6635 up under the @code{if} with at least one non-blank line in between
6636 containing all or part of the condition to be tested.
6637
6638 @item ^I^IN_MODE^
6639 @emph{check mode IN keywords.}
6640 Mode @code{in} (the default mode) is not
6641 allowed to be given explicitly. @code{in out} is fine,
6642 but not @code{in} on its own.
6643
6644 @item ^k^KEYWORD^
6645 @emph{Check keyword casing.}
6646 All keywords must be in lower case (with the exception of keywords
6647 such as @code{digits} used as attribute names to which this check
6648 does not apply).
6649
6650 @item ^l^LAYOUT^
6651 @emph{Check layout.}
6652 Layout of statement and declaration constructs must follow the
6653 recommendations in the Ada Reference Manual, as indicated by the
6654 form of the syntax rules. For example an @code{else} keyword must
6655 be lined up with the corresponding @code{if} keyword.
6656
6657 There are two respects in which the style rule enforced by this check
6658 option are more liberal than those in the Ada Reference Manual. First
6659 in the case of record declarations, it is permissible to put the
6660 @code{record} keyword on the same line as the @code{type} keyword, and
6661 then the @code{end} in @code{end record} must line up under @code{type}.
6662 This is also permitted when the type declaration is split on two lines.
6663 For example, any of the following three layouts is acceptable:
6664
6665 @smallexample @c ada
6666 @cartouche
6667 type q is record
6668 a : integer;
6669 b : integer;
6670 end record;
6671
6672 type q is
6673 record
6674 a : integer;
6675 b : integer;
6676 end record;
6677
6678 type q is
6679 record
6680 a : integer;
6681 b : integer;
6682 end record;
6683
6684 @end cartouche
6685 @end smallexample
6686
6687 @noindent
6688 Second, in the case of a block statement, a permitted alternative
6689 is to put the block label on the same line as the @code{declare} or
6690 @code{begin} keyword, and then line the @code{end} keyword up under
6691 the block label. For example both the following are permitted:
6692
6693 @smallexample @c ada
6694 @cartouche
6695 Block : declare
6696 A : Integer := 3;
6697 begin
6698 Proc (A, A);
6699 end Block;
6700
6701 Block :
6702 declare
6703 A : Integer := 3;
6704 begin
6705 Proc (A, A);
6706 end Block;
6707 @end cartouche
6708 @end smallexample
6709
6710 @noindent
6711 The same alternative format is allowed for loops. For example, both of
6712 the following are permitted:
6713
6714 @smallexample @c ada
6715 @cartouche
6716 Clear : while J < 10 loop
6717 A (J) := 0;
6718 end loop Clear;
6719
6720 Clear :
6721 while J < 10 loop
6722 A (J) := 0;
6723 end loop Clear;
6724 @end cartouche
6725 @end smallexample
6726
6727 @item ^Lnnn^MAX_NESTING=nnn^
6728 @emph{Set maximum nesting level.}
6729 The maximum level of nesting of constructs (including subprograms, loops,
6730 blocks, packages, and conditionals) may not exceed the given value
6731 @option{nnn}. A value of zero disconnects this style check.
6732
6733 @item ^m^LINE_LENGTH^
6734 @emph{Check maximum line length.}
6735 The length of source lines must not exceed 79 characters, including
6736 any trailing blanks. The value of 79 allows convenient display on an
6737 80 character wide device or window, allowing for possible special
6738 treatment of 80 character lines. Note that this count is of
6739 characters in the source text. This means that a tab character counts
6740 as one character in this count and a wide character sequence counts as
6741 a single character (however many bytes are needed in the encoding).
6742
6743 @item ^Mnnn^MAX_LENGTH=nnn^
6744 @emph{Set maximum line length.}
6745 The length of lines must not exceed the
6746 given value @option{nnn}. The maximum value that can be specified is 32767.
6747 If neither style option for setting the line length is used, then the
6748 default is 255. This also controls the maximum length of lexical elements,
6749 where the only restriction is that they must fit on a single line.
6750
6751 @item ^n^STANDARD_CASING^
6752 @emph{Check casing of entities in Standard.}
6753 Any identifier from Standard must be cased
6754 to match the presentation in the Ada Reference Manual (for example,
6755 @code{Integer} and @code{ASCII.NUL}).
6756
6757 @item ^N^NONE^
6758 @emph{Turn off all style checks.}
6759 All style check options are turned off.
6760
6761 @item ^o^ORDERED_SUBPROGRAMS^
6762 @emph{Check order of subprogram bodies.}
6763 All subprogram bodies in a given scope
6764 (e.g.@: a package body) must be in alphabetical order. The ordering
6765 rule uses normal Ada rules for comparing strings, ignoring casing
6766 of letters, except that if there is a trailing numeric suffix, then
6767 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6768 before Junk10).
6769
6770 @item ^O^OVERRIDING_INDICATORS^
6771 @emph{Check that overriding subprograms are explicitly marked as such.}
6772 The declaration of a primitive operation of a type extension that overrides
6773 an inherited operation must carry an overriding indicator.
6774
6775 @item ^p^PRAGMA^
6776 @emph{Check pragma casing.}
6777 Pragma names must be written in mixed case, that is, the
6778 initial letter and any letter following an underscore must be uppercase.
6779 All other letters must be lowercase.
6780
6781 @item ^r^REFERENCES^
6782 @emph{Check references.}
6783 All identifier references must be cased in the same way as the
6784 corresponding declaration. No specific casing style is imposed on
6785 identifiers. The only requirement is for consistency of references
6786 with declarations.
6787
6788 @item ^s^SPECS^
6789 @emph{Check separate specs.}
6790 Separate declarations (``specs'') are required for subprograms (a
6791 body is not allowed to serve as its own declaration). The only
6792 exception is that parameterless library level procedures are
6793 not required to have a separate declaration. This exception covers
6794 the most frequent form of main program procedures.
6795
6796 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6797 @emph{Check no statements after @code{then}/@code{else}.}
6798 No statements are allowed
6799 on the same line as a @code{then} or @code{else} keyword following the
6800 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6801 affected, and a special exception allows a pragma to appear after @code{else}.
6802
6803 @item ^t^TOKEN^
6804 @emph{Check token spacing.}
6805 The following token spacing rules are enforced:
6806
6807 @itemize @bullet
6808
6809 @item
6810 The keywords @code{abs} and @code{not} must be followed by a space.
6811
6812 @item
6813 The token @code{=>} must be surrounded by spaces.
6814
6815 @item
6816 The token @code{<>} must be preceded by a space or a left parenthesis.
6817
6818 @item
6819 Binary operators other than @code{**} must be surrounded by spaces.
6820 There is no restriction on the layout of the @code{**} binary operator.
6821
6822 @item
6823 Colon must be surrounded by spaces.
6824
6825 @item
6826 Colon-equal (assignment, initialization) must be surrounded by spaces.
6827
6828 @item
6829 Comma must be the first non-blank character on the line, or be
6830 immediately preceded by a non-blank character, and must be followed
6831 by a space.
6832
6833 @item
6834 If the token preceding a left parenthesis ends with a letter or digit, then
6835 a space must separate the two tokens.
6836
6837 @item
6838 if the token following a right parenthesis starts with a letter or digit, then
6839 a space must separate the two tokens.
6840
6841 @item
6842 A right parenthesis must either be the first non-blank character on
6843 a line, or it must be preceded by a non-blank character.
6844
6845 @item
6846 A semicolon must not be preceded by a space, and must not be followed by
6847 a non-blank character.
6848
6849 @item
6850 A unary plus or minus may not be followed by a space.
6851
6852 @item
6853 A vertical bar must be surrounded by spaces.
6854 @end itemize
6855
6856 @item
6857 Exactly one blank (and no other white space) must appear between
6858 a @code{not} token and a following @code{in} token.
6859
6860 @item ^u^UNNECESSARY_BLANK_LINES^
6861 @emph{Check unnecessary blank lines.}
6862 Unnecessary blank lines are not allowed. A blank line is considered
6863 unnecessary if it appears at the end of the file, or if more than
6864 one blank line occurs in sequence.
6865
6866 @item ^x^XTRA_PARENS^
6867 @emph{Check extra parentheses.}
6868 Unnecessary extra level of parentheses (C-style) are not allowed
6869 around conditions in @code{if} statements, @code{while} statements and
6870 @code{exit} statements.
6871
6872 @item ^y^ALL_BUILTIN^
6873 @emph{Set all standard style check options}
6874 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6875 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6876 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6877 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6878
6879 @ifclear vms
6880 @item -
6881 @emph{Remove style check options}
6882 This causes any subsequent options in the string to act as canceling the
6883 corresponding style check option. To cancel maximum nesting level control,
6884 use @option{L} parameter witout any integer value after that, because any
6885 digit following @option{-} in the parameter string of the @option{-gnaty}
6886 option will be threated as canceling indentation check. The same is true
6887 for @option{M} parameter. @option{y} and @option{N} parameters are not
6888 allowed after @option{-}.
6889
6890 @item +
6891 This causes any subsequent options in the string to enable the corresponding
6892 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6893 if any.
6894 @end ifclear
6895
6896 @ifset vms
6897 @item NOxxx
6898 @emph{Removing style check options}
6899 If the name of a style check is preceded by @option{NO} then the corresponding
6900 style check is turned off. For example @option{NOCOMMENTS} turns off style
6901 checking for comments.
6902 @end ifset
6903 @end table
6904
6905 @noindent
6906 In the above rules, appearing in column one is always permitted, that is,
6907 counts as meeting either a requirement for a required preceding space,
6908 or as meeting a requirement for no preceding space.
6909
6910 Appearing at the end of a line is also always permitted, that is, counts
6911 as meeting either a requirement for a following space, or as meeting
6912 a requirement for no following space.
6913
6914 @noindent
6915 If any of these style rules is violated, a message is generated giving
6916 details on the violation. The initial characters of such messages are
6917 always ``@code{(style)}''. Note that these messages are treated as warning
6918 messages, so they normally do not prevent the generation of an object
6919 file. The @option{-gnatwe} switch can be used to treat warning messages,
6920 including style messages, as fatal errors.
6921
6922 The switch
6923 @ifclear vms
6924 @option{-gnaty} on its own (that is not
6925 followed by any letters or digits) is equivalent
6926 to the use of @option{-gnatyy} as described above, that is all
6927 built-in standard style check options are enabled.
6928
6929 @end ifclear
6930 @ifset vms
6931 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6932 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6933 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6934 @end ifset
6935
6936 The switch
6937 @ifclear vms
6938 @option{-gnatyN}
6939 @end ifclear
6940 @ifset vms
6941 /STYLE_CHECKS=NONE
6942 @end ifset
6943 clears any previously set style checks.
6944
6945 @node Run-Time Checks
6946 @subsection Run-Time Checks
6947 @cindex Division by zero
6948 @cindex Access before elaboration
6949 @cindex Checks, division by zero
6950 @cindex Checks, access before elaboration
6951 @cindex Checks, stack overflow checking
6952
6953 @noindent
6954 By default, the following checks are suppressed: integer overflow
6955 checks, stack overflow checks, and checks for access before
6956 elaboration on subprogram calls. All other checks, including range
6957 checks and array bounds checks, are turned on by default. The
6958 following @command{gcc} switches refine this default behavior.
6959
6960 @table @option
6961 @c !sort!
6962 @item -gnatp
6963 @cindex @option{-gnatp} (@command{gcc})
6964 @cindex Suppressing checks
6965 @cindex Checks, suppressing
6966 @findex Suppress
6967 This switch causes the unit to be compiled
6968 as though @code{pragma Suppress (All_checks)}
6969 had been present in the source. Validity checks are also eliminated (in
6970 other words @option{-gnatp} also implies @option{-gnatVn}.
6971 Use this switch to improve the performance
6972 of the code at the expense of safety in the presence of invalid data or
6973 program bugs.
6974
6975 Note that when checks are suppressed, the compiler is allowed, but not
6976 required, to omit the checking code. If the run-time cost of the
6977 checking code is zero or near-zero, the compiler will generate it even
6978 if checks are suppressed. In particular, if the compiler can prove
6979 that a certain check will necessarily fail, it will generate code to
6980 do an unconditional ``raise'', even if checks are suppressed. The
6981 compiler warns in this case. Another case in which checks may not be
6982 eliminated is when they are embedded in certain run time routines such
6983 as math library routines.
6984
6985 Of course, run-time checks are omitted whenever the compiler can prove
6986 that they will not fail, whether or not checks are suppressed.
6987
6988 Note that if you suppress a check that would have failed, program
6989 execution is erroneous, which means the behavior is totally
6990 unpredictable. The program might crash, or print wrong answers, or
6991 do anything else. It might even do exactly what you wanted it to do
6992 (and then it might start failing mysteriously next week or next
6993 year). The compiler will generate code based on the assumption that
6994 the condition being checked is true, which can result in disaster if
6995 that assumption is wrong.
6996
6997 The checks subject to suppression include all the checks defined by
6998 the Ada standard, the additional implementation defined checks
6999 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
7000 @code{Validity_Check}, as well as any checks introduced using
7001 @code{pragma Check_Name}.
7002
7003 The @option{-gnatp} switch has no effect if a subsequent
7004 @option{-gnat-p} switch appears.
7005
7006 @item -gnat-p
7007 @cindex @option{-gnat-p} (@command{gcc})
7008 @cindex Suppressing checks
7009 @cindex Checks, suppressing
7010 @findex Suppress
7011 This switch cancels the effect of a previous @option{gnatp} switch.
7012
7013 @item -gnato??
7014 @cindex @option{-gnato??} (@command{gcc})
7015 @cindex Overflow checks
7016 @cindex Overflow mode
7017 @cindex Check, overflow
7018 This switch controls the mode used for computing intermediate
7019 arithmetic integer operations, and also enables overflow checking.
7020 For a full description of overflow mode and checking control, see
7021 the ``Overflow Check Handling in GNAT'' appendix in this
7022 User's Guide.
7023
7024 Overflow checks are always enabled by this switch. The argument
7025 controls the mode, using the codes
7026
7027 @itemize
7028 @item 1 = STRICT
7029 In STRICT mode, intermediate operations are always done using the
7030 base type, and overflow checking ensures that the result is within
7031 the base type range.
7032
7033 @item 2 = MINIMIZED
7034 In MINIMIZED mode, overflows in intermediate operations are avoided
7035 where possible by using a larger integer type for the computation
7036 (typically @code{Long_Long_Integer}). Overflow checking ensures that
7037 the result fits in this larger integer type.
7038
7039 @item 3 = ELIMINATED
7040 In ELIMINATED mode, overflows in intermediate operations are avoided
7041 by using multi-precision arithmetic. In this case, overflow checking
7042 has no effect on intermediate operations (since overflow is impossible).
7043 @end itemize
7044
7045 If two digits are present after @option{-gnato} then the first digit
7046 sets the mode for expressions outside assertions, and the second digit
7047 sets the mode for expressions within assertions. Here assertions is used
7048 in the technical sense (which includes for example precondition and
7049 postcondition expressions).
7050
7051 If one digit is present, the corresponding mode is applicable to both
7052 expressions within and outside assertion expressions.
7053
7054 If no digits are present, the default is to enable overflow checks
7055 and set STRICT mode for both kinds of expressions. This is compatible
7056 with the use of @option{-gnato} in previous versions of GNAT.
7057
7058 @findex Machine_Overflows
7059 Note that the @option{-gnato??} switch does not affect the code generated
7060 for any floating-point operations; it applies only to integer semantics.
7061 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
7062 attribute set to @code{False} and the normal mode of operation is to
7063 generate IEEE NaN and infinite values on overflow or invalid operations
7064 (such as dividing 0.0 by 0.0).
7065
7066 The reason that we distinguish overflow checking from other kinds of
7067 range constraint checking is that a failure of an overflow check, unlike
7068 for example the failure of a range check, can result in an incorrect
7069 value, but cannot cause random memory destruction (like an out of range
7070 subscript), or a wild jump (from an out of range case value). Overflow
7071 checking is also quite expensive in time and space, since in general it
7072 requires the use of double length arithmetic.
7073
7074 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
7075 so overflow checking is not performed in default mode. This means that out of
7076 the box, with the default settings, @value{EDITION} does not do all the checks
7077 expected from the language description in the Ada Reference Manual.
7078 If you want all constraint checks to be performed, as described in this Manual,
7079 then you must explicitly use the @option{-gnato??}
7080 switch either on the @command{gnatmake} or @command{gcc} command.
7081
7082 @item -gnatE
7083 @cindex @option{-gnatE} (@command{gcc})
7084 @cindex Elaboration checks
7085 @cindex Check, elaboration
7086 Enables dynamic checks for access-before-elaboration
7087 on subprogram calls and generic instantiations.
7088 Note that @option{-gnatE} is not necessary for safety, because in the
7089 default mode, GNAT ensures statically that the checks would not fail.
7090 For full details of the effect and use of this switch,
7091 @xref{Compiling Using gcc}.
7092
7093 @item -fstack-check
7094 @cindex @option{-fstack-check} (@command{gcc})
7095 @cindex Stack Overflow Checking
7096 @cindex Checks, stack overflow checking
7097 Activates stack overflow checking. For full details of the effect and use of
7098 this switch see @ref{Stack Overflow Checking}.
7099 @end table
7100
7101 @findex Unsuppress
7102 @noindent
7103 The setting of these switches only controls the default setting of the
7104 checks. You may modify them using either @code{Suppress} (to remove
7105 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
7106 the program source.
7107
7108 @node Using gcc for Syntax Checking
7109 @subsection Using @command{gcc} for Syntax Checking
7110 @table @option
7111 @item -gnats
7112 @cindex @option{-gnats} (@command{gcc})
7113 @ifclear vms
7114
7115 @noindent
7116 The @code{s} stands for ``syntax''.
7117 @end ifclear
7118
7119 Run GNAT in syntax checking only mode. For
7120 example, the command
7121
7122 @smallexample
7123 $ gcc -c -gnats x.adb
7124 @end smallexample
7125
7126 @noindent
7127 compiles file @file{x.adb} in syntax-check-only mode. You can check a
7128 series of files in a single command
7129 @ifclear vms
7130 , and can use wild cards to specify such a group of files.
7131 Note that you must specify the @option{-c} (compile
7132 only) flag in addition to the @option{-gnats} flag.
7133 @end ifclear
7134 .
7135 You may use other switches in conjunction with @option{-gnats}. In
7136 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7137 format of any generated error messages.
7138
7139 When the source file is empty or contains only empty lines and/or comments,
7140 the output is a warning:
7141
7142 @smallexample
7143 $ gcc -c -gnats -x ada toto.txt
7144 toto.txt:1:01: warning: empty file, contains no compilation units
7145 $
7146 @end smallexample
7147
7148 Otherwise, the output is simply the error messages, if any. No object file or
7149 ALI file is generated by a syntax-only compilation. Also, no units other
7150 than the one specified are accessed. For example, if a unit @code{X}
7151 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7152 check only mode does not access the source file containing unit
7153 @code{Y}.
7154
7155 @cindex Multiple units, syntax checking
7156 Normally, GNAT allows only a single unit in a source file. However, this
7157 restriction does not apply in syntax-check-only mode, and it is possible
7158 to check a file containing multiple compilation units concatenated
7159 together. This is primarily used by the @code{gnatchop} utility
7160 (@pxref{Renaming Files Using gnatchop}).
7161 @end table
7162
7163 @node Using gcc for Semantic Checking
7164 @subsection Using @command{gcc} for Semantic Checking
7165 @table @option
7166 @item -gnatc
7167 @cindex @option{-gnatc} (@command{gcc})
7168
7169 @ifclear vms
7170 @noindent
7171 The @code{c} stands for ``check''.
7172 @end ifclear
7173 Causes the compiler to operate in semantic check mode,
7174 with full checking for all illegalities specified in the
7175 Ada Reference Manual, but without generation of any object code
7176 (no object file is generated).
7177
7178 Because dependent files must be accessed, you must follow the GNAT
7179 semantic restrictions on file structuring to operate in this mode:
7180
7181 @itemize @bullet
7182 @item
7183 The needed source files must be accessible
7184 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7185
7186 @item
7187 Each file must contain only one compilation unit.
7188
7189 @item
7190 The file name and unit name must match (@pxref{File Naming Rules}).
7191 @end itemize
7192
7193 The output consists of error messages as appropriate. No object file is
7194 generated. An @file{ALI} file is generated for use in the context of
7195 cross-reference tools, but this file is marked as not being suitable
7196 for binding (since no object file is generated).
7197 The checking corresponds exactly to the notion of
7198 legality in the Ada Reference Manual.
7199
7200 Any unit can be compiled in semantics-checking-only mode, including
7201 units that would not normally be compiled (subunits,
7202 and specifications where a separate body is present).
7203 @end table
7204
7205 @node Compiling Different Versions of Ada
7206 @subsection Compiling Different Versions of Ada
7207
7208 @noindent
7209 The switches described in this section allow you to explicitly specify
7210 the version of the Ada language that your programs are written in.
7211 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7212 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7213 indicate Ada 83 compatibility mode.
7214
7215 @table @option
7216 @cindex Compatibility with Ada 83
7217
7218 @item -gnat83 (Ada 83 Compatibility Mode)
7219 @cindex @option{-gnat83} (@command{gcc})
7220 @cindex ACVC, Ada 83 tests
7221 @cindex Ada 83 mode
7222
7223 @noindent
7224 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7225 specifies that the program is to be compiled in Ada 83 mode. With
7226 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7227 semantics where this can be done easily.
7228 It is not possible to guarantee this switch does a perfect
7229 job; some subtle tests, such as are
7230 found in earlier ACVC tests (and that have been removed from the ACATS suite
7231 for Ada 95), might not compile correctly.
7232 Nevertheless, this switch may be useful in some circumstances, for example
7233 where, due to contractual reasons, existing code needs to be maintained
7234 using only Ada 83 features.
7235
7236 With few exceptions (most notably the need to use @code{<>} on
7237 @cindex Generic formal parameters
7238 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7239 reserved words, and the use of packages
7240 with optional bodies), it is not necessary to specify the
7241 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7242 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7243 a correct Ada 83 program is usually also a correct program
7244 in these later versions of the language standard.
7245 For further information, please refer to @ref{Compatibility and Porting Guide}.
7246
7247 @item -gnat95 (Ada 95 mode)
7248 @cindex @option{-gnat95} (@command{gcc})
7249 @cindex Ada 95 mode
7250
7251 @noindent
7252 This switch directs the compiler to implement the Ada 95 version of the
7253 language.
7254 Since Ada 95 is almost completely upwards
7255 compatible with Ada 83, Ada 83 programs may generally be compiled using
7256 this switch (see the description of the @option{-gnat83} switch for further
7257 information about Ada 83 mode).
7258 If an Ada 2005 program is compiled in Ada 95 mode,
7259 uses of the new Ada 2005 features will cause error
7260 messages or warnings.
7261
7262 This switch also can be used to cancel the effect of a previous
7263 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7264 switch earlier in the command line.
7265
7266 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7267 @cindex @option{-gnat05} (@command{gcc})
7268 @cindex @option{-gnat2005} (@command{gcc})
7269 @cindex Ada 2005 mode
7270
7271 @noindent
7272 This switch directs the compiler to implement the Ada 2005 version of the
7273 language, as documented in the official Ada standards document.
7274 Since Ada 2005 is almost completely upwards
7275 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7276 may generally be compiled using this switch (see the description of the
7277 @option{-gnat83} and @option{-gnat95} switches for further
7278 information).
7279
7280 @ifset PROEDITION
7281 Note that even though Ada 2005 is the current official version of the
7282 language, GNAT still compiles in Ada 95 mode by default, so if you are
7283 using Ada 2005 features in your program, you must use this switch (or
7284 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7285 @end ifset
7286
7287 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7288 @cindex @option{-gnat12} (@command{gcc})
7289 @cindex @option{-gnat2012} (@command{gcc})
7290 @cindex Ada 2012 mode
7291
7292 @noindent
7293 This switch directs the compiler to implement the Ada 2012 version of the
7294 language.
7295 Since Ada 2012 is almost completely upwards
7296 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7297 Ada 83 and Ada 95 programs
7298 may generally be compiled using this switch (see the description of the
7299 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7300 for further information).
7301
7302 For information about the approved ``Ada Issues'' that have been incorporated
7303 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7304 Included with GNAT releases is a file @file{features-ada12} that describes
7305 the set of implemented Ada 2012 features.
7306
7307 @item -gnatX (Enable GNAT Extensions)
7308 @cindex @option{-gnatX} (@command{gcc})
7309 @cindex Ada language extensions
7310 @cindex GNAT extensions
7311
7312 @noindent
7313 This switch directs the compiler to implement the latest version of the
7314 language (currently Ada 2012) and also to enable certain GNAT implementation
7315 extensions that are not part of any Ada standard. For a full list of these
7316 extensions, see the GNAT reference manual.
7317
7318 @end table
7319
7320 @node Character Set Control
7321 @subsection Character Set Control
7322 @table @option
7323 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7324 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7325
7326 @noindent
7327 Normally GNAT recognizes the Latin-1 character set in source program
7328 identifiers, as described in the Ada Reference Manual.
7329 This switch causes
7330 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7331 single character ^^or word^ indicating the character set, as follows:
7332
7333 @table @code
7334 @item 1
7335 ISO 8859-1 (Latin-1) identifiers
7336
7337 @item 2
7338 ISO 8859-2 (Latin-2) letters allowed in identifiers
7339
7340 @item 3
7341 ISO 8859-3 (Latin-3) letters allowed in identifiers
7342
7343 @item 4
7344 ISO 8859-4 (Latin-4) letters allowed in identifiers
7345
7346 @item 5
7347 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7348
7349 @item 9
7350 ISO 8859-15 (Latin-9) letters allowed in identifiers
7351
7352 @item ^p^PC^
7353 IBM PC letters (code page 437) allowed in identifiers
7354
7355 @item ^8^PC850^
7356 IBM PC letters (code page 850) allowed in identifiers
7357
7358 @item ^f^FULL_UPPER^
7359 Full upper-half codes allowed in identifiers
7360
7361 @item ^n^NO_UPPER^
7362 No upper-half codes allowed in identifiers
7363
7364 @item ^w^WIDE^
7365 Wide-character codes (that is, codes greater than 255)
7366 allowed in identifiers
7367 @end table
7368
7369 @xref{Foreign Language Representation}, for full details on the
7370 implementation of these character sets.
7371
7372 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7373 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7374 Specify the method of encoding for wide characters.
7375 @var{e} is one of the following:
7376
7377 @table @code
7378
7379 @item ^h^HEX^
7380 Hex encoding (brackets coding also recognized)
7381
7382 @item ^u^UPPER^
7383 Upper half encoding (brackets encoding also recognized)
7384
7385 @item ^s^SHIFT_JIS^
7386 Shift/JIS encoding (brackets encoding also recognized)
7387
7388 @item ^e^EUC^
7389 EUC encoding (brackets encoding also recognized)
7390
7391 @item ^8^UTF8^
7392 UTF-8 encoding (brackets encoding also recognized)
7393
7394 @item ^b^BRACKETS^
7395 Brackets encoding only (default value)
7396 @end table
7397 For full details on these encoding
7398 methods see @ref{Wide Character Encodings}.
7399 Note that brackets coding is always accepted, even if one of the other
7400 options is specified, so for example @option{-gnatW8} specifies that both
7401 brackets and UTF-8 encodings will be recognized. The units that are
7402 with'ed directly or indirectly will be scanned using the specified
7403 representation scheme, and so if one of the non-brackets scheme is
7404 used, it must be used consistently throughout the program. However,
7405 since brackets encoding is always recognized, it may be conveniently
7406 used in standard libraries, allowing these libraries to be used with
7407 any of the available coding schemes.
7408
7409 Note that brackets encoding only applies to program text. Within comments,
7410 brackets are considered to be normal graphic characters, and bracket sequences
7411 are never recognized as wide characters.
7412
7413 If no @option{-gnatW?} parameter is present, then the default
7414 representation is normally Brackets encoding only. However, if the
7415 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7416 byte order mark or BOM for UTF-8), then these three characters are
7417 skipped and the default representation for the file is set to UTF-8.
7418
7419 Note that the wide character representation that is specified (explicitly
7420 or by default) for the main program also acts as the default encoding used
7421 for Wide_Text_IO files if not specifically overridden by a WCEM form
7422 parameter.
7423
7424 @end table
7425
7426 When no @option{-gnatW?} is specified, then characters (other than wide
7427 characters represented using brackets notation) are treated as 8-bit
7428 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7429 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7430 characters in the range 16#00#..16#1F# are not accepted in program text
7431 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7432 in program text, but allowed and ignored in comments. Note in particular
7433 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7434 as an end of line in this default mode. If your source program contains
7435 instances of the NEL character used as a line terminator,
7436 you must use UTF-8 encoding for the whole
7437 source program. In default mode, all lines must be ended by a standard
7438 end of line sequence (CR, CR/LF, or LF).
7439
7440 Note that the convention of simply accepting all upper half characters in
7441 comments means that programs that use standard ASCII for program text, but
7442 UTF-8 encoding for comments are accepted in default mode, providing that the
7443 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7444 This is a common mode for many programs with foreign language comments.
7445
7446 @node File Naming Control
7447 @subsection File Naming Control
7448
7449 @table @option
7450 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7451 @cindex @option{-gnatk} (@command{gcc})
7452 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7453 1-999, indicates the maximum allowable length of a file name (not
7454 including the @file{.ads} or @file{.adb} extension). The default is not
7455 to enable file name krunching.
7456
7457 For the source file naming rules, @xref{File Naming Rules}.
7458 @end table
7459
7460 @node Subprogram Inlining Control
7461 @subsection Subprogram Inlining Control
7462
7463 @table @option
7464 @c !sort!
7465 @item -gnatn[12]
7466 @cindex @option{-gnatn} (@command{gcc})
7467 @ifclear vms
7468 The @code{n} here is intended to suggest the first syllable of the
7469 word ``inline''.
7470 @end ifclear
7471 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7472 inlining to actually occur, optimization must be enabled and, in order
7473 to enable inlining of subprograms specified by pragma @code{Inline},
7474 you must also specify this switch.
7475 In the absence of this switch, GNAT does not attempt
7476 inlining and does not need to access the bodies of
7477 subprograms for which @code{pragma Inline} is specified if they are not
7478 in the current unit.
7479
7480 You can optionally specify the inlining level: 1 for moderate inlining across
7481 modules, which is a good compromise between compilation times and performances
7482 at run time, or 2 for full inlining across modules, which may bring about
7483 longer compilation times. If no inlining level is specified, the compiler will
7484 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7485 @option{-Os} and 2 for @option{-O3}.
7486
7487 If you specify this switch the compiler will access these bodies,
7488 creating an extra source dependency for the resulting object file, and
7489 where possible, the call will be inlined.
7490 For further details on when inlining is possible
7491 see @ref{Inlining of Subprograms}.
7492
7493 @item -gnatN
7494 @cindex @option{-gnatN} (@command{gcc})
7495 This switch activates front-end inlining which also
7496 generates additional dependencies.
7497
7498 When using a gcc-based back end (in practice this means using any version
7499 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7500 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7501 Historically front end inlining was more extensive than the gcc back end
7502 inlining, but that is no longer the case.
7503 @end table
7504
7505 @node Auxiliary Output Control
7506 @subsection Auxiliary Output Control
7507
7508 @table @option
7509 @item -gnatt
7510 @cindex @option{-gnatt} (@command{gcc})
7511 @cindex Writing internal trees
7512 @cindex Internal trees, writing to file
7513 Causes GNAT to write the internal tree for a unit to a file (with the
7514 extension @file{.adt}.
7515 This not normally required, but is used by separate analysis tools.
7516 Typically
7517 these tools do the necessary compilations automatically, so you should
7518 not have to specify this switch in normal operation.
7519 Note that the combination of switches @option{-gnatct}
7520 generates a tree in the form required by ASIS applications.
7521
7522 @item -gnatu
7523 @cindex @option{-gnatu} (@command{gcc})
7524 Print a list of units required by this compilation on @file{stdout}.
7525 The listing includes all units on which the unit being compiled depends
7526 either directly or indirectly.
7527
7528 @ifclear vms
7529 @item -pass-exit-codes
7530 @cindex @option{-pass-exit-codes} (@command{gcc})
7531 If this switch is not used, the exit code returned by @command{gcc} when
7532 compiling multiple files indicates whether all source files have
7533 been successfully used to generate object files or not.
7534
7535 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7536 exit status and allows an integrated development environment to better
7537 react to a compilation failure. Those exit status are:
7538
7539 @table @asis
7540 @item 5
7541 There was an error in at least one source file.
7542 @item 3
7543 At least one source file did not generate an object file.
7544 @item 2
7545 The compiler died unexpectedly (internal error for example).
7546 @item 0
7547 An object file has been generated for every source file.
7548 @end table
7549 @end ifclear
7550 @end table
7551
7552 @node Debugging Control
7553 @subsection Debugging Control
7554
7555 @table @option
7556 @c !sort!
7557 @cindex Debugging options
7558 @ifclear vms
7559 @item -gnatd@var{x}
7560 @cindex @option{-gnatd} (@command{gcc})
7561 Activate internal debugging switches. @var{x} is a letter or digit, or
7562 string of letters or digits, which specifies the type of debugging
7563 outputs desired. Normally these are used only for internal development
7564 or system debugging purposes. You can find full documentation for these
7565 switches in the body of the @code{Debug} unit in the compiler source
7566 file @file{debug.adb}.
7567 @end ifclear
7568
7569 @item -gnatG[=nn]
7570 @cindex @option{-gnatG} (@command{gcc})
7571 This switch causes the compiler to generate auxiliary output containing
7572 a pseudo-source listing of the generated expanded code. Like most Ada
7573 compilers, GNAT works by first transforming the high level Ada code into
7574 lower level constructs. For example, tasking operations are transformed
7575 into calls to the tasking run-time routines. A unique capability of GNAT
7576 is to list this expanded code in a form very close to normal Ada source.
7577 This is very useful in understanding the implications of various Ada
7578 usage on the efficiency of the generated code. There are many cases in
7579 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7580 generate a lot of run-time code. By using @option{-gnatG} you can identify
7581 these cases, and consider whether it may be desirable to modify the coding
7582 approach to improve efficiency.
7583
7584 The optional parameter @code{nn} if present after -gnatG specifies an
7585 alternative maximum line length that overrides the normal default of 72.
7586 This value is in the range 40-999999, values less than 40 being silently
7587 reset to 40. The equal sign is optional.
7588
7589 The format of the output is very similar to standard Ada source, and is
7590 easily understood by an Ada programmer. The following special syntactic
7591 additions correspond to low level features used in the generated code that
7592 do not have any exact analogies in pure Ada source form. The following
7593 is a partial list of these special constructions. See the spec
7594 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7595
7596 If the switch @option{-gnatL} is used in conjunction with
7597 @cindex @option{-gnatL} (@command{gcc})
7598 @option{-gnatG}, then the original source lines are interspersed
7599 in the expanded source (as comment lines with the original line number).
7600
7601 @table @code
7602 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7603 Shows the storage pool being used for an allocator.
7604
7605 @item at end @var{procedure-name};
7606 Shows the finalization (cleanup) procedure for a scope.
7607
7608 @item (if @var{expr} then @var{expr} else @var{expr})
7609 Conditional expression equivalent to the @code{x?y:z} construction in C.
7610
7611 @item @var{target}^^^(@var{source})
7612 A conversion with floating-point truncation instead of rounding.
7613
7614 @item @var{target}?(@var{source})
7615 A conversion that bypasses normal Ada semantic checking. In particular
7616 enumeration types and fixed-point types are treated simply as integers.
7617
7618 @item @var{target}?^^^(@var{source})
7619 Combines the above two cases.
7620
7621 @item @var{x} #/ @var{y}
7622 @itemx @var{x} #mod @var{y}
7623 @itemx @var{x} #* @var{y}
7624 @itemx @var{x} #rem @var{y}
7625 A division or multiplication of fixed-point values which are treated as
7626 integers without any kind of scaling.
7627
7628 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7629 Shows the storage pool associated with a @code{free} statement.
7630
7631 @item [subtype or type declaration]
7632 Used to list an equivalent declaration for an internally generated
7633 type that is referenced elsewhere in the listing.
7634
7635 @c @item freeze @var{type-name} @ovar{actions}
7636 @c Expanding @ovar macro inline (explanation in macro def comments)
7637 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7638 Shows the point at which @var{type-name} is frozen, with possible
7639 associated actions to be performed at the freeze point.
7640
7641 @item reference @var{itype}
7642 Reference (and hence definition) to internal type @var{itype}.
7643
7644 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7645 Intrinsic function call.
7646
7647 @item @var{label-name} : label
7648 Declaration of label @var{labelname}.
7649
7650 @item #$ @var{subprogram-name}
7651 An implicit call to a run-time support routine
7652 (to meet the requirement of H.3.1(9) in a
7653 convenient manner).
7654
7655 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7656 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7657 @var{expr}, but handled more efficiently).
7658
7659 @item [constraint_error]
7660 Raise the @code{Constraint_Error} exception.
7661
7662 @item @var{expression}'reference
7663 A pointer to the result of evaluating @var{expression}.
7664
7665 @item @var{target-type}!(@var{source-expression})
7666 An unchecked conversion of @var{source-expression} to @var{target-type}.
7667
7668 @item [@var{numerator}/@var{denominator}]
7669 Used to represent internal real literals (that) have no exact
7670 representation in base 2-16 (for example, the result of compile time
7671 evaluation of the expression 1.0/27.0).
7672 @end table
7673
7674 @item -gnatD[=nn]
7675 @cindex @option{-gnatD} (@command{gcc})
7676 When used in conjunction with @option{-gnatG}, this switch causes
7677 the expanded source, as described above for
7678 @option{-gnatG} to be written to files with names
7679 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7680 instead of to the standard output file. For
7681 example, if the source file name is @file{hello.adb}, then a file
7682 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7683 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7684 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7685 you to do source level debugging using the generated code which is
7686 sometimes useful for complex code, for example to find out exactly
7687 which part of a complex construction raised an exception. This switch
7688 also suppress generation of cross-reference information (see
7689 @option{-gnatx}) since otherwise the cross-reference information
7690 would refer to the @file{^.dg^.DG^} file, which would cause
7691 confusion since this is not the original source file.
7692
7693 Note that @option{-gnatD} actually implies @option{-gnatG}
7694 automatically, so it is not necessary to give both options.
7695 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7696
7697 If the switch @option{-gnatL} is used in conjunction with
7698 @cindex @option{-gnatL} (@command{gcc})
7699 @option{-gnatDG}, then the original source lines are interspersed
7700 in the expanded source (as comment lines with the original line number).
7701
7702 The optional parameter @code{nn} if present after -gnatD specifies an
7703 alternative maximum line length that overrides the normal default of 72.
7704 This value is in the range 40-999999, values less than 40 being silently
7705 reset to 40. The equal sign is optional.
7706
7707 @item -gnatr
7708 @cindex @option{-gnatr} (@command{gcc})
7709 @cindex pragma Restrictions
7710 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7711 so that violation of restrictions causes warnings rather than illegalities.
7712 This is useful during the development process when new restrictions are added
7713 or investigated. The switch also causes pragma Profile to be treated as
7714 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7715 restriction warnings rather than restrictions.
7716
7717 @ifclear vms
7718 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7719 @cindex @option{-gnatR} (@command{gcc})
7720 This switch controls output from the compiler of a listing showing
7721 representation information for declared types and objects. For
7722 @option{-gnatR0}, no information is output (equivalent to omitting
7723 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7724 so @option{-gnatR} with no parameter has the same effect), size and alignment
7725 information is listed for declared array and record types. For
7726 @option{-gnatR2}, size and alignment information is listed for all
7727 declared types and objects. Finally @option{-gnatR3} includes symbolic
7728 expressions for values that are computed at run time for
7729 variant records. These symbolic expressions have a mostly obvious
7730 format with #n being used to represent the value of the n'th
7731 discriminant. See source files @file{repinfo.ads/adb} in the
7732 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7733 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7734 the output is to a file with the name @file{^file.rep^file_REP^} where
7735 file is the name of the corresponding source file.
7736 @end ifclear
7737 @ifset vms
7738 @item /REPRESENTATION_INFO
7739 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7740 This qualifier controls output from the compiler of a listing showing
7741 representation information for declared types and objects. For
7742 @option{/REPRESENTATION_INFO=NONE}, no information is output
7743 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7744 @option{/REPRESENTATION_INFO} without option is equivalent to
7745 @option{/REPRESENTATION_INFO=ARRAYS}.
7746 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7747 information is listed for declared array and record types. For
7748 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7749 is listed for all expression information for values that are computed
7750 at run time for variant records. These symbolic expressions have a mostly
7751 obvious format with #n being used to represent the value of the n'th
7752 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7753 @code{GNAT} sources for full details on the format of
7754 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7755 If _FILE is added at the end of an option
7756 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7757 then the output is to a file with the name @file{file_REP} where
7758 file is the name of the corresponding source file.
7759 @end ifset
7760 Note that it is possible for record components to have zero size. In
7761 this case, the component clause uses an obvious extension of permitted
7762 Ada syntax, for example @code{at 0 range 0 .. -1}.
7763
7764 Representation information requires that code be generated (since it is the
7765 code generator that lays out complex data structures). If an attempt is made
7766 to output representation information when no code is generated, for example
7767 when a subunit is compiled on its own, then no information can be generated
7768 and the compiler outputs a message to this effect.
7769
7770 @item -gnatS
7771 @cindex @option{-gnatS} (@command{gcc})
7772 The use of the switch @option{-gnatS} for an
7773 Ada compilation will cause the compiler to output a
7774 representation of package Standard in a form very
7775 close to standard Ada. It is not quite possible to
7776 do this entirely in standard Ada (since new
7777 numeric base types cannot be created in standard
7778 Ada), but the output is easily
7779 readable to any Ada programmer, and is useful to
7780 determine the characteristics of target dependent
7781 types in package Standard.
7782
7783 @item -gnatx
7784 @cindex @option{-gnatx} (@command{gcc})
7785 Normally the compiler generates full cross-referencing information in
7786 the @file{ALI} file. This information is used by a number of tools,
7787 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7788 suppresses this information. This saves some space and may slightly
7789 speed up compilation, but means that these tools cannot be used.
7790 @end table
7791
7792 @node Exception Handling Control
7793 @subsection Exception Handling Control
7794
7795 @noindent
7796 GNAT uses two methods for handling exceptions at run-time. The
7797 @code{setjmp/longjmp} method saves the context when entering
7798 a frame with an exception handler. Then when an exception is
7799 raised, the context can be restored immediately, without the
7800 need for tracing stack frames. This method provides very fast
7801 exception propagation, but introduces significant overhead for
7802 the use of exception handlers, even if no exception is raised.
7803
7804 The other approach is called ``zero cost'' exception handling.
7805 With this method, the compiler builds static tables to describe
7806 the exception ranges. No dynamic code is required when entering
7807 a frame containing an exception handler. When an exception is
7808 raised, the tables are used to control a back trace of the
7809 subprogram invocation stack to locate the required exception
7810 handler. This method has considerably poorer performance for
7811 the propagation of exceptions, but there is no overhead for
7812 exception handlers if no exception is raised. Note that in this
7813 mode and in the context of mixed Ada and C/C++ programming,
7814 to propagate an exception through a C/C++ code, the C/C++ code
7815 must be compiled with the @option{-funwind-tables} GCC's
7816 option.
7817
7818 The following switches may be used to control which of the
7819 two exception handling methods is used.
7820
7821 @table @option
7822 @c !sort!
7823
7824 @item --RTS=sjlj
7825 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7826 This switch causes the setjmp/longjmp run-time (when available) to be used
7827 for exception handling. If the default
7828 mechanism for the target is zero cost exceptions, then
7829 this switch can be used to modify this default, and must be
7830 used for all units in the partition.
7831 This option is rarely used. One case in which it may be
7832 advantageous is if you have an application where exception
7833 raising is common and the overall performance of the
7834 application is improved by favoring exception propagation.
7835
7836 @item --RTS=zcx
7837 @cindex @option{--RTS=zcx} (@command{gnatmake})
7838 @cindex Zero Cost Exceptions
7839 This switch causes the zero cost approach to be used
7840 for exception handling. If this is the default mechanism for the
7841 target (see below), then this switch is unneeded. If the default
7842 mechanism for the target is setjmp/longjmp exceptions, then
7843 this switch can be used to modify this default, and must be
7844 used for all units in the partition.
7845 This option can only be used if the zero cost approach
7846 is available for the target in use, otherwise it will generate an error.
7847 @end table
7848
7849 @noindent
7850 The same option @option{--RTS} must be used both for @command{gcc}
7851 and @command{gnatbind}. Passing this option to @command{gnatmake}
7852 (@pxref{Switches for gnatmake}) will ensure the required consistency
7853 through the compilation and binding steps.
7854
7855 @node Units to Sources Mapping Files
7856 @subsection Units to Sources Mapping Files
7857
7858 @table @option
7859
7860 @item -gnatem=@var{path}
7861 @cindex @option{-gnatem} (@command{gcc})
7862 A mapping file is a way to communicate to the compiler two mappings:
7863 from unit names to file names (without any directory information) and from
7864 file names to path names (with full directory information). These mappings
7865 are used by the compiler to short-circuit the path search.
7866
7867 The use of mapping files is not required for correct operation of the
7868 compiler, but mapping files can improve efficiency, particularly when
7869 sources are read over a slow network connection. In normal operation,
7870 you need not be concerned with the format or use of mapping files,
7871 and the @option{-gnatem} switch is not a switch that you would use
7872 explicitly. It is intended primarily for use by automatic tools such as
7873 @command{gnatmake} running under the project file facility. The
7874 description here of the format of mapping files is provided
7875 for completeness and for possible use by other tools.
7876
7877 A mapping file is a sequence of sets of three lines. In each set, the
7878 first line is the unit name, in lower case, with @code{%s} appended
7879 for specs and @code{%b} appended for bodies; the second line is the
7880 file name; and the third line is the path name.
7881
7882 Example:
7883 @smallexample
7884 main%b
7885 main.2.ada
7886 /gnat/project1/sources/main.2.ada
7887 @end smallexample
7888
7889 When the switch @option{-gnatem} is specified, the compiler will
7890 create in memory the two mappings from the specified file. If there is
7891 any problem (nonexistent file, truncated file or duplicate entries),
7892 no mapping will be created.
7893
7894 Several @option{-gnatem} switches may be specified; however, only the
7895 last one on the command line will be taken into account.
7896
7897 When using a project file, @command{gnatmake} creates a temporary
7898 mapping file and communicates it to the compiler using this switch.
7899
7900 @end table
7901
7902 @node Integrated Preprocessing
7903 @subsection Integrated Preprocessing
7904
7905 @noindent
7906 GNAT sources may be preprocessed immediately before compilation.
7907 In this case, the actual
7908 text of the source is not the text of the source file, but is derived from it
7909 through a process called preprocessing. Integrated preprocessing is specified
7910 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7911 indicates, through a text file, the preprocessing data to be used.
7912 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7913
7914 @noindent
7915 Note that when integrated preprocessing is used, the output from the
7916 preprocessor is not written to any external file. Instead it is passed
7917 internally to the compiler. If you need to preserve the result of
7918 preprocessing in a file, then you should use @command{gnatprep}
7919 to perform the desired preprocessing in stand-alone mode.
7920
7921 @noindent
7922 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7923 used when Integrated Preprocessing is used. The reason is that preprocessing
7924 with another Preprocessing Data file without changing the sources will
7925 not trigger recompilation without this switch.
7926
7927 @noindent
7928 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7929 always trigger recompilation for sources that are preprocessed,
7930 because @command{gnatmake} cannot compute the checksum of the source after
7931 preprocessing.
7932
7933 @noindent
7934 The actual preprocessing function is described in details in section
7935 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7936 preprocessing is triggered and parameterized.
7937
7938 @table @code
7939
7940 @item -gnatep=@var{file}
7941 @cindex @option{-gnatep} (@command{gcc})
7942 This switch indicates to the compiler the file name (without directory
7943 information) of the preprocessor data file to use. The preprocessor data file
7944 should be found in the source directories. Note that when the compiler is
7945 called by a builder such as (@command{gnatmake} with a project
7946 file, if the object directory is not also a source directory, the builder needs
7947 to be called with @option{-x}.
7948
7949 @noindent
7950 A preprocessing data file is a text file with significant lines indicating
7951 how should be preprocessed either a specific source or all sources not
7952 mentioned in other lines. A significant line is a nonempty, non-comment line.
7953 Comments are similar to Ada comments.
7954
7955 @noindent
7956 Each significant line starts with either a literal string or the character '*'.
7957 A literal string is the file name (without directory information) of the source
7958 to preprocess. A character '*' indicates the preprocessing for all the sources
7959 that are not specified explicitly on other lines (order of the lines is not
7960 significant). It is an error to have two lines with the same file name or two
7961 lines starting with the character '*'.
7962
7963 @noindent
7964 After the file name or the character '*', another optional literal string
7965 indicating the file name of the definition file to be used for preprocessing
7966 (@pxref{Form of Definitions File}). The definition files are found by the
7967 compiler in one of the source directories. In some cases, when compiling
7968 a source in a directory other than the current directory, if the definition
7969 file is in the current directory, it may be necessary to add the current
7970 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7971 the compiler would not find the definition file.
7972
7973 @noindent
7974 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7975 be found. Those ^switches^switches^ are:
7976
7977 @table @code
7978
7979 @item -b
7980 Causes both preprocessor lines and the lines deleted by
7981 preprocessing to be replaced by blank lines, preserving the line number.
7982 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7983 it cancels the effect of @option{-c}.
7984
7985 @item -c
7986 Causes both preprocessor lines and the lines deleted
7987 by preprocessing to be retained as comments marked
7988 with the special string ``@code{--! }''.
7989
7990 @item -Dsymbol=value
7991 Define or redefine a symbol, associated with value. A symbol is an Ada
7992 identifier, or an Ada reserved word, with the exception of @code{if},
7993 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7994 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7995 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7996 same name defined in a definition file.
7997
7998 @item -s
7999 Causes a sorted list of symbol names and values to be
8000 listed on the standard output file.
8001
8002 @item -u
8003 Causes undefined symbols to be treated as having the value @code{FALSE}
8004 in the context
8005 of a preprocessor test. In the absence of this option, an undefined symbol in
8006 a @code{#if} or @code{#elsif} test will be treated as an error.
8007
8008 @end table
8009
8010 @noindent
8011 Examples of valid lines in a preprocessor data file:
8012
8013 @smallexample
8014 "toto.adb" "prep.def" -u
8015 -- preprocess "toto.adb", using definition file "prep.def",
8016 -- undefined symbol are False.
8017
8018 * -c -DVERSION=V101
8019 -- preprocess all other sources without a definition file;
8020 -- suppressed lined are commented; symbol VERSION has the value V101.
8021
8022 "titi.adb" "prep2.def" -s
8023 -- preprocess "titi.adb", using definition file "prep2.def";
8024 -- list all symbols with their values.
8025 @end smallexample
8026
8027 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
8028 @cindex @option{-gnateD} (@command{gcc})
8029 Define or redefine a preprocessing symbol, associated with value. If no value
8030 is given on the command line, then the value of the symbol is @code{True}.
8031 A symbol is an identifier, following normal Ada (case-insensitive)
8032 rules for its syntax, and value is any sequence (including an empty sequence)
8033 of characters from the set (letters, digits, period, underline).
8034 Ada reserved words may be used as symbols, with the exceptions of @code{if},
8035 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
8036
8037 @noindent
8038 A symbol declared with this ^switch^switch^ on the command line replaces a
8039 symbol with the same name either in a definition file or specified with a
8040 ^switch^switch^ -D in the preprocessor data file.
8041
8042 @noindent
8043 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
8044
8045 @item -gnateG
8046 When integrated preprocessing is performed and the preprocessor modifies
8047 the source text, write the result of this preprocessing into a file
8048 <source>^.prep^_prep^.
8049
8050 @end table
8051
8052 @node Code Generation Control
8053 @subsection Code Generation Control
8054
8055 @noindent
8056
8057 The GCC technology provides a wide range of target dependent
8058 @option{-m} switches for controlling
8059 details of code generation with respect to different versions of
8060 architectures. This includes variations in instruction sets (e.g.@:
8061 different members of the power pc family), and different requirements
8062 for optimal arrangement of instructions (e.g.@: different members of
8063 the x86 family). The list of available @option{-m} switches may be
8064 found in the GCC documentation.
8065
8066 Use of these @option{-m} switches may in some cases result in improved
8067 code performance.
8068
8069 The @value{EDITION} technology is tested and qualified without any
8070 @option{-m} switches,
8071 so generally the most reliable approach is to avoid the use of these
8072 switches. However, we generally expect most of these switches to work
8073 successfully with @value{EDITION}, and many customers have reported successful
8074 use of these options.
8075
8076 Our general advice is to avoid the use of @option{-m} switches unless
8077 special needs lead to requirements in this area. In particular,
8078 there is no point in using @option{-m} switches to improve performance
8079 unless you actually see a performance improvement.
8080
8081 @ifset vms
8082 @node Return Codes
8083 @subsection Return Codes
8084 @cindex Return Codes
8085 @cindex @option{/RETURN_CODES=VMS}
8086
8087 @noindent
8088 On VMS, GNAT compiled programs return POSIX-style codes by default,
8089 e.g.@: @option{/RETURN_CODES=POSIX}.
8090
8091 To enable VMS style return codes, use GNAT BIND and LINK with the option
8092 @option{/RETURN_CODES=VMS}. For example:
8093
8094 @smallexample
8095 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
8096 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
8097 @end smallexample
8098
8099 @noindent
8100 Programs built with /RETURN_CODES=VMS are suitable to be called in
8101 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
8102 are suitable for spawning with appropriate GNAT RTL routines.
8103
8104 @end ifset
8105
8106 @node Search Paths and the Run-Time Library (RTL)
8107 @section Search Paths and the Run-Time Library (RTL)
8108
8109 @noindent
8110 With the GNAT source-based library system, the compiler must be able to
8111 find source files for units that are needed by the unit being compiled.
8112 Search paths are used to guide this process.
8113
8114 The compiler compiles one source file whose name must be given
8115 explicitly on the command line. In other words, no searching is done
8116 for this file. To find all other source files that are needed (the most
8117 common being the specs of units), the compiler examines the following
8118 directories, in the following order:
8119
8120 @enumerate
8121 @item
8122 The directory containing the source file of the main unit being compiled
8123 (the file name on the command line).
8124
8125 @item
8126 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8127 @command{gcc} command line, in the order given.
8128
8129 @item
8130 @findex ADA_PRJ_INCLUDE_FILE
8131 Each of the directories listed in the text file whose name is given
8132 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8133
8134 @noindent
8135 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8136 driver when project files are used. It should not normally be set
8137 by other means.
8138
8139 @item
8140 @findex ADA_INCLUDE_PATH
8141 Each of the directories listed in the value of the
8142 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8143 @ifclear vms
8144 Construct this value
8145 exactly as the @env{PATH} environment variable: a list of directory
8146 names separated by colons (semicolons when working with the NT version).
8147 @end ifclear
8148 @ifset vms
8149 Normally, define this value as a logical name containing a comma separated
8150 list of directory names.
8151
8152 This variable can also be defined by means of an environment string
8153 (an argument to the HP C exec* set of functions).
8154
8155 Logical Name:
8156 @smallexample
8157 DEFINE ANOTHER_PATH FOO:[BAG]
8158 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8159 @end smallexample
8160
8161 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8162 first, followed by the standard Ada
8163 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8164 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8165 (Text_IO, Sequential_IO, etc)
8166 instead of the standard Ada packages. Thus, in order to get the standard Ada
8167 packages by default, ADA_INCLUDE_PATH must be redefined.
8168 @end ifset
8169
8170 @item
8171 The content of the @file{ada_source_path} file which is part of the GNAT
8172 installation tree and is used to store standard libraries such as the
8173 GNAT Run Time Library (RTL) source files.
8174 @ifclear vms
8175 @ref{Installing a library}
8176 @end ifclear
8177 @end enumerate
8178
8179 @noindent
8180 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8181 inhibits the use of the directory
8182 containing the source file named in the command line. You can still
8183 have this directory on your search path, but in this case it must be
8184 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8185
8186 Specifying the switch @option{-nostdinc}
8187 inhibits the search of the default location for the GNAT Run Time
8188 Library (RTL) source files.
8189
8190 The compiler outputs its object files and ALI files in the current
8191 working directory.
8192 @ifclear vms
8193 Caution: The object file can be redirected with the @option{-o} switch;
8194 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8195 so the @file{ALI} file will not go to the right place. Therefore, you should
8196 avoid using the @option{-o} switch.
8197 @end ifclear
8198
8199 @findex System.IO
8200 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8201 children make up the GNAT RTL, together with the simple @code{System.IO}
8202 package used in the @code{"Hello World"} example. The sources for these units
8203 are needed by the compiler and are kept together in one directory. Not
8204 all of the bodies are needed, but all of the sources are kept together
8205 anyway. In a normal installation, you need not specify these directory
8206 names when compiling or binding. Either the environment variables or
8207 the built-in defaults cause these files to be found.
8208
8209 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8210 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8211 consisting of child units of @code{GNAT}. This is a collection of generally
8212 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8213 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8214
8215 Besides simplifying access to the RTL, a major use of search paths is
8216 in compiling sources from multiple directories. This can make
8217 development environments much more flexible.
8218
8219 @node Order of Compilation Issues
8220 @section Order of Compilation Issues
8221
8222 @noindent
8223 If, in our earlier example, there was a spec for the @code{hello}
8224 procedure, it would be contained in the file @file{hello.ads}; yet this
8225 file would not have to be explicitly compiled. This is the result of the
8226 model we chose to implement library management. Some of the consequences
8227 of this model are as follows:
8228
8229 @itemize @bullet
8230 @item
8231 There is no point in compiling specs (except for package
8232 specs with no bodies) because these are compiled as needed by clients. If
8233 you attempt a useless compilation, you will receive an error message.
8234 It is also useless to compile subunits because they are compiled as needed
8235 by the parent.
8236
8237 @item
8238 There are no order of compilation requirements: performing a
8239 compilation never obsoletes anything. The only way you can obsolete
8240 something and require recompilations is to modify one of the
8241 source files on which it depends.
8242
8243 @item
8244 There is no library as such, apart from the ALI files
8245 (@pxref{The Ada Library Information Files}, for information on the format
8246 of these files). For now we find it convenient to create separate ALI files,
8247 but eventually the information therein may be incorporated into the object
8248 file directly.
8249
8250 @item
8251 When you compile a unit, the source files for the specs of all units
8252 that it @code{with}'s, all its subunits, and the bodies of any generics it
8253 instantiates must be available (reachable by the search-paths mechanism
8254 described above), or you will receive a fatal error message.
8255 @end itemize
8256
8257 @node Examples
8258 @section Examples
8259
8260 @noindent
8261 The following are some typical Ada compilation command line examples:
8262
8263 @table @code
8264 @item $ gcc -c xyz.adb
8265 Compile body in file @file{xyz.adb} with all default options.
8266
8267 @ifclear vms
8268 @item $ gcc -c -O2 -gnata xyz-def.adb
8269 @end ifclear
8270 @ifset vms
8271 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8272 @end ifset
8273
8274 Compile the child unit package in file @file{xyz-def.adb} with extensive
8275 optimizations, and pragma @code{Assert}/@code{Debug} statements
8276 enabled.
8277
8278 @item $ gcc -c -gnatc abc-def.adb
8279 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8280 mode.
8281 @end table
8282
8283 @node Binding Using gnatbind
8284 @chapter Binding Using @code{gnatbind}
8285 @findex gnatbind
8286
8287 @menu
8288 * Running gnatbind::
8289 * Switches for gnatbind::
8290 * Command-Line Access::
8291 * Search Paths for gnatbind::
8292 * Examples of gnatbind Usage::
8293 @end menu
8294
8295 @noindent
8296 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8297 to bind compiled GNAT objects.
8298
8299 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8300 driver (see @ref{The GNAT Driver and Project Files}).
8301
8302 The @code{gnatbind} program performs four separate functions:
8303
8304 @enumerate
8305 @item
8306 Checks that a program is consistent, in accordance with the rules in
8307 Chapter 10 of the Ada Reference Manual. In particular, error
8308 messages are generated if a program uses inconsistent versions of a
8309 given unit.
8310
8311 @item
8312 Checks that an acceptable order of elaboration exists for the program
8313 and issues an error message if it cannot find an order of elaboration
8314 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8315
8316 @item
8317 Generates a main program incorporating the given elaboration order.
8318 This program is a small Ada package (body and spec) that
8319 must be subsequently compiled
8320 using the GNAT compiler. The necessary compilation step is usually
8321 performed automatically by @command{gnatlink}. The two most important
8322 functions of this program
8323 are to call the elaboration routines of units in an appropriate order
8324 and to call the main program.
8325
8326 @item
8327 Determines the set of object files required by the given main program.
8328 This information is output in the forms of comments in the generated program,
8329 to be read by the @command{gnatlink} utility used to link the Ada application.
8330 @end enumerate
8331
8332 @node Running gnatbind
8333 @section Running @code{gnatbind}
8334
8335 @noindent
8336 The form of the @code{gnatbind} command is
8337
8338 @smallexample
8339 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8340 @c Expanding @ovar macro inline (explanation in macro def comments)
8341 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8342 @end smallexample
8343
8344 @noindent
8345 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8346 unit body. @code{gnatbind} constructs an Ada
8347 package in two files whose names are
8348 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8349 For example, if given the
8350 parameter @file{hello.ali}, for a main program contained in file
8351 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8352 and @file{b~hello.adb}.
8353
8354 When doing consistency checking, the binder takes into consideration
8355 any source files it can locate. For example, if the binder determines
8356 that the given main program requires the package @code{Pack}, whose
8357 @file{.ALI}
8358 file is @file{pack.ali} and whose corresponding source spec file is
8359 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8360 (using the same search path conventions as previously described for the
8361 @command{gcc} command). If it can locate this source file, it checks that
8362 the time stamps
8363 or source checksums of the source and its references to in @file{ALI} files
8364 match. In other words, any @file{ALI} files that mentions this spec must have
8365 resulted from compiling this version of the source file (or in the case
8366 where the source checksums match, a version close enough that the
8367 difference does not matter).
8368
8369 @cindex Source files, use by binder
8370 The effect of this consistency checking, which includes source files, is
8371 that the binder ensures that the program is consistent with the latest
8372 version of the source files that can be located at bind time. Editing a
8373 source file without compiling files that depend on the source file cause
8374 error messages to be generated by the binder.
8375
8376 For example, suppose you have a main program @file{hello.adb} and a
8377 package @code{P}, from file @file{p.ads} and you perform the following
8378 steps:
8379
8380 @enumerate
8381 @item
8382 Enter @code{gcc -c hello.adb} to compile the main program.
8383
8384 @item
8385 Enter @code{gcc -c p.ads} to compile package @code{P}.
8386
8387 @item
8388 Edit file @file{p.ads}.
8389
8390 @item
8391 Enter @code{gnatbind hello}.
8392 @end enumerate
8393
8394 @noindent
8395 At this point, the file @file{p.ali} contains an out-of-date time stamp
8396 because the file @file{p.ads} has been edited. The attempt at binding
8397 fails, and the binder generates the following error messages:
8398
8399 @smallexample
8400 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8401 error: "p.ads" has been modified and must be recompiled
8402 @end smallexample
8403
8404 @noindent
8405 Now both files must be recompiled as indicated, and then the bind can
8406 succeed, generating a main program. You need not normally be concerned
8407 with the contents of this file, but for reference purposes a sample
8408 binder output file is given in @ref{Example of Binder Output File}.
8409
8410 In most normal usage, the default mode of @command{gnatbind} which is to
8411 generate the main package in Ada, as described in the previous section.
8412 In particular, this means that any Ada programmer can read and understand
8413 the generated main program. It can also be debugged just like any other
8414 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8415 @command{gnatbind} and @command{gnatlink}.
8416
8417 @node Switches for gnatbind
8418 @section Switches for @command{gnatbind}
8419
8420 @noindent
8421 The following switches are available with @code{gnatbind}; details will
8422 be presented in subsequent sections.
8423
8424 @menu
8425 * Consistency-Checking Modes::
8426 * Binder Error Message Control::
8427 * Elaboration Control::
8428 * Output Control::
8429 * Dynamic Allocation Control::
8430 * Binding with Non-Ada Main Programs::
8431 * Binding Programs with No Main Subprogram::
8432 @end menu
8433
8434 @table @option
8435 @c !sort!
8436
8437 @item --version
8438 @cindex @option{--version} @command{gnatbind}
8439 Display Copyright and version, then exit disregarding all other options.
8440
8441 @item --help
8442 @cindex @option{--help} @command{gnatbind}
8443 If @option{--version} was not used, display usage, then exit disregarding
8444 all other options.
8445
8446 @item -a
8447 @cindex @option{-a} @command{gnatbind}
8448 Indicates that, if supported by the platform, the adainit procedure should
8449 be treated as an initialisation routine by the linker (a constructor). This
8450 is intended to be used by the Project Manager to automatically initialize
8451 shared Stand-Alone Libraries.
8452
8453 @item ^-aO^/OBJECT_SEARCH^
8454 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8455 Specify directory to be searched for ALI files.
8456
8457 @item ^-aI^/SOURCE_SEARCH^
8458 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8459 Specify directory to be searched for source file.
8460
8461 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8462 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8463 Output ALI list (to standard output or to the named file).
8464
8465 @item ^-b^/REPORT_ERRORS=BRIEF^
8466 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8467 Generate brief messages to @file{stderr} even if verbose mode set.
8468
8469 @item ^-c^/NOOUTPUT^
8470 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8471 Check only, no generation of binder output file.
8472
8473 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8474 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8475 This switch can be used to change the default task stack size value
8476 to a specified size @var{nn}, which is expressed in bytes by default, or
8477 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8478 with @var{m}.
8479 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8480 in effect, to completing all task specs with
8481 @smallexample @c ada
8482 pragma Storage_Size (nn);
8483 @end smallexample
8484 When they do not already have such a pragma.
8485
8486 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8487 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8488 This switch can be used to change the default secondary stack size value
8489 to a specified size @var{nn}, which is expressed in bytes by default, or
8490 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8491 with @var{m}.
8492
8493 The secondary stack is used to deal with functions that return a variable
8494 sized result, for example a function returning an unconstrained
8495 String. There are two ways in which this secondary stack is allocated.
8496
8497 For most targets, the secondary stack is growing on demand and is allocated
8498 as a chain of blocks in the heap. The -D option is not very
8499 relevant. It only give some control over the size of the allocated
8500 blocks (whose size is the minimum of the default secondary stack size value,
8501 and the actual size needed for the current allocation request).
8502
8503 For certain targets, notably VxWorks 653,
8504 the secondary stack is allocated by carving off a fixed ratio chunk of the
8505 primary task stack. The -D option is used to define the
8506 size of the environment task's secondary stack.
8507
8508 @item ^-e^/ELABORATION_DEPENDENCIES^
8509 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8510 Output complete list of elaboration-order dependencies.
8511
8512 @item ^-E^/STORE_TRACEBACKS^
8513 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8514 Store tracebacks in exception occurrences when the target supports it.
8515 @ignore
8516 @c The following may get moved to an appendix
8517 This option is currently supported on the following targets:
8518 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8519 @end ignore
8520 See also the packages @code{GNAT.Traceback} and
8521 @code{GNAT.Traceback.Symbolic} for more information.
8522 @ifclear vms
8523 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8524 @command{gcc} option.
8525 @end ifclear
8526
8527 @item ^-F^/FORCE_ELABS_FLAGS^
8528 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8529 Force the checks of elaboration flags. @command{gnatbind} does not normally
8530 generate checks of elaboration flags for the main executable, except when
8531 a Stand-Alone Library is used. However, there are cases when this cannot be
8532 detected by gnatbind. An example is importing an interface of a Stand-Alone
8533 Library through a pragma Import and only specifying through a linker switch
8534 this Stand-Alone Library. This switch is used to guarantee that elaboration
8535 flag checks are generated.
8536
8537 @item ^-h^/HELP^
8538 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8539 Output usage (help) information
8540
8541 @item ^-H32^/32_MALLOC^
8542 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8543 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8544 For further details see @ref{Dynamic Allocation Control}.
8545
8546 @item ^-H64^/64_MALLOC^
8547 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8548 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8549 @cindex @code{__gnat_malloc}
8550 For further details see @ref{Dynamic Allocation Control}.
8551
8552 @item ^-I^/SEARCH^
8553 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8554 Specify directory to be searched for source and ALI files.
8555
8556 @item ^-I-^/NOCURRENT_DIRECTORY^
8557 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8558 Do not look for sources in the current directory where @code{gnatbind} was
8559 invoked, and do not look for ALI files in the directory containing the
8560 ALI file named in the @code{gnatbind} command line.
8561
8562 @item ^-l^/ORDER_OF_ELABORATION^
8563 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8564 Output chosen elaboration order.
8565
8566 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8567 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8568 Bind the units for library building. In this case the adainit and
8569 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8570 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8571 ^@var{xxx}final^@var{XXX}FINAL^.
8572 Implies ^-n^/NOCOMPILE^.
8573 @ifclear vms
8574 (@xref{GNAT and Libraries}, for more details.)
8575 @end ifclear
8576 @ifset vms
8577 On OpenVMS, these init and final procedures are exported in uppercase
8578 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8579 the init procedure will be "TOTOINIT" and the exported name of the final
8580 procedure will be "TOTOFINAL".
8581 @end ifset
8582
8583 @item ^-Mxyz^/RENAME_MAIN=xyz^
8584 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8585 Rename generated main program from main to xyz. This option is
8586 supported on cross environments only.
8587
8588 @item ^-m^/ERROR_LIMIT=^@var{n}
8589 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8590 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8591 in the range 1..999999. The default value if no switch is
8592 given is 9999. If the number of warnings reaches this limit, then a
8593 message is output and further warnings are suppressed, the bind
8594 continues in this case. If the number of errors reaches this
8595 limit, then a message is output and the bind is abandoned.
8596 A value of zero means that no limit is enforced. The equal
8597 sign is optional.
8598
8599 @ifset unw
8600 Furthermore, under Windows, the sources pointed to by the libraries path
8601 set in the registry are not searched for.
8602 @end ifset
8603
8604 @item ^-n^/NOMAIN^
8605 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8606 No main program.
8607
8608 @item -nostdinc
8609 @cindex @option{-nostdinc} (@command{gnatbind})
8610 Do not look for sources in the system default directory.
8611
8612 @item -nostdlib
8613 @cindex @option{-nostdlib} (@command{gnatbind})
8614 Do not look for library files in the system default directory.
8615
8616 @item --RTS=@var{rts-path}
8617 @cindex @option{--RTS} (@code{gnatbind})
8618 Specifies the default location of the runtime library. Same meaning as the
8619 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8620
8621 @item ^-o ^/OUTPUT=^@var{file}
8622 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8623 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8624 Note that if this option is used, then linking must be done manually,
8625 gnatlink cannot be used.
8626
8627 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8628 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8629 Output object list (to standard output or to the named file).
8630
8631 @item ^-p^/PESSIMISTIC_ELABORATION^
8632 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8633 Pessimistic (worst-case) elaboration order
8634
8635 @item ^-P^-P^
8636 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8637 Generate binder file suitable for CodePeer.
8638
8639 @item ^-R^-R^
8640 @cindex @option{^-R^-R^} (@command{gnatbind})
8641 Output closure source list.
8642
8643 @item ^-s^/READ_SOURCES=ALL^
8644 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8645 Require all source files to be present.
8646
8647 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8648 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8649 Specifies the value to be used when detecting uninitialized scalar
8650 objects with pragma Initialize_Scalars.
8651 The @var{xxx} ^string specified with the switch^option^ may be either
8652 @itemize @bullet
8653 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8654 @item ``@option{^lo^LOW^}'' for the lowest possible value
8655 @item ``@option{^hi^HIGH^}'' for the highest possible value
8656 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8657 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8658 @end itemize
8659
8660 In addition, you can specify @option{-Sev} to indicate that the value is
8661 to be set at run time. In this case, the program will look for an environment
8662 @cindex GNAT_INIT_SCALARS
8663 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8664 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8665 If no environment variable is found, or if it does not have a valid value,
8666 then the default is @option{in} (invalid values).
8667
8668 @ifclear vms
8669 @item -static
8670 @cindex @option{-static} (@code{gnatbind})
8671 Link against a static GNAT run time.
8672
8673 @item -shared
8674 @cindex @option{-shared} (@code{gnatbind})
8675 Link against a shared GNAT run time when available.
8676 @end ifclear
8677
8678 @item ^-t^/NOTIME_STAMP_CHECK^
8679 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8680 Tolerate time stamp and other consistency errors
8681
8682 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8683 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8684 Set the time slice value to @var{n} milliseconds. If the system supports
8685 the specification of a specific time slice value, then the indicated value
8686 is used. If the system does not support specific time slice values, but
8687 does support some general notion of round-robin scheduling, then any
8688 nonzero value will activate round-robin scheduling.
8689
8690 A value of zero is treated specially. It turns off time
8691 slicing, and in addition, indicates to the tasking run time that the
8692 semantics should match as closely as possible the Annex D
8693 requirements of the Ada RM, and in particular sets the default
8694 scheduling policy to @code{FIFO_Within_Priorities}.
8695
8696 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8697 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8698 Enable dynamic stack usage, with @var{n} results stored and displayed
8699 at program termination. A result is generated when a task
8700 terminates. Results that can't be stored are displayed on the fly, at
8701 task termination. This option is currently not supported on Itanium
8702 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8703
8704 @item ^-v^/REPORT_ERRORS=VERBOSE^
8705 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8706 Verbose mode. Write error messages, header, summary output to
8707 @file{stdout}.
8708
8709 @ifclear vms
8710 @item -w@var{x}
8711 @cindex @option{-w} (@code{gnatbind})
8712 Warning mode (@var{x}=s/e for suppress/treat as error)
8713 @end ifclear
8714
8715 @ifset vms
8716 @item /WARNINGS=NORMAL
8717 @cindex @option{/WARNINGS} (@code{gnatbind})
8718 Normal warnings mode. Warnings are issued but ignored
8719
8720 @item /WARNINGS=SUPPRESS
8721 @cindex @option{/WARNINGS} (@code{gnatbind})
8722 All warning messages are suppressed
8723
8724 @item /WARNINGS=ERROR
8725 @cindex @option{/WARNINGS} (@code{gnatbind})
8726 Warning messages are treated as fatal errors
8727 @end ifset
8728
8729 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8730 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8731 Override default wide character encoding for standard Text_IO files.
8732
8733 @item ^-x^/READ_SOURCES=NONE^
8734 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8735 Exclude source files (check object consistency only).
8736
8737 @ifset vms
8738 @item /READ_SOURCES=AVAILABLE
8739 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8740 Default mode, in which sources are checked for consistency only if
8741 they are available.
8742 @end ifset
8743
8744 @item ^-y^/ENABLE_LEAP_SECONDS^
8745 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8746 Enable leap seconds support in @code{Ada.Calendar} and its children.
8747
8748 @item ^-z^/ZERO_MAIN^
8749 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8750 No main subprogram.
8751 @end table
8752
8753 @ifclear vms
8754 @noindent
8755 You may obtain this listing of switches by running @code{gnatbind} with
8756 no arguments.
8757 @end ifclear
8758
8759 @node Consistency-Checking Modes
8760 @subsection Consistency-Checking Modes
8761
8762 @noindent
8763 As described earlier, by default @code{gnatbind} checks
8764 that object files are consistent with one another and are consistent
8765 with any source files it can locate. The following switches control binder
8766 access to sources.
8767
8768 @table @option
8769 @c !sort!
8770 @item ^-s^/READ_SOURCES=ALL^
8771 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8772 Require source files to be present. In this mode, the binder must be
8773 able to locate all source files that are referenced, in order to check
8774 their consistency. In normal mode, if a source file cannot be located it
8775 is simply ignored. If you specify this switch, a missing source
8776 file is an error.
8777
8778 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8779 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8780 Override default wide character encoding for standard Text_IO files.
8781 Normally the default wide character encoding method used for standard
8782 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8783 the main source input (see description of switch
8784 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8785 use of this switch for the binder (which has the same set of
8786 possible arguments) overrides this default as specified.
8787
8788 @item ^-x^/READ_SOURCES=NONE^
8789 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8790 Exclude source files. In this mode, the binder only checks that ALI
8791 files are consistent with one another. Source files are not accessed.
8792 The binder runs faster in this mode, and there is still a guarantee that
8793 the resulting program is self-consistent.
8794 If a source file has been edited since it was last compiled, and you
8795 specify this switch, the binder will not detect that the object
8796 file is out of date with respect to the source file. Note that this is the
8797 mode that is automatically used by @command{gnatmake} because in this
8798 case the checking against sources has already been performed by
8799 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8800
8801 @ifset vms
8802 @item /READ_SOURCES=AVAILABLE
8803 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8804 This is the default mode in which source files are checked if they are
8805 available, and ignored if they are not available.
8806 @end ifset
8807 @end table
8808
8809 @node Binder Error Message Control
8810 @subsection Binder Error Message Control
8811
8812 @noindent
8813 The following switches provide control over the generation of error
8814 messages from the binder:
8815
8816 @table @option
8817 @c !sort!
8818 @item ^-v^/REPORT_ERRORS=VERBOSE^
8819 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8820 Verbose mode. In the normal mode, brief error messages are generated to
8821 @file{stderr}. If this switch is present, a header is written
8822 to @file{stdout} and any error messages are directed to @file{stdout}.
8823 All that is written to @file{stderr} is a brief summary message.
8824
8825 @item ^-b^/REPORT_ERRORS=BRIEF^
8826 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8827 Generate brief error messages to @file{stderr} even if verbose mode is
8828 specified. This is relevant only when used with the
8829 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8830
8831 @ifclear vms
8832 @item -m@var{n}
8833 @cindex @option{-m} (@code{gnatbind})
8834 Limits the number of error messages to @var{n}, a decimal integer in the
8835 range 1-999. The binder terminates immediately if this limit is reached.
8836
8837 @item -M@var{xxx}
8838 @cindex @option{-M} (@code{gnatbind})
8839 Renames the generated main program from @code{main} to @code{xxx}.
8840 This is useful in the case of some cross-building environments, where
8841 the actual main program is separate from the one generated
8842 by @code{gnatbind}.
8843 @end ifclear
8844
8845 @item ^-ws^/WARNINGS=SUPPRESS^
8846 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8847 @cindex Warnings
8848 Suppress all warning messages.
8849
8850 @item ^-we^/WARNINGS=ERROR^
8851 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8852 Treat any warning messages as fatal errors.
8853
8854 @ifset vms
8855 @item /WARNINGS=NORMAL
8856 Standard mode with warnings generated, but warnings do not get treated
8857 as errors.
8858 @end ifset
8859
8860 @item ^-t^/NOTIME_STAMP_CHECK^
8861 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8862 @cindex Time stamp checks, in binder
8863 @cindex Binder consistency checks
8864 @cindex Consistency checks, in binder
8865 The binder performs a number of consistency checks including:
8866
8867 @itemize @bullet
8868 @item
8869 Check that time stamps of a given source unit are consistent
8870 @item
8871 Check that checksums of a given source unit are consistent
8872 @item
8873 Check that consistent versions of @code{GNAT} were used for compilation
8874 @item
8875 Check consistency of configuration pragmas as required
8876 @end itemize
8877
8878 @noindent
8879 Normally failure of such checks, in accordance with the consistency
8880 requirements of the Ada Reference Manual, causes error messages to be
8881 generated which abort the binder and prevent the output of a binder
8882 file and subsequent link to obtain an executable.
8883
8884 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8885 into warnings, so that
8886 binding and linking can continue to completion even in the presence of such
8887 errors. The result may be a failed link (due to missing symbols), or a
8888 non-functional executable which has undefined semantics.
8889 @emph{This means that
8890 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8891 with extreme care.}
8892 @end table
8893
8894 @node Elaboration Control
8895 @subsection Elaboration Control
8896
8897 @noindent
8898 The following switches provide additional control over the elaboration
8899 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8900
8901 @table @option
8902 @item ^-p^/PESSIMISTIC_ELABORATION^
8903 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8904 Normally the binder attempts to choose an elaboration order that is
8905 likely to minimize the likelihood of an elaboration order error resulting
8906 in raising a @code{Program_Error} exception. This switch reverses the
8907 action of the binder, and requests that it deliberately choose an order
8908 that is likely to maximize the likelihood of an elaboration error.
8909 This is useful in ensuring portability and avoiding dependence on
8910 accidental fortuitous elaboration ordering.
8911
8912 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8913 switch if dynamic
8914 elaboration checking is used (@option{-gnatE} switch used for compilation).
8915 This is because in the default static elaboration mode, all necessary
8916 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8917 These implicit pragmas are still respected by the binder in
8918 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8919 safe elaboration order is assured.
8920
8921 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8922 production use; it is more for debugging/experimental use.
8923 @end table
8924
8925 @node Output Control
8926 @subsection Output Control
8927
8928 @noindent
8929 The following switches allow additional control over the output
8930 generated by the binder.
8931
8932 @table @option
8933 @c !sort!
8934
8935 @item ^-c^/NOOUTPUT^
8936 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8937 Check only. Do not generate the binder output file. In this mode the
8938 binder performs all error checks but does not generate an output file.
8939
8940 @item ^-e^/ELABORATION_DEPENDENCIES^
8941 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8942 Output complete list of elaboration-order dependencies, showing the
8943 reason for each dependency. This output can be rather extensive but may
8944 be useful in diagnosing problems with elaboration order. The output is
8945 written to @file{stdout}.
8946
8947 @item ^-h^/HELP^
8948 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8949 Output usage information. The output is written to @file{stdout}.
8950
8951 @item ^-K^/LINKER_OPTION_LIST^
8952 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8953 Output linker options to @file{stdout}. Includes library search paths,
8954 contents of pragmas Ident and Linker_Options, and libraries added
8955 by @code{gnatbind}.
8956
8957 @item ^-l^/ORDER_OF_ELABORATION^
8958 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8959 Output chosen elaboration order. The output is written to @file{stdout}.
8960
8961 @item ^-O^/OBJECT_LIST^
8962 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8963 Output full names of all the object files that must be linked to provide
8964 the Ada component of the program. The output is written to @file{stdout}.
8965 This list includes the files explicitly supplied and referenced by the user
8966 as well as implicitly referenced run-time unit files. The latter are
8967 omitted if the corresponding units reside in shared libraries. The
8968 directory names for the run-time units depend on the system configuration.
8969
8970 @item ^-o ^/OUTPUT=^@var{file}
8971 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8972 Set name of output file to @var{file} instead of the normal
8973 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8974 binder generated body filename.
8975 Note that if this option is used, then linking must be done manually.
8976 It is not possible to use gnatlink in this case, since it cannot locate
8977 the binder file.
8978
8979 @item ^-r^/RESTRICTION_LIST^
8980 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8981 Generate list of @code{pragma Restrictions} that could be applied to
8982 the current unit. This is useful for code audit purposes, and also may
8983 be used to improve code generation in some cases.
8984
8985 @end table
8986
8987 @node Dynamic Allocation Control
8988 @subsection Dynamic Allocation Control
8989
8990 @noindent
8991 The heap control switches -- @option{-H32} and @option{-H64} --
8992 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8993 They only affect compiler-generated allocations via @code{__gnat_malloc};
8994 explicit calls to @code{malloc} and related functions from the C
8995 run-time library are unaffected.
8996
8997 @table @option
8998 @item -H32
8999 Allocate memory on 32-bit heap
9000
9001 @item -H64
9002 Allocate memory on 64-bit heap. This is the default
9003 unless explicitly overridden by a @code{'Size} clause on the access type.
9004 @end table
9005
9006 @ifset vms
9007 @noindent
9008 See also @ref{Access types and 32/64-bit allocation}.
9009 @end ifset
9010 @ifclear vms
9011 @noindent
9012 These switches are only effective on VMS platforms.
9013 @end ifclear
9014
9015
9016 @node Binding with Non-Ada Main Programs
9017 @subsection Binding with Non-Ada Main Programs
9018
9019 @noindent
9020 In our description so far we have assumed that the main
9021 program is in Ada, and that the task of the binder is to generate a
9022 corresponding function @code{main} that invokes this Ada main
9023 program. GNAT also supports the building of executable programs where
9024 the main program is not in Ada, but some of the called routines are
9025 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
9026 The following switch is used in this situation:
9027
9028 @table @option
9029 @item ^-n^/NOMAIN^
9030 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
9031 No main program. The main program is not in Ada.
9032 @end table
9033
9034 @noindent
9035 In this case, most of the functions of the binder are still required,
9036 but instead of generating a main program, the binder generates a file
9037 containing the following callable routines:
9038
9039 @table @code
9040 @item adainit
9041 @findex adainit
9042 You must call this routine to initialize the Ada part of the program by
9043 calling the necessary elaboration routines. A call to @code{adainit} is
9044 required before the first call to an Ada subprogram.
9045
9046 Note that it is assumed that the basic execution environment must be setup
9047 to be appropriate for Ada execution at the point where the first Ada
9048 subprogram is called. In particular, if the Ada code will do any
9049 floating-point operations, then the FPU must be setup in an appropriate
9050 manner. For the case of the x86, for example, full precision mode is
9051 required. The procedure GNAT.Float_Control.Reset may be used to ensure
9052 that the FPU is in the right state.
9053
9054 @item adafinal
9055 @findex adafinal
9056 You must call this routine to perform any library-level finalization
9057 required by the Ada subprograms. A call to @code{adafinal} is required
9058 after the last call to an Ada subprogram, and before the program
9059 terminates.
9060 @end table
9061
9062 @noindent
9063 If the @option{^-n^/NOMAIN^} switch
9064 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
9065 @cindex Binder, multiple input files
9066 is given, more than one ALI file may appear on
9067 the command line for @code{gnatbind}. The normal @dfn{closure}
9068 calculation is performed for each of the specified units. Calculating
9069 the closure means finding out the set of units involved by tracing
9070 @code{with} references. The reason it is necessary to be able to
9071 specify more than one ALI file is that a given program may invoke two or
9072 more quite separate groups of Ada units.
9073
9074 The binder takes the name of its output file from the last specified ALI
9075 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
9076 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
9077 The output is an Ada unit in source form that can be compiled with GNAT.
9078 This compilation occurs automatically as part of the @command{gnatlink}
9079 processing.
9080
9081 Currently the GNAT run time requires a FPU using 80 bits mode
9082 precision. Under targets where this is not the default it is required to
9083 call GNAT.Float_Control.Reset before using floating point numbers (this
9084 include float computation, float input and output) in the Ada code. A
9085 side effect is that this could be the wrong mode for the foreign code
9086 where floating point computation could be broken after this call.
9087
9088 @node Binding Programs with No Main Subprogram
9089 @subsection Binding Programs with No Main Subprogram
9090
9091 @noindent
9092 It is possible to have an Ada program which does not have a main
9093 subprogram. This program will call the elaboration routines of all the
9094 packages, then the finalization routines.
9095
9096 The following switch is used to bind programs organized in this manner:
9097
9098 @table @option
9099 @item ^-z^/ZERO_MAIN^
9100 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
9101 Normally the binder checks that the unit name given on the command line
9102 corresponds to a suitable main subprogram. When this switch is used,
9103 a list of ALI files can be given, and the execution of the program
9104 consists of elaboration of these units in an appropriate order. Note
9105 that the default wide character encoding method for standard Text_IO
9106 files is always set to Brackets if this switch is set (you can use
9107 the binder switch
9108 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9109 @end table
9110
9111 @node Command-Line Access
9112 @section Command-Line Access
9113
9114 @noindent
9115 The package @code{Ada.Command_Line} provides access to the command-line
9116 arguments and program name. In order for this interface to operate
9117 correctly, the two variables
9118
9119 @smallexample
9120 @group
9121 int gnat_argc;
9122 char **gnat_argv;
9123 @end group
9124 @end smallexample
9125
9126 @noindent
9127 @findex gnat_argv
9128 @findex gnat_argc
9129 are declared in one of the GNAT library routines. These variables must
9130 be set from the actual @code{argc} and @code{argv} values passed to the
9131 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9132 generates the C main program to automatically set these variables.
9133 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9134 set these variables. If they are not set, the procedures in
9135 @code{Ada.Command_Line} will not be available, and any attempt to use
9136 them will raise @code{Constraint_Error}. If command line access is
9137 required, your main program must set @code{gnat_argc} and
9138 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9139 it.
9140
9141 @node Search Paths for gnatbind
9142 @section Search Paths for @code{gnatbind}
9143
9144 @noindent
9145 The binder takes the name of an ALI file as its argument and needs to
9146 locate source files as well as other ALI files to verify object consistency.
9147
9148 For source files, it follows exactly the same search rules as @command{gcc}
9149 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9150 directories searched are:
9151
9152 @enumerate
9153 @item
9154 The directory containing the ALI file named in the command line, unless
9155 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9156
9157 @item
9158 All directories specified by @option{^-I^/SEARCH^}
9159 switches on the @code{gnatbind}
9160 command line, in the order given.
9161
9162 @item
9163 @findex ADA_PRJ_OBJECTS_FILE
9164 Each of the directories listed in the text file whose name is given
9165 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9166
9167 @noindent
9168 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9169 driver when project files are used. It should not normally be set
9170 by other means.
9171
9172 @item
9173 @findex ADA_OBJECTS_PATH
9174 Each of the directories listed in the value of the
9175 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9176 @ifset unw
9177 Construct this value
9178 exactly as the @env{PATH} environment variable: a list of directory
9179 names separated by colons (semicolons when working with the NT version
9180 of GNAT).
9181 @end ifset
9182 @ifset vms
9183 Normally, define this value as a logical name containing a comma separated
9184 list of directory names.
9185
9186 This variable can also be defined by means of an environment string
9187 (an argument to the HP C exec* set of functions).
9188
9189 Logical Name:
9190 @smallexample
9191 DEFINE ANOTHER_PATH FOO:[BAG]
9192 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9193 @end smallexample
9194
9195 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9196 first, followed by the standard Ada
9197 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9198 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9199 (Text_IO, Sequential_IO, etc)
9200 instead of the standard Ada packages. Thus, in order to get the standard Ada
9201 packages by default, ADA_OBJECTS_PATH must be redefined.
9202 @end ifset
9203
9204 @item
9205 The content of the @file{ada_object_path} file which is part of the GNAT
9206 installation tree and is used to store standard libraries such as the
9207 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9208 specified.
9209 @ifclear vms
9210 @ref{Installing a library}
9211 @end ifclear
9212 @end enumerate
9213
9214 @noindent
9215 In the binder the switch @option{^-I^/SEARCH^}
9216 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9217 is used to specify both source and
9218 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9219 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9220 instead if you want to specify
9221 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9222 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9223 if you want to specify library paths
9224 only. This means that for the binder
9225 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9226 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9227 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9228 The binder generates the bind file (a C language source file) in the
9229 current working directory.
9230
9231 @findex Ada
9232 @findex System
9233 @findex Interfaces
9234 @findex GNAT
9235 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9236 children make up the GNAT Run-Time Library, together with the package
9237 GNAT and its children, which contain a set of useful additional
9238 library functions provided by GNAT. The sources for these units are
9239 needed by the compiler and are kept together in one directory. The ALI
9240 files and object files generated by compiling the RTL are needed by the
9241 binder and the linker and are kept together in one directory, typically
9242 different from the directory containing the sources. In a normal
9243 installation, you need not specify these directory names when compiling
9244 or binding. Either the environment variables or the built-in defaults
9245 cause these files to be found.
9246
9247 Besides simplifying access to the RTL, a major use of search paths is
9248 in compiling sources from multiple directories. This can make
9249 development environments much more flexible.
9250
9251 @node Examples of gnatbind Usage
9252 @section Examples of @code{gnatbind} Usage
9253
9254 @noindent
9255 This section contains a number of examples of using the GNAT binding
9256 utility @code{gnatbind}.
9257
9258 @table @code
9259 @item gnatbind hello
9260 The main program @code{Hello} (source program in @file{hello.adb}) is
9261 bound using the standard switch settings. The generated main program is
9262 @file{b~hello.adb}. This is the normal, default use of the binder.
9263
9264 @ifclear vms
9265 @item gnatbind hello -o mainprog.adb
9266 @end ifclear
9267 @ifset vms
9268 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9269 @end ifset
9270 The main program @code{Hello} (source program in @file{hello.adb}) is
9271 bound using the standard switch settings. The generated main program is
9272 @file{mainprog.adb} with the associated spec in
9273 @file{mainprog.ads}. Note that you must specify the body here not the
9274 spec. Note that if this option is used, then linking must be done manually,
9275 since gnatlink will not be able to find the generated file.
9276 @end table
9277
9278 @c ------------------------------------
9279 @node Linking Using gnatlink
9280 @chapter Linking Using @command{gnatlink}
9281 @c ------------------------------------
9282 @findex gnatlink
9283
9284 @noindent
9285 This chapter discusses @command{gnatlink}, a tool that links
9286 an Ada program and builds an executable file. This utility
9287 invokes the system linker ^(via the @command{gcc} command)^^
9288 with a correct list of object files and library references.
9289 @command{gnatlink} automatically determines the list of files and
9290 references for the Ada part of a program. It uses the binder file
9291 generated by the @command{gnatbind} to determine this list.
9292
9293 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9294 driver (see @ref{The GNAT Driver and Project Files}).
9295
9296 @menu
9297 * Running gnatlink::
9298 * Switches for gnatlink::
9299 @end menu
9300
9301 @node Running gnatlink
9302 @section Running @command{gnatlink}
9303
9304 @noindent
9305 The form of the @command{gnatlink} command is
9306
9307 @smallexample
9308 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9309 @c @ovar{non-Ada objects} @ovar{linker options}
9310 @c Expanding @ovar macro inline (explanation in macro def comments)
9311 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9312 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9313
9314 @end smallexample
9315
9316 @noindent
9317 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9318 non-Ada objects
9319 or linker options) may be in any order, provided that no non-Ada object may
9320 be mistaken for a main @file{ALI} file.
9321 Any file name @file{F} without the @file{.ali}
9322 extension will be taken as the main @file{ALI} file if a file exists
9323 whose name is the concatenation of @file{F} and @file{.ali}.
9324
9325 @noindent
9326 @file{@var{mainprog}.ali} references the ALI file of the main program.
9327 The @file{.ali} extension of this file can be omitted. From this
9328 reference, @command{gnatlink} locates the corresponding binder file
9329 @file{b~@var{mainprog}.adb} and, using the information in this file along
9330 with the list of non-Ada objects and linker options, constructs a
9331 linker command file to create the executable.
9332
9333 The arguments other than the @command{gnatlink} switches and the main
9334 @file{ALI} file are passed to the linker uninterpreted.
9335 They typically include the names of
9336 object files for units written in other languages than Ada and any library
9337 references required to resolve references in any of these foreign language
9338 units, or in @code{Import} pragmas in any Ada units.
9339
9340 @var{linker options} is an optional list of linker specific
9341 switches.
9342 The default linker called by gnatlink is @command{gcc} which in
9343 turn calls the appropriate system linker.
9344
9345 One useful option for the linker is @option{-s}: it reduces the size of the
9346 executable by removing all symbol table and relocation information from the
9347 executable.
9348
9349 Standard options for the linker such as @option{-lmy_lib} or
9350 @option{-Ldir} can be added as is.
9351 For options that are not recognized by
9352 @command{gcc} as linker options, use the @command{gcc} switches
9353 @option{-Xlinker} or @option{-Wl,}.
9354
9355 Refer to the GCC documentation for
9356 details.
9357
9358 Here is an example showing how to generate a linker map:
9359
9360 @smallexample
9361 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9362 @end smallexample
9363
9364 Using @var{linker options} it is possible to set the program stack and
9365 heap size.
9366 @ifset unw
9367 See @ref{Setting Stack Size from gnatlink} and
9368 @ref{Setting Heap Size from gnatlink}.
9369 @end ifset
9370
9371 @command{gnatlink} determines the list of objects required by the Ada
9372 program and prepends them to the list of objects passed to the linker.
9373 @command{gnatlink} also gathers any arguments set by the use of
9374 @code{pragma Linker_Options} and adds them to the list of arguments
9375 presented to the linker.
9376
9377 @ifset vms
9378 @command{gnatlink} accepts the following types of extra files on the command
9379 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9380 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9381 handled according to their extension.
9382 @end ifset
9383
9384 @node Switches for gnatlink
9385 @section Switches for @command{gnatlink}
9386
9387 @noindent
9388 The following switches are available with the @command{gnatlink} utility:
9389
9390 @table @option
9391 @c !sort!
9392
9393 @item --version
9394 @cindex @option{--version} @command{gnatlink}
9395 Display Copyright and version, then exit disregarding all other options.
9396
9397 @item --help
9398 @cindex @option{--help} @command{gnatlink}
9399 If @option{--version} was not used, display usage, then exit disregarding
9400 all other options.
9401
9402 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9403 @cindex Command line length
9404 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9405 On some targets, the command line length is limited, and @command{gnatlink}
9406 will generate a separate file for the linker if the list of object files
9407 is too long.
9408 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9409 to be generated even if
9410 the limit is not exceeded. This is useful in some cases to deal with
9411 special situations where the command line length is exceeded.
9412
9413 @item ^-g^/DEBUG^
9414 @cindex Debugging information, including
9415 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9416 The option to include debugging information causes the Ada bind file (in
9417 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9418 @option{^-g^/DEBUG^}.
9419 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9420 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9421 Without @option{^-g^/DEBUG^}, the binder removes these files by
9422 default. The same procedure apply if a C bind file was generated using
9423 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9424 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9425
9426 @item ^-n^/NOCOMPILE^
9427 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9428 Do not compile the file generated by the binder. This may be used when
9429 a link is rerun with different options, but there is no need to recompile
9430 the binder file.
9431
9432 @item ^-v^/VERBOSE^
9433 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9434 Causes additional information to be output, including a full list of the
9435 included object files. This switch option is most useful when you want
9436 to see what set of object files are being used in the link step.
9437
9438 @item ^-v -v^/VERBOSE/VERBOSE^
9439 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9440 Very verbose mode. Requests that the compiler operate in verbose mode when
9441 it compiles the binder file, and that the system linker run in verbose mode.
9442
9443 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9444 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9445 @var{exec-name} specifies an alternate name for the generated
9446 executable program. If this switch is omitted, the executable has the same
9447 name as the main unit. For example, @code{gnatlink try.ali} creates
9448 an executable called @file{^try^TRY.EXE^}.
9449
9450 @ifclear vms
9451 @item -b @var{target}
9452 @cindex @option{-b} (@command{gnatlink})
9453 Compile your program to run on @var{target}, which is the name of a
9454 system configuration. You must have a GNAT cross-compiler built if
9455 @var{target} is not the same as your host system.
9456
9457 @item -B@var{dir}
9458 @cindex @option{-B} (@command{gnatlink})
9459 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9460 from @var{dir} instead of the default location. Only use this switch
9461 when multiple versions of the GNAT compiler are available.
9462 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9463 for further details. You would normally use the @option{-b} or
9464 @option{-V} switch instead.
9465
9466 @item -M
9467 When linking an executable, create a map file. The name of the map file
9468 has the same name as the executable with extension ".map".
9469
9470 @item -M=mapfile
9471 When linking an executable, create a map file. The name of the map file is
9472 "mapfile".
9473
9474 @item --GCC=@var{compiler_name}
9475 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9476 Program used for compiling the binder file. The default is
9477 @command{gcc}. You need to use quotes around @var{compiler_name} if
9478 @code{compiler_name} contains spaces or other separator characters.
9479 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9480 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9481 inserted after your command name. Thus in the above example the compiler
9482 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9483 A limitation of this syntax is that the name and path name of the executable
9484 itself must not include any embedded spaces. If the compiler executable is
9485 different from the default one (gcc or <prefix>-gcc), then the back-end
9486 switches in the ALI file are not used to compile the binder generated source.
9487 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9488 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9489 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9490 is taken into account. However, all the additional switches are also taken
9491 into account. Thus,
9492 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9493 @option{--GCC="bar -x -y -z -t"}.
9494
9495 @item --LINK=@var{name}
9496 @cindex @option{--LINK=} (@command{gnatlink})
9497 @var{name} is the name of the linker to be invoked. This is especially
9498 useful in mixed language programs since languages such as C++ require
9499 their own linker to be used. When this switch is omitted, the default
9500 name for the linker is @command{gcc}. When this switch is used, the
9501 specified linker is called instead of @command{gcc} with exactly the same
9502 parameters that would have been passed to @command{gcc} so if the desired
9503 linker requires different parameters it is necessary to use a wrapper
9504 script that massages the parameters before invoking the real linker. It
9505 may be useful to control the exact invocation by using the verbose
9506 switch.
9507
9508 @end ifclear
9509
9510 @ifset vms
9511 @item /DEBUG=TRACEBACK
9512 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9513 This qualifier causes sufficient information to be included in the
9514 executable file to allow a traceback, but does not include the full
9515 symbol information needed by the debugger.
9516
9517 @item /IDENTIFICATION="<string>"
9518 @code{"<string>"} specifies the string to be stored in the image file
9519 identification field in the image header.
9520 It overrides any pragma @code{Ident} specified string.
9521
9522 @item /NOINHIBIT-EXEC
9523 Generate the executable file even if there are linker warnings.
9524
9525 @item /NOSTART_FILES
9526 Don't link in the object file containing the ``main'' transfer address.
9527 Used when linking with a foreign language main program compiled with an
9528 HP compiler.
9529
9530 @item /STATIC
9531 Prefer linking with object libraries over sharable images, even without
9532 /DEBUG.
9533 @end ifset
9534
9535 @end table
9536
9537 @node The GNAT Make Program gnatmake
9538 @chapter The GNAT Make Program @command{gnatmake}
9539 @findex gnatmake
9540
9541 @menu
9542 * Running gnatmake::
9543 * Switches for gnatmake::
9544 * Mode Switches for gnatmake::
9545 * Notes on the Command Line::
9546 * How gnatmake Works::
9547 * Examples of gnatmake Usage::
9548 @end menu
9549 @noindent
9550 A typical development cycle when working on an Ada program consists of
9551 the following steps:
9552
9553 @enumerate
9554 @item
9555 Edit some sources to fix bugs.
9556
9557 @item
9558 Add enhancements.
9559
9560 @item
9561 Compile all sources affected.
9562
9563 @item
9564 Rebind and relink.
9565
9566 @item
9567 Test.
9568 @end enumerate
9569
9570 @noindent
9571 The third step can be tricky, because not only do the modified files
9572 @cindex Dependency rules
9573 have to be compiled, but any files depending on these files must also be
9574 recompiled. The dependency rules in Ada can be quite complex, especially
9575 in the presence of overloading, @code{use} clauses, generics and inlined
9576 subprograms.
9577
9578 @command{gnatmake} automatically takes care of the third and fourth steps
9579 of this process. It determines which sources need to be compiled,
9580 compiles them, and binds and links the resulting object files.
9581
9582 Unlike some other Ada make programs, the dependencies are always
9583 accurately recomputed from the new sources. The source based approach of
9584 the GNAT compilation model makes this possible. This means that if
9585 changes to the source program cause corresponding changes in
9586 dependencies, they will always be tracked exactly correctly by
9587 @command{gnatmake}.
9588
9589 @node Running gnatmake
9590 @section Running @command{gnatmake}
9591
9592 @noindent
9593 The usual form of the @command{gnatmake} command is
9594
9595 @smallexample
9596 @c $ gnatmake @ovar{switches} @var{file_name}
9597 @c @ovar{file_names} @ovar{mode_switches}
9598 @c Expanding @ovar macro inline (explanation in macro def comments)
9599 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9600 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9601 @end smallexample
9602
9603 @noindent
9604 The only required argument is one @var{file_name}, which specifies
9605 a compilation unit that is a main program. Several @var{file_names} can be
9606 specified: this will result in several executables being built.
9607 If @code{switches} are present, they can be placed before the first
9608 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9609 If @var{mode_switches} are present, they must always be placed after
9610 the last @var{file_name} and all @code{switches}.
9611
9612 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9613 extension may be omitted from the @var{file_name} arguments. However, if
9614 you are using non-standard extensions, then it is required that the
9615 extension be given. A relative or absolute directory path can be
9616 specified in a @var{file_name}, in which case, the input source file will
9617 be searched for in the specified directory only. Otherwise, the input
9618 source file will first be searched in the directory where
9619 @command{gnatmake} was invoked and if it is not found, it will be search on
9620 the source path of the compiler as described in
9621 @ref{Search Paths and the Run-Time Library (RTL)}.
9622
9623 All @command{gnatmake} output (except when you specify
9624 @option{^-M^/DEPENDENCIES_LIST^}) is to
9625 @file{stderr}. The output produced by the
9626 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9627 @file{stdout}.
9628
9629 @node Switches for gnatmake
9630 @section Switches for @command{gnatmake}
9631
9632 @noindent
9633 You may specify any of the following switches to @command{gnatmake}:
9634
9635 @table @option
9636 @c !sort!
9637
9638 @item --version
9639 @cindex @option{--version} @command{gnatmake}
9640 Display Copyright and version, then exit disregarding all other options.
9641
9642 @item --help
9643 @cindex @option{--help} @command{gnatmake}
9644 If @option{--version} was not used, display usage, then exit disregarding
9645 all other options.
9646
9647 @ifclear vms
9648 @item --GCC=@var{compiler_name}
9649 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9650 Program used for compiling. The default is `@command{gcc}'. You need to use
9651 quotes around @var{compiler_name} if @code{compiler_name} contains
9652 spaces or other separator characters. As an example @option{--GCC="foo -x
9653 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9654 compiler. A limitation of this syntax is that the name and path name of
9655 the executable itself must not include any embedded spaces. Note that
9656 switch @option{-c} is always inserted after your command name. Thus in the
9657 above example the compiler command that will be used by @command{gnatmake}
9658 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9659 used, only the last @var{compiler_name} is taken into account. However,
9660 all the additional switches are also taken into account. Thus,
9661 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9662 @option{--GCC="bar -x -y -z -t"}.
9663
9664 @item --GNATBIND=@var{binder_name}
9665 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9666 Program used for binding. The default is `@code{gnatbind}'. You need to
9667 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9668 or other separator characters. As an example @option{--GNATBIND="bar -x
9669 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9670 binder. Binder switches that are normally appended by @command{gnatmake}
9671 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9672 A limitation of this syntax is that the name and path name of the executable
9673 itself must not include any embedded spaces.
9674
9675 @item --GNATLINK=@var{linker_name}
9676 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9677 Program used for linking. The default is `@command{gnatlink}'. You need to
9678 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9679 or other separator characters. As an example @option{--GNATLINK="lan -x
9680 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9681 linker. Linker switches that are normally appended by @command{gnatmake} to
9682 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9683 A limitation of this syntax is that the name and path name of the executable
9684 itself must not include any embedded spaces.
9685
9686 @end ifclear
9687
9688 @item ^--subdirs^/SUBDIRS^=subdir
9689 Actual object directory of each project file is the subdirectory subdir of the
9690 object directory specified or defaulted in the project file.
9691
9692 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9693 Disallow simultaneous compilations in the same object directory when
9694 project files are used.
9695
9696 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9697 By default, shared library projects are not allowed to import static library
9698 projects. When this switch is used on the command line, this restriction is
9699 relaxed.
9700
9701 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9702 Specify a source info file. This switch is active only when project files
9703 are used. If the source info file is specified as a relative path, then it is
9704 relative to the object directory of the main project. If the source info file
9705 does not exist, then after the Project Manager has successfully parsed and
9706 processed the project files and found the sources, it creates the source info
9707 file. If the source info file already exists and can be read successfully,
9708 then the Project Manager will get all the needed information about the sources
9709 from the source info file and will not look for them. This reduces the time
9710 to process the project files, especially when looking for sources that take a
9711 long time. If the source info file exists but cannot be parsed successfully,
9712 the Project Manager will attempt to recreate it. If the Project Manager fails
9713 to create the source info file, a message is issued, but gnatmake does not
9714 fail. @command{gnatmake} "trusts" the source info file. This means that
9715 if the source files have changed (addition, deletion, moving to a different
9716 source directory), then the source info file need to be deleted and recreated.
9717
9718 @ifclear vms
9719 @item --create-map-file
9720 When linking an executable, create a map file. The name of the map file
9721 has the same name as the executable with extension ".map".
9722
9723 @item --create-map-file=mapfile
9724 When linking an executable, create a map file. The name of the map file is
9725 "mapfile".
9726
9727 @end ifclear
9728
9729 @item ^-a^/ALL_FILES^
9730 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9731 Consider all files in the make process, even the GNAT internal system
9732 files (for example, the predefined Ada library files), as well as any
9733 locked files. Locked files are files whose ALI file is write-protected.
9734 By default,
9735 @command{gnatmake} does not check these files,
9736 because the assumption is that the GNAT internal files are properly up
9737 to date, and also that any write protected ALI files have been properly
9738 installed. Note that if there is an installation problem, such that one
9739 of these files is not up to date, it will be properly caught by the
9740 binder.
9741 You may have to specify this switch if you are working on GNAT
9742 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9743 in conjunction with @option{^-f^/FORCE_COMPILE^}
9744 if you need to recompile an entire application,
9745 including run-time files, using special configuration pragmas,
9746 such as a @code{Normalize_Scalars} pragma.
9747
9748 By default
9749 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9750 internal files with
9751 @ifclear vms
9752 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9753 @end ifclear
9754 @ifset vms
9755 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9756 @end ifset
9757
9758 @item ^-b^/ACTIONS=BIND^
9759 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9760 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9761 compilation and binding, but no link.
9762 Can be combined with @option{^-l^/ACTIONS=LINK^}
9763 to do binding and linking. When not combined with
9764 @option{^-c^/ACTIONS=COMPILE^}
9765 all the units in the closure of the main program must have been previously
9766 compiled and must be up to date. The root unit specified by @var{file_name}
9767 may be given without extension, with the source extension or, if no GNAT
9768 Project File is specified, with the ALI file extension.
9769
9770 @item ^-c^/ACTIONS=COMPILE^
9771 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9772 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9773 is also specified. Do not perform linking, except if both
9774 @option{^-b^/ACTIONS=BIND^} and
9775 @option{^-l^/ACTIONS=LINK^} are also specified.
9776 If the root unit specified by @var{file_name} is not a main unit, this is the
9777 default. Otherwise @command{gnatmake} will attempt binding and linking
9778 unless all objects are up to date and the executable is more recent than
9779 the objects.
9780
9781 @item ^-C^/MAPPING^
9782 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9783 Use a temporary mapping file. A mapping file is a way to communicate
9784 to the compiler two mappings: from unit names to file names (without
9785 any directory information) and from file names to path names (with
9786 full directory information). A mapping file can make the compiler's
9787 file searches faster, especially if there are many source directories,
9788 or the sources are read over a slow network connection. If
9789 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9790 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9791 is initially populated based on the project file. If
9792 @option{^-C^/MAPPING^} is used without
9793 @option{^-P^/PROJECT_FILE^},
9794 the mapping file is initially empty. Each invocation of the compiler
9795 will add any newly accessed sources to the mapping file.
9796
9797 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9798 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9799 Use a specific mapping file. The file, specified as a path name (absolute or
9800 relative) by this switch, should already exist, otherwise the switch is
9801 ineffective. The specified mapping file will be communicated to the compiler.
9802 This switch is not compatible with a project file
9803 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9804 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9805
9806 @item ^-d^/DISPLAY_PROGRESS^
9807 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9808 Display progress for each source, up to date or not, as a single line
9809
9810 @smallexample
9811 completed x out of y (zz%)
9812 @end smallexample
9813
9814 If the file needs to be compiled this is displayed after the invocation of
9815 the compiler. These lines are displayed even in quiet output mode.
9816
9817 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9818 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9819 Put all object files and ALI file in directory @var{dir}.
9820 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9821 and ALI files go in the current working directory.
9822
9823 This switch cannot be used when using a project file.
9824
9825 @item -eInnn
9826 @cindex @option{-eI} (@command{gnatmake})
9827 Indicates that the main source is a multi-unit source and the rank of the unit
9828 in the source file is nnn. nnn needs to be a positive number and a valid
9829 index in the source. This switch cannot be used when @command{gnatmake} is
9830 invoked for several mains.
9831
9832 @ifclear vms
9833 @item -eL
9834 @cindex @option{-eL} (@command{gnatmake})
9835 @cindex symbolic links
9836 Follow all symbolic links when processing project files.
9837 This should be used if your project uses symbolic links for files or
9838 directories, but is not needed in other cases.
9839
9840 @cindex naming scheme
9841 This also assumes that no directory matches the naming scheme for files (for
9842 instance that you do not have a directory called "sources.ads" when using the
9843 default GNAT naming scheme).
9844
9845 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9846 save a lot of system calls (several per source file and object file), which
9847 can result in a significant speed up to load and manipulate a project file,
9848 especially when using source files from a remote system.
9849
9850 @end ifclear
9851
9852 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9853 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9854 Output the commands for the compiler, the binder and the linker
9855 on ^standard output^SYS$OUTPUT^,
9856 instead of ^standard error^SYS$ERROR^.
9857
9858 @item ^-f^/FORCE_COMPILE^
9859 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9860 Force recompilations. Recompile all sources, even though some object
9861 files may be up to date, but don't recompile predefined or GNAT internal
9862 files or locked files (files with a write-protected ALI file),
9863 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9864
9865 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9866 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9867 When using project files, if some errors or warnings are detected during
9868 parsing and verbose mode is not in effect (no use of switch
9869 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9870 file, rather than its simple file name.
9871
9872 @item ^-g^/DEBUG^
9873 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9874 Enable debugging. This switch is simply passed to the compiler and to the
9875 linker.
9876
9877 @item ^-i^/IN_PLACE^
9878 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9879 In normal mode, @command{gnatmake} compiles all object files and ALI files
9880 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9881 then instead object files and ALI files that already exist are overwritten
9882 in place. This means that once a large project is organized into separate
9883 directories in the desired manner, then @command{gnatmake} will automatically
9884 maintain and update this organization. If no ALI files are found on the
9885 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9886 the new object and ALI files are created in the
9887 directory containing the source being compiled. If another organization
9888 is desired, where objects and sources are kept in different directories,
9889 a useful technique is to create dummy ALI files in the desired directories.
9890 When detecting such a dummy file, @command{gnatmake} will be forced to
9891 recompile the corresponding source file, and it will be put the resulting
9892 object and ALI files in the directory where it found the dummy file.
9893
9894 @item ^-j^/PROCESSES=^@var{n}
9895 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9896 @cindex Parallel make
9897 Use @var{n} processes to carry out the (re)compilations. On a
9898 multiprocessor machine compilations will occur in parallel. In the
9899 event of compilation errors, messages from various compilations might
9900 get interspersed (but @command{gnatmake} will give you the full ordered
9901 list of failing compiles at the end). If this is problematic, rerun
9902 the make process with n set to 1 to get a clean list of messages.
9903
9904 @item ^-k^/CONTINUE_ON_ERROR^
9905 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9906 Keep going. Continue as much as possible after a compilation error. To
9907 ease the programmer's task in case of compilation errors, the list of
9908 sources for which the compile fails is given when @command{gnatmake}
9909 terminates.
9910
9911 If @command{gnatmake} is invoked with several @file{file_names} and with this
9912 switch, if there are compilation errors when building an executable,
9913 @command{gnatmake} will not attempt to build the following executables.
9914
9915 @item ^-l^/ACTIONS=LINK^
9916 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9917 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9918 and linking. Linking will not be performed if combined with
9919 @option{^-c^/ACTIONS=COMPILE^}
9920 but not with @option{^-b^/ACTIONS=BIND^}.
9921 When not combined with @option{^-b^/ACTIONS=BIND^}
9922 all the units in the closure of the main program must have been previously
9923 compiled and must be up to date, and the main program needs to have been bound.
9924 The root unit specified by @var{file_name}
9925 may be given without extension, with the source extension or, if no GNAT
9926 Project File is specified, with the ALI file extension.
9927
9928 @item ^-m^/MINIMAL_RECOMPILATION^
9929 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9930 Specify that the minimum necessary amount of recompilations
9931 be performed. In this mode @command{gnatmake} ignores time
9932 stamp differences when the only
9933 modifications to a source file consist in adding/removing comments,
9934 empty lines, spaces or tabs. This means that if you have changed the
9935 comments in a source file or have simply reformatted it, using this
9936 switch will tell @command{gnatmake} not to recompile files that depend on it
9937 (provided other sources on which these files depend have undergone no
9938 semantic modifications). Note that the debugging information may be
9939 out of date with respect to the sources if the @option{-m} switch causes
9940 a compilation to be switched, so the use of this switch represents a
9941 trade-off between compilation time and accurate debugging information.
9942
9943 @item ^-M^/DEPENDENCIES_LIST^
9944 @cindex Dependencies, producing list
9945 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9946 Check if all objects are up to date. If they are, output the object
9947 dependences to @file{stdout} in a form that can be directly exploited in
9948 a @file{Makefile}. By default, each source file is prefixed with its
9949 (relative or absolute) directory name. This name is whatever you
9950 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9951 and @option{^-I^/SEARCH^} switches. If you use
9952 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9953 @option{^-q^/QUIET^}
9954 (see below), only the source file names,
9955 without relative paths, are output. If you just specify the
9956 @option{^-M^/DEPENDENCIES_LIST^}
9957 switch, dependencies of the GNAT internal system files are omitted. This
9958 is typically what you want. If you also specify
9959 the @option{^-a^/ALL_FILES^} switch,
9960 dependencies of the GNAT internal files are also listed. Note that
9961 dependencies of the objects in external Ada libraries (see switch
9962 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9963 are never reported.
9964
9965 @item ^-n^/DO_OBJECT_CHECK^
9966 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9967 Don't compile, bind, or link. Checks if all objects are up to date.
9968 If they are not, the full name of the first file that needs to be
9969 recompiled is printed.
9970 Repeated use of this option, followed by compiling the indicated source
9971 file, will eventually result in recompiling all required units.
9972
9973 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9974 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9975 Output executable name. The name of the final executable program will be
9976 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9977 name for the executable will be the name of the input file in appropriate form
9978 for an executable file on the host system.
9979
9980 This switch cannot be used when invoking @command{gnatmake} with several
9981 @file{file_names}.
9982
9983 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9984 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9985 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9986 automatically missing object directories, library directories and exec
9987 directories.
9988
9989 @item ^-P^/PROJECT_FILE=^@var{project}
9990 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9991 Use project file @var{project}. Only one such switch can be used.
9992 @xref{gnatmake and Project Files}.
9993
9994 @item ^-q^/QUIET^
9995 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9996 Quiet. When this flag is not set, the commands carried out by
9997 @command{gnatmake} are displayed.
9998
9999 @item ^-s^/SWITCH_CHECK/^
10000 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
10001 Recompile if compiler switches have changed since last compilation.
10002 All compiler switches but -I and -o are taken into account in the
10003 following way:
10004 orders between different ``first letter'' switches are ignored, but
10005 orders between same switches are taken into account. For example,
10006 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
10007 is equivalent to @option{-O -g}.
10008
10009 This switch is recommended when Integrated Preprocessing is used.
10010
10011 @item ^-u^/UNIQUE^
10012 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
10013 Unique. Recompile at most the main files. It implies -c. Combined with
10014 -f, it is equivalent to calling the compiler directly. Note that using
10015 ^-u^/UNIQUE^ with a project file and no main has a special meaning
10016 (@pxref{Project Files and Main Subprograms}).
10017
10018 @item ^-U^/ALL_PROJECTS^
10019 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
10020 When used without a project file or with one or several mains on the command
10021 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
10022 on the command line, all sources of all project files are checked and compiled
10023 if not up to date, and libraries are rebuilt, if necessary.
10024
10025 @item ^-v^/REASONS^
10026 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
10027 Verbose. Display the reason for all recompilations @command{gnatmake}
10028 decides are necessary, with the highest verbosity level.
10029
10030 @item ^-vl^/LOW_VERBOSITY^
10031 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
10032 Verbosity level Low. Display fewer lines than in verbosity Medium.
10033
10034 @item ^-vm^/MEDIUM_VERBOSITY^
10035 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
10036 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
10037
10038 @item ^-vh^/HIGH_VERBOSITY^
10039 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
10040 Verbosity level High. Equivalent to ^-v^/REASONS^.
10041
10042 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
10043 Indicate the verbosity of the parsing of GNAT project files.
10044 @xref{Switches Related to Project Files}.
10045
10046 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
10047 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
10048 Indicate that sources that are not part of any Project File may be compiled.
10049 Normally, when using Project Files, only sources that are part of a Project
10050 File may be compile. When this switch is used, a source outside of all Project
10051 Files may be compiled. The ALI file and the object file will be put in the
10052 object directory of the main Project. The compilation switches used will only
10053 be those specified on the command line. Even when
10054 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
10055 command line need to be sources of a project file.
10056
10057 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
10058 Indicate that external variable @var{name} has the value @var{value}.
10059 The Project Manager will use this value for occurrences of
10060 @code{external(name)} when parsing the project file.
10061 @xref{Switches Related to Project Files}.
10062
10063 @item ^-z^/NOMAIN^
10064 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
10065 No main subprogram. Bind and link the program even if the unit name
10066 given on the command line is a package name. The resulting executable
10067 will execute the elaboration routines of the package and its closure,
10068 then the finalization routines.
10069
10070 @end table
10071
10072 @table @asis
10073 @item @command{gcc} @asis{switches}
10074 @ifclear vms
10075 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
10076 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
10077 @end ifclear
10078 @ifset vms
10079 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
10080 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
10081 automatically treated as a compiler switch, and passed on to all
10082 compilations that are carried out.
10083 @end ifset
10084 @end table
10085
10086 @noindent
10087 Source and library search path switches:
10088
10089 @table @option
10090 @c !sort!
10091 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
10092 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
10093 When looking for source files also look in directory @var{dir}.
10094 The order in which source files search is undertaken is
10095 described in @ref{Search Paths and the Run-Time Library (RTL)}.
10096
10097 @item ^-aL^/SKIP_MISSING=^@var{dir}
10098 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
10099 Consider @var{dir} as being an externally provided Ada library.
10100 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
10101 files have been located in directory @var{dir}. This allows you to have
10102 missing bodies for the units in @var{dir} and to ignore out of date bodies
10103 for the same units. You still need to specify
10104 the location of the specs for these units by using the switches
10105 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10106 or @option{^-I^/SEARCH=^@var{dir}}.
10107 Note: this switch is provided for compatibility with previous versions
10108 of @command{gnatmake}. The easier method of causing standard libraries
10109 to be excluded from consideration is to write-protect the corresponding
10110 ALI files.
10111
10112 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10113 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10114 When searching for library and object files, look in directory
10115 @var{dir}. The order in which library files are searched is described in
10116 @ref{Search Paths for gnatbind}.
10117
10118 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10119 @cindex Search paths, for @command{gnatmake}
10120 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10121 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10122 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10123
10124 @item ^-I^/SEARCH=^@var{dir}
10125 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10126 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10127 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10128
10129 @item ^-I-^/NOCURRENT_DIRECTORY^
10130 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10131 @cindex Source files, suppressing search
10132 Do not look for source files in the directory containing the source
10133 file named in the command line.
10134 Do not look for ALI or object files in the directory
10135 where @command{gnatmake} was invoked.
10136
10137 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10138 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10139 @cindex Linker libraries
10140 Add directory @var{dir} to the list of directories in which the linker
10141 will search for libraries. This is equivalent to
10142 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10143 @ifclear vms
10144 Furthermore, under Windows, the sources pointed to by the libraries path
10145 set in the registry are not searched for.
10146 @end ifclear
10147
10148 @item -nostdinc
10149 @cindex @option{-nostdinc} (@command{gnatmake})
10150 Do not look for source files in the system default directory.
10151
10152 @item -nostdlib
10153 @cindex @option{-nostdlib} (@command{gnatmake})
10154 Do not look for library files in the system default directory.
10155
10156 @item --RTS=@var{rts-path}
10157 @cindex @option{--RTS} (@command{gnatmake})
10158 Specifies the default location of the runtime library. GNAT looks for the
10159 runtime
10160 in the following directories, and stops as soon as a valid runtime is found
10161 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10162 @file{ada_object_path} present):
10163
10164 @itemize @bullet
10165 @item <current directory>/$rts_path
10166
10167 @item <default-search-dir>/$rts_path
10168
10169 @item <default-search-dir>/rts-$rts_path
10170 @end itemize
10171
10172 @noindent
10173 The selected path is handled like a normal RTS path.
10174
10175 @end table
10176
10177 @node Mode Switches for gnatmake
10178 @section Mode Switches for @command{gnatmake}
10179
10180 @noindent
10181 The mode switches (referred to as @code{mode_switches}) allow the
10182 inclusion of switches that are to be passed to the compiler itself, the
10183 binder or the linker. The effect of a mode switch is to cause all
10184 subsequent switches up to the end of the switch list, or up to the next
10185 mode switch, to be interpreted as switches to be passed on to the
10186 designated component of GNAT.
10187
10188 @table @option
10189 @c !sort!
10190 @item -cargs @var{switches}
10191 @cindex @option{-cargs} (@command{gnatmake})
10192 Compiler switches. Here @var{switches} is a list of switches
10193 that are valid switches for @command{gcc}. They will be passed on to
10194 all compile steps performed by @command{gnatmake}.
10195
10196 @item -bargs @var{switches}
10197 @cindex @option{-bargs} (@command{gnatmake})
10198 Binder switches. Here @var{switches} is a list of switches
10199 that are valid switches for @code{gnatbind}. They will be passed on to
10200 all bind steps performed by @command{gnatmake}.
10201
10202 @item -largs @var{switches}
10203 @cindex @option{-largs} (@command{gnatmake})
10204 Linker switches. Here @var{switches} is a list of switches
10205 that are valid switches for @command{gnatlink}. They will be passed on to
10206 all link steps performed by @command{gnatmake}.
10207
10208 @item -margs @var{switches}
10209 @cindex @option{-margs} (@command{gnatmake})
10210 Make switches. The switches are directly interpreted by @command{gnatmake},
10211 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10212 or @option{-largs}.
10213 @end table
10214
10215 @node Notes on the Command Line
10216 @section Notes on the Command Line
10217
10218 @noindent
10219 This section contains some additional useful notes on the operation
10220 of the @command{gnatmake} command.
10221
10222 @itemize @bullet
10223 @item
10224 @cindex Recompilation, by @command{gnatmake}
10225 If @command{gnatmake} finds no ALI files, it recompiles the main program
10226 and all other units required by the main program.
10227 This means that @command{gnatmake}
10228 can be used for the initial compile, as well as during subsequent steps of
10229 the development cycle.
10230
10231 @item
10232 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10233 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10234 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10235 warning.
10236
10237 @item
10238 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10239 is used to specify both source and
10240 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10241 instead if you just want to specify
10242 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10243 if you want to specify library paths
10244 only.
10245
10246 @item
10247 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10248 This may conveniently be used to exclude standard libraries from
10249 consideration and in particular it means that the use of the
10250 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10251 unless @option{^-a^/ALL_FILES^} is also specified.
10252
10253 @item
10254 @command{gnatmake} has been designed to make the use of Ada libraries
10255 particularly convenient. Assume you have an Ada library organized
10256 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10257 of your Ada compilation units,
10258 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10259 specs of these units, but no bodies. Then to compile a unit
10260 stored in @code{main.adb}, which uses this Ada library you would just type
10261
10262 @smallexample
10263 @ifclear vms
10264 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10265 @end ifclear
10266 @ifset vms
10267 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10268 /SKIP_MISSING=@i{[OBJ_DIR]} main
10269 @end ifset
10270 @end smallexample
10271
10272 @item
10273 Using @command{gnatmake} along with the
10274 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10275 switch provides a mechanism for avoiding unnecessary recompilations. Using
10276 this switch,
10277 you can update the comments/format of your
10278 source files without having to recompile everything. Note, however, that
10279 adding or deleting lines in a source files may render its debugging
10280 info obsolete. If the file in question is a spec, the impact is rather
10281 limited, as that debugging info will only be useful during the
10282 elaboration phase of your program. For bodies the impact can be more
10283 significant. In all events, your debugger will warn you if a source file
10284 is more recent than the corresponding object, and alert you to the fact
10285 that the debugging information may be out of date.
10286 @end itemize
10287
10288 @node How gnatmake Works
10289 @section How @command{gnatmake} Works
10290
10291 @noindent
10292 Generally @command{gnatmake} automatically performs all necessary
10293 recompilations and you don't need to worry about how it works. However,
10294 it may be useful to have some basic understanding of the @command{gnatmake}
10295 approach and in particular to understand how it uses the results of
10296 previous compilations without incorrectly depending on them.
10297
10298 First a definition: an object file is considered @dfn{up to date} if the
10299 corresponding ALI file exists and if all the source files listed in the
10300 dependency section of this ALI file have time stamps matching those in
10301 the ALI file. This means that neither the source file itself nor any
10302 files that it depends on have been modified, and hence there is no need
10303 to recompile this file.
10304
10305 @command{gnatmake} works by first checking if the specified main unit is up
10306 to date. If so, no compilations are required for the main unit. If not,
10307 @command{gnatmake} compiles the main program to build a new ALI file that
10308 reflects the latest sources. Then the ALI file of the main unit is
10309 examined to find all the source files on which the main program depends,
10310 and @command{gnatmake} recursively applies the above procedure on all these
10311 files.
10312
10313 This process ensures that @command{gnatmake} only trusts the dependencies
10314 in an existing ALI file if they are known to be correct. Otherwise it
10315 always recompiles to determine a new, guaranteed accurate set of
10316 dependencies. As a result the program is compiled ``upside down'' from what may
10317 be more familiar as the required order of compilation in some other Ada
10318 systems. In particular, clients are compiled before the units on which
10319 they depend. The ability of GNAT to compile in any order is critical in
10320 allowing an order of compilation to be chosen that guarantees that
10321 @command{gnatmake} will recompute a correct set of new dependencies if
10322 necessary.
10323
10324 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10325 imported by several of the executables, it will be recompiled at most once.
10326
10327 Note: when using non-standard naming conventions
10328 (@pxref{Using Other File Names}), changing through a configuration pragmas
10329 file the version of a source and invoking @command{gnatmake} to recompile may
10330 have no effect, if the previous version of the source is still accessible
10331 by @command{gnatmake}. It may be necessary to use the switch
10332 ^-f^/FORCE_COMPILE^.
10333
10334 @node Examples of gnatmake Usage
10335 @section Examples of @command{gnatmake} Usage
10336
10337 @table @code
10338 @item gnatmake hello.adb
10339 Compile all files necessary to bind and link the main program
10340 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10341 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10342
10343 @item gnatmake main1 main2 main3
10344 Compile all files necessary to bind and link the main programs
10345 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10346 (containing unit @code{Main2}) and @file{main3.adb}
10347 (containing unit @code{Main3}) and bind and link the resulting object files
10348 to generate three executable files @file{^main1^MAIN1.EXE^},
10349 @file{^main2^MAIN2.EXE^}
10350 and @file{^main3^MAIN3.EXE^}.
10351
10352 @ifclear vms
10353 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10354 @end ifclear
10355
10356 @ifset vms
10357 @item gnatmake Main_Unit /QUIET
10358 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10359 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10360 @end ifset
10361 Compile all files necessary to bind and link the main program unit
10362 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10363 be done with optimization level 2 and the order of elaboration will be
10364 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10365 displaying commands it is executing.
10366 @end table
10367
10368 @c *************************
10369 @node Improving Performance
10370 @chapter Improving Performance
10371 @cindex Improving performance
10372
10373 @noindent
10374 This chapter presents several topics related to program performance.
10375 It first describes some of the tradeoffs that need to be considered
10376 and some of the techniques for making your program run faster.
10377 It then documents the @command{gnatelim} tool and unused subprogram/data
10378 elimination feature, which can reduce the size of program executables.
10379
10380 @ifnottex
10381 @menu
10382 * Performance Considerations::
10383 * Text_IO Suggestions::
10384 * Reducing Size of Ada Executables with gnatelim::
10385 * Reducing Size of Executables with unused subprogram/data elimination::
10386 @end menu
10387 @end ifnottex
10388
10389 @c *****************************
10390 @node Performance Considerations
10391 @section Performance Considerations
10392
10393 @noindent
10394 The GNAT system provides a number of options that allow a trade-off
10395 between
10396
10397 @itemize @bullet
10398 @item
10399 performance of the generated code
10400
10401 @item
10402 speed of compilation
10403
10404 @item
10405 minimization of dependences and recompilation
10406
10407 @item
10408 the degree of run-time checking.
10409 @end itemize
10410
10411 @noindent
10412 The defaults (if no options are selected) aim at improving the speed
10413 of compilation and minimizing dependences, at the expense of performance
10414 of the generated code:
10415
10416 @itemize @bullet
10417 @item
10418 no optimization
10419
10420 @item
10421 no inlining of subprogram calls
10422
10423 @item
10424 all run-time checks enabled except overflow and elaboration checks
10425 @end itemize
10426
10427 @noindent
10428 These options are suitable for most program development purposes. This
10429 chapter describes how you can modify these choices, and also provides
10430 some guidelines on debugging optimized code.
10431
10432 @menu
10433 * Controlling Run-Time Checks::
10434 * Use of Restrictions::
10435 * Optimization Levels::
10436 * Debugging Optimized Code::
10437 * Inlining of Subprograms::
10438 * Vectorization of loops::
10439 * Other Optimization Switches::
10440 * Optimization and Strict Aliasing::
10441
10442 @ifset vms
10443 * Coverage Analysis::
10444 @end ifset
10445 @end menu
10446
10447 @node Controlling Run-Time Checks
10448 @subsection Controlling Run-Time Checks
10449
10450 @noindent
10451 By default, GNAT generates all run-time checks, except integer overflow
10452 checks, stack overflow checks, and checks for access before elaboration on
10453 subprogram calls. The latter are not required in default mode, because all
10454 necessary checking is done at compile time.
10455 @cindex @option{-gnatp} (@command{gcc})
10456 @cindex @option{-gnato} (@command{gcc})
10457 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10458 be modified. @xref{Run-Time Checks}.
10459
10460 Our experience is that the default is suitable for most development
10461 purposes.
10462
10463 We treat integer overflow specially because these
10464 are quite expensive and in our experience are not as important as other
10465 run-time checks in the development process. Note that division by zero
10466 is not considered an overflow check, and divide by zero checks are
10467 generated where required by default.
10468
10469 Elaboration checks are off by default, and also not needed by default, since
10470 GNAT uses a static elaboration analysis approach that avoids the need for
10471 run-time checking. This manual contains a full chapter discussing the issue
10472 of elaboration checks, and if the default is not satisfactory for your use,
10473 you should read this chapter.
10474
10475 For validity checks, the minimal checks required by the Ada Reference
10476 Manual (for case statements and assignments to array elements) are on
10477 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10478 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10479 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10480 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10481 are also suppressed entirely if @option{-gnatp} is used.
10482
10483 @cindex Overflow checks
10484 @cindex Checks, overflow
10485 @findex Suppress
10486 @findex Unsuppress
10487 @cindex pragma Suppress
10488 @cindex pragma Unsuppress
10489 Note that the setting of the switches controls the default setting of
10490 the checks. They may be modified using either @code{pragma Suppress} (to
10491 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10492 checks) in the program source.
10493
10494 @node Use of Restrictions
10495 @subsection Use of Restrictions
10496
10497 @noindent
10498 The use of pragma Restrictions allows you to control which features are
10499 permitted in your program. Apart from the obvious point that if you avoid
10500 relatively expensive features like finalization (enforceable by the use
10501 of pragma Restrictions (No_Finalization), the use of this pragma does not
10502 affect the generated code in most cases.
10503
10504 One notable exception to this rule is that the possibility of task abort
10505 results in some distributed overhead, particularly if finalization or
10506 exception handlers are used. The reason is that certain sections of code
10507 have to be marked as non-abortable.
10508
10509 If you use neither the @code{abort} statement, nor asynchronous transfer
10510 of control (@code{select @dots{} then abort}), then this distributed overhead
10511 is removed, which may have a general positive effect in improving
10512 overall performance. Especially code involving frequent use of tasking
10513 constructs and controlled types will show much improved performance.
10514 The relevant restrictions pragmas are
10515
10516 @smallexample @c ada
10517 pragma Restrictions (No_Abort_Statements);
10518 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10519 @end smallexample
10520
10521 @noindent
10522 It is recommended that these restriction pragmas be used if possible. Note
10523 that this also means that you can write code without worrying about the
10524 possibility of an immediate abort at any point.
10525
10526 @node Optimization Levels
10527 @subsection Optimization Levels
10528 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10529
10530 @noindent
10531 Without any optimization ^option,^qualifier,^
10532 the compiler's goal is to reduce the cost of
10533 compilation and to make debugging produce the expected results.
10534 Statements are independent: if you stop the program with a breakpoint between
10535 statements, you can then assign a new value to any variable or change
10536 the program counter to any other statement in the subprogram and get exactly
10537 the results you would expect from the source code.
10538
10539 Turning on optimization makes the compiler attempt to improve the
10540 performance and/or code size at the expense of compilation time and
10541 possibly the ability to debug the program.
10542
10543 If you use multiple
10544 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10545 the last such option is the one that is effective.
10546
10547 @noindent
10548 The default is optimization off. This results in the fastest compile
10549 times, but GNAT makes absolutely no attempt to optimize, and the
10550 generated programs are considerably larger and slower than when
10551 optimization is enabled. You can use the
10552 @ifclear vms
10553 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10554 @option{-O2}, @option{-O3}, and @option{-Os})
10555 @end ifclear
10556 @ifset vms
10557 @code{OPTIMIZE} qualifier
10558 @end ifset
10559 to @command{gcc} to control the optimization level:
10560
10561 @table @option
10562 @item ^-O0^/OPTIMIZE=NONE^
10563 No optimization (the default);
10564 generates unoptimized code but has
10565 the fastest compilation time.
10566
10567 Note that many other compilers do fairly extensive optimization
10568 even if ``no optimization'' is specified. With gcc, it is
10569 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10570 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10571 really does mean no optimization at all. This difference between
10572 gcc and other compilers should be kept in mind when doing
10573 performance comparisons.
10574
10575 @item ^-O1^/OPTIMIZE=SOME^
10576 Moderate optimization;
10577 optimizes reasonably well but does not
10578 degrade compilation time significantly.
10579
10580 @item ^-O2^/OPTIMIZE=ALL^
10581 @ifset vms
10582 @itemx /OPTIMIZE=DEVELOPMENT
10583 @end ifset
10584 Full optimization;
10585 generates highly optimized code and has
10586 the slowest compilation time.
10587
10588 @item ^-O3^/OPTIMIZE=INLINING^
10589 Full optimization as in @option{-O2};
10590 also uses more aggressive automatic inlining of subprograms within a unit
10591 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10592
10593 @item ^-Os^/OPTIMIZE=SPACE^
10594 Optimize space usage (code and data) of resulting program.
10595 @end table
10596
10597 @noindent
10598 Higher optimization levels perform more global transformations on the
10599 program and apply more expensive analysis algorithms in order to generate
10600 faster and more compact code. The price in compilation time, and the
10601 resulting improvement in execution time,
10602 both depend on the particular application and the hardware environment.
10603 You should experiment to find the best level for your application.
10604
10605 Since the precise set of optimizations done at each level will vary from
10606 release to release (and sometime from target to target), it is best to think
10607 of the optimization settings in general terms.
10608 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10609 the GNU Compiler Collection (GCC)}, for details about
10610 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10611 individually enable or disable specific optimizations.
10612
10613 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10614 been tested extensively at all optimization levels. There are some bugs
10615 which appear only with optimization turned on, but there have also been
10616 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10617 level of optimization does not improve the reliability of the code
10618 generator, which in practice is highly reliable at all optimization
10619 levels.
10620
10621 Note regarding the use of @option{-O3}: The use of this optimization level
10622 is generally discouraged with GNAT, since it often results in larger
10623 executables which may run more slowly. See further discussion of this point
10624 in @ref{Inlining of Subprograms}.
10625
10626 @node Debugging Optimized Code
10627 @subsection Debugging Optimized Code
10628 @cindex Debugging optimized code
10629 @cindex Optimization and debugging
10630
10631 @noindent
10632 Although it is possible to do a reasonable amount of debugging at
10633 @ifclear vms
10634 nonzero optimization levels,
10635 the higher the level the more likely that
10636 @end ifclear
10637 @ifset vms
10638 @option{/OPTIMIZE} settings other than @code{NONE},
10639 such settings will make it more likely that
10640 @end ifset
10641 source-level constructs will have been eliminated by optimization.
10642 For example, if a loop is strength-reduced, the loop
10643 control variable may be completely eliminated and thus cannot be
10644 displayed in the debugger.
10645 This can only happen at @option{-O2} or @option{-O3}.
10646 Explicit temporary variables that you code might be eliminated at
10647 ^level^setting^ @option{-O1} or higher.
10648
10649 The use of the @option{^-g^/DEBUG^} switch,
10650 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10651 which is needed for source-level debugging,
10652 affects the size of the program executable on disk,
10653 and indeed the debugging information can be quite large.
10654 However, it has no effect on the generated code (and thus does not
10655 degrade performance)
10656
10657 Since the compiler generates debugging tables for a compilation unit before
10658 it performs optimizations, the optimizing transformations may invalidate some
10659 of the debugging data. You therefore need to anticipate certain
10660 anomalous situations that may arise while debugging optimized code.
10661 These are the most common cases:
10662
10663 @enumerate
10664 @item
10665 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10666 commands show
10667 the PC bouncing back and forth in the code. This may result from any of
10668 the following optimizations:
10669
10670 @itemize @bullet
10671 @item
10672 @i{Common subexpression elimination:} using a single instance of code for a
10673 quantity that the source computes several times. As a result you
10674 may not be able to stop on what looks like a statement.
10675
10676 @item
10677 @i{Invariant code motion:} moving an expression that does not change within a
10678 loop, to the beginning of the loop.
10679
10680 @item
10681 @i{Instruction scheduling:} moving instructions so as to
10682 overlap loads and stores (typically) with other code, or in
10683 general to move computations of values closer to their uses. Often
10684 this causes you to pass an assignment statement without the assignment
10685 happening and then later bounce back to the statement when the
10686 value is actually needed. Placing a breakpoint on a line of code
10687 and then stepping over it may, therefore, not always cause all the
10688 expected side-effects.
10689 @end itemize
10690
10691 @item
10692 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10693 two identical pieces of code are merged and the program counter suddenly
10694 jumps to a statement that is not supposed to be executed, simply because
10695 it (and the code following) translates to the same thing as the code
10696 that @emph{was} supposed to be executed. This effect is typically seen in
10697 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10698 a @code{break} in a C @code{^switch^switch^} statement.
10699
10700 @item
10701 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10702 There are various reasons for this effect:
10703
10704 @itemize @bullet
10705 @item
10706 In a subprogram prologue, a parameter may not yet have been moved to its
10707 ``home''.
10708
10709 @item
10710 A variable may be dead, and its register re-used. This is
10711 probably the most common cause.
10712
10713 @item
10714 As mentioned above, the assignment of a value to a variable may
10715 have been moved.
10716
10717 @item
10718 A variable may be eliminated entirely by value propagation or
10719 other means. In this case, GCC may incorrectly generate debugging
10720 information for the variable
10721 @end itemize
10722
10723 @noindent
10724 In general, when an unexpected value appears for a local variable or parameter
10725 you should first ascertain if that value was actually computed by
10726 your program, as opposed to being incorrectly reported by the debugger.
10727 Record fields or
10728 array elements in an object designated by an access value
10729 are generally less of a problem, once you have ascertained that the access
10730 value is sensible.
10731 Typically, this means checking variables in the preceding code and in the
10732 calling subprogram to verify that the value observed is explainable from other
10733 values (one must apply the procedure recursively to those
10734 other values); or re-running the code and stopping a little earlier
10735 (perhaps before the call) and stepping to better see how the variable obtained
10736 the value in question; or continuing to step @emph{from} the point of the
10737 strange value to see if code motion had simply moved the variable's
10738 assignments later.
10739 @end enumerate
10740
10741 @noindent
10742 In light of such anomalies, a recommended technique is to use @option{-O0}
10743 early in the software development cycle, when extensive debugging capabilities
10744 are most needed, and then move to @option{-O1} and later @option{-O2} as
10745 the debugger becomes less critical.
10746 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10747 a release management issue.
10748 @ifclear vms
10749 Note that if you use @option{-g} you can then use the @command{strip} program
10750 on the resulting executable,
10751 which removes both debugging information and global symbols.
10752 @end ifclear
10753
10754 @node Inlining of Subprograms
10755 @subsection Inlining of Subprograms
10756
10757 @noindent
10758 A call to a subprogram in the current unit is inlined if all the
10759 following conditions are met:
10760
10761 @itemize @bullet
10762 @item
10763 The optimization level is at least @option{-O1}.
10764
10765 @item
10766 The called subprogram is suitable for inlining: It must be small enough
10767 and not contain something that @command{gcc} cannot support in inlined
10768 subprograms.
10769
10770 @item
10771 @cindex pragma Inline
10772 @findex Inline
10773 Any one of the following applies: @code{pragma Inline} is applied to the
10774 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10775 subprogram is local to the unit and called once from within it; the
10776 subprogram is small and optimization level @option{-O2} is specified;
10777 optimization level @option{-O3} is specified.
10778 @end itemize
10779
10780 @noindent
10781 Calls to subprograms in @code{with}'ed units are normally not inlined.
10782 To achieve actual inlining (that is, replacement of the call by the code
10783 in the body of the subprogram), the following conditions must all be true:
10784
10785 @itemize @bullet
10786 @item
10787 The optimization level is at least @option{-O1}.
10788
10789 @item
10790 The called subprogram is suitable for inlining: It must be small enough
10791 and not contain something that @command{gcc} cannot support in inlined
10792 subprograms.
10793
10794 @item
10795 The call appears in a body (not in a package spec).
10796
10797 @item
10798 There is a @code{pragma Inline} for the subprogram.
10799
10800 @item
10801 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10802 @end itemize
10803
10804 Even if all these conditions are met, it may not be possible for
10805 the compiler to inline the call, due to the length of the body,
10806 or features in the body that make it impossible for the compiler
10807 to do the inlining.
10808
10809 Note that specifying the @option{-gnatn} switch causes additional
10810 compilation dependencies. Consider the following:
10811
10812 @smallexample @c ada
10813 @cartouche
10814 package R is
10815 procedure Q;
10816 pragma Inline (Q);
10817 end R;
10818 package body R is
10819 @dots{}
10820 end R;
10821
10822 with R;
10823 procedure Main is
10824 begin
10825 @dots{}
10826 R.Q;
10827 end Main;
10828 @end cartouche
10829 @end smallexample
10830
10831 @noindent
10832 With the default behavior (no @option{-gnatn} switch specified), the
10833 compilation of the @code{Main} procedure depends only on its own source,
10834 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10835 means that editing the body of @code{R} does not require recompiling
10836 @code{Main}.
10837
10838 On the other hand, the call @code{R.Q} is not inlined under these
10839 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10840 is compiled, the call will be inlined if the body of @code{Q} is small
10841 enough, but now @code{Main} depends on the body of @code{R} in
10842 @file{r.adb} as well as on the spec. This means that if this body is edited,
10843 the main program must be recompiled. Note that this extra dependency
10844 occurs whether or not the call is in fact inlined by @command{gcc}.
10845
10846 The use of front end inlining with @option{-gnatN} generates similar
10847 additional dependencies.
10848
10849 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10850 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10851 can be used to prevent
10852 all inlining. This switch overrides all other conditions and ensures
10853 that no inlining occurs. The extra dependences resulting from
10854 @option{-gnatn} will still be active, even if
10855 this switch is used to suppress the resulting inlining actions.
10856
10857 @cindex @option{-fno-inline-functions} (@command{gcc})
10858 Note: The @option{-fno-inline-functions} switch can be used to prevent
10859 automatic inlining of subprograms if @option{-O3} is used.
10860
10861 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10862 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10863 automatic inlining of small subprograms if @option{-O2} is used.
10864
10865 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10866 Note: The @option{-fno-inline-functions-called-once} switch
10867 can be used to prevent inlining of subprograms local to the unit
10868 and called once from within it if @option{-O1} is used.
10869
10870 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10871 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10872 specified in lieu of it, @option{-gnatn} being translated into one of them
10873 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10874 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10875 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10876 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10877 full inlining across modules. If you have used pragma @code{Inline} in appropriate cases, then it is usually much better to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which has the additional
10878 effect of inlining subprograms you did not think should be inlined. We have
10879 found that the use of @option{-O3} may slow down the compilation and increase
10880 the code size by performing excessive inlining, leading to increased
10881 instruction cache pressure from the increased code size and thus minor
10882 performance improvements. So the bottom line here is that you should not
10883 automatically assume that @option{-O3} is better than @option{-O2}, and
10884 indeed you should use @option{-O3} only if tests show that it actually
10885 improves performance for your program.
10886
10887 @node Vectorization of loops
10888 @subsection Vectorization of loops
10889 @cindex Optimization Switches
10890
10891 You can take advantage of the auto-vectorizer present in the @command{gcc}
10892 back end to vectorize loops with GNAT. The corresponding command line switch
10893 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10894 and other aggressive optimizations helpful for vectorization also are enabled
10895 by default at this level, using @option{-O3} directly is recommended.
10896
10897 You also need to make sure that the target architecture features a supported
10898 SIMD instruction set. For example, for the x86 architecture, you should at
10899 least specify @option{-msse2} to get significant vectorization (but you don't
10900 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10901 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10902
10903 The preferred loop form for vectorization is the @code{for} iteration scheme.
10904 Loops with a @code{while} iteration scheme can also be vectorized if they are
10905 very simple, but the vectorizer will quickly give up otherwise. With either
10906 iteration scheme, the flow of control must be straight, in particular no
10907 @code{exit} statement may appear in the loop body. The loop may however
10908 contain a single nested loop, if it can be vectorized when considered alone:
10909
10910 @smallexample @c ada
10911 @cartouche
10912 A : array (1..4, 1..4) of Long_Float;
10913 S : array (1..4) of Long_Float;
10914
10915 procedure Sum is
10916 begin
10917 for I in A'Range(1) loop
10918 for J in A'Range(2) loop
10919 S (I) := S (I) + A (I, J);
10920 end loop;
10921 end loop;
10922 end Sum;
10923 @end cartouche
10924 @end smallexample
10925
10926 The vectorizable operations depend on the targeted SIMD instruction set, but
10927 the adding and some of the multiplying operators are generally supported, as
10928 well as the logical operators for modular types. Note that, in the former
10929 case, enabling overflow checks, for example with @option{-gnato}, totally
10930 disables vectorization. The other checks are not supposed to have the same
10931 definitive effect, although compiling with @option{-gnatp} might well reveal
10932 cases where some checks do thwart vectorization.
10933
10934 Type conversions may also prevent vectorization if they involve semantics that
10935 are not directly supported by the code generator or the SIMD instruction set.
10936 A typical example is direct conversion from floating-point to integer types.
10937 The solution in this case is to use the following idiom:
10938
10939 @smallexample @c ada
10940 Integer (S'Truncation (F))
10941 @end smallexample
10942
10943 @noindent
10944 if @code{S} is the subtype of floating-point object @code{F}.
10945
10946 In most cases, the vectorizable loops are loops that iterate over arrays.
10947 All kinds of array types are supported, i.e. constrained array types with
10948 static bounds:
10949
10950 @smallexample @c ada
10951 type Array_Type is array (1 .. 4) of Long_Float;
10952 @end smallexample
10953
10954 @noindent
10955 constrained array types with dynamic bounds:
10956
10957 @smallexample @c ada
10958 type Array_Type is array (1 .. Q.N) of Long_Float;
10959
10960 type Array_Type is array (Q.K .. 4) of Long_Float;
10961
10962 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10963 @end smallexample
10964
10965 @noindent
10966 or unconstrained array types:
10967
10968 @smallexample @c ada
10969 type Array_Type is array (Positive range <>) of Long_Float;
10970 @end smallexample
10971
10972 @noindent
10973 The quality of the generated code decreases when the dynamic aspect of the
10974 array type increases, the worst code being generated for unconstrained array
10975 types. This is so because, the less information the compiler has about the
10976 bounds of the array, the more fallback code it needs to generate in order to
10977 fix things up at run time.
10978
10979 It is possible to specify that a given loop should be subject to vectorization
10980 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10981
10982 @smallexample @c ada
10983 pragma Loop_Optimize (Vector);
10984 @end smallexample
10985
10986 @noindent
10987 placed immediately within the loop will convey the appropriate hint to the
10988 compiler for this loop.
10989
10990 You can obtain information about the vectorization performed by the compiler
10991 by specifying @option{-ftree-vectorizer-verbose=N}. For more details of
10992 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10993 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10994
10995 @node Other Optimization Switches
10996 @subsection Other Optimization Switches
10997 @cindex Optimization Switches
10998
10999 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
11000 @command{gcc} optimization switches are potentially usable. These switches
11001 have not been extensively tested with GNAT but can generally be expected
11002 to work. Examples of switches in this category are @option{-funroll-loops}
11003 and the various target-specific @option{-m} options (in particular, it has
11004 been observed that @option{-march=xxx} can significantly improve performance
11005 on appropriate machines). For full details of these switches, see
11006 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
11007 the GNU Compiler Collection (GCC)}.
11008
11009 @node Optimization and Strict Aliasing
11010 @subsection Optimization and Strict Aliasing
11011 @cindex Aliasing
11012 @cindex Strict Aliasing
11013 @cindex No_Strict_Aliasing
11014
11015 @noindent
11016 The strong typing capabilities of Ada allow an optimizer to generate
11017 efficient code in situations where other languages would be forced to
11018 make worst case assumptions preventing such optimizations. Consider
11019 the following example:
11020
11021 @smallexample @c ada
11022 @cartouche
11023 procedure R is
11024 type Int1 is new Integer;
11025 type Int2 is new Integer;
11026 type Int1A is access Int1;
11027 type Int2A is access Int2;
11028 Int1V : Int1A;
11029 Int2V : Int2A;
11030 @dots{}
11031
11032 begin
11033 @dots{}
11034 for J in Data'Range loop
11035 if Data (J) = Int1V.all then
11036 Int2V.all := Int2V.all + 1;
11037 end if;
11038 end loop;
11039 @dots{}
11040 end R;
11041 @end cartouche
11042 @end smallexample
11043
11044 @noindent
11045 In this example, since the variable @code{Int1V} can only access objects
11046 of type @code{Int1}, and @code{Int2V} can only access objects of type
11047 @code{Int2}, there is no possibility that the assignment to
11048 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
11049 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
11050 for all iterations of the loop and avoid the extra memory reference
11051 required to dereference it each time through the loop.
11052
11053 This kind of optimization, called strict aliasing analysis, is
11054 triggered by specifying an optimization level of @option{-O2} or
11055 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
11056 when access values are involved.
11057
11058 However, although this optimization is always correct in terms of
11059 the formal semantics of the Ada Reference Manual, difficulties can
11060 arise if features like @code{Unchecked_Conversion} are used to break
11061 the typing system. Consider the following complete program example:
11062
11063 @smallexample @c ada
11064 @cartouche
11065 package p1 is
11066 type int1 is new integer;
11067 type int2 is new integer;
11068 type a1 is access int1;
11069 type a2 is access int2;
11070 end p1;
11071
11072 with p1; use p1;
11073 package p2 is
11074 function to_a2 (Input : a1) return a2;
11075 end p2;
11076
11077 with Unchecked_Conversion;
11078 package body p2 is
11079 function to_a2 (Input : a1) return a2 is
11080 function to_a2u is
11081 new Unchecked_Conversion (a1, a2);
11082 begin
11083 return to_a2u (Input);
11084 end to_a2;
11085 end p2;
11086
11087 with p2; use p2;
11088 with p1; use p1;
11089 with Text_IO; use Text_IO;
11090 procedure m is
11091 v1 : a1 := new int1;
11092 v2 : a2 := to_a2 (v1);
11093 begin
11094 v1.all := 1;
11095 v2.all := 0;
11096 put_line (int1'image (v1.all));
11097 end;
11098 @end cartouche
11099 @end smallexample
11100
11101 @noindent
11102 This program prints out 0 in @option{-O0} or @option{-O1}
11103 mode, but it prints out 1 in @option{-O2} mode. That's
11104 because in strict aliasing mode, the compiler can and
11105 does assume that the assignment to @code{v2.all} could not
11106 affect the value of @code{v1.all}, since different types
11107 are involved.
11108
11109 This behavior is not a case of non-conformance with the standard, since
11110 the Ada RM specifies that an unchecked conversion where the resulting
11111 bit pattern is not a correct value of the target type can result in an
11112 abnormal value and attempting to reference an abnormal value makes the
11113 execution of a program erroneous. That's the case here since the result
11114 does not point to an object of type @code{int2}. This means that the
11115 effect is entirely unpredictable.
11116
11117 However, although that explanation may satisfy a language
11118 lawyer, in practice an applications programmer expects an
11119 unchecked conversion involving pointers to create true
11120 aliases and the behavior of printing 1 seems plain wrong.
11121 In this case, the strict aliasing optimization is unwelcome.
11122
11123 Indeed the compiler recognizes this possibility, and the
11124 unchecked conversion generates a warning:
11125
11126 @smallexample
11127 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11128 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11129 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
11130 @end smallexample
11131
11132 @noindent
11133 Unfortunately the problem is recognized when compiling the body of
11134 package @code{p2}, but the actual "bad" code is generated while
11135 compiling the body of @code{m} and this latter compilation does not see
11136 the suspicious @code{Unchecked_Conversion}.
11137
11138 As implied by the warning message, there are approaches you can use to
11139 avoid the unwanted strict aliasing optimization in a case like this.
11140
11141 One possibility is to simply avoid the use of @option{-O2}, but
11142 that is a bit drastic, since it throws away a number of useful
11143 optimizations that do not involve strict aliasing assumptions.
11144
11145 A less drastic approach is to compile the program using the
11146 option @option{-fno-strict-aliasing}. Actually it is only the
11147 unit containing the dereferencing of the suspicious pointer
11148 that needs to be compiled. So in this case, if we compile
11149 unit @code{m} with this switch, then we get the expected
11150 value of zero printed. Analyzing which units might need
11151 the switch can be painful, so a more reasonable approach
11152 is to compile the entire program with options @option{-O2}
11153 and @option{-fno-strict-aliasing}. If the performance is
11154 satisfactory with this combination of options, then the
11155 advantage is that the entire issue of possible "wrong"
11156 optimization due to strict aliasing is avoided.
11157
11158 To avoid the use of compiler switches, the configuration
11159 pragma @code{No_Strict_Aliasing} with no parameters may be
11160 used to specify that for all access types, the strict
11161 aliasing optimization should be suppressed.
11162
11163 However, these approaches are still overkill, in that they causes
11164 all manipulations of all access values to be deoptimized. A more
11165 refined approach is to concentrate attention on the specific
11166 access type identified as problematic.
11167
11168 First, if a careful analysis of uses of the pointer shows
11169 that there are no possible problematic references, then
11170 the warning can be suppressed by bracketing the
11171 instantiation of @code{Unchecked_Conversion} to turn
11172 the warning off:
11173
11174 @smallexample @c ada
11175 pragma Warnings (Off);
11176 function to_a2u is
11177 new Unchecked_Conversion (a1, a2);
11178 pragma Warnings (On);
11179 @end smallexample
11180
11181 @noindent
11182 Of course that approach is not appropriate for this particular
11183 example, since indeed there is a problematic reference. In this
11184 case we can take one of two other approaches.
11185
11186 The first possibility is to move the instantiation of unchecked
11187 conversion to the unit in which the type is declared. In
11188 this example, we would move the instantiation of
11189 @code{Unchecked_Conversion} from the body of package
11190 @code{p2} to the spec of package @code{p1}. Now the
11191 warning disappears. That's because any use of the
11192 access type knows there is a suspicious unchecked
11193 conversion, and the strict aliasing optimization
11194 is automatically suppressed for the type.
11195
11196 If it is not practical to move the unchecked conversion to the same unit
11197 in which the destination access type is declared (perhaps because the
11198 source type is not visible in that unit), you may use pragma
11199 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11200 same declarative sequence as the declaration of the access type:
11201
11202 @smallexample @c ada
11203 type a2 is access int2;
11204 pragma No_Strict_Aliasing (a2);
11205 @end smallexample
11206
11207 @noindent
11208 Here again, the compiler now knows that the strict aliasing optimization
11209 should be suppressed for any reference to type @code{a2} and the
11210 expected behavior is obtained.
11211
11212 Finally, note that although the compiler can generate warnings for
11213 simple cases of unchecked conversions, there are tricker and more
11214 indirect ways of creating type incorrect aliases which the compiler
11215 cannot detect. Examples are the use of address overlays and unchecked
11216 conversions involving composite types containing access types as
11217 components. In such cases, no warnings are generated, but there can
11218 still be aliasing problems. One safe coding practice is to forbid the
11219 use of address clauses for type overlaying, and to allow unchecked
11220 conversion only for primitive types. This is not really a significant
11221 restriction since any possible desired effect can be achieved by
11222 unchecked conversion of access values.
11223
11224 The aliasing analysis done in strict aliasing mode can certainly
11225 have significant benefits. We have seen cases of large scale
11226 application code where the time is increased by up to 5% by turning
11227 this optimization off. If you have code that includes significant
11228 usage of unchecked conversion, you might want to just stick with
11229 @option{-O1} and avoid the entire issue. If you get adequate
11230 performance at this level of optimization level, that's probably
11231 the safest approach. If tests show that you really need higher
11232 levels of optimization, then you can experiment with @option{-O2}
11233 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11234 has on size and speed of the code. If you really need to use
11235 @option{-O2} with strict aliasing in effect, then you should
11236 review any uses of unchecked conversion of access types,
11237 particularly if you are getting the warnings described above.
11238
11239 @ifset vms
11240 @node Coverage Analysis
11241 @subsection Coverage Analysis
11242
11243 @noindent
11244 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11245 the user to determine the distribution of execution time across a program,
11246 @pxref{Profiling} for details of usage.
11247 @end ifset
11248
11249
11250 @node Text_IO Suggestions
11251 @section @code{Text_IO} Suggestions
11252 @cindex @code{Text_IO} and performance
11253
11254 @noindent
11255 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11256 the requirement of maintaining page and line counts. If performance
11257 is critical, a recommendation is to use @code{Stream_IO} instead of
11258 @code{Text_IO} for volume output, since this package has less overhead.
11259
11260 If @code{Text_IO} must be used, note that by default output to the standard
11261 output and standard error files is unbuffered (this provides better
11262 behavior when output statements are used for debugging, or if the
11263 progress of a program is observed by tracking the output, e.g. by
11264 using the Unix @command{tail -f} command to watch redirected output.
11265
11266 If you are generating large volumes of output with @code{Text_IO} and
11267 performance is an important factor, use a designated file instead
11268 of the standard output file, or change the standard output file to
11269 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11270
11271
11272
11273 @node Reducing Size of Ada Executables with gnatelim
11274 @section Reducing Size of Ada Executables with @code{gnatelim}
11275 @findex gnatelim
11276
11277 @noindent
11278 This section describes @command{gnatelim}, a tool which detects unused
11279 subprograms and helps the compiler to create a smaller executable for your
11280 program.
11281
11282 @menu
11283 * About gnatelim::
11284 * Running gnatelim::
11285 * Processing Precompiled Libraries::
11286 * Correcting the List of Eliminate Pragmas::
11287 * Making Your Executables Smaller::
11288 * Summary of the gnatelim Usage Cycle::
11289 @end menu
11290
11291 @node About gnatelim
11292 @subsection About @code{gnatelim}
11293
11294 @noindent
11295 When a program shares a set of Ada
11296 packages with other programs, it may happen that this program uses
11297 only a fraction of the subprograms defined in these packages. The code
11298 created for these unused subprograms increases the size of the executable.
11299
11300 @code{gnatelim} tracks unused subprograms in an Ada program and
11301 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11302 subprograms that are declared but never called. By placing the list of
11303 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11304 recompiling your program, you may decrease the size of its executable,
11305 because the compiler will not generate the code for 'eliminated' subprograms.
11306 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11307 information about this pragma.
11308
11309 @code{gnatelim} needs as its input data the name of the main subprogram.
11310
11311 If a set of source files is specified as @code{gnatelim} arguments, it
11312 treats these files as a complete set of sources making up a program to
11313 analyse, and analyses only these sources.
11314
11315 After a full successful build of the main subprogram @code{gnatelim} can be
11316 called without specifying sources to analyse, in this case it computes
11317 the source closure of the main unit from the @file{ALI} files.
11318
11319 The following command will create the set of @file{ALI} files needed for
11320 @code{gnatelim}:
11321
11322 @smallexample
11323 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11324 @end smallexample
11325
11326 Note that @code{gnatelim} does not need object files.
11327
11328 @node Running gnatelim
11329 @subsection Running @code{gnatelim}
11330
11331 @noindent
11332 @code{gnatelim} has the following command-line interface:
11333
11334 @smallexample
11335 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11336 @end smallexample
11337
11338 @noindent
11339 @var{main_unit_name} should be a name of a source file that contains the main
11340 subprogram of a program (partition).
11341
11342 Each @var{filename} is the name (including the extension) of a source
11343 file to process. ``Wildcards'' are allowed, and
11344 the file name may contain path information.
11345
11346 @samp{@var{gcc_switches}} is a list of switches for
11347 @command{gcc}. They will be passed on to all compiler invocations made by
11348 @command{gnatelim} to generate the ASIS trees. Here you can provide
11349 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11350 use the @option{-gnatec} switch to set the configuration file,
11351 use the @option{-gnat05} switch if sources should be compiled in
11352 Ada 2005 mode etc.
11353
11354 @code{gnatelim} has the following switches:
11355
11356 @table @option
11357 @c !sort!
11358 @item ^-files^/FILES^=@var{filename}
11359 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11360 Take the argument source files from the specified file. This file should be an
11361 ordinary text file containing file names separated by spaces or
11362 line breaks. You can use this switch more than once in the same call to
11363 @command{gnatelim}. You also can combine this switch with
11364 an explicit list of files.
11365
11366 @item ^-log^/LOG^
11367 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11368 Duplicate all the output sent to @file{stderr} into a log file. The log file
11369 is named @file{gnatelim.log} and is located in the current directory.
11370
11371 @item ^-log^/LOGFILE^=@var{filename}
11372 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11373 Duplicate all the output sent to @file{stderr} into a specified log file.
11374
11375 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11376 @item ^--no-elim-dispatch^/NO_DISPATCH^
11377 Do not generate pragmas for dispatching operations.
11378
11379 @item ^--ignore^/IGNORE^=@var{filename}
11380 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11381 Do not generate pragmas for subprograms declared in the sources
11382 listed in a specified file
11383
11384 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11385 @item ^-o^/OUTPUT^=@var{report_file}
11386 Put @command{gnatelim} output into a specified file. If this file already exists,
11387 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11388 into @file{stderr}
11389
11390 @item ^-q^/QUIET^
11391 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11392 Quiet mode: by default @code{gnatelim} outputs to the standard error
11393 stream the number of program units left to be processed. This option turns
11394 this trace off.
11395
11396 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11397 @item ^-t^/TIME^
11398 Print out execution time.
11399
11400 @item ^-v^/VERBOSE^
11401 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11402 Verbose mode: @code{gnatelim} version information is printed as Ada
11403 comments to the standard output stream. Also, in addition to the number of
11404 program units left @code{gnatelim} will output the name of the current unit
11405 being processed.
11406
11407 @item ^-wq^/WARNINGS=QUIET^
11408 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11409 Quiet warning mode - some warnings are suppressed. In particular warnings that
11410 indicate that the analysed set of sources is incomplete to make up a
11411 partition and that some subprogram bodies are missing are not generated.
11412 @end table
11413
11414 @noindent
11415 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11416 driver (see @ref{The GNAT Driver and Project Files}).
11417
11418 @node Processing Precompiled Libraries
11419 @subsection Processing Precompiled Libraries
11420
11421 @noindent
11422 If some program uses a precompiled Ada library, it can be processed by
11423 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11424 Eliminate pragma for a subprogram if the body of this subprogram has not
11425 been analysed, this is a typical case for subprograms from precompiled
11426 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11427 warnings about missing source files and non-analyzed subprogram bodies
11428 that can be generated when processing precompiled Ada libraries.
11429
11430 @node Correcting the List of Eliminate Pragmas
11431 @subsection Correcting the List of Eliminate Pragmas
11432
11433 @noindent
11434 In some rare cases @code{gnatelim} may try to eliminate
11435 subprograms that are actually called in the program. In this case, the
11436 compiler will generate an error message of the form:
11437
11438 @smallexample
11439 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11440 @end smallexample
11441
11442 @noindent
11443 You will need to manually remove the wrong @code{Eliminate} pragmas from
11444 the configuration file indicated in the error message. You should recompile
11445 your program from scratch after that, because you need a consistent
11446 configuration file(s) during the entire compilation.
11447
11448 @node Making Your Executables Smaller
11449 @subsection Making Your Executables Smaller
11450
11451 @noindent
11452 In order to get a smaller executable for your program you now have to
11453 recompile the program completely with the configuration file containing
11454 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11455 @file{gnat.adc} file located in your current directory, just do:
11456
11457 @smallexample
11458 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11459 @end smallexample
11460
11461 @noindent
11462 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11463 recompile everything
11464 with the set of pragmas @code{Eliminate} that you have obtained with
11465 @command{gnatelim}).
11466
11467 Be aware that the set of @code{Eliminate} pragmas is specific to each
11468 program. It is not recommended to merge sets of @code{Eliminate}
11469 pragmas created for different programs in one configuration file.
11470
11471 @node Summary of the gnatelim Usage Cycle
11472 @subsection Summary of the @code{gnatelim} Usage Cycle
11473
11474 @noindent
11475 Here is a quick summary of the steps to be taken in order to reduce
11476 the size of your executables with @code{gnatelim}. You may use
11477 other GNAT options to control the optimization level,
11478 to produce the debugging information, to set search path, etc.
11479
11480 @enumerate
11481 @item
11482 Create a complete set of @file{ALI} files (if the program has not been
11483 built already)
11484
11485 @smallexample
11486 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11487 @end smallexample
11488
11489 @item
11490 Generate a list of @code{Eliminate} pragmas in default configuration file
11491 @file{gnat.adc} in the current directory
11492 @smallexample
11493 @ifset vms
11494 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11495 @end ifset
11496 @ifclear vms
11497 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11498 @end ifclear
11499 @end smallexample
11500
11501 @item
11502 Recompile the application
11503
11504 @smallexample
11505 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11506 @end smallexample
11507
11508 @end enumerate
11509
11510 @node Reducing Size of Executables with unused subprogram/data elimination
11511 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11512 @findex unused subprogram/data elimination
11513
11514 @noindent
11515 This section describes how you can eliminate unused subprograms and data from
11516 your executable just by setting options at compilation time.
11517
11518 @menu
11519 * About unused subprogram/data elimination::
11520 * Compilation options::
11521 * Example of unused subprogram/data elimination::
11522 @end menu
11523
11524 @node About unused subprogram/data elimination
11525 @subsection About unused subprogram/data elimination
11526
11527 @noindent
11528 By default, an executable contains all code and data of its composing objects
11529 (directly linked or coming from statically linked libraries), even data or code
11530 never used by this executable.
11531
11532 This feature will allow you to eliminate such unused code from your
11533 executable, making it smaller (in disk and in memory).
11534
11535 This functionality is available on all Linux platforms except for the IA-64
11536 architecture and on all cross platforms using the ELF binary file format.
11537 In both cases GNU binutils version 2.16 or later are required to enable it.
11538
11539 @node Compilation options
11540 @subsection Compilation options
11541
11542 @noindent
11543 The operation of eliminating the unused code and data from the final executable
11544 is directly performed by the linker.
11545
11546 In order to do this, it has to work with objects compiled with the
11547 following options:
11548 @option{-ffunction-sections} @option{-fdata-sections}.
11549 @cindex @option{-ffunction-sections} (@command{gcc})
11550 @cindex @option{-fdata-sections} (@command{gcc})
11551 These options are usable with C and Ada files.
11552 They will place respectively each
11553 function or data in a separate section in the resulting object file.
11554
11555 Once the objects and static libraries are created with these options, the
11556 linker can perform the dead code elimination. You can do this by setting
11557 the @option{-Wl,--gc-sections} option to gcc command or in the
11558 @option{-largs} section of @command{gnatmake}. This will perform a
11559 garbage collection of code and data never referenced.
11560
11561 If the linker performs a partial link (@option{-r} ld linker option), then you
11562 will need to provide one or several entry point using the
11563 @option{-e} / @option{--entry} ld option.
11564
11565 Note that objects compiled without the @option{-ffunction-sections} and
11566 @option{-fdata-sections} options can still be linked with the executable.
11567 However, no dead code elimination will be performed on those objects (they will
11568 be linked as is).
11569
11570 The GNAT static library is now compiled with -ffunction-sections and
11571 -fdata-sections on some platforms. This allows you to eliminate the unused code
11572 and data of the GNAT library from your executable.
11573
11574 @node Example of unused subprogram/data elimination
11575 @subsection Example of unused subprogram/data elimination
11576
11577 @noindent
11578 Here is a simple example:
11579
11580 @smallexample @c ada
11581 with Aux;
11582
11583 procedure Test is
11584 begin
11585 Aux.Used (10);
11586 end Test;
11587
11588 package Aux is
11589 Used_Data : Integer;
11590 Unused_Data : Integer;
11591
11592 procedure Used (Data : Integer);
11593 procedure Unused (Data : Integer);
11594 end Aux;
11595
11596 package body Aux is
11597 procedure Used (Data : Integer) is
11598 begin
11599 Used_Data := Data;
11600 end Used;
11601
11602 procedure Unused (Data : Integer) is
11603 begin
11604 Unused_Data := Data;
11605 end Unused;
11606 end Aux;
11607 @end smallexample
11608
11609 @noindent
11610 @code{Unused} and @code{Unused_Data} are never referenced in this code
11611 excerpt, and hence they may be safely removed from the final executable.
11612
11613 @smallexample
11614 $ gnatmake test
11615
11616 $ nm test | grep used
11617 020015f0 T aux__unused
11618 02005d88 B aux__unused_data
11619 020015cc T aux__used
11620 02005d84 B aux__used_data
11621
11622 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11623 -largs -Wl,--gc-sections
11624
11625 $ nm test | grep used
11626 02005350 T aux__used
11627 0201ffe0 B aux__used_data
11628 @end smallexample
11629
11630 @noindent
11631 It can be observed that the procedure @code{Unused} and the object
11632 @code{Unused_Data} are removed by the linker when using the
11633 appropriate options.
11634
11635 @c ********************************
11636 @node Renaming Files Using gnatchop
11637 @chapter Renaming Files Using @code{gnatchop}
11638 @findex gnatchop
11639
11640 @noindent
11641 This chapter discusses how to handle files with multiple units by using
11642 the @code{gnatchop} utility. This utility is also useful in renaming
11643 files to meet the standard GNAT default file naming conventions.
11644
11645 @menu
11646 * Handling Files with Multiple Units::
11647 * Operating gnatchop in Compilation Mode::
11648 * Command Line for gnatchop::
11649 * Switches for gnatchop::
11650 * Examples of gnatchop Usage::
11651 @end menu
11652
11653 @node Handling Files with Multiple Units
11654 @section Handling Files with Multiple Units
11655
11656 @noindent
11657 The basic compilation model of GNAT requires that a file submitted to the
11658 compiler have only one unit and there be a strict correspondence
11659 between the file name and the unit name.
11660
11661 The @code{gnatchop} utility allows both of these rules to be relaxed,
11662 allowing GNAT to process files which contain multiple compilation units
11663 and files with arbitrary file names. @code{gnatchop}
11664 reads the specified file and generates one or more output files,
11665 containing one unit per file. The unit and the file name correspond,
11666 as required by GNAT.
11667
11668 If you want to permanently restructure a set of ``foreign'' files so that
11669 they match the GNAT rules, and do the remaining development using the
11670 GNAT structure, you can simply use @command{gnatchop} once, generate the
11671 new set of files and work with them from that point on.
11672
11673 Alternatively, if you want to keep your files in the ``foreign'' format,
11674 perhaps to maintain compatibility with some other Ada compilation
11675 system, you can set up a procedure where you use @command{gnatchop} each
11676 time you compile, regarding the source files that it writes as temporary
11677 files that you throw away.
11678
11679 Note that if your file containing multiple units starts with a byte order
11680 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11681 will each start with a copy of this BOM, meaning that they can be compiled
11682 automatically in UTF-8 mode without needing to specify an explicit encoding.
11683
11684 @node Operating gnatchop in Compilation Mode
11685 @section Operating gnatchop in Compilation Mode
11686
11687 @noindent
11688 The basic function of @code{gnatchop} is to take a file with multiple units
11689 and split it into separate files. The boundary between files is reasonably
11690 clear, except for the issue of comments and pragmas. In default mode, the
11691 rule is that any pragmas between units belong to the previous unit, except
11692 that configuration pragmas always belong to the following unit. Any comments
11693 belong to the following unit. These rules
11694 almost always result in the right choice of
11695 the split point without needing to mark it explicitly and most users will
11696 find this default to be what they want. In this default mode it is incorrect to
11697 submit a file containing only configuration pragmas, or one that ends in
11698 configuration pragmas, to @code{gnatchop}.
11699
11700 However, using a special option to activate ``compilation mode'',
11701 @code{gnatchop}
11702 can perform another function, which is to provide exactly the semantics
11703 required by the RM for handling of configuration pragmas in a compilation.
11704 In the absence of configuration pragmas (at the main file level), this
11705 option has no effect, but it causes such configuration pragmas to be handled
11706 in a quite different manner.
11707
11708 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11709 only configuration pragmas, then this file is appended to the
11710 @file{gnat.adc} file in the current directory. This behavior provides
11711 the required behavior described in the RM for the actions to be taken
11712 on submitting such a file to the compiler, namely that these pragmas
11713 should apply to all subsequent compilations in the same compilation
11714 environment. Using GNAT, the current directory, possibly containing a
11715 @file{gnat.adc} file is the representation
11716 of a compilation environment. For more information on the
11717 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11718
11719 Second, in compilation mode, if @code{gnatchop}
11720 is given a file that starts with
11721 configuration pragmas, and contains one or more units, then these
11722 configuration pragmas are prepended to each of the chopped files. This
11723 behavior provides the required behavior described in the RM for the
11724 actions to be taken on compiling such a file, namely that the pragmas
11725 apply to all units in the compilation, but not to subsequently compiled
11726 units.
11727
11728 Finally, if configuration pragmas appear between units, they are appended
11729 to the previous unit. This results in the previous unit being illegal,
11730 since the compiler does not accept configuration pragmas that follow
11731 a unit. This provides the required RM behavior that forbids configuration
11732 pragmas other than those preceding the first compilation unit of a
11733 compilation.
11734
11735 For most purposes, @code{gnatchop} will be used in default mode. The
11736 compilation mode described above is used only if you need exactly
11737 accurate behavior with respect to compilations, and you have files
11738 that contain multiple units and configuration pragmas. In this
11739 circumstance the use of @code{gnatchop} with the compilation mode
11740 switch provides the required behavior, and is for example the mode
11741 in which GNAT processes the ACVC tests.
11742
11743 @node Command Line for gnatchop
11744 @section Command Line for @code{gnatchop}
11745
11746 @noindent
11747 The @code{gnatchop} command has the form:
11748
11749 @smallexample
11750 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11751 @c @ovar{directory}
11752 @c Expanding @ovar macro inline (explanation in macro def comments)
11753 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11754 @r{[}@var{directory}@r{]}
11755 @end smallexample
11756
11757 @noindent
11758 The only required argument is the file name of the file to be chopped.
11759 There are no restrictions on the form of this file name. The file itself
11760 contains one or more Ada units, in normal GNAT format, concatenated
11761 together. As shown, more than one file may be presented to be chopped.
11762
11763 When run in default mode, @code{gnatchop} generates one output file in
11764 the current directory for each unit in each of the files.
11765
11766 @var{directory}, if specified, gives the name of the directory to which
11767 the output files will be written. If it is not specified, all files are
11768 written to the current directory.
11769
11770 For example, given a
11771 file called @file{hellofiles} containing
11772
11773 @smallexample @c ada
11774 @group
11775 @cartouche
11776 procedure hello;
11777
11778 with Text_IO; use Text_IO;
11779 procedure hello is
11780 begin
11781 Put_Line ("Hello");
11782 end hello;
11783 @end cartouche
11784 @end group
11785 @end smallexample
11786
11787 @noindent
11788 the command
11789
11790 @smallexample
11791 $ gnatchop ^hellofiles^HELLOFILES.^
11792 @end smallexample
11793
11794 @noindent
11795 generates two files in the current directory, one called
11796 @file{hello.ads} containing the single line that is the procedure spec,
11797 and the other called @file{hello.adb} containing the remaining text. The
11798 original file is not affected. The generated files can be compiled in
11799 the normal manner.
11800
11801 @noindent
11802 When gnatchop is invoked on a file that is empty or that contains only empty
11803 lines and/or comments, gnatchop will not fail, but will not produce any
11804 new sources.
11805
11806 For example, given a
11807 file called @file{toto.txt} containing
11808
11809 @smallexample @c ada
11810 @group
11811 @cartouche
11812 -- Just a comment
11813 @end cartouche
11814 @end group
11815 @end smallexample
11816
11817 @noindent
11818 the command
11819
11820 @smallexample
11821 $ gnatchop ^toto.txt^TOT.TXT^
11822 @end smallexample
11823
11824 @noindent
11825 will not produce any new file and will result in the following warnings:
11826
11827 @smallexample
11828 toto.txt:1:01: warning: empty file, contains no compilation units
11829 no compilation units found
11830 no source files written
11831 @end smallexample
11832
11833 @node Switches for gnatchop
11834 @section Switches for @code{gnatchop}
11835
11836 @noindent
11837 @command{gnatchop} recognizes the following switches:
11838
11839 @table @option
11840 @c !sort!
11841
11842 @item --version
11843 @cindex @option{--version} @command{gnatchop}
11844 Display Copyright and version, then exit disregarding all other options.
11845
11846 @item --help
11847 @cindex @option{--help} @command{gnatchop}
11848 If @option{--version} was not used, display usage, then exit disregarding
11849 all other options.
11850
11851 @item ^-c^/COMPILATION^
11852 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11853 Causes @code{gnatchop} to operate in compilation mode, in which
11854 configuration pragmas are handled according to strict RM rules. See
11855 previous section for a full description of this mode.
11856
11857 @ifclear vms
11858 @item -gnat@var{xxx}
11859 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11860 used to parse the given file. Not all @var{xxx} options make sense,
11861 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11862 process a source file that uses Latin-2 coding for identifiers.
11863 @end ifclear
11864
11865 @item ^-h^/HELP^
11866 Causes @code{gnatchop} to generate a brief help summary to the standard
11867 output file showing usage information.
11868
11869 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11870 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11871 Limit generated file names to the specified number @code{mm}
11872 of characters.
11873 This is useful if the
11874 resulting set of files is required to be interoperable with systems
11875 which limit the length of file names.
11876 @ifset vms
11877 If no value is given, or
11878 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11879 a default of 39, suitable for OpenVMS Alpha
11880 Systems, is assumed
11881 @end ifset
11882 @ifclear vms
11883 No space is allowed between the @option{-k} and the numeric value. The numeric
11884 value may be omitted in which case a default of @option{-k8},
11885 suitable for use
11886 with DOS-like file systems, is used. If no @option{-k} switch
11887 is present then
11888 there is no limit on the length of file names.
11889 @end ifclear
11890
11891 @item ^-p^/PRESERVE^
11892 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11893 Causes the file ^modification^creation^ time stamp of the input file to be
11894 preserved and used for the time stamp of the output file(s). This may be
11895 useful for preserving coherency of time stamps in an environment where
11896 @code{gnatchop} is used as part of a standard build process.
11897
11898 @item ^-q^/QUIET^
11899 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11900 Causes output of informational messages indicating the set of generated
11901 files to be suppressed. Warnings and error messages are unaffected.
11902
11903 @item ^-r^/REFERENCE^
11904 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11905 @findex Source_Reference
11906 Generate @code{Source_Reference} pragmas. Use this switch if the output
11907 files are regarded as temporary and development is to be done in terms
11908 of the original unchopped file. This switch causes
11909 @code{Source_Reference} pragmas to be inserted into each of the
11910 generated files to refers back to the original file name and line number.
11911 The result is that all error messages refer back to the original
11912 unchopped file.
11913 In addition, the debugging information placed into the object file (when
11914 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11915 specified)
11916 also refers back to this original file so that tools like profilers and
11917 debuggers will give information in terms of the original unchopped file.
11918
11919 If the original file to be chopped itself contains
11920 a @code{Source_Reference}
11921 pragma referencing a third file, then gnatchop respects
11922 this pragma, and the generated @code{Source_Reference} pragmas
11923 in the chopped file refer to the original file, with appropriate
11924 line numbers. This is particularly useful when @code{gnatchop}
11925 is used in conjunction with @code{gnatprep} to compile files that
11926 contain preprocessing statements and multiple units.
11927
11928 @item ^-v^/VERBOSE^
11929 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11930 Causes @code{gnatchop} to operate in verbose mode. The version
11931 number and copyright notice are output, as well as exact copies of
11932 the gnat1 commands spawned to obtain the chop control information.
11933
11934 @item ^-w^/OVERWRITE^
11935 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11936 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11937 fatal error if there is already a file with the same name as a
11938 file it would otherwise output, in other words if the files to be
11939 chopped contain duplicated units. This switch bypasses this
11940 check, and causes all but the last instance of such duplicated
11941 units to be skipped.
11942
11943 @ifclear vms
11944 @item --GCC=@var{xxxx}
11945 @cindex @option{--GCC=} (@code{gnatchop})
11946 Specify the path of the GNAT parser to be used. When this switch is used,
11947 no attempt is made to add the prefix to the GNAT parser executable.
11948 @end ifclear
11949 @end table
11950
11951 @node Examples of gnatchop Usage
11952 @section Examples of @code{gnatchop} Usage
11953
11954 @table @code
11955 @ifset vms
11956 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11957 @end ifset
11958 @ifclear vms
11959 @item gnatchop -w hello_s.ada prerelease/files
11960 @end ifclear
11961
11962 Chops the source file @file{hello_s.ada}. The output files will be
11963 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11964 overwriting any
11965 files with matching names in that directory (no files in the current
11966 directory are modified).
11967
11968 @item gnatchop ^archive^ARCHIVE.^
11969 Chops the source file @file{^archive^ARCHIVE.^}
11970 into the current directory. One
11971 useful application of @code{gnatchop} is in sending sets of sources
11972 around, for example in email messages. The required sources are simply
11973 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11974 command), and then
11975 @command{gnatchop} is used at the other end to reconstitute the original
11976 file names.
11977
11978 @item gnatchop file1 file2 file3 direc
11979 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11980 the resulting files in the directory @file{direc}. Note that if any units
11981 occur more than once anywhere within this set of files, an error message
11982 is generated, and no files are written. To override this check, use the
11983 @option{^-w^/OVERWRITE^} switch,
11984 in which case the last occurrence in the last file will
11985 be the one that is output, and earlier duplicate occurrences for a given
11986 unit will be skipped.
11987 @end table
11988
11989 @node Configuration Pragmas
11990 @chapter Configuration Pragmas
11991 @cindex Configuration pragmas
11992 @cindex Pragmas, configuration
11993
11994 @noindent
11995 Configuration pragmas include those pragmas described as
11996 such in the Ada Reference Manual, as well as
11997 implementation-dependent pragmas that are configuration pragmas.
11998 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11999 for details on these additional GNAT-specific configuration pragmas.
12000 Most notably, the pragma @code{Source_File_Name}, which allows
12001 specifying non-default names for source files, is a configuration
12002 pragma. The following is a complete list of configuration pragmas
12003 recognized by GNAT:
12004
12005 @smallexample
12006 Ada_83
12007 Ada_95
12008 Ada_05
12009 Ada_2005
12010 Ada_12
12011 Ada_2012
12012 Annotate
12013 Assertion_Policy
12014 Assume_No_Invalid_Values
12015 C_Pass_By_Copy
12016 Check_Name
12017 Check_Policy
12018 Compile_Time_Error
12019 Compile_Time_Warning
12020 Compiler_Unit
12021 Component_Alignment
12022 Convention_Identifier
12023 Debug_Policy
12024 Detect_Blocking
12025 Default_Storage_Pool
12026 Discard_Names
12027 Elaboration_Checks
12028 Eliminate
12029 Extend_System
12030 Extensions_Allowed
12031 External_Name_Casing
12032 Fast_Math
12033 Favor_Top_Level
12034 Float_Representation
12035 Implicit_Packing
12036 Initialize_Scalars
12037 Interrupt_State
12038 License
12039 Locking_Policy
12040 Long_Float
12041 No_Run_Time
12042 No_Strict_Aliasing
12043 Normalize_Scalars
12044 Optimize_Alignment
12045 Persistent_BSS
12046 Polling
12047 Priority_Specific_Dispatching
12048 Profile
12049 Profile_Warnings
12050 Propagate_Exceptions
12051 Queuing_Policy
12052 Ravenscar
12053 Restricted_Run_Time
12054 Restrictions
12055 Restrictions_Warnings
12056 Reviewable
12057 Short_Circuit_And_Or
12058 Source_File_Name
12059 Source_File_Name_Project
12060 Style_Checks
12061 Suppress
12062 Suppress_Exception_Locations
12063 Task_Dispatching_Policy
12064 Universal_Data
12065 Unsuppress
12066 Use_VADS_Size
12067 Validity_Checks
12068 Warnings
12069 Wide_Character_Encoding
12070
12071 @end smallexample
12072
12073 @menu
12074 * Handling of Configuration Pragmas::
12075 * The Configuration Pragmas Files::
12076 @end menu
12077
12078 @node Handling of Configuration Pragmas
12079 @section Handling of Configuration Pragmas
12080
12081 Configuration pragmas may either appear at the start of a compilation
12082 unit, or they can appear in a configuration pragma file to apply to
12083 all compilations performed in a given compilation environment.
12084
12085 GNAT also provides the @code{gnatchop} utility to provide an automatic
12086 way to handle configuration pragmas following the semantics for
12087 compilations (that is, files with multiple units), described in the RM.
12088 See @ref{Operating gnatchop in Compilation Mode} for details.
12089 However, for most purposes, it will be more convenient to edit the
12090 @file{gnat.adc} file that contains configuration pragmas directly,
12091 as described in the following section.
12092
12093 In the case of @code{Restrictions} pragmas appearing as configuration
12094 pragmas in individual compilation units, the exact handling depends on
12095 the type of restriction.
12096
12097 Restrictions that require partition-wide consistency (like
12098 @code{No_Tasking}) are
12099 recognized wherever they appear
12100 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12101 unit. This makes sense since the binder will in any case insist on seeing
12102 consistent use, so any unit not conforming to any restrictions that are
12103 anywhere in the partition will be rejected, and you might as well find
12104 that out at compile time rather than at bind time.
12105
12106 For restrictions that do not require partition-wide consistency, e.g.
12107 SPARK or No_Implementation_Attributes, in general the restriction applies
12108 only to the unit in which the pragma appears, and not to any other units.
12109
12110 The exception is No_Elaboration_Code which always applies to the entire
12111 object file from a compilation, i.e. to the body, spec, and all subunits.
12112 This restriction can be specified in a configuration pragma file, or it
12113 can be on the body and/or the spec (in eithe case it applies to all the
12114 relevant units). It can appear on a subunit only if it has previously
12115 appeared in the body of spec.
12116
12117 @node The Configuration Pragmas Files
12118 @section The Configuration Pragmas Files
12119 @cindex @file{gnat.adc}
12120
12121 @noindent
12122 In GNAT a compilation environment is defined by the current
12123 directory at the time that a compile command is given. This current
12124 directory is searched for a file whose name is @file{gnat.adc}. If
12125 this file is present, it is expected to contain one or more
12126 configuration pragmas that will be applied to the current compilation.
12127 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12128 considered.
12129
12130 Configuration pragmas may be entered into the @file{gnat.adc} file
12131 either by running @code{gnatchop} on a source file that consists only of
12132 configuration pragmas, or more conveniently by
12133 direct editing of the @file{gnat.adc} file, which is a standard format
12134 source file.
12135
12136 In addition to @file{gnat.adc}, additional files containing configuration
12137 pragmas may be applied to the current compilation using the switch
12138 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12139 contains only configuration pragmas. These configuration pragmas are
12140 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12141 is present and switch @option{-gnatA} is not used).
12142
12143 It is allowed to specify several switches @option{-gnatec}, all of which
12144 will be taken into account.
12145
12146 If you are using project file, a separate mechanism is provided using
12147 project attributes, see @ref{Specifying Configuration Pragmas} for more
12148 details.
12149
12150 @ifset vms
12151 Of special interest to GNAT OpenVMS Alpha is the following
12152 configuration pragma:
12153
12154 @smallexample @c ada
12155 @cartouche
12156 pragma Extend_System (Aux_DEC);
12157 @end cartouche
12158 @end smallexample
12159
12160 @noindent
12161 In the presence of this pragma, GNAT adds to the definition of the
12162 predefined package SYSTEM all the additional types and subprograms that are
12163 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12164 @end ifset
12165
12166 @node Handling Arbitrary File Naming Conventions Using gnatname
12167 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
12168 @cindex Arbitrary File Naming Conventions
12169
12170 @menu
12171 * Arbitrary File Naming Conventions::
12172 * Running gnatname::
12173 * Switches for gnatname::
12174 * Examples of gnatname Usage::
12175 @end menu
12176
12177 @node Arbitrary File Naming Conventions
12178 @section Arbitrary File Naming Conventions
12179
12180 @noindent
12181 The GNAT compiler must be able to know the source file name of a compilation
12182 unit. When using the standard GNAT default file naming conventions
12183 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12184 does not need additional information.
12185
12186 @noindent
12187 When the source file names do not follow the standard GNAT default file naming
12188 conventions, the GNAT compiler must be given additional information through
12189 a configuration pragmas file (@pxref{Configuration Pragmas})
12190 or a project file.
12191 When the non-standard file naming conventions are well-defined,
12192 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12193 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12194 if the file naming conventions are irregular or arbitrary, a number
12195 of pragma @code{Source_File_Name} for individual compilation units
12196 must be defined.
12197 To help maintain the correspondence between compilation unit names and
12198 source file names within the compiler,
12199 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12200 set of files.
12201
12202 @node Running gnatname
12203 @section Running @code{gnatname}
12204
12205 @noindent
12206 The usual form of the @code{gnatname} command is
12207
12208 @smallexample
12209 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12210 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12211 @c Expanding @ovar macro inline (explanation in macro def comments)
12212 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12213 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12214 @end smallexample
12215
12216 @noindent
12217 All of the arguments are optional. If invoked without any argument,
12218 @code{gnatname} will display its usage.
12219
12220 @noindent
12221 When used with at least one naming pattern, @code{gnatname} will attempt to
12222 find all the compilation units in files that follow at least one of the
12223 naming patterns. To find these compilation units,
12224 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12225 regular files.
12226
12227 @noindent
12228 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12229 Each Naming Pattern is enclosed between double quotes (or single
12230 quotes on Windows).
12231 A Naming Pattern is a regular expression similar to the wildcard patterns
12232 used in file names by the Unix shells or the DOS prompt.
12233
12234 @noindent
12235 @code{gnatname} may be called with several sections of directories/patterns.
12236 Sections are separated by switch @code{--and}. In each section, there must be
12237 at least one pattern. If no directory is specified in a section, the current
12238 directory (or the project directory is @code{-P} is used) is implied.
12239 The options other that the directory switches and the patterns apply globally
12240 even if they are in different sections.
12241
12242 @noindent
12243 Examples of Naming Patterns are
12244
12245 @smallexample
12246 "*.[12].ada"
12247 "*.ad[sb]*"
12248 "body_*" "spec_*"
12249 @end smallexample
12250
12251 @noindent
12252 For a more complete description of the syntax of Naming Patterns,
12253 see the second kind of regular expressions described in @file{g-regexp.ads}
12254 (the ``Glob'' regular expressions).
12255
12256 @noindent
12257 When invoked with no switch @code{-P}, @code{gnatname} will create a
12258 configuration pragmas file @file{gnat.adc} in the current working directory,
12259 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12260 unit.
12261
12262 @node Switches for gnatname
12263 @section Switches for @code{gnatname}
12264
12265 @noindent
12266 Switches for @code{gnatname} must precede any specified Naming Pattern.
12267
12268 @noindent
12269 You may specify any of the following switches to @code{gnatname}:
12270
12271 @table @option
12272 @c !sort!
12273
12274 @item --version
12275 @cindex @option{--version} @command{gnatname}
12276 Display Copyright and version, then exit disregarding all other options.
12277
12278 @item --help
12279 @cindex @option{--help} @command{gnatname}
12280 If @option{--version} was not used, display usage, then exit disregarding
12281 all other options.
12282
12283 @item --subdirs=<dir>
12284 Real object, library or exec directories are subdirectories <dir> of the
12285 specified ones.
12286
12287 @item --no-backup
12288 Do not create a backup copy of an existing project file.
12289
12290 @item --and
12291 Start another section of directories/patterns.
12292
12293 @item ^-c^/CONFIG_FILE=^@file{file}
12294 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12295 Create a configuration pragmas file @file{file} (instead of the default
12296 @file{gnat.adc}).
12297 @ifclear vms
12298 There may be zero, one or more space between @option{-c} and
12299 @file{file}.
12300 @end ifclear
12301 @file{file} may include directory information. @file{file} must be
12302 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12303 When a switch @option{^-c^/CONFIG_FILE^} is
12304 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12305
12306 @item ^-d^/SOURCE_DIRS=^@file{dir}
12307 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12308 Look for source files in directory @file{dir}. There may be zero, one or more
12309 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12310 @file{dir} may end with @code{/**}, that is it may be of the form
12311 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12312 subdirectories, recursively, have to be searched for sources.
12313 When a switch @option{^-d^/SOURCE_DIRS^}
12314 is specified, the current working directory will not be searched for source
12315 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12316 or @option{^-D^/DIR_FILES^} switch.
12317 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12318 If @file{dir} is a relative path, it is relative to the directory of
12319 the configuration pragmas file specified with switch
12320 @option{^-c^/CONFIG_FILE^},
12321 or to the directory of the project file specified with switch
12322 @option{^-P^/PROJECT_FILE^} or,
12323 if neither switch @option{^-c^/CONFIG_FILE^}
12324 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12325 current working directory. The directory
12326 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12327
12328 @item ^-D^/DIRS_FILE=^@file{file}
12329 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12330 Look for source files in all directories listed in text file @file{file}.
12331 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12332 and @file{file}.
12333 @file{file} must be an existing, readable text file.
12334 Each nonempty line in @file{file} must be a directory.
12335 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12336 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12337 @file{file}.
12338
12339 @item -eL
12340 Follow symbolic links when processing project files.
12341
12342 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12343 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12344 Foreign patterns. Using this switch, it is possible to add sources of languages
12345 other than Ada to the list of sources of a project file.
12346 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12347 For example,
12348 @smallexample
12349 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12350 @end smallexample
12351 @noindent
12352 will look for Ada units in all files with the @file{.ada} extension,
12353 and will add to the list of file for project @file{prj.gpr} the C files
12354 with extension @file{.^c^C^}.
12355
12356 @item ^-h^/HELP^
12357 @cindex @option{^-h^/HELP^} (@code{gnatname})
12358 Output usage (help) information. The output is written to @file{stdout}.
12359
12360 @item ^-P^/PROJECT_FILE=^@file{proj}
12361 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12362 Create or update project file @file{proj}. There may be zero, one or more space
12363 between @option{-P} and @file{proj}. @file{proj} may include directory
12364 information. @file{proj} must be writable.
12365 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12366 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12367 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12368 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12369 existing project file <proj>.gpr, a backup copy of the project file is created
12370 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12371 non negative number that makes this backup copy a new file.
12372
12373 @item ^-v^/VERBOSE^
12374 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12375 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12376 This includes name of the file written, the name of the directories to search
12377 and, for each file in those directories whose name matches at least one of
12378 the Naming Patterns, an indication of whether the file contains a unit,
12379 and if so the name of the unit.
12380
12381 @item ^-v -v^/VERBOSE /VERBOSE^
12382 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12383 Very Verbose mode. In addition to the output produced in verbose mode,
12384 for each file in the searched directories whose name matches none of
12385 the Naming Patterns, an indication is given that there is no match.
12386
12387 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12388 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12389 Excluded patterns. Using this switch, it is possible to exclude some files
12390 that would match the name patterns. For example,
12391 @smallexample
12392 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12393 @end smallexample
12394 @noindent
12395 will look for Ada units in all files with the @file{.ada} extension,
12396 except those whose names end with @file{_nt.ada}.
12397
12398 @end table
12399
12400 @node Examples of gnatname Usage
12401 @section Examples of @code{gnatname} Usage
12402
12403 @ifset vms
12404 @smallexample
12405 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12406 @end smallexample
12407 @end ifset
12408
12409 @ifclear vms
12410 @smallexample
12411 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12412 @end smallexample
12413 @end ifclear
12414
12415 @noindent
12416 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12417 and be writable. In addition, the directory
12418 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12419 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12420
12421 @ifclear vms
12422 Note the optional spaces after @option{-c} and @option{-d}.
12423 @end ifclear
12424
12425 @smallexample
12426 @ifclear vms
12427 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12428 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12429 @end ifclear
12430 @ifset vms
12431 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12432 /EXCLUDED_PATTERN=*_nt_body.ada
12433 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12434 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12435 @end ifset
12436 @end smallexample
12437
12438 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12439 even in conjunction with one or several switches
12440 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12441 are used in this example.
12442
12443 @c *****************************************
12444 @c * G N A T P r o j e c t M a n a g e r *
12445 @c *****************************************
12446
12447 @c ------ macros for projects.texi
12448 @c These macros are needed when building the gprbuild documentation, but
12449 @c should have no effect in the gnat user's guide
12450
12451 @macro CODESAMPLE{TXT}
12452 @smallexample
12453 @group
12454 \TXT\
12455 @end group
12456 @end smallexample
12457 @end macro
12458
12459 @macro PROJECTFILE{TXT}
12460 @CODESAMPLE{\TXT\}
12461 @end macro
12462
12463 @c simulates a newline when in a @CODESAMPLE
12464 @macro NL{}
12465 @end macro
12466
12467 @macro TIP{TXT}
12468 @quotation
12469 @noindent
12470 \TXT\
12471 @end quotation
12472 @end macro
12473
12474 @macro TIPHTML{TXT}
12475 \TXT\
12476 @end macro
12477
12478 @macro IMPORTANT{TXT}
12479 @quotation
12480 @noindent
12481 \TXT\
12482 @end quotation
12483
12484 @end macro
12485
12486 @macro NOTE{TXT}
12487 @quotation
12488 @noindent
12489 \TXT\
12490 @end quotation
12491 @end macro
12492
12493 @include projects.texi
12494
12495 @c ---------------------------------------------
12496 @c Tools Supporting Project Files
12497 @c ---------------------------------------------
12498
12499 @node Tools Supporting Project Files
12500 @chapter Tools Supporting Project Files
12501
12502 @noindent
12503
12504 @menu
12505 * gnatmake and Project Files::
12506 * The GNAT Driver and Project Files::
12507 @end menu
12508
12509 @c ---------------------------------------------
12510 @node gnatmake and Project Files
12511 @section gnatmake and Project Files
12512 @c ---------------------------------------------
12513
12514 @noindent
12515 This section covers several topics related to @command{gnatmake} and
12516 project files: defining ^switches^switches^ for @command{gnatmake}
12517 and for the tools that it invokes; specifying configuration pragmas;
12518 the use of the @code{Main} attribute; building and rebuilding library project
12519 files.
12520
12521 @menu
12522 * Switches Related to Project Files::
12523 * Switches and Project Files::
12524 * Specifying Configuration Pragmas::
12525 * Project Files and Main Subprograms::
12526 * Library Project Files::
12527 @end menu
12528
12529 @c ---------------------------------------------
12530 @node Switches Related to Project Files
12531 @subsection Switches Related to Project Files
12532 @c ---------------------------------------------
12533
12534 @noindent
12535 The following switches are used by GNAT tools that support project files:
12536
12537 @table @option
12538
12539 @item ^-P^/PROJECT_FILE=^@var{project}
12540 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12541 Indicates the name of a project file. This project file will be parsed with
12542 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12543 if any, and using the external references indicated
12544 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12545 @ifclear vms
12546 There may zero, one or more spaces between @option{-P} and @var{project}.
12547 @end ifclear
12548
12549 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12550
12551 Since the Project Manager parses the project file only after all the switches
12552 on the command line are checked, the order of the switches
12553 @option{^-P^/PROJECT_FILE^},
12554 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12555 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12556
12557 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12558 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12559 Indicates that external variable @var{name} has the value @var{value}.
12560 The Project Manager will use this value for occurrences of
12561 @code{external(name)} when parsing the project file.
12562
12563 @ifclear vms
12564 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12565 put between quotes.
12566 @smallexample
12567 -XOS=NT
12568 -X"user=John Doe"
12569 @end smallexample
12570 @end ifclear
12571
12572 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12573 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12574 @var{name}, only the last one is used.
12575
12576 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12577 takes precedence over the value of the same name in the environment.
12578
12579 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12580 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12581 Indicates the verbosity of the parsing of GNAT project files.
12582
12583 @ifclear vms
12584 @option{-vP0} means Default;
12585 @option{-vP1} means Medium;
12586 @option{-vP2} means High.
12587 @end ifclear
12588
12589 @ifset vms
12590 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12591 HIGH.
12592 @end ifset
12593
12594 The default is ^Default^DEFAULT^: no output for syntactically correct
12595 project files.
12596 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12597 only the last one is used.
12598
12599 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12600 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12601 Add directory <dir> at the beginning of the project search path, in order,
12602 after the current working directory.
12603
12604 @ifclear vms
12605 @item -eL
12606 @cindex @option{-eL} (any project-aware tool)
12607 Follow all symbolic links when processing project files.
12608 @end ifclear
12609
12610 @item ^--subdirs^/SUBDIRS^=<subdir>
12611 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12612 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12613 indicate that the real directories (except the source directories) are the
12614 subdirectories <subdir> of the directories specified in the project files.
12615 This applies in particular to object directories, library directories and
12616 exec directories. If the subdirectories do not exist, they are created
12617 automatically.
12618
12619 @end table
12620
12621 @c ---------------------------------------------
12622 @node Switches and Project Files
12623 @subsection Switches and Project Files
12624 @c ---------------------------------------------
12625
12626 @noindent
12627 @ifset vms
12628 It is not currently possible to specify VMS style qualifiers in the project
12629 files; only Unix style ^switches^switches^ may be specified.
12630 @end ifset
12631
12632 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12633 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12634 attribute, a @code{Switches} attribute, or both;
12635 as their names imply, these ^switch^switch^-related
12636 attributes affect the ^switches^switches^ that are used for each of these GNAT
12637 components when
12638 @command{gnatmake} is invoked. As will be explained below, these
12639 component-specific ^switches^switches^ precede
12640 the ^switches^switches^ provided on the @command{gnatmake} command line.
12641
12642 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12643 indexed by language name (case insensitive) whose value is a string list.
12644 For example:
12645
12646 @smallexample @c projectfile
12647 @group
12648 package Compiler is
12649 for ^Default_Switches^Default_Switches^ ("Ada")
12650 use ("^-gnaty^-gnaty^",
12651 "^-v^-v^");
12652 end Compiler;
12653 @end group
12654 @end smallexample
12655
12656 @noindent
12657 The @code{Switches} attribute is indexed on a file name (which may or may
12658 not be case sensitive, depending
12659 on the operating system) whose value is a string list. For example:
12660
12661 @smallexample @c projectfile
12662 @group
12663 package Builder is
12664 for Switches ("main1.adb")
12665 use ("^-O2^-O2^");
12666 for Switches ("main2.adb")
12667 use ("^-g^-g^");
12668 end Builder;
12669 @end group
12670 @end smallexample
12671
12672 @noindent
12673 For the @code{Builder} package, the file names must designate source files
12674 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12675 file names must designate @file{ALI} or source files for main subprograms.
12676 In each case just the file name without an explicit extension is acceptable.
12677
12678 For each tool used in a program build (@command{gnatmake}, the compiler, the
12679 binder, and the linker), the corresponding package @dfn{contributes} a set of
12680 ^switches^switches^ for each file on which the tool is invoked, based on the
12681 ^switch^switch^-related attributes defined in the package.
12682 In particular, the ^switches^switches^
12683 that each of these packages contributes for a given file @var{f} comprise:
12684
12685 @itemize @bullet
12686 @item the value of attribute @code{Switches (@var{f})},
12687 if it is specified in the package for the given file,
12688 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12689 if it is specified in the package.
12690
12691 @end itemize
12692
12693 @noindent
12694 If neither of these attributes is defined in the package, then the package does
12695 not contribute any ^switches^switches^ for the given file.
12696
12697 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12698 two sets, in the following order: those contributed for the file
12699 by the @code{Builder} package;
12700 and the switches passed on the command line.
12701
12702 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12703 the ^switches^switches^ passed to the tool comprise three sets,
12704 in the following order:
12705
12706 @enumerate
12707 @item
12708 the applicable ^switches^switches^ contributed for the file
12709 by the @code{Builder} package in the project file supplied on the command line;
12710
12711 @item
12712 those contributed for the file by the package (in the relevant project file --
12713 see below) corresponding to the tool; and
12714
12715 @item
12716 the applicable switches passed on the command line.
12717 @end enumerate
12718
12719 The term @emph{applicable ^switches^switches^} reflects the fact that
12720 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12721 tools, depending on the individual ^switch^switch^.
12722
12723 @command{gnatmake} may invoke the compiler on source files from different
12724 projects. The Project Manager will use the appropriate project file to
12725 determine the @code{Compiler} package for each source file being compiled.
12726 Likewise for the @code{Binder} and @code{Linker} packages.
12727
12728 As an example, consider the following package in a project file:
12729
12730 @smallexample @c projectfile
12731 @group
12732 project Proj1 is
12733 package Compiler is
12734 for ^Default_Switches^Default_Switches^ ("Ada")
12735 use ("^-g^-g^");
12736 for Switches ("a.adb")
12737 use ("^-O1^-O1^");
12738 for Switches ("b.adb")
12739 use ("^-O2^-O2^",
12740 "^-gnaty^-gnaty^");
12741 end Compiler;
12742 end Proj1;
12743 @end group
12744 @end smallexample
12745
12746 @noindent
12747 If @command{gnatmake} is invoked with this project file, and it needs to
12748 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12749 @file{a.adb} will be compiled with the ^switch^switch^
12750 @option{^-O1^-O1^},
12751 @file{b.adb} with ^switches^switches^
12752 @option{^-O2^-O2^}
12753 and @option{^-gnaty^-gnaty^},
12754 and @file{c.adb} with @option{^-g^-g^}.
12755
12756 The following example illustrates the ordering of the ^switches^switches^
12757 contributed by different packages:
12758
12759 @smallexample @c projectfile
12760 @group
12761 project Proj2 is
12762 package Builder is
12763 for Switches ("main.adb")
12764 use ("^-g^-g^",
12765 "^-O1^-)1^",
12766 "^-f^-f^");
12767 end Builder;
12768 @end group
12769
12770 @group
12771 package Compiler is
12772 for Switches ("main.adb")
12773 use ("^-O2^-O2^");
12774 end Compiler;
12775 end Proj2;
12776 @end group
12777 @end smallexample
12778
12779 @noindent
12780 If you issue the command:
12781
12782 @smallexample
12783 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12784 @end smallexample
12785
12786 @noindent
12787 then the compiler will be invoked on @file{main.adb} with the following
12788 sequence of ^switches^switches^
12789
12790 @smallexample
12791 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12792 @end smallexample
12793
12794 @noindent
12795 with the last @option{^-O^-O^}
12796 ^switch^switch^ having precedence over the earlier ones;
12797 several other ^switches^switches^
12798 (such as @option{^-c^-c^}) are added implicitly.
12799
12800 The ^switches^switches^
12801 @option{^-g^-g^}
12802 and @option{^-O1^-O1^} are contributed by package
12803 @code{Builder}, @option{^-O2^-O2^} is contributed
12804 by the package @code{Compiler}
12805 and @option{^-O0^-O0^} comes from the command line.
12806
12807 The @option{^-g^-g^}
12808 ^switch^switch^ will also be passed in the invocation of
12809 @command{Gnatlink.}
12810
12811 A final example illustrates switch contributions from packages in different
12812 project files:
12813
12814 @smallexample @c projectfile
12815 @group
12816 project Proj3 is
12817 for Source_Files use ("pack.ads", "pack.adb");
12818 package Compiler is
12819 for ^Default_Switches^Default_Switches^ ("Ada")
12820 use ("^-gnata^-gnata^");
12821 end Compiler;
12822 end Proj3;
12823 @end group
12824
12825 @group
12826 with "Proj3";
12827 project Proj4 is
12828 for Source_Files use ("foo_main.adb", "bar_main.adb");
12829 package Builder is
12830 for Switches ("foo_main.adb")
12831 use ("^-s^-s^",
12832 "^-g^-g^");
12833 end Builder;
12834 end Proj4;
12835 @end group
12836
12837 @group
12838 -- Ada source file:
12839 with Pack;
12840 procedure Foo_Main is
12841 @dots{}
12842 end Foo_Main;
12843 @end group
12844 @end smallexample
12845
12846 @noindent
12847 If the command is
12848 @smallexample
12849 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12850 @end smallexample
12851
12852 @noindent
12853 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12854 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12855 @option{^-gnato^-gnato^} (passed on the command line).
12856 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12857 are @option{^-g^-g^} from @code{Proj4.Builder},
12858 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12859 and @option{^-gnato^-gnato^} from the command line.
12860
12861 When using @command{gnatmake} with project files, some ^switches^switches^ or
12862 arguments may be expressed as relative paths. As the working directory where
12863 compilation occurs may change, these relative paths are converted to absolute
12864 paths. For the ^switches^switches^ found in a project file, the relative paths
12865 are relative to the project file directory, for the switches on the command
12866 line, they are relative to the directory where @command{gnatmake} is invoked.
12867 The ^switches^switches^ for which this occurs are:
12868 ^-I^-I^,
12869 ^-A^-A^,
12870 ^-L^-L^,
12871 ^-aO^-aO^,
12872 ^-aL^-aL^,
12873 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12874 ^switch^switch^
12875 ^-o^-o^, object files specified in package @code{Linker} or after
12876 -largs on the command line). The exception to this rule is the ^switch^switch^
12877 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12878
12879 @c ---------------------------------------------
12880 @node Specifying Configuration Pragmas
12881 @subsection Specifying Configuration Pragmas
12882 @c ---------------------------------------------
12883
12884 @noindent
12885 When using @command{gnatmake} with project files, if there exists a file
12886 @file{gnat.adc} that contains configuration pragmas, this file will be
12887 ignored.
12888
12889 Configuration pragmas can be defined by means of the following attributes in
12890 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12891 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12892
12893 Both these attributes are single string attributes. Their values is the path
12894 name of a file containing configuration pragmas. If a path name is relative,
12895 then it is relative to the project directory of the project file where the
12896 attribute is defined.
12897
12898 When compiling a source, the configuration pragmas used are, in order,
12899 those listed in the file designated by attribute
12900 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12901 project file, if it is specified, and those listed in the file designated by
12902 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12903 the project file of the source, if it exists.
12904
12905 @c ---------------------------------------------
12906 @node Project Files and Main Subprograms
12907 @subsection Project Files and Main Subprograms
12908 @c ---------------------------------------------
12909
12910 @noindent
12911 When using a project file, you can invoke @command{gnatmake}
12912 with one or several main subprograms, by specifying their source files on the
12913 command line.
12914
12915 @smallexample
12916 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12917 @end smallexample
12918
12919 @noindent
12920 Each of these needs to be a source file of the same project, except
12921 when the switch ^-u^/UNIQUE^ is used.
12922
12923 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12924 same project, one of the project in the tree rooted at the project specified
12925 on the command line. The package @code{Builder} of this common project, the
12926 "main project" is the one that is considered by @command{gnatmake}.
12927
12928 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12929 imported directly or indirectly by the project specified on the command line.
12930 Note that if such a source file is not part of the project specified on the
12931 command line, the ^switches^switches^ found in package @code{Builder} of the
12932 project specified on the command line, if any, that are transmitted
12933 to the compiler will still be used, not those found in the project file of
12934 the source file.
12935
12936 When using a project file, you can also invoke @command{gnatmake} without
12937 explicitly specifying any main, and the effect depends on whether you have
12938 defined the @code{Main} attribute. This attribute has a string list value,
12939 where each element in the list is the name of a source file (the file
12940 extension is optional) that contains a unit that can be a main subprogram.
12941
12942 If the @code{Main} attribute is defined in a project file as a non-empty
12943 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12944 line, then invoking @command{gnatmake} with this project file but without any
12945 main on the command line is equivalent to invoking @command{gnatmake} with all
12946 the file names in the @code{Main} attribute on the command line.
12947
12948 Example:
12949 @smallexample @c projectfile
12950 @group
12951 project Prj is
12952 for Main use ("main1.adb", "main2.adb", "main3.adb");
12953 end Prj;
12954 @end group
12955 @end smallexample
12956
12957 @noindent
12958 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12959 is equivalent to
12960 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12961
12962 When the project attribute @code{Main} is not specified, or is specified
12963 as an empty string list, or when the switch @option{-u} is used on the command
12964 line, then invoking @command{gnatmake} with no main on the command line will
12965 result in all immediate sources of the project file being checked, and
12966 potentially recompiled. Depending on the presence of the switch @option{-u},
12967 sources from other project files on which the immediate sources of the main
12968 project file depend are also checked and potentially recompiled. In other
12969 words, the @option{-u} switch is applied to all of the immediate sources of the
12970 main project file.
12971
12972 When no main is specified on the command line and attribute @code{Main} exists
12973 and includes several mains, or when several mains are specified on the
12974 command line, the default ^switches^switches^ in package @code{Builder} will
12975 be used for all mains, even if there are specific ^switches^switches^
12976 specified for one or several mains.
12977
12978 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12979 the specific ^switches^switches^ for each main, if they are specified.
12980
12981 @c ---------------------------------------------
12982 @node Library Project Files
12983 @subsection Library Project Files
12984 @c ---------------------------------------------
12985
12986 @noindent
12987 When @command{gnatmake} is invoked with a main project file that is a library
12988 project file, it is not allowed to specify one or more mains on the command
12989 line.
12990
12991 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12992 ^-l^/ACTION=LINK^ have special meanings.
12993
12994 @itemize @bullet
12995 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12996 to @command{gnatmake} that @command{gnatbind} should be invoked for the
12997 library.
12998
12999 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13000 to @command{gnatmake} that the binder generated file should be compiled
13001 (in the case of a stand-alone library) and that the library should be built.
13002 @end itemize
13003
13004 @c ---------------------------------------------
13005 @node The GNAT Driver and Project Files
13006 @section The GNAT Driver and Project Files
13007 @c ---------------------------------------------
13008
13009 @noindent
13010 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13011 can benefit from project files:
13012 (@command{^gnatbind^gnatbind^},
13013 @command{^gnatcheck^gnatcheck^},
13014 @command{^gnatclean^gnatclean^},
13015 @command{^gnatelim^gnatelim^},
13016 @command{^gnatfind^gnatfind^},
13017 @command{^gnatlink^gnatlink^},
13018 @command{^gnatls^gnatls^},
13019 @command{^gnatmetric^gnatmetric^},
13020 @command{^gnatpp^gnatpp^},
13021 @command{^gnatstub^gnatstub^},
13022 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13023 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13024 They must be invoked through the @command{gnat} driver.
13025
13026 The @command{gnat} driver is a wrapper that accepts a number of commands and
13027 calls the corresponding tool. It was designed initially for VMS platforms (to
13028 convert VMS qualifiers to Unix-style switches), but it is now available on all
13029 GNAT platforms.
13030
13031 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13032 (case insensitive):
13033
13034 @itemize @bullet
13035 @item BIND to invoke @command{^gnatbind^gnatbind^}
13036 @item CHOP to invoke @command{^gnatchop^gnatchop^}
13037 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
13038 @item COMP or COMPILE to invoke the compiler
13039 @item ELIM to invoke @command{^gnatelim^gnatelim^}
13040 @item FIND to invoke @command{^gnatfind^gnatfind^}
13041 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13042 @item LINK to invoke @command{^gnatlink^gnatlink^}
13043 @item LS or LIST to invoke @command{^gnatls^gnatls^}
13044 @item MAKE to invoke @command{^gnatmake^gnatmake^}
13045 @item NAME to invoke @command{^gnatname^gnatname^}
13046 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13047 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13048 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13049 @item STUB to invoke @command{^gnatstub^gnatstub^}
13050 @item XREF to invoke @command{^gnatxref^gnatxref^}
13051
13052 @end itemize
13053
13054 @noindent
13055 (note that the compiler is invoked using the command
13056 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13057
13058 On non-VMS platforms, between @command{gnat} and the command, two
13059 special switches may be used:
13060
13061 @itemize @bullet
13062 @item @command{-v} to display the invocation of the tool.
13063 @item @command{-dn} to prevent the @command{gnat} driver from removing
13064 the temporary files it has created. These temporary files are
13065 configuration files and temporary file list files.
13066
13067 @end itemize
13068
13069 @noindent
13070 The command may be followed by switches and arguments for the invoked
13071 tool.
13072
13073 @smallexample
13074 gnat bind -C main.ali
13075 gnat ls -a main
13076 gnat chop foo.txt
13077 @end smallexample
13078
13079 @noindent
13080 Switches may also be put in text files, one switch per line, and the text
13081 files may be specified with their path name preceded by '@@'.
13082
13083 @smallexample
13084 gnat bind @@args.txt main.ali
13085 @end smallexample
13086
13087 @noindent
13088 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13089 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13090 (@option{^-P^/PROJECT_FILE^},
13091 @option{^-X^/EXTERNAL_REFERENCE^} and
13092 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13093 the switches of the invoking tool.
13094
13095 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13096 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13097 the immediate sources of the specified project file.
13098
13099 When GNAT METRIC is used with a project file, but with no source
13100 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13101 with all the immediate sources of the specified project file and with
13102 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13103 of the project.
13104
13105 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13106 a project file, no source is specified on the command line and
13107 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13108 the underlying tool (^gnatpp^gnatpp^ or
13109 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13110 not only for the immediate sources of the main project.
13111 @ifclear vms
13112 (-U stands for Universal or Union of the project files of the project tree)
13113 @end ifclear
13114
13115 For each of the following commands, there is optionally a corresponding
13116 package in the main project.
13117
13118 @itemize @bullet
13119 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13120
13121 @item package @code{Check} for command CHECK (invoking
13122 @code{^gnatcheck^gnatcheck^})
13123
13124 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13125
13126 @item package @code{Cross_Reference} for command XREF (invoking
13127 @code{^gnatxref^gnatxref^})
13128
13129 @item package @code{Eliminate} for command ELIM (invoking
13130 @code{^gnatelim^gnatelim^})
13131
13132 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13133
13134 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13135
13136 @item package @code{Gnatstub} for command STUB
13137 (invoking @code{^gnatstub^gnatstub^})
13138
13139 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13140
13141 @item package @code{Check} for command CHECK
13142 (invoking @code{^gnatcheck^gnatcheck^})
13143
13144 @item package @code{Metrics} for command METRIC
13145 (invoking @code{^gnatmetric^gnatmetric^})
13146
13147 @item package @code{Pretty_Printer} for command PP or PRETTY
13148 (invoking @code{^gnatpp^gnatpp^})
13149
13150 @end itemize
13151
13152 @noindent
13153 Package @code{Gnatls} has a unique attribute @code{Switches},
13154 a simple variable with a string list value. It contains ^switches^switches^
13155 for the invocation of @code{^gnatls^gnatls^}.
13156
13157 @smallexample @c projectfile
13158 @group
13159 project Proj1 is
13160 package gnatls is
13161 for Switches
13162 use ("^-a^-a^",
13163 "^-v^-v^");
13164 end gnatls;
13165 end Proj1;
13166 @end group
13167 @end smallexample
13168
13169 @noindent
13170 All other packages have two attribute @code{Switches} and
13171 @code{^Default_Switches^Default_Switches^}.
13172
13173 @code{Switches} is an indexed attribute, indexed by the
13174 source file name, that has a string list value: the ^switches^switches^ to be
13175 used when the tool corresponding to the package is invoked for the specific
13176 source file.
13177
13178 @code{^Default_Switches^Default_Switches^} is an attribute,
13179 indexed by the programming language that has a string list value.
13180 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13181 ^switches^switches^ for the invocation of the tool corresponding
13182 to the package, except if a specific @code{Switches} attribute
13183 is specified for the source file.
13184
13185 @smallexample @c projectfile
13186 @group
13187 project Proj is
13188
13189 for Source_Dirs use ("**");
13190
13191 package gnatls is
13192 for Switches use
13193 ("^-a^-a^",
13194 "^-v^-v^");
13195 end gnatls;
13196 @end group
13197 @group
13198
13199 package Compiler is
13200 for ^Default_Switches^Default_Switches^ ("Ada")
13201 use ("^-gnatv^-gnatv^",
13202 "^-gnatwa^-gnatwa^");
13203 end Binder;
13204 @end group
13205 @group
13206
13207 package Binder is
13208 for ^Default_Switches^Default_Switches^ ("Ada")
13209 use ("^-C^-C^",
13210 "^-e^-e^");
13211 end Binder;
13212 @end group
13213 @group
13214
13215 package Linker is
13216 for ^Default_Switches^Default_Switches^ ("Ada")
13217 use ("^-C^-C^");
13218 for Switches ("main.adb")
13219 use ("^-C^-C^",
13220 "^-v^-v^",
13221 "^-v^-v^");
13222 end Linker;
13223 @end group
13224 @group
13225
13226 package Finder is
13227 for ^Default_Switches^Default_Switches^ ("Ada")
13228 use ("^-a^-a^",
13229 "^-f^-f^");
13230 end Finder;
13231 @end group
13232 @group
13233
13234 package Cross_Reference is
13235 for ^Default_Switches^Default_Switches^ ("Ada")
13236 use ("^-a^-a^",
13237 "^-f^-f^",
13238 "^-d^-d^",
13239 "^-u^-u^");
13240 end Cross_Reference;
13241 end Proj;
13242 @end group
13243 @end smallexample
13244
13245 @noindent
13246 With the above project file, commands such as
13247
13248 @smallexample
13249 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13250 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13251 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13252 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13253 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13254 @end smallexample
13255
13256 @noindent
13257 will set up the environment properly and invoke the tool with the switches
13258 found in the package corresponding to the tool:
13259 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13260 except @code{Switches ("main.adb")}
13261 for @code{^gnatlink^gnatlink^}.
13262 It is also possible to invoke some of the tools,
13263 (@code{^gnatcheck^gnatcheck^},
13264 @code{^gnatmetric^gnatmetric^},
13265 and @code{^gnatpp^gnatpp^})
13266 on a set of project units thanks to the combination of the switches
13267 @option{-P}, @option{-U} and possibly the main unit when one is interested
13268 in its closure. For instance,
13269 @smallexample
13270 gnat metric -Pproj
13271 @end smallexample
13272
13273 @noindent
13274 will compute the metrics for all the immediate units of project
13275 @code{proj}.
13276 @smallexample
13277 gnat metric -Pproj -U
13278 @end smallexample
13279
13280 @noindent
13281 will compute the metrics for all the units of the closure of projects
13282 rooted at @code{proj}.
13283 @smallexample
13284 gnat metric -Pproj -U main_unit
13285 @end smallexample
13286
13287 @noindent
13288 will compute the metrics for the closure of units rooted at
13289 @code{main_unit}. This last possibility relies implicitly
13290 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13291 tool invoked by the @command{gnat} driver are explicitly specified
13292 either directly or through the tool @option{-files} option, then the tool
13293 is called only for these explicitly specified files.
13294
13295 @c *****************************************
13296 @c * Cross-referencing tools
13297 @c *****************************************
13298
13299 @node The Cross-Referencing Tools gnatxref and gnatfind
13300 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13301 @findex gnatxref
13302 @findex gnatfind
13303
13304 @noindent
13305 The compiler generates cross-referencing information (unless
13306 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13307 This information indicates where in the source each entity is declared and
13308 referenced. Note that entities in package Standard are not included, but
13309 entities in all other predefined units are included in the output.
13310
13311 Before using any of these two tools, you need to compile successfully your
13312 application, so that GNAT gets a chance to generate the cross-referencing
13313 information.
13314
13315 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13316 information to provide the user with the capability to easily locate the
13317 declaration and references to an entity. These tools are quite similar,
13318 the difference being that @code{gnatfind} is intended for locating
13319 definitions and/or references to a specified entity or entities, whereas
13320 @code{gnatxref} is oriented to generating a full report of all
13321 cross-references.
13322
13323 To use these tools, you must not compile your application using the
13324 @option{-gnatx} switch on the @command{gnatmake} command line
13325 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13326 information will not be generated.
13327
13328 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13329 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13330
13331 @menu
13332 * Switches for gnatxref::
13333 * Switches for gnatfind::
13334 * Project Files for gnatxref and gnatfind::
13335 * Regular Expressions in gnatfind and gnatxref::
13336 * Examples of gnatxref Usage::
13337 * Examples of gnatfind Usage::
13338 @end menu
13339
13340 @node Switches for gnatxref
13341 @section @code{gnatxref} Switches
13342
13343 @noindent
13344 The command invocation for @code{gnatxref} is:
13345 @smallexample
13346 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13347 @c Expanding @ovar macro inline (explanation in macro def comments)
13348 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13349 @end smallexample
13350
13351 @noindent
13352 where
13353
13354 @table @var
13355 @item sourcefile1
13356 @itemx sourcefile2
13357 identifies the source files for which a report is to be generated. The
13358 ``with''ed units will be processed too. You must provide at least one file.
13359
13360 These file names are considered to be regular expressions, so for instance
13361 specifying @file{source*.adb} is the same as giving every file in the current
13362 directory whose name starts with @file{source} and whose extension is
13363 @file{adb}.
13364
13365 You shouldn't specify any directory name, just base names. @command{gnatxref}
13366 and @command{gnatfind} will be able to locate these files by themselves using
13367 the source path. If you specify directories, no result is produced.
13368
13369 @end table
13370
13371 @noindent
13372 The switches can be:
13373 @table @option
13374 @c !sort!
13375 @item --version
13376 @cindex @option{--version} @command{gnatxref}
13377 Display Copyright and version, then exit disregarding all other options.
13378
13379 @item --help
13380 @cindex @option{--help} @command{gnatxref}
13381 If @option{--version} was not used, display usage, then exit disregarding
13382 all other options.
13383
13384 @item ^-a^/ALL_FILES^
13385 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13386 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13387 the read-only files found in the library search path. Otherwise, these files
13388 will be ignored. This option can be used to protect Gnat sources or your own
13389 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13390 much faster, and their output much smaller. Read-only here refers to access
13391 or permissions status in the file system for the current user.
13392
13393 @item -aIDIR
13394 @cindex @option{-aIDIR} (@command{gnatxref})
13395 When looking for source files also look in directory DIR. The order in which
13396 source file search is undertaken is the same as for @command{gnatmake}.
13397
13398 @item -aODIR
13399 @cindex @option{-aODIR} (@command{gnatxref})
13400 When searching for library and object files, look in directory
13401 DIR. The order in which library files are searched is the same as for
13402 @command{gnatmake}.
13403
13404 @item -nostdinc
13405 @cindex @option{-nostdinc} (@command{gnatxref})
13406 Do not look for sources in the system default directory.
13407
13408 @item -nostdlib
13409 @cindex @option{-nostdlib} (@command{gnatxref})
13410 Do not look for library files in the system default directory.
13411
13412 @item --ext=@var{extension}
13413 @cindex @option{--ext} (@command{gnatxref})
13414 Specify an alternate ali file extension. The default is @code{ali} and other
13415 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13416 switch. Note that if this switch overrides the default, which means that only
13417 the new extension will be considered.
13418
13419 @item --RTS=@var{rts-path}
13420 @cindex @option{--RTS} (@command{gnatxref})
13421 Specifies the default location of the runtime library. Same meaning as the
13422 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13423
13424 @item ^-d^/DERIVED_TYPES^
13425 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13426 If this switch is set @code{gnatxref} will output the parent type
13427 reference for each matching derived types.
13428
13429 @item ^-f^/FULL_PATHNAME^
13430 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13431 If this switch is set, the output file names will be preceded by their
13432 directory (if the file was found in the search path). If this switch is
13433 not set, the directory will not be printed.
13434
13435 @item ^-g^/IGNORE_LOCALS^
13436 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13437 If this switch is set, information is output only for library-level
13438 entities, ignoring local entities. The use of this switch may accelerate
13439 @code{gnatfind} and @code{gnatxref}.
13440
13441 @item -IDIR
13442 @cindex @option{-IDIR} (@command{gnatxref})
13443 Equivalent to @samp{-aODIR -aIDIR}.
13444
13445 @item -pFILE
13446 @cindex @option{-pFILE} (@command{gnatxref})
13447 Specify a project file to use @xref{GNAT Project Manager}.
13448 If you need to use the @file{.gpr}
13449 project files, you should use gnatxref through the GNAT driver
13450 (@command{gnat xref -Pproject}).
13451
13452 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13453 project file in the current directory.
13454
13455 If a project file is either specified or found by the tools, then the content
13456 of the source directory and object directory lines are added as if they
13457 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13458 and @samp{^-aO^OBJECT_SEARCH^}.
13459 @item ^-u^/UNUSED^
13460 Output only unused symbols. This may be really useful if you give your
13461 main compilation unit on the command line, as @code{gnatxref} will then
13462 display every unused entity and 'with'ed package.
13463
13464 @ifclear vms
13465 @item -v
13466 Instead of producing the default output, @code{gnatxref} will generate a
13467 @file{tags} file that can be used by vi. For examples how to use this
13468 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13469 to the standard output, thus you will have to redirect it to a file.
13470 @end ifclear
13471
13472 @end table
13473
13474 @noindent
13475 All these switches may be in any order on the command line, and may even
13476 appear after the file names. They need not be separated by spaces, thus
13477 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13478 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13479
13480 @node Switches for gnatfind
13481 @section @code{gnatfind} Switches
13482
13483 @noindent
13484 The command line for @code{gnatfind} is:
13485
13486 @smallexample
13487 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13488 @c @r{[}@var{file1} @var{file2} @dots{}]
13489 @c Expanding @ovar macro inline (explanation in macro def comments)
13490 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13491 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13492 @end smallexample
13493
13494 @noindent
13495 where
13496
13497 @table @var
13498 @item pattern
13499 An entity will be output only if it matches the regular expression found
13500 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13501
13502 Omitting the pattern is equivalent to specifying @samp{*}, which
13503 will match any entity. Note that if you do not provide a pattern, you
13504 have to provide both a sourcefile and a line.
13505
13506 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13507 for matching purposes. At the current time there is no support for
13508 8-bit codes other than Latin-1, or for wide characters in identifiers.
13509
13510 @item sourcefile
13511 @code{gnatfind} will look for references, bodies or declarations
13512 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13513 and column @var{column}. See @ref{Examples of gnatfind Usage}
13514 for syntax examples.
13515
13516 @item line
13517 is a decimal integer identifying the line number containing
13518 the reference to the entity (or entities) to be located.
13519
13520 @item column
13521 is a decimal integer identifying the exact location on the
13522 line of the first character of the identifier for the
13523 entity reference. Columns are numbered from 1.
13524
13525 @item file1 file2 @dots{}
13526 The search will be restricted to these source files. If none are given, then
13527 the search will be done for every library file in the search path.
13528 These file must appear only after the pattern or sourcefile.
13529
13530 These file names are considered to be regular expressions, so for instance
13531 specifying @file{source*.adb} is the same as giving every file in the current
13532 directory whose name starts with @file{source} and whose extension is
13533 @file{adb}.
13534
13535 The location of the spec of the entity will always be displayed, even if it
13536 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13537 occurrences of the entity in the separate units of the ones given on the
13538 command line will also be displayed.
13539
13540 Note that if you specify at least one file in this part, @code{gnatfind} may
13541 sometimes not be able to find the body of the subprograms.
13542
13543 @end table
13544
13545 @noindent
13546 At least one of 'sourcefile' or 'pattern' has to be present on
13547 the command line.
13548
13549 The following switches are available:
13550 @table @option
13551 @c !sort!
13552
13553 @cindex @option{--version} @command{gnatfind}
13554 Display Copyright and version, then exit disregarding all other options.
13555
13556 @item --help
13557 @cindex @option{--help} @command{gnatfind}
13558 If @option{--version} was not used, display usage, then exit disregarding
13559 all other options.
13560
13561 @item ^-a^/ALL_FILES^
13562 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13563 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13564 the read-only files found in the library search path. Otherwise, these files
13565 will be ignored. This option can be used to protect Gnat sources or your own
13566 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13567 much faster, and their output much smaller. Read-only here refers to access
13568 or permission status in the file system for the current user.
13569
13570 @item -aIDIR
13571 @cindex @option{-aIDIR} (@command{gnatfind})
13572 When looking for source files also look in directory DIR. The order in which
13573 source file search is undertaken is the same as for @command{gnatmake}.
13574
13575 @item -aODIR
13576 @cindex @option{-aODIR} (@command{gnatfind})
13577 When searching for library and object files, look in directory
13578 DIR. The order in which library files are searched is the same as for
13579 @command{gnatmake}.
13580
13581 @item -nostdinc
13582 @cindex @option{-nostdinc} (@command{gnatfind})
13583 Do not look for sources in the system default directory.
13584
13585 @item -nostdlib
13586 @cindex @option{-nostdlib} (@command{gnatfind})
13587 Do not look for library files in the system default directory.
13588
13589 @item --ext=@var{extension}
13590 @cindex @option{--ext} (@command{gnatfind})
13591 Specify an alternate ali file extension. The default is @code{ali} and other
13592 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13593 switch. Note that if this switch overrides the default, which means that only
13594 the new extension will be considered.
13595
13596 @item --RTS=@var{rts-path}
13597 @cindex @option{--RTS} (@command{gnatfind})
13598 Specifies the default location of the runtime library. Same meaning as the
13599 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13600
13601 @item ^-d^/DERIVED_TYPE_INFORMATION^
13602 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13603 If this switch is set, then @code{gnatfind} will output the parent type
13604 reference for each matching derived types.
13605
13606 @item ^-e^/EXPRESSIONS^
13607 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13608 By default, @code{gnatfind} accept the simple regular expression set for
13609 @samp{pattern}. If this switch is set, then the pattern will be
13610 considered as full Unix-style regular expression.
13611
13612 @item ^-f^/FULL_PATHNAME^
13613 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13614 If this switch is set, the output file names will be preceded by their
13615 directory (if the file was found in the search path). If this switch is
13616 not set, the directory will not be printed.
13617
13618 @item ^-g^/IGNORE_LOCALS^
13619 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13620 If this switch is set, information is output only for library-level
13621 entities, ignoring local entities. The use of this switch may accelerate
13622 @code{gnatfind} and @code{gnatxref}.
13623
13624 @item -IDIR
13625 @cindex @option{-IDIR} (@command{gnatfind})
13626 Equivalent to @samp{-aODIR -aIDIR}.
13627
13628 @item -pFILE
13629 @cindex @option{-pFILE} (@command{gnatfind})
13630 Specify a project file (@pxref{GNAT Project Manager}) to use.
13631 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13632 project file in the current directory.
13633
13634 If a project file is either specified or found by the tools, then the content
13635 of the source directory and object directory lines are added as if they
13636 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13637 @samp{^-aO^/OBJECT_SEARCH^}.
13638
13639 @item ^-r^/REFERENCES^
13640 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13641 By default, @code{gnatfind} will output only the information about the
13642 declaration, body or type completion of the entities. If this switch is
13643 set, the @code{gnatfind} will locate every reference to the entities in
13644 the files specified on the command line (or in every file in the search
13645 path if no file is given on the command line).
13646
13647 @item ^-s^/PRINT_LINES^
13648 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13649 If this switch is set, then @code{gnatfind} will output the content
13650 of the Ada source file lines were the entity was found.
13651
13652 @item ^-t^/TYPE_HIERARCHY^
13653 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13654 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13655 the specified type. It act like -d option but recursively from parent
13656 type to parent type. When this switch is set it is not possible to
13657 specify more than one file.
13658
13659 @end table
13660
13661 @noindent
13662 All these switches may be in any order on the command line, and may even
13663 appear after the file names. They need not be separated by spaces, thus
13664 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13665 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13666
13667 As stated previously, gnatfind will search in every directory in the
13668 search path. You can force it to look only in the current directory if
13669 you specify @code{*} at the end of the command line.
13670
13671 @node Project Files for gnatxref and gnatfind
13672 @section Project Files for @command{gnatxref} and @command{gnatfind}
13673
13674 @noindent
13675 Project files allow a programmer to specify how to compile its
13676 application, where to find sources, etc. These files are used
13677 @ifclear vms
13678 primarily by GPS, but they can also be used
13679 @end ifclear
13680 by the two tools
13681 @code{gnatxref} and @code{gnatfind}.
13682
13683 A project file name must end with @file{.gpr}. If a single one is
13684 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13685 extract the information from it. If multiple project files are found, none of
13686 them is read, and you have to use the @samp{-p} switch to specify the one
13687 you want to use.
13688
13689 The following lines can be included, even though most of them have default
13690 values which can be used in most cases.
13691 The lines can be entered in any order in the file.
13692 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13693 each line. If you have multiple instances, only the last one is taken into
13694 account.
13695
13696 @table @code
13697 @item src_dir=DIR
13698 [default: @code{"^./^[]^"}]
13699 specifies a directory where to look for source files. Multiple @code{src_dir}
13700 lines can be specified and they will be searched in the order they
13701 are specified.
13702
13703 @item obj_dir=DIR
13704 [default: @code{"^./^[]^"}]
13705 specifies a directory where to look for object and library files. Multiple
13706 @code{obj_dir} lines can be specified, and they will be searched in the order
13707 they are specified
13708
13709 @item comp_opt=SWITCHES
13710 [default: @code{""}]
13711 creates a variable which can be referred to subsequently by using
13712 the @code{$@{comp_opt@}} notation. This is intended to store the default
13713 switches given to @command{gnatmake} and @command{gcc}.
13714
13715 @item bind_opt=SWITCHES
13716 [default: @code{""}]
13717 creates a variable which can be referred to subsequently by using
13718 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13719 switches given to @command{gnatbind}.
13720
13721 @item link_opt=SWITCHES
13722 [default: @code{""}]
13723 creates a variable which can be referred to subsequently by using
13724 the @samp{$@{link_opt@}} notation. This is intended to store the default
13725 switches given to @command{gnatlink}.
13726
13727 @item main=EXECUTABLE
13728 [default: @code{""}]
13729 specifies the name of the executable for the application. This variable can
13730 be referred to in the following lines by using the @samp{$@{main@}} notation.
13731
13732 @ifset vms
13733 @item comp_cmd=COMMAND
13734 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13735 @end ifset
13736 @ifclear vms
13737 @item comp_cmd=COMMAND
13738 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13739 @end ifclear
13740 specifies the command used to compile a single file in the application.
13741
13742 @ifset vms
13743 @item make_cmd=COMMAND
13744 [default: @code{"GNAT MAKE $@{main@}
13745 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13746 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13747 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13748 @end ifset
13749 @ifclear vms
13750 @item make_cmd=COMMAND
13751 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13752 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13753 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13754 @end ifclear
13755 specifies the command used to recompile the whole application.
13756
13757 @item run_cmd=COMMAND
13758 [default: @code{"$@{main@}"}]
13759 specifies the command used to run the application.
13760
13761 @item debug_cmd=COMMAND
13762 [default: @code{"gdb $@{main@}"}]
13763 specifies the command used to debug the application
13764
13765 @end table
13766
13767 @noindent
13768 @command{gnatxref} and @command{gnatfind} only take into account the
13769 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13770
13771 @node Regular Expressions in gnatfind and gnatxref
13772 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13773
13774 @noindent
13775 As specified in the section about @command{gnatfind}, the pattern can be a
13776 regular expression. Actually, there are to set of regular expressions
13777 which are recognized by the program:
13778
13779 @table @code
13780 @item globbing patterns
13781 These are the most usual regular expression. They are the same that you
13782 generally used in a Unix shell command line, or in a DOS session.
13783
13784 Here is a more formal grammar:
13785 @smallexample
13786 @group
13787 @iftex
13788 @leftskip=.5cm
13789 @end iftex
13790 regexp ::= term
13791 term ::= elmt -- matches elmt
13792 term ::= elmt elmt -- concatenation (elmt then elmt)
13793 term ::= * -- any string of 0 or more characters
13794 term ::= ? -- matches any character
13795 term ::= [char @{char@}] -- matches any character listed
13796 term ::= [char - char] -- matches any character in range
13797 @end group
13798 @end smallexample
13799
13800 @item full regular expression
13801 The second set of regular expressions is much more powerful. This is the
13802 type of regular expressions recognized by utilities such a @file{grep}.
13803
13804 The following is the form of a regular expression, expressed in Ada
13805 reference manual style BNF is as follows
13806
13807 @smallexample
13808 @iftex
13809 @leftskip=.5cm
13810 @end iftex
13811 @group
13812 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13813
13814 term ::= item @{item@} -- concatenation (item then item)
13815
13816 item ::= elmt -- match elmt
13817 item ::= elmt * -- zero or more elmt's
13818 item ::= elmt + -- one or more elmt's
13819 item ::= elmt ? -- matches elmt or nothing
13820 @end group
13821 @group
13822 elmt ::= nschar -- matches given character
13823 elmt ::= [nschar @{nschar@}] -- matches any character listed
13824 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13825 elmt ::= [char - char] -- matches chars in given range
13826 elmt ::= \ char -- matches given character
13827 elmt ::= . -- matches any single character
13828 elmt ::= ( regexp ) -- parens used for grouping
13829
13830 char ::= any character, including special characters
13831 nschar ::= any character except ()[].*+?^^^
13832 @end group
13833 @end smallexample
13834
13835 Following are a few examples:
13836
13837 @table @samp
13838 @item abcde|fghi
13839 will match any of the two strings @samp{abcde} and @samp{fghi},
13840
13841 @item abc*d
13842 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13843 @samp{abcccd}, and so on,
13844
13845 @item [a-z]+
13846 will match any string which has only lowercase characters in it (and at
13847 least one character.
13848
13849 @end table
13850 @end table
13851
13852 @node Examples of gnatxref Usage
13853 @section Examples of @code{gnatxref} Usage
13854
13855 @subsection General Usage
13856
13857 @noindent
13858 For the following examples, we will consider the following units:
13859
13860 @smallexample @c ada
13861 @group
13862 @cartouche
13863 main.ads:
13864 1: with Bar;
13865 2: package Main is
13866 3: procedure Foo (B : in Integer);
13867 4: C : Integer;
13868 5: private
13869 6: D : Integer;
13870 7: end Main;
13871
13872 main.adb:
13873 1: package body Main is
13874 2: procedure Foo (B : in Integer) is
13875 3: begin
13876 4: C := B;
13877 5: D := B;
13878 6: Bar.Print (B);
13879 7: Bar.Print (C);
13880 8: end Foo;
13881 9: end Main;
13882
13883 bar.ads:
13884 1: package Bar is
13885 2: procedure Print (B : Integer);
13886 3: end bar;
13887 @end cartouche
13888 @end group
13889 @end smallexample
13890
13891 @table @code
13892
13893 @noindent
13894 The first thing to do is to recompile your application (for instance, in
13895 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13896 the cross-referencing information.
13897 You can then issue any of the following commands:
13898
13899 @item gnatxref main.adb
13900 @code{gnatxref} generates cross-reference information for main.adb
13901 and every unit 'with'ed by main.adb.
13902
13903 The output would be:
13904 @smallexample
13905 @iftex
13906 @leftskip=0cm
13907 @end iftex
13908 B Type: Integer
13909 Decl: bar.ads 2:22
13910 B Type: Integer
13911 Decl: main.ads 3:20
13912 Body: main.adb 2:20
13913 Ref: main.adb 4:13 5:13 6:19
13914 Bar Type: Unit
13915 Decl: bar.ads 1:9
13916 Ref: main.adb 6:8 7:8
13917 main.ads 1:6
13918 C Type: Integer
13919 Decl: main.ads 4:5
13920 Modi: main.adb 4:8
13921 Ref: main.adb 7:19
13922 D Type: Integer
13923 Decl: main.ads 6:5
13924 Modi: main.adb 5:8
13925 Foo Type: Unit
13926 Decl: main.ads 3:15
13927 Body: main.adb 2:15
13928 Main Type: Unit
13929 Decl: main.ads 2:9
13930 Body: main.adb 1:14
13931 Print Type: Unit
13932 Decl: bar.ads 2:15
13933 Ref: main.adb 6:12 7:12
13934 @end smallexample
13935
13936 @noindent
13937 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13938 its body is in main.adb, line 1, column 14 and is not referenced any where.
13939
13940 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13941 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13942
13943 @item gnatxref package1.adb package2.ads
13944 @code{gnatxref} will generates cross-reference information for
13945 package1.adb, package2.ads and any other package 'with'ed by any
13946 of these.
13947
13948 @end table
13949
13950 @ifclear vms
13951 @subsection Using gnatxref with vi
13952
13953 @code{gnatxref} can generate a tags file output, which can be used
13954 directly from @command{vi}. Note that the standard version of @command{vi}
13955 will not work properly with overloaded symbols. Consider using another
13956 free implementation of @command{vi}, such as @command{vim}.
13957
13958 @smallexample
13959 $ gnatxref -v gnatfind.adb > tags
13960 @end smallexample
13961
13962 @noindent
13963 will generate the tags file for @code{gnatfind} itself (if the sources
13964 are in the search path!).
13965
13966 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13967 (replacing @var{entity} by whatever you are looking for), and vi will
13968 display a new file with the corresponding declaration of entity.
13969 @end ifclear
13970
13971 @node Examples of gnatfind Usage
13972 @section Examples of @code{gnatfind} Usage
13973
13974 @table @code
13975
13976 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13977 Find declarations for all entities xyz referenced at least once in
13978 main.adb. The references are search in every library file in the search
13979 path.
13980
13981 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13982 switch is set)
13983
13984 The output will look like:
13985 @smallexample
13986 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13987 ^directory/^[directory]^main.adb:24:10: xyz <= body
13988 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13989 @end smallexample
13990
13991 @noindent
13992 that is to say, one of the entities xyz found in main.adb is declared at
13993 line 12 of main.ads (and its body is in main.adb), and another one is
13994 declared at line 45 of foo.ads
13995
13996 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13997 This is the same command as the previous one, instead @code{gnatfind} will
13998 display the content of the Ada source file lines.
13999
14000 The output will look like:
14001
14002 @smallexample
14003 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14004 procedure xyz;
14005 ^directory/^[directory]^main.adb:24:10: xyz <= body
14006 procedure xyz is
14007 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14008 xyz : Integer;
14009 @end smallexample
14010
14011 @noindent
14012 This can make it easier to find exactly the location your are looking
14013 for.
14014
14015 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14016 Find references to all entities containing an x that are
14017 referenced on line 123 of main.ads.
14018 The references will be searched only in main.ads and foo.adb.
14019
14020 @item gnatfind main.ads:123
14021 Find declarations and bodies for all entities that are referenced on
14022 line 123 of main.ads.
14023
14024 This is the same as @code{gnatfind "*":main.adb:123}.
14025
14026 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14027 Find the declaration for the entity referenced at column 45 in
14028 line 123 of file main.adb in directory mydir. Note that it
14029 is usual to omit the identifier name when the column is given,
14030 since the column position identifies a unique reference.
14031
14032 The column has to be the beginning of the identifier, and should not
14033 point to any character in the middle of the identifier.
14034
14035 @end table
14036
14037 @c *********************************
14038 @node The GNAT Pretty-Printer gnatpp
14039 @chapter The GNAT Pretty-Printer @command{gnatpp}
14040 @findex gnatpp
14041 @cindex Pretty-Printer
14042
14043 @noindent
14044 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14045 for source reformatting / pretty-printing.
14046 It takes an Ada source file as input and generates a reformatted
14047 version as output.
14048 You can specify various style directives via switches; e.g.,
14049 identifier case conventions, rules of indentation, and comment layout.
14050
14051 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14052 tree for the input source and thus requires the input to be syntactically and
14053 semantically legal.
14054 If this condition is not met, @command{gnatpp} will terminate with an
14055 error message; no output file will be generated.
14056
14057 @command{gnatpp} cannot process sources that contain
14058 preprocessing directives.
14059
14060 If the compilation unit
14061 contained in the input source depends semantically upon units located
14062 outside the current directory, you have to provide the source search path
14063 when invoking @command{gnatpp}, if these units are contained in files with
14064 names that do not follow the GNAT file naming rules, you have to provide
14065 the configuration file describing the corresponding naming scheme;
14066 see the description of the @command{gnatpp}
14067 switches below. Another possibility is to use a project file and to
14068 call @command{gnatpp} through the @command{gnat} driver
14069 (see @ref{The GNAT Driver and Project Files}).
14070
14071 The @command{gnatpp} command has the form
14072
14073 @smallexample
14074 @c $ gnatpp @ovar{switches} @var{filename}
14075 @c Expanding @ovar macro inline (explanation in macro def comments)
14076 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14077 @end smallexample
14078
14079 @noindent
14080 where
14081 @itemize @bullet
14082 @item
14083 @var{switches} is an optional sequence of switches defining such properties as
14084 the formatting rules, the source search path, and the destination for the
14085 output source file
14086
14087 @item
14088 @var{filename} is the name (including the extension) of the source file to
14089 reformat; ``wildcards'' or several file names on the same gnatpp command are
14090 allowed. The file name may contain path information; it does not have to
14091 follow the GNAT file naming rules
14092
14093 @item
14094 @samp{@var{gcc_switches}} is a list of switches for
14095 @command{gcc}. They will be passed on to all compiler invocations made by
14096 @command{gnatelim} to generate the ASIS trees. Here you can provide
14097 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14098 use the @option{-gnatec} switch to set the configuration file,
14099 use the @option{-gnat05} switch if sources should be compiled in
14100 Ada 2005 mode etc.
14101 @end itemize
14102
14103 @menu
14104 * Switches for gnatpp::
14105 * Formatting Rules::
14106 @end menu
14107
14108 @node Switches for gnatpp
14109 @section Switches for @command{gnatpp}
14110
14111 @noindent
14112 The following subsections describe the various switches accepted by
14113 @command{gnatpp}, organized by category.
14114
14115 @ifclear vms
14116 You specify a switch by supplying a name and generally also a value.
14117 In many cases the values for a switch with a given name are incompatible with
14118 each other
14119 (for example the switch that controls the casing of a reserved word may have
14120 exactly one value: upper case, lower case, or
14121 mixed case) and thus exactly one such switch can be in effect for an
14122 invocation of @command{gnatpp}.
14123 If more than one is supplied, the last one is used.
14124 However, some values for the same switch are mutually compatible.
14125 You may supply several such switches to @command{gnatpp}, but then
14126 each must be specified in full, with both the name and the value.
14127 Abbreviated forms (the name appearing once, followed by each value) are
14128 not permitted.
14129 For example, to set
14130 the alignment of the assignment delimiter both in declarations and in
14131 assignment statements, you must write @option{-A2A3}
14132 (or @option{-A2 -A3}), but not @option{-A23}.
14133 @end ifclear
14134
14135 @ifset vms
14136 In many cases the set of options for a given qualifier are incompatible with
14137 each other (for example the qualifier that controls the casing of a reserved
14138 word may have exactly one option, which specifies either upper case, lower
14139 case, or mixed case), and thus exactly one such option can be in effect for
14140 an invocation of @command{gnatpp}.
14141 If more than one is supplied, the last one is used.
14142 However, some qualifiers have options that are mutually compatible,
14143 and then you may then supply several such options when invoking
14144 @command{gnatpp}.
14145 @end ifset
14146
14147 In most cases, it is obvious whether or not the
14148 ^values for a switch with a given name^options for a given qualifier^
14149 are compatible with each other.
14150 When the semantics might not be evident, the summaries below explicitly
14151 indicate the effect.
14152
14153 @menu
14154 * Alignment Control::
14155 * Casing Control::
14156 * Construct Layout Control::
14157 * General Text Layout Control::
14158 * Other Formatting Options::
14159 * Setting the Source Search Path::
14160 * Output File Control::
14161 * Other gnatpp Switches::
14162 @end menu
14163
14164 @node Alignment Control
14165 @subsection Alignment Control
14166 @cindex Alignment control in @command{gnatpp}
14167
14168 @noindent
14169 Programs can be easier to read if certain constructs are vertically aligned.
14170 By default all alignments are set ON.
14171 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14172 OFF, and then use one or more of the other
14173 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14174 to activate alignment for specific constructs.
14175
14176 @table @option
14177 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14178
14179 @ifset vms
14180 @item /ALIGN=ON
14181 Set all alignments to ON
14182 @end ifset
14183
14184 @item ^-A0^/ALIGN=OFF^
14185 Set all alignments to OFF
14186
14187 @item ^-A1^/ALIGN=COLONS^
14188 Align @code{:} in declarations
14189
14190 @item ^-A2^/ALIGN=DECLARATIONS^
14191 Align @code{:=} in initializations in declarations
14192
14193 @item ^-A3^/ALIGN=STATEMENTS^
14194 Align @code{:=} in assignment statements
14195
14196 @item ^-A4^/ALIGN=ARROWS^
14197 Align @code{=>} in associations
14198
14199 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14200 Align @code{at} keywords in the component clauses in record
14201 representation clauses
14202 @end table
14203
14204 @noindent
14205 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14206 is allowed.
14207
14208 @node Casing Control
14209 @subsection Casing Control
14210 @cindex Casing control in @command{gnatpp}
14211
14212 @noindent
14213 @command{gnatpp} allows you to specify the casing for reserved words,
14214 pragma names, attribute designators and identifiers.
14215 For identifiers you may define a
14216 general rule for name casing but also override this rule
14217 via a set of dictionary files.
14218
14219 Three types of casing are supported: lower case, upper case, and mixed case.
14220 Lower and upper case are self-explanatory (but since some letters in
14221 Latin1 and other GNAT-supported character sets
14222 exist only in lower-case form, an upper case conversion will have no
14223 effect on them.)
14224 ``Mixed case'' means that the first letter, and also each letter immediately
14225 following an underscore, are converted to their uppercase forms;
14226 all the other letters are converted to their lowercase forms.
14227
14228 @table @option
14229 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14230 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14231 Attribute designators are lower case
14232
14233 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14234 Attribute designators are upper case
14235
14236 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14237 Attribute designators are mixed case (this is the default)
14238
14239 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14240 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14241 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14242 lower case (this is the default)
14243
14244 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14245 Keywords are upper case
14246
14247 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14248 @item ^-nD^/NAME_CASING=AS_DECLARED^
14249 Name casing for defining occurrences are as they appear in the source file
14250 (this is the default)
14251
14252 @item ^-nU^/NAME_CASING=UPPER_CASE^
14253 Names are in upper case
14254
14255 @item ^-nL^/NAME_CASING=LOWER_CASE^
14256 Names are in lower case
14257
14258 @item ^-nM^/NAME_CASING=MIXED_CASE^
14259 Names are in mixed case
14260
14261 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14262 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14263 Enumeration literal casing for defining occurrences are as they appear in the
14264 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14265
14266 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14267 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14268 setting.
14269
14270 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14271 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14272 setting.
14273
14274 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14275 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14276 setting.
14277
14278 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14279 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14280 Names introduced by type and subtype declarations are always
14281 cased as they appear in the declaration in the source file.
14282 Overrides ^-n^/NAME_CASING^ casing setting.
14283
14284 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14285 Names introduced by type and subtype declarations are always in
14286 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14287
14288 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14289 Names introduced by type and subtype declarations are always in
14290 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14291
14292 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14293 Names introduced by type and subtype declarations are always in
14294 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14295
14296 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14297 Names introduced by number declarations are always in
14298 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14299
14300 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14301 Names introduced by number declarations are always in
14302 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14303
14304 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14305 Names introduced by number declarations are always in
14306 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14307
14308 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14309 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14310 Pragma names are lower case
14311
14312 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14313 Pragma names are upper case
14314
14315 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14316 Pragma names are mixed case (this is the default)
14317
14318 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14319 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14320 Use @var{file} as a @emph{dictionary file} that defines
14321 the casing for a set of specified names,
14322 thereby overriding the effect on these names by
14323 any explicit or implicit
14324 ^-n^/NAME_CASING^ switch.
14325 To supply more than one dictionary file,
14326 use ^several @option{-D} switches^a list of files as options^.
14327
14328 @noindent
14329 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14330 to define the casing for the Ada predefined names and
14331 the names declared in the GNAT libraries.
14332
14333 @item ^-D-^/SPECIFIC_CASING^
14334 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14335 Do not use the default dictionary file;
14336 instead, use the casing
14337 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14338 dictionary file(s)
14339 @end table
14340
14341 @noindent
14342 The structure of a dictionary file, and details on the conventions
14343 used in the default dictionary file, are defined in @ref{Name Casing}.
14344
14345 The @option{^-D-^/SPECIFIC_CASING^} and
14346 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14347 compatible.
14348
14349 @node Construct Layout Control
14350 @subsection Construct Layout Control
14351 @cindex Layout control in @command{gnatpp}
14352
14353 @noindent
14354 This group of @command{gnatpp} switches controls the layout of comments and
14355 complex syntactic constructs. See @ref{Formatting Comments} for details
14356 on their effect.
14357
14358 @table @option
14359 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14360 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14361 All the comments remain unchanged
14362
14363 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14364 GNAT-style comment line indentation (this is the default).
14365
14366 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14367 Reference-manual comment line indentation.
14368
14369 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14370 GNAT-style comment beginning
14371
14372 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14373 Reformat comment blocks
14374
14375 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14376 Keep unchanged special form comments
14377
14378 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14379 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14380 GNAT-style layout (this is the default)
14381
14382 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14383 Compact layout
14384
14385 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14386 Uncompact layout
14387
14388 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14389 @item ^-N^/NOTABS^
14390 All the VT characters are removed from the comment text. All the HT characters
14391 are expanded with the sequences of space characters to get to the next tab
14392 stops.
14393
14394 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14395 @item ^--no-separate-is^/NO_SEPARATE_IS^
14396 Do not place the keyword @code{is} on a separate line in a subprogram body in
14397 case if the spec occupies more than one line.
14398
14399 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14400 @item ^--separate-label^/SEPARATE_LABEL^
14401 Place statement label(s) on a separate line, with the following statement
14402 on the next line.
14403
14404 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14405 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14406 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14407 keyword @code{then} in IF statements on a separate line.
14408
14409 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14410 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14411 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14412 keyword @code{then} in IF statements on a separate line. This option is
14413 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14414
14415 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14416 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14417 Start each USE clause in a context clause from a separate line.
14418
14419 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14420 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14421 Use a separate line for a loop or block statement name, but do not use an extra
14422 indentation level for the statement itself.
14423
14424 @end table
14425
14426 @ifclear vms
14427 @noindent
14428 The @option{-c1} and @option{-c2} switches are incompatible.
14429 The @option{-c3} and @option{-c4} switches are compatible with each other and
14430 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14431 the other comment formatting switches.
14432
14433 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14434 @end ifclear
14435
14436 @ifset vms
14437 @noindent
14438 For the @option{/COMMENTS_LAYOUT} qualifier:
14439 @itemize @bullet
14440 @item
14441 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14442 @item
14443 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14444 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14445 @end itemize
14446
14447 @noindent
14448 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14449 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14450 @end ifset
14451
14452 @node General Text Layout Control
14453 @subsection General Text Layout Control
14454
14455 @noindent
14456 These switches allow control over line length and indentation.
14457
14458 @table @option
14459 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14460 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14461 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14462
14463 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14464 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14465 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14466
14467 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14468 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14469 Indentation level for continuation lines (relative to the line being
14470 continued), @var{nnn} from 1@dots{}9.
14471 The default
14472 value is one less than the (normal) indentation level, unless the
14473 indentation is set to 1 (in which case the default value for continuation
14474 line indentation is also 1)
14475 @end table
14476
14477 @node Other Formatting Options
14478 @subsection Other Formatting Options
14479
14480 @noindent
14481 These switches control the inclusion of missing end/exit labels, and
14482 the indentation level in @b{case} statements.
14483
14484 @table @option
14485 @item ^-e^/NO_MISSED_LABELS^
14486 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14487 Do not insert missing end/exit labels. An end label is the name of
14488 a construct that may optionally be repeated at the end of the
14489 construct's declaration;
14490 e.g., the names of packages, subprograms, and tasks.
14491 An exit label is the name of a loop that may appear as target
14492 of an exit statement within the loop.
14493 By default, @command{gnatpp} inserts these end/exit labels when
14494 they are absent from the original source. This option suppresses such
14495 insertion, so that the formatted source reflects the original.
14496
14497 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14498 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14499 Insert a Form Feed character after a pragma Page.
14500
14501 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14502 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14503 Do not use an additional indentation level for @b{case} alternatives
14504 and variants if there are @var{nnn} or more (the default
14505 value is 10).
14506 If @var{nnn} is 0, an additional indentation level is
14507 used for @b{case} alternatives and variants regardless of their number.
14508
14509 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14510 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14511 If the number of parameter associations is greater than @var{nnn} and if at
14512 least one association uses named notation, start each association from
14513 a new line. If @var{nnn} is 0, no check for the number of associations
14514 is made, this is the default.
14515
14516 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14517 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14518 If the number of parameter specifications is greater than @var{nnn}
14519 (or equal to @var{nnn} in case of a function), start each specification from
14520 a new line. The default for @var{nnn} is 3.
14521 @end table
14522
14523 @node Setting the Source Search Path
14524 @subsection Setting the Source Search Path
14525
14526 @noindent
14527 To define the search path for the input source file, @command{gnatpp}
14528 uses the same switches as the GNAT compiler, with the same effects.
14529
14530 @table @option
14531 @item ^-I^/SEARCH=^@var{dir}
14532 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14533 The same as the corresponding gcc switch
14534
14535 @item ^-I-^/NOCURRENT_DIRECTORY^
14536 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14537 The same as the corresponding gcc switch
14538
14539 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14540 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14541 The same as the corresponding gcc switch
14542
14543 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14544 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14545 The same as the corresponding gcc switch
14546
14547 @end table
14548
14549 @node Output File Control
14550 @subsection Output File Control
14551
14552 @noindent
14553 By default the output is sent to the file whose name is obtained by appending
14554 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14555 (if the file with this name already exists, it is unconditionally overwritten).
14556 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14557 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14558 as output file.
14559 The output may be redirected by the following switches:
14560
14561 @table @option
14562 @item ^-pipe^/STANDARD_OUTPUT^
14563 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14564 Send the output to @code{Standard_Output}
14565
14566 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14567 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14568 Write the output into @var{output_file}.
14569 If @var{output_file} already exists, @command{gnatpp} terminates without
14570 reading or processing the input file.
14571
14572 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14573 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14574 Write the output into @var{output_file}, overwriting the existing file
14575 (if one is present).
14576
14577 @item ^-r^/REPLACE^
14578 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14579 Replace the input source file with the reformatted output, and copy the
14580 original input source into the file whose name is obtained by appending the
14581 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14582 If a file with this name already exists, @command{gnatpp} terminates without
14583 reading or processing the input file.
14584
14585 @item ^-rf^/OVERRIDING_REPLACE^
14586 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14587 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14588 already exists, it is overwritten.
14589
14590 @item ^-rnb^/REPLACE_NO_BACKUP^
14591 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14592 Replace the input source file with the reformatted output without
14593 creating any backup copy of the input source.
14594
14595 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14596 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14597 Specifies the format of the reformatted output file. The @var{xxx}
14598 ^string specified with the switch^option^ may be either
14599 @itemize @bullet
14600 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14601 @item ``@option{^crlf^CRLF^}''
14602 the same as @option{^crlf^CRLF^}
14603 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14604 @item ``@option{^lf^LF^}''
14605 the same as @option{^unix^UNIX^}
14606 @end itemize
14607
14608 @item ^-W^/RESULT_ENCODING=^@var{e}
14609 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14610 Specify the wide character encoding method used to write the code in the
14611 result file
14612 @var{e} is one of the following:
14613
14614 @itemize @bullet
14615
14616 @item ^h^HEX^
14617 Hex encoding
14618
14619 @item ^u^UPPER^
14620 Upper half encoding
14621
14622 @item ^s^SHIFT_JIS^
14623 Shift/JIS encoding
14624
14625 @item ^e^EUC^
14626 EUC encoding
14627
14628 @item ^8^UTF8^
14629 UTF-8 encoding
14630
14631 @item ^b^BRACKETS^
14632 Brackets encoding (default value)
14633 @end itemize
14634
14635 @end table
14636
14637 @noindent
14638 Options @option{^-pipe^/STANDARD_OUTPUT^},
14639 @option{^-o^/OUTPUT^} and
14640 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14641 contains only one file to reformat.
14642 Option
14643 @option{^--eol^/END_OF_LINE^}
14644 and
14645 @option{^-W^/RESULT_ENCODING^}
14646 cannot be used together
14647 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14648
14649 @node Other gnatpp Switches
14650 @subsection Other @code{gnatpp} Switches
14651
14652 @noindent
14653 The additional @command{gnatpp} switches are defined in this subsection.
14654
14655 @table @option
14656 @item ^-files @var{filename}^/FILES=@var{filename}^
14657 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14658 Take the argument source files from the specified file. This file should be an
14659 ordinary text file containing file names separated by spaces or
14660 line breaks. You can use this switch more than once in the same call to
14661 @command{gnatpp}. You also can combine this switch with an explicit list of
14662 files.
14663
14664 @item ^-v^/VERBOSE^
14665 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14666 Verbose mode;
14667 @command{gnatpp} generates version information and then
14668 a trace of the actions it takes to produce or obtain the ASIS tree.
14669
14670 @item ^-w^/WARNINGS^
14671 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14672 Warning mode;
14673 @command{gnatpp} generates a warning whenever it cannot provide
14674 a required layout in the result source.
14675 @end table
14676
14677 @node Formatting Rules
14678 @section Formatting Rules
14679
14680 @noindent
14681 The following subsections show how @command{gnatpp} treats ``white space'',
14682 comments, program layout, and name casing.
14683 They provide the detailed descriptions of the switches shown above.
14684
14685 @menu
14686 * White Space and Empty Lines::
14687 * Formatting Comments::
14688 * Construct Layout::
14689 * Name Casing::
14690 @end menu
14691
14692 @node White Space and Empty Lines
14693 @subsection White Space and Empty Lines
14694
14695 @noindent
14696 @command{gnatpp} does not have an option to control space characters.
14697 It will add or remove spaces according to the style illustrated by the
14698 examples in the @cite{Ada Reference Manual}.
14699
14700 The only format effectors
14701 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14702 that will appear in the output file are platform-specific line breaks,
14703 and also format effectors within (but not at the end of) comments.
14704 In particular, each horizontal tab character that is not inside
14705 a comment will be treated as a space and thus will appear in the
14706 output file as zero or more spaces depending on
14707 the reformatting of the line in which it appears.
14708 The only exception is a Form Feed character, which is inserted after a
14709 pragma @code{Page} when @option{-ff} is set.
14710
14711 The output file will contain no lines with trailing ``white space'' (spaces,
14712 format effectors).
14713
14714 Empty lines in the original source are preserved
14715 only if they separate declarations or statements.
14716 In such contexts, a
14717 sequence of two or more empty lines is replaced by exactly one empty line.
14718 Note that a blank line will be removed if it separates two ``comment blocks''
14719 (a comment block is a sequence of whole-line comments).
14720 In order to preserve a visual separation between comment blocks, use an
14721 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14722 Likewise, if for some reason you wish to have a sequence of empty lines,
14723 use a sequence of empty comments instead.
14724
14725 @node Formatting Comments
14726 @subsection Formatting Comments
14727
14728 @noindent
14729 Comments in Ada code are of two kinds:
14730 @itemize @bullet
14731 @item
14732 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14733 ``white space'') on a line
14734
14735 @item
14736 an @emph{end-of-line comment}, which follows some other Ada lexical element
14737 on the same line.
14738 @end itemize
14739
14740 @noindent
14741 The indentation of a whole-line comment is that of either
14742 the preceding or following line in
14743 the formatted source, depending on switch settings as will be described below.
14744
14745 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14746 between the end of the preceding Ada lexical element and the beginning
14747 of the comment as appear in the original source,
14748 unless either the comment has to be split to
14749 satisfy the line length limitation, or else the next line contains a
14750 whole line comment that is considered a continuation of this end-of-line
14751 comment (because it starts at the same position).
14752 In the latter two
14753 cases, the start of the end-of-line comment is moved right to the nearest
14754 multiple of the indentation level.
14755 This may result in a ``line overflow'' (the right-shifted comment extending
14756 beyond the maximum line length), in which case the comment is split as
14757 described below.
14758
14759 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14760 (GNAT-style comment line indentation)
14761 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14762 (reference-manual comment line indentation).
14763 With reference-manual style, a whole-line comment is indented as if it
14764 were a declaration or statement at the same place
14765 (i.e., according to the indentation of the preceding line(s)).
14766 With GNAT style, a whole-line comment that is immediately followed by an
14767 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14768 word @b{begin}, is indented based on the construct that follows it.
14769
14770 For example:
14771 @smallexample @c ada
14772 @cartouche
14773 if A then
14774 null;
14775 -- some comment
14776 else
14777 null;
14778 end if;
14779 @end cartouche
14780 @end smallexample
14781
14782 @noindent
14783 Reference-manual indentation produces:
14784
14785 @smallexample @c ada
14786 @cartouche
14787 if A then
14788 null;
14789 -- some comment
14790 else
14791 null;
14792 end if;
14793 @end cartouche
14794 @end smallexample
14795
14796 @noindent
14797 while GNAT-style indentation produces:
14798
14799 @smallexample @c ada
14800 @cartouche
14801 if A then
14802 null;
14803 -- some comment
14804 else
14805 null;
14806 end if;
14807 @end cartouche
14808 @end smallexample
14809
14810 @noindent
14811 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14812 (GNAT style comment beginning) has the following
14813 effect:
14814
14815 @itemize @bullet
14816 @item
14817 For each whole-line comment that does not end with two hyphens,
14818 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14819 to ensure that there are at least two spaces between these hyphens and the
14820 first non-blank character of the comment.
14821 @end itemize
14822
14823 @noindent
14824 For an end-of-line comment, if in the original source the next line is a
14825 whole-line comment that starts at the same position
14826 as the end-of-line comment,
14827 then the whole-line comment (and all whole-line comments
14828 that follow it and that start at the same position)
14829 will start at this position in the output file.
14830
14831 @noindent
14832 That is, if in the original source we have:
14833
14834 @smallexample @c ada
14835 @cartouche
14836 begin
14837 A := B + C; -- B must be in the range Low1..High1
14838 -- C must be in the range Low2..High2
14839 --B+C will be in the range Low1+Low2..High1+High2
14840 X := X + 1;
14841 @end cartouche
14842 @end smallexample
14843
14844 @noindent
14845 Then in the formatted source we get
14846
14847 @smallexample @c ada
14848 @cartouche
14849 begin
14850 A := B + C; -- B must be in the range Low1..High1
14851 -- C must be in the range Low2..High2
14852 -- B+C will be in the range Low1+Low2..High1+High2
14853 X := X + 1;
14854 @end cartouche
14855 @end smallexample
14856
14857 @noindent
14858 A comment that exceeds the line length limit will be split.
14859 Unless switch
14860 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14861 the line belongs to a reformattable block, splitting the line generates a
14862 @command{gnatpp} warning.
14863 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14864 comments may be reformatted in typical
14865 word processor style (that is, moving words between lines and putting as
14866 many words in a line as possible).
14867
14868 @noindent
14869 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14870 that has a special format (that is, a character that is neither a letter nor digit
14871 not white space nor line break immediately following the leading @code{--} of
14872 the comment) should be without any change moved from the argument source
14873 into reformatted source. This switch allows to preserve comments that are used
14874 as a special marks in the code (e.g.@: SPARK annotation).
14875
14876 @node Construct Layout
14877 @subsection Construct Layout
14878
14879 @noindent
14880 In several cases the suggested layout in the Ada Reference Manual includes
14881 an extra level of indentation that many programmers prefer to avoid. The
14882 affected cases include:
14883
14884 @itemize @bullet
14885
14886 @item Record type declaration (RM 3.8)
14887
14888 @item Record representation clause (RM 13.5.1)
14889
14890 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14891
14892 @item Block statement in case if a block has a statement identifier (RM 5.6)
14893 @end itemize
14894
14895 @noindent
14896 In compact mode (when GNAT style layout or compact layout is set),
14897 the pretty printer uses one level of indentation instead
14898 of two. This is achieved in the record definition and record representation
14899 clause cases by putting the @code{record} keyword on the same line as the
14900 start of the declaration or representation clause, and in the block and loop
14901 case by putting the block or loop header on the same line as the statement
14902 identifier.
14903
14904 @noindent
14905 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14906 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14907 layout on the one hand, and uncompact layout
14908 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14909 can be illustrated by the following examples:
14910
14911 @iftex
14912 @cartouche
14913 @multitable @columnfractions .5 .5
14914 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14915
14916 @item
14917 @smallexample @c ada
14918 type q is record
14919 a : integer;
14920 b : integer;
14921 end record;
14922 @end smallexample
14923 @tab
14924 @smallexample @c ada
14925 type q is
14926 record
14927 a : integer;
14928 b : integer;
14929 end record;
14930 @end smallexample
14931
14932 @item
14933 @smallexample @c ada
14934 for q use record
14935 a at 0 range 0 .. 31;
14936 b at 4 range 0 .. 31;
14937 end record;
14938 @end smallexample
14939 @tab
14940 @smallexample @c ada
14941 for q use
14942 record
14943 a at 0 range 0 .. 31;
14944 b at 4 range 0 .. 31;
14945 end record;
14946 @end smallexample
14947
14948 @item
14949 @smallexample @c ada
14950 Block : declare
14951 A : Integer := 3;
14952 begin
14953 Proc (A, A);
14954 end Block;
14955 @end smallexample
14956 @tab
14957 @smallexample @c ada
14958 Block :
14959 declare
14960 A : Integer := 3;
14961 begin
14962 Proc (A, A);
14963 end Block;
14964 @end smallexample
14965
14966 @item
14967 @smallexample @c ada
14968 Clear : for J in 1 .. 10 loop
14969 A (J) := 0;
14970 end loop Clear;
14971 @end smallexample
14972 @tab
14973 @smallexample @c ada
14974 Clear :
14975 for J in 1 .. 10 loop
14976 A (J) := 0;
14977 end loop Clear;
14978 @end smallexample
14979 @end multitable
14980 @end cartouche
14981 @end iftex
14982
14983 @ifnottex
14984 @smallexample
14985 @cartouche
14986 GNAT style, compact layout Uncompact layout
14987
14988 type q is record type q is
14989 a : integer; record
14990 b : integer; a : integer;
14991 end record; b : integer;
14992 end record;
14993
14994 for q use record for q use
14995 a at 0 range 0 .. 31; record
14996 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
14997 end record; b at 4 range 0 .. 31;
14998 end record;
14999
15000 Block : declare Block :
15001 A : Integer := 3; declare
15002 begin A : Integer := 3;
15003 Proc (A, A); begin
15004 end Block; Proc (A, A);
15005 end Block;
15006
15007 Clear : for J in 1 .. 10 loop Clear :
15008 A (J) := 0; for J in 1 .. 10 loop
15009 end loop Clear; A (J) := 0;
15010 end loop Clear;
15011 @end cartouche
15012 @end smallexample
15013 @end ifnottex
15014
15015 @noindent
15016 A further difference between GNAT style layout and compact layout is that
15017 GNAT style layout inserts empty lines as separation for
15018 compound statements, return statements and bodies.
15019
15020 Note that the layout specified by
15021 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
15022 for named block and loop statements overrides the layout defined by these
15023 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
15024 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
15025 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
15026
15027 @node Name Casing
15028 @subsection Name Casing
15029
15030 @noindent
15031 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15032 the same casing as the corresponding defining identifier.
15033
15034 You control the casing for defining occurrences via the
15035 @option{^-n^/NAME_CASING^} switch.
15036 @ifclear vms
15037 With @option{-nD} (``as declared'', which is the default),
15038 @end ifclear
15039 @ifset vms
15040 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15041 @end ifset
15042 defining occurrences appear exactly as in the source file
15043 where they are declared.
15044 The other ^values for this switch^options for this qualifier^ ---
15045 @option{^-nU^UPPER_CASE^},
15046 @option{^-nL^LOWER_CASE^},
15047 @option{^-nM^MIXED_CASE^} ---
15048 result in
15049 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15050 If @command{gnatpp} changes the casing of a defining
15051 occurrence, it analogously changes the casing of all the
15052 usage occurrences of this name.
15053
15054 If the defining occurrence of a name is not in the source compilation unit
15055 currently being processed by @command{gnatpp}, the casing of each reference to
15056 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15057 switch (subject to the dictionary file mechanism described below).
15058 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15059 had affected the
15060 casing for the defining occurrence of the name.
15061
15062 Some names may need to be spelled with casing conventions that are not
15063 covered by the upper-, lower-, and mixed-case transformations.
15064 You can arrange correct casing by placing such names in a
15065 @emph{dictionary file},
15066 and then supplying a @option{^-D^/DICTIONARY^} switch.
15067 The casing of names from dictionary files overrides
15068 any @option{^-n^/NAME_CASING^} switch.
15069
15070 To handle the casing of Ada predefined names and the names from GNAT libraries,
15071 @command{gnatpp} assumes a default dictionary file.
15072 The name of each predefined entity is spelled with the same casing as is used
15073 for the entity in the @cite{Ada Reference Manual}.
15074 The name of each entity in the GNAT libraries is spelled with the same casing
15075 as is used in the declaration of that entity.
15076
15077 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15078 default dictionary file.
15079 Instead, the casing for predefined and GNAT-defined names will be established
15080 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15081 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15082 will appear as just shown,
15083 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15084 To ensure that even such names are rendered in uppercase,
15085 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15086 (or else, less conveniently, place these names in upper case in a dictionary
15087 file).
15088
15089 A dictionary file is
15090 a plain text file; each line in this file can be either a blank line
15091 (containing only space characters and ASCII.HT characters), an Ada comment
15092 line, or the specification of exactly one @emph{casing schema}.
15093
15094 A casing schema is a string that has the following syntax:
15095
15096 @smallexample
15097 @cartouche
15098 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15099
15100 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15101 @end cartouche
15102 @end smallexample
15103
15104 @noindent
15105 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15106 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15107
15108 The casing schema string can be followed by white space and/or an Ada-style
15109 comment; any amount of white space is allowed before the string.
15110
15111 If a dictionary file is passed as
15112 @ifclear vms
15113 the value of a @option{-D@var{file}} switch
15114 @end ifclear
15115 @ifset vms
15116 an option to the @option{/DICTIONARY} qualifier
15117 @end ifset
15118 then for every
15119 simple name and every identifier, @command{gnatpp} checks if the dictionary
15120 defines the casing for the name or for some of its parts (the term ``subword''
15121 is used below to denote the part of a name which is delimited by ``_'' or by
15122 the beginning or end of the word and which does not contain any ``_'' inside):
15123
15124 @itemize @bullet
15125 @item
15126 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15127 the casing defined by the dictionary; no subwords are checked for this word
15128
15129 @item
15130 for every subword @command{gnatpp} checks if the dictionary contains the
15131 corresponding string of the form @code{*@var{simple_identifier}*},
15132 and if it does, the casing of this @var{simple_identifier} is used
15133 for this subword
15134
15135 @item
15136 if the whole name does not contain any ``_'' inside, and if for this name
15137 the dictionary contains two entries - one of the form @var{identifier},
15138 and another - of the form *@var{simple_identifier}*, then the first one
15139 is applied to define the casing of this name
15140
15141 @item
15142 if more than one dictionary file is passed as @command{gnatpp} switches, each
15143 dictionary adds new casing exceptions and overrides all the existing casing
15144 exceptions set by the previous dictionaries
15145
15146 @item
15147 when @command{gnatpp} checks if the word or subword is in the dictionary,
15148 this check is not case sensitive
15149 @end itemize
15150
15151 @noindent
15152 For example, suppose we have the following source to reformat:
15153
15154 @smallexample @c ada
15155 @cartouche
15156 procedure test is
15157 name1 : integer := 1;
15158 name4_name3_name2 : integer := 2;
15159 name2_name3_name4 : Boolean;
15160 name1_var : Float;
15161 begin
15162 name2_name3_name4 := name4_name3_name2 > name1;
15163 end;
15164 @end cartouche
15165 @end smallexample
15166
15167 @noindent
15168 And suppose we have two dictionaries:
15169
15170 @smallexample
15171 @cartouche
15172 @i{dict1:}
15173 NAME1
15174 *NaMe3*
15175 *Name1*
15176 @end cartouche
15177
15178 @cartouche
15179 @i{dict2:}
15180 *NAME3*
15181 @end cartouche
15182 @end smallexample
15183
15184 @noindent
15185 If @command{gnatpp} is called with the following switches:
15186
15187 @smallexample
15188 @ifclear vms
15189 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15190 @end ifclear
15191 @ifset vms
15192 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15193 @end ifset
15194 @end smallexample
15195
15196 @noindent
15197 then we will get the following name casing in the @command{gnatpp} output:
15198
15199 @smallexample @c ada
15200 @cartouche
15201 procedure Test is
15202 NAME1 : Integer := 1;
15203 Name4_NAME3_Name2 : Integer := 2;
15204 Name2_NAME3_Name4 : Boolean;
15205 Name1_Var : Float;
15206 begin
15207 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15208 end Test;
15209 @end cartouche
15210 @end smallexample
15211
15212 @c *********************************
15213 @node The GNAT Metric Tool gnatmetric
15214 @chapter The GNAT Metric Tool @command{gnatmetric}
15215 @findex gnatmetric
15216 @cindex Metric tool
15217
15218 @noindent
15219 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15220 for computing various program metrics.
15221 It takes an Ada source file as input and generates a file containing the
15222 metrics data as output. Various switches control which
15223 metrics are computed and output.
15224
15225 @command{gnatmetric} generates and uses the ASIS
15226 tree for the input source and thus requires the input to be syntactically and
15227 semantically legal.
15228 If this condition is not met, @command{gnatmetric} will generate
15229 an error message; no metric information for this file will be
15230 computed and reported.
15231
15232 If the compilation unit contained in the input source depends semantically
15233 upon units in files located outside the current directory, you have to provide
15234 the source search path when invoking @command{gnatmetric}.
15235 If it depends semantically upon units that are contained
15236 in files with names that do not follow the GNAT file naming rules, you have to
15237 provide the configuration file describing the corresponding naming scheme (see
15238 the description of the @command{gnatmetric} switches below.)
15239 Alternatively, you may use a project file and invoke @command{gnatmetric}
15240 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15241
15242 The @command{gnatmetric} command has the form
15243
15244 @smallexample
15245 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15246 @c Expanding @ovar macro inline (explanation in macro def comments)
15247 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15248 @end smallexample
15249
15250 @noindent
15251 where
15252 @itemize @bullet
15253 @item
15254 @var{switches} specify the metrics to compute and define the destination for
15255 the output
15256
15257 @item
15258 Each @var{filename} is the name (including the extension) of a source
15259 file to process. ``Wildcards'' are allowed, and
15260 the file name may contain path information.
15261 If no @var{filename} is supplied, then the @var{switches} list must contain
15262 at least one
15263 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15264 Including both a @option{-files} switch and one or more
15265 @var{filename} arguments is permitted.
15266
15267 @item
15268 @samp{@var{gcc_switches}} is a list of switches for
15269 @command{gcc}. They will be passed on to all compiler invocations made by
15270 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15271 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15272 and use the @option{-gnatec} switch to set the configuration file,
15273 use the @option{-gnat05} switch if sources should be compiled in
15274 Ada 2005 mode etc.
15275 @end itemize
15276
15277 @menu
15278 * Switches for gnatmetric::
15279 @end menu
15280
15281 @node Switches for gnatmetric
15282 @section Switches for @command{gnatmetric}
15283
15284 @noindent
15285 The following subsections describe the various switches accepted by
15286 @command{gnatmetric}, organized by category.
15287
15288 @menu
15289 * Output Files Control::
15290 * Disable Metrics For Local Units::
15291 * Specifying a set of metrics to compute::
15292 * Other gnatmetric Switches::
15293 * Generate project-wide metrics::
15294 @end menu
15295
15296 @node Output Files Control
15297 @subsection Output File Control
15298 @cindex Output file control in @command{gnatmetric}
15299
15300 @noindent
15301 @command{gnatmetric} has two output formats. It can generate a
15302 textual (human-readable) form, and also XML. By default only textual
15303 output is generated.
15304
15305 When generating the output in textual form, @command{gnatmetric} creates
15306 for each Ada source file a corresponding text file
15307 containing the computed metrics, except for the case when the set of metrics
15308 specified by gnatmetric parameters consists only of metrics that are computed
15309 for the whole set of analyzed sources, but not for each Ada source.
15310 By default, this file is placed in the same directory as where the source
15311 file is located, and its name is obtained
15312 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15313 input file.
15314
15315 All the output information generated in XML format is placed in a single
15316 file. By default this file is placed in the current directory and has the
15317 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15318
15319 Some of the computed metrics are summed over the units passed to
15320 @command{gnatmetric}; for example, the total number of lines of code.
15321 By default this information is sent to @file{stdout}, but a file
15322 can be specified with the @option{-og} switch.
15323
15324 The following switches control the @command{gnatmetric} output:
15325
15326 @table @option
15327 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15328 @item ^-x^/XML^
15329 Generate the XML output
15330
15331 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15332 @item ^-xs^/XSD^
15333 Generate the XML output and the XML schema file that describes the structure
15334 of the XML metric report, this schema is assigned to the XML file. The schema
15335 file has the same name as the XML output file with @file{.xml} suffix replaced
15336 with @file{.xsd}
15337
15338 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15339 @item ^-nt^/NO_TEXT^
15340 Do not generate the output in text form (implies @option{^-x^/XML^})
15341
15342 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15343 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15344 Put text files with detailed metrics into @var{output_dir}
15345
15346 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15347 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15348 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15349 in the name of the output file.
15350
15351 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15352 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15353 Put global metrics into @var{file_name}
15354
15355 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15356 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15357 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15358
15359 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15360 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15361 Use ``short'' source file names in the output. (The @command{gnatmetric}
15362 output includes the name(s) of the Ada source file(s) from which the metrics
15363 are computed. By default each name includes the absolute path. The
15364 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15365 to exclude all directory information from the file names that are output.)
15366
15367 @end table
15368
15369 @node Disable Metrics For Local Units
15370 @subsection Disable Metrics For Local Units
15371 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15372
15373 @noindent
15374 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15375 one compilation
15376 unit per one source file. It computes line metrics for the whole source
15377 file, and it also computes syntax
15378 and complexity metrics for the file's outermost unit.
15379
15380 By default, @command{gnatmetric} will also compute all metrics for certain
15381 kinds of locally declared program units:
15382
15383 @itemize @bullet
15384 @item
15385 subprogram (and generic subprogram) bodies;
15386
15387 @item
15388 package (and generic package) specs and bodies;
15389
15390 @item
15391 task object and type specifications and bodies;
15392
15393 @item
15394 protected object and type specifications and bodies.
15395 @end itemize
15396
15397 @noindent
15398 These kinds of entities will be referred to as
15399 @emph{eligible local program units}, or simply @emph{eligible local units},
15400 @cindex Eligible local unit (for @command{gnatmetric})
15401 in the discussion below.
15402
15403 Note that a subprogram declaration, generic instantiation,
15404 or renaming declaration only receives metrics
15405 computation when it appear as the outermost entity
15406 in a source file.
15407
15408 Suppression of metrics computation for eligible local units can be
15409 obtained via the following switch:
15410
15411 @table @option
15412 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15413 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15414 Do not compute detailed metrics for eligible local program units
15415
15416 @end table
15417
15418 @node Specifying a set of metrics to compute
15419 @subsection Specifying a set of metrics to compute
15420
15421 @noindent
15422 By default all the metrics are computed and reported. The switches
15423 described in this subsection allow you to control, on an individual
15424 basis, whether metrics are computed and
15425 reported. If at least one positive metric
15426 switch is specified (that is, a switch that defines that a given
15427 metric or set of metrics is to be computed), then only
15428 explicitly specified metrics are reported.
15429
15430 @menu
15431 * Line Metrics Control::
15432 * Syntax Metrics Control::
15433 * Complexity Metrics Control::
15434 * Coupling Metrics Control::
15435 @end menu
15436
15437 @node Line Metrics Control
15438 @subsubsection Line Metrics Control
15439 @cindex Line metrics control in @command{gnatmetric}
15440
15441 @noindent
15442 For any (legal) source file, and for each of its
15443 eligible local program units, @command{gnatmetric} computes the following
15444 metrics:
15445
15446 @itemize @bullet
15447 @item
15448 the total number of lines;
15449
15450 @item
15451 the total number of code lines (i.e., non-blank lines that are not comments)
15452
15453 @item
15454 the number of comment lines
15455
15456 @item
15457 the number of code lines containing end-of-line comments;
15458
15459 @item
15460 the comment percentage: the ratio between the number of lines that contain
15461 comments and the number of all non-blank lines, expressed as a percentage;
15462
15463 @item
15464 the number of empty lines and lines containing only space characters and/or
15465 format effectors (blank lines)
15466
15467 @item
15468 the average number of code lines in subprogram bodies, task bodies, entry
15469 bodies and statement sequences in package bodies (this metric is only computed
15470 across the whole set of the analyzed units)
15471
15472 @end itemize
15473
15474 @noindent
15475 @command{gnatmetric} sums the values of the line metrics for all the
15476 files being processed and then generates the cumulative results. The tool
15477 also computes for all the files being processed the average number of code
15478 lines in bodies.
15479
15480 You can use the following switches to select the specific line metrics
15481 to be computed and reported.
15482
15483 @table @option
15484 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15485
15486 @ifclear vms
15487 @cindex @option{--no-lines@var{x}}
15488 @end ifclear
15489
15490 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15491 Report all the line metrics
15492
15493 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15494 Do not report any of line metrics
15495
15496 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15497 Report the number of all lines
15498
15499 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15500 Do not report the number of all lines
15501
15502 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15503 Report the number of code lines
15504
15505 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15506 Do not report the number of code lines
15507
15508 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15509 Report the number of comment lines
15510
15511 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15512 Do not report the number of comment lines
15513
15514 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15515 Report the number of code lines containing
15516 end-of-line comments
15517
15518 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15519 Do not report the number of code lines containing
15520 end-of-line comments
15521
15522 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15523 Report the comment percentage in the program text
15524
15525 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15526 Do not report the comment percentage in the program text
15527
15528 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15529 Report the number of blank lines
15530
15531 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15532 Do not report the number of blank lines
15533
15534 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15535 Report the average number of code lines in subprogram bodies, task bodies,
15536 entry bodies and statement sequences in package bodies. The metric is computed
15537 and reported for the whole set of processed Ada sources only.
15538
15539 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15540 Do not report the average number of code lines in subprogram bodies,
15541 task bodies, entry bodies and statement sequences in package bodies.
15542
15543 @end table
15544
15545 @node Syntax Metrics Control
15546 @subsubsection Syntax Metrics Control
15547 @cindex Syntax metrics control in @command{gnatmetric}
15548
15549 @noindent
15550 @command{gnatmetric} computes various syntactic metrics for the
15551 outermost unit and for each eligible local unit:
15552
15553 @table @emph
15554 @item LSLOC (``Logical Source Lines Of Code'')
15555 The total number of declarations and the total number of statements. Note
15556 that the definition of declarations is the one given in the reference
15557 manual:
15558
15559 @noindent
15560 ``Each of the following is defined to be a declaration: any basic_declaration;
15561 an enumeration_literal_specification; a discriminant_specification;
15562 a component_declaration; a loop_parameter_specification; a
15563 parameter_specification; a subprogram_body; an entry_declaration;
15564 an entry_index_specification; a choice_parameter_specification;
15565 a generic_formal_parameter_declaration.''
15566
15567 This means for example that each enumeration literal adds one to the count,
15568 as well as each subprogram parameter.
15569
15570 Thus the results from this metric will be significantly greater than might
15571 be expected from a naive view of counting semicolons.
15572
15573 @item Maximal static nesting level of inner program units
15574 According to
15575 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15576 package, a task unit, a protected unit, a
15577 protected entry, a generic unit, or an explicitly declared subprogram other
15578 than an enumeration literal.''
15579
15580 @item Maximal nesting level of composite syntactic constructs
15581 This corresponds to the notion of the
15582 maximum nesting level in the GNAT built-in style checks
15583 (@pxref{Style Checking})
15584 @end table
15585
15586 @noindent
15587 For the outermost unit in the file, @command{gnatmetric} additionally computes
15588 the following metrics:
15589
15590 @table @emph
15591 @item Public subprograms
15592 This metric is computed for package specs. It is the
15593 number of subprograms and generic subprograms declared in the visible
15594 part (including the visible part of nested packages, protected objects, and
15595 protected types).
15596
15597 @item All subprograms
15598 This metric is computed for bodies and subunits. The
15599 metric is equal to a total number of subprogram bodies in the compilation
15600 unit.
15601 Neither generic instantiations nor renamings-as-a-body nor body stubs
15602 are counted. Any subprogram body is counted, independently of its nesting
15603 level and enclosing constructs. Generic bodies and bodies of protected
15604 subprograms are counted in the same way as ``usual'' subprogram bodies.
15605
15606 @item Public types
15607 This metric is computed for package specs and
15608 generic package declarations. It is the total number of types
15609 that can be referenced from outside this compilation unit, plus the
15610 number of types from all the visible parts of all the visible generic
15611 packages. Generic formal types are not counted. Only types, not subtypes,
15612 are included.
15613
15614 @noindent
15615 Along with the total number of public types, the following
15616 types are counted and reported separately:
15617
15618 @itemize @bullet
15619 @item
15620 Abstract types
15621
15622 @item
15623 Root tagged types (abstract, non-abstract, private, non-private). Type
15624 extensions are @emph{not} counted
15625
15626 @item
15627 Private types (including private extensions)
15628
15629 @item
15630 Task types
15631
15632 @item
15633 Protected types
15634
15635 @end itemize
15636
15637 @item All types
15638 This metric is computed for any compilation unit. It is equal to the total
15639 number of the declarations of different types given in the compilation unit.
15640 The private and the corresponding full type declaration are counted as one
15641 type declaration. Incomplete type declarations and generic formal types
15642 are not counted.
15643 No distinction is made among different kinds of types (abstract,
15644 private etc.); the total number of types is computed and reported.
15645
15646 @end table
15647
15648 @noindent
15649 By default, all the syntax metrics are computed and reported. You can use the
15650 following switches to select specific syntax metrics.
15651
15652 @table @option
15653
15654 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15655
15656 @ifclear vms
15657 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15658 @end ifclear
15659
15660 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15661 Report all the syntax metrics
15662
15663 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15664 Do not report any of syntax metrics
15665
15666 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15667 Report the total number of declarations
15668
15669 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15670 Do not report the total number of declarations
15671
15672 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15673 Report the total number of statements
15674
15675 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15676 Do not report the total number of statements
15677
15678 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15679 Report the number of public subprograms in a compilation unit
15680
15681 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15682 Do not report the number of public subprograms in a compilation unit
15683
15684 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15685 Report the number of all the subprograms in a compilation unit
15686
15687 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15688 Do not report the number of all the subprograms in a compilation unit
15689
15690 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15691 Report the number of public types in a compilation unit
15692
15693 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15694 Do not report the number of public types in a compilation unit
15695
15696 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15697 Report the number of all the types in a compilation unit
15698
15699 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15700 Do not report the number of all the types in a compilation unit
15701
15702 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15703 Report the maximal program unit nesting level
15704
15705 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15706 Do not report the maximal program unit nesting level
15707
15708 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15709 Report the maximal construct nesting level
15710
15711 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15712 Do not report the maximal construct nesting level
15713
15714 @end table
15715
15716 @node Complexity Metrics Control
15717 @subsubsection Complexity Metrics Control
15718 @cindex Complexity metrics control in @command{gnatmetric}
15719
15720 @noindent
15721 For a program unit that is an executable body (a subprogram body (including
15722 generic bodies), task body, entry body or a package body containing
15723 its own statement sequence) @command{gnatmetric} computes the following
15724 complexity metrics:
15725
15726 @itemize @bullet
15727 @item
15728 McCabe cyclomatic complexity;
15729
15730 @item
15731 McCabe essential complexity;
15732
15733 @item
15734 maximal loop nesting level;
15735
15736 @item
15737 extra exit points (for subprograms);
15738 @end itemize
15739
15740 @noindent
15741 The McCabe cyclomatic complexity metric is defined
15742 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15743
15744 According to McCabe, both control statements and short-circuit control forms
15745 should be taken into account when computing cyclomatic complexity.
15746 For Ada 2012 we have also take into account conditional expressions
15747 and quantified expressions. For each body, we compute three metric values:
15748
15749 @itemize @bullet
15750 @item
15751 the complexity introduced by control
15752 statements only, without taking into account short-circuit forms,
15753
15754 @item
15755 the complexity introduced by short-circuit control forms only, and
15756
15757 @item
15758 the total
15759 cyclomatic complexity, which is the sum of these two values.
15760 @end itemize
15761
15762 @noindent
15763
15764 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15765 An expression function cannot have statements as its components, so only one
15766 metric value is computed as a cyclomatic complexity of an expression function.
15767
15768 The origin of cyclomatic complexity metric is the need to estimate the number
15769 of independent paths in the control flow graph that in turn gives the number
15770 of tests needed to satisfy paths coverage testing completeness criterion.
15771 Considered from the testing point of view, a static Ada @code{loop} (that is,
15772 the @code{loop} statement having static subtype in loop parameter
15773 specification) does not add to cyclomatic complexity. By providing
15774 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
15775 may specify that such loops should not be counted when computing the
15776 cyclomatic complexity metric
15777
15778 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15779 counted for the code that is reduced by excluding all the pure structural Ada
15780 control statements. An compound statement is considered as a non-structural
15781 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15782 or if it contains a @code{goto} statement that transfers the control outside
15783 the operator. A selective accept statement with @code{terminate} alternative
15784 is considered as non-structural statement. When computing this metric,
15785 @code{exit} statements are treated in the same way as @code{goto}
15786 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
15787
15788 The Ada essential complexity metric defined here is intended to quantify
15789 the extent to which the software is unstructured. It is adapted from
15790 the McCabe essential complexity metric defined in
15791 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15792 suitable for typical Ada usage. For example, short circuit forms
15793 are not penalized as unstructured in the Ada essential complexity metric.
15794
15795 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15796 the code in the exception handlers and in all the nested program units. The
15797 code of assertions and predicates (that is, subprogram preconditions and
15798 postconditions, subtype predicates and type invariants) is also skipped.
15799
15800 By default, all the complexity metrics are computed and reported.
15801 For more fine-grained control you can use
15802 the following switches:
15803
15804 @table @option
15805 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
15806
15807 @ifclear vms
15808 @cindex @option{--no-complexity@var{x}}
15809 @end ifclear
15810
15811 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
15812 Report all the complexity metrics
15813
15814 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15815 Do not report any of complexity metrics
15816
15817 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15818 Report the McCabe Cyclomatic Complexity
15819
15820 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15821 Do not report the McCabe Cyclomatic Complexity
15822
15823 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15824 Report the Essential Complexity
15825
15826 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15827 Do not report the Essential Complexity
15828
15829 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15830 Report maximal loop nesting level
15831
15832 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15833 Do not report maximal loop nesting level
15834
15835 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15836 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15837 task bodies, entry bodies and statement sequences in package bodies.
15838 The metric is computed and reported for whole set of processed Ada sources
15839 only.
15840
15841 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15842 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15843 bodies, task bodies, entry bodies and statement sequences in package bodies
15844
15845 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15846 @item ^-ne^/NO_EXITS_AS_GOTOS^
15847 Do not consider @code{exit} statements as @code{goto}s when
15848 computing Essential Complexity
15849
15850 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15851 @item ^--no-static-loop^/NO_STATIC_LOOP^
15852 Do not consider static loops when computing cyclomatic complexity
15853
15854 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15855 Report the extra exit points for subprogram bodies. As an exit point, this
15856 metric counts @code{return} statements and raise statements in case when the
15857 raised exception is not handled in the same body. In case of a function this
15858 metric subtracts 1 from the number of exit points, because a function body
15859 must contain at least one @code{return} statement.
15860
15861 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15862 Do not report the extra exit points for subprogram bodies
15863 @end table
15864
15865
15866 @node Coupling Metrics Control
15867 @subsubsection Coupling Metrics Control
15868 @cindex Coupling metrics control in @command{gnatmetric}
15869
15870 @noindent
15871 @cindex Coupling metrics (in in @command{gnatmetric})
15872 Coupling metrics measure the dependencies between a given entity and other
15873 entities the program consists of. The goal of these metrics is to estimate the
15874 stability of the whole program considered as the collection of entities
15875 (modules, classes etc.).
15876
15877 Gnatmetric computes the following coupling metrics:
15878
15879 @itemize @bullet
15880
15881 @item
15882 @emph{object-oriented coupling} - for classes in traditional object-oriented
15883 sense;
15884
15885 @item
15886 @emph{unit coupling} - for all the program units making up a program;
15887
15888 @item
15889 @emph{control coupling} - this metric counts dependencies between a unit and
15890 only those units that define subprograms;
15891 @end itemize
15892
15893 @noindent
15894 Two kinds of coupling metrics are computed:
15895
15896 @table @asis
15897 @item fan-out coupling (efferent coupling)
15898 @cindex fan-out coupling
15899 @cindex efferent coupling
15900 the number of entities the given entity depends upon. It
15901 estimates in what extent the given entity depends on the changes in
15902 ``external world''
15903
15904 @item fan-in coupling (afferent coupling)
15905 @cindex fan-in coupling
15906 @cindex afferent coupling
15907 the number of entities that depend on a given entity.
15908 It estimates in what extent the ``external world'' depends on the changes in a
15909 given entity
15910 @end table
15911
15912 @noindent
15913
15914 Object-oriented coupling metrics are metrics that measure the dependencies
15915 between a given class (or a group of classes) and the other classes in the
15916 program. In this subsection the term ``class'' is used in its traditional
15917 object-oriented programming sense (an instantiable module that contains data
15918 and/or method members). A @emph{category} (of classes) is a group of closely
15919 related classes that are reused and/or modified together.
15920
15921 A class @code{K}'s fan-out coupling is the number of classes
15922 that @code{K} depends upon.
15923 A category's fan-out coupling is the number of classes outside the
15924 category that the classes inside the category depend upon.
15925
15926 A class @code{K}'s fan-in coupling is the number of classes
15927 that depend upon @code{K}.
15928 A category's fan-in coupling is the number of classes outside the
15929 category that depend on classes belonging to the category.
15930
15931 Ada's implementation of the object-oriented paradigm does not use the
15932 traditional class notion, so the definition of the coupling
15933 metrics for Ada maps the class and class category notions
15934 onto Ada constructs.
15935
15936 For the coupling metrics, several kinds of modules -- a library package,
15937 a library generic package, and a library generic package instantiation --
15938 that define a tagged type or an interface type are
15939 considered to be a class. A category consists of a library package (or
15940 a library generic package) that defines a tagged or an interface type,
15941 together with all its descendant (generic) packages that define tagged
15942 or interface types. That is a
15943 category is an Ada hierarchy of library-level program units. So class coupling
15944 in case of Ada is called as tagged coupling, and category coupling - as
15945 hierarchy coupling.
15946
15947 For any package counted as a class, its body and subunits (if any) are
15948 considered together with its spec when counting the dependencies, and coupling
15949 metrics are reported for spec units only. For dependencies between classes,
15950 the Ada semantic dependencies are considered. For object-oriented coupling
15951 metrics, only dependencies on units that are considered as classes, are
15952 considered.
15953
15954 For unit and control coupling also not compilation units but program units are
15955 counted. That is, for a package, its spec, its body and its subunits (if any)
15956 are considered as making up one unit, and the dependencies that are counted
15957 are the dependencies of all these compilation units collected together as
15958 the dependencies as a (whole) unit. And metrics are reported for spec
15959 compilation units only (or for a subprogram body unit in case if there is no
15960 separate spec for the given subprogram).
15961
15962 For unit coupling, dependencies between all kinds of program units are
15963 considered. For control coupling, for each unit the dependencies of this unit
15964 upon units that define subprograms are counted, so control fan-out coupling
15965 is reported for all units, but control fan-in coupling - only for the units
15966 that define subprograms.
15967
15968 The following simple example illustrates the difference between unit coupling
15969 and control coupling metrics:
15970
15971 @smallexample @c ada
15972 package Lib_1 is
15973 function F_1 (I : Integer) return Integer;
15974 end Lib_1;
15975
15976 package Lib_2 is
15977 type T_2 is new Integer;
15978 end Lib_2;
15979
15980 package body Lib_1 is
15981 function F_1 (I : Integer) return Integer is
15982 begin
15983 return I + 1;
15984 end F_1;
15985 end Lib_1;
15986
15987 with Lib_2; use Lib_2;
15988 package Pack is
15989 Var : T_2;
15990 function Fun (I : Integer) return Integer;
15991 end Pack;
15992
15993 with Lib_1; use Lib_1;
15994 package body Pack is
15995 function Fun (I : Integer) return Integer is
15996 begin
15997 return F_1 (I);
15998 end Fun;
15999 end Pack;
16000 @end smallexample
16001
16002 @noindent
16003 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16004 units, the result will be:
16005
16006 @smallexample
16007 Coupling metrics:
16008 =================
16009 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16010 control fan-out coupling : 0
16011 control fan-in coupling : 1
16012 unit fan-out coupling : 0
16013 unit fan-in coupling : 1
16014
16015 Unit Pack (C:\customers\662\L406-007\pack.ads)
16016 control fan-out coupling : 1
16017 control fan-in coupling : 0
16018 unit fan-out coupling : 2
16019 unit fan-in coupling : 0
16020
16021 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16022 control fan-out coupling : 0
16023 unit fan-out coupling : 0
16024 unit fan-in coupling : 1
16025 @end smallexample
16026
16027 @noindent
16028 The result does not contain values for object-oriented
16029 coupling because none of the argument unit contains a tagged type and
16030 therefore none of these units can be treated as a class.
16031
16032 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16033 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16034 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16035 well as control fan-in coupling. Only one of the units @code{Pack} depends
16036 upon defines a subprogram, so its control fan-out coupling is 1.
16037
16038 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16039 not define a subprogram, so control fan-in metric cannot be applied to it,
16040 and there is one unit that depends on it (@code{Pack}), so it has
16041 unit fan-in coupling equals to 1.
16042
16043 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16044 So it has control fan-in coupling equals to 1 (because there is a unit
16045 depending on it).
16046
16047 When computing coupling metrics, @command{gnatmetric} counts only
16048 dependencies between units that are arguments of the @command{gnatmetric}
16049 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16050 get a valid result, you should call @command{gnatmetric} for
16051 the whole set of sources that make up your program. It can be done
16052 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16053 option (see @ref{The GNAT Driver and Project Files} for details).
16054
16055 By default, all the coupling metrics are disabled. You can use the following
16056 switches to specify the coupling metrics to be computed and reported:
16057
16058 @table @option
16059
16060 @ifclear vms
16061 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16062 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16063 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16064 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16065 @end ifclear
16066
16067 @ifset vms
16068 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16069 @end ifset
16070
16071 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16072 Report all the coupling metrics
16073
16074 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16075 Report tagged (class) fan-out coupling
16076
16077 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16078 Report tagged (class) fan-in coupling
16079
16080 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16081 Report hierarchy (category) fan-out coupling
16082
16083 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16084 Report hierarchy (category) fan-in coupling
16085
16086 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16087 Report unit fan-out coupling
16088
16089 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16090 Report unit fan-in coupling
16091
16092 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16093 Report control fan-out coupling
16094
16095 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16096 Report control fan-in coupling
16097 @end table
16098
16099 @node Other gnatmetric Switches
16100 @subsection Other @code{gnatmetric} Switches
16101
16102 @noindent
16103 Additional @command{gnatmetric} switches are as follows:
16104
16105 @table @option
16106 @item ^-files @var{filename}^/FILES=@var{filename}^
16107 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16108 Take the argument source files from the specified file. This file should be an
16109 ordinary text file containing file names separated by spaces or
16110 line breaks. You can use this switch more than once in the same call to
16111 @command{gnatmetric}. You also can combine this switch with
16112 an explicit list of files.
16113
16114 @item ^-v^/VERBOSE^
16115 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16116 Verbose mode;
16117 @command{gnatmetric} generates version information and then
16118 a trace of sources being processed.
16119
16120 @item ^-q^/QUIET^
16121 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16122 Quiet mode.
16123 @end table
16124
16125 @node Generate project-wide metrics
16126 @subsection Generate project-wide metrics
16127
16128 In order to compute metrics on all units of a given project, you can use
16129 the @command{gnat} driver along with the @option{-P} option:
16130 @smallexample
16131 gnat metric -Pproj
16132 @end smallexample
16133
16134 @noindent
16135 If the project @code{proj} depends upon other projects, you can compute
16136 the metrics on the project closure using the @option{-U} option:
16137 @smallexample
16138 gnat metric -Pproj -U
16139 @end smallexample
16140
16141 @noindent
16142 Finally, if not all the units are relevant to a particular main
16143 program in the project closure, you can generate metrics for the set
16144 of units needed to create a given main program (unit closure) using
16145 the @option{-U} option followed by the name of the main unit:
16146 @smallexample
16147 gnat metric -Pproj -U main
16148 @end smallexample
16149
16150
16151 @c ***********************************
16152 @node File Name Krunching Using gnatkr
16153 @chapter File Name Krunching Using @code{gnatkr}
16154 @findex gnatkr
16155
16156 @noindent
16157 This chapter discusses the method used by the compiler to shorten
16158 the default file names chosen for Ada units so that they do not
16159 exceed the maximum length permitted. It also describes the
16160 @code{gnatkr} utility that can be used to determine the result of
16161 applying this shortening.
16162 @menu
16163 * About gnatkr::
16164 * Using gnatkr::
16165 * Krunching Method::
16166 * Examples of gnatkr Usage::
16167 @end menu
16168
16169 @node About gnatkr
16170 @section About @code{gnatkr}
16171
16172 @noindent
16173 The default file naming rule in GNAT
16174 is that the file name must be derived from
16175 the unit name. The exact default rule is as follows:
16176 @itemize @bullet
16177 @item
16178 Take the unit name and replace all dots by hyphens.
16179 @item
16180 If such a replacement occurs in the
16181 second character position of a name, and the first character is
16182 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16183 then replace the dot by the character
16184 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16185 instead of a minus.
16186 @end itemize
16187 The reason for this exception is to avoid clashes
16188 with the standard names for children of System, Ada, Interfaces,
16189 and GNAT, which use the prefixes
16190 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16191 respectively.
16192
16193 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16194 switch of the compiler activates a ``krunching''
16195 circuit that limits file names to nn characters (where nn is a decimal
16196 integer). For example, using OpenVMS,
16197 where the maximum file name length is
16198 39, the value of nn is usually set to 39, but if you want to generate
16199 a set of files that would be usable if ported to a system with some
16200 different maximum file length, then a different value can be specified.
16201 The default value of 39 for OpenVMS need not be specified.
16202
16203 The @code{gnatkr} utility can be used to determine the krunched name for
16204 a given file, when krunched to a specified maximum length.
16205
16206 @node Using gnatkr
16207 @section Using @code{gnatkr}
16208
16209 @noindent
16210 The @code{gnatkr} command has the form
16211
16212 @ifclear vms
16213 @smallexample
16214 @c $ gnatkr @var{name} @ovar{length}
16215 @c Expanding @ovar macro inline (explanation in macro def comments)
16216 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16217 @end smallexample
16218 @end ifclear
16219
16220 @ifset vms
16221 @smallexample
16222 $ gnatkr @var{name} /COUNT=nn
16223 @end smallexample
16224 @end ifset
16225
16226 @noindent
16227 @var{name} is the uncrunched file name, derived from the name of the unit
16228 in the standard manner described in the previous section (i.e., in particular
16229 all dots are replaced by hyphens). The file name may or may not have an
16230 extension (defined as a suffix of the form period followed by arbitrary
16231 characters other than period). If an extension is present then it will
16232 be preserved in the output. For example, when krunching @file{hellofile.ads}
16233 to eight characters, the result will be hellofil.ads.
16234
16235 Note: for compatibility with previous versions of @code{gnatkr} dots may
16236 appear in the name instead of hyphens, but the last dot will always be
16237 taken as the start of an extension. So if @code{gnatkr} is given an argument
16238 such as @file{Hello.World.adb} it will be treated exactly as if the first
16239 period had been a hyphen, and for example krunching to eight characters
16240 gives the result @file{hellworl.adb}.
16241
16242 Note that the result is always all lower case (except on OpenVMS where it is
16243 all upper case). Characters of the other case are folded as required.
16244
16245 @var{length} represents the length of the krunched name. The default
16246 when no argument is given is ^8^39^ characters. A length of zero stands for
16247 unlimited, in other words do not chop except for system files where the
16248 implied crunching length is always eight characters.
16249
16250 @noindent
16251 The output is the krunched name. The output has an extension only if the
16252 original argument was a file name with an extension.
16253
16254 @node Krunching Method
16255 @section Krunching Method
16256
16257 @noindent
16258 The initial file name is determined by the name of the unit that the file
16259 contains. The name is formed by taking the full expanded name of the
16260 unit and replacing the separating dots with hyphens and
16261 using ^lowercase^uppercase^
16262 for all letters, except that a hyphen in the second character position is
16263 replaced by a ^tilde^dollar sign^ if the first character is
16264 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16265 The extension is @code{.ads} for a
16266 spec and @code{.adb} for a body.
16267 Krunching does not affect the extension, but the file name is shortened to
16268 the specified length by following these rules:
16269
16270 @itemize @bullet
16271 @item
16272 The name is divided into segments separated by hyphens, tildes or
16273 underscores and all hyphens, tildes, and underscores are
16274 eliminated. If this leaves the name short enough, we are done.
16275
16276 @item
16277 If the name is too long, the longest segment is located (left-most
16278 if there are two of equal length), and shortened by dropping
16279 its last character. This is repeated until the name is short enough.
16280
16281 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16282 to fit the name into 8 characters as required by some operating systems.
16283
16284 @smallexample
16285 our-strings-wide_fixed 22
16286 our strings wide fixed 19
16287 our string wide fixed 18
16288 our strin wide fixed 17
16289 our stri wide fixed 16
16290 our stri wide fixe 15
16291 our str wide fixe 14
16292 our str wid fixe 13
16293 our str wid fix 12
16294 ou str wid fix 11
16295 ou st wid fix 10
16296 ou st wi fix 9
16297 ou st wi fi 8
16298 Final file name: oustwifi.adb
16299 @end smallexample
16300
16301 @item
16302 The file names for all predefined units are always krunched to eight
16303 characters. The krunching of these predefined units uses the following
16304 special prefix replacements:
16305
16306 @table @file
16307 @item ada-
16308 replaced by @file{^a^A^-}
16309
16310 @item gnat-
16311 replaced by @file{^g^G^-}
16312
16313 @item interfaces-
16314 replaced by @file{^i^I^-}
16315
16316 @item system-
16317 replaced by @file{^s^S^-}
16318 @end table
16319
16320 These system files have a hyphen in the second character position. That
16321 is why normal user files replace such a character with a
16322 ^tilde^dollar sign^, to
16323 avoid confusion with system file names.
16324
16325 As an example of this special rule, consider
16326 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16327
16328 @smallexample
16329 ada-strings-wide_fixed 22
16330 a- strings wide fixed 18
16331 a- string wide fixed 17
16332 a- strin wide fixed 16
16333 a- stri wide fixed 15
16334 a- stri wide fixe 14
16335 a- str wide fixe 13
16336 a- str wid fixe 12
16337 a- str wid fix 11
16338 a- st wid fix 10
16339 a- st wi fix 9
16340 a- st wi fi 8
16341 Final file name: a-stwifi.adb
16342 @end smallexample
16343 @end itemize
16344
16345 Of course no file shortening algorithm can guarantee uniqueness over all
16346 possible unit names, and if file name krunching is used then it is your
16347 responsibility to ensure that no name clashes occur. The utility
16348 program @code{gnatkr} is supplied for conveniently determining the
16349 krunched name of a file.
16350
16351 @node Examples of gnatkr Usage
16352 @section Examples of @code{gnatkr} Usage
16353
16354 @smallexample
16355 @iftex
16356 @leftskip=0cm
16357 @end iftex
16358 @ifclear vms
16359 $ gnatkr very_long_unit_name.ads --> velounna.ads
16360 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16361 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16362 $ gnatkr grandparent-parent-child --> grparchi
16363 @end ifclear
16364 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16365 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16366 @end smallexample
16367
16368 @node Preprocessing Using gnatprep
16369 @chapter Preprocessing Using @code{gnatprep}
16370 @findex gnatprep
16371
16372 @noindent
16373 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16374 preprocessing.
16375 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16376 special GNAT features.
16377 For further discussion of conditional compilation in general, see
16378 @ref{Conditional Compilation}.
16379
16380 @menu
16381 * Preprocessing Symbols::
16382 * Using gnatprep::
16383 * Switches for gnatprep::
16384 * Form of Definitions File::
16385 * Form of Input Text for gnatprep::
16386 @end menu
16387
16388 @node Preprocessing Symbols
16389 @section Preprocessing Symbols
16390
16391 @noindent
16392 Preprocessing symbols are defined in definition files and referred to in
16393 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16394 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16395 all characters need to be in the ASCII set (no accented letters).
16396
16397 @node Using gnatprep
16398 @section Using @code{gnatprep}
16399
16400 @noindent
16401 To call @code{gnatprep} use
16402
16403 @smallexample
16404 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16405 @c Expanding @ovar macro inline (explanation in macro def comments)
16406 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16407 @end smallexample
16408
16409 @noindent
16410 where
16411 @table @var
16412 @item switches
16413 is an optional sequence of switches as described in the next section.
16414
16415 @item infile
16416 is the full name of the input file, which is an Ada source
16417 file containing preprocessor directives.
16418
16419 @item outfile
16420 is the full name of the output file, which is an Ada source
16421 in standard Ada form. When used with GNAT, this file name will
16422 normally have an ads or adb suffix.
16423
16424 @item deffile
16425 is the full name of a text file containing definitions of
16426 preprocessing symbols to be referenced by the preprocessor. This argument is
16427 optional, and can be replaced by the use of the @option{-D} switch.
16428
16429 @end table
16430
16431 @node Switches for gnatprep
16432 @section Switches for @code{gnatprep}
16433
16434 @table @option
16435 @c !sort!
16436
16437 @item ^-b^/BLANK_LINES^
16438 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16439 Causes both preprocessor lines and the lines deleted by
16440 preprocessing to be replaced by blank lines in the output source file,
16441 preserving line numbers in the output file.
16442
16443 @item ^-c^/COMMENTS^
16444 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16445 Causes both preprocessor lines and the lines deleted
16446 by preprocessing to be retained in the output source as comments marked
16447 with the special string @code{"--! "}. This option will result in line numbers
16448 being preserved in the output file.
16449
16450 @item ^-C^/REPLACE_IN_COMMENTS^
16451 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16452 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16453 If this option is specified, then comments are scanned and any $symbol
16454 substitutions performed as in program text. This is particularly useful
16455 when structured comments are used (e.g., when writing programs in the
16456 SPARK dialect of Ada). Note that this switch is not available when
16457 doing integrated preprocessing (it would be useless in this context
16458 since comments are ignored by the compiler in any case).
16459
16460 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16461 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16462 Defines a new preprocessing symbol, associated with value. If no value is given
16463 on the command line, then symbol is considered to be @code{True}. This switch
16464 can be used in place of a definition file.
16465
16466 @ifset vms
16467 @item /REMOVE
16468 @cindex @option{/REMOVE} (@command{gnatprep})
16469 This is the default setting which causes lines deleted by preprocessing
16470 to be entirely removed from the output file.
16471 @end ifset
16472
16473 @item ^-r^/REFERENCE^
16474 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16475 Causes a @code{Source_Reference} pragma to be generated that
16476 references the original input file, so that error messages will use
16477 the file name of this original file. The use of this switch implies
16478 that preprocessor lines are not to be removed from the file, so its
16479 use will force @option{^-b^/BLANK_LINES^} mode if
16480 @option{^-c^/COMMENTS^}
16481 has not been specified explicitly.
16482
16483 Note that if the file to be preprocessed contains multiple units, then
16484 it will be necessary to @code{gnatchop} the output file from
16485 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16486 in the preprocessed file, it will be respected by
16487 @code{gnatchop ^-r^/REFERENCE^}
16488 so that the final chopped files will correctly refer to the original
16489 input source file for @code{gnatprep}.
16490
16491 @item ^-s^/SYMBOLS^
16492 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16493 Causes a sorted list of symbol names and values to be
16494 listed on the standard output file.
16495
16496 @item ^-u^/UNDEFINED^
16497 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16498 Causes undefined symbols to be treated as having the value FALSE in the context
16499 of a preprocessor test. In the absence of this option, an undefined symbol in
16500 a @code{#if} or @code{#elsif} test will be treated as an error.
16501
16502 @end table
16503
16504 @ifclear vms
16505 @noindent
16506 Note: if neither @option{-b} nor @option{-c} is present,
16507 then preprocessor lines and
16508 deleted lines are completely removed from the output, unless -r is
16509 specified, in which case -b is assumed.
16510 @end ifclear
16511
16512 @node Form of Definitions File
16513 @section Form of Definitions File
16514
16515 @noindent
16516 The definitions file contains lines of the form
16517
16518 @smallexample
16519 symbol := value
16520 @end smallexample
16521
16522 @noindent
16523 where symbol is a preprocessing symbol, and value is one of the following:
16524
16525 @itemize @bullet
16526 @item
16527 Empty, corresponding to a null substitution
16528 @item
16529 A string literal using normal Ada syntax
16530 @item
16531 Any sequence of characters from the set
16532 (letters, digits, period, underline).
16533 @end itemize
16534
16535 @noindent
16536 Comment lines may also appear in the definitions file, starting with
16537 the usual @code{--},
16538 and comments may be added to the definitions lines.
16539
16540 @node Form of Input Text for gnatprep
16541 @section Form of Input Text for @code{gnatprep}
16542
16543 @noindent
16544 The input text may contain preprocessor conditional inclusion lines,
16545 as well as general symbol substitution sequences.
16546
16547 The preprocessor conditional inclusion commands have the form
16548
16549 @smallexample
16550 @group
16551 @cartouche
16552 #if @i{expression} @r{[}then@r{]}
16553 lines
16554 #elsif @i{expression} @r{[}then@r{]}
16555 lines
16556 #elsif @i{expression} @r{[}then@r{]}
16557 lines
16558 @dots{}
16559 #else
16560 lines
16561 #end if;
16562 @end cartouche
16563 @end group
16564 @end smallexample
16565
16566 @noindent
16567 In this example, @i{expression} is defined by the following grammar:
16568 @smallexample
16569 @i{expression} ::= <symbol>
16570 @i{expression} ::= <symbol> = "<value>"
16571 @i{expression} ::= <symbol> = <symbol>
16572 @i{expression} ::= <symbol> 'Defined
16573 @i{expression} ::= not @i{expression}
16574 @i{expression} ::= @i{expression} and @i{expression}
16575 @i{expression} ::= @i{expression} or @i{expression}
16576 @i{expression} ::= @i{expression} and then @i{expression}
16577 @i{expression} ::= @i{expression} or else @i{expression}
16578 @i{expression} ::= ( @i{expression} )
16579 @end smallexample
16580
16581 The following restriction exists: it is not allowed to have "and" or "or"
16582 following "not" in the same expression without parentheses. For example, this
16583 is not allowed:
16584
16585 @smallexample
16586 not X or Y
16587 @end smallexample
16588
16589 This should be one of the following:
16590
16591 @smallexample
16592 (not X) or Y
16593 not (X or Y)
16594 @end smallexample
16595
16596 @noindent
16597 For the first test (@i{expression} ::= <symbol>) the symbol must have
16598 either the value true or false, that is to say the right-hand of the
16599 symbol definition must be one of the (case-insensitive) literals
16600 @code{True} or @code{False}. If the value is true, then the
16601 corresponding lines are included, and if the value is false, they are
16602 excluded.
16603
16604 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16605 the symbol has been defined in the definition file or by a @option{-D}
16606 switch on the command line. Otherwise, the test is false.
16607
16608 The equality tests are case insensitive, as are all the preprocessor lines.
16609
16610 If the symbol referenced is not defined in the symbol definitions file,
16611 then the effect depends on whether or not switch @option{-u}
16612 is specified. If so, then the symbol is treated as if it had the value
16613 false and the test fails. If this switch is not specified, then
16614 it is an error to reference an undefined symbol. It is also an error to
16615 reference a symbol that is defined with a value other than @code{True}
16616 or @code{False}.
16617
16618 The use of the @code{not} operator inverts the sense of this logical test.
16619 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16620 operators, without parentheses. For example, "if not X or Y then" is not
16621 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16622
16623 The @code{then} keyword is optional as shown
16624
16625 The @code{#} must be the first non-blank character on a line, but
16626 otherwise the format is free form. Spaces or tabs may appear between
16627 the @code{#} and the keyword. The keywords and the symbols are case
16628 insensitive as in normal Ada code. Comments may be used on a
16629 preprocessor line, but other than that, no other tokens may appear on a
16630 preprocessor line. Any number of @code{elsif} clauses can be present,
16631 including none at all. The @code{else} is optional, as in Ada.
16632
16633 The @code{#} marking the start of a preprocessor line must be the first
16634 non-blank character on the line, i.e., it must be preceded only by
16635 spaces or horizontal tabs.
16636
16637 Symbol substitution outside of preprocessor lines is obtained by using
16638 the sequence
16639
16640 @smallexample
16641 $symbol
16642 @end smallexample
16643
16644 @noindent
16645 anywhere within a source line, except in a comment or within a
16646 string literal. The identifier
16647 following the @code{$} must match one of the symbols defined in the symbol
16648 definition file, and the result is to substitute the value of the
16649 symbol in place of @code{$symbol} in the output file.
16650
16651 Note that although the substitution of strings within a string literal
16652 is not possible, it is possible to have a symbol whose defined value is
16653 a string literal. So instead of setting XYZ to @code{hello} and writing:
16654
16655 @smallexample
16656 Header : String := "$XYZ";
16657 @end smallexample
16658
16659 @noindent
16660 you should set XYZ to @code{"hello"} and write:
16661
16662 @smallexample
16663 Header : String := $XYZ;
16664 @end smallexample
16665
16666 @noindent
16667 and then the substitution will occur as desired.
16668
16669 @node The GNAT Library Browser gnatls
16670 @chapter The GNAT Library Browser @code{gnatls}
16671 @findex gnatls
16672 @cindex Library browser
16673
16674 @noindent
16675 @code{gnatls} is a tool that outputs information about compiled
16676 units. It gives the relationship between objects, unit names and source
16677 files. It can also be used to check the source dependencies of a unit
16678 as well as various characteristics.
16679
16680 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16681 driver (see @ref{The GNAT Driver and Project Files}).
16682
16683 @menu
16684 * Running gnatls::
16685 * Switches for gnatls::
16686 * Examples of gnatls Usage::
16687 @end menu
16688
16689 @node Running gnatls
16690 @section Running @code{gnatls}
16691
16692 @noindent
16693 The @code{gnatls} command has the form
16694
16695 @smallexample
16696 $ gnatls switches @var{object_or_ali_file}
16697 @end smallexample
16698
16699 @noindent
16700 The main argument is the list of object or @file{ali} files
16701 (@pxref{The Ada Library Information Files})
16702 for which information is requested.
16703
16704 In normal mode, without additional option, @code{gnatls} produces a
16705 four-column listing. Each line represents information for a specific
16706 object. The first column gives the full path of the object, the second
16707 column gives the name of the principal unit in this object, the third
16708 column gives the status of the source and the fourth column gives the
16709 full path of the source representing this unit.
16710 Here is a simple example of use:
16711
16712 @smallexample
16713 $ gnatls *.o
16714 ^./^[]^demo1.o demo1 DIF demo1.adb
16715 ^./^[]^demo2.o demo2 OK demo2.adb
16716 ^./^[]^hello.o h1 OK hello.adb
16717 ^./^[]^instr-child.o instr.child MOK instr-child.adb
16718 ^./^[]^instr.o instr OK instr.adb
16719 ^./^[]^tef.o tef DIF tef.adb
16720 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
16721 ^./^[]^tgef.o tgef DIF tgef.adb
16722 @end smallexample
16723
16724 @noindent
16725 The first line can be interpreted as follows: the main unit which is
16726 contained in
16727 object file @file{demo1.o} is demo1, whose main source is in
16728 @file{demo1.adb}. Furthermore, the version of the source used for the
16729 compilation of demo1 has been modified (DIF). Each source file has a status
16730 qualifier which can be:
16731
16732 @table @code
16733 @item OK (unchanged)
16734 The version of the source file used for the compilation of the
16735 specified unit corresponds exactly to the actual source file.
16736
16737 @item MOK (slightly modified)
16738 The version of the source file used for the compilation of the
16739 specified unit differs from the actual source file but not enough to
16740 require recompilation. If you use gnatmake with the qualifier
16741 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16742 MOK will not be recompiled.
16743
16744 @item DIF (modified)
16745 No version of the source found on the path corresponds to the source
16746 used to build this object.
16747
16748 @item ??? (file not found)
16749 No source file was found for this unit.
16750
16751 @item HID (hidden, unchanged version not first on PATH)
16752 The version of the source that corresponds exactly to the source used
16753 for compilation has been found on the path but it is hidden by another
16754 version of the same source that has been modified.
16755
16756 @end table
16757
16758 @node Switches for gnatls
16759 @section Switches for @code{gnatls}
16760
16761 @noindent
16762 @code{gnatls} recognizes the following switches:
16763
16764 @table @option
16765 @c !sort!
16766 @cindex @option{--version} @command{gnatls}
16767 Display Copyright and version, then exit disregarding all other options.
16768
16769 @item --help
16770 @cindex @option{--help} @command{gnatls}
16771 If @option{--version} was not used, display usage, then exit disregarding
16772 all other options.
16773
16774 @item ^-a^/ALL_UNITS^
16775 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16776 Consider all units, including those of the predefined Ada library.
16777 Especially useful with @option{^-d^/DEPENDENCIES^}.
16778
16779 @item ^-d^/DEPENDENCIES^
16780 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16781 List sources from which specified units depend on.
16782
16783 @item ^-h^/OUTPUT=OPTIONS^
16784 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16785 Output the list of options.
16786
16787 @item ^-o^/OUTPUT=OBJECTS^
16788 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16789 Only output information about object files.
16790
16791 @item ^-s^/OUTPUT=SOURCES^
16792 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16793 Only output information about source files.
16794
16795 @item ^-u^/OUTPUT=UNITS^
16796 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16797 Only output information about compilation units.
16798
16799 @item ^-files^/FILES^=@var{file}
16800 @cindex @option{^-files^/FILES^} (@code{gnatls})
16801 Take as arguments the files listed in text file @var{file}.
16802 Text file @var{file} may contain empty lines that are ignored.
16803 Each nonempty line should contain the name of an existing file.
16804 Several such switches may be specified simultaneously.
16805
16806 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16807 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16808 @itemx ^-I^/SEARCH=^@var{dir}
16809 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16810 @itemx -nostdinc
16811 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16812 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16813 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16814 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16815 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16816 flags (@pxref{Switches for gnatmake}).
16817
16818 @item --RTS=@var{rts-path}
16819 @cindex @option{--RTS} (@code{gnatls})
16820 Specifies the default location of the runtime library. Same meaning as the
16821 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16822
16823 @item ^-v^/OUTPUT=VERBOSE^
16824 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16825 Verbose mode. Output the complete source, object and project paths. Do not use
16826 the default column layout but instead use long format giving as much as
16827 information possible on each requested units, including special
16828 characteristics such as:
16829
16830 @table @code
16831 @item Preelaborable
16832 The unit is preelaborable in the Ada sense.
16833
16834 @item No_Elab_Code
16835 No elaboration code has been produced by the compiler for this unit.
16836
16837 @item Pure
16838 The unit is pure in the Ada sense.
16839
16840 @item Elaborate_Body
16841 The unit contains a pragma Elaborate_Body.
16842
16843 @item Remote_Types
16844 The unit contains a pragma Remote_Types.
16845
16846 @item Shared_Passive
16847 The unit contains a pragma Shared_Passive.
16848
16849 @item Predefined
16850 This unit is part of the predefined environment and cannot be modified
16851 by the user.
16852
16853 @item Remote_Call_Interface
16854 The unit contains a pragma Remote_Call_Interface.
16855
16856 @end table
16857
16858 @end table
16859
16860 @node Examples of gnatls Usage
16861 @section Example of @code{gnatls} Usage
16862 @ifclear vms
16863
16864 @noindent
16865 Example of using the verbose switch. Note how the source and
16866 object paths are affected by the -I switch.
16867
16868 @smallexample
16869 $ gnatls -v -I.. demo1.o
16870
16871 GNATLS 5.03w (20041123-34)
16872 Copyright 1997-2004 Free Software Foundation, Inc.
16873
16874 Source Search Path:
16875 <Current_Directory>
16876 ../
16877 /home/comar/local/adainclude/
16878
16879 Object Search Path:
16880 <Current_Directory>
16881 ../
16882 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16883
16884 Project Search Path:
16885 <Current_Directory>
16886 /home/comar/local/lib/gnat/
16887
16888 ./demo1.o
16889 Unit =>
16890 Name => demo1
16891 Kind => subprogram body
16892 Flags => No_Elab_Code
16893 Source => demo1.adb modified
16894 @end smallexample
16895
16896 @noindent
16897 The following is an example of use of the dependency list.
16898 Note the use of the -s switch
16899 which gives a straight list of source files. This can be useful for
16900 building specialized scripts.
16901
16902 @smallexample
16903 $ gnatls -d demo2.o
16904 ./demo2.o demo2 OK demo2.adb
16905 OK gen_list.ads
16906 OK gen_list.adb
16907 OK instr.ads
16908 OK instr-child.ads
16909
16910 $ gnatls -d -s -a demo1.o
16911 demo1.adb
16912 /home/comar/local/adainclude/ada.ads
16913 /home/comar/local/adainclude/a-finali.ads
16914 /home/comar/local/adainclude/a-filico.ads
16915 /home/comar/local/adainclude/a-stream.ads
16916 /home/comar/local/adainclude/a-tags.ads
16917 gen_list.ads
16918 gen_list.adb
16919 /home/comar/local/adainclude/gnat.ads
16920 /home/comar/local/adainclude/g-io.ads
16921 instr.ads
16922 /home/comar/local/adainclude/system.ads
16923 /home/comar/local/adainclude/s-exctab.ads
16924 /home/comar/local/adainclude/s-finimp.ads
16925 /home/comar/local/adainclude/s-finroo.ads
16926 /home/comar/local/adainclude/s-secsta.ads
16927 /home/comar/local/adainclude/s-stalib.ads
16928 /home/comar/local/adainclude/s-stoele.ads
16929 /home/comar/local/adainclude/s-stratt.ads
16930 /home/comar/local/adainclude/s-tasoli.ads
16931 /home/comar/local/adainclude/s-unstyp.ads
16932 /home/comar/local/adainclude/unchconv.ads
16933 @end smallexample
16934 @end ifclear
16935
16936 @ifset vms
16937 @smallexample
16938 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16939
16940 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16941 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16942 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16943 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16944 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16945 demo1.adb
16946 gen_list.ads
16947 gen_list.adb
16948 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16949 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16950 instr.ads
16951 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16952 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16953 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16954 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16955 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16956 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16957 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16958 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16959 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16960 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16961 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16962 @end smallexample
16963 @end ifset
16964
16965 @node Cleaning Up Using gnatclean
16966 @chapter Cleaning Up Using @code{gnatclean}
16967 @findex gnatclean
16968 @cindex Cleaning tool
16969
16970 @noindent
16971 @code{gnatclean} is a tool that allows the deletion of files produced by the
16972 compiler, binder and linker, including ALI files, object files, tree files,
16973 expanded source files, library files, interface copy source files, binder
16974 generated files and executable files.
16975
16976 @menu
16977 * Running gnatclean::
16978 * Switches for gnatclean::
16979 @c * Examples of gnatclean Usage::
16980 @end menu
16981
16982 @node Running gnatclean
16983 @section Running @code{gnatclean}
16984
16985 @noindent
16986 The @code{gnatclean} command has the form:
16987
16988 @smallexample
16989 $ gnatclean switches @var{names}
16990 @end smallexample
16991
16992 @noindent
16993 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16994 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16995 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16996
16997 @noindent
16998 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16999 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17000 the linker. In informative-only mode, specified by switch
17001 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17002 normal mode is listed, but no file is actually deleted.
17003
17004 @node Switches for gnatclean
17005 @section Switches for @code{gnatclean}
17006
17007 @noindent
17008 @code{gnatclean} recognizes the following switches:
17009
17010 @table @option
17011 @c !sort!
17012 @cindex @option{--version} @command{gnatclean}
17013 Display Copyright and version, then exit disregarding all other options.
17014
17015 @item --help
17016 @cindex @option{--help} @command{gnatclean}
17017 If @option{--version} was not used, display usage, then exit disregarding
17018 all other options.
17019
17020 @item ^--subdirs^/SUBDIRS^=subdir
17021 Actual object directory of each project file is the subdirectory subdir of the
17022 object directory specified or defaulted in the project file.
17023
17024 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17025 By default, shared library projects are not allowed to import static library
17026 projects. When this switch is used on the command line, this restriction is
17027 relaxed.
17028
17029 @item ^-c^/COMPILER_FILES_ONLY^
17030 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17031 Only attempt to delete the files produced by the compiler, not those produced
17032 by the binder or the linker. The files that are not to be deleted are library
17033 files, interface copy files, binder generated files and executable files.
17034
17035 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17036 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17037 Indicate that ALI and object files should normally be found in directory
17038 @var{dir}.
17039
17040 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17041 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17042 When using project files, if some errors or warnings are detected during
17043 parsing and verbose mode is not in effect (no use of switch
17044 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17045 file, rather than its simple file name.
17046
17047 @item ^-h^/HELP^
17048 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17049 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17050
17051 @item ^-n^/NODELETE^
17052 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17053 Informative-only mode. Do not delete any files. Output the list of the files
17054 that would have been deleted if this switch was not specified.
17055
17056 @item ^-P^/PROJECT_FILE=^@var{project}
17057 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17058 Use project file @var{project}. Only one such switch can be used.
17059 When cleaning a project file, the files produced by the compilation of the
17060 immediate sources or inherited sources of the project files are to be
17061 deleted. This is not depending on the presence or not of executable names
17062 on the command line.
17063
17064 @item ^-q^/QUIET^
17065 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17066 Quiet output. If there are no errors, do not output anything, except in
17067 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17068 (switch ^-n^/NODELETE^).
17069
17070 @item ^-r^/RECURSIVE^
17071 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17072 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17073 clean all imported and extended project files, recursively. If this switch
17074 is not specified, only the files related to the main project file are to be
17075 deleted. This switch has no effect if no project file is specified.
17076
17077 @item ^-v^/VERBOSE^
17078 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17079 Verbose mode.
17080
17081 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17082 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17083 Indicates the verbosity of the parsing of GNAT project files.
17084 @xref{Switches Related to Project Files}.
17085
17086 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17087 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17088 Indicates that external variable @var{name} has the value @var{value}.
17089 The Project Manager will use this value for occurrences of
17090 @code{external(name)} when parsing the project file.
17091 @xref{Switches Related to Project Files}.
17092
17093 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17094 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17095 When searching for ALI and object files, look in directory
17096 @var{dir}.
17097
17098 @item ^-I^/SEARCH=^@var{dir}
17099 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17100 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17101
17102 @item ^-I-^/NOCURRENT_DIRECTORY^
17103 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17104 @cindex Source files, suppressing search
17105 Do not look for ALI or object files in the directory
17106 where @code{gnatclean} was invoked.
17107
17108 @end table
17109
17110 @c @node Examples of gnatclean Usage
17111 @c @section Examples of @code{gnatclean} Usage
17112
17113 @ifclear vms
17114 @node GNAT and Libraries
17115 @chapter GNAT and Libraries
17116 @cindex Library, building, installing, using
17117
17118 @noindent
17119 This chapter describes how to build and use libraries with GNAT, and also shows
17120 how to recompile the GNAT run-time library. You should be familiar with the
17121 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17122 chapter.
17123
17124 @menu
17125 * Introduction to Libraries in GNAT::
17126 * General Ada Libraries::
17127 * Stand-alone Ada Libraries::
17128 * Rebuilding the GNAT Run-Time Library::
17129 @end menu
17130
17131 @node Introduction to Libraries in GNAT
17132 @section Introduction to Libraries in GNAT
17133
17134 @noindent
17135 A library is, conceptually, a collection of objects which does not have its
17136 own main thread of execution, but rather provides certain services to the
17137 applications that use it. A library can be either statically linked with the
17138 application, in which case its code is directly included in the application,
17139 or, on platforms that support it, be dynamically linked, in which case
17140 its code is shared by all applications making use of this library.
17141
17142 GNAT supports both types of libraries.
17143 In the static case, the compiled code can be provided in different ways. The
17144 simplest approach is to provide directly the set of objects resulting from
17145 compilation of the library source files. Alternatively, you can group the
17146 objects into an archive using whatever commands are provided by the operating
17147 system. For the latter case, the objects are grouped into a shared library.
17148
17149 In the GNAT environment, a library has three types of components:
17150 @itemize @bullet
17151 @item
17152 Source files.
17153 @item
17154 @file{ALI} files.
17155 @xref{The Ada Library Information Files}.
17156 @item
17157 Object files, an archive or a shared library.
17158 @end itemize
17159
17160 @noindent
17161 A GNAT library may expose all its source files, which is useful for
17162 documentation purposes. Alternatively, it may expose only the units needed by
17163 an external user to make use of the library. That is to say, the specs
17164 reflecting the library services along with all the units needed to compile
17165 those specs, which can include generic bodies or any body implementing an
17166 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17167 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17168
17169 All compilation units comprising an application, including those in a library,
17170 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17171 computes the elaboration order from the @file{ALI} files and this is why they
17172 constitute a mandatory part of GNAT libraries.
17173 @emph{Stand-alone libraries} are the exception to this rule because a specific
17174 library elaboration routine is produced independently of the application(s)
17175 using the library.
17176
17177 @node General Ada Libraries
17178 @section General Ada Libraries
17179
17180 @menu
17181 * Building a library::
17182 * Installing a library::
17183 * Using a library::
17184 @end menu
17185
17186 @node Building a library
17187 @subsection Building a library
17188
17189 @noindent
17190 The easiest way to build a library is to use the Project Manager,
17191 which supports a special type of project called a @emph{Library Project}
17192 (@pxref{Library Projects}).
17193
17194 A project is considered a library project, when two project-level attributes
17195 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17196 control different aspects of library configuration, additional optional
17197 project-level attributes can be specified:
17198 @table @code
17199 @item Library_Kind
17200 This attribute controls whether the library is to be static or dynamic
17201
17202 @item Library_Version
17203 This attribute specifies the library version; this value is used
17204 during dynamic linking of shared libraries to determine if the currently
17205 installed versions of the binaries are compatible.
17206
17207 @item Library_Options
17208 @item Library_GCC
17209 These attributes specify additional low-level options to be used during
17210 library generation, and redefine the actual application used to generate
17211 library.
17212 @end table
17213
17214 @noindent
17215 The GNAT Project Manager takes full care of the library maintenance task,
17216 including recompilation of the source files for which objects do not exist
17217 or are not up to date, assembly of the library archive, and installation of
17218 the library (i.e., copying associated source, object and @file{ALI} files
17219 to the specified location).
17220
17221 Here is a simple library project file:
17222 @smallexample @c ada
17223 project My_Lib is
17224 for Source_Dirs use ("src1", "src2");
17225 for Object_Dir use "obj";
17226 for Library_Name use "mylib";
17227 for Library_Dir use "lib";
17228 for Library_Kind use "dynamic";
17229 end My_lib;
17230 @end smallexample
17231
17232 @noindent
17233 and the compilation command to build and install the library:
17234
17235 @smallexample @c ada
17236 $ gnatmake -Pmy_lib
17237 @end smallexample
17238
17239 @noindent
17240 It is not entirely trivial to perform manually all the steps required to
17241 produce a library. We recommend that you use the GNAT Project Manager
17242 for this task. In special cases where this is not desired, the necessary
17243 steps are discussed below.
17244
17245 There are various possibilities for compiling the units that make up the
17246 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17247 with a conventional script. For simple libraries, it is also possible to create
17248 a dummy main program which depends upon all the packages that comprise the
17249 interface of the library. This dummy main program can then be given to
17250 @command{gnatmake}, which will ensure that all necessary objects are built.
17251
17252 After this task is accomplished, you should follow the standard procedure
17253 of the underlying operating system to produce the static or shared library.
17254
17255 Here is an example of such a dummy program:
17256 @smallexample @c ada
17257 @group
17258 with My_Lib.Service1;
17259 with My_Lib.Service2;
17260 with My_Lib.Service3;
17261 procedure My_Lib_Dummy is
17262 begin
17263 null;
17264 end;
17265 @end group
17266 @end smallexample
17267
17268 @noindent
17269 Here are the generic commands that will build an archive or a shared library.
17270
17271 @smallexample
17272 # compiling the library
17273 $ gnatmake -c my_lib_dummy.adb
17274
17275 # we don't need the dummy object itself
17276 $ rm my_lib_dummy.o my_lib_dummy.ali
17277
17278 # create an archive with the remaining objects
17279 $ ar rc libmy_lib.a *.o
17280 # some systems may require "ranlib" to be run as well
17281
17282 # or create a shared library
17283 $ gcc -shared -o libmy_lib.so *.o
17284 # some systems may require the code to have been compiled with -fPIC
17285
17286 # remove the object files that are now in the library
17287 $ rm *.o
17288
17289 # Make the ALI files read-only so that gnatmake will not try to
17290 # regenerate the objects that are in the library
17291 $ chmod -w *.ali
17292 @end smallexample
17293
17294 @noindent
17295 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17296 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17297 be accessed by the directive @option{-l@var{xxx}} at link time.
17298
17299 @node Installing a library
17300 @subsection Installing a library
17301 @cindex @code{ADA_PROJECT_PATH}
17302 @cindex @code{GPR_PROJECT_PATH}
17303
17304 @noindent
17305 If you use project files, library installation is part of the library build
17306 process (@pxref{Installing a library with project files}).
17307
17308 When project files are not an option, it is also possible, but not recommended,
17309 to install the library so that the sources needed to use the library are on the
17310 Ada source path and the ALI files & libraries be on the Ada Object path (see
17311 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17312 administrator can place general-purpose libraries in the default compiler
17313 paths, by specifying the libraries' location in the configuration files
17314 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17315 must be located in the GNAT installation tree at the same place as the gcc spec
17316 file. The location of the gcc spec file can be determined as follows:
17317 @smallexample
17318 $ gcc -v
17319 @end smallexample
17320
17321 @noindent
17322 The configuration files mentioned above have a simple format: each line
17323 must contain one unique directory name.
17324 Those names are added to the corresponding path
17325 in their order of appearance in the file. The names can be either absolute
17326 or relative; in the latter case, they are relative to where theses files
17327 are located.
17328
17329 The files @file{ada_source_path} and @file{ada_object_path} might not be
17330 present in a
17331 GNAT installation, in which case, GNAT will look for its run-time library in
17332 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17333 objects and @file{ALI} files). When the files exist, the compiler does not
17334 look in @file{adainclude} and @file{adalib}, and thus the
17335 @file{ada_source_path} file
17336 must contain the location for the GNAT run-time sources (which can simply
17337 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17338 contain the location for the GNAT run-time objects (which can simply
17339 be @file{adalib}).
17340
17341 You can also specify a new default path to the run-time library at compilation
17342 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17343 the run-time library you want your program to be compiled with. This switch is
17344 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17345 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17346
17347 It is possible to install a library before or after the standard GNAT
17348 library, by reordering the lines in the configuration files. In general, a
17349 library must be installed before the GNAT library if it redefines
17350 any part of it.
17351
17352 @node Using a library
17353 @subsection Using a library
17354
17355 @noindent Once again, the project facility greatly simplifies the use of
17356 libraries. In this context, using a library is just a matter of adding a
17357 @code{with} clause in the user project. For instance, to make use of the
17358 library @code{My_Lib} shown in examples in earlier sections, you can
17359 write:
17360
17361 @smallexample @c projectfile
17362 with "my_lib";
17363 project My_Proj is
17364 @dots{}
17365 end My_Proj;
17366 @end smallexample
17367
17368 Even if you have a third-party, non-Ada library, you can still use GNAT's
17369 Project Manager facility to provide a wrapper for it. For example, the
17370 following project, when @code{with}ed by your main project, will link with the
17371 third-party library @file{liba.a}:
17372
17373 @smallexample @c projectfile
17374 @group
17375 project Liba is
17376 for Externally_Built use "true";
17377 for Source_Files use ();
17378 for Library_Dir use "lib";
17379 for Library_Name use "a";
17380 for Library_Kind use "static";
17381 end Liba;
17382 @end group
17383 @end smallexample
17384 This is an alternative to the use of @code{pragma Linker_Options}. It is
17385 especially interesting in the context of systems with several interdependent
17386 static libraries where finding a proper linker order is not easy and best be
17387 left to the tools having visibility over project dependence information.
17388
17389 @noindent
17390 In order to use an Ada library manually, you need to make sure that this
17391 library is on both your source and object path
17392 (see @ref{Search Paths and the Run-Time Library (RTL)}
17393 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17394 in an archive or a shared library, you need to specify the desired
17395 library at link time.
17396
17397 For example, you can use the library @file{mylib} installed in
17398 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17399
17400 @smallexample
17401 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17402 -largs -lmy_lib
17403 @end smallexample
17404
17405 @noindent
17406 This can be expressed more simply:
17407 @smallexample
17408 $ gnatmake my_appl
17409 @end smallexample
17410 @noindent
17411 when the following conditions are met:
17412 @itemize @bullet
17413 @item
17414 @file{/dir/my_lib_src} has been added by the user to the environment
17415 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17416 @file{ada_source_path}
17417 @item
17418 @file{/dir/my_lib_obj} has been added by the user to the environment
17419 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17420 @file{ada_object_path}
17421 @item
17422 a pragma @code{Linker_Options} has been added to one of the sources.
17423 For example:
17424
17425 @smallexample @c ada
17426 pragma Linker_Options ("-lmy_lib");
17427 @end smallexample
17428 @end itemize
17429
17430 @node Stand-alone Ada Libraries
17431 @section Stand-alone Ada Libraries
17432 @cindex Stand-alone library, building, using
17433
17434 @menu
17435 * Introduction to Stand-alone Libraries::
17436 * Building a Stand-alone Library::
17437 * Creating a Stand-alone Library to be used in a non-Ada context::
17438 * Restrictions in Stand-alone Libraries::
17439 @end menu
17440
17441 @node Introduction to Stand-alone Libraries
17442 @subsection Introduction to Stand-alone Libraries
17443
17444 @noindent
17445 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17446 necessary code to
17447 elaborate the Ada units that are included in the library. In contrast with
17448 an ordinary library, which consists of all sources, objects and @file{ALI}
17449 files of the
17450 library, a SAL may specify a restricted subset of compilation units
17451 to serve as a library interface. In this case, the fully
17452 self-sufficient set of files will normally consist of an objects
17453 archive, the sources of interface units' specs, and the @file{ALI}
17454 files of interface units.
17455 If an interface spec contains a generic unit or an inlined subprogram,
17456 the body's
17457 source must also be provided; if the units that must be provided in the source
17458 form depend on other units, the source and @file{ALI} files of those must
17459 also be provided.
17460
17461 The main purpose of a SAL is to minimize the recompilation overhead of client
17462 applications when a new version of the library is installed. Specifically,
17463 if the interface sources have not changed, client applications do not need to
17464 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17465 version, controlled by @code{Library_Version} attribute, is not changed,
17466 then the clients do not need to be relinked.
17467
17468 SALs also allow the library providers to minimize the amount of library source
17469 text exposed to the clients. Such ``information hiding'' might be useful or
17470 necessary for various reasons.
17471
17472 Stand-alone libraries are also well suited to be used in an executable whose
17473 main routine is not written in Ada.
17474
17475 @node Building a Stand-alone Library
17476 @subsection Building a Stand-alone Library
17477
17478 @noindent
17479 GNAT's Project facility provides a simple way of building and installing
17480 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17481 To be a Stand-alone Library Project, in addition to the two attributes
17482 that make a project a Library Project (@code{Library_Name} and
17483 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17484 @code{Library_Interface} must be defined. For example:
17485
17486 @smallexample @c projectfile
17487 @group
17488 for Library_Dir use "lib_dir";
17489 for Library_Name use "dummy";
17490 for Library_Interface use ("int1", "int1.child");
17491 @end group
17492 @end smallexample
17493
17494 @noindent
17495 Attribute @code{Library_Interface} has a non-empty string list value,
17496 each string in the list designating a unit contained in an immediate source
17497 of the project file.
17498
17499 When a Stand-alone Library is built, first the binder is invoked to build
17500 a package whose name depends on the library name
17501 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17502 This binder-generated package includes initialization and
17503 finalization procedures whose
17504 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17505 in the example
17506 above). The object corresponding to this package is included in the library.
17507
17508 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17509 calling of these procedures if a static SAL is built, or if a shared SAL
17510 is built
17511 with the project-level attribute @code{Library_Auto_Init} set to
17512 @code{"false"}.
17513
17514 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17515 (those that are listed in attribute @code{Library_Interface}) are copied to
17516 the Library Directory. As a consequence, only the Interface Units may be
17517 imported from Ada units outside of the library. If other units are imported,
17518 the binding phase will fail.
17519
17520 @noindent
17521 It is also possible to build an encapsulated library where not only
17522 the code to elaborate and finalize the library is embedded but also
17523 ensuring that the library is linked only against static
17524 libraries. So an encapsulated library only depends on system
17525 libraries, all other code, including the GNAT runtime, is embedded. To
17526 build an encapsulated library the attribute
17527 @code{Library_Standalone} must be set to @code{encapsulated}:
17528
17529 @smallexample @c projectfile
17530 @group
17531 for Library_Dir use "lib_dir";
17532 for Library_Name use "dummy";
17533 for Library_Interface use ("int1", "int1.child");
17534 for Library_Standalone use "encapsulated";
17535 @end group
17536 @end smallexample
17537
17538 @noindent
17539 The default value for this attribute is @code{standard} in which case
17540 a stand-alone library is built.
17541
17542 The attribute @code{Library_Src_Dir} may be specified for a
17543 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17544 single string value. Its value must be the path (absolute or relative to the
17545 project directory) of an existing directory. This directory cannot be the
17546 object directory or one of the source directories, but it can be the same as
17547 the library directory. The sources of the Interface
17548 Units of the library that are needed by an Ada client of the library will be
17549 copied to the designated directory, called the Interface Copy directory.
17550 These sources include the specs of the Interface Units, but they may also
17551 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17552 are used, or when there is a generic unit in the spec. Before the sources
17553 are copied to the Interface Copy directory, an attempt is made to delete all
17554 files in the Interface Copy directory.
17555
17556 Building stand-alone libraries by hand is somewhat tedious, but for those
17557 occasions when it is necessary here are the steps that you need to perform:
17558 @itemize @bullet
17559 @item
17560 Compile all library sources.
17561
17562 @item
17563 Invoke the binder with the switch @option{-n} (No Ada main program),
17564 with all the @file{ALI} files of the interfaces, and
17565 with the switch @option{-L} to give specific names to the @code{init}
17566 and @code{final} procedures. For example:
17567 @smallexample
17568 gnatbind -n int1.ali int2.ali -Lsal1
17569 @end smallexample
17570
17571 @item
17572 Compile the binder generated file:
17573 @smallexample
17574 gcc -c b~int2.adb
17575 @end smallexample
17576
17577 @item
17578 Link the dynamic library with all the necessary object files,
17579 indicating to the linker the names of the @code{init} (and possibly
17580 @code{final}) procedures for automatic initialization (and finalization).
17581 The built library should be placed in a directory different from
17582 the object directory.
17583
17584 @item
17585 Copy the @code{ALI} files of the interface to the library directory,
17586 add in this copy an indication that it is an interface to a SAL
17587 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17588 with letter ``P'') and make the modified copy of the @file{ALI} file
17589 read-only.
17590 @end itemize
17591
17592 @noindent
17593 Using SALs is not different from using other libraries
17594 (see @ref{Using a library}).
17595
17596 @node Creating a Stand-alone Library to be used in a non-Ada context
17597 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17598
17599 @noindent
17600 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17601 a non-Ada context.
17602
17603 The only extra step required is to ensure that library interface subprograms
17604 are compatible with the main program, by means of @code{pragma Export}
17605 or @code{pragma Convention}.
17606
17607 Here is an example of simple library interface for use with C main program:
17608
17609 @smallexample @c ada
17610 package My_Package is
17611
17612 procedure Do_Something;
17613 pragma Export (C, Do_Something, "do_something");
17614
17615 procedure Do_Something_Else;
17616 pragma Export (C, Do_Something_Else, "do_something_else");
17617
17618 end My_Package;
17619 @end smallexample
17620
17621 @noindent
17622 On the foreign language side, you must provide a ``foreign'' view of the
17623 library interface; remember that it should contain elaboration routines in
17624 addition to interface subprograms.
17625
17626 The example below shows the content of @code{mylib_interface.h} (note
17627 that there is no rule for the naming of this file, any name can be used)
17628 @smallexample
17629 /* the library elaboration procedure */
17630 extern void mylibinit (void);
17631
17632 /* the library finalization procedure */
17633 extern void mylibfinal (void);
17634
17635 /* the interface exported by the library */
17636 extern void do_something (void);
17637 extern void do_something_else (void);
17638 @end smallexample
17639
17640 @noindent
17641 Libraries built as explained above can be used from any program, provided
17642 that the elaboration procedures (named @code{mylibinit} in the previous
17643 example) are called before the library services are used. Any number of
17644 libraries can be used simultaneously, as long as the elaboration
17645 procedure of each library is called.
17646
17647 Below is an example of a C program that uses the @code{mylib} library.
17648
17649 @smallexample
17650 #include "mylib_interface.h"
17651
17652 int
17653 main (void)
17654 @{
17655 /* First, elaborate the library before using it */
17656 mylibinit ();
17657
17658 /* Main program, using the library exported entities */
17659 do_something ();
17660 do_something_else ();
17661
17662 /* Library finalization at the end of the program */
17663 mylibfinal ();
17664 return 0;
17665 @}
17666 @end smallexample
17667
17668 @noindent
17669 Note that invoking any library finalization procedure generated by
17670 @code{gnatbind} shuts down the Ada run-time environment.
17671 Consequently, the
17672 finalization of all Ada libraries must be performed at the end of the program.
17673 No call to these libraries or to the Ada run-time library should be made
17674 after the finalization phase.
17675
17676 @node Restrictions in Stand-alone Libraries
17677 @subsection Restrictions in Stand-alone Libraries
17678
17679 @noindent
17680 The pragmas listed below should be used with caution inside libraries,
17681 as they can create incompatibilities with other Ada libraries:
17682 @itemize @bullet
17683 @item pragma @code{Locking_Policy}
17684 @item pragma @code{Queuing_Policy}
17685 @item pragma @code{Task_Dispatching_Policy}
17686 @item pragma @code{Unreserve_All_Interrupts}
17687 @end itemize
17688
17689 @noindent
17690 When using a library that contains such pragmas, the user must make sure
17691 that all libraries use the same pragmas with the same values. Otherwise,
17692 @code{Program_Error} will
17693 be raised during the elaboration of the conflicting
17694 libraries. The usage of these pragmas and its consequences for the user
17695 should therefore be well documented.
17696
17697 Similarly, the traceback in the exception occurrence mechanism should be
17698 enabled or disabled in a consistent manner across all libraries.
17699 Otherwise, Program_Error will be raised during the elaboration of the
17700 conflicting libraries.
17701
17702 If the @code{Version} or @code{Body_Version}
17703 attributes are used inside a library, then you need to
17704 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17705 libraries, so that version identifiers can be properly computed.
17706 In practice these attributes are rarely used, so this is unlikely
17707 to be a consideration.
17708
17709 @node Rebuilding the GNAT Run-Time Library
17710 @section Rebuilding the GNAT Run-Time Library
17711 @cindex GNAT Run-Time Library, rebuilding
17712 @cindex Building the GNAT Run-Time Library
17713 @cindex Rebuilding the GNAT Run-Time Library
17714 @cindex Run-Time Library, rebuilding
17715
17716 @noindent
17717 It may be useful to recompile the GNAT library in various contexts, the
17718 most important one being the use of partition-wide configuration pragmas
17719 such as @code{Normalize_Scalars}. A special Makefile called
17720 @code{Makefile.adalib} is provided to that effect and can be found in
17721 the directory containing the GNAT library. The location of this
17722 directory depends on the way the GNAT environment has been installed and can
17723 be determined by means of the command:
17724
17725 @smallexample
17726 $ gnatls -v
17727 @end smallexample
17728
17729 @noindent
17730 The last entry in the object search path usually contains the
17731 gnat library. This Makefile contains its own documentation and in
17732 particular the set of instructions needed to rebuild a new library and
17733 to use it.
17734
17735 @node Using the GNU make Utility
17736 @chapter Using the GNU @code{make} Utility
17737 @findex make
17738
17739 @noindent
17740 This chapter offers some examples of makefiles that solve specific
17741 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17742 make, make, GNU @code{make}}), nor does it try to replace the
17743 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17744
17745 All the examples in this section are specific to the GNU version of
17746 make. Although @command{make} is a standard utility, and the basic language
17747 is the same, these examples use some advanced features found only in
17748 @code{GNU make}.
17749
17750 @menu
17751 * Using gnatmake in a Makefile::
17752 * Automatically Creating a List of Directories::
17753 * Generating the Command Line Switches::
17754 * Overcoming Command Line Length Limits::
17755 @end menu
17756
17757 @node Using gnatmake in a Makefile
17758 @section Using gnatmake in a Makefile
17759 @findex makefile
17760 @cindex GNU make
17761
17762 @noindent
17763 Complex project organizations can be handled in a very powerful way by
17764 using GNU make combined with gnatmake. For instance, here is a Makefile
17765 which allows you to build each subsystem of a big project into a separate
17766 shared library. Such a makefile allows you to significantly reduce the link
17767 time of very big applications while maintaining full coherence at
17768 each step of the build process.
17769
17770 The list of dependencies are handled automatically by
17771 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17772 the appropriate directories.
17773
17774 Note that you should also read the example on how to automatically
17775 create the list of directories
17776 (@pxref{Automatically Creating a List of Directories})
17777 which might help you in case your project has a lot of subdirectories.
17778
17779 @smallexample
17780 @iftex
17781 @leftskip=0cm
17782 @font@heightrm=cmr8
17783 @heightrm
17784 @end iftex
17785 ## This Makefile is intended to be used with the following directory
17786 ## configuration:
17787 ## - The sources are split into a series of csc (computer software components)
17788 ## Each of these csc is put in its own directory.
17789 ## Their name are referenced by the directory names.
17790 ## They will be compiled into shared library (although this would also work
17791 ## with static libraries
17792 ## - The main program (and possibly other packages that do not belong to any
17793 ## csc is put in the top level directory (where the Makefile is).
17794 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17795 ## \_ second_csc (sources) __ lib (will contain the library)
17796 ## \_ @dots{}
17797 ## Although this Makefile is build for shared library, it is easy to modify
17798 ## to build partial link objects instead (modify the lines with -shared and
17799 ## gnatlink below)
17800 ##
17801 ## With this makefile, you can change any file in the system or add any new
17802 ## file, and everything will be recompiled correctly (only the relevant shared
17803 ## objects will be recompiled, and the main program will be re-linked).
17804
17805 # The list of computer software component for your project. This might be
17806 # generated automatically.
17807 CSC_LIST=aa bb cc
17808
17809 # Name of the main program (no extension)
17810 MAIN=main
17811
17812 # If we need to build objects with -fPIC, uncomment the following line
17813 #NEED_FPIC=-fPIC
17814
17815 # The following variable should give the directory containing libgnat.so
17816 # You can get this directory through 'gnatls -v'. This is usually the last
17817 # directory in the Object_Path.
17818 GLIB=@dots{}
17819
17820 # The directories for the libraries
17821 # (This macro expands the list of CSC to the list of shared libraries, you
17822 # could simply use the expanded form:
17823 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17824 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17825
17826 $@{MAIN@}: objects $@{LIB_DIR@}
17827 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17828 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17829
17830 objects::
17831 # recompile the sources
17832 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17833
17834 # Note: In a future version of GNAT, the following commands will be simplified
17835 # by a new tool, gnatmlib
17836 $@{LIB_DIR@}:
17837 mkdir -p $@{dir $@@ @}
17838 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17839 cd $@{dir $@@ @} && cp -f ../*.ali .
17840
17841 # The dependencies for the modules
17842 # Note that we have to force the expansion of *.o, since in some cases
17843 # make won't be able to do it itself.
17844 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17845 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17846 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17847
17848 # Make sure all of the shared libraries are in the path before starting the
17849 # program
17850 run::
17851 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17852
17853 clean::
17854 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17855 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17856 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17857 $@{RM@} *.o *.ali $@{MAIN@}
17858 @end smallexample
17859
17860 @node Automatically Creating a List of Directories
17861 @section Automatically Creating a List of Directories
17862
17863 @noindent
17864 In most makefiles, you will have to specify a list of directories, and
17865 store it in a variable. For small projects, it is often easier to
17866 specify each of them by hand, since you then have full control over what
17867 is the proper order for these directories, which ones should be
17868 included.
17869
17870 However, in larger projects, which might involve hundreds of
17871 subdirectories, it might be more convenient to generate this list
17872 automatically.
17873
17874 The example below presents two methods. The first one, although less
17875 general, gives you more control over the list. It involves wildcard
17876 characters, that are automatically expanded by @command{make}. Its
17877 shortcoming is that you need to explicitly specify some of the
17878 organization of your project, such as for instance the directory tree
17879 depth, whether some directories are found in a separate tree, @enddots{}
17880
17881 The second method is the most general one. It requires an external
17882 program, called @command{find}, which is standard on all Unix systems. All
17883 the directories found under a given root directory will be added to the
17884 list.
17885
17886 @smallexample
17887 @iftex
17888 @leftskip=0cm
17889 @font@heightrm=cmr8
17890 @heightrm
17891 @end iftex
17892 # The examples below are based on the following directory hierarchy:
17893 # All the directories can contain any number of files
17894 # ROOT_DIRECTORY -> a -> aa -> aaa
17895 # -> ab
17896 # -> ac
17897 # -> b -> ba -> baa
17898 # -> bb
17899 # -> bc
17900 # This Makefile creates a variable called DIRS, that can be reused any time
17901 # you need this list (see the other examples in this section)
17902
17903 # The root of your project's directory hierarchy
17904 ROOT_DIRECTORY=.
17905
17906 ####
17907 # First method: specify explicitly the list of directories
17908 # This allows you to specify any subset of all the directories you need.
17909 ####
17910
17911 DIRS := a/aa/ a/ab/ b/ba/
17912
17913 ####
17914 # Second method: use wildcards
17915 # Note that the argument(s) to wildcard below should end with a '/'.
17916 # Since wildcards also return file names, we have to filter them out
17917 # to avoid duplicate directory names.
17918 # We thus use make's @code{dir} and @code{sort} functions.
17919 # It sets DIRs to the following value (note that the directories aaa and baa
17920 # are not given, unless you change the arguments to wildcard).
17921 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17922 ####
17923
17924 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17925 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17926
17927 ####
17928 # Third method: use an external program
17929 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17930 # This is the most complete command: it sets DIRs to the following value:
17931 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17932 ####
17933
17934 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17935
17936 @end smallexample
17937
17938 @node Generating the Command Line Switches
17939 @section Generating the Command Line Switches
17940
17941 @noindent
17942 Once you have created the list of directories as explained in the
17943 previous section (@pxref{Automatically Creating a List of Directories}),
17944 you can easily generate the command line arguments to pass to gnatmake.
17945
17946 For the sake of completeness, this example assumes that the source path
17947 is not the same as the object path, and that you have two separate lists
17948 of directories.
17949
17950 @smallexample
17951 # see "Automatically creating a list of directories" to create
17952 # these variables
17953 SOURCE_DIRS=
17954 OBJECT_DIRS=
17955
17956 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17957 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17958
17959 all:
17960 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17961 @end smallexample
17962
17963 @node Overcoming Command Line Length Limits
17964 @section Overcoming Command Line Length Limits
17965
17966 @noindent
17967 One problem that might be encountered on big projects is that many
17968 operating systems limit the length of the command line. It is thus hard to give
17969 gnatmake the list of source and object directories.
17970
17971 This example shows how you can set up environment variables, which will
17972 make @command{gnatmake} behave exactly as if the directories had been
17973 specified on the command line, but have a much higher length limit (or
17974 even none on most systems).
17975
17976 It assumes that you have created a list of directories in your Makefile,
17977 using one of the methods presented in
17978 @ref{Automatically Creating a List of Directories}.
17979 For the sake of completeness, we assume that the object
17980 path (where the ALI files are found) is different from the sources patch.
17981
17982 Note a small trick in the Makefile below: for efficiency reasons, we
17983 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17984 expanded immediately by @code{make}. This way we overcome the standard
17985 make behavior which is to expand the variables only when they are
17986 actually used.
17987
17988 On Windows, if you are using the standard Windows command shell, you must
17989 replace colons with semicolons in the assignments to these variables.
17990
17991 @smallexample
17992 @iftex
17993 @leftskip=0cm
17994 @font@heightrm=cmr8
17995 @heightrm
17996 @end iftex
17997 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17998 # This is the same thing as putting the -I arguments on the command line.
17999 # (the equivalent of using -aI on the command line would be to define
18000 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18001 # You can of course have different values for these variables.
18002 #
18003 # Note also that we need to keep the previous values of these variables, since
18004 # they might have been set before running 'make' to specify where the GNAT
18005 # library is installed.
18006
18007 # see "Automatically creating a list of directories" to create these
18008 # variables
18009 SOURCE_DIRS=
18010 OBJECT_DIRS=
18011
18012 empty:=
18013 space:=$@{empty@} $@{empty@}
18014 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18015 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18016 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18017 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18018 export ADA_INCLUDE_PATH
18019 export ADA_OBJECTS_PATH
18020
18021 all:
18022 gnatmake main_unit
18023 @end smallexample
18024 @end ifclear
18025
18026 @node Memory Management Issues
18027 @chapter Memory Management Issues
18028
18029 @noindent
18030 This chapter describes some useful memory pools provided in the GNAT library
18031 and in particular the GNAT Debug Pool facility, which can be used to detect
18032 incorrect uses of access values (including ``dangling references'').
18033 @ifclear vms
18034 It also describes the @command{gnatmem} tool, which can be used to track down
18035 ``memory leaks''.
18036 @end ifclear
18037
18038 @menu
18039 * Some Useful Memory Pools::
18040 * The GNAT Debug Pool Facility::
18041 @ifclear vms
18042 * The gnatmem Tool::
18043 @end ifclear
18044 @end menu
18045
18046 @node Some Useful Memory Pools
18047 @section Some Useful Memory Pools
18048 @findex Memory Pool
18049 @cindex storage, pool
18050
18051 @noindent
18052 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18053 storage pool. Allocations use the standard system call @code{malloc} while
18054 deallocations use the standard system call @code{free}. No reclamation is
18055 performed when the pool goes out of scope. For performance reasons, the
18056 standard default Ada allocators/deallocators do not use any explicit storage
18057 pools but if they did, they could use this storage pool without any change in
18058 behavior. That is why this storage pool is used when the user
18059 manages to make the default implicit allocator explicit as in this example:
18060 @smallexample @c ada
18061 type T1 is access Something;
18062 -- no Storage pool is defined for T2
18063 type T2 is access Something_Else;
18064 for T2'Storage_Pool use T1'Storage_Pool;
18065 -- the above is equivalent to
18066 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18067 @end smallexample
18068
18069 @noindent
18070 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18071 pool. The allocation strategy is similar to @code{Pool_Local}'s
18072 except that the all
18073 storage allocated with this pool is reclaimed when the pool object goes out of
18074 scope. This pool provides a explicit mechanism similar to the implicit one
18075 provided by several Ada 83 compilers for allocations performed through a local
18076 access type and whose purpose was to reclaim memory when exiting the
18077 scope of a given local access. As an example, the following program does not
18078 leak memory even though it does not perform explicit deallocation:
18079
18080 @smallexample @c ada
18081 with System.Pool_Local;
18082 procedure Pooloc1 is
18083 procedure Internal is
18084 type A is access Integer;
18085 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18086 for A'Storage_Pool use X;
18087 v : A;
18088 begin
18089 for I in 1 .. 50 loop
18090 v := new Integer;
18091 end loop;
18092 end Internal;
18093 begin
18094 for I in 1 .. 100 loop
18095 Internal;
18096 end loop;
18097 end Pooloc1;
18098 @end smallexample
18099
18100 @noindent
18101 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18102 @code{Storage_Size} is specified for an access type.
18103 The whole storage for the pool is
18104 allocated at once, usually on the stack at the point where the access type is
18105 elaborated. It is automatically reclaimed when exiting the scope where the
18106 access type is defined. This package is not intended to be used directly by the
18107 user and it is implicitly used for each such declaration:
18108
18109 @smallexample @c ada
18110 type T1 is access Something;
18111 for T1'Storage_Size use 10_000;
18112 @end smallexample
18113
18114 @node The GNAT Debug Pool Facility
18115 @section The GNAT Debug Pool Facility
18116 @findex Debug Pool
18117 @cindex storage, pool, memory corruption
18118
18119 @noindent
18120 The use of unchecked deallocation and unchecked conversion can easily
18121 lead to incorrect memory references. The problems generated by such
18122 references are usually difficult to tackle because the symptoms can be
18123 very remote from the origin of the problem. In such cases, it is
18124 very helpful to detect the problem as early as possible. This is the
18125 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18126
18127 In order to use the GNAT specific debugging pool, the user must
18128 associate a debug pool object with each of the access types that may be
18129 related to suspected memory problems. See Ada Reference Manual 13.11.
18130 @smallexample @c ada
18131 type Ptr is access Some_Type;
18132 Pool : GNAT.Debug_Pools.Debug_Pool;
18133 for Ptr'Storage_Pool use Pool;
18134 @end smallexample
18135
18136 @noindent
18137 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18138 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18139 allow the user to redefine allocation and deallocation strategies. They
18140 also provide a checkpoint for each dereference, through the use of
18141 the primitive operation @code{Dereference} which is implicitly called at
18142 each dereference of an access value.
18143
18144 Once an access type has been associated with a debug pool, operations on
18145 values of the type may raise four distinct exceptions,
18146 which correspond to four potential kinds of memory corruption:
18147 @itemize @bullet
18148 @item
18149 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18150 @item
18151 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18152 @item
18153 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18154 @item
18155 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18156 @end itemize
18157
18158 @noindent
18159 For types associated with a Debug_Pool, dynamic allocation is performed using
18160 the standard GNAT allocation routine. References to all allocated chunks of
18161 memory are kept in an internal dictionary. Several deallocation strategies are
18162 provided, whereupon the user can choose to release the memory to the system,
18163 keep it allocated for further invalid access checks, or fill it with an easily
18164 recognizable pattern for debug sessions. The memory pattern is the old IBM
18165 hexadecimal convention: @code{16#DEADBEEF#}.
18166
18167 See the documentation in the file g-debpoo.ads for more information on the
18168 various strategies.
18169
18170 Upon each dereference, a check is made that the access value denotes a
18171 properly allocated memory location. Here is a complete example of use of
18172 @code{Debug_Pools}, that includes typical instances of memory corruption:
18173 @smallexample @c ada
18174 @iftex
18175 @leftskip=0cm
18176 @end iftex
18177 with Gnat.Io; use Gnat.Io;
18178 with Unchecked_Deallocation;
18179 with Unchecked_Conversion;
18180 with GNAT.Debug_Pools;
18181 with System.Storage_Elements;
18182 with Ada.Exceptions; use Ada.Exceptions;
18183 procedure Debug_Pool_Test is
18184
18185 type T is access Integer;
18186 type U is access all T;
18187
18188 P : GNAT.Debug_Pools.Debug_Pool;
18189 for T'Storage_Pool use P;
18190
18191 procedure Free is new Unchecked_Deallocation (Integer, T);
18192 function UC is new Unchecked_Conversion (U, T);
18193 A, B : aliased T;
18194
18195 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18196
18197 begin
18198 Info (P);
18199 A := new Integer;
18200 B := new Integer;
18201 B := A;
18202 Info (P);
18203 Free (A);
18204 begin
18205 Put_Line (Integer'Image(B.all));
18206 exception
18207 when E : others => Put_Line ("raised: " & Exception_Name (E));
18208 end;
18209 begin
18210 Free (B);
18211 exception
18212 when E : others => Put_Line ("raised: " & Exception_Name (E));
18213 end;
18214 B := UC(A'Access);
18215 begin
18216 Put_Line (Integer'Image(B.all));
18217 exception
18218 when E : others => Put_Line ("raised: " & Exception_Name (E));
18219 end;
18220 begin
18221 Free (B);
18222 exception
18223 when E : others => Put_Line ("raised: " & Exception_Name (E));
18224 end;
18225 Info (P);
18226 end Debug_Pool_Test;
18227 @end smallexample
18228
18229 @noindent
18230 The debug pool mechanism provides the following precise diagnostics on the
18231 execution of this erroneous program:
18232 @smallexample
18233 Debug Pool info:
18234 Total allocated bytes : 0
18235 Total deallocated bytes : 0
18236 Current Water Mark: 0
18237 High Water Mark: 0
18238
18239 Debug Pool info:
18240 Total allocated bytes : 8
18241 Total deallocated bytes : 0
18242 Current Water Mark: 8
18243 High Water Mark: 8
18244
18245 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18246 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18247 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18248 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18249 Debug Pool info:
18250 Total allocated bytes : 8
18251 Total deallocated bytes : 4
18252 Current Water Mark: 4
18253 High Water Mark: 8
18254 @end smallexample
18255
18256 @ifclear vms
18257 @node The gnatmem Tool
18258 @section The @command{gnatmem} Tool
18259 @findex gnatmem
18260
18261 @noindent
18262 The @code{gnatmem} utility monitors dynamic allocation and
18263 deallocation activity in a program, and displays information about
18264 incorrect deallocations and possible sources of memory leaks.
18265 It is designed to work in association with a static runtime library
18266 only and in this context provides three types of information:
18267 @itemize @bullet
18268 @item
18269 General information concerning memory management, such as the total
18270 number of allocations and deallocations, the amount of allocated
18271 memory and the high water mark, i.e.@: the largest amount of allocated
18272 memory in the course of program execution.
18273
18274 @item
18275 Backtraces for all incorrect deallocations, that is to say deallocations
18276 which do not correspond to a valid allocation.
18277
18278 @item
18279 Information on each allocation that is potentially the origin of a memory
18280 leak.
18281 @end itemize
18282
18283 @menu
18284 * Running gnatmem::
18285 * Switches for gnatmem::
18286 * Example of gnatmem Usage::
18287 @end menu
18288
18289 @node Running gnatmem
18290 @subsection Running @code{gnatmem}
18291
18292 @noindent
18293 @code{gnatmem} makes use of the output created by the special version of
18294 allocation and deallocation routines that record call information. This
18295 allows to obtain accurate dynamic memory usage history at a minimal cost to
18296 the execution speed. Note however, that @code{gnatmem} is not supported on
18297 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18298 Solaris and Windows NT/2000/XP (x86).
18299
18300 @noindent
18301 The @code{gnatmem} command has the form
18302
18303 @smallexample
18304 @c $ gnatmem @ovar{switches} user_program
18305 @c Expanding @ovar macro inline (explanation in macro def comments)
18306 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18307 @end smallexample
18308
18309 @noindent
18310 The program must have been linked with the instrumented version of the
18311 allocation and deallocation routines. This is done by linking with the
18312 @file{libgmem.a} library. For correct symbolic backtrace information,
18313 the user program should be compiled with debugging options
18314 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18315
18316 @smallexample
18317 $ gnatmake -g my_program -largs -lgmem
18318 @end smallexample
18319
18320 @noindent
18321 As library @file{libgmem.a} contains an alternate body for package
18322 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18323 when an executable is linked with library @file{libgmem.a}. It is then not
18324 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18325
18326 @noindent
18327 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18328 This file contains information about all allocations and deallocations
18329 performed by the program. It is produced by the instrumented allocations and
18330 deallocations routines and will be used by @code{gnatmem}.
18331
18332 In order to produce symbolic backtrace information for allocations and
18333 deallocations performed by the GNAT run-time library, you need to use a
18334 version of that library that has been compiled with the @option{-g} switch
18335 (see @ref{Rebuilding the GNAT Run-Time Library}).
18336
18337 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18338 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18339 @option{-i} switch, gnatmem will assume that this file can be found in the
18340 current directory. For example, after you have executed @file{my_program},
18341 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18342
18343 @smallexample
18344 $ gnatmem my_program
18345 @end smallexample
18346
18347 @noindent
18348 This will produce the output with the following format:
18349
18350 *************** debut cc
18351 @smallexample
18352 $ gnatmem my_program
18353
18354 Global information
18355 ------------------
18356 Total number of allocations : 45
18357 Total number of deallocations : 6
18358 Final Water Mark (non freed mem) : 11.29 Kilobytes
18359 High Water Mark : 11.40 Kilobytes
18360
18361 .
18362 .
18363 .
18364 Allocation Root # 2
18365 -------------------
18366 Number of non freed allocations : 11
18367 Final Water Mark (non freed mem) : 1.16 Kilobytes
18368 High Water Mark : 1.27 Kilobytes
18369 Backtrace :
18370 my_program.adb:23 my_program.alloc
18371 .
18372 .
18373 .
18374 @end smallexample
18375
18376 The first block of output gives general information. In this case, the
18377 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18378 Unchecked_Deallocation routine occurred.
18379
18380 @noindent
18381 Subsequent paragraphs display information on all allocation roots.
18382 An allocation root is a specific point in the execution of the program
18383 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18384 construct. This root is represented by an execution backtrace (or subprogram
18385 call stack). By default the backtrace depth for allocations roots is 1, so
18386 that a root corresponds exactly to a source location. The backtrace can
18387 be made deeper, to make the root more specific.
18388
18389 @node Switches for gnatmem
18390 @subsection Switches for @code{gnatmem}
18391
18392 @noindent
18393 @code{gnatmem} recognizes the following switches:
18394
18395 @table @option
18396
18397 @item -q
18398 @cindex @option{-q} (@code{gnatmem})
18399 Quiet. Gives the minimum output needed to identify the origin of the
18400 memory leaks. Omits statistical information.
18401
18402 @item @var{N}
18403 @cindex @var{N} (@code{gnatmem})
18404 N is an integer literal (usually between 1 and 10) which controls the
18405 depth of the backtraces defining allocation root. The default value for
18406 N is 1. The deeper the backtrace, the more precise the localization of
18407 the root. Note that the total number of roots can depend on this
18408 parameter. This parameter must be specified @emph{before} the name of the
18409 executable to be analyzed, to avoid ambiguity.
18410
18411 @item -b n
18412 @cindex @option{-b} (@code{gnatmem})
18413 This switch has the same effect as just depth parameter.
18414
18415 @item -i @var{file}
18416 @cindex @option{-i} (@code{gnatmem})
18417 Do the @code{gnatmem} processing starting from @file{file}, rather than
18418 @file{gmem.out} in the current directory.
18419
18420 @item -m n
18421 @cindex @option{-m} (@code{gnatmem})
18422 This switch causes @code{gnatmem} to mask the allocation roots that have less
18423 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18424 examine even the roots that didn't result in leaks.
18425
18426 @item -s order
18427 @cindex @option{-s} (@code{gnatmem})
18428 This switch causes @code{gnatmem} to sort the allocation roots according to the
18429 specified order of sort criteria, each identified by a single letter. The
18430 currently supported criteria are @code{n, h, w} standing respectively for
18431 number of unfreed allocations, high watermark, and final watermark
18432 corresponding to a specific root. The default order is @code{nwh}.
18433
18434 @end table
18435
18436 @node Example of gnatmem Usage
18437 @subsection Example of @code{gnatmem} Usage
18438
18439 @noindent
18440 The following example shows the use of @code{gnatmem}
18441 on a simple memory-leaking program.
18442 Suppose that we have the following Ada program:
18443
18444 @smallexample @c ada
18445 @group
18446 @cartouche
18447 with Unchecked_Deallocation;
18448 procedure Test_Gm is
18449
18450 type T is array (1..1000) of Integer;
18451 type Ptr is access T;
18452 procedure Free is new Unchecked_Deallocation (T, Ptr);
18453 A : Ptr;
18454
18455 procedure My_Alloc is
18456 begin
18457 A := new T;
18458 end My_Alloc;
18459
18460 procedure My_DeAlloc is
18461 B : Ptr := A;
18462 begin
18463 Free (B);
18464 end My_DeAlloc;
18465
18466 begin
18467 My_Alloc;
18468 for I in 1 .. 5 loop
18469 for J in I .. 5 loop
18470 My_Alloc;
18471 end loop;
18472 My_Dealloc;
18473 end loop;
18474 end;
18475 @end cartouche
18476 @end group
18477 @end smallexample
18478
18479 @noindent
18480 The program needs to be compiled with debugging option and linked with
18481 @code{gmem} library:
18482
18483 @smallexample
18484 $ gnatmake -g test_gm -largs -lgmem
18485 @end smallexample
18486
18487 @noindent
18488 Then we execute the program as usual:
18489
18490 @smallexample
18491 $ test_gm
18492 @end smallexample
18493
18494 @noindent
18495 Then @code{gnatmem} is invoked simply with
18496 @smallexample
18497 $ gnatmem test_gm
18498 @end smallexample
18499
18500 @noindent
18501 which produces the following output (result may vary on different platforms):
18502
18503 @smallexample
18504 Global information
18505 ------------------
18506 Total number of allocations : 18
18507 Total number of deallocations : 5
18508 Final Water Mark (non freed mem) : 53.00 Kilobytes
18509 High Water Mark : 56.90 Kilobytes
18510
18511 Allocation Root # 1
18512 -------------------
18513 Number of non freed allocations : 11
18514 Final Water Mark (non freed mem) : 42.97 Kilobytes
18515 High Water Mark : 46.88 Kilobytes
18516 Backtrace :
18517 test_gm.adb:11 test_gm.my_alloc
18518
18519 Allocation Root # 2
18520 -------------------
18521 Number of non freed allocations : 1
18522 Final Water Mark (non freed mem) : 10.02 Kilobytes
18523 High Water Mark : 10.02 Kilobytes
18524 Backtrace :
18525 s-secsta.adb:81 system.secondary_stack.ss_init
18526
18527 Allocation Root # 3
18528 -------------------
18529 Number of non freed allocations : 1
18530 Final Water Mark (non freed mem) : 12 Bytes
18531 High Water Mark : 12 Bytes
18532 Backtrace :
18533 s-secsta.adb:181 system.secondary_stack.ss_init
18534 @end smallexample
18535
18536 @noindent
18537 Note that the GNAT run time contains itself a certain number of
18538 allocations that have no corresponding deallocation,
18539 as shown here for root #2 and root
18540 #3. This is a normal behavior when the number of non-freed allocations
18541 is one, it allocates dynamic data structures that the run time needs for
18542 the complete lifetime of the program. Note also that there is only one
18543 allocation root in the user program with a single line back trace:
18544 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18545 program shows that 'My_Alloc' is called at 2 different points in the
18546 source (line 21 and line 24). If those two allocation roots need to be
18547 distinguished, the backtrace depth parameter can be used:
18548
18549 @smallexample
18550 $ gnatmem 3 test_gm
18551 @end smallexample
18552
18553 @noindent
18554 which will give the following output:
18555
18556 @smallexample
18557 Global information
18558 ------------------
18559 Total number of allocations : 18
18560 Total number of deallocations : 5
18561 Final Water Mark (non freed mem) : 53.00 Kilobytes
18562 High Water Mark : 56.90 Kilobytes
18563
18564 Allocation Root # 1
18565 -------------------
18566 Number of non freed allocations : 10
18567 Final Water Mark (non freed mem) : 39.06 Kilobytes
18568 High Water Mark : 42.97 Kilobytes
18569 Backtrace :
18570 test_gm.adb:11 test_gm.my_alloc
18571 test_gm.adb:24 test_gm
18572 b_test_gm.c:52 main
18573
18574 Allocation Root # 2
18575 -------------------
18576 Number of non freed allocations : 1
18577 Final Water Mark (non freed mem) : 10.02 Kilobytes
18578 High Water Mark : 10.02 Kilobytes
18579 Backtrace :
18580 s-secsta.adb:81 system.secondary_stack.ss_init
18581 s-secsta.adb:283 <system__secondary_stack___elabb>
18582 b_test_gm.c:33 adainit
18583
18584 Allocation Root # 3
18585 -------------------
18586 Number of non freed allocations : 1
18587 Final Water Mark (non freed mem) : 3.91 Kilobytes
18588 High Water Mark : 3.91 Kilobytes
18589 Backtrace :
18590 test_gm.adb:11 test_gm.my_alloc
18591 test_gm.adb:21 test_gm
18592 b_test_gm.c:52 main
18593
18594 Allocation Root # 4
18595 -------------------
18596 Number of non freed allocations : 1
18597 Final Water Mark (non freed mem) : 12 Bytes
18598 High Water Mark : 12 Bytes
18599 Backtrace :
18600 s-secsta.adb:181 system.secondary_stack.ss_init
18601 s-secsta.adb:283 <system__secondary_stack___elabb>
18602 b_test_gm.c:33 adainit
18603 @end smallexample
18604
18605 @noindent
18606 The allocation root #1 of the first example has been split in 2 roots #1
18607 and #3 thanks to the more precise associated backtrace.
18608
18609 @end ifclear
18610
18611 @node Stack Related Facilities
18612 @chapter Stack Related Facilities
18613
18614 @noindent
18615 This chapter describes some useful tools associated with stack
18616 checking and analysis. In
18617 particular, it deals with dynamic and static stack usage measurements.
18618
18619 @menu
18620 * Stack Overflow Checking::
18621 * Static Stack Usage Analysis::
18622 * Dynamic Stack Usage Analysis::
18623 @end menu
18624
18625 @node Stack Overflow Checking
18626 @section Stack Overflow Checking
18627 @cindex Stack Overflow Checking
18628 @cindex -fstack-check
18629
18630 @noindent
18631 For most operating systems, @command{gcc} does not perform stack overflow
18632 checking by default. This means that if the main environment task or
18633 some other task exceeds the available stack space, then unpredictable
18634 behavior will occur. Most native systems offer some level of protection by
18635 adding a guard page at the end of each task stack. This mechanism is usually
18636 not enough for dealing properly with stack overflow situations because
18637 a large local variable could ``jump'' above the guard page.
18638 Furthermore, when the
18639 guard page is hit, there may not be any space left on the stack for executing
18640 the exception propagation code. Enabling stack checking avoids
18641 such situations.
18642
18643 To activate stack checking, compile all units with the gcc option
18644 @option{-fstack-check}. For example:
18645
18646 @smallexample
18647 gcc -c -fstack-check package1.adb
18648 @end smallexample
18649
18650 @noindent
18651 Units compiled with this option will generate extra instructions to check
18652 that any use of the stack (for procedure calls or for declaring local
18653 variables in declare blocks) does not exceed the available stack space.
18654 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18655
18656 For declared tasks, the stack size is controlled by the size
18657 given in an applicable @code{Storage_Size} pragma or by the value specified
18658 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18659 the default size as defined in the GNAT runtime otherwise.
18660
18661 For the environment task, the stack size depends on
18662 system defaults and is unknown to the compiler. Stack checking
18663 may still work correctly if a fixed
18664 size stack is allocated, but this cannot be guaranteed.
18665 @ifclear vms
18666 To ensure that a clean exception is signalled for stack
18667 overflow, set the environment variable
18668 @env{GNAT_STACK_LIMIT} to indicate the maximum
18669 stack area that can be used, as in:
18670 @cindex GNAT_STACK_LIMIT
18671
18672 @smallexample
18673 SET GNAT_STACK_LIMIT 1600
18674 @end smallexample
18675
18676 @noindent
18677 The limit is given in kilobytes, so the above declaration would
18678 set the stack limit of the environment task to 1.6 megabytes.
18679 Note that the only purpose of this usage is to limit the amount
18680 of stack used by the environment task. If it is necessary to
18681 increase the amount of stack for the environment task, then this
18682 is an operating systems issue, and must be addressed with the
18683 appropriate operating systems commands.
18684 @end ifclear
18685 @ifset vms
18686 To have a fixed size stack in the environment task, the stack must be put
18687 in the P0 address space and its size specified. Use these switches to
18688 create a p0 image:
18689
18690 @smallexample
18691 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18692 @end smallexample
18693
18694 @noindent
18695 The quotes are required to keep case. The number after @samp{STACK=} is the
18696 size of the environmental task stack in pagelets (512 bytes). In this example
18697 the stack size is about 2 megabytes.
18698
18699 @noindent
18700 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18701 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
18702 more details about the @option{/p0image} qualifier and the @option{stack}
18703 option.
18704
18705 @noindent
18706 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18707 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18708 stack in kilobytes. For example:
18709
18710 @smallexample
18711 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18712 @end smallexample
18713 @end ifset
18714
18715 @node Static Stack Usage Analysis
18716 @section Static Stack Usage Analysis
18717 @cindex Static Stack Usage Analysis
18718 @cindex -fstack-usage
18719
18720 @noindent
18721 A unit compiled with @option{-fstack-usage} will generate an extra file
18722 that specifies
18723 the maximum amount of stack used, on a per-function basis.
18724 The file has the same
18725 basename as the target object file with a @file{.su} extension.
18726 Each line of this file is made up of three fields:
18727
18728 @itemize
18729 @item
18730 The name of the function.
18731 @item
18732 A number of bytes.
18733 @item
18734 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18735 @end itemize
18736
18737 The second field corresponds to the size of the known part of the function
18738 frame.
18739
18740 The qualifier @code{static} means that the function frame size
18741 is purely static.
18742 It usually means that all local variables have a static size.
18743 In this case, the second field is a reliable measure of the function stack
18744 utilization.
18745
18746 The qualifier @code{dynamic} means that the function frame size is not static.
18747 It happens mainly when some local variables have a dynamic size. When this
18748 qualifier appears alone, the second field is not a reliable measure
18749 of the function stack analysis. When it is qualified with @code{bounded}, it
18750 means that the second field is a reliable maximum of the function stack
18751 utilization.
18752
18753 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18754 subprogram whose stack usage might be larger than the specified amount of
18755 bytes. The wording is in keeping with the qualifier documented above.
18756
18757 @node Dynamic Stack Usage Analysis
18758 @section Dynamic Stack Usage Analysis
18759
18760 @noindent
18761 It is possible to measure the maximum amount of stack used by a task, by
18762 adding a switch to @command{gnatbind}, as:
18763
18764 @smallexample
18765 $ gnatbind -u0 file
18766 @end smallexample
18767
18768 @noindent
18769 With this option, at each task termination, its stack usage is output on
18770 @file{stderr}.
18771 It is not always convenient to output the stack usage when the program
18772 is still running. Hence, it is possible to delay this output until program
18773 termination. for a given number of tasks specified as the argument of the
18774 @option{-u} option. For instance:
18775
18776 @smallexample
18777 $ gnatbind -u100 file
18778 @end smallexample
18779
18780 @noindent
18781 will buffer the stack usage information of the first 100 tasks to terminate and
18782 output this info at program termination. Results are displayed in four
18783 columns:
18784
18785 @noindent
18786 Index | Task Name | Stack Size | Stack Usage
18787
18788 @noindent
18789 where:
18790
18791 @table @emph
18792 @item Index
18793 is a number associated with each task.
18794
18795 @item Task Name
18796 is the name of the task analyzed.
18797
18798 @item Stack Size
18799 is the maximum size for the stack.
18800
18801 @item Stack Usage
18802 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18803 is not entirely analyzed, and it's not possible to know exactly how
18804 much has actually been used.
18805
18806 @end table
18807
18808 @noindent
18809 The environment task stack, e.g., the stack that contains the main unit, is
18810 only processed when the environment variable GNAT_STACK_LIMIT is set.
18811
18812 @noindent
18813 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18814 stack usage reports at run-time. See its body for the details.
18815
18816 @c *********************************
18817 @c * GNATCHECK *
18818 @c *********************************
18819 @node Verifying Properties Using gnatcheck
18820 @chapter Verifying Properties Using @command{gnatcheck}
18821 @findex gnatcheck
18822 @cindex @command{gnatcheck}
18823
18824 @noindent
18825 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18826 of Ada source files according to a given set of semantic rules.
18827 @cindex ASIS
18828
18829 In order to check compliance with a given rule, @command{gnatcheck} has to
18830 semantically analyze the Ada sources.
18831 Therefore, checks can only be performed on
18832 legal Ada units. Moreover, when a unit depends semantically upon units located
18833 outside the current directory, the source search path has to be provided when
18834 calling @command{gnatcheck}, either through a specified project file or
18835 through @command{gnatcheck} switches.
18836
18837 For full details, refer to @cite{GNATcheck Reference Manual} document.
18838
18839
18840 @c *********************************
18841 @node Creating Sample Bodies Using gnatstub
18842 @chapter Creating Sample Bodies Using @command{gnatstub}
18843 @findex gnatstub
18844
18845 @noindent
18846 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18847 for library unit declarations.
18848
18849 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18850 driver (see @ref{The GNAT Driver and Project Files}).
18851
18852 To create a body stub, @command{gnatstub} has to compile the library
18853 unit declaration. Therefore, bodies can be created only for legal
18854 library units. Moreover, if a library unit depends semantically upon
18855 units located outside the current directory, you have to provide
18856 the source search path when calling @command{gnatstub}, see the description
18857 of @command{gnatstub} switches below.
18858
18859 By default, all the program unit body stubs generated by @code{gnatstub}
18860 raise the predefined @code{Program_Error} exception, which will catch
18861 accidental calls of generated stubs. This behavior can be changed with
18862 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18863
18864 @menu
18865 * Running gnatstub::
18866 * Switches for gnatstub::
18867 @end menu
18868
18869 @node Running gnatstub
18870 @section Running @command{gnatstub}
18871
18872 @noindent
18873 @command{gnatstub} has a command-line interface of the form:
18874
18875 @smallexample
18876 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18877 @c Expanding @ovar macro inline (explanation in macro def comments)
18878 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18879 @end smallexample
18880
18881 @noindent
18882 where
18883 @table @var
18884 @item filename
18885 is the name of the source file that contains a library unit declaration
18886 for which a body must be created. The file name may contain the path
18887 information.
18888 The file name does not have to follow the GNAT file name conventions. If the
18889 name
18890 does not follow GNAT file naming conventions, the name of the body file must
18891 be provided
18892 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18893 If the file name follows the GNAT file naming
18894 conventions and the name of the body file is not provided,
18895 @command{gnatstub}
18896 creates the name
18897 of the body file from the argument file name by replacing the @file{.ads}
18898 suffix
18899 with the @file{.adb} suffix.
18900
18901 @item directory
18902 indicates the directory in which the body stub is to be placed (the default
18903 is the
18904 current directory)
18905
18906 @item @samp{@var{gcc_switches}} is a list of switches for
18907 @command{gcc}. They will be passed on to all compiler invocations made by
18908 @command{gnatstub} to generate the ASIS trees. Here you can provide
18909 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18910 use the @option{-gnatec} switch to set the configuration file,
18911 use the @option{-gnat05} switch if sources should be compiled in
18912 Ada 2005 mode etc.
18913
18914 @item switches
18915 is an optional sequence of switches as described in the next section
18916 @end table
18917
18918 @node Switches for gnatstub
18919 @section Switches for @command{gnatstub}
18920
18921 @table @option
18922 @c !sort!
18923
18924 @item ^-f^/FULL^
18925 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18926 If the destination directory already contains a file with the name of the
18927 body file
18928 for the argument spec file, replace it with the generated body stub.
18929
18930 @item ^-hs^/HEADER=SPEC^
18931 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18932 Put the comment header (i.e., all the comments preceding the
18933 compilation unit) from the source of the library unit declaration
18934 into the body stub.
18935
18936 @item ^-hg^/HEADER=GENERAL^
18937 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18938 Put a sample comment header into the body stub.
18939
18940 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
18941 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
18942 Use the content of the file as the comment header for a generated body stub.
18943
18944 @ifclear vms
18945 @item -IDIR
18946 @cindex @option{-IDIR} (@command{gnatstub})
18947 @itemx -I-
18948 @cindex @option{-I-} (@command{gnatstub})
18949 @end ifclear
18950 @ifset vms
18951 @item /NOCURRENT_DIRECTORY
18952 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18953 @end ifset
18954 ^These switches have ^This switch has^ the same meaning as in calls to
18955 @command{gcc}.
18956 ^They define ^It defines ^ the source search path in the call to
18957 @command{gcc} issued
18958 by @command{gnatstub} to compile an argument source file.
18959
18960 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18961 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18962 This switch has the same meaning as in calls to @command{gcc}.
18963 It defines the additional configuration file to be passed to the call to
18964 @command{gcc} issued
18965 by @command{gnatstub} to compile an argument source file.
18966
18967 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18968 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18969 (@var{n} is a non-negative integer). Set the maximum line length in the
18970 body stub to @var{n}; the default is 79. The maximum value that can be
18971 specified is 32767. Note that in the special case of configuration
18972 pragma files, the maximum is always 32767 regardless of whether or
18973 not this switch appears.
18974
18975 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18976 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18977 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18978 the generated body sample to @var{n}.
18979 The default indentation is 3.
18980
18981 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18982 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18983 Order local bodies alphabetically. (By default local bodies are ordered
18984 in the same way as the corresponding local specs in the argument spec file.)
18985
18986 @item ^-i^/INDENTATION=^@var{n}
18987 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18988 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18989
18990 @item ^-k^/TREE_FILE=SAVE^
18991 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18992 Do not remove the tree file (i.e., the snapshot of the compiler internal
18993 structures used by @command{gnatstub}) after creating the body stub.
18994
18995 @item ^-l^/LINE_LENGTH=^@var{n}
18996 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18997 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18998
18999 @item ^--no-exception^/NO_EXCEPTION^
19000 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19001 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19002 This is not always possible for function stubs.
19003
19004 @item ^--no-local-header^/NO_LOCAL_HEADER^
19005 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19006 Do not place local comment header with unit name before body stub for a
19007 unit.
19008
19009 @item ^-o ^/BODY=^@var{body-name}
19010 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19011 Body file name. This should be set if the argument file name does not
19012 follow
19013 the GNAT file naming
19014 conventions. If this switch is omitted the default name for the body will be
19015 obtained
19016 from the argument file name according to the GNAT file naming conventions.
19017
19018 @item ^-q^/QUIET^
19019 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19020 Quiet mode: do not generate a confirmation when a body is
19021 successfully created, and do not generate a message when a body is not
19022 required for an
19023 argument unit.
19024
19025 @item ^-r^/TREE_FILE=REUSE^
19026 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19027 Reuse the tree file (if it exists) instead of creating it. Instead of
19028 creating the tree file for the library unit declaration, @command{gnatstub}
19029 tries to find it in the current directory and use it for creating
19030 a body. If the tree file is not found, no body is created. This option
19031 also implies @option{^-k^/SAVE^}, whether or not
19032 the latter is set explicitly.
19033
19034 @item ^-t^/TREE_FILE=OVERWRITE^
19035 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19036 Overwrite the existing tree file. If the current directory already
19037 contains the file which, according to the GNAT file naming rules should
19038 be considered as a tree file for the argument source file,
19039 @command{gnatstub}
19040 will refuse to create the tree file needed to create a sample body
19041 unless this option is set.
19042
19043 @item ^-v^/VERBOSE^
19044 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19045 Verbose mode: generate version information.
19046
19047 @end table
19048
19049 @c *********************************
19050 @node Creating Unit Tests Using gnattest
19051 @chapter Creating Unit Tests Using @command{gnattest}
19052 @findex gnattest
19053
19054 @noindent
19055 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19056 as well as a test driver infrastructure (harness). @command{gnattest} creates
19057 a skeleton for each visible subprogram in the packages under consideration when
19058 they do not exist already.
19059
19060 In order to process source files from a project, @command{gnattest} has to
19061 semantically analyze the sources. Therefore, test skeletons can only be
19062 generated for legal Ada units. If a unit is dependent on other units,
19063 those units should be among the source files of the project or of other projects
19064 imported by this one.
19065
19066 Generated skeletons and harnesses are based on the AUnit testing framework.
19067 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19068 for Java or CppUnit for C++. While it is advised that gnattest users read
19069 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19070 For correct operation of @command{gnattest}, AUnit should be installed and
19071 aunit.gpr must be on the project path. This happens automatically when Aunit
19072 is installed at its default location.
19073 @menu
19074 * Running gnattest::
19075 * Switches for gnattest::
19076 * Project Attributes for gnattest::
19077 * Simple Example::
19078 * Setting Up and Tearing Down the Testing Environment::
19079 * Regenerating Tests::
19080 * Default Test Behavior::
19081 * Testing Primitive Operations of Tagged Types::
19082 * Testing Inheritance::
19083 * Tagged Types Substitutability Testing::
19084 * Testing with Contracts::
19085 * Additional Tests::
19086 @ifclear vms
19087 * Support for other platforms/run-times::
19088 @end ifclear
19089 * Current Limitations::
19090 @end menu
19091
19092 @node Running gnattest
19093 @section Running @command{gnattest}
19094
19095 @noindent
19096 @command{gnattest} has a command-line interface of the form
19097
19098 @smallexample
19099 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19100 @c Expanding @ovar macro inline (explanation in macro def comments)
19101 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19102 @end smallexample
19103
19104 @noindent
19105 where
19106 @table @var
19107
19108 @item -Pprojname
19109 specifies the project defining the location of source files. When no
19110 file names are provided on the command line, all sources in the project
19111 are used as input. This switch is required.
19112
19113 @item filename
19114 is the name of the source file containing the library unit package declaration
19115 for which a test package will be created. The file name may be given with a
19116 path.
19117
19118 @item @samp{@var{gcc_switches}}
19119 is a list of switches for
19120 @command{gcc}. These switches will be passed on to all compiler invocations
19121 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19122 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19123 use the @option{-gnatec} switch to set the configuration file,
19124 use the @option{-gnat05} switch if sources should be compiled in
19125 Ada 2005 mode, etc.
19126
19127 @item switches
19128 is an optional sequence of switches as described in the next section.
19129
19130 @end table
19131
19132 @command{gnattest} results can be found in two different places.
19133
19134 @itemize @bullet
19135 @item automatic harness:
19136 the harness code, which is located by default in "gnattest/harness" directory
19137 that is created in the object directory of corresponding project file. All of
19138 this code is generated completely automatically and can be destroyed and
19139 regenerated at will. It is not recommended to modify this code manually, since
19140 it could easily be overridden by mistake. The entry point in the harness code is
19141 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19142 using a command such as:
19143
19144 @smallexample
19145 gnatmake -P<harness-dir>/test_driver
19146 test_runner
19147 @end smallexample
19148
19149 Note that you might need to specify the necessary values of scenario variables
19150 when you are not using the AUnit defaults.
19151
19152 @item actual unit test skeletons:
19153 a test skeleton for each visible subprogram is created in a separate file, if it
19154 doesn't exist already. By default, those separate test files are located in a
19155 "gnattest/tests" directory that is created in the object directory of
19156 corresponding project file. For example, if a source file my_unit.ads in
19157 directory src contains a visible subprogram Proc, then the corresponding unit
19158 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19159 <code> is a signature encoding used to differentiate test names in case of
19160 overloading.
19161
19162 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19163 this will cause a name conflict with the generated test package.
19164 @end itemize
19165
19166 @node Switches for gnattest
19167 @section Switches for @command{gnattest}
19168
19169 @table @option
19170 @c !sort!
19171
19172 @item --harness-only
19173 @cindex @option{--harness-only} (@command{gnattest})
19174 When this option is given, @command{gnattest} creates a harness for all
19175 sources, treating them as test packages.
19176
19177 @item --additional-tests=@var{projname}
19178 @cindex @option{--additional-tests} (@command{gnattest})
19179 Sources described in @var{projname} are considered potential additional
19180 manual tests to be added to the test suite.
19181
19182 @item -r
19183 @cindex @option{-r} (@command{gnattest})
19184 Recursively consider all sources from all projects.
19185
19186 @item -X@var{name=value}
19187 @cindex @option{-X} (@command{gnattest})
19188 Indicate that external variable @var{name} has the value @var{value}.
19189
19190 @item -q
19191 @cindex @option{-q} (@command{gnattest})
19192 Suppresses noncritical output messages.
19193
19194 @item -v
19195 @cindex @option{-v} (@command{gnattest})
19196 Verbose mode: generates version information.
19197
19198 @item --validate-type-extensions
19199 @cindex @option{--validate-type-extensions} (@command{gnattest})
19200 Enables substitution check: run all tests from all parents in order
19201 to check substitutability.
19202
19203 @item --skeleton-default=@var{val}
19204 @cindex @option{--skeleton-default} (@command{gnattest})
19205 Specifies the default behavior of generated skeletons. @var{val} can be either
19206 "fail" or "pass", "fail" being the default.
19207
19208 @item --tests-root=@var{dirname}
19209 @cindex @option{--tests-root} (@command{gnattest})
19210 The directory hierarchy of tested sources is recreated in the @var{dirname}
19211 directory, and test packages are placed in corresponding directories.
19212 If the @var{dirname} is a relative path, it is considered relative to the object
19213 directory of the project file. When all sources from all projects are taken
19214 recursively from all projects, directory hierarchies of tested sources are
19215 recreated for each project in their object directories and test packages are
19216 placed accordingly.
19217
19218 @item --subdir=@var{dirname}
19219 @cindex @option{--subdir} (@command{gnattest})
19220 Test packages are placed in subdirectories.
19221
19222 @item --tests-dir=@var{dirname}
19223 @cindex @option{--tests-dir} (@command{gnattest})
19224 All test packages are placed in the @var{dirname} directory.
19225 If the @var{dirname} is a relative path, it is considered relative to the object
19226 directory of the project file. When all sources from all projects are taken
19227 recursively from all projects, @var{dirname} directories are created for each
19228 project in their object directories and test packages are placed accordingly.
19229
19230 @item --harness-dir=@var{dirname}
19231 @cindex @option{--harness-dir} (@command{gnattest})
19232 specifies the directory that will hold the harness packages and project file
19233 for the test driver. If the @var{dirname} is a relative path, it is considered
19234 relative to the object directory of the project file.
19235
19236 @item --separates
19237 @cindex @option{--separates} (@command{gnattest})
19238 Bodies of all test routines are generated as separates. Note that this mode is
19239 kept for compatibility reasons only and it is not advised to use it due to
19240 possible problems with hash in names of test skeletons when using an
19241 inconsistent casing. Separate test skeletons can be incorporated to monolith
19242 test package with improved hash being used by using @option{--transition}
19243 switch.
19244
19245
19246 @item --transition
19247 @cindex @option{--transition} (@command{gnattest})
19248 This allows transition from separate test routines to monolith test packages.
19249 All matching test routines are overwritten with contents of corresponding
19250 separates. Note that if separate test routines had any manually added with
19251 clauses they will be moved to the test package body as is and have to be moved
19252 by hand.
19253
19254 @end table
19255
19256 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19257 mutually exclusive.
19258
19259 @node Project Attributes for gnattest
19260 @section Project Attributes for @command{gnattest}
19261
19262 @noindent
19263
19264 Most of the command-line options can also be passed to the tool by adding
19265 special attributes to the project file. Those attributes should be put in
19266 package gnattest. Here is the list of attributes:
19267
19268 @itemize @bullet
19269
19270 @item Tests_Root
19271 is used to select the same output mode as with the --tests-root option.
19272 This attribute cannot be used together with Subdir or Tests_Dir.
19273
19274 @item Subdir
19275 is used to select the same output mode as with the --subdir option.
19276 This attribute cannot be used together with Tests_Root or Tests_Dir.
19277
19278 @item Tests_Dir
19279 is used to select the same output mode as with the --tests-dir option.
19280 This attribute cannot be used together with Subdir or Tests_Root.
19281
19282 @item Harness_Dir
19283 is used to specify the directory in which to place harness packages and project
19284 file for the test driver, otherwise specified by --harness-dir.
19285
19286 @item Additional_Tests
19287 is used to specify the project file, otherwise given by
19288 --additional-tests switch.
19289
19290 @item Skeletons_Default
19291 is used to specify the default behaviour of test skeletons, otherwise
19292 specified by --skeleton-default option. The value of this attribute
19293 should be either "pass" or "fail".
19294
19295 @end itemize
19296
19297 Each of those attributes can be overridden from the command line if needed.
19298 Other @command{gnattest} switches can also be passed via the project
19299 file as an attribute list called GNATtest_Switches.
19300
19301 @node Simple Example
19302 @section Simple Example
19303
19304 @noindent
19305
19306 Let's take a very simple example using the first @command{gnattest} example
19307 located in:
19308
19309 @smallexample
19310 <install_prefix>/share/examples/gnattest/simple
19311 @end smallexample
19312
19313 This project contains a simple package containing one subprogram. By running gnattest:
19314
19315 @smallexample
19316 $ gnattest --harness-dir=driver -Psimple.gpr
19317 @end smallexample
19318
19319 a test driver is created in directory "driver". It can be compiled and run:
19320
19321 @smallexample
19322 $ cd obj/driver
19323 $ gnatmake -Ptest_driver
19324 $ test_runner
19325 @end smallexample
19326
19327 One failed test with diagnosis "test not implemented" is reported.
19328 Since no special output option was specified, the test package Simple.Tests
19329 is located in:
19330
19331 @smallexample
19332 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19333 @end smallexample
19334
19335 For each package containing visible subprograms, a child test package is
19336 generated. It contains one test routine per tested subprogram. Each
19337 declaration of a test subprogram has a comment specifying which tested
19338 subprogram it corresponds to. Bodies of test routines are placed in test package
19339 bodies and are surrounded by special comment sections. Those comment sections
19340 should not be removed or modified in order for gnattest to be able to regenerate
19341 test packages and keep already written tests in place.
19342 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19343 a single statement: a call to procedure Assert. It has two arguments:
19344 the Boolean expression we want to check and the diagnosis message to display if
19345 the condition is false.
19346
19347 That is where actual testing code should be written after a proper setup.
19348 An actual check can be performed by replacing the Assert call with:
19349
19350 @smallexample @c ada
19351 Assert (Inc (1) = 2, "wrong incrementation");
19352 @end smallexample
19353
19354 After recompiling and running the test driver, one successfully passed test
19355 is reported.
19356
19357 @node Setting Up and Tearing Down the Testing Environment
19358 @section Setting Up and Tearing Down the Testing Environment
19359
19360 @noindent
19361
19362 Besides test routines themselves, each test package has a parent package
19363 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19364 overwritten by the tool. Set_Up is called before each test routine of the
19365 package and Tear_Down is called after each test routine. Those two procedures
19366 can be used to perform necessary initialization and finalization,
19367 memory allocation, etc. Test type declared in Test_Data package is parent type
19368 for the test type of test package and can have user-defined components whose
19369 values can be set by Set_Up routine and used in test routines afterwards.
19370
19371 @node Regenerating Tests
19372 @section Regenerating Tests
19373
19374 @noindent
19375
19376 Bodies of test routines and test_data packages are never overridden after they
19377 have been created once. As long as the name of the subprogram, full expanded Ada
19378 names, and the order of its parameters is the same, and comment sections are
19379 intact the old test routine will fit in its place and no test skeleton will be
19380 generated for the subprogram.
19381
19382 This can be demonstrated with the previous example. By uncommenting declaration
19383 and body of function Dec in simple.ads and simple.adb, running
19384 @command{gnattest} on the project, and then running the test driver:
19385
19386 @smallexample
19387 gnattest --harness-dir=driver -Psimple.gpr
19388 cd obj/driver
19389 gnatmake -Ptest_driver
19390 test_runner
19391 @end smallexample
19392
19393 the old test is not replaced with a stub, nor is it lost, but a new test
19394 skeleton is created for function Dec.
19395
19396 The only way of regenerating tests skeletons is to remove the previously created
19397 tests together with corresponding comment sections.
19398
19399 @node Default Test Behavior
19400 @section Default Test Behavior
19401
19402 @noindent
19403
19404 The generated test driver can treat unimplemented tests in two ways:
19405 either count them all as failed (this is useful to see which tests are still
19406 left to implement) or as passed (to sort out unimplemented ones from those
19407 actually failing).
19408
19409 The test driver accepts a switch to specify this behavior:
19410 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19411 @command{gnattest}).
19412
19413 The default behavior of the test driver is set with the same switch
19414 as passed to gnattest when generating the test driver.
19415
19416 Passing it to the driver generated on the first example:
19417
19418 @smallexample
19419 test_runner --skeleton-default=pass
19420 @end smallexample
19421
19422 makes both tests pass, even the unimplemented one.
19423
19424 @node Testing Primitive Operations of Tagged Types
19425 @section Testing Primitive Operations of Tagged Types
19426
19427 @noindent
19428
19429 Creation of test skeletons for primitive operations of tagged types entails
19430 a number of features. Test routines for all primitives of a given tagged type
19431 are placed in a separate child package named according to the tagged type. For
19432 example, if you have tagged type T in package P, all tests for primitives
19433 of T will be in P.T_Test_Data.T_Tests.
19434
19435 Consider running gnattest on the second example (note: actual tests for this
19436 example already exist, so there's no need to worry if the tool reports that
19437 no new stubs were generated):
19438
19439 @smallexample
19440 cd <install_prefix>/share/examples/gnattest/tagged_rec
19441 gnattest --harness-dir=driver -Ptagged_rec.gpr
19442 @end smallexample
19443
19444 Taking a closer look at the test type declared in the test package
19445 Speed1.Controller_Test_Data is necessary. It is declared in:
19446
19447 @smallexample
19448 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19449 @end smallexample
19450
19451 Test types are direct or indirect descendants of
19452 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19453 subprograms, the user doesn't need to be concerned with them. However,
19454 when generating test packages for primitive operations, there are some things
19455 the user needs to know.
19456
19457 Type Test_Controller has components that allow assignment of various
19458 derivations of type Controller. And if you look at the specification of
19459 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19460 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19461 Thus, test types mirror the hierarchy of tested types.
19462
19463 The Set_Up procedure of Test_Data package corresponding to a test package
19464 of primitive operations of type T assigns to Fixture a reference to an
19465 object of that exact type T. Notice, however, that if the tagged type has
19466 discriminants, the Set_Up only has a commented template for setting
19467 up the fixture, since filling the discriminant with actual value is up
19468 to the user.
19469
19470 The knowledge of the structure of test types allows additional testing
19471 without additional effort. Those possibilities are described below.
19472
19473 @node Testing Inheritance
19474 @section Testing Inheritance
19475
19476 @noindent
19477
19478 Since the test type hierarchy mimics the hierarchy of tested types, the
19479 inheritance of tests takes place. An example of such inheritance can be
19480 seen by running the test driver generated for the second example. As previously
19481 mentioned, actual tests are already written for this example.
19482
19483 @smallexample
19484 cd obj/driver
19485 gnatmake -Ptest_driver
19486 test_runner
19487 @end smallexample
19488
19489 There are 6 passed tests while there are only 5 testable subprograms. The test
19490 routine for function Speed has been inherited and run against objects of the
19491 derived type.
19492
19493 @node Tagged Types Substitutability Testing
19494 @section Tagged Types Substitutability Testing
19495
19496 @noindent
19497
19498 Tagged Types Substitutability Testing is a way of verifying the global type
19499 consistency by testing. Global type consistency is a principle stating that if
19500 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19501 then objects of type T may be replaced with objects of type S (that is,
19502 objects of type S may be substituted for objects of type T), without
19503 altering any of the desirable properties of the program. When the properties
19504 of the program are expressed in the form of subprogram preconditions and
19505 postconditions (let's call them pre and post), the principle is formulated as
19506 relations between the pre and post of primitive operations and the pre and post
19507 of their derived operations. The pre of a derived operation should not be
19508 stronger than the original pre, and the post of the derived operation should
19509 not be weaker than the original post. Those relations ensure that verifying if
19510 a dispatching call is safe can be done just by using the pre and post of the
19511 root operation.
19512
19513 Verifying global type consistency by testing consists of running all the unit
19514 tests associated with the primitives of a given tagged type with objects of its
19515 derived types.
19516
19517 In the example used in the previous section, there was clearly a violation of
19518 type consistency. The overriding primitive Adjust_Speed in package Speed2
19519 removes the functionality of the overridden primitive and thus doesn't respect
19520 the consistency principle.
19521 Gnattest has a special option to run overridden parent tests against objects
19522 of the type which have overriding primitives:
19523
19524 @smallexample
19525 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19526 cd obj/driver
19527 gnatmake -Ptest_driver
19528 test_runner
19529 @end smallexample
19530
19531 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19532 against objects of the derived type.
19533
19534 Non-overridden tests are already inherited for derived test types, so the
19535 --validate-type-extensions enables the application of overriden tests to objects
19536 of derived types.
19537
19538 @node Testing with Contracts
19539 @section Testing with Contracts
19540
19541 @noindent
19542
19543 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19544 as well as corresponding aspects.
19545 Test routines are generated, one per each Test_Case associated with a tested
19546 subprogram. Those test routines have special wrappers for tested functions
19547 that have composition of pre- and postcondition of the subprogram with
19548 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19549 either count for Nominal mode or do not count for Robustness mode).
19550
19551 The third example demonstrates how this works:
19552
19553 @smallexample
19554 cd <install_prefix>/share/examples/gnattest/contracts
19555 gnattest --harness-dir=driver -Pcontracts.gpr
19556 @end smallexample
19557
19558 Putting actual checks within the range of the contract does not cause any
19559 error reports. For example, for the test routine which corresponds to
19560 test case 1:
19561
19562 @smallexample @c ada
19563 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19564 @end smallexample
19565
19566 and for the test routine corresponding to test case 2:
19567
19568 @smallexample @c ada
19569 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19570 @end smallexample
19571
19572 are acceptable:
19573
19574 @smallexample
19575 cd obj/driver
19576 gnatmake -Ptest_driver
19577 test_runner
19578 @end smallexample
19579
19580 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19581 a precondition violation for test case one. Also, by using any otherwise
19582 correct but positive pair of numbers in the second test routine, you can also
19583 get a precondition violation. Postconditions are checked and reported
19584 the same way.
19585
19586 @node Additional Tests
19587 @section Additional Tests
19588
19589 @noindent
19590 @command{gnattest} can add user-written tests to the main suite of the test
19591 driver. @command{gnattest} traverses the given packages and searches for test
19592 routines. All procedures with a single in out parameter of a type which is
19593 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19594 specifications are added to the suites and are then executed by the test driver.
19595 (Set_Up and Tear_Down are filtered out.)
19596
19597 An example illustrates two ways of creating test harnesses for user-written
19598 tests. Directory additional_tests contains an AUnit-based test driver written
19599 by hand.
19600
19601 @smallexample
19602 <install_prefix>/share/examples/gnattest/additional_tests/
19603 @end smallexample
19604
19605 To create a test driver for already-written tests, use the --harness-only
19606 option:
19607
19608 @smallexample
19609 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19610 --harness-only
19611 gnatmake -Pharness_only/test_driver.gpr
19612 harness_only/test_runner
19613 @end smallexample
19614
19615 Additional tests can also be executed together with generated tests:
19616
19617 @smallexample
19618 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19619 --harness-dir=mixing
19620 gnatmake -Pmixing/test_driver.gpr
19621 mixing/test_runner
19622 @end smallexample
19623
19624 @ifclear vms
19625 @node Support for other platforms/run-times
19626 @section Support for other platforms/run-times
19627
19628 @noindent
19629 @command{gnattest} can be used to generate the test harness for platforms
19630 and run-time libraries others than the default native target with the
19631 default full run-time. For example, when using a limited run-time library
19632 such as Zero FootPrint (ZFP), a simplified harness is generated.
19633
19634 Two variables are used to tell the underlying AUnit framework how to generate
19635 the test harness: @code{PLATFORM}, which identifies the target, and
19636 @code{RUNTIME}, used to determine the run-time library for which the harness
19637 is generated. Corresponding prefix should also be used when calling
19638 @command{gnattest} for non-native targets. For example, the following options
19639 are used to generate the AUnit test harness for a PowerPC ELF target using
19640 the ZFP run-time library:
19641
19642 @smallexample
19643 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19644 @end smallexample
19645 @end ifclear
19646
19647 @node Current Limitations
19648 @section Current Limitations
19649
19650 @noindent
19651
19652 The tool currently does not support following features:
19653
19654 @itemize @bullet
19655 @item generic tests for generic packages and package instantiations
19656 @item tests for protected subprograms and entries
19657
19658 @end itemize
19659
19660 @c *********************************
19661 @node Performing Dimensionality Analysis in GNAT
19662 @chapter Performing Dimensionality Analysis in GNAT
19663 @noindent
19664 The GNAT compiler now supports dimensionality checking. The user can
19665 specify physical units for objects, and the compiler will verify that uses
19666 of these objects are compatible with their dimensions, in a fashion that is
19667 familiar to engineering practice. The dimensions of algebraic expressions
19668 (including powers with static exponents) are computed from their consistuents.
19669
19670 This feature depends on Ada 2012 aspect specifications, and is available from
19671 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19672 the user to define a system of units; the aspect Dimension then allows the user
19673 to declare dimensioned quantities within a given system.
19674
19675 The major advantage of this model is that it does not require the declaration of
19676 multiple operators for all possible combinations of types: it is only necessary
19677 to use the proper subtypes in object declarations.
19678
19679 The simplest way to impose dimensionality checking on a computation is to make
19680 use of the package System.Dim.Mks, which is part of the GNAT library. This
19681 package defines a floating-point type MKS_Type, for which a sequence of
19682 dimension names are specified, together with their conventional abbreviations.
19683 The following should be read together with the full specification of the
19684 package, in file s-dimmks.ads.
19685
19686 @smallexample @c ada
19687 type Mks_Type is new Long_Long_Float
19688 with
19689 Dimension_System => (
19690 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
19691 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
19692 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
19693 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
19694 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
19695 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
19696 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
19697 @end smallexample
19698
19699 @noindent
19700 The package then defines a series of subtypes that correspond to these
19701 conventional units. For example:
19702 @smallexample @c ada
19703 subtype Length is Mks_Type
19704 with
19705 Dimension => (Symbol => 'm',
19706 Meter => 1,
19707 others => 0);
19708 @end smallexample
19709 @noindent
19710 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19711 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19712 the SI system).
19713
19714 The package also defines conventional names for values of each unit, for
19715 example:
19716
19717 @smallexample @c ada
19718 m : constant Length := 1.0;
19719 kg : constant Mass := 1.0;
19720 s : constant Time := 1.0;
19721 A : constant Electric_Current := 1.0;
19722 @end smallexample
19723
19724 @noindent
19725 as well as useful multiples of these units:
19726
19727 @smallexample @c ada
19728 cm : constant Length := 1.0E-02;
19729 g : constant Mass := 1.0E-03;
19730 min : constant Time := 60.0;
19731 day : constant TIme := 60.0 * 24.0 * min;
19732 ...
19733 @end smallexample
19734
19735 @noindent
19736 The user can then define a derived unit by providing the aspect that
19737 specifies its dimensions within the MKS system, as well as the string to
19738 be used for output of a value of that unit:
19739
19740 @smallexample @c ada
19741 subtype Acceleration is Mks_Type
19742 with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0);
19743 @end smallexample
19744
19745 @noindent
19746 Here is a complete example of use:
19747
19748 @smallexample @c ada
19749 with System.Dim.MKS; use System.Dim.Mks;
19750 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
19751 with Text_IO; use Text_IO;
19752 procedure Free_Fall is
19753 subtype Acceleration is Mks_Type
19754 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
19755 G : constant acceleration := 9.81 * m / (s ** 2);
19756 T : Time := 10.0*s;
19757 Distance : Length;
19758 begin
19759 Put ("Gravitational constant: ");
19760 Put (G, Aft => 2, Exp => 0); Put_Line ("");
19761 Distance := 0.5 * G * T ** 2;
19762 Put ("distance travelled in 10 seconds of free fall ");
19763 Put (Distance, Aft => 2, Exp => 0);
19764 Put_Line ("");
19765 end Free_Fall;
19766 @end smallexample
19767
19768 @noindent
19769 Execution of this program yields:
19770 @smallexample
19771 Gravitational constant: 9.81 m/sec^^^2
19772 distance travelled in 10 seconds of free fall 490.50 m
19773 @end smallexample
19774
19775 @noindent
19776 However, incorrect assignments such as:
19777
19778 @smallexample @c ada
19779 Distance := 5.0;
19780 Distance := 5.0 * kg:
19781 @end smallexample
19782
19783 @noindent
19784 are rejected with the following diagnoses:
19785
19786 @smallexample
19787 Distance := 5.0;
19788 >>> dimensions mismatch in assignment
19789 >>> left-hand side has dimension [L]
19790 >>> right-hand side is dimensionless
19791
19792 Distance := 5.0 * kg:
19793 >>> dimensions mismatch in assignment
19794 >>> left-hand side has dimension [L]
19795 >>> right-hand side has dimension [M]
19796 @end smallexample
19797
19798 @noindent
19799 The dimensions of an expression are properly displayed, even if there is
19800 no explicit subtype for it. If we add to the program:
19801
19802 @smallexample @c ada
19803 Put ("Final velocity: ");
19804 Put (G * T, Aft =>2, Exp =>0);
19805 Put_Line ("");
19806 @end smallexample
19807
19808 @noindent
19809 then the output includes:
19810 @smallexample
19811 Final velocity: 98.10 m.s**(-1)
19812 @end smallexample
19813
19814 @c *********************************
19815 @node Generating Ada Bindings for C and C++ headers
19816 @chapter Generating Ada Bindings for C and C++ headers
19817 @findex binding
19818
19819 @noindent
19820 GNAT now comes with a binding generator for C and C++ headers which is
19821 intended to do 95% of the tedious work of generating Ada specs from C
19822 or C++ header files.
19823
19824 Note that this capability is not intended to generate 100% correct Ada specs,
19825 and will is some cases require manual adjustments, although it can often
19826 be used out of the box in practice.
19827
19828 Some of the known limitations include:
19829
19830 @itemize @bullet
19831 @item only very simple character constant macros are translated into Ada
19832 constants. Function macros (macros with arguments) are partially translated
19833 as comments, to be completed manually if needed.
19834 @item some extensions (e.g. vector types) are not supported
19835 @item pointers to pointers or complex structures are mapped to System.Address
19836 @item identifiers with identical name (except casing) will generate compilation
19837 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19838 @end itemize
19839
19840 The code generated is using the Ada 2005 syntax, which makes it
19841 easier to interface with other languages than previous versions of Ada.
19842
19843 @menu
19844 * Running the binding generator::
19845 * Generating bindings for C++ headers::
19846 * Switches::
19847 @end menu
19848
19849 @node Running the binding generator
19850 @section Running the binding generator
19851
19852 @noindent
19853 The binding generator is part of the @command{gcc} compiler and can be
19854 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19855 spec files for the header files specified on the command line, and all
19856 header files needed by these files transitively. For example:
19857
19858 @smallexample
19859 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19860 $ gcc -c -gnat05 *.ads
19861 @end smallexample
19862
19863 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19864 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19865 correspond to the files @file{/usr/include/time.h},
19866 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19867 mode these Ada specs.
19868
19869 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19870 and will attempt to generate corresponding Ada comments.
19871
19872 If you want to generate a single Ada file and not the transitive closure, you
19873 can use instead the @option{-fdump-ada-spec-slim} switch.
19874
19875 You can optionally specify a parent unit, of which all generated units will
19876 be children, using @code{-fada-spec-parent=}@var{unit}.
19877
19878 Note that we recommend when possible to use the @command{g++} driver to
19879 generate bindings, even for most C headers, since this will in general
19880 generate better Ada specs. For generating bindings for C++ headers, it is
19881 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19882 is equivalent in this case. If @command{g++} cannot work on your C headers
19883 because of incompatibilities between C and C++, then you can fallback to
19884 @command{gcc} instead.
19885
19886 For an example of better bindings generated from the C++ front-end,
19887 the name of the parameters (when available) are actually ignored by the C
19888 front-end. Consider the following C header:
19889
19890 @smallexample
19891 extern void foo (int variable);
19892 @end smallexample
19893
19894 with the C front-end, @code{variable} is ignored, and the above is handled as:
19895
19896 @smallexample
19897 extern void foo (int);
19898 @end smallexample
19899
19900 generating a generic:
19901
19902 @smallexample
19903 procedure foo (param1 : int);
19904 @end smallexample
19905
19906 with the C++ front-end, the name is available, and we generate:
19907
19908 @smallexample
19909 procedure foo (variable : int);
19910 @end smallexample
19911
19912 In some cases, the generated bindings will be more complete or more meaningful
19913 when defining some macros, which you can do via the @option{-D} switch. This
19914 is for example the case with @file{Xlib.h} under GNU/Linux:
19915
19916 @smallexample
19917 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19918 @end smallexample
19919
19920 The above will generate more complete bindings than a straight call without
19921 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19922
19923 In other cases, it is not possible to parse a header file in a stand-alone
19924 manner, because other include files need to be included first. In this
19925 case, the solution is to create a small header file including the needed
19926 @code{#include} and possible @code{#define} directives. For example, to
19927 generate Ada bindings for @file{readline/readline.h}, you need to first
19928 include @file{stdio.h}, so you can create a file with the following two
19929 lines in e.g. @file{readline1.h}:
19930
19931 @smallexample
19932 #include <stdio.h>
19933 #include <readline/readline.h>
19934 @end smallexample
19935
19936 and then generate Ada bindings from this file:
19937
19938 @smallexample
19939 $ g++ -c -fdump-ada-spec readline1.h
19940 @end smallexample
19941
19942 @node Generating bindings for C++ headers
19943 @section Generating bindings for C++ headers
19944
19945 @noindent
19946 Generating bindings for C++ headers is done using the same options, always
19947 with the @command{g++} compiler.
19948
19949 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19950 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19951 multiple inheritance of abstract classes will be mapped to Ada interfaces
19952 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19953 information on interfacing to C++).
19954
19955 For example, given the following C++ header file:
19956
19957 @smallexample
19958 @group
19959 @cartouche
19960 class Carnivore @{
19961 public:
19962 virtual int Number_Of_Teeth () = 0;
19963 @};
19964
19965 class Domestic @{
19966 public:
19967 virtual void Set_Owner (char* Name) = 0;
19968 @};
19969
19970 class Animal @{
19971 public:
19972 int Age_Count;
19973 virtual void Set_Age (int New_Age);
19974 @};
19975
19976 class Dog : Animal, Carnivore, Domestic @{
19977 public:
19978 int Tooth_Count;
19979 char *Owner;
19980
19981 virtual int Number_Of_Teeth ();
19982 virtual void Set_Owner (char* Name);
19983
19984 Dog();
19985 @};
19986 @end cartouche
19987 @end group
19988 @end smallexample
19989
19990 The corresponding Ada code is generated:
19991
19992 @smallexample @c ada
19993 @group
19994 @cartouche
19995 package Class_Carnivore is
19996 type Carnivore is limited interface;
19997 pragma Import (CPP, Carnivore);
19998
19999 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20000 end;
20001 use Class_Carnivore;
20002
20003 package Class_Domestic is
20004 type Domestic is limited interface;
20005 pragma Import (CPP, Domestic);
20006
20007 procedure Set_Owner
20008 (this : access Domestic;
20009 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20010 end;
20011 use Class_Domestic;
20012
20013 package Class_Animal is
20014 type Animal is tagged limited record
20015 Age_Count : aliased int;
20016 end record;
20017 pragma Import (CPP, Animal);
20018
20019 procedure Set_Age (this : access Animal; New_Age : int);
20020 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20021 end;
20022 use Class_Animal;
20023
20024 package Class_Dog is
20025 type Dog is new Animal and Carnivore and Domestic with record
20026 Tooth_Count : aliased int;
20027 Owner : Interfaces.C.Strings.chars_ptr;
20028 end record;
20029 pragma Import (CPP, Dog);
20030
20031 function Number_Of_Teeth (this : access Dog) return int;
20032 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20033
20034 procedure Set_Owner
20035 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20036 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20037
20038 function New_Dog return Dog;
20039 pragma CPP_Constructor (New_Dog);
20040 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20041 end;
20042 use Class_Dog;
20043 @end cartouche
20044 @end group
20045 @end smallexample
20046
20047 @node Switches
20048 @section Switches
20049
20050 @table @option
20051 @item -fdump-ada-spec
20052 @cindex @option{-fdump-ada-spec} (@command{gcc})
20053 Generate Ada spec files for the given header files transitively (including
20054 all header files that these headers depend upon).
20055
20056 @item -fdump-ada-spec-slim
20057 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20058 Generate Ada spec files for the header files specified on the command line
20059 only.
20060
20061 @item -fada-spec-parent=@var{unit}
20062 @cindex -fada-spec-parent (@command{gcc})
20063 Specifies that all files generated by @option{-fdump-ada-spec*} are
20064 to be child units of the specified parent unit.
20065
20066 @item -C
20067 @cindex @option{-C} (@command{gcc})
20068 Extract comments from headers and generate Ada comments in the Ada spec files.
20069 @end table
20070
20071 @node Other Utility Programs
20072 @chapter Other Utility Programs
20073
20074 @noindent
20075 This chapter discusses some other utility programs available in the Ada
20076 environment.
20077
20078 @menu
20079 * Using Other Utility Programs with GNAT::
20080 * The External Symbol Naming Scheme of GNAT::
20081 * Converting Ada Files to html with gnathtml::
20082 * Installing gnathtml::
20083 @ifset vms
20084 * LSE::
20085 * Profiling::
20086 @end ifset
20087 @end menu
20088
20089 @node Using Other Utility Programs with GNAT
20090 @section Using Other Utility Programs with GNAT
20091
20092 @noindent
20093 The object files generated by GNAT are in standard system format and in
20094 particular the debugging information uses this format. This means
20095 programs generated by GNAT can be used with existing utilities that
20096 depend on these formats.
20097
20098 @ifclear vms
20099 In general, any utility program that works with C will also often work with
20100 Ada programs generated by GNAT. This includes software utilities such as
20101 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20102 as Purify.
20103 @end ifclear
20104
20105 @node The External Symbol Naming Scheme of GNAT
20106 @section The External Symbol Naming Scheme of GNAT
20107
20108 @noindent
20109 In order to interpret the output from GNAT, when using tools that are
20110 originally intended for use with other languages, it is useful to
20111 understand the conventions used to generate link names from the Ada
20112 entity names.
20113
20114 All link names are in all lowercase letters. With the exception of library
20115 procedure names, the mechanism used is simply to use the full expanded
20116 Ada name with dots replaced by double underscores. For example, suppose
20117 we have the following package spec:
20118
20119 @smallexample @c ada
20120 @group
20121 @cartouche
20122 package QRS is
20123 MN : Integer;
20124 end QRS;
20125 @end cartouche
20126 @end group
20127 @end smallexample
20128
20129 @noindent
20130 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20131 the corresponding link name is @code{qrs__mn}.
20132 @findex Export
20133 Of course if a @code{pragma Export} is used this may be overridden:
20134
20135 @smallexample @c ada
20136 @group
20137 @cartouche
20138 package Exports is
20139 Var1 : Integer;
20140 pragma Export (Var1, C, External_Name => "var1_name");
20141 Var2 : Integer;
20142 pragma Export (Var2, C, Link_Name => "var2_link_name");
20143 end Exports;
20144 @end cartouche
20145 @end group
20146 @end smallexample
20147
20148 @noindent
20149 In this case, the link name for @var{Var1} is whatever link name the
20150 C compiler would assign for the C function @var{var1_name}. This typically
20151 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20152 system conventions, but other possibilities exist. The link name for
20153 @var{Var2} is @var{var2_link_name}, and this is not operating system
20154 dependent.
20155
20156 @findex _main
20157 One exception occurs for library level procedures. A potential ambiguity
20158 arises between the required name @code{_main} for the C main program,
20159 and the name we would otherwise assign to an Ada library level procedure
20160 called @code{Main} (which might well not be the main program).
20161
20162 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20163 names. So if we have a library level procedure such as
20164
20165 @smallexample @c ada
20166 @group
20167 @cartouche
20168 procedure Hello (S : String);
20169 @end cartouche
20170 @end group
20171 @end smallexample
20172
20173 @noindent
20174 the external name of this procedure will be @var{_ada_hello}.
20175
20176
20177 @node Converting Ada Files to html with gnathtml
20178 @section Converting Ada Files to HTML with @code{gnathtml}
20179
20180 @noindent
20181 This @code{Perl} script allows Ada source files to be browsed using
20182 standard Web browsers. For installation procedure, see the section
20183 @xref{Installing gnathtml}.
20184
20185 Ada reserved keywords are highlighted in a bold font and Ada comments in
20186 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20187 switch to suppress the generation of cross-referencing information, user
20188 defined variables and types will appear in a different color; you will
20189 be able to click on any identifier and go to its declaration.
20190
20191 The command line is as follow:
20192 @smallexample
20193 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20194 @c Expanding @ovar macro inline (explanation in macro def comments)
20195 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20196 @end smallexample
20197
20198 @noindent
20199 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20200 an html file for every ada file, and a global file called @file{index.htm}.
20201 This file is an index of every identifier defined in the files.
20202
20203 The available ^switches^options^ are the following ones:
20204
20205 @table @option
20206 @item -83
20207 @cindex @option{-83} (@code{gnathtml})
20208 Only the Ada 83 subset of keywords will be highlighted.
20209
20210 @item -cc @var{color}
20211 @cindex @option{-cc} (@code{gnathtml})
20212 This option allows you to change the color used for comments. The default
20213 value is green. The color argument can be any name accepted by html.
20214
20215 @item -d
20216 @cindex @option{-d} (@code{gnathtml})
20217 If the Ada files depend on some other files (for instance through
20218 @code{with} clauses, the latter files will also be converted to html.
20219 Only the files in the user project will be converted to html, not the files
20220 in the run-time library itself.
20221
20222 @item -D
20223 @cindex @option{-D} (@code{gnathtml})
20224 This command is the same as @option{-d} above, but @command{gnathtml} will
20225 also look for files in the run-time library, and generate html files for them.
20226
20227 @item -ext @var{extension}
20228 @cindex @option{-ext} (@code{gnathtml})
20229 This option allows you to change the extension of the generated HTML files.
20230 If you do not specify an extension, it will default to @file{htm}.
20231
20232 @item -f
20233 @cindex @option{-f} (@code{gnathtml})
20234 By default, gnathtml will generate html links only for global entities
20235 ('with'ed units, global variables and types,@dots{}). If you specify
20236 @option{-f} on the command line, then links will be generated for local
20237 entities too.
20238
20239 @item -l @var{number}
20240 @cindex @option{-l} (@code{gnathtml})
20241 If this ^switch^option^ is provided and @var{number} is not 0, then
20242 @code{gnathtml} will number the html files every @var{number} line.
20243
20244 @item -I @var{dir}
20245 @cindex @option{-I} (@code{gnathtml})
20246 Specify a directory to search for library files (@file{.ALI} files) and
20247 source files. You can provide several -I switches on the command line,
20248 and the directories will be parsed in the order of the command line.
20249
20250 @item -o @var{dir}
20251 @cindex @option{-o} (@code{gnathtml})
20252 Specify the output directory for html files. By default, gnathtml will
20253 saved the generated html files in a subdirectory named @file{html/}.
20254
20255 @item -p @var{file}
20256 @cindex @option{-p} (@code{gnathtml})
20257 If you are using Emacs and the most recent Emacs Ada mode, which provides
20258 a full Integrated Development Environment for compiling, checking,
20259 running and debugging applications, you may use @file{.gpr} files
20260 to give the directories where Emacs can find sources and object files.
20261
20262 Using this ^switch^option^, you can tell gnathtml to use these files.
20263 This allows you to get an html version of your application, even if it
20264 is spread over multiple directories.
20265
20266 @item -sc @var{color}
20267 @cindex @option{-sc} (@code{gnathtml})
20268 This ^switch^option^ allows you to change the color used for symbol
20269 definitions.
20270 The default value is red. The color argument can be any name accepted by html.
20271
20272 @item -t @var{file}
20273 @cindex @option{-t} (@code{gnathtml})
20274 This ^switch^option^ provides the name of a file. This file contains a list of
20275 file names to be converted, and the effect is exactly as though they had
20276 appeared explicitly on the command line. This
20277 is the recommended way to work around the command line length limit on some
20278 systems.
20279
20280 @end table
20281
20282 @node Installing gnathtml
20283 @section Installing @code{gnathtml}
20284
20285 @noindent
20286 @code{Perl} needs to be installed on your machine to run this script.
20287 @code{Perl} is freely available for almost every architecture and
20288 Operating System via the Internet.
20289
20290 On Unix systems, you may want to modify the first line of the script
20291 @code{gnathtml}, to explicitly tell the Operating system where Perl
20292 is. The syntax of this line is:
20293 @smallexample
20294 #!full_path_name_to_perl
20295 @end smallexample
20296
20297 @noindent
20298 Alternatively, you may run the script using the following command line:
20299
20300 @smallexample
20301 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20302 @c Expanding @ovar macro inline (explanation in macro def comments)
20303 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20304 @end smallexample
20305
20306 @ifset vms
20307 @node LSE
20308 @section LSE
20309 @findex LSE
20310
20311 @noindent
20312 The GNAT distribution provides an Ada 95 template for the HP Language
20313 Sensitive Editor (LSE), a component of DECset. In order to
20314 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20315
20316 @node Profiling
20317 @section Profiling
20318 @findex PCA
20319
20320 @noindent
20321 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20322 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20323 the collection phase with the /DEBUG qualifier.
20324
20325 @smallexample
20326 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20327 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20328 $ RUN/DEBUG <PROGRAM_NAME>
20329 @end smallexample
20330 @noindent
20331 @end ifset
20332
20333 @ifclear vms
20334 @c ******************************
20335 @node Code Coverage and Profiling
20336 @chapter Code Coverage and Profiling
20337 @cindex Code Coverage
20338 @cindex Profiling
20339
20340 @noindent
20341 This chapter describes how to use @code{gcov} - coverage testing tool - and
20342 @code{gprof} - profiler tool - on your Ada programs.
20343
20344 @menu
20345 * Code Coverage of Ada Programs using gcov::
20346 * Profiling an Ada Program using gprof::
20347 @end menu
20348
20349 @node Code Coverage of Ada Programs using gcov
20350 @section Code Coverage of Ada Programs using gcov
20351 @cindex gcov
20352 @cindex -fprofile-arcs
20353 @cindex -ftest-coverage
20354 @cindex -coverage
20355 @cindex Code Coverage
20356
20357 @noindent
20358 @code{gcov} is a test coverage program: it analyzes the execution of a given
20359 program on selected tests, to help you determine the portions of the program
20360 that are still untested.
20361
20362 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20363 User's Guide. You can refer to this documentation for a more complete
20364 description.
20365
20366 This chapter provides a quick startup guide, and
20367 details some Gnat-specific features.
20368
20369 @menu
20370 * Quick startup guide::
20371 * Gnat specifics::
20372 @end menu
20373
20374 @node Quick startup guide
20375 @subsection Quick startup guide
20376
20377 In order to perform coverage analysis of a program using @code{gcov}, 3
20378 steps are needed:
20379
20380 @itemize @bullet
20381 @item
20382 Code instrumentation during the compilation process
20383 @item
20384 Execution of the instrumented program
20385 @item
20386 Execution of the @code{gcov} tool to generate the result.
20387 @end itemize
20388
20389 The code instrumentation needed by gcov is created at the object level:
20390 The source code is not modified in any way, because the instrumentation code is
20391 inserted by gcc during the compilation process. To compile your code with code
20392 coverage activated, you need to recompile your whole project using the
20393 switches
20394 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20395 @code{-fprofile-arcs}.
20396
20397 @smallexample
20398 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20399 -largs -fprofile-arcs
20400 @end smallexample
20401
20402 This compilation process will create @file{.gcno} files together with
20403 the usual object files.
20404
20405 Once the program is compiled with coverage instrumentation, you can
20406 run it as many times as needed - on portions of a test suite for
20407 example. The first execution will produce @file{.gcda} files at the
20408 same location as the @file{.gcno} files. The following executions
20409 will update those files, so that a cumulative result of the covered
20410 portions of the program is generated.
20411
20412 Finally, you need to call the @code{gcov} tool. The different options of
20413 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20414
20415 This will create annotated source files with a @file{.gcov} extension:
20416 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20417
20418 @node Gnat specifics
20419 @subsection Gnat specifics
20420
20421 Because Ada semantics, portions of the source code may be shared among
20422 several object files. This is the case for example when generics are
20423 involved, when inlining is active or when declarations generate initialisation
20424 calls. In order to take
20425 into account this shared code, you need to call @code{gcov} on all
20426 source files of the tested program at once.
20427
20428 The list of source files might exceed the system's maximum command line
20429 length. In order to bypass this limitation, a new mechanism has been
20430 implemented in @code{gcov}: you can now list all your project's files into a
20431 text file, and provide this file to gcov as a parameter, preceded by a @@
20432 (e.g. @samp{gcov @@mysrclist.txt}).
20433
20434 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20435 not supported as there can be unresolved symbols during the final link.
20436
20437 @node Profiling an Ada Program using gprof
20438 @section Profiling an Ada Program using gprof
20439 @cindex gprof
20440 @cindex -pg
20441 @cindex Profiling
20442
20443 @noindent
20444 This section is not meant to be an exhaustive documentation of @code{gprof}.
20445 Full documentation for it can be found in the GNU Profiler User's Guide
20446 documentation that is part of this GNAT distribution.
20447
20448 Profiling a program helps determine the parts of a program that are executed
20449 most often, and are therefore the most time-consuming.
20450
20451 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20452 better handle Ada programs and multitasking.
20453 It is currently supported on the following platforms
20454 @itemize @bullet
20455 @item
20456 linux x86/x86_64
20457 @item
20458 solaris sparc/sparc64/x86
20459 @item
20460 windows x86
20461 @end itemize
20462
20463 @noindent
20464 In order to profile a program using @code{gprof}, 3 steps are needed:
20465
20466 @itemize @bullet
20467 @item
20468 Code instrumentation, requiring a full recompilation of the project with the
20469 proper switches.
20470 @item
20471 Execution of the program under the analysis conditions, i.e. with the desired
20472 input.
20473 @item
20474 Analysis of the results using the @code{gprof} tool.
20475 @end itemize
20476
20477 @noindent
20478 The following sections detail the different steps, and indicate how
20479 to interpret the results:
20480 @menu
20481 * Compilation for profiling::
20482 * Program execution::
20483 * Running gprof::
20484 * Interpretation of profiling results::
20485 @end menu
20486
20487 @node Compilation for profiling
20488 @subsection Compilation for profiling
20489 @cindex -pg
20490 @cindex Profiling
20491
20492 In order to profile a program the first step is to tell the compiler
20493 to generate the necessary profiling information. The compiler switch to be used
20494 is @code{-pg}, which must be added to other compilation switches. This
20495 switch needs to be specified both during compilation and link stages, and can
20496 be specified once when using gnatmake:
20497
20498 @smallexample
20499 gnatmake -f -pg -P my_project
20500 @end smallexample
20501
20502 @noindent
20503 Note that only the objects that were compiled with the @samp{-pg} switch will
20504 be profiled; if you need to profile your whole project, use the @samp{-f}
20505 gnatmake switch to force full recompilation.
20506
20507 @node Program execution
20508 @subsection Program execution
20509
20510 @noindent
20511 Once the program has been compiled for profiling, you can run it as usual.
20512
20513 The only constraint imposed by profiling is that the program must terminate
20514 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20515 properly analyzed.
20516
20517 Once the program completes execution, a data file called @file{gmon.out} is
20518 generated in the directory where the program was launched from. If this file
20519 already exists, it will be overwritten.
20520
20521 @node Running gprof
20522 @subsection Running gprof
20523
20524 @noindent
20525 The @code{gprof} tool is called as follow:
20526
20527 @smallexample
20528 gprof my_prog gmon.out
20529 @end smallexample
20530
20531 @noindent
20532 or simpler:
20533
20534 @smallexample
20535 gprof my_prog
20536 @end smallexample
20537
20538 @noindent
20539 The complete form of the gprof command line is the following:
20540
20541 @smallexample
20542 gprof [^switches^options^] [executable [data-file]]
20543 @end smallexample
20544
20545 @noindent
20546 @code{gprof} supports numerous ^switch^options^. The order of these
20547 ^switch^options^ does not matter. The full list of options can be found in
20548 the GNU Profiler User's Guide documentation that comes with this documentation.
20549
20550 The following is the subset of those switches that is most relevant:
20551
20552 @table @option
20553
20554 @item --demangle[=@var{style}]
20555 @itemx --no-demangle
20556 @cindex @option{--demangle} (@code{gprof})
20557 These options control whether symbol names should be demangled when
20558 printing output. The default is to demangle C++ symbols. The
20559 @code{--no-demangle} option may be used to turn off demangling. Different
20560 compilers have different mangling styles. The optional demangling style
20561 argument can be used to choose an appropriate demangling style for your
20562 compiler, in particular Ada symbols generated by GNAT can be demangled using
20563 @code{--demangle=gnat}.
20564
20565 @item -e @var{function_name}
20566 @cindex @option{-e} (@code{gprof})
20567 The @samp{-e @var{function}} option tells @code{gprof} not to print
20568 information about the function @var{function_name} (and its
20569 children@dots{}) in the call graph. The function will still be listed
20570 as a child of any functions that call it, but its index number will be
20571 shown as @samp{[not printed]}. More than one @samp{-e} option may be
20572 given; only one @var{function_name} may be indicated with each @samp{-e}
20573 option.
20574
20575 @item -E @var{function_name}
20576 @cindex @option{-E} (@code{gprof})
20577 The @code{-E @var{function}} option works like the @code{-e} option, but
20578 execution time spent in the function (and children who were not called from
20579 anywhere else), will not be used to compute the percentages-of-time for
20580 the call graph. More than one @samp{-E} option may be given; only one
20581 @var{function_name} may be indicated with each @samp{-E} option.
20582
20583 @item -f @var{function_name}
20584 @cindex @option{-f} (@code{gprof})
20585 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20586 call graph to the function @var{function_name} and its children (and
20587 their children@dots{}). More than one @samp{-f} option may be given;
20588 only one @var{function_name} may be indicated with each @samp{-f}
20589 option.
20590
20591 @item -F @var{function_name}
20592 @cindex @option{-F} (@code{gprof})
20593 The @samp{-F @var{function}} option works like the @code{-f} option, but
20594 only time spent in the function and its children (and their
20595 children@dots{}) will be used to determine total-time and
20596 percentages-of-time for the call graph. More than one @samp{-F} option
20597 may be given; only one @var{function_name} may be indicated with each
20598 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
20599
20600 @end table
20601
20602 @node Interpretation of profiling results
20603 @subsection Interpretation of profiling results
20604
20605 @noindent
20606
20607 The results of the profiling analysis are represented by two arrays: the
20608 'flat profile' and the 'call graph'. Full documentation of those outputs
20609 can be found in the GNU Profiler User's Guide.
20610
20611 The flat profile shows the time spent in each function of the program, and how
20612 many time it has been called. This allows you to locate easily the most
20613 time-consuming functions.
20614
20615 The call graph shows, for each subprogram, the subprograms that call it,
20616 and the subprograms that it calls. It also provides an estimate of the time
20617 spent in each of those callers/called subprograms.
20618 @end ifclear
20619
20620 @c ******************************
20621 @node Running and Debugging Ada Programs
20622 @chapter Running and Debugging Ada Programs
20623 @cindex Debugging
20624
20625 @noindent
20626 This chapter discusses how to debug Ada programs.
20627 @ifset vms
20628 It applies to GNAT on the Alpha OpenVMS platform;
20629 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20630 since HP has implemented Ada support in the OpenVMS debugger on I64.
20631 @end ifset
20632
20633 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20634
20635 @enumerate
20636 @item
20637 The illegality may be a violation of the static semantics of Ada. In
20638 that case GNAT diagnoses the constructs in the program that are illegal.
20639 It is then a straightforward matter for the user to modify those parts of
20640 the program.
20641
20642 @item
20643 The illegality may be a violation of the dynamic semantics of Ada. In
20644 that case the program compiles and executes, but may generate incorrect
20645 results, or may terminate abnormally with some exception.
20646
20647 @item
20648 When presented with a program that contains convoluted errors, GNAT
20649 itself may terminate abnormally without providing full diagnostics on
20650 the incorrect user program.
20651 @end enumerate
20652
20653 @menu
20654 * The GNAT Debugger GDB::
20655 * Running GDB::
20656 * Introduction to GDB Commands::
20657 * Using Ada Expressions::
20658 * Calling User-Defined Subprograms::
20659 * Using the Next Command in a Function::
20660 * Ada Exceptions::
20661 * Ada Tasks::
20662 * Debugging Generic Units::
20663 * Remote Debugging using gdbserver::
20664 * GNAT Abnormal Termination or Failure to Terminate::
20665 * Naming Conventions for GNAT Source Files::
20666 * Getting Internal Debugging Information::
20667 * Stack Traceback::
20668 @end menu
20669
20670 @cindex Debugger
20671 @findex gdb
20672
20673 @node The GNAT Debugger GDB
20674 @section The GNAT Debugger GDB
20675
20676 @noindent
20677 @code{GDB} is a general purpose, platform-independent debugger that
20678 can be used to debug mixed-language programs compiled with @command{gcc},
20679 and in particular is capable of debugging Ada programs compiled with
20680 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20681 complex Ada data structures.
20682
20683 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20684 @ifset vms
20685 located in the GNU:[DOCS] directory,
20686 @end ifset
20687 for full details on the usage of @code{GDB}, including a section on
20688 its usage on programs. This manual should be consulted for full
20689 details. The section that follows is a brief introduction to the
20690 philosophy and use of @code{GDB}.
20691
20692 When GNAT programs are compiled, the compiler optionally writes debugging
20693 information into the generated object file, including information on
20694 line numbers, and on declared types and variables. This information is
20695 separate from the generated code. It makes the object files considerably
20696 larger, but it does not add to the size of the actual executable that
20697 will be loaded into memory, and has no impact on run-time performance. The
20698 generation of debug information is triggered by the use of the
20699 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20700 used to carry out the compilations. It is important to emphasize that
20701 the use of these options does not change the generated code.
20702
20703 The debugging information is written in standard system formats that
20704 are used by many tools, including debuggers and profilers. The format
20705 of the information is typically designed to describe C types and
20706 semantics, but GNAT implements a translation scheme which allows full
20707 details about Ada types and variables to be encoded into these
20708 standard C formats. Details of this encoding scheme may be found in
20709 the file exp_dbug.ads in the GNAT source distribution. However, the
20710 details of this encoding are, in general, of no interest to a user,
20711 since @code{GDB} automatically performs the necessary decoding.
20712
20713 When a program is bound and linked, the debugging information is
20714 collected from the object files, and stored in the executable image of
20715 the program. Again, this process significantly increases the size of
20716 the generated executable file, but it does not increase the size of
20717 the executable program itself. Furthermore, if this program is run in
20718 the normal manner, it runs exactly as if the debug information were
20719 not present, and takes no more actual memory.
20720
20721 However, if the program is run under control of @code{GDB}, the
20722 debugger is activated. The image of the program is loaded, at which
20723 point it is ready to run. If a run command is given, then the program
20724 will run exactly as it would have if @code{GDB} were not present. This
20725 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
20726 entirely non-intrusive until a breakpoint is encountered. If no
20727 breakpoint is ever hit, the program will run exactly as it would if no
20728 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20729 the debugging information and can respond to user commands to inspect
20730 variables, and more generally to report on the state of execution.
20731
20732 @c **************
20733 @node Running GDB
20734 @section Running GDB
20735
20736 @noindent
20737 This section describes how to initiate the debugger.
20738 @c The above sentence is really just filler, but it was otherwise
20739 @c clumsy to get the first paragraph nonindented given the conditional
20740 @c nature of the description
20741
20742 @ifclear vms
20743 The debugger can be launched from a @code{GPS} menu or
20744 directly from the command line. The description below covers the latter use.
20745 All the commands shown can be used in the @code{GPS} debug console window,
20746 but there are usually more GUI-based ways to achieve the same effect.
20747 @end ifclear
20748
20749 The command to run @code{GDB} is
20750
20751 @smallexample
20752 $ ^gdb program^GDB PROGRAM^
20753 @end smallexample
20754
20755 @noindent
20756 where @code{^program^PROGRAM^} is the name of the executable file. This
20757 activates the debugger and results in a prompt for debugger commands.
20758 The simplest command is simply @code{run}, which causes the program to run
20759 exactly as if the debugger were not present. The following section
20760 describes some of the additional commands that can be given to @code{GDB}.
20761
20762 @c *******************************
20763 @node Introduction to GDB Commands
20764 @section Introduction to GDB Commands
20765
20766 @noindent
20767 @code{GDB} contains a large repertoire of commands. @xref{Top,,
20768 Debugging with GDB, gdb, Debugging with GDB},
20769 @ifset vms
20770 located in the GNU:[DOCS] directory,
20771 @end ifset
20772 for extensive documentation on the use
20773 of these commands, together with examples of their use. Furthermore,
20774 the command @command{help} invoked from within GDB activates a simple help
20775 facility which summarizes the available commands and their options.
20776 In this section we summarize a few of the most commonly
20777 used commands to give an idea of what @code{GDB} is about. You should create
20778 a simple program with debugging information and experiment with the use of
20779 these @code{GDB} commands on the program as you read through the
20780 following section.
20781
20782 @table @code
20783 @item set args @var{arguments}
20784 The @var{arguments} list above is a list of arguments to be passed to
20785 the program on a subsequent run command, just as though the arguments
20786 had been entered on a normal invocation of the program. The @code{set args}
20787 command is not needed if the program does not require arguments.
20788
20789 @item run
20790 The @code{run} command causes execution of the program to start from
20791 the beginning. If the program is already running, that is to say if
20792 you are currently positioned at a breakpoint, then a prompt will ask
20793 for confirmation that you want to abandon the current execution and
20794 restart.
20795
20796 @item breakpoint @var{location}
20797 The breakpoint command sets a breakpoint, that is to say a point at which
20798 execution will halt and @code{GDB} will await further
20799 commands. @var{location} is
20800 either a line number within a file, given in the format @code{file:linenumber},
20801 or it is the name of a subprogram. If you request that a breakpoint be set on
20802 a subprogram that is overloaded, a prompt will ask you to specify on which of
20803 those subprograms you want to breakpoint. You can also
20804 specify that all of them should be breakpointed. If the program is run
20805 and execution encounters the breakpoint, then the program
20806 stops and @code{GDB} signals that the breakpoint was encountered by
20807 printing the line of code before which the program is halted.
20808
20809 @item catch exception @var{name}
20810 This command causes the program execution to stop whenever exception
20811 @var{name} is raised. If @var{name} is omitted, then the execution is
20812 suspended when any exception is raised.
20813
20814 @item print @var{expression}
20815 This will print the value of the given expression. Most simple
20816 Ada expression formats are properly handled by @code{GDB}, so the expression
20817 can contain function calls, variables, operators, and attribute references.
20818
20819 @item continue
20820 Continues execution following a breakpoint, until the next breakpoint or the
20821 termination of the program.
20822
20823 @item step
20824 Executes a single line after a breakpoint. If the next statement
20825 is a subprogram call, execution continues into (the first statement of)
20826 the called subprogram.
20827
20828 @item next
20829 Executes a single line. If this line is a subprogram call, executes and
20830 returns from the call.
20831
20832 @item list
20833 Lists a few lines around the current source location. In practice, it
20834 is usually more convenient to have a separate edit window open with the
20835 relevant source file displayed. Successive applications of this command
20836 print subsequent lines. The command can be given an argument which is a
20837 line number, in which case it displays a few lines around the specified one.
20838
20839 @item backtrace
20840 Displays a backtrace of the call chain. This command is typically
20841 used after a breakpoint has occurred, to examine the sequence of calls that
20842 leads to the current breakpoint. The display includes one line for each
20843 activation record (frame) corresponding to an active subprogram.
20844
20845 @item up
20846 At a breakpoint, @code{GDB} can display the values of variables local
20847 to the current frame. The command @code{up} can be used to
20848 examine the contents of other active frames, by moving the focus up
20849 the stack, that is to say from callee to caller, one frame at a time.
20850
20851 @item down
20852 Moves the focus of @code{GDB} down from the frame currently being
20853 examined to the frame of its callee (the reverse of the previous command),
20854
20855 @item frame @var{n}
20856 Inspect the frame with the given number. The value 0 denotes the frame
20857 of the current breakpoint, that is to say the top of the call stack.
20858
20859 @end table
20860
20861 @noindent
20862 The above list is a very short introduction to the commands that
20863 @code{GDB} provides. Important additional capabilities, including conditional
20864 breakpoints, the ability to execute command sequences on a breakpoint,
20865 the ability to debug at the machine instruction level and many other
20866 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20867 Debugging with GDB}. Note that most commands can be abbreviated
20868 (for example, c for continue, bt for backtrace).
20869
20870 @node Using Ada Expressions
20871 @section Using Ada Expressions
20872 @cindex Ada expressions
20873
20874 @noindent
20875 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20876 extensions. The philosophy behind the design of this subset is
20877
20878 @itemize @bullet
20879 @item
20880 That @code{GDB} should provide basic literals and access to operations for
20881 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20882 leaving more sophisticated computations to subprograms written into the
20883 program (which therefore may be called from @code{GDB}).
20884
20885 @item
20886 That type safety and strict adherence to Ada language restrictions
20887 are not particularly important to the @code{GDB} user.
20888
20889 @item
20890 That brevity is important to the @code{GDB} user.
20891 @end itemize
20892
20893 @noindent
20894 Thus, for brevity, the debugger acts as if there were
20895 implicit @code{with} and @code{use} clauses in effect for all user-written
20896 packages, thus making it unnecessary to fully qualify most names with
20897 their packages, regardless of context. Where this causes ambiguity,
20898 @code{GDB} asks the user's intent.
20899
20900 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20901 GDB, gdb, Debugging with GDB}.
20902
20903 @node Calling User-Defined Subprograms
20904 @section Calling User-Defined Subprograms
20905
20906 @noindent
20907 An important capability of @code{GDB} is the ability to call user-defined
20908 subprograms while debugging. This is achieved simply by entering
20909 a subprogram call statement in the form:
20910
20911 @smallexample
20912 call subprogram-name (parameters)
20913 @end smallexample
20914
20915 @noindent
20916 The keyword @code{call} can be omitted in the normal case where the
20917 @code{subprogram-name} does not coincide with any of the predefined
20918 @code{GDB} commands.
20919
20920 The effect is to invoke the given subprogram, passing it the
20921 list of parameters that is supplied. The parameters can be expressions and
20922 can include variables from the program being debugged. The
20923 subprogram must be defined
20924 at the library level within your program, and @code{GDB} will call the
20925 subprogram within the environment of your program execution (which
20926 means that the subprogram is free to access or even modify variables
20927 within your program).
20928
20929 The most important use of this facility is in allowing the inclusion of
20930 debugging routines that are tailored to particular data structures
20931 in your program. Such debugging routines can be written to provide a suitably
20932 high-level description of an abstract type, rather than a low-level dump
20933 of its physical layout. After all, the standard
20934 @code{GDB print} command only knows the physical layout of your
20935 types, not their abstract meaning. Debugging routines can provide information
20936 at the desired semantic level and are thus enormously useful.
20937
20938 For example, when debugging GNAT itself, it is crucial to have access to
20939 the contents of the tree nodes used to represent the program internally.
20940 But tree nodes are represented simply by an integer value (which in turn
20941 is an index into a table of nodes).
20942 Using the @code{print} command on a tree node would simply print this integer
20943 value, which is not very useful. But the PN routine (defined in file
20944 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20945 a useful high level representation of the tree node, which includes the
20946 syntactic category of the node, its position in the source, the integers
20947 that denote descendant nodes and parent node, as well as varied
20948 semantic information. To study this example in more detail, you might want to
20949 look at the body of the PN procedure in the stated file.
20950
20951 @node Using the Next Command in a Function
20952 @section Using the Next Command in a Function
20953
20954 @noindent
20955 When you use the @code{next} command in a function, the current source
20956 location will advance to the next statement as usual. A special case
20957 arises in the case of a @code{return} statement.
20958
20959 Part of the code for a return statement is the ``epilog'' of the function.
20960 This is the code that returns to the caller. There is only one copy of
20961 this epilog code, and it is typically associated with the last return
20962 statement in the function if there is more than one return. In some
20963 implementations, this epilog is associated with the first statement
20964 of the function.
20965
20966 The result is that if you use the @code{next} command from a return
20967 statement that is not the last return statement of the function you
20968 may see a strange apparent jump to the last return statement or to
20969 the start of the function. You should simply ignore this odd jump.
20970 The value returned is always that from the first return statement
20971 that was stepped through.
20972
20973 @node Ada Exceptions
20974 @section Stopping when Ada Exceptions are Raised
20975 @cindex Exceptions
20976
20977 @noindent
20978 You can set catchpoints that stop the program execution when your program
20979 raises selected exceptions.
20980
20981 @table @code
20982 @item catch exception
20983 Set a catchpoint that stops execution whenever (any task in the) program
20984 raises any exception.
20985
20986 @item catch exception @var{name}
20987 Set a catchpoint that stops execution whenever (any task in the) program
20988 raises the exception @var{name}.
20989
20990 @item catch exception unhandled
20991 Set a catchpoint that stops executing whenever (any task in the) program
20992 raises an exception for which there is no handler.
20993
20994 @item info exceptions
20995 @itemx info exceptions @var{regexp}
20996 The @code{info exceptions} command permits the user to examine all defined
20997 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20998 argument, prints out only those exceptions whose name matches @var{regexp}.
20999 @end table
21000
21001 @node Ada Tasks
21002 @section Ada Tasks
21003 @cindex Tasks
21004
21005 @noindent
21006 @code{GDB} allows the following task-related commands:
21007
21008 @table @code
21009 @item info tasks
21010 This command shows a list of current Ada tasks, as in the following example:
21011
21012 @smallexample
21013 @iftex
21014 @leftskip=0cm
21015 @end iftex
21016 (gdb) info tasks
21017 ID TID P-ID Thread Pri State Name
21018 1 8088000 0 807e000 15 Child Activation Wait main_task
21019 2 80a4000 1 80ae000 15 Accept/Select Wait b
21020 3 809a800 1 80a4800 15 Child Activation Wait a
21021 * 4 80ae800 3 80b8000 15 Running c
21022 @end smallexample
21023
21024 @noindent
21025 In this listing, the asterisk before the first task indicates it to be the
21026 currently running task. The first column lists the task ID that is used
21027 to refer to tasks in the following commands.
21028
21029 @item break @var{linespec} task @var{taskid}
21030 @itemx break @var{linespec} task @var{taskid} if @dots{}
21031 @cindex Breakpoints and tasks
21032 These commands are like the @code{break @dots{} thread @dots{}}.
21033 @var{linespec} specifies source lines.
21034
21035 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21036 to specify that you only want @code{GDB} to stop the program when a
21037 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21038 numeric task identifiers assigned by @code{GDB}, shown in the first
21039 column of the @samp{info tasks} display.
21040
21041 If you do not specify @samp{task @var{taskid}} when you set a
21042 breakpoint, the breakpoint applies to @emph{all} tasks of your
21043 program.
21044
21045 You can use the @code{task} qualifier on conditional breakpoints as
21046 well; in this case, place @samp{task @var{taskid}} before the
21047 breakpoint condition (before the @code{if}).
21048
21049 @item task @var{taskno}
21050 @cindex Task switching
21051
21052 This command allows to switch to the task referred by @var{taskno}. In
21053 particular, This allows to browse the backtrace of the specified
21054 task. It is advised to switch back to the original task before
21055 continuing execution otherwise the scheduling of the program may be
21056 perturbed.
21057 @end table
21058
21059 @noindent
21060 For more detailed information on the tasking support,
21061 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21062
21063 @node Debugging Generic Units
21064 @section Debugging Generic Units
21065 @cindex Debugging Generic Units
21066 @cindex Generics
21067
21068 @noindent
21069 GNAT always uses code expansion for generic instantiation. This means that
21070 each time an instantiation occurs, a complete copy of the original code is
21071 made, with appropriate substitutions of formals by actuals.
21072
21073 It is not possible to refer to the original generic entities in
21074 @code{GDB}, but it is always possible to debug a particular instance of
21075 a generic, by using the appropriate expanded names. For example, if we have
21076
21077 @smallexample @c ada
21078 @group
21079 @cartouche
21080 procedure g is
21081
21082 generic package k is
21083 procedure kp (v1 : in out integer);
21084 end k;
21085
21086 package body k is
21087 procedure kp (v1 : in out integer) is
21088 begin
21089 v1 := v1 + 1;
21090 end kp;
21091 end k;
21092
21093 package k1 is new k;
21094 package k2 is new k;
21095
21096 var : integer := 1;
21097
21098 begin
21099 k1.kp (var);
21100 k2.kp (var);
21101 k1.kp (var);
21102 k2.kp (var);
21103 end;
21104 @end cartouche
21105 @end group
21106 @end smallexample
21107
21108 @noindent
21109 Then to break on a call to procedure kp in the k2 instance, simply
21110 use the command:
21111
21112 @smallexample
21113 (gdb) break g.k2.kp
21114 @end smallexample
21115
21116 @noindent
21117 When the breakpoint occurs, you can step through the code of the
21118 instance in the normal manner and examine the values of local variables, as for
21119 other units.
21120
21121 @node Remote Debugging using gdbserver
21122 @section Remote Debugging using gdbserver
21123 @cindex Remote Debugging using gdbserver
21124
21125 @noindent
21126 On platforms where gdbserver is supported, it is possible to use this tool
21127 to debug your application remotely. This can be useful in situations
21128 where the program needs to be run on a target host that is different
21129 from the host used for development, particularly when the target has
21130 a limited amount of resources (either CPU and/or memory).
21131
21132 To do so, start your program using gdbserver on the target machine.
21133 gdbserver then automatically suspends the execution of your program
21134 at its entry point, waiting for a debugger to connect to it. The
21135 following commands starts an application and tells gdbserver to
21136 wait for a connection with the debugger on localhost port 4444.
21137
21138 @smallexample
21139 $ gdbserver localhost:4444 program
21140 Process program created; pid = 5685
21141 Listening on port 4444
21142 @end smallexample
21143
21144 Once gdbserver has started listening, we can tell the debugger to establish
21145 a connection with this gdbserver, and then start the same debugging session
21146 as if the program was being debugged on the same host, directly under
21147 the control of GDB.
21148
21149 @smallexample
21150 $ gdb program
21151 (gdb) target remote targethost:4444
21152 Remote debugging using targethost:4444
21153 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21154 (gdb) b foo.adb:3
21155 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21156 (gdb) continue
21157 Continuing.
21158
21159 Breakpoint 1, foo () at foo.adb:4
21160 4 end foo;
21161 @end smallexample
21162
21163 It is also possible to use gdbserver to attach to an already running
21164 program, in which case the execution of that program is simply suspended
21165 until the connection between the debugger and gdbserver is established.
21166
21167 For more information on how to use gdbserver, @ref{Top, Server, Using
21168 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21169 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21170
21171 @node GNAT Abnormal Termination or Failure to Terminate
21172 @section GNAT Abnormal Termination or Failure to Terminate
21173 @cindex GNAT Abnormal Termination or Failure to Terminate
21174
21175 @noindent
21176 When presented with programs that contain serious errors in syntax
21177 or semantics,
21178 GNAT may on rare occasions experience problems in operation, such
21179 as aborting with a
21180 segmentation fault or illegal memory access, raising an internal
21181 exception, terminating abnormally, or failing to terminate at all.
21182 In such cases, you can activate
21183 various features of GNAT that can help you pinpoint the construct in your
21184 program that is the likely source of the problem.
21185
21186 The following strategies are presented in increasing order of
21187 difficulty, corresponding to your experience in using GNAT and your
21188 familiarity with compiler internals.
21189
21190 @enumerate
21191 @item
21192 Run @command{gcc} with the @option{-gnatf}. This first
21193 switch causes all errors on a given line to be reported. In its absence,
21194 only the first error on a line is displayed.
21195
21196 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21197 are encountered, rather than after compilation is terminated. If GNAT
21198 terminates prematurely or goes into an infinite loop, the last error
21199 message displayed may help to pinpoint the culprit.
21200
21201 @item
21202 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21203 mode, @command{gcc} produces ongoing information about the progress of the
21204 compilation and provides the name of each procedure as code is
21205 generated. This switch allows you to find which Ada procedure was being
21206 compiled when it encountered a code generation problem.
21207
21208 @item
21209 @cindex @option{-gnatdc} switch
21210 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21211 switch that does for the front-end what @option{^-v^VERBOSE^} does
21212 for the back end. The system prints the name of each unit,
21213 either a compilation unit or nested unit, as it is being analyzed.
21214 @item
21215 Finally, you can start
21216 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21217 front-end of GNAT, and can be run independently (normally it is just
21218 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21219 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21220 @code{where} command is the first line of attack; the variable
21221 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21222 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21223 which the execution stopped, and @code{input_file name} indicates the name of
21224 the source file.
21225 @end enumerate
21226
21227 @node Naming Conventions for GNAT Source Files
21228 @section Naming Conventions for GNAT Source Files
21229
21230 @noindent
21231 In order to examine the workings of the GNAT system, the following
21232 brief description of its organization may be helpful:
21233
21234 @itemize @bullet
21235 @item
21236 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21237
21238 @item
21239 All files prefixed with @file{^par^PAR^} are components of the parser. The
21240 numbers correspond to chapters of the Ada Reference Manual. For example,
21241 parsing of select statements can be found in @file{par-ch9.adb}.
21242
21243 @item
21244 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21245 numbers correspond to chapters of the Ada standard. For example, all
21246 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21247 addition, some features of the language require sufficient special processing
21248 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21249 dynamic dispatching, etc.
21250
21251 @item
21252 All files prefixed with @file{^exp^EXP^} perform normalization and
21253 expansion of the intermediate representation (abstract syntax tree, or AST).
21254 these files use the same numbering scheme as the parser and semantics files.
21255 For example, the construction of record initialization procedures is done in
21256 @file{exp_ch3.adb}.
21257
21258 @item
21259 The files prefixed with @file{^bind^BIND^} implement the binder, which
21260 verifies the consistency of the compilation, determines an order of
21261 elaboration, and generates the bind file.
21262
21263 @item
21264 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21265 data structures used by the front-end.
21266
21267 @item
21268 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21269 the abstract syntax tree as produced by the parser.
21270
21271 @item
21272 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21273 all entities, computed during semantic analysis.
21274
21275 @item
21276 Library management issues are dealt with in files with prefix
21277 @file{^lib^LIB^}.
21278
21279 @item
21280 @findex Ada
21281 @cindex Annex A
21282 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21283 defined in Annex A.
21284
21285 @item
21286 @findex Interfaces
21287 @cindex Annex B
21288 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21289 defined in Annex B.
21290
21291 @item
21292 @findex System
21293 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21294 both language-defined children and GNAT run-time routines.
21295
21296 @item
21297 @findex GNAT
21298 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21299 general-purpose packages, fully documented in their specs. All
21300 the other @file{.c} files are modifications of common @command{gcc} files.
21301 @end itemize
21302
21303 @node Getting Internal Debugging Information
21304 @section Getting Internal Debugging Information
21305
21306 @noindent
21307 Most compilers have internal debugging switches and modes. GNAT
21308 does also, except GNAT internal debugging switches and modes are not
21309 secret. A summary and full description of all the compiler and binder
21310 debug flags are in the file @file{debug.adb}. You must obtain the
21311 sources of the compiler to see the full detailed effects of these flags.
21312
21313 The switches that print the source of the program (reconstructed from
21314 the internal tree) are of general interest for user programs, as are the
21315 options to print
21316 the full internal tree, and the entity table (the symbol table
21317 information). The reconstructed source provides a readable version of the
21318 program after the front-end has completed analysis and expansion,
21319 and is useful when studying the performance of specific constructs.
21320 For example, constraint checks are indicated, complex aggregates
21321 are replaced with loops and assignments, and tasking primitives
21322 are replaced with run-time calls.
21323
21324 @node Stack Traceback
21325 @section Stack Traceback
21326 @cindex traceback
21327 @cindex stack traceback
21328 @cindex stack unwinding
21329
21330 @noindent
21331 Traceback is a mechanism to display the sequence of subprogram calls that
21332 leads to a specified execution point in a program. Often (but not always)
21333 the execution point is an instruction at which an exception has been raised.
21334 This mechanism is also known as @i{stack unwinding} because it obtains
21335 its information by scanning the run-time stack and recovering the activation
21336 records of all active subprograms. Stack unwinding is one of the most
21337 important tools for program debugging.
21338
21339 The first entry stored in traceback corresponds to the deepest calling level,
21340 that is to say the subprogram currently executing the instruction
21341 from which we want to obtain the traceback.
21342
21343 Note that there is no runtime performance penalty when stack traceback
21344 is enabled, and no exception is raised during program execution.
21345
21346 @menu
21347 * Non-Symbolic Traceback::
21348 * Symbolic Traceback::
21349 @end menu
21350
21351 @node Non-Symbolic Traceback
21352 @subsection Non-Symbolic Traceback
21353 @cindex traceback, non-symbolic
21354
21355 @noindent
21356 Note: this feature is not supported on all platforms. See
21357 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21358 platforms.
21359
21360 @menu
21361 * Tracebacks From an Unhandled Exception::
21362 * Tracebacks From Exception Occurrences (non-symbolic)::
21363 * Tracebacks From Anywhere in a Program (non-symbolic)::
21364 @end menu
21365
21366 @node Tracebacks From an Unhandled Exception
21367 @subsubsection Tracebacks From an Unhandled Exception
21368
21369 @noindent
21370 A runtime non-symbolic traceback is a list of addresses of call instructions.
21371 To enable this feature you must use the @option{-E}
21372 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21373 of exception information. You can retrieve this information using the
21374 @code{addr2line} tool.
21375
21376 Here is a simple example:
21377
21378 @smallexample @c ada
21379 @cartouche
21380 procedure STB is
21381
21382 procedure P1 is
21383 begin
21384 raise Constraint_Error;
21385 end P1;
21386
21387 procedure P2 is
21388 begin
21389 P1;
21390 end P2;
21391
21392 begin
21393 P2;
21394 end STB;
21395 @end cartouche
21396 @end smallexample
21397
21398 @smallexample
21399 $ gnatmake stb -bargs -E
21400 $ stb
21401
21402 Execution terminated by unhandled exception
21403 Exception name: CONSTRAINT_ERROR
21404 Message: stb.adb:5
21405 Call stack traceback locations:
21406 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21407 @end smallexample
21408
21409 @noindent
21410 As we see the traceback lists a sequence of addresses for the unhandled
21411 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21412 guess that this exception come from procedure P1. To translate these
21413 addresses into the source lines where the calls appear, the
21414 @code{addr2line} tool, described below, is invaluable. The use of this tool
21415 requires the program to be compiled with debug information.
21416
21417 @smallexample
21418 $ gnatmake -g stb -bargs -E
21419 $ stb
21420
21421 Execution terminated by unhandled exception
21422 Exception name: CONSTRAINT_ERROR
21423 Message: stb.adb:5
21424 Call stack traceback locations:
21425 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21426
21427 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21428 0x4011f1 0x77e892a4
21429
21430 00401373 at d:/stb/stb.adb:5
21431 0040138B at d:/stb/stb.adb:10
21432 0040139C at d:/stb/stb.adb:14
21433 00401335 at d:/stb/b~stb.adb:104
21434 004011C4 at /build/@dots{}/crt1.c:200
21435 004011F1 at /build/@dots{}/crt1.c:222
21436 77E892A4 in ?? at ??:0
21437 @end smallexample
21438
21439 @noindent
21440 The @code{addr2line} tool has several other useful options:
21441
21442 @table @code
21443 @item --functions
21444 to get the function name corresponding to any location
21445
21446 @item --demangle=gnat
21447 to use the gnat decoding mode for the function names. Note that
21448 for binutils version 2.9.x the option is simply @option{--demangle}.
21449 @end table
21450
21451 @smallexample
21452 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21453 0x40139c 0x401335 0x4011c4 0x4011f1
21454
21455 00401373 in stb.p1 at d:/stb/stb.adb:5
21456 0040138B in stb.p2 at d:/stb/stb.adb:10
21457 0040139C in stb at d:/stb/stb.adb:14
21458 00401335 in main at d:/stb/b~stb.adb:104
21459 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21460 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21461 @end smallexample
21462
21463 @noindent
21464 From this traceback we can see that the exception was raised in
21465 @file{stb.adb} at line 5, which was reached from a procedure call in
21466 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21467 which contains the call to the main program.
21468 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21469 and the output will vary from platform to platform.
21470
21471 It is also possible to use @code{GDB} with these traceback addresses to debug
21472 the program. For example, we can break at a given code location, as reported
21473 in the stack traceback:
21474
21475 @smallexample
21476 $ gdb -nw stb
21477 @ifclear vms
21478 @noindent
21479 Furthermore, this feature is not implemented inside Windows DLL. Only
21480 the non-symbolic traceback is reported in this case.
21481 @end ifclear
21482
21483 (gdb) break *0x401373
21484 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21485 @end smallexample
21486
21487 @noindent
21488 It is important to note that the stack traceback addresses
21489 do not change when debug information is included. This is particularly useful
21490 because it makes it possible to release software without debug information (to
21491 minimize object size), get a field report that includes a stack traceback
21492 whenever an internal bug occurs, and then be able to retrieve the sequence
21493 of calls with the same program compiled with debug information.
21494
21495 @node Tracebacks From Exception Occurrences (non-symbolic)
21496 @subsubsection Tracebacks From Exception Occurrences
21497
21498 @noindent
21499 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21500 The stack traceback is attached to the exception information string, and can
21501 be retrieved in an exception handler within the Ada program, by means of the
21502 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21503
21504 @smallexample @c ada
21505 with Ada.Text_IO;
21506 with Ada.Exceptions;
21507
21508 procedure STB is
21509
21510 use Ada;
21511 use Ada.Exceptions;
21512
21513 procedure P1 is
21514 K : Positive := 1;
21515 begin
21516 K := K - 1;
21517 exception
21518 when E : others =>
21519 Text_IO.Put_Line (Exception_Information (E));
21520 end P1;
21521
21522 procedure P2 is
21523 begin
21524 P1;
21525 end P2;
21526
21527 begin
21528 P2;
21529 end STB;
21530 @end smallexample
21531
21532 @noindent
21533 This program will output:
21534
21535 @smallexample
21536 $ stb
21537
21538 Exception name: CONSTRAINT_ERROR
21539 Message: stb.adb:12
21540 Call stack traceback locations:
21541 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21542 @end smallexample
21543
21544 @node Tracebacks From Anywhere in a Program (non-symbolic)
21545 @subsubsection Tracebacks From Anywhere in a Program
21546
21547 @noindent
21548 It is also possible to retrieve a stack traceback from anywhere in a
21549 program. For this you need to
21550 use the @code{GNAT.Traceback} API. This package includes a procedure called
21551 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21552 display procedures described below. It is not necessary to use the
21553 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21554 is invoked explicitly.
21555
21556 @noindent
21557 In the following example we compute a traceback at a specific location in
21558 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21559 convert addresses to strings:
21560
21561 @smallexample @c ada
21562 with Ada.Text_IO;
21563 with GNAT.Traceback;
21564 with GNAT.Debug_Utilities;
21565
21566 procedure STB is
21567
21568 use Ada;
21569 use GNAT;
21570 use GNAT.Traceback;
21571
21572 procedure P1 is
21573 TB : Tracebacks_Array (1 .. 10);
21574 -- We are asking for a maximum of 10 stack frames.
21575 Len : Natural;
21576 -- Len will receive the actual number of stack frames returned.
21577 begin
21578 Call_Chain (TB, Len);
21579
21580 Text_IO.Put ("In STB.P1 : ");
21581
21582 for K in 1 .. Len loop
21583 Text_IO.Put (Debug_Utilities.Image (TB (K)));
21584 Text_IO.Put (' ');
21585 end loop;
21586
21587 Text_IO.New_Line;
21588 end P1;
21589
21590 procedure P2 is
21591 begin
21592 P1;
21593 end P2;
21594
21595 begin
21596 P2;
21597 end STB;
21598 @end smallexample
21599
21600 @smallexample
21601 $ gnatmake -g stb
21602 $ stb
21603
21604 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21605 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21606 @end smallexample
21607
21608 @noindent
21609 You can then get further information by invoking the @code{addr2line}
21610 tool as described earlier (note that the hexadecimal addresses
21611 need to be specified in C format, with a leading ``0x'').
21612
21613 @node Symbolic Traceback
21614 @subsection Symbolic Traceback
21615 @cindex traceback, symbolic
21616
21617 @noindent
21618 A symbolic traceback is a stack traceback in which procedure names are
21619 associated with each code location.
21620
21621 @noindent
21622 Note that this feature is not supported on all platforms. See
21623 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21624 list of currently supported platforms.
21625
21626 @noindent
21627 Note that the symbolic traceback requires that the program be compiled
21628 with debug information. If it is not compiled with debug information
21629 only the non-symbolic information will be valid.
21630
21631 @menu
21632 * Tracebacks From Exception Occurrences (symbolic)::
21633 * Tracebacks From Anywhere in a Program (symbolic)::
21634 @end menu
21635
21636 @node Tracebacks From Exception Occurrences (symbolic)
21637 @subsubsection Tracebacks From Exception Occurrences
21638
21639 @smallexample @c ada
21640 with Ada.Text_IO;
21641 with GNAT.Traceback.Symbolic;
21642
21643 procedure STB is
21644
21645 procedure P1 is
21646 begin
21647 raise Constraint_Error;
21648 end P1;
21649
21650 procedure P2 is
21651 begin
21652 P1;
21653 end P2;
21654
21655 procedure P3 is
21656 begin
21657 P2;
21658 end P3;
21659
21660 begin
21661 P3;
21662 exception
21663 when E : others =>
21664 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21665 end STB;
21666 @end smallexample
21667
21668 @smallexample
21669 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
21670 $ stb
21671
21672 0040149F in stb.p1 at stb.adb:8
21673 004014B7 in stb.p2 at stb.adb:13
21674 004014CF in stb.p3 at stb.adb:18
21675 004015DD in ada.stb at stb.adb:22
21676 00401461 in main at b~stb.adb:168
21677 004011C4 in __mingw_CRTStartup at crt1.c:200
21678 004011F1 in mainCRTStartup at crt1.c:222
21679 77E892A4 in ?? at ??:0
21680 @end smallexample
21681
21682 @noindent
21683 In the above example the ``.\'' syntax in the @command{gnatmake} command
21684 is currently required by @command{addr2line} for files that are in
21685 the current working directory.
21686 Moreover, the exact sequence of linker options may vary from platform
21687 to platform.
21688 The above @option{-largs} section is for Windows platforms. By contrast,
21689 under Unix there is no need for the @option{-largs} section.
21690 Differences across platforms are due to details of linker implementation.
21691
21692 @node Tracebacks From Anywhere in a Program (symbolic)
21693 @subsubsection Tracebacks From Anywhere in a Program
21694
21695 @noindent
21696 It is possible to get a symbolic stack traceback
21697 from anywhere in a program, just as for non-symbolic tracebacks.
21698 The first step is to obtain a non-symbolic
21699 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21700 information. Here is an example:
21701
21702 @smallexample @c ada
21703 with Ada.Text_IO;
21704 with GNAT.Traceback;
21705 with GNAT.Traceback.Symbolic;
21706
21707 procedure STB is
21708
21709 use Ada;
21710 use GNAT.Traceback;
21711 use GNAT.Traceback.Symbolic;
21712
21713 procedure P1 is
21714 TB : Tracebacks_Array (1 .. 10);
21715 -- We are asking for a maximum of 10 stack frames.
21716 Len : Natural;
21717 -- Len will receive the actual number of stack frames returned.
21718 begin
21719 Call_Chain (TB, Len);
21720 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21721 end P1;
21722
21723 procedure P2 is
21724 begin
21725 P1;
21726 end P2;
21727
21728 begin
21729 P2;
21730 end STB;
21731 @end smallexample
21732
21733 @c ******************************
21734 @ifset vms
21735 @node Compatibility with HP Ada
21736 @chapter Compatibility with HP Ada
21737 @cindex Compatibility
21738
21739 @noindent
21740 @cindex DEC Ada
21741 @cindex HP Ada
21742 @cindex Compatibility between GNAT and HP Ada
21743 This chapter compares HP Ada (formerly known as ``DEC Ada'')
21744 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
21745 GNAT is highly compatible
21746 with HP Ada, and it should generally be straightforward to port code
21747 from the HP Ada environment to GNAT. However, there are a few language
21748 and implementation differences of which the user must be aware. These
21749 differences are discussed in this chapter. In
21750 addition, the operating environment and command structure for the
21751 compiler are different, and these differences are also discussed.
21752
21753 For further details on these and other compatibility issues,
21754 see Appendix E of the HP publication
21755 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
21756
21757 Except where otherwise indicated, the description of GNAT for OpenVMS
21758 applies to both the Alpha and I64 platforms.
21759
21760 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
21761 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21762
21763 The discussion in this chapter addresses specifically the implementation
21764 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
21765 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
21766 GNAT always follows the Alpha implementation.
21767
21768 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
21769 attributes are recognized, although only a subset of them can sensibly
21770 be implemented. The description of pragmas in
21771 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21772 indicates whether or not they are applicable to non-VMS systems.
21773
21774 @menu
21775 * Ada Language Compatibility::
21776 * Differences in the Definition of Package System::
21777 * Language-Related Features::
21778 * The Package STANDARD::
21779 * The Package SYSTEM::
21780 * Tasking and Task-Related Features::
21781 * Pragmas and Pragma-Related Features::
21782 * Library of Predefined Units::
21783 * Bindings::
21784 * Main Program Definition::
21785 * Implementation-Defined Attributes::
21786 * Compiler and Run-Time Interfacing::
21787 * Program Compilation and Library Management::
21788 * Input-Output::
21789 * Implementation Limits::
21790 * Tools and Utilities::
21791 @end menu
21792
21793 @node Ada Language Compatibility
21794 @section Ada Language Compatibility
21795
21796 @noindent
21797 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
21798 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
21799 with Ada 83, and therefore Ada 83 programs will compile
21800 and run under GNAT with
21801 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
21802 provides details on specific incompatibilities.
21803
21804 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
21805 as well as the pragma @code{ADA_83}, to force the compiler to
21806 operate in Ada 83 mode. This mode does not guarantee complete
21807 conformance to Ada 83, but in practice is sufficient to
21808 eliminate most sources of incompatibilities.
21809 In particular, it eliminates the recognition of the
21810 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
21811 in Ada 83 programs is legal, and handles the cases of packages
21812 with optional bodies, and generics that instantiate unconstrained
21813 types without the use of @code{(<>)}.
21814
21815 @node Differences in the Definition of Package System
21816 @section Differences in the Definition of Package @code{System}
21817
21818 @noindent
21819 An Ada compiler is allowed to add
21820 implementation-dependent declarations to package @code{System}.
21821 In normal mode,
21822 GNAT does not take advantage of this permission, and the version of
21823 @code{System} provided by GNAT exactly matches that defined in the Ada
21824 Reference Manual.
21825
21826 However, HP Ada adds an extensive set of declarations to package
21827 @code{System},
21828 as fully documented in the HP Ada manuals. To minimize changes required
21829 for programs that make use of these extensions, GNAT provides the pragma
21830 @code{Extend_System} for extending the definition of package System. By using:
21831 @cindex pragma @code{Extend_System}
21832 @cindex @code{Extend_System} pragma
21833
21834 @smallexample @c ada
21835 @group
21836 @cartouche
21837 pragma Extend_System (Aux_DEC);
21838 @end cartouche
21839 @end group
21840 @end smallexample
21841
21842 @noindent
21843 the set of definitions in @code{System} is extended to include those in
21844 package @code{System.Aux_DEC}.
21845 @cindex @code{System.Aux_DEC} package
21846 @cindex @code{Aux_DEC} package (child of @code{System})
21847 These definitions are incorporated directly into package @code{System},
21848 as though they had been declared there. For a
21849 list of the declarations added, see the spec of this package,
21850 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21851 @cindex @file{s-auxdec.ads} file
21852 The pragma @code{Extend_System} is a configuration pragma, which means that
21853 it can be placed in the file @file{gnat.adc}, so that it will automatically
21854 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21855 for further details.
21856
21857 An alternative approach that avoids the use of the non-standard
21858 @code{Extend_System} pragma is to add a context clause to the unit that
21859 references these facilities:
21860
21861 @smallexample @c ada
21862 @cartouche
21863 with System.Aux_DEC;
21864 use System.Aux_DEC;
21865 @end cartouche
21866 @end smallexample
21867
21868 @noindent
21869 The effect is not quite semantically identical to incorporating
21870 the declarations directly into package @code{System},
21871 but most programs will not notice a difference
21872 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21873 to reference the entities directly in package @code{System}.
21874 For units containing such references,
21875 the prefixes must either be removed, or the pragma @code{Extend_System}
21876 must be used.
21877
21878 @node Language-Related Features
21879 @section Language-Related Features
21880
21881 @noindent
21882 The following sections highlight differences in types,
21883 representations of types, operations, alignment, and
21884 related topics.
21885
21886 @menu
21887 * Integer Types and Representations::
21888 * Floating-Point Types and Representations::
21889 * Pragmas Float_Representation and Long_Float::
21890 * Fixed-Point Types and Representations::
21891 * Record and Array Component Alignment::
21892 * Address Clauses::
21893 * Other Representation Clauses::
21894 @end menu
21895
21896 @node Integer Types and Representations
21897 @subsection Integer Types and Representations
21898
21899 @noindent
21900 The set of predefined integer types is identical in HP Ada and GNAT.
21901 Furthermore the representation of these integer types is also identical,
21902 including the capability of size clauses forcing biased representation.
21903
21904 In addition,
21905 HP Ada for OpenVMS Alpha systems has defined the
21906 following additional integer types in package @code{System}:
21907
21908 @itemize @bullet
21909
21910 @item
21911 @code{INTEGER_8}
21912
21913 @item
21914 @code{INTEGER_16}
21915
21916 @item
21917 @code{INTEGER_32}
21918
21919 @item
21920 @code{INTEGER_64}
21921
21922 @item
21923 @code{LARGEST_INTEGER}
21924 @end itemize
21925
21926 @noindent
21927 In GNAT, the first four of these types may be obtained from the
21928 standard Ada package @code{Interfaces}.
21929 Alternatively, by use of the pragma @code{Extend_System}, identical
21930 declarations can be referenced directly in package @code{System}.
21931 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21932
21933 @node Floating-Point Types and Representations
21934 @subsection Floating-Point Types and Representations
21935 @cindex Floating-Point types
21936
21937 @noindent
21938 The set of predefined floating-point types is identical in HP Ada and GNAT.
21939 Furthermore the representation of these floating-point
21940 types is also identical. One important difference is that the default
21941 representation for HP Ada is @code{VAX_Float}, but the default representation
21942 for GNAT is IEEE.
21943
21944 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21945 pragma @code{Float_Representation} as described in the HP Ada
21946 documentation.
21947 For example, the declarations:
21948
21949 @smallexample @c ada
21950 @cartouche
21951 type F_Float is digits 6;
21952 pragma Float_Representation (VAX_Float, F_Float);
21953 @end cartouche
21954 @end smallexample
21955
21956 @noindent
21957 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21958 format.
21959 This set of declarations actually appears in @code{System.Aux_DEC},
21960 which contains
21961 the full set of additional floating-point declarations provided in
21962 the HP Ada version of package @code{System}.
21963 This and similar declarations may be accessed in a user program
21964 by using pragma @code{Extend_System}. The use of this
21965 pragma, and the related pragma @code{Long_Float} is described in further
21966 detail in the following section.
21967
21968 @node Pragmas Float_Representation and Long_Float
21969 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21970
21971 @noindent
21972 HP Ada provides the pragma @code{Float_Representation}, which
21973 acts as a program library switch to allow control over
21974 the internal representation chosen for the predefined
21975 floating-point types declared in the package @code{Standard}.
21976 The format of this pragma is as follows:
21977
21978 @smallexample @c ada
21979 @cartouche
21980 pragma Float_Representation(VAX_Float | IEEE_Float);
21981 @end cartouche
21982 @end smallexample
21983
21984 @noindent
21985 This pragma controls the representation of floating-point
21986 types as follows:
21987
21988 @itemize @bullet
21989 @item
21990 @code{VAX_Float} specifies that floating-point
21991 types are represented by default with the VAX system hardware types
21992 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21993 Note that the @code{H-floating}
21994 type was available only on VAX systems, and is not available
21995 in either HP Ada or GNAT.
21996
21997 @item
21998 @code{IEEE_Float} specifies that floating-point
21999 types are represented by default with the IEEE single and
22000 double floating-point types.
22001 @end itemize
22002
22003 @noindent
22004 GNAT provides an identical implementation of the pragma
22005 @code{Float_Representation}, except that it functions as a
22006 configuration pragma. Note that the
22007 notion of configuration pragma corresponds closely to the
22008 HP Ada notion of a program library switch.
22009
22010 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22011 which is different
22012 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22013 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22014 advisable to change the format of numbers passed to standard library
22015 routines, and if necessary explicit type conversions may be needed.
22016
22017 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22018 efficient, and (given that it conforms to an international standard)
22019 potentially more portable.
22020 The situation in which @code{VAX_Float} may be useful is in interfacing
22021 to existing code and data that expect the use of @code{VAX_Float}.
22022 In such a situation use the predefined @code{VAX_Float}
22023 types in package @code{System}, as extended by
22024 @code{Extend_System}. For example, use @code{System.F_Float}
22025 to specify the 32-bit @code{F-Float} format.
22026
22027 @noindent
22028 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22029 to allow control over the internal representation chosen
22030 for the predefined type @code{Long_Float} and for floating-point
22031 type declarations with digits specified in the range 7 .. 15.
22032 The format of this pragma is as follows:
22033
22034 @smallexample @c ada
22035 @cartouche
22036 pragma Long_Float (D_FLOAT | G_FLOAT);
22037 @end cartouche
22038 @end smallexample
22039
22040 @node Fixed-Point Types and Representations
22041 @subsection Fixed-Point Types and Representations
22042
22043 @noindent
22044 On HP Ada for OpenVMS Alpha systems, rounding is
22045 away from zero for both positive and negative numbers.
22046 Therefore, @code{+0.5} rounds to @code{1},
22047 and @code{-0.5} rounds to @code{-1}.
22048
22049 On GNAT the results of operations
22050 on fixed-point types are in accordance with the Ada
22051 rules. In particular, results of operations on decimal
22052 fixed-point types are truncated.
22053
22054 @node Record and Array Component Alignment
22055 @subsection Record and Array Component Alignment
22056
22057 @noindent
22058 On HP Ada for OpenVMS Alpha, all non-composite components
22059 are aligned on natural boundaries. For example, 1-byte
22060 components are aligned on byte boundaries, 2-byte
22061 components on 2-byte boundaries, 4-byte components on 4-byte
22062 byte boundaries, and so on. The OpenVMS Alpha hardware
22063 runs more efficiently with naturally aligned data.
22064
22065 On GNAT, alignment rules are compatible
22066 with HP Ada for OpenVMS Alpha.
22067
22068 @node Address Clauses
22069 @subsection Address Clauses
22070
22071 @noindent
22072 In HP Ada and GNAT, address clauses are supported for
22073 objects and imported subprograms.
22074 The predefined type @code{System.Address} is a private type
22075 in both compilers on Alpha OpenVMS, with the same representation
22076 (it is simply a machine pointer). Addition, subtraction, and comparison
22077 operations are available in the standard Ada package
22078 @code{System.Storage_Elements}, or in package @code{System}
22079 if it is extended to include @code{System.Aux_DEC} using a
22080 pragma @code{Extend_System} as previously described.
22081
22082 Note that code that @code{with}'s both this extended package @code{System}
22083 and the package @code{System.Storage_Elements} should not @code{use}
22084 both packages, or ambiguities will result. In general it is better
22085 not to mix these two sets of facilities. The Ada package was
22086 designed specifically to provide the kind of features that HP Ada
22087 adds directly to package @code{System}.
22088
22089 The type @code{System.Address} is a 64-bit integer type in GNAT for
22090 I64 OpenVMS. For more information,
22091 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22092
22093 GNAT is compatible with HP Ada in its handling of address
22094 clauses, except for some limitations in
22095 the form of address clauses for composite objects with
22096 initialization. Such address clauses are easily replaced
22097 by the use of an explicitly-defined constant as described
22098 in the Ada Reference Manual (13.1(22)). For example, the sequence
22099 of declarations:
22100
22101 @smallexample @c ada
22102 @cartouche
22103 X, Y : Integer := Init_Func;
22104 Q : String (X .. Y) := "abc";
22105 @dots{}
22106 for Q'Address use Compute_Address;
22107 @end cartouche
22108 @end smallexample
22109
22110 @noindent
22111 will be rejected by GNAT, since the address cannot be computed at the time
22112 that @code{Q} is declared. To achieve the intended effect, write instead:
22113
22114 @smallexample @c ada
22115 @group
22116 @cartouche
22117 X, Y : Integer := Init_Func;
22118 Q_Address : constant Address := Compute_Address;
22119 Q : String (X .. Y) := "abc";
22120 @dots{}
22121 for Q'Address use Q_Address;
22122 @end cartouche
22123 @end group
22124 @end smallexample
22125
22126 @noindent
22127 which will be accepted by GNAT (and other Ada compilers), and is also
22128 compatible with Ada 83. A fuller description of the restrictions
22129 on address specifications is found in @ref{Top, GNAT Reference Manual,
22130 About This Guide, gnat_rm, GNAT Reference Manual}.
22131
22132 @node Other Representation Clauses
22133 @subsection Other Representation Clauses
22134
22135 @noindent
22136 GNAT implements in a compatible manner all the representation
22137 clauses supported by HP Ada. In addition, GNAT
22138 implements the representation clause forms that were introduced in Ada 95,
22139 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22140
22141 @node The Package STANDARD
22142 @section The Package @code{STANDARD}
22143
22144 @noindent
22145 The package @code{STANDARD}, as implemented by HP Ada, is fully
22146 described in the @cite{Ada Reference Manual} and in the
22147 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22148 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22149
22150 In addition, HP Ada supports the Latin-1 character set in
22151 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22152 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22153 the type @code{WIDE_CHARACTER}.
22154
22155 The floating-point types supported by GNAT are those
22156 supported by HP Ada, but the defaults are different, and are controlled by
22157 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22158
22159 @node The Package SYSTEM
22160 @section The Package @code{SYSTEM}
22161
22162 @noindent
22163 HP Ada provides a specific version of the package
22164 @code{SYSTEM} for each platform on which the language is implemented.
22165 For the complete spec of the package @code{SYSTEM}, see
22166 Appendix F of the @cite{HP Ada Language Reference Manual}.
22167
22168 On HP Ada, the package @code{SYSTEM} includes the following conversion
22169 functions:
22170 @itemize @bullet
22171 @item @code{TO_ADDRESS(INTEGER)}
22172
22173 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22174
22175 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22176
22177 @item @code{TO_INTEGER(ADDRESS)}
22178
22179 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22180
22181 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22182 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22183 @end itemize
22184
22185 @noindent
22186 By default, GNAT supplies a version of @code{SYSTEM} that matches
22187 the definition given in the @cite{Ada Reference Manual}.
22188 This
22189 is a subset of the HP system definitions, which is as
22190 close as possible to the original definitions. The only difference
22191 is that the definition of @code{SYSTEM_NAME} is different:
22192
22193 @smallexample @c ada
22194 @cartouche
22195 type Name is (SYSTEM_NAME_GNAT);
22196 System_Name : constant Name := SYSTEM_NAME_GNAT;
22197 @end cartouche
22198 @end smallexample
22199
22200 @noindent
22201 Also, GNAT adds the Ada declarations for
22202 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22203
22204 However, the use of the following pragma causes GNAT
22205 to extend the definition of package @code{SYSTEM} so that it
22206 encompasses the full set of HP-specific extensions,
22207 including the functions listed above:
22208
22209 @smallexample @c ada
22210 @cartouche
22211 pragma Extend_System (Aux_DEC);
22212 @end cartouche
22213 @end smallexample
22214
22215 @noindent
22216 The pragma @code{Extend_System} is a configuration pragma that
22217 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22218 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22219
22220 HP Ada does not allow the recompilation of the package
22221 @code{SYSTEM}. Instead HP Ada provides several pragmas
22222 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22223 to modify values in the package @code{SYSTEM}.
22224 On OpenVMS Alpha systems, the pragma
22225 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22226 its single argument.
22227
22228 GNAT does permit the recompilation of package @code{SYSTEM} using
22229 the special switch @option{-gnatg}, and this switch can be used if
22230 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22231 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22232 or @code{MEMORY_SIZE} by any other means.
22233
22234 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22235 enumeration literal @code{SYSTEM_NAME_GNAT}.
22236
22237 The definitions provided by the use of
22238
22239 @smallexample @c ada
22240 pragma Extend_System (AUX_Dec);
22241 @end smallexample
22242
22243 @noindent
22244 are virtually identical to those provided by the HP Ada 83 package
22245 @code{SYSTEM}. One important difference is that the name of the
22246 @code{TO_ADDRESS}
22247 function for type @code{UNSIGNED_LONGWORD} is changed to
22248 @code{TO_ADDRESS_LONG}.
22249 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22250 discussion of why this change was necessary.
22251
22252 @noindent
22253 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22254 is in fact
22255 an extension to Ada 83 not strictly compatible with the reference manual.
22256 GNAT, in order to be exactly compatible with the standard,
22257 does not provide this capability. In HP Ada 83, the
22258 point of this definition is to deal with a call like:
22259
22260 @smallexample @c ada
22261 TO_ADDRESS (16#12777#);
22262 @end smallexample
22263
22264 @noindent
22265 Normally, according to Ada 83 semantics, one would expect this to be
22266 ambiguous, since it matches both the @code{INTEGER} and
22267 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22268 However, in HP Ada 83, there is no ambiguity, since the
22269 definition using @i{universal_integer} takes precedence.
22270
22271 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22272 it is
22273 not possible to be 100% compatible. Since there are many programs using
22274 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22275 GNAT was
22276 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22277 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22278
22279 @smallexample @c ada
22280 function To_Address (X : Integer) return Address;
22281 pragma Pure_Function (To_Address);
22282
22283 function To_Address_Long (X : Unsigned_Longword) return Address;
22284 pragma Pure_Function (To_Address_Long);
22285 @end smallexample
22286
22287 @noindent
22288 This means that programs using @code{TO_ADDRESS} for
22289 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22290
22291 @node Tasking and Task-Related Features
22292 @section Tasking and Task-Related Features
22293
22294 @noindent
22295 This section compares the treatment of tasking in GNAT
22296 and in HP Ada for OpenVMS Alpha.
22297 The GNAT description applies to both Alpha and I64 OpenVMS.
22298 For detailed information on tasking in
22299 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22300 relevant run-time reference manual.
22301
22302 @menu
22303 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22304 * Assigning Task IDs::
22305 * Task IDs and Delays::
22306 * Task-Related Pragmas::
22307 * Scheduling and Task Priority::
22308 * The Task Stack::
22309 * External Interrupts::
22310 @end menu
22311
22312 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22313 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22314
22315 @noindent
22316 On OpenVMS Alpha systems, each Ada task (except a passive
22317 task) is implemented as a single stream of execution
22318 that is created and managed by the kernel. On these
22319 systems, HP Ada tasking support is based on DECthreads,
22320 an implementation of the POSIX standard for threads.
22321
22322 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22323 code that calls DECthreads routines can be used together.
22324 The interaction between Ada tasks and DECthreads routines
22325 can have some benefits. For example when on OpenVMS Alpha,
22326 HP Ada can call C code that is already threaded.
22327
22328 GNAT uses the facilities of DECthreads,
22329 and Ada tasks are mapped to threads.
22330
22331 @node Assigning Task IDs
22332 @subsection Assigning Task IDs
22333
22334 @noindent
22335 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22336 the environment task that executes the main program. On
22337 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22338 that have been created but are not yet activated.
22339
22340 On OpenVMS Alpha systems, task IDs are assigned at
22341 activation. On GNAT systems, task IDs are also assigned at
22342 task creation but do not have the same form or values as
22343 task ID values in HP Ada. There is no null task, and the
22344 environment task does not have a specific task ID value.
22345
22346 @node Task IDs and Delays
22347 @subsection Task IDs and Delays
22348
22349 @noindent
22350 On OpenVMS Alpha systems, tasking delays are implemented
22351 using Timer System Services. The Task ID is used for the
22352 identification of the timer request (the @code{REQIDT} parameter).
22353 If Timers are used in the application take care not to use
22354 @code{0} for the identification, because cancelling such a timer
22355 will cancel all timers and may lead to unpredictable results.
22356
22357 @node Task-Related Pragmas
22358 @subsection Task-Related Pragmas
22359
22360 @noindent
22361 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22362 specification of the size of the guard area for a task
22363 stack. (The guard area forms an area of memory that has no
22364 read or write access and thus helps in the detection of
22365 stack overflow.) On OpenVMS Alpha systems, if the pragma
22366 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22367 area is created. In the absence of a pragma @code{TASK_STORAGE},
22368 a default guard area is created.
22369
22370 GNAT supplies the following task-related pragmas:
22371
22372 @itemize @bullet
22373 @item @code{TASK_INFO}
22374
22375 This pragma appears within a task definition and
22376 applies to the task in which it appears. The argument
22377 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22378
22379 @item @code{TASK_STORAGE}
22380
22381 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22382 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22383 @code{SUPPRESS}, and @code{VOLATILE}.
22384 @end itemize
22385 @node Scheduling and Task Priority
22386 @subsection Scheduling and Task Priority
22387
22388 @noindent
22389 HP Ada implements the Ada language requirement that
22390 when two tasks are eligible for execution and they have
22391 different priorities, the lower priority task does not
22392 execute while the higher priority task is waiting. The HP
22393 Ada Run-Time Library keeps a task running until either the
22394 task is suspended or a higher priority task becomes ready.
22395
22396 On OpenVMS Alpha systems, the default strategy is round-
22397 robin with preemption. Tasks of equal priority take turns
22398 at the processor. A task is run for a certain period of
22399 time and then placed at the tail of the ready queue for
22400 its priority level.
22401
22402 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22403 which can be used to enable or disable round-robin
22404 scheduling of tasks with the same priority.
22405 See the relevant HP Ada run-time reference manual for
22406 information on using the pragmas to control HP Ada task
22407 scheduling.
22408
22409 GNAT follows the scheduling rules of Annex D (Real-Time
22410 Annex) of the @cite{Ada Reference Manual}. In general, this
22411 scheduling strategy is fully compatible with HP Ada
22412 although it provides some additional constraints (as
22413 fully documented in Annex D).
22414 GNAT implements time slicing control in a manner compatible with
22415 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22416 are identical to the HP Ada 83 pragma of the same name.
22417 Note that it is not possible to mix GNAT tasking and
22418 HP Ada 83 tasking in the same program, since the two run-time
22419 libraries are not compatible.
22420
22421 @node The Task Stack
22422 @subsection The Task Stack
22423
22424 @noindent
22425 In HP Ada, a task stack is allocated each time a
22426 non-passive task is activated. As soon as the task is
22427 terminated, the storage for the task stack is deallocated.
22428 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22429 a default stack size is used. Also, regardless of the size
22430 specified, some additional space is allocated for task
22431 management purposes. On OpenVMS Alpha systems, at least
22432 one page is allocated.
22433
22434 GNAT handles task stacks in a similar manner. In accordance with
22435 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22436 an alternative method for controlling the task stack size.
22437 The specification of the attribute @code{T'STORAGE_SIZE} is also
22438 supported in a manner compatible with HP Ada.
22439
22440 @node External Interrupts
22441 @subsection External Interrupts
22442
22443 @noindent
22444 On HP Ada, external interrupts can be associated with task entries.
22445 GNAT is compatible with HP Ada in its handling of external interrupts.
22446
22447 @node Pragmas and Pragma-Related Features
22448 @section Pragmas and Pragma-Related Features
22449
22450 @noindent
22451 Both HP Ada and GNAT supply all language-defined pragmas
22452 as specified by the Ada 83 standard. GNAT also supplies all
22453 language-defined pragmas introduced by Ada 95 and Ada 2005.
22454 In addition, GNAT implements the implementation-defined pragmas
22455 from HP Ada 83.
22456
22457 @itemize @bullet
22458 @item @code{AST_ENTRY}
22459
22460 @item @code{COMMON_OBJECT}
22461
22462 @item @code{COMPONENT_ALIGNMENT}
22463
22464 @item @code{EXPORT_EXCEPTION}
22465
22466 @item @code{EXPORT_FUNCTION}
22467
22468 @item @code{EXPORT_OBJECT}
22469
22470 @item @code{EXPORT_PROCEDURE}
22471
22472 @item @code{EXPORT_VALUED_PROCEDURE}
22473
22474 @item @code{FLOAT_REPRESENTATION}
22475
22476 @item @code{IDENT}
22477
22478 @item @code{IMPORT_EXCEPTION}
22479
22480 @item @code{IMPORT_FUNCTION}
22481
22482 @item @code{IMPORT_OBJECT}
22483
22484 @item @code{IMPORT_PROCEDURE}
22485
22486 @item @code{IMPORT_VALUED_PROCEDURE}
22487
22488 @item @code{INLINE_GENERIC}
22489
22490 @item @code{INTERFACE_NAME}
22491
22492 @item @code{LONG_FLOAT}
22493
22494 @item @code{MAIN_STORAGE}
22495
22496 @item @code{PASSIVE}
22497
22498 @item @code{PSECT_OBJECT}
22499
22500 @item @code{SHARE_GENERIC}
22501
22502 @item @code{SUPPRESS_ALL}
22503
22504 @item @code{TASK_STORAGE}
22505
22506 @item @code{TIME_SLICE}
22507
22508 @item @code{TITLE}
22509 @end itemize
22510
22511 @noindent
22512 These pragmas are all fully implemented, with the exception of @code{TITLE},
22513 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22514 recognized, but which have no
22515 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22516 use of Ada protected objects. In GNAT, all generics are inlined.
22517
22518 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22519 a separate subprogram specification which must appear before the
22520 subprogram body.
22521
22522 GNAT also supplies a number of implementation-defined pragmas including the
22523 following:
22524
22525 @itemize @bullet
22526 @item @code{ABORT_DEFER}
22527
22528 @item @code{ADA_83}
22529
22530 @item @code{ADA_95}
22531
22532 @item @code{ADA_05}
22533
22534 @item @code{Ada_2005}
22535
22536 @item @code{Ada_12}
22537
22538 @item @code{Ada_2012}
22539
22540 @item @code{ANNOTATE}
22541
22542 @item @code{ASSERT}
22543
22544 @item @code{C_PASS_BY_COPY}
22545
22546 @item @code{CPP_CLASS}
22547
22548 @item @code{CPP_CONSTRUCTOR}
22549
22550 @item @code{CPP_DESTRUCTOR}
22551
22552 @item @code{DEBUG}
22553
22554 @item @code{EXTEND_SYSTEM}
22555
22556 @item @code{LINKER_ALIAS}
22557
22558 @item @code{LINKER_SECTION}
22559
22560 @item @code{MACHINE_ATTRIBUTE}
22561
22562 @item @code{NO_RETURN}
22563
22564 @item @code{PURE_FUNCTION}
22565
22566 @item @code{SOURCE_FILE_NAME}
22567
22568 @item @code{SOURCE_REFERENCE}
22569
22570 @item @code{TASK_INFO}
22571
22572 @item @code{UNCHECKED_UNION}
22573
22574 @item @code{UNIMPLEMENTED_UNIT}
22575
22576 @item @code{UNIVERSAL_DATA}
22577
22578 @item @code{UNSUPPRESS}
22579
22580 @item @code{WARNINGS}
22581
22582 @item @code{WEAK_EXTERNAL}
22583 @end itemize
22584
22585 @noindent
22586 For full details on these and other GNAT implementation-defined pragmas,
22587 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22588 Manual}.
22589
22590 @menu
22591 * Restrictions on the Pragma INLINE::
22592 * Restrictions on the Pragma INTERFACE::
22593 * Restrictions on the Pragma SYSTEM_NAME::
22594 @end menu
22595
22596 @node Restrictions on the Pragma INLINE
22597 @subsection Restrictions on Pragma @code{INLINE}
22598
22599 @noindent
22600 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22601 @itemize @bullet
22602 @item Parameters cannot have a task type.
22603
22604 @item Function results cannot be task types, unconstrained
22605 array types, or unconstrained types with discriminants.
22606
22607 @item Bodies cannot declare the following:
22608 @itemize @bullet
22609 @item Subprogram body or stub (imported subprogram is allowed)
22610
22611 @item Tasks
22612
22613 @item Generic declarations
22614
22615 @item Instantiations
22616
22617 @item Exceptions
22618
22619 @item Access types (types derived from access types allowed)
22620
22621 @item Array or record types
22622
22623 @item Dependent tasks
22624
22625 @item Direct recursive calls of subprogram or containing
22626 subprogram, directly or via a renaming
22627
22628 @end itemize
22629 @end itemize
22630
22631 @noindent
22632 In GNAT, the only restriction on pragma @code{INLINE} is that the
22633 body must occur before the call if both are in the same
22634 unit, and the size must be appropriately small. There are
22635 no other specific restrictions which cause subprograms to
22636 be incapable of being inlined.
22637
22638 @node Restrictions on the Pragma INTERFACE
22639 @subsection Restrictions on Pragma @code{INTERFACE}
22640
22641 @noindent
22642 The following restrictions on pragma @code{INTERFACE}
22643 are enforced by both HP Ada and GNAT:
22644 @itemize @bullet
22645 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
22646 Default is the default on OpenVMS Alpha systems.
22647
22648 @item Parameter passing: Language specifies default
22649 mechanisms but can be overridden with an @code{EXPORT} pragma.
22650
22651 @itemize @bullet
22652 @item Ada: Use internal Ada rules.
22653
22654 @item Bliss, C: Parameters must be mode @code{in}; cannot be
22655 record or task type. Result cannot be a string, an
22656 array, or a record.
22657
22658 @item Fortran: Parameters cannot have a task type. Result cannot
22659 be a string, an array, or a record.
22660 @end itemize
22661 @end itemize
22662
22663 @noindent
22664 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22665 record parameters for all languages.
22666
22667 @node Restrictions on the Pragma SYSTEM_NAME
22668 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
22669
22670 @noindent
22671 For HP Ada for OpenVMS Alpha, the enumeration literal
22672 for the type @code{NAME} is @code{OPENVMS_AXP}.
22673 In GNAT, the enumeration
22674 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22675
22676 @node Library of Predefined Units
22677 @section Library of Predefined Units
22678
22679 @noindent
22680 A library of predefined units is provided as part of the
22681 HP Ada and GNAT implementations. HP Ada does not provide
22682 the package @code{MACHINE_CODE} but instead recommends importing
22683 assembler code.
22684
22685 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22686 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22687 version.
22688 The HP Ada Predefined Library units are modified to remove post-Ada 83
22689 incompatibilities and to make them interoperable with GNAT
22690 (@pxref{Changes to DECLIB}, for details).
22691 The units are located in the @file{DECLIB} directory.
22692
22693 The GNAT RTL is contained in
22694 the @file{ADALIB} directory, and
22695 the default search path is set up to find @code{DECLIB} units in preference
22696 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22697 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22698
22699 @menu
22700 * Changes to DECLIB::
22701 @end menu
22702
22703 @node Changes to DECLIB
22704 @subsection Changes to @code{DECLIB}
22705
22706 @noindent
22707 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22708 compatibility are minor and include the following:
22709
22710 @itemize @bullet
22711 @item Adjusting the location of pragmas and record representation
22712 clauses to obey Ada 95 (and thus Ada 2005) rules
22713
22714 @item Adding the proper notation to generic formal parameters
22715 that take unconstrained types in instantiation
22716
22717 @item Adding pragma @code{ELABORATE_BODY} to package specs
22718 that have package bodies not otherwise allowed
22719
22720 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
22721 ``@code{PROTECTD}''.
22722 Currently these are found only in the @code{STARLET} package spec.
22723
22724 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
22725 where the address size is constrained to 32 bits.
22726 @end itemize
22727
22728 @noindent
22729 None of the above changes is visible to users.
22730
22731 @node Bindings
22732 @section Bindings
22733
22734 @noindent
22735 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
22736 @itemize @bullet
22737
22738 @item Command Language Interpreter (CLI interface)
22739
22740 @item DECtalk Run-Time Library (DTK interface)
22741
22742 @item Librarian utility routines (LBR interface)
22743
22744 @item General Purpose Run-Time Library (LIB interface)
22745
22746 @item Math Run-Time Library (MTH interface)
22747
22748 @item National Character Set Run-Time Library (NCS interface)
22749
22750 @item Compiled Code Support Run-Time Library (OTS interface)
22751
22752 @item Parallel Processing Run-Time Library (PPL interface)
22753
22754 @item Screen Management Run-Time Library (SMG interface)
22755
22756 @item Sort Run-Time Library (SOR interface)
22757
22758 @item String Run-Time Library (STR interface)
22759
22760 @item STARLET System Library
22761 @findex Starlet
22762
22763 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
22764
22765 @item X Windows Toolkit (XT interface)
22766
22767 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
22768 @end itemize
22769
22770 @noindent
22771 GNAT provides implementations of these HP bindings in the @code{DECLIB}
22772 directory, on both the Alpha and I64 OpenVMS platforms.
22773
22774 The X components of DECLIB compatibility package are located in a separate
22775 library, called XDECGNAT, which is not linked with by default; this library
22776 must be explicitly linked with any application that makes use of any X facilities,
22777 with a command similar to
22778
22779 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
22780
22781 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
22782 in the
22783 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
22784 A pragma @code{Linker_Options} has been added to packages @code{Xm},
22785 @code{Xt}, and @code{X_Lib}
22786 causing the default X/Motif sharable image libraries to be linked in. This
22787 is done via options files named @file{xm.opt}, @file{xt.opt}, and
22788 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
22789
22790 It may be necessary to edit these options files to update or correct the
22791 library names if, for example, the newer X/Motif bindings from
22792 @file{ADA$EXAMPLES}
22793 had been (previous to installing GNAT) copied and renamed to supersede the
22794 default @file{ADA$PREDEFINED} versions.
22795
22796 @menu
22797 * Shared Libraries and Options Files::
22798 * Interfaces to C::
22799 @end menu
22800
22801 @node Shared Libraries and Options Files
22802 @subsection Shared Libraries and Options Files
22803
22804 @noindent
22805 When using the HP Ada
22806 predefined X and Motif bindings, the linking with their sharable images is
22807 done automatically by @command{GNAT LINK}.
22808 When using other X and Motif bindings, you need
22809 to add the corresponding sharable images to the command line for
22810 @code{GNAT LINK}. When linking with shared libraries, or with
22811 @file{.OPT} files, you must
22812 also add them to the command line for @command{GNAT LINK}.
22813
22814 A shared library to be used with GNAT is built in the same way as other
22815 libraries under VMS. The VMS Link command can be used in standard fashion.
22816
22817 @node Interfaces to C
22818 @subsection Interfaces to C
22819
22820 @noindent
22821 HP Ada
22822 provides the following Ada types and operations:
22823
22824 @itemize @bullet
22825 @item C types package (@code{C_TYPES})
22826
22827 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22828
22829 @item Other_types (@code{SHORT_INT})
22830 @end itemize
22831
22832 @noindent
22833 Interfacing to C with GNAT, you can use the above approach
22834 described for HP Ada or the facilities of Annex B of
22835 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22836 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22837 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22838
22839 The @option{-gnatF} qualifier forces default and explicit
22840 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22841 to be uppercased for compatibility with the default behavior
22842 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22843
22844 @node Main Program Definition
22845 @section Main Program Definition
22846
22847 @noindent
22848 The following section discusses differences in the
22849 definition of main programs on HP Ada and GNAT.
22850 On HP Ada, main programs are defined to meet the
22851 following conditions:
22852 @itemize @bullet
22853 @item Procedure with no formal parameters (returns @code{0} upon
22854 normal completion)
22855
22856 @item Procedure with no formal parameters (returns @code{42} when
22857 an unhandled exception is raised)
22858
22859 @item Function with no formal parameters whose returned value
22860 is of a discrete type
22861
22862 @item Procedure with one @code{out} formal of a discrete type for
22863 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22864
22865 @end itemize
22866
22867 @noindent
22868 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22869 a main function or main procedure returns a discrete
22870 value whose size is less than 64 bits (32 on VAX systems),
22871 the value is zero- or sign-extended as appropriate.
22872 On GNAT, main programs are defined as follows:
22873 @itemize @bullet
22874 @item Must be a non-generic, parameterless subprogram that
22875 is either a procedure or function returning an Ada
22876 @code{STANDARD.INTEGER} (the predefined type)
22877
22878 @item Cannot be a generic subprogram or an instantiation of a
22879 generic subprogram
22880 @end itemize
22881
22882 @node Implementation-Defined Attributes
22883 @section Implementation-Defined Attributes
22884
22885 @noindent
22886 GNAT provides all HP Ada implementation-defined
22887 attributes.
22888
22889 @node Compiler and Run-Time Interfacing
22890 @section Compiler and Run-Time Interfacing
22891
22892 @noindent
22893 HP Ada provides the following qualifiers to pass options to the linker
22894 (ACS LINK):
22895 @itemize @bullet
22896 @item @option{/WAIT} and @option{/SUBMIT}
22897
22898 @item @option{/COMMAND}
22899
22900 @item @option{/@r{[}NO@r{]}MAP}
22901
22902 @item @option{/OUTPUT=@var{file-spec}}
22903
22904 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22905 @end itemize
22906
22907 @noindent
22908 To pass options to the linker, GNAT provides the following
22909 switches:
22910
22911 @itemize @bullet
22912 @item @option{/EXECUTABLE=@var{exec-name}}
22913
22914 @item @option{/VERBOSE}
22915
22916 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
22917 @end itemize
22918
22919 @noindent
22920 For more information on these switches, see
22921 @ref{Switches for gnatlink}.
22922 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22923 to control optimization. HP Ada also supplies the
22924 following pragmas:
22925 @itemize @bullet
22926 @item @code{OPTIMIZE}
22927
22928 @item @code{INLINE}
22929
22930 @item @code{INLINE_GENERIC}
22931
22932 @item @code{SUPPRESS_ALL}
22933
22934 @item @code{PASSIVE}
22935 @end itemize
22936
22937 @noindent
22938 In GNAT, optimization is controlled strictly by command
22939 line parameters, as described in the corresponding section of this guide.
22940 The HP pragmas for control of optimization are
22941 recognized but ignored.
22942
22943 Note that in GNAT, the default is optimization off, whereas in HP Ada
22944 the default is that optimization is turned on.
22945
22946 @node Program Compilation and Library Management
22947 @section Program Compilation and Library Management
22948
22949 @noindent
22950 HP Ada and GNAT provide a comparable set of commands to
22951 build programs. HP Ada also provides a program library,
22952 which is a concept that does not exist on GNAT. Instead,
22953 GNAT provides directories of sources that are compiled as
22954 needed.
22955
22956 The following table summarizes
22957 the HP Ada commands and provides
22958 equivalent GNAT commands. In this table, some GNAT
22959 equivalents reflect the fact that GNAT does not use the
22960 concept of a program library. Instead, it uses a model
22961 in which collections of source and object files are used
22962 in a manner consistent with other languages like C and
22963 Fortran. Therefore, standard system file commands are used
22964 to manipulate these elements. Those GNAT commands are marked with
22965 an asterisk.
22966 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22967
22968 @need 1500
22969 @multitable @columnfractions .35 .65
22970
22971 @item @emph{HP Ada Command}
22972 @tab @emph{GNAT Equivalent / Description}
22973
22974 @item @command{ADA}
22975 @tab @command{GNAT COMPILE}@*
22976 Invokes the compiler to compile one or more Ada source files.
22977
22978 @item @command{ACS ATTACH}@*
22979 @tab [No equivalent]@*
22980 Switches control of terminal from current process running the program
22981 library manager.
22982
22983 @item @command{ACS CHECK}
22984 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22985 Forms the execution closure of one
22986 or more compiled units and checks completeness and currency.
22987
22988 @item @command{ACS COMPILE}
22989 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22990 Forms the execution closure of one or
22991 more specified units, checks completeness and currency,
22992 identifies units that have revised source files, compiles same,
22993 and recompiles units that are or will become obsolete.
22994 Also completes incomplete generic instantiations.
22995
22996 @item @command{ACS COPY FOREIGN}
22997 @tab Copy (*)@*
22998 Copies a foreign object file into the program library as a
22999 library unit body.
23000
23001 @item @command{ACS COPY UNIT}
23002 @tab Copy (*)@*
23003 Copies a compiled unit from one program library to another.
23004
23005 @item @command{ACS CREATE LIBRARY}
23006 @tab Create /directory (*)@*
23007 Creates a program library.
23008
23009 @item @command{ACS CREATE SUBLIBRARY}
23010 @tab Create /directory (*)@*
23011 Creates a program sublibrary.
23012
23013 @item @command{ACS DELETE LIBRARY}
23014 @tab @*
23015 Deletes a program library and its contents.
23016
23017 @item @command{ACS DELETE SUBLIBRARY}
23018 @tab @*
23019 Deletes a program sublibrary and its contents.
23020
23021 @item @command{ACS DELETE UNIT}
23022 @tab Delete file (*)@*
23023 On OpenVMS systems, deletes one or more compiled units from
23024 the current program library.
23025
23026 @item @command{ACS DIRECTORY}
23027 @tab Directory (*)@*
23028 On OpenVMS systems, lists units contained in the current
23029 program library.
23030
23031 @item @command{ACS ENTER FOREIGN}
23032 @tab Copy (*)@*
23033 Allows the import of a foreign body as an Ada library
23034 spec and enters a reference to a pointer.
23035
23036 @item @command{ACS ENTER UNIT}
23037 @tab Copy (*)@*
23038 Enters a reference (pointer) from the current program library to
23039 a unit compiled into another program library.
23040
23041 @item @command{ACS EXIT}
23042 @tab [No equivalent]@*
23043 Exits from the program library manager.
23044
23045 @item @command{ACS EXPORT}
23046 @tab Copy (*)@*
23047 Creates an object file that contains system-specific object code
23048 for one or more units. With GNAT, object files can simply be copied
23049 into the desired directory.
23050
23051 @item @command{ACS EXTRACT SOURCE}
23052 @tab Copy (*)@*
23053 Allows access to the copied source file for each Ada compilation unit
23054
23055 @item @command{ACS HELP}
23056 @tab @command{HELP GNAT}@*
23057 Provides online help.
23058
23059 @item @command{ACS LINK}
23060 @tab @command{GNAT LINK}@*
23061 Links an object file containing Ada units into an executable file.
23062
23063 @item @command{ACS LOAD}
23064 @tab Copy (*)@*
23065 Loads (partially compiles) Ada units into the program library.
23066 Allows loading a program from a collection of files into a library
23067 without knowing the relationship among units.
23068
23069 @item @command{ACS MERGE}
23070 @tab Copy (*)@*
23071 Merges into the current program library, one or more units from
23072 another library where they were modified.
23073
23074 @item @command{ACS RECOMPILE}
23075 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23076 Recompiles from external or copied source files any obsolete
23077 unit in the closure. Also, completes any incomplete generic
23078 instantiations.
23079
23080 @item @command{ACS REENTER}
23081 @tab @command{GNAT MAKE}@*
23082 Reenters current references to units compiled after last entered
23083 with the @command{ACS ENTER UNIT} command.
23084
23085 @item @command{ACS SET LIBRARY}
23086 @tab Set default (*)@*
23087 Defines a program library to be the compilation context as well
23088 as the target library for compiler output and commands in general.
23089
23090 @item @command{ACS SET PRAGMA}
23091 @tab Edit @file{gnat.adc} (*)@*
23092 Redefines specified values of the library characteristics
23093 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23094 and @code{Float_Representation}.
23095
23096 @item @command{ACS SET SOURCE}
23097 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23098 Defines the source file search list for the @command{ACS COMPILE} command.
23099
23100 @item @command{ACS SHOW LIBRARY}
23101 @tab Directory (*)@*
23102 Lists information about one or more program libraries.
23103
23104 @item @command{ACS SHOW PROGRAM}
23105 @tab [No equivalent]@*
23106 Lists information about the execution closure of one or
23107 more units in the program library.
23108
23109 @item @command{ACS SHOW SOURCE}
23110 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23111 Shows the source file search used when compiling units.
23112
23113 @item @command{ACS SHOW VERSION}
23114 @tab Compile with @option{VERBOSE} option
23115 Displays the version number of the compiler and program library
23116 manager used.
23117
23118 @item @command{ACS SPAWN}
23119 @tab [No equivalent]@*
23120 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23121 command).
23122
23123 @item @command{ACS VERIFY}
23124 @tab [No equivalent]@*
23125 Performs a series of consistency checks on a program library to
23126 determine whether the library structure and library files are in
23127 valid form.
23128 @end multitable
23129
23130 @noindent
23131
23132 @node Input-Output
23133 @section Input-Output
23134
23135 @noindent
23136 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23137 Management Services (RMS) to perform operations on
23138 external files.
23139
23140 @noindent
23141 HP Ada and GNAT predefine an identical set of input-
23142 output packages. To make the use of the
23143 generic @code{TEXT_IO} operations more convenient, HP Ada
23144 provides predefined library packages that instantiate the
23145 integer and floating-point operations for the predefined
23146 integer and floating-point types as shown in the following table.
23147
23148 @multitable @columnfractions .45 .55
23149 @item @emph{Package Name} @tab Instantiation
23150
23151 @item @code{INTEGER_TEXT_IO}
23152 @tab @code{INTEGER_IO(INTEGER)}
23153
23154 @item @code{SHORT_INTEGER_TEXT_IO}
23155 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23156
23157 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23158 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23159
23160 @item @code{FLOAT_TEXT_IO}
23161 @tab @code{FLOAT_IO(FLOAT)}
23162
23163 @item @code{LONG_FLOAT_TEXT_IO}
23164 @tab @code{FLOAT_IO(LONG_FLOAT)}
23165 @end multitable
23166
23167 @noindent
23168 The HP Ada predefined packages and their operations
23169 are implemented using OpenVMS Alpha files and input-output
23170 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23171 Familiarity with the following is recommended:
23172 @itemize @bullet
23173 @item RMS file organizations and access methods
23174
23175 @item OpenVMS file specifications and directories
23176
23177 @item OpenVMS File Definition Language (FDL)
23178 @end itemize
23179
23180 @noindent
23181 GNAT provides I/O facilities that are completely
23182 compatible with HP Ada. The distribution includes the
23183 standard HP Ada versions of all I/O packages, operating
23184 in a manner compatible with HP Ada. In particular, the
23185 following packages are by default the HP Ada (Ada 83)
23186 versions of these packages rather than the renamings
23187 suggested in Annex J of the Ada Reference Manual:
23188 @itemize @bullet
23189 @item @code{TEXT_IO}
23190
23191 @item @code{SEQUENTIAL_IO}
23192
23193 @item @code{DIRECT_IO}
23194 @end itemize
23195
23196 @noindent
23197 The use of the standard child package syntax (for
23198 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23199 packages.
23200 GNAT provides HP-compatible predefined instantiations
23201 of the @code{TEXT_IO} packages, and also
23202 provides the standard predefined instantiations required
23203 by the @cite{Ada Reference Manual}.
23204
23205 For further information on how GNAT interfaces to the file
23206 system or how I/O is implemented in programs written in
23207 mixed languages, see @ref{Implementation of the Standard I/O,,,
23208 gnat_rm, GNAT Reference Manual}.
23209 This chapter covers the following:
23210 @itemize @bullet
23211 @item Standard I/O packages
23212
23213 @item @code{FORM} strings
23214
23215 @item @code{ADA.DIRECT_IO}
23216
23217 @item @code{ADA.SEQUENTIAL_IO}
23218
23219 @item @code{ADA.TEXT_IO}
23220
23221 @item Stream pointer positioning
23222
23223 @item Reading and writing non-regular files
23224
23225 @item @code{GET_IMMEDIATE}
23226
23227 @item Treating @code{TEXT_IO} files as streams
23228
23229 @item Shared files
23230
23231 @item Open modes
23232 @end itemize
23233
23234 @node Implementation Limits
23235 @section Implementation Limits
23236
23237 @noindent
23238 The following table lists implementation limits for HP Ada
23239 and GNAT systems.
23240 @multitable @columnfractions .60 .20 .20
23241 @sp 1
23242 @item @emph{Compilation Parameter}
23243 @tab @emph{HP Ada}
23244 @tab @emph{GNAT}
23245 @sp 1
23246
23247 @item In a subprogram or entry declaration, maximum number of
23248 formal parameters that are of an unconstrained record type
23249 @tab 32
23250 @tab No set limit
23251 @sp 1
23252
23253 @item Maximum identifier length (number of characters)
23254 @tab 255
23255 @tab 32766
23256 @sp 1
23257
23258 @item Maximum number of characters in a source line
23259 @tab 255
23260 @tab 32766
23261 @sp 1
23262
23263 @item Maximum collection size (number of bytes)
23264 @tab 2**31-1
23265 @tab 2**31-1
23266 @sp 1
23267
23268 @item Maximum number of discriminants for a record type
23269 @tab 245
23270 @tab No set limit
23271 @sp 1
23272
23273 @item Maximum number of formal parameters in an entry or
23274 subprogram declaration
23275 @tab 246
23276 @tab No set limit
23277 @sp 1
23278
23279 @item Maximum number of dimensions in an array type
23280 @tab 255
23281 @tab No set limit
23282 @sp 1
23283
23284 @item Maximum number of library units and subunits in a compilation.
23285 @tab 4095
23286 @tab No set limit
23287 @sp 1
23288
23289 @item Maximum number of library units and subunits in an execution.
23290 @tab 16383
23291 @tab No set limit
23292 @sp 1
23293
23294 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23295 or @code{PSECT_OBJECT}
23296 @tab 32757
23297 @tab No set limit
23298 @sp 1
23299
23300 @item Maximum number of enumeration literals in an enumeration type
23301 definition
23302 @tab 65535
23303 @tab No set limit
23304 @sp 1
23305
23306 @item Maximum number of lines in a source file
23307 @tab 65534
23308 @tab No set limit
23309 @sp 1
23310
23311 @item Maximum number of bits in any object
23312 @tab 2**31-1
23313 @tab 2**31-1
23314 @sp 1
23315
23316 @item Maximum size of the static portion of a stack frame (approximate)
23317 @tab 2**31-1
23318 @tab 2**31-1
23319 @end multitable
23320
23321 @node Tools and Utilities
23322 @section Tools and Utilities
23323
23324 @noindent
23325 The following table lists some of the OpenVMS development tools
23326 available for HP Ada, and the corresponding tools for
23327 use with @value{EDITION} on Alpha and I64 platforms.
23328 Aside from the debugger, all the OpenVMS tools identified are part
23329 of the DECset package.
23330
23331 @iftex
23332 @c Specify table in TeX since Texinfo does a poor job
23333 @tex
23334 \smallskip
23335 \smallskip
23336 \settabs\+Language-Sensitive Editor\quad
23337 &Product with HP Ada\quad
23338 &\cr
23339 \+\it Tool
23340 &\it Product with HP Ada
23341 & \it Product with @value{EDITION}\cr
23342 \smallskip
23343 \+Code Management System
23344 &HP CMS
23345 & HP CMS\cr
23346 \smallskip
23347 \+Language-Sensitive Editor
23348 &HP LSE
23349 & emacs or HP LSE (Alpha)\cr
23350 \+
23351 &
23352 & HP LSE (I64)\cr
23353 \smallskip
23354 \+Debugger
23355 &OpenVMS Debug
23356 & gdb (Alpha),\cr
23357 \+
23358 &
23359 & OpenVMS Debug (I64)\cr
23360 \smallskip
23361 \+Source Code Analyzer /
23362 &HP SCA
23363 & GNAT XREF\cr
23364 \+Cross Referencer
23365 &
23366 &\cr
23367 \smallskip
23368 \+Test Manager
23369 &HP Digital Test
23370 & HP DTM\cr
23371 \+
23372 &Manager (DTM)
23373 &\cr
23374 \smallskip
23375 \+Performance and
23376 & HP PCA
23377 & HP PCA\cr
23378 \+Coverage Analyzer
23379 &
23380 &\cr
23381 \smallskip
23382 \+Module Management
23383 & HP MMS
23384 & Not applicable\cr
23385 \+ System
23386 &
23387 &\cr
23388 \smallskip
23389 \smallskip
23390 @end tex
23391 @end iftex
23392
23393 @ifnottex
23394 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23395 @c the TeX version above for the printed version
23396 @flushleft
23397 @c @multitable @columnfractions .3 .4 .4
23398 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23399 @item @i{Tool}
23400 @tab @i{Tool with HP Ada}
23401 @tab @i{Tool with @value{EDITION}}
23402 @item Code Management@*System
23403 @tab HP CMS
23404 @tab HP CMS
23405 @item Language-Sensitive@*Editor
23406 @tab HP LSE
23407 @tab emacs or HP LSE (Alpha)
23408 @item
23409 @tab
23410 @tab HP LSE (I64)
23411 @item Debugger
23412 @tab OpenVMS Debug
23413 @tab gdb (Alpha),
23414 @item
23415 @tab
23416 @tab OpenVMS Debug (I64)
23417 @item Source Code Analyzer /@*Cross Referencer
23418 @tab HP SCA
23419 @tab GNAT XREF
23420 @item Test Manager
23421 @tab HP Digital Test@*Manager (DTM)
23422 @tab HP DTM
23423 @item Performance and@*Coverage Analyzer
23424 @tab HP PCA
23425 @tab HP PCA
23426 @item Module Management@*System
23427 @tab HP MMS
23428 @tab Not applicable
23429 @end multitable
23430 @end flushleft
23431 @end ifnottex
23432
23433 @end ifset
23434
23435 @c **************************************
23436 @node Platform-Specific Information for the Run-Time Libraries
23437 @appendix Platform-Specific Information for the Run-Time Libraries
23438 @cindex Tasking and threads libraries
23439 @cindex Threads libraries and tasking
23440 @cindex Run-time libraries (platform-specific information)
23441
23442 @noindent
23443 The GNAT run-time implementation may vary with respect to both the
23444 underlying threads library and the exception handling scheme.
23445 For threads support, one or more of the following are supplied:
23446 @itemize @bullet
23447 @item @b{native threads library}, a binding to the thread package from
23448 the underlying operating system
23449
23450 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23451 POSIX thread package
23452 @end itemize
23453
23454 @noindent
23455 For exception handling, either or both of two models are supplied:
23456 @itemize @bullet
23457 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23458 Most programs should experience a substantial speed improvement by
23459 being compiled with a ZCX run-time.
23460 This is especially true for
23461 tasking applications or applications with many exception handlers.}
23462 @cindex Zero-Cost Exceptions
23463 @cindex ZCX (Zero-Cost Exceptions)
23464 which uses binder-generated tables that
23465 are interrogated at run time to locate a handler
23466
23467 @item @b{setjmp / longjmp} (``SJLJ''),
23468 @cindex setjmp/longjmp Exception Model
23469 @cindex SJLJ (setjmp/longjmp Exception Model)
23470 which uses dynamically-set data to establish
23471 the set of handlers
23472 @end itemize
23473
23474 @noindent
23475 This appendix summarizes which combinations of threads and exception support
23476 are supplied on various GNAT platforms.
23477 It then shows how to select a particular library either
23478 permanently or temporarily,
23479 explains the properties of (and tradeoffs among) the various threads
23480 libraries, and provides some additional
23481 information about several specific platforms.
23482
23483 @menu
23484 * Summary of Run-Time Configurations::
23485 * Specifying a Run-Time Library::
23486 * Choosing the Scheduling Policy::
23487 * Solaris-Specific Considerations::
23488 * Linux-Specific Considerations::
23489 * AIX-Specific Considerations::
23490 * RTX-Specific Considerations::
23491 * HP-UX-Specific Considerations::
23492 @end menu
23493
23494 @node Summary of Run-Time Configurations
23495 @section Summary of Run-Time Configurations
23496
23497 @multitable @columnfractions .30 .70
23498 @item @b{alpha-openvms}
23499 @item @code{@ @ }@i{rts-native (default)}
23500 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23501 @item @code{@ @ @ @ }Exceptions @tab ZCX
23502 @*
23503 @item @code{@ @ }@i{rts-sjlj}
23504 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
23505 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23506 @*
23507 @item @b{ia64-hp_linux}
23508 @item @code{@ @ }@i{rts-native (default)}
23509 @item @code{@ @ @ @ }Tasking @tab pthread library
23510 @item @code{@ @ @ @ }Exceptions @tab ZCX
23511 @*
23512 @item @b{ia64-hpux}
23513 @item @code{@ @ }@i{rts-native (default)}
23514 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23515 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23516 @*
23517 @item @b{ia64-openvms}
23518 @item @code{@ @ }@i{rts-native (default)}
23519 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23520 @item @code{@ @ @ @ }Exceptions @tab ZCX
23521 @*
23522 @item @b{ia64-sgi_linux}
23523 @item @code{@ @ }@i{rts-native (default)}
23524 @item @code{@ @ @ @ }Tasking @tab pthread library
23525 @item @code{@ @ @ @ }Exceptions @tab ZCX
23526 @*
23527 @item @b{pa-hpux}
23528 @item @code{@ @ }@i{rts-native (default)}
23529 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23530 @item @code{@ @ @ @ }Exceptions @tab ZCX
23531 @*
23532 @item @code{@ @ }@i{rts-sjlj}
23533 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23534 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23535 @*
23536 @item @b{ppc-aix}
23537 @item @code{@ @ }@i{rts-native (default)}
23538 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23539 @item @code{@ @ @ @ }Exceptions @tab ZCX
23540 @*
23541 @item @code{@ @ }@i{rts-sjlj}
23542 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23543 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23544 @*
23545 @item @b{ppc-darwin}
23546 @item @code{@ @ }@i{rts-native (default)}
23547 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
23548 @item @code{@ @ @ @ }Exceptions @tab ZCX
23549 @*
23550 @item @b{sparc-solaris} @tab
23551 @item @code{@ @ }@i{rts-native (default)}
23552 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23553 @item @code{@ @ @ @ }Exceptions @tab ZCX
23554 @*
23555 @item @code{@ @ }@i{rts-pthread}
23556 @item @code{@ @ @ @ }Tasking @tab pthread library
23557 @item @code{@ @ @ @ }Exceptions @tab ZCX
23558 @*
23559 @item @code{@ @ }@i{rts-sjlj}
23560 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23561 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23562 @*
23563 @item @b{sparc64-solaris} @tab
23564 @item @code{@ @ }@i{rts-native (default)}
23565 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23566 @item @code{@ @ @ @ }Exceptions @tab ZCX
23567 @*
23568 @item @b{x86-linux}
23569 @item @code{@ @ }@i{rts-native (default)}
23570 @item @code{@ @ @ @ }Tasking @tab pthread library
23571 @item @code{@ @ @ @ }Exceptions @tab ZCX
23572 @*
23573 @item @code{@ @ }@i{rts-sjlj}
23574 @item @code{@ @ @ @ }Tasking @tab pthread library
23575 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23576 @*
23577 @item @b{x86-lynx}
23578 @item @code{@ @ }@i{rts-native (default)}
23579 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
23580 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23581 @*
23582 @item @b{x86-solaris}
23583 @item @code{@ @ }@i{rts-native (default)}
23584 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
23585 @item @code{@ @ @ @ }Exceptions @tab ZCX
23586 @*
23587 @item @code{@ @ }@i{rts-sjlj}
23588 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23589 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23590 @*
23591 @item @b{x86-windows}
23592 @item @code{@ @ }@i{rts-native (default)}
23593 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23594 @item @code{@ @ @ @ }Exceptions @tab ZCX
23595 @*
23596 @item @code{@ @ }@i{rts-sjlj}
23597 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23598 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23599 @*
23600 @item @b{x86-windows-rtx}
23601 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23602 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
23603 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23604 @*
23605 @item @code{@ @ }@i{rts-rtx-w32}
23606 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
23607 @item @code{@ @ @ @ }Exceptions @tab ZCX
23608 @*
23609 @item @b{x86_64-linux}
23610 @item @code{@ @ }@i{rts-native (default)}
23611 @item @code{@ @ @ @ }Tasking @tab pthread library
23612 @item @code{@ @ @ @ }Exceptions @tab ZCX
23613 @*
23614 @item @code{@ @ }@i{rts-sjlj}
23615 @item @code{@ @ @ @ }Tasking @tab pthread library
23616 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23617 @*
23618 @end multitable
23619
23620 @node Specifying a Run-Time Library
23621 @section Specifying a Run-Time Library
23622
23623 @noindent
23624 The @file{adainclude} subdirectory containing the sources of the GNAT
23625 run-time library, and the @file{adalib} subdirectory containing the
23626 @file{ALI} files and the static and/or shared GNAT library, are located
23627 in the gcc target-dependent area:
23628
23629 @smallexample
23630 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23631 @end smallexample
23632
23633 @noindent
23634 As indicated above, on some platforms several run-time libraries are supplied.
23635 These libraries are installed in the target dependent area and
23636 contain a complete source and binary subdirectory. The detailed description
23637 below explains the differences between the different libraries in terms of
23638 their thread support.
23639
23640 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23641 This default run time is selected by the means of soft links.
23642 For example on x86-linux:
23643
23644 @smallexample
23645 @group
23646 $(target-dir)
23647 |
23648 +--- adainclude----------+
23649 | |
23650 +--- adalib-----------+ |
23651 | | |
23652 +--- rts-native | |
23653 | | | |
23654 | +--- adainclude <---+
23655 | | |
23656 | +--- adalib <----+
23657 |
23658 +--- rts-sjlj
23659 |
23660 +--- adainclude
23661 |
23662 +--- adalib
23663 @end group
23664 @end smallexample
23665
23666 @noindent
23667 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23668 these soft links can be modified with the following commands:
23669
23670 @smallexample
23671 $ cd $target
23672 $ rm -f adainclude adalib
23673 $ ln -s rts-sjlj/adainclude adainclude
23674 $ ln -s rts-sjlj/adalib adalib
23675 @end smallexample
23676
23677 @noindent
23678 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23679 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23680 @file{$target/ada_object_path}.
23681
23682 Selecting another run-time library temporarily can be
23683 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23684 @cindex @option{--RTS} option
23685
23686 @node Choosing the Scheduling Policy
23687 @section Choosing the Scheduling Policy
23688
23689 @noindent
23690 When using a POSIX threads implementation, you have a choice of several
23691 scheduling policies: @code{SCHED_FIFO},
23692 @cindex @code{SCHED_FIFO} scheduling policy
23693 @code{SCHED_RR}
23694 @cindex @code{SCHED_RR} scheduling policy
23695 and @code{SCHED_OTHER}.
23696 @cindex @code{SCHED_OTHER} scheduling policy
23697 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23698 or @code{SCHED_RR} requires special (e.g., root) privileges.
23699
23700 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23701 @code{SCHED_FIFO},
23702 @cindex @code{SCHED_FIFO} scheduling policy
23703 you can use one of the following:
23704
23705 @itemize @bullet
23706 @item
23707 @code{pragma Time_Slice (0.0)}
23708 @cindex pragma Time_Slice
23709 @item
23710 the corresponding binder option @option{-T0}
23711 @cindex @option{-T0} option
23712 @item
23713 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23714 @cindex pragma Task_Dispatching_Policy
23715 @end itemize
23716
23717 @noindent
23718 To specify @code{SCHED_RR},
23719 @cindex @code{SCHED_RR} scheduling policy
23720 you should use @code{pragma Time_Slice} with a
23721 value greater than @code{0.0}, or else use the corresponding @option{-T}
23722 binder option.
23723
23724 @node Solaris-Specific Considerations
23725 @section Solaris-Specific Considerations
23726 @cindex Solaris Sparc threads libraries
23727
23728 @noindent
23729 This section addresses some topics related to the various threads libraries
23730 on Sparc Solaris.
23731
23732 @menu
23733 * Solaris Threads Issues::
23734 @end menu
23735
23736 @node Solaris Threads Issues
23737 @subsection Solaris Threads Issues
23738
23739 @noindent
23740 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23741 library based on POSIX threads --- @emph{rts-pthread}.
23742 @cindex rts-pthread threads library
23743 This run-time library has the advantage of being mostly shared across all
23744 POSIX-compliant thread implementations, and it also provides under
23745 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
23746 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
23747 and @code{PTHREAD_PRIO_PROTECT}
23748 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
23749 semantics that can be selected using the predefined pragma
23750 @code{Locking_Policy}
23751 @cindex pragma Locking_Policy (under rts-pthread)
23752 with respectively
23753 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
23754 @cindex @code{Inheritance_Locking} (under rts-pthread)
23755 @cindex @code{Ceiling_Locking} (under rts-pthread)
23756
23757 As explained above, the native run-time library is based on the Solaris thread
23758 library (@code{libthread}) and is the default library.
23759
23760 When the Solaris threads library is used (this is the default), programs
23761 compiled with GNAT can automatically take advantage of
23762 and can thus execute on multiple processors.
23763 The user can alternatively specify a processor on which the program should run
23764 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23765 is made by
23766 setting the environment variable @env{GNAT_PROCESSOR}
23767 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
23768 to one of the following:
23769
23770 @table @code
23771 @item -2
23772 Use the default configuration (run the program on all
23773 available processors) - this is the same as having @code{GNAT_PROCESSOR}
23774 unset
23775
23776 @item -1
23777 Let the run-time implementation choose one processor and run the program on
23778 that processor
23779
23780 @item 0 .. Last_Proc
23781 Run the program on the specified processor.
23782 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
23783 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
23784 @end table
23785
23786 @node Linux-Specific Considerations
23787 @section Linux-Specific Considerations
23788 @cindex Linux threads libraries
23789
23790 @noindent
23791 On GNU/Linux without NPTL support (usually system with GNU C Library
23792 older than 2.3), the signal model is not POSIX compliant, which means
23793 that to send a signal to the process, you need to send the signal to all
23794 threads, e.g.@: by using @code{killpg()}.
23795
23796 @node AIX-Specific Considerations
23797 @section AIX-Specific Considerations
23798 @cindex AIX resolver library
23799
23800 @noindent
23801 On AIX, the resolver library initializes some internal structure on
23802 the first call to @code{get*by*} functions, which are used to implement
23803 @code{GNAT.Sockets.Get_Host_By_Name} and
23804 @code{GNAT.Sockets.Get_Host_By_Address}.
23805 If such initialization occurs within an Ada task, and the stack size for
23806 the task is the default size, a stack overflow may occur.
23807
23808 To avoid this overflow, the user should either ensure that the first call
23809 to @code{GNAT.Sockets.Get_Host_By_Name} or
23810 @code{GNAT.Sockets.Get_Host_By_Addrss}
23811 occurs in the environment task, or use @code{pragma Storage_Size} to
23812 specify a sufficiently large size for the stack of the task that contains
23813 this call.
23814
23815 @node RTX-Specific Considerations
23816 @section RTX-Specific Considerations
23817 @cindex RTX libraries
23818
23819 @noindent
23820 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23821 API. Applications can be built to work in two different modes:
23822
23823 @itemize @bullet
23824 @item
23825 Windows executables that run in Ring 3 to utilize memory protection
23826 (@emph{rts-rtx-w32}).
23827
23828 @item
23829 Real-time subsystem (RTSS) executables that run in Ring 0, where
23830 performance can be optimized with RTSS applications taking precedent
23831 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23832 the Microsoft linker to handle RTSS libraries.
23833
23834 @end itemize
23835
23836 @node HP-UX-Specific Considerations
23837 @section HP-UX-Specific Considerations
23838 @cindex HP-UX Scheduling
23839
23840 @noindent
23841 On HP-UX, appropriate privileges are required to change the scheduling
23842 parameters of a task. The calling process must have appropriate
23843 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23844 successfully change the scheduling parameters.
23845
23846 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23847 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23848 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23849
23850 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23851 one of the following:
23852
23853 @itemize @bullet
23854 @item
23855 @code{pragma Time_Slice (0.0)}
23856 @cindex pragma Time_Slice
23857 @item
23858 the corresponding binder option @option{-T0}
23859 @cindex @option{-T0} option
23860 @item
23861 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23862 @cindex pragma Task_Dispatching_Policy
23863 @end itemize
23864
23865 @noindent
23866 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23867 you should use @code{pragma Time_Slice} with a
23868 value greater than @code{0.0}, or use the corresponding @option{-T}
23869 binder option, or set the @code{pragma Task_Dispatching_Policy
23870 (Round_Robin_Within_Priorities)}.
23871
23872 @c *******************************
23873 @node Example of Binder Output File
23874 @appendix Example of Binder Output File
23875
23876 @noindent
23877 This Appendix displays the source code for @command{gnatbind}'s output
23878 file generated for a simple ``Hello World'' program.
23879 Comments have been added for clarification purposes.
23880
23881 @smallexample @c adanocomment
23882 @iftex
23883 @leftskip=0cm
23884 @end iftex
23885 -- The package is called Ada_Main unless this name is actually used
23886 -- as a unit name in the partition, in which case some other unique
23887 -- name is used.
23888
23889 with System;
23890 package ada_main is
23891
23892 Elab_Final_Code : Integer;
23893 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23894
23895 -- The main program saves the parameters (argument count,
23896 -- argument values, environment pointer) in global variables
23897 -- for later access by other units including
23898 -- Ada.Command_Line.
23899
23900 gnat_argc : Integer;
23901 gnat_argv : System.Address;
23902 gnat_envp : System.Address;
23903
23904 -- The actual variables are stored in a library routine. This
23905 -- is useful for some shared library situations, where there
23906 -- are problems if variables are not in the library.
23907
23908 pragma Import (C, gnat_argc);
23909 pragma Import (C, gnat_argv);
23910 pragma Import (C, gnat_envp);
23911
23912 -- The exit status is similarly an external location
23913
23914 gnat_exit_status : Integer;
23915 pragma Import (C, gnat_exit_status);
23916
23917 GNAT_Version : constant String :=
23918 "GNAT Version: 6.0.0w (20061115)";
23919 pragma Export (C, GNAT_Version, "__gnat_version");
23920
23921 -- This is the generated adafinal routine that performs
23922 -- finalization at the end of execution. In the case where
23923 -- Ada is the main program, this main program makes a call
23924 -- to adafinal at program termination.
23925
23926 procedure adafinal;
23927 pragma Export (C, adafinal, "adafinal");
23928
23929 -- This is the generated adainit routine that performs
23930 -- initialization at the start of execution. In the case
23931 -- where Ada is the main program, this main program makes
23932 -- a call to adainit at program startup.
23933
23934 procedure adainit;
23935 pragma Export (C, adainit, "adainit");
23936
23937 -- This routine is called at the start of execution. It is
23938 -- a dummy routine that is used by the debugger to breakpoint
23939 -- at the start of execution.
23940
23941 procedure Break_Start;
23942 pragma Import (C, Break_Start, "__gnat_break_start");
23943
23944 -- This is the actual generated main program (it would be
23945 -- suppressed if the no main program switch were used). As
23946 -- required by standard system conventions, this program has
23947 -- the external name main.
23948
23949 function main
23950 (argc : Integer;
23951 argv : System.Address;
23952 envp : System.Address)
23953 return Integer;
23954 pragma Export (C, main, "main");
23955
23956 -- The following set of constants give the version
23957 -- identification values for every unit in the bound
23958 -- partition. This identification is computed from all
23959 -- dependent semantic units, and corresponds to the
23960 -- string that would be returned by use of the
23961 -- Body_Version or Version attributes.
23962
23963 type Version_32 is mod 2 ** 32;
23964 u00001 : constant Version_32 := 16#7880BEB3#;
23965 u00002 : constant Version_32 := 16#0D24CBD0#;
23966 u00003 : constant Version_32 := 16#3283DBEB#;
23967 u00004 : constant Version_32 := 16#2359F9ED#;
23968 u00005 : constant Version_32 := 16#664FB847#;
23969 u00006 : constant Version_32 := 16#68E803DF#;
23970 u00007 : constant Version_32 := 16#5572E604#;
23971 u00008 : constant Version_32 := 16#46B173D8#;
23972 u00009 : constant Version_32 := 16#156A40CF#;
23973 u00010 : constant Version_32 := 16#033DABE0#;
23974 u00011 : constant Version_32 := 16#6AB38FEA#;
23975 u00012 : constant Version_32 := 16#22B6217D#;
23976 u00013 : constant Version_32 := 16#68A22947#;
23977 u00014 : constant Version_32 := 16#18CC4A56#;
23978 u00015 : constant Version_32 := 16#08258E1B#;
23979 u00016 : constant Version_32 := 16#367D5222#;
23980 u00017 : constant Version_32 := 16#20C9ECA4#;
23981 u00018 : constant Version_32 := 16#50D32CB6#;
23982 u00019 : constant Version_32 := 16#39A8BB77#;
23983 u00020 : constant Version_32 := 16#5CF8FA2B#;
23984 u00021 : constant Version_32 := 16#2F1EB794#;
23985 u00022 : constant Version_32 := 16#31AB6444#;
23986 u00023 : constant Version_32 := 16#1574B6E9#;
23987 u00024 : constant Version_32 := 16#5109C189#;
23988 u00025 : constant Version_32 := 16#56D770CD#;
23989 u00026 : constant Version_32 := 16#02F9DE3D#;
23990 u00027 : constant Version_32 := 16#08AB6B2C#;
23991 u00028 : constant Version_32 := 16#3FA37670#;
23992 u00029 : constant Version_32 := 16#476457A0#;
23993 u00030 : constant Version_32 := 16#731E1B6E#;
23994 u00031 : constant Version_32 := 16#23C2E789#;
23995 u00032 : constant Version_32 := 16#0F1BD6A1#;
23996 u00033 : constant Version_32 := 16#7C25DE96#;
23997 u00034 : constant Version_32 := 16#39ADFFA2#;
23998 u00035 : constant Version_32 := 16#571DE3E7#;
23999 u00036 : constant Version_32 := 16#5EB646AB#;
24000 u00037 : constant Version_32 := 16#4249379B#;
24001 u00038 : constant Version_32 := 16#0357E00A#;
24002 u00039 : constant Version_32 := 16#3784FB72#;
24003 u00040 : constant Version_32 := 16#2E723019#;
24004 u00041 : constant Version_32 := 16#623358EA#;
24005 u00042 : constant Version_32 := 16#107F9465#;
24006 u00043 : constant Version_32 := 16#6843F68A#;
24007 u00044 : constant Version_32 := 16#63305874#;
24008 u00045 : constant Version_32 := 16#31E56CE1#;
24009 u00046 : constant Version_32 := 16#02917970#;
24010 u00047 : constant Version_32 := 16#6CCBA70E#;
24011 u00048 : constant Version_32 := 16#41CD4204#;
24012 u00049 : constant Version_32 := 16#572E3F58#;
24013 u00050 : constant Version_32 := 16#20729FF5#;
24014 u00051 : constant Version_32 := 16#1D4F93E8#;
24015 u00052 : constant Version_32 := 16#30B2EC3D#;
24016 u00053 : constant Version_32 := 16#34054F96#;
24017 u00054 : constant Version_32 := 16#5A199860#;
24018 u00055 : constant Version_32 := 16#0E7F912B#;
24019 u00056 : constant Version_32 := 16#5760634A#;
24020 u00057 : constant Version_32 := 16#5D851835#;
24021
24022 -- The following Export pragmas export the version numbers
24023 -- with symbolic names ending in B (for body) or S
24024 -- (for spec) so that they can be located in a link. The
24025 -- information provided here is sufficient to track down
24026 -- the exact versions of units used in a given build.
24027
24028 pragma Export (C, u00001, "helloB");
24029 pragma Export (C, u00002, "system__standard_libraryB");
24030 pragma Export (C, u00003, "system__standard_libraryS");
24031 pragma Export (C, u00004, "adaS");
24032 pragma Export (C, u00005, "ada__text_ioB");
24033 pragma Export (C, u00006, "ada__text_ioS");
24034 pragma Export (C, u00007, "ada__exceptionsB");
24035 pragma Export (C, u00008, "ada__exceptionsS");
24036 pragma Export (C, u00009, "gnatS");
24037 pragma Export (C, u00010, "gnat__heap_sort_aB");
24038 pragma Export (C, u00011, "gnat__heap_sort_aS");
24039 pragma Export (C, u00012, "systemS");
24040 pragma Export (C, u00013, "system__exception_tableB");
24041 pragma Export (C, u00014, "system__exception_tableS");
24042 pragma Export (C, u00015, "gnat__htableB");
24043 pragma Export (C, u00016, "gnat__htableS");
24044 pragma Export (C, u00017, "system__exceptionsS");
24045 pragma Export (C, u00018, "system__machine_state_operationsB");
24046 pragma Export (C, u00019, "system__machine_state_operationsS");
24047 pragma Export (C, u00020, "system__machine_codeS");
24048 pragma Export (C, u00021, "system__storage_elementsB");
24049 pragma Export (C, u00022, "system__storage_elementsS");
24050 pragma Export (C, u00023, "system__secondary_stackB");
24051 pragma Export (C, u00024, "system__secondary_stackS");
24052 pragma Export (C, u00025, "system__parametersB");
24053 pragma Export (C, u00026, "system__parametersS");
24054 pragma Export (C, u00027, "system__soft_linksB");
24055 pragma Export (C, u00028, "system__soft_linksS");
24056 pragma Export (C, u00029, "system__stack_checkingB");
24057 pragma Export (C, u00030, "system__stack_checkingS");
24058 pragma Export (C, u00031, "system__tracebackB");
24059 pragma Export (C, u00032, "system__tracebackS");
24060 pragma Export (C, u00033, "ada__streamsS");
24061 pragma Export (C, u00034, "ada__tagsB");
24062 pragma Export (C, u00035, "ada__tagsS");
24063 pragma Export (C, u00036, "system__string_opsB");
24064 pragma Export (C, u00037, "system__string_opsS");
24065 pragma Export (C, u00038, "interfacesS");
24066 pragma Export (C, u00039, "interfaces__c_streamsB");
24067 pragma Export (C, u00040, "interfaces__c_streamsS");
24068 pragma Export (C, u00041, "system__file_ioB");
24069 pragma Export (C, u00042, "system__file_ioS");
24070 pragma Export (C, u00043, "ada__finalizationB");
24071 pragma Export (C, u00044, "ada__finalizationS");
24072 pragma Export (C, u00045, "system__finalization_rootB");
24073 pragma Export (C, u00046, "system__finalization_rootS");
24074 pragma Export (C, u00047, "system__finalization_implementationB");
24075 pragma Export (C, u00048, "system__finalization_implementationS");
24076 pragma Export (C, u00049, "system__string_ops_concat_3B");
24077 pragma Export (C, u00050, "system__string_ops_concat_3S");
24078 pragma Export (C, u00051, "system__stream_attributesB");
24079 pragma Export (C, u00052, "system__stream_attributesS");
24080 pragma Export (C, u00053, "ada__io_exceptionsS");
24081 pragma Export (C, u00054, "system__unsigned_typesS");
24082 pragma Export (C, u00055, "system__file_control_blockS");
24083 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24084 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24085
24086 -- BEGIN ELABORATION ORDER
24087 -- ada (spec)
24088 -- gnat (spec)
24089 -- gnat.heap_sort_a (spec)
24090 -- gnat.heap_sort_a (body)
24091 -- gnat.htable (spec)
24092 -- gnat.htable (body)
24093 -- interfaces (spec)
24094 -- system (spec)
24095 -- system.machine_code (spec)
24096 -- system.parameters (spec)
24097 -- system.parameters (body)
24098 -- interfaces.c_streams (spec)
24099 -- interfaces.c_streams (body)
24100 -- system.standard_library (spec)
24101 -- ada.exceptions (spec)
24102 -- system.exception_table (spec)
24103 -- system.exception_table (body)
24104 -- ada.io_exceptions (spec)
24105 -- system.exceptions (spec)
24106 -- system.storage_elements (spec)
24107 -- system.storage_elements (body)
24108 -- system.machine_state_operations (spec)
24109 -- system.machine_state_operations (body)
24110 -- system.secondary_stack (spec)
24111 -- system.stack_checking (spec)
24112 -- system.soft_links (spec)
24113 -- system.soft_links (body)
24114 -- system.stack_checking (body)
24115 -- system.secondary_stack (body)
24116 -- system.standard_library (body)
24117 -- system.string_ops (spec)
24118 -- system.string_ops (body)
24119 -- ada.tags (spec)
24120 -- ada.tags (body)
24121 -- ada.streams (spec)
24122 -- system.finalization_root (spec)
24123 -- system.finalization_root (body)
24124 -- system.string_ops_concat_3 (spec)
24125 -- system.string_ops_concat_3 (body)
24126 -- system.traceback (spec)
24127 -- system.traceback (body)
24128 -- ada.exceptions (body)
24129 -- system.unsigned_types (spec)
24130 -- system.stream_attributes (spec)
24131 -- system.stream_attributes (body)
24132 -- system.finalization_implementation (spec)
24133 -- system.finalization_implementation (body)
24134 -- ada.finalization (spec)
24135 -- ada.finalization (body)
24136 -- ada.finalization.list_controller (spec)
24137 -- ada.finalization.list_controller (body)
24138 -- system.file_control_block (spec)
24139 -- system.file_io (spec)
24140 -- system.file_io (body)
24141 -- ada.text_io (spec)
24142 -- ada.text_io (body)
24143 -- hello (body)
24144 -- END ELABORATION ORDER
24145
24146 end ada_main;
24147
24148 -- The following source file name pragmas allow the generated file
24149 -- names to be unique for different main programs. They are needed
24150 -- since the package name will always be Ada_Main.
24151
24152 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24153 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24154
24155 -- Generated package body for Ada_Main starts here
24156
24157 package body ada_main is
24158
24159 -- The actual finalization is performed by calling the
24160 -- library routine in System.Standard_Library.Adafinal
24161
24162 procedure Do_Finalize;
24163 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24164
24165 -------------
24166 -- adainit --
24167 -------------
24168
24169 @findex adainit
24170 procedure adainit is
24171
24172 -- These booleans are set to True once the associated unit has
24173 -- been elaborated. It is also used to avoid elaborating the
24174 -- same unit twice.
24175
24176 E040 : Boolean;
24177 pragma Import (Ada, E040, "interfaces__c_streams_E");
24178
24179 E008 : Boolean;
24180 pragma Import (Ada, E008, "ada__exceptions_E");
24181
24182 E014 : Boolean;
24183 pragma Import (Ada, E014, "system__exception_table_E");
24184
24185 E053 : Boolean;
24186 pragma Import (Ada, E053, "ada__io_exceptions_E");
24187
24188 E017 : Boolean;
24189 pragma Import (Ada, E017, "system__exceptions_E");
24190
24191 E024 : Boolean;
24192 pragma Import (Ada, E024, "system__secondary_stack_E");
24193
24194 E030 : Boolean;
24195 pragma Import (Ada, E030, "system__stack_checking_E");
24196
24197 E028 : Boolean;
24198 pragma Import (Ada, E028, "system__soft_links_E");
24199
24200 E035 : Boolean;
24201 pragma Import (Ada, E035, "ada__tags_E");
24202
24203 E033 : Boolean;
24204 pragma Import (Ada, E033, "ada__streams_E");
24205
24206 E046 : Boolean;
24207 pragma Import (Ada, E046, "system__finalization_root_E");
24208
24209 E048 : Boolean;
24210 pragma Import (Ada, E048, "system__finalization_implementation_E");
24211
24212 E044 : Boolean;
24213 pragma Import (Ada, E044, "ada__finalization_E");
24214
24215 E057 : Boolean;
24216 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24217
24218 E055 : Boolean;
24219 pragma Import (Ada, E055, "system__file_control_block_E");
24220
24221 E042 : Boolean;
24222 pragma Import (Ada, E042, "system__file_io_E");
24223
24224 E006 : Boolean;
24225 pragma Import (Ada, E006, "ada__text_io_E");
24226
24227 -- Set_Globals is a library routine that stores away the
24228 -- value of the indicated set of global values in global
24229 -- variables within the library.
24230
24231 procedure Set_Globals
24232 (Main_Priority : Integer;
24233 Time_Slice_Value : Integer;
24234 WC_Encoding : Character;
24235 Locking_Policy : Character;
24236 Queuing_Policy : Character;
24237 Task_Dispatching_Policy : Character;
24238 Adafinal : System.Address;
24239 Unreserve_All_Interrupts : Integer;
24240 Exception_Tracebacks : Integer);
24241 @findex __gnat_set_globals
24242 pragma Import (C, Set_Globals, "__gnat_set_globals");
24243
24244 -- SDP_Table_Build is a library routine used to build the
24245 -- exception tables. See unit Ada.Exceptions in files
24246 -- a-except.ads/adb for full details of how zero cost
24247 -- exception handling works. This procedure, the call to
24248 -- it, and the two following tables are all omitted if the
24249 -- build is in longjmp/setjmp exception mode.
24250
24251 @findex SDP_Table_Build
24252 @findex Zero Cost Exceptions
24253 procedure SDP_Table_Build
24254 (SDP_Addresses : System.Address;
24255 SDP_Count : Natural;
24256 Elab_Addresses : System.Address;
24257 Elab_Addr_Count : Natural);
24258 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24259
24260 -- Table of Unit_Exception_Table addresses. Used for zero
24261 -- cost exception handling to build the top level table.
24262
24263 ST : aliased constant array (1 .. 23) of System.Address := (
24264 Hello'UET_Address,
24265 Ada.Text_Io'UET_Address,
24266 Ada.Exceptions'UET_Address,
24267 Gnat.Heap_Sort_A'UET_Address,
24268 System.Exception_Table'UET_Address,
24269 System.Machine_State_Operations'UET_Address,
24270 System.Secondary_Stack'UET_Address,
24271 System.Parameters'UET_Address,
24272 System.Soft_Links'UET_Address,
24273 System.Stack_Checking'UET_Address,
24274 System.Traceback'UET_Address,
24275 Ada.Streams'UET_Address,
24276 Ada.Tags'UET_Address,
24277 System.String_Ops'UET_Address,
24278 Interfaces.C_Streams'UET_Address,
24279 System.File_Io'UET_Address,
24280 Ada.Finalization'UET_Address,
24281 System.Finalization_Root'UET_Address,
24282 System.Finalization_Implementation'UET_Address,
24283 System.String_Ops_Concat_3'UET_Address,
24284 System.Stream_Attributes'UET_Address,
24285 System.File_Control_Block'UET_Address,
24286 Ada.Finalization.List_Controller'UET_Address);
24287
24288 -- Table of addresses of elaboration routines. Used for
24289 -- zero cost exception handling to make sure these
24290 -- addresses are included in the top level procedure
24291 -- address table.
24292
24293 EA : aliased constant array (1 .. 23) of System.Address := (
24294 adainit'Code_Address,
24295 Do_Finalize'Code_Address,
24296 Ada.Exceptions'Elab_Spec'Address,
24297 System.Exceptions'Elab_Spec'Address,
24298 Interfaces.C_Streams'Elab_Spec'Address,
24299 System.Exception_Table'Elab_Body'Address,
24300 Ada.Io_Exceptions'Elab_Spec'Address,
24301 System.Stack_Checking'Elab_Spec'Address,
24302 System.Soft_Links'Elab_Body'Address,
24303 System.Secondary_Stack'Elab_Body'Address,
24304 Ada.Tags'Elab_Spec'Address,
24305 Ada.Tags'Elab_Body'Address,
24306 Ada.Streams'Elab_Spec'Address,
24307 System.Finalization_Root'Elab_Spec'Address,
24308 Ada.Exceptions'Elab_Body'Address,
24309 System.Finalization_Implementation'Elab_Spec'Address,
24310 System.Finalization_Implementation'Elab_Body'Address,
24311 Ada.Finalization'Elab_Spec'Address,
24312 Ada.Finalization.List_Controller'Elab_Spec'Address,
24313 System.File_Control_Block'Elab_Spec'Address,
24314 System.File_Io'Elab_Body'Address,
24315 Ada.Text_Io'Elab_Spec'Address,
24316 Ada.Text_Io'Elab_Body'Address);
24317
24318 -- Start of processing for adainit
24319
24320 begin
24321
24322 -- Call SDP_Table_Build to build the top level procedure
24323 -- table for zero cost exception handling (omitted in
24324 -- longjmp/setjmp mode).
24325
24326 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24327
24328 -- Call Set_Globals to record various information for
24329 -- this partition. The values are derived by the binder
24330 -- from information stored in the ali files by the compiler.
24331
24332 @findex __gnat_set_globals
24333 Set_Globals
24334 (Main_Priority => -1,
24335 -- Priority of main program, -1 if no pragma Priority used
24336
24337 Time_Slice_Value => -1,
24338 -- Time slice from Time_Slice pragma, -1 if none used
24339
24340 WC_Encoding => 'b',
24341 -- Wide_Character encoding used, default is brackets
24342
24343 Locking_Policy => ' ',
24344 -- Locking_Policy used, default of space means not
24345 -- specified, otherwise it is the first character of
24346 -- the policy name.
24347
24348 Queuing_Policy => ' ',
24349 -- Queuing_Policy used, default of space means not
24350 -- specified, otherwise it is the first character of
24351 -- the policy name.
24352
24353 Task_Dispatching_Policy => ' ',
24354 -- Task_Dispatching_Policy used, default of space means
24355 -- not specified, otherwise first character of the
24356 -- policy name.
24357
24358 Adafinal => System.Null_Address,
24359 -- Address of Adafinal routine, not used anymore
24360
24361 Unreserve_All_Interrupts => 0,
24362 -- Set true if pragma Unreserve_All_Interrupts was used
24363
24364 Exception_Tracebacks => 0);
24365 -- Indicates if exception tracebacks are enabled
24366
24367 Elab_Final_Code := 1;
24368
24369 -- Now we have the elaboration calls for all units in the partition.
24370 -- The Elab_Spec and Elab_Body attributes generate references to the
24371 -- implicit elaboration procedures generated by the compiler for
24372 -- each unit that requires elaboration.
24373
24374 if not E040 then
24375 Interfaces.C_Streams'Elab_Spec;
24376 end if;
24377 E040 := True;
24378 if not E008 then
24379 Ada.Exceptions'Elab_Spec;
24380 end if;
24381 if not E014 then
24382 System.Exception_Table'Elab_Body;
24383 E014 := True;
24384 end if;
24385 if not E053 then
24386 Ada.Io_Exceptions'Elab_Spec;
24387 E053 := True;
24388 end if;
24389 if not E017 then
24390 System.Exceptions'Elab_Spec;
24391 E017 := True;
24392 end if;
24393 if not E030 then
24394 System.Stack_Checking'Elab_Spec;
24395 end if;
24396 if not E028 then
24397 System.Soft_Links'Elab_Body;
24398 E028 := True;
24399 end if;
24400 E030 := True;
24401 if not E024 then
24402 System.Secondary_Stack'Elab_Body;
24403 E024 := True;
24404 end if;
24405 if not E035 then
24406 Ada.Tags'Elab_Spec;
24407 end if;
24408 if not E035 then
24409 Ada.Tags'Elab_Body;
24410 E035 := True;
24411 end if;
24412 if not E033 then
24413 Ada.Streams'Elab_Spec;
24414 E033 := True;
24415 end if;
24416 if not E046 then
24417 System.Finalization_Root'Elab_Spec;
24418 end if;
24419 E046 := True;
24420 if not E008 then
24421 Ada.Exceptions'Elab_Body;
24422 E008 := True;
24423 end if;
24424 if not E048 then
24425 System.Finalization_Implementation'Elab_Spec;
24426 end if;
24427 if not E048 then
24428 System.Finalization_Implementation'Elab_Body;
24429 E048 := True;
24430 end if;
24431 if not E044 then
24432 Ada.Finalization'Elab_Spec;
24433 end if;
24434 E044 := True;
24435 if not E057 then
24436 Ada.Finalization.List_Controller'Elab_Spec;
24437 end if;
24438 E057 := True;
24439 if not E055 then
24440 System.File_Control_Block'Elab_Spec;
24441 E055 := True;
24442 end if;
24443 if not E042 then
24444 System.File_Io'Elab_Body;
24445 E042 := True;
24446 end if;
24447 if not E006 then
24448 Ada.Text_Io'Elab_Spec;
24449 end if;
24450 if not E006 then
24451 Ada.Text_Io'Elab_Body;
24452 E006 := True;
24453 end if;
24454
24455 Elab_Final_Code := 0;
24456 end adainit;
24457
24458 --------------
24459 -- adafinal --
24460 --------------
24461
24462 @findex adafinal
24463 procedure adafinal is
24464 begin
24465 Do_Finalize;
24466 end adafinal;
24467
24468 ----------
24469 -- main --
24470 ----------
24471
24472 -- main is actually a function, as in the ANSI C standard,
24473 -- defined to return the exit status. The three parameters
24474 -- are the argument count, argument values and environment
24475 -- pointer.
24476
24477 @findex Main Program
24478 function main
24479 (argc : Integer;
24480 argv : System.Address;
24481 envp : System.Address)
24482 return Integer
24483 is
24484 -- The initialize routine performs low level system
24485 -- initialization using a standard library routine which
24486 -- sets up signal handling and performs any other
24487 -- required setup. The routine can be found in file
24488 -- a-init.c.
24489
24490 @findex __gnat_initialize
24491 procedure initialize;
24492 pragma Import (C, initialize, "__gnat_initialize");
24493
24494 -- The finalize routine performs low level system
24495 -- finalization using a standard library routine. The
24496 -- routine is found in file a-final.c and in the standard
24497 -- distribution is a dummy routine that does nothing, so
24498 -- really this is a hook for special user finalization.
24499
24500 @findex __gnat_finalize
24501 procedure finalize;
24502 pragma Import (C, finalize, "__gnat_finalize");
24503
24504 -- We get to the main program of the partition by using
24505 -- pragma Import because if we try to with the unit and
24506 -- call it Ada style, then not only do we waste time
24507 -- recompiling it, but also, we don't really know the right
24508 -- switches (e.g.@: identifier character set) to be used
24509 -- to compile it.
24510
24511 procedure Ada_Main_Program;
24512 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24513
24514 -- Start of processing for main
24515
24516 begin
24517 -- Save global variables
24518
24519 gnat_argc := argc;
24520 gnat_argv := argv;
24521 gnat_envp := envp;
24522
24523 -- Call low level system initialization
24524
24525 Initialize;
24526
24527 -- Call our generated Ada initialization routine
24528
24529 adainit;
24530
24531 -- This is the point at which we want the debugger to get
24532 -- control
24533
24534 Break_Start;
24535
24536 -- Now we call the main program of the partition
24537
24538 Ada_Main_Program;
24539
24540 -- Perform Ada finalization
24541
24542 adafinal;
24543
24544 -- Perform low level system finalization
24545
24546 Finalize;
24547
24548 -- Return the proper exit status
24549 return (gnat_exit_status);
24550 end;
24551
24552 -- This section is entirely comments, so it has no effect on the
24553 -- compilation of the Ada_Main package. It provides the list of
24554 -- object files and linker options, as well as some standard
24555 -- libraries needed for the link. The gnatlink utility parses
24556 -- this b~hello.adb file to read these comment lines to generate
24557 -- the appropriate command line arguments for the call to the
24558 -- system linker. The BEGIN/END lines are used for sentinels for
24559 -- this parsing operation.
24560
24561 -- The exact file names will of course depend on the environment,
24562 -- host/target and location of files on the host system.
24563
24564 @findex Object file list
24565 -- BEGIN Object file/option list
24566 -- ./hello.o
24567 -- -L./
24568 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24569 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24570 -- END Object file/option list
24571
24572 end ada_main;
24573 @end smallexample
24574
24575 @noindent
24576 The Ada code in the above example is exactly what is generated by the
24577 binder. We have added comments to more clearly indicate the function
24578 of each part of the generated @code{Ada_Main} package.
24579
24580 The code is standard Ada in all respects, and can be processed by any
24581 tools that handle Ada. In particular, it is possible to use the debugger
24582 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24583 suppose that for reasons that you do not understand, your program is crashing
24584 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24585 you can place a breakpoint on the call:
24586
24587 @smallexample @c ada
24588 Ada.Text_Io'Elab_Body;
24589 @end smallexample
24590
24591 @noindent
24592 and trace the elaboration routine for this package to find out where
24593 the problem might be (more usually of course you would be debugging
24594 elaboration code in your own application).
24595
24596 @node Elaboration Order Handling in GNAT
24597 @appendix Elaboration Order Handling in GNAT
24598 @cindex Order of elaboration
24599 @cindex Elaboration control
24600
24601 @menu
24602 * Elaboration Code::
24603 * Checking the Elaboration Order::
24604 * Controlling the Elaboration Order::
24605 * Controlling Elaboration in GNAT - Internal Calls::
24606 * Controlling Elaboration in GNAT - External Calls::
24607 * Default Behavior in GNAT - Ensuring Safety::
24608 * Treatment of Pragma Elaborate::
24609 * Elaboration Issues for Library Tasks::
24610 * Mixing Elaboration Models::
24611 * What to Do If the Default Elaboration Behavior Fails::
24612 * Elaboration for Dispatching Calls::
24613 * Summary of Procedures for Elaboration Control::
24614 * Other Elaboration Order Considerations::
24615 @end menu
24616
24617 @noindent
24618 This chapter describes the handling of elaboration code in Ada and
24619 in GNAT, and discusses how the order of elaboration of program units can
24620 be controlled in GNAT, either automatically or with explicit programming
24621 features.
24622
24623 @node Elaboration Code
24624 @section Elaboration Code
24625
24626 @noindent
24627 Ada provides rather general mechanisms for executing code at elaboration
24628 time, that is to say before the main program starts executing. Such code arises
24629 in three contexts:
24630
24631 @table @asis
24632 @item Initializers for variables.
24633 Variables declared at the library level, in package specs or bodies, can
24634 require initialization that is performed at elaboration time, as in:
24635 @smallexample @c ada
24636 @cartouche
24637 Sqrt_Half : Float := Sqrt (0.5);
24638 @end cartouche
24639 @end smallexample
24640
24641 @item Package initialization code
24642 Code in a @code{BEGIN-END} section at the outer level of a package body is
24643 executed as part of the package body elaboration code.
24644
24645 @item Library level task allocators
24646 Tasks that are declared using task allocators at the library level
24647 start executing immediately and hence can execute at elaboration time.
24648 @end table
24649
24650 @noindent
24651 Subprogram calls are possible in any of these contexts, which means that
24652 any arbitrary part of the program may be executed as part of the elaboration
24653 code. It is even possible to write a program which does all its work at
24654 elaboration time, with a null main program, although stylistically this
24655 would usually be considered an inappropriate way to structure
24656 a program.
24657
24658 An important concern arises in the context of elaboration code:
24659 we have to be sure that it is executed in an appropriate order. What we
24660 have is a series of elaboration code sections, potentially one section
24661 for each unit in the program. It is important that these execute
24662 in the correct order. Correctness here means that, taking the above
24663 example of the declaration of @code{Sqrt_Half},
24664 if some other piece of
24665 elaboration code references @code{Sqrt_Half},
24666 then it must run after the
24667 section of elaboration code that contains the declaration of
24668 @code{Sqrt_Half}.
24669
24670 There would never be any order of elaboration problem if we made a rule
24671 that whenever you @code{with} a unit, you must elaborate both the spec and body
24672 of that unit before elaborating the unit doing the @code{with}'ing:
24673
24674 @smallexample @c ada
24675 @group
24676 @cartouche
24677 with Unit_1;
24678 package Unit_2 is @dots{}
24679 @end cartouche
24680 @end group
24681 @end smallexample
24682
24683 @noindent
24684 would require that both the body and spec of @code{Unit_1} be elaborated
24685 before the spec of @code{Unit_2}. However, a rule like that would be far too
24686 restrictive. In particular, it would make it impossible to have routines
24687 in separate packages that were mutually recursive.
24688
24689 You might think that a clever enough compiler could look at the actual
24690 elaboration code and determine an appropriate correct order of elaboration,
24691 but in the general case, this is not possible. Consider the following
24692 example.
24693
24694 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24695 that references
24696 the variable @code{Sqrt_1}, which is declared in the elaboration code
24697 of the body of @code{Unit_1}:
24698
24699 @smallexample @c ada
24700 @cartouche
24701 Sqrt_1 : Float := Sqrt (0.1);
24702 @end cartouche
24703 @end smallexample
24704
24705 @noindent
24706 The elaboration code of the body of @code{Unit_1} also contains:
24707
24708 @smallexample @c ada
24709 @group
24710 @cartouche
24711 if expression_1 = 1 then
24712 Q := Unit_2.Func_2;
24713 end if;
24714 @end cartouche
24715 @end group
24716 @end smallexample
24717
24718 @noindent
24719 @code{Unit_2} is exactly parallel,
24720 it has a procedure @code{Func_2} that references
24721 the variable @code{Sqrt_2}, which is declared in the elaboration code of
24722 the body @code{Unit_2}:
24723
24724 @smallexample @c ada
24725 @cartouche
24726 Sqrt_2 : Float := Sqrt (0.1);
24727 @end cartouche
24728 @end smallexample
24729
24730 @noindent
24731 The elaboration code of the body of @code{Unit_2} also contains:
24732
24733 @smallexample @c ada
24734 @group
24735 @cartouche
24736 if expression_2 = 2 then
24737 Q := Unit_1.Func_1;
24738 end if;
24739 @end cartouche
24740 @end group
24741 @end smallexample
24742
24743 @noindent
24744 Now the question is, which of the following orders of elaboration is
24745 acceptable:
24746
24747 @smallexample
24748 @group
24749 Spec of Unit_1
24750 Spec of Unit_2
24751 Body of Unit_1
24752 Body of Unit_2
24753 @end group
24754 @end smallexample
24755
24756 @noindent
24757 or
24758
24759 @smallexample
24760 @group
24761 Spec of Unit_2
24762 Spec of Unit_1
24763 Body of Unit_2
24764 Body of Unit_1
24765 @end group
24766 @end smallexample
24767
24768 @noindent
24769 If you carefully analyze the flow here, you will see that you cannot tell
24770 at compile time the answer to this question.
24771 If @code{expression_1} is not equal to 1,
24772 and @code{expression_2} is not equal to 2,
24773 then either order is acceptable, because neither of the function calls is
24774 executed. If both tests evaluate to true, then neither order is acceptable
24775 and in fact there is no correct order.
24776
24777 If one of the two expressions is true, and the other is false, then one
24778 of the above orders is correct, and the other is incorrect. For example,
24779 if @code{expression_1} /= 1 and @code{expression_2} = 2,
24780 then the call to @code{Func_1}
24781 will occur, but not the call to @code{Func_2.}
24782 This means that it is essential
24783 to elaborate the body of @code{Unit_1} before
24784 the body of @code{Unit_2}, so the first
24785 order of elaboration is correct and the second is wrong.
24786
24787 By making @code{expression_1} and @code{expression_2}
24788 depend on input data, or perhaps
24789 the time of day, we can make it impossible for the compiler or binder
24790 to figure out which of these expressions will be true, and hence it
24791 is impossible to guarantee a safe order of elaboration at run time.
24792
24793 @node Checking the Elaboration Order
24794 @section Checking the Elaboration Order
24795
24796 @noindent
24797 In some languages that involve the same kind of elaboration problems,
24798 e.g.@: Java and C++, the programmer is expected to worry about these
24799 ordering problems himself, and it is common to
24800 write a program in which an incorrect elaboration order gives
24801 surprising results, because it references variables before they
24802 are initialized.
24803 Ada is designed to be a safe language, and a programmer-beware approach is
24804 clearly not sufficient. Consequently, the language provides three lines
24805 of defense:
24806
24807 @table @asis
24808 @item Standard rules
24809 Some standard rules restrict the possible choice of elaboration
24810 order. In particular, if you @code{with} a unit, then its spec is always
24811 elaborated before the unit doing the @code{with}. Similarly, a parent
24812 spec is always elaborated before the child spec, and finally
24813 a spec is always elaborated before its corresponding body.
24814
24815 @item Dynamic elaboration checks
24816 @cindex Elaboration checks
24817 @cindex Checks, elaboration
24818 Dynamic checks are made at run time, so that if some entity is accessed
24819 before it is elaborated (typically by means of a subprogram call)
24820 then the exception (@code{Program_Error}) is raised.
24821
24822 @item Elaboration control
24823 Facilities are provided for the programmer to specify the desired order
24824 of elaboration.
24825 @end table
24826
24827 Let's look at these facilities in more detail. First, the rules for
24828 dynamic checking. One possible rule would be simply to say that the
24829 exception is raised if you access a variable which has not yet been
24830 elaborated. The trouble with this approach is that it could require
24831 expensive checks on every variable reference. Instead Ada has two
24832 rules which are a little more restrictive, but easier to check, and
24833 easier to state:
24834
24835 @table @asis
24836 @item Restrictions on calls
24837 A subprogram can only be called at elaboration time if its body
24838 has been elaborated. The rules for elaboration given above guarantee
24839 that the spec of the subprogram has been elaborated before the
24840 call, but not the body. If this rule is violated, then the
24841 exception @code{Program_Error} is raised.
24842
24843 @item Restrictions on instantiations
24844 A generic unit can only be instantiated if the body of the generic
24845 unit has been elaborated. Again, the rules for elaboration given above
24846 guarantee that the spec of the generic unit has been elaborated
24847 before the instantiation, but not the body. If this rule is
24848 violated, then the exception @code{Program_Error} is raised.
24849 @end table
24850
24851 @noindent
24852 The idea is that if the body has been elaborated, then any variables
24853 it references must have been elaborated; by checking for the body being
24854 elaborated we guarantee that none of its references causes any
24855 trouble. As we noted above, this is a little too restrictive, because a
24856 subprogram that has no non-local references in its body may in fact be safe
24857 to call. However, it really would be unsafe to rely on this, because
24858 it would mean that the caller was aware of details of the implementation
24859 in the body. This goes against the basic tenets of Ada.
24860
24861 A plausible implementation can be described as follows.
24862 A Boolean variable is associated with each subprogram
24863 and each generic unit. This variable is initialized to False, and is set to
24864 True at the point body is elaborated. Every call or instantiation checks the
24865 variable, and raises @code{Program_Error} if the variable is False.
24866
24867 Note that one might think that it would be good enough to have one Boolean
24868 variable for each package, but that would not deal with cases of trying
24869 to call a body in the same package as the call
24870 that has not been elaborated yet.
24871 Of course a compiler may be able to do enough analysis to optimize away
24872 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24873 does such optimizations, but still the easiest conceptual model is to
24874 think of there being one variable per subprogram.
24875
24876 @node Controlling the Elaboration Order
24877 @section Controlling the Elaboration Order
24878
24879 @noindent
24880 In the previous section we discussed the rules in Ada which ensure
24881 that @code{Program_Error} is raised if an incorrect elaboration order is
24882 chosen. This prevents erroneous executions, but we need mechanisms to
24883 specify a correct execution and avoid the exception altogether.
24884 To achieve this, Ada provides a number of features for controlling
24885 the order of elaboration. We discuss these features in this section.
24886
24887 First, there are several ways of indicating to the compiler that a given
24888 unit has no elaboration problems:
24889
24890 @table @asis
24891 @item packages that do not require a body
24892 A library package that does not require a body does not permit
24893 a body (this rule was introduced in Ada 95).
24894 Thus if we have a such a package, as in:
24895
24896 @smallexample @c ada
24897 @group
24898 @cartouche
24899 package Definitions is
24900 generic
24901 type m is new integer;
24902 package Subp is
24903 type a is array (1 .. 10) of m;
24904 type b is array (1 .. 20) of m;
24905 end Subp;
24906 end Definitions;
24907 @end cartouche
24908 @end group
24909 @end smallexample
24910
24911 @noindent
24912 A package that @code{with}'s @code{Definitions} may safely instantiate
24913 @code{Definitions.Subp} because the compiler can determine that there
24914 definitely is no package body to worry about in this case
24915
24916 @item pragma Pure
24917 @cindex pragma Pure
24918 @findex Pure
24919 Places sufficient restrictions on a unit to guarantee that
24920 no call to any subprogram in the unit can result in an
24921 elaboration problem. This means that the compiler does not need
24922 to worry about the point of elaboration of such units, and in
24923 particular, does not need to check any calls to any subprograms
24924 in this unit.
24925
24926 @item pragma Preelaborate
24927 @findex Preelaborate
24928 @cindex pragma Preelaborate
24929 This pragma places slightly less stringent restrictions on a unit than
24930 does pragma Pure,
24931 but these restrictions are still sufficient to ensure that there
24932 are no elaboration problems with any calls to the unit.
24933
24934 @item pragma Elaborate_Body
24935 @findex Elaborate_Body
24936 @cindex pragma Elaborate_Body
24937 This pragma requires that the body of a unit be elaborated immediately
24938 after its spec. Suppose a unit @code{A} has such a pragma,
24939 and unit @code{B} does
24940 a @code{with} of unit @code{A}. Recall that the standard rules require
24941 the spec of unit @code{A}
24942 to be elaborated before the @code{with}'ing unit; given the pragma in
24943 @code{A}, we also know that the body of @code{A}
24944 will be elaborated before @code{B}, so
24945 that calls to @code{A} are safe and do not need a check.
24946 @end table
24947
24948 @noindent
24949 Note that,
24950 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24951 the use of
24952 @code{Elaborate_Body} does not guarantee that the program is
24953 free of elaboration problems, because it may not be possible
24954 to satisfy the requested elaboration order.
24955 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24956 If a programmer
24957 marks @code{Unit_1} as @code{Elaborate_Body},
24958 and not @code{Unit_2,} then the order of
24959 elaboration will be:
24960
24961 @smallexample
24962 @group
24963 Spec of Unit_2
24964 Spec of Unit_1
24965 Body of Unit_1
24966 Body of Unit_2
24967 @end group
24968 @end smallexample
24969
24970 @noindent
24971 Now that means that the call to @code{Func_1} in @code{Unit_2}
24972 need not be checked,
24973 it must be safe. But the call to @code{Func_2} in
24974 @code{Unit_1} may still fail if
24975 @code{Expression_1} is equal to 1,
24976 and the programmer must still take
24977 responsibility for this not being the case.
24978
24979 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24980 eliminated, except for calls entirely within a body, which are
24981 in any case fully under programmer control. However, using the pragma
24982 everywhere is not always possible.
24983 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24984 we marked both of them as having pragma @code{Elaborate_Body}, then
24985 clearly there would be no possible elaboration order.
24986
24987 The above pragmas allow a server to guarantee safe use by clients, and
24988 clearly this is the preferable approach. Consequently a good rule
24989 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24990 and if this is not possible,
24991 mark them as @code{Elaborate_Body} if possible.
24992 As we have seen, there are situations where neither of these
24993 three pragmas can be used.
24994 So we also provide methods for clients to control the
24995 order of elaboration of the servers on which they depend:
24996
24997 @table @asis
24998 @item pragma Elaborate (unit)
24999 @findex Elaborate
25000 @cindex pragma Elaborate
25001 This pragma is placed in the context clause, after a @code{with} clause,
25002 and it requires that the body of the named unit be elaborated before
25003 the unit in which the pragma occurs. The idea is to use this pragma
25004 if the current unit calls at elaboration time, directly or indirectly,
25005 some subprogram in the named unit.
25006
25007 @item pragma Elaborate_All (unit)
25008 @findex Elaborate_All
25009 @cindex pragma Elaborate_All
25010 This is a stronger version of the Elaborate pragma. Consider the
25011 following example:
25012
25013 @smallexample
25014 Unit A @code{with}'s unit B and calls B.Func in elab code
25015 Unit B @code{with}'s unit C, and B.Func calls C.Func
25016 @end smallexample
25017
25018 @noindent
25019 Now if we put a pragma @code{Elaborate (B)}
25020 in unit @code{A}, this ensures that the
25021 body of @code{B} is elaborated before the call, but not the
25022 body of @code{C}, so
25023 the call to @code{C.Func} could still cause @code{Program_Error} to
25024 be raised.
25025
25026 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25027 not only that the body of the named unit be elaborated before the
25028 unit doing the @code{with}, but also the bodies of all units that the
25029 named unit uses, following @code{with} links transitively. For example,
25030 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25031 then it requires
25032 not only that the body of @code{B} be elaborated before @code{A},
25033 but also the
25034 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25035 @end table
25036
25037 @noindent
25038 We are now in a position to give a usage rule in Ada for avoiding
25039 elaboration problems, at least if dynamic dispatching and access to
25040 subprogram values are not used. We will handle these cases separately
25041 later.
25042
25043 The rule is simple. If a unit has elaboration code that can directly or
25044 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25045 a generic package in a @code{with}'ed unit,
25046 then if the @code{with}'ed unit does not have
25047 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25048 a pragma @code{Elaborate_All}
25049 for the @code{with}'ed unit. By following this rule a client is
25050 assured that calls can be made without risk of an exception.
25051
25052 For generic subprogram instantiations, the rule can be relaxed to
25053 require only a pragma @code{Elaborate} since elaborating the body
25054 of a subprogram cannot cause any transitive elaboration (we are
25055 not calling the subprogram in this case, just elaborating its
25056 declaration).
25057
25058 If this rule is not followed, then a program may be in one of four
25059 states:
25060
25061 @table @asis
25062 @item No order exists
25063 No order of elaboration exists which follows the rules, taking into
25064 account any @code{Elaborate}, @code{Elaborate_All},
25065 or @code{Elaborate_Body} pragmas. In
25066 this case, an Ada compiler must diagnose the situation at bind
25067 time, and refuse to build an executable program.
25068
25069 @item One or more orders exist, all incorrect
25070 One or more acceptable elaboration orders exist, and all of them
25071 generate an elaboration order problem. In this case, the binder
25072 can build an executable program, but @code{Program_Error} will be raised
25073 when the program is run.
25074
25075 @item Several orders exist, some right, some incorrect
25076 One or more acceptable elaboration orders exists, and some of them
25077 work, and some do not. The programmer has not controlled
25078 the order of elaboration, so the binder may or may not pick one of
25079 the correct orders, and the program may or may not raise an
25080 exception when it is run. This is the worst case, because it means
25081 that the program may fail when moved to another compiler, or even
25082 another version of the same compiler.
25083
25084 @item One or more orders exists, all correct
25085 One ore more acceptable elaboration orders exist, and all of them
25086 work. In this case the program runs successfully. This state of
25087 affairs can be guaranteed by following the rule we gave above, but
25088 may be true even if the rule is not followed.
25089 @end table
25090
25091 @noindent
25092 Note that one additional advantage of following our rules on the use
25093 of @code{Elaborate} and @code{Elaborate_All}
25094 is that the program continues to stay in the ideal (all orders OK) state
25095 even if maintenance
25096 changes some bodies of some units. Conversely, if a program that does
25097 not follow this rule happens to be safe at some point, this state of affairs
25098 may deteriorate silently as a result of maintenance changes.
25099
25100 You may have noticed that the above discussion did not mention
25101 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25102 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25103 code in the body makes calls to some other unit, so it is still necessary
25104 to use @code{Elaborate_All} on such units.
25105
25106 @node Controlling Elaboration in GNAT - Internal Calls
25107 @section Controlling Elaboration in GNAT - Internal Calls
25108
25109 @noindent
25110 In the case of internal calls, i.e., calls within a single package, the
25111 programmer has full control over the order of elaboration, and it is up
25112 to the programmer to elaborate declarations in an appropriate order. For
25113 example writing:
25114
25115 @smallexample @c ada
25116 @group
25117 @cartouche
25118 function One return Float;
25119
25120 Q : Float := One;
25121
25122 function One return Float is
25123 begin
25124 return 1.0;
25125 end One;
25126 @end cartouche
25127 @end group
25128 @end smallexample
25129
25130 @noindent
25131 will obviously raise @code{Program_Error} at run time, because function
25132 One will be called before its body is elaborated. In this case GNAT will
25133 generate a warning that the call will raise @code{Program_Error}:
25134
25135 @smallexample
25136 @group
25137 @cartouche
25138 1. procedure y is
25139 2. function One return Float;
25140 3.
25141 4. Q : Float := One;
25142 |
25143 >>> warning: cannot call "One" before body is elaborated
25144 >>> warning: Program_Error will be raised at run time
25145
25146 5.
25147 6. function One return Float is
25148 7. begin
25149 8. return 1.0;
25150 9. end One;
25151 10.
25152 11. begin
25153 12. null;
25154 13. end;
25155 @end cartouche
25156 @end group
25157 @end smallexample
25158
25159 @noindent
25160 Note that in this particular case, it is likely that the call is safe, because
25161 the function @code{One} does not access any global variables.
25162 Nevertheless in Ada, we do not want the validity of the check to depend on
25163 the contents of the body (think about the separate compilation case), so this
25164 is still wrong, as we discussed in the previous sections.
25165
25166 The error is easily corrected by rearranging the declarations so that the
25167 body of @code{One} appears before the declaration containing the call
25168 (note that in Ada 95 and Ada 2005,
25169 declarations can appear in any order, so there is no restriction that
25170 would prevent this reordering, and if we write:
25171
25172 @smallexample @c ada
25173 @group
25174 @cartouche
25175 function One return Float;
25176
25177 function One return Float is
25178 begin
25179 return 1.0;
25180 end One;
25181
25182 Q : Float := One;
25183 @end cartouche
25184 @end group
25185 @end smallexample
25186
25187 @noindent
25188 then all is well, no warning is generated, and no
25189 @code{Program_Error} exception
25190 will be raised.
25191 Things are more complicated when a chain of subprograms is executed:
25192
25193 @smallexample @c ada
25194 @group
25195 @cartouche
25196 function A return Integer;
25197 function B return Integer;
25198 function C return Integer;
25199
25200 function B return Integer is begin return A; end;
25201 function C return Integer is begin return B; end;
25202
25203 X : Integer := C;
25204
25205 function A return Integer is begin return 1; end;
25206 @end cartouche
25207 @end group
25208 @end smallexample
25209
25210 @noindent
25211 Now the call to @code{C}
25212 at elaboration time in the declaration of @code{X} is correct, because
25213 the body of @code{C} is already elaborated,
25214 and the call to @code{B} within the body of
25215 @code{C} is correct, but the call
25216 to @code{A} within the body of @code{B} is incorrect, because the body
25217 of @code{A} has not been elaborated, so @code{Program_Error}
25218 will be raised on the call to @code{A}.
25219 In this case GNAT will generate a
25220 warning that @code{Program_Error} may be
25221 raised at the point of the call. Let's look at the warning:
25222
25223 @smallexample
25224 @group
25225 @cartouche
25226 1. procedure x is
25227 2. function A return Integer;
25228 3. function B return Integer;
25229 4. function C return Integer;
25230 5.
25231 6. function B return Integer is begin return A; end;
25232 |
25233 >>> warning: call to "A" before body is elaborated may
25234 raise Program_Error
25235 >>> warning: "B" called at line 7
25236 >>> warning: "C" called at line 9
25237
25238 7. function C return Integer is begin return B; end;
25239 8.
25240 9. X : Integer := C;
25241 10.
25242 11. function A return Integer is begin return 1; end;
25243 12.
25244 13. begin
25245 14. null;
25246 15. end;
25247 @end cartouche
25248 @end group
25249 @end smallexample
25250
25251 @noindent
25252 Note that the message here says ``may raise'', instead of the direct case,
25253 where the message says ``will be raised''. That's because whether
25254 @code{A} is
25255 actually called depends in general on run-time flow of control.
25256 For example, if the body of @code{B} said
25257
25258 @smallexample @c ada
25259 @group
25260 @cartouche
25261 function B return Integer is
25262 begin
25263 if some-condition-depending-on-input-data then
25264 return A;
25265 else
25266 return 1;
25267 end if;
25268 end B;
25269 @end cartouche
25270 @end group
25271 @end smallexample
25272
25273 @noindent
25274 then we could not know until run time whether the incorrect call to A would
25275 actually occur, so @code{Program_Error} might
25276 or might not be raised. It is possible for a compiler to
25277 do a better job of analyzing bodies, to
25278 determine whether or not @code{Program_Error}
25279 might be raised, but it certainly
25280 couldn't do a perfect job (that would require solving the halting problem
25281 and is provably impossible), and because this is a warning anyway, it does
25282 not seem worth the effort to do the analysis. Cases in which it
25283 would be relevant are rare.
25284
25285 In practice, warnings of either of the forms given
25286 above will usually correspond to
25287 real errors, and should be examined carefully and eliminated.
25288 In the rare case where a warning is bogus, it can be suppressed by any of
25289 the following methods:
25290
25291 @itemize @bullet
25292 @item
25293 Compile with the @option{-gnatws} switch set
25294
25295 @item
25296 Suppress @code{Elaboration_Check} for the called subprogram
25297
25298 @item
25299 Use pragma @code{Warnings_Off} to turn warnings off for the call
25300 @end itemize
25301
25302 @noindent
25303 For the internal elaboration check case,
25304 GNAT by default generates the
25305 necessary run-time checks to ensure
25306 that @code{Program_Error} is raised if any
25307 call fails an elaboration check. Of course this can only happen if a
25308 warning has been issued as described above. The use of pragma
25309 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25310 some of these checks, meaning that it may be possible (but is not
25311 guaranteed) for a program to be able to call a subprogram whose body
25312 is not yet elaborated, without raising a @code{Program_Error} exception.
25313
25314 @node Controlling Elaboration in GNAT - External Calls
25315 @section Controlling Elaboration in GNAT - External Calls
25316
25317 @noindent
25318 The previous section discussed the case in which the execution of a
25319 particular thread of elaboration code occurred entirely within a
25320 single unit. This is the easy case to handle, because a programmer
25321 has direct and total control over the order of elaboration, and
25322 furthermore, checks need only be generated in cases which are rare
25323 and which the compiler can easily detect.
25324 The situation is more complex when separate compilation is taken into account.
25325 Consider the following:
25326
25327 @smallexample @c ada
25328 @cartouche
25329 @group
25330 package Math is
25331 function Sqrt (Arg : Float) return Float;
25332 end Math;
25333
25334 package body Math is
25335 function Sqrt (Arg : Float) return Float is
25336 begin
25337 @dots{}
25338 end Sqrt;
25339 end Math;
25340 @end group
25341 @group
25342 with Math;
25343 package Stuff is
25344 X : Float := Math.Sqrt (0.5);
25345 end Stuff;
25346
25347 with Stuff;
25348 procedure Main is
25349 begin
25350 @dots{}
25351 end Main;
25352 @end group
25353 @end cartouche
25354 @end smallexample
25355
25356 @noindent
25357 where @code{Main} is the main program. When this program is executed, the
25358 elaboration code must first be executed, and one of the jobs of the
25359 binder is to determine the order in which the units of a program are
25360 to be elaborated. In this case we have four units: the spec and body
25361 of @code{Math},
25362 the spec of @code{Stuff} and the body of @code{Main}).
25363 In what order should the four separate sections of elaboration code
25364 be executed?
25365
25366 There are some restrictions in the order of elaboration that the binder
25367 can choose. In particular, if unit U has a @code{with}
25368 for a package @code{X}, then you
25369 are assured that the spec of @code{X}
25370 is elaborated before U , but you are
25371 not assured that the body of @code{X}
25372 is elaborated before U.
25373 This means that in the above case, the binder is allowed to choose the
25374 order:
25375
25376 @smallexample
25377 spec of Math
25378 spec of Stuff
25379 body of Math
25380 body of Main
25381 @end smallexample
25382
25383 @noindent
25384 but that's not good, because now the call to @code{Math.Sqrt}
25385 that happens during
25386 the elaboration of the @code{Stuff}
25387 spec happens before the body of @code{Math.Sqrt} is
25388 elaborated, and hence causes @code{Program_Error} exception to be raised.
25389 At first glance, one might say that the binder is misbehaving, because
25390 obviously you want to elaborate the body of something you @code{with}
25391 first, but
25392 that is not a general rule that can be followed in all cases. Consider
25393
25394 @smallexample @c ada
25395 @group
25396 @cartouche
25397 package X is @dots{}
25398
25399 package Y is @dots{}
25400
25401 with X;
25402 package body Y is @dots{}
25403
25404 with Y;
25405 package body X is @dots{}
25406 @end cartouche
25407 @end group
25408 @end smallexample
25409
25410 @noindent
25411 This is a common arrangement, and, apart from the order of elaboration
25412 problems that might arise in connection with elaboration code, this works fine.
25413 A rule that says that you must first elaborate the body of anything you
25414 @code{with} cannot work in this case:
25415 the body of @code{X} @code{with}'s @code{Y},
25416 which means you would have to
25417 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25418 which means
25419 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25420 loop that cannot be broken.
25421
25422 It is true that the binder can in many cases guess an order of elaboration
25423 that is unlikely to cause a @code{Program_Error}
25424 exception to be raised, and it tries to do so (in the
25425 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25426 by default
25427 elaborate the body of @code{Math} right after its spec, so all will be well).
25428
25429 However, a program that blindly relies on the binder to be helpful can
25430 get into trouble, as we discussed in the previous sections, so
25431 GNAT
25432 provides a number of facilities for assisting the programmer in
25433 developing programs that are robust with respect to elaboration order.
25434
25435 @node Default Behavior in GNAT - Ensuring Safety
25436 @section Default Behavior in GNAT - Ensuring Safety
25437
25438 @noindent
25439 The default behavior in GNAT ensures elaboration safety. In its
25440 default mode GNAT implements the
25441 rule we previously described as the right approach. Let's restate it:
25442
25443 @itemize
25444 @item
25445 @emph{If a unit has elaboration code that can directly or indirectly make a
25446 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25447 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25448 does not have pragma @code{Pure} or
25449 @code{Preelaborate}, then the client should have an
25450 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25451
25452 @emph{In the case of instantiating a generic subprogram, it is always
25453 sufficient to have only an @code{Elaborate} pragma for the
25454 @code{with}'ed unit.}
25455 @end itemize
25456
25457 @noindent
25458 By following this rule a client is assured that calls and instantiations
25459 can be made without risk of an exception.
25460
25461 In this mode GNAT traces all calls that are potentially made from
25462 elaboration code, and puts in any missing implicit @code{Elaborate}
25463 and @code{Elaborate_All} pragmas.
25464 The advantage of this approach is that no elaboration problems
25465 are possible if the binder can find an elaboration order that is
25466 consistent with these implicit @code{Elaborate} and
25467 @code{Elaborate_All} pragmas. The
25468 disadvantage of this approach is that no such order may exist.
25469
25470 If the binder does not generate any diagnostics, then it means that it has
25471 found an elaboration order that is guaranteed to be safe. However, the binder
25472 may still be relying on implicitly generated @code{Elaborate} and
25473 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25474 guaranteed.
25475
25476 If it is important to guarantee portability, then the compilations should
25477 use the
25478 @option{-gnatwl}
25479 (warn on elaboration problems) switch. This will cause warning messages
25480 to be generated indicating the missing @code{Elaborate} and
25481 @code{Elaborate_All} pragmas.
25482 Consider the following source program:
25483
25484 @smallexample @c ada
25485 @group
25486 @cartouche
25487 with k;
25488 package j is
25489 m : integer := k.r;
25490 end;
25491 @end cartouche
25492 @end group
25493 @end smallexample
25494
25495 @noindent
25496 where it is clear that there
25497 should be a pragma @code{Elaborate_All}
25498 for unit @code{k}. An implicit pragma will be generated, and it is
25499 likely that the binder will be able to honor it. However, if you want
25500 to port this program to some other Ada compiler than GNAT.
25501 it is safer to include the pragma explicitly in the source. If this
25502 unit is compiled with the
25503 @option{-gnatwl}
25504 switch, then the compiler outputs a warning:
25505
25506 @smallexample
25507 @group
25508 @cartouche
25509 1. with k;
25510 2. package j is
25511 3. m : integer := k.r;
25512 |
25513 >>> warning: call to "r" may raise Program_Error
25514 >>> warning: missing pragma Elaborate_All for "k"
25515
25516 4. end;
25517 @end cartouche
25518 @end group
25519 @end smallexample
25520
25521 @noindent
25522 and these warnings can be used as a guide for supplying manually
25523 the missing pragmas. It is usually a bad idea to use this warning
25524 option during development. That's because it will warn you when
25525 you need to put in a pragma, but cannot warn you when it is time
25526 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25527 unnecessary dependencies and even false circularities.
25528
25529 This default mode is more restrictive than the Ada Reference
25530 Manual, and it is possible to construct programs which will compile
25531 using the dynamic model described there, but will run into a
25532 circularity using the safer static model we have described.
25533
25534 Of course any Ada compiler must be able to operate in a mode
25535 consistent with the requirements of the Ada Reference Manual,
25536 and in particular must have the capability of implementing the
25537 standard dynamic model of elaboration with run-time checks.
25538
25539 In GNAT, this standard mode can be achieved either by the use of
25540 the @option{-gnatE} switch on the compiler (@command{gcc} or
25541 @command{gnatmake}) command, or by the use of the configuration pragma:
25542
25543 @smallexample @c ada
25544 pragma Elaboration_Checks (DYNAMIC);
25545 @end smallexample
25546
25547 @noindent
25548 Either approach will cause the unit affected to be compiled using the
25549 standard dynamic run-time elaboration checks described in the Ada
25550 Reference Manual. The static model is generally preferable, since it
25551 is clearly safer to rely on compile and link time checks rather than
25552 run-time checks. However, in the case of legacy code, it may be
25553 difficult to meet the requirements of the static model. This
25554 issue is further discussed in
25555 @ref{What to Do If the Default Elaboration Behavior Fails}.
25556
25557 Note that the static model provides a strict subset of the allowed
25558 behavior and programs of the Ada Reference Manual, so if you do
25559 adhere to the static model and no circularities exist,
25560 then you are assured that your program will
25561 work using the dynamic model, providing that you remove any
25562 pragma Elaborate statements from the source.
25563
25564 @node Treatment of Pragma Elaborate
25565 @section Treatment of Pragma Elaborate
25566 @cindex Pragma Elaborate
25567
25568 @noindent
25569 The use of @code{pragma Elaborate}
25570 should generally be avoided in Ada 95 and Ada 2005 programs,
25571 since there is no guarantee that transitive calls
25572 will be properly handled. Indeed at one point, this pragma was placed
25573 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25574
25575 Now that's a bit restrictive. In practice, the case in which
25576 @code{pragma Elaborate} is useful is when the caller knows that there
25577 are no transitive calls, or that the called unit contains all necessary
25578 transitive @code{pragma Elaborate} statements, and legacy code often
25579 contains such uses.
25580
25581 Strictly speaking the static mode in GNAT should ignore such pragmas,
25582 since there is no assurance at compile time that the necessary safety
25583 conditions are met. In practice, this would cause GNAT to be incompatible
25584 with correctly written Ada 83 code that had all necessary
25585 @code{pragma Elaborate} statements in place. Consequently, we made the
25586 decision that GNAT in its default mode will believe that if it encounters
25587 a @code{pragma Elaborate} then the programmer knows what they are doing,
25588 and it will trust that no elaboration errors can occur.
25589
25590 The result of this decision is two-fold. First to be safe using the
25591 static mode, you should remove all @code{pragma Elaborate} statements.
25592 Second, when fixing circularities in existing code, you can selectively
25593 use @code{pragma Elaborate} statements to convince the static mode of
25594 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25595 statement.
25596
25597 When using the static mode with @option{-gnatwl}, any use of
25598 @code{pragma Elaborate} will generate a warning about possible
25599 problems.
25600
25601 @node Elaboration Issues for Library Tasks
25602 @section Elaboration Issues for Library Tasks
25603 @cindex Library tasks, elaboration issues
25604 @cindex Elaboration of library tasks
25605
25606 @noindent
25607 In this section we examine special elaboration issues that arise for
25608 programs that declare library level tasks.
25609
25610 Generally the model of execution of an Ada program is that all units are
25611 elaborated, and then execution of the program starts. However, the
25612 declaration of library tasks definitely does not fit this model. The
25613 reason for this is that library tasks start as soon as they are declared
25614 (more precisely, as soon as the statement part of the enclosing package
25615 body is reached), that is to say before elaboration
25616 of the program is complete. This means that if such a task calls a
25617 subprogram, or an entry in another task, the callee may or may not be
25618 elaborated yet, and in the standard
25619 Reference Manual model of dynamic elaboration checks, you can even
25620 get timing dependent Program_Error exceptions, since there can be
25621 a race between the elaboration code and the task code.
25622
25623 The static model of elaboration in GNAT seeks to avoid all such
25624 dynamic behavior, by being conservative, and the conservative
25625 approach in this particular case is to assume that all the code
25626 in a task body is potentially executed at elaboration time if
25627 a task is declared at the library level.
25628
25629 This can definitely result in unexpected circularities. Consider
25630 the following example
25631
25632 @smallexample @c ada
25633 package Decls is
25634 task Lib_Task is
25635 entry Start;
25636 end Lib_Task;
25637
25638 type My_Int is new Integer;
25639
25640 function Ident (M : My_Int) return My_Int;
25641 end Decls;
25642
25643 with Utils;
25644 package body Decls is
25645 task body Lib_Task is
25646 begin
25647 accept Start;
25648 Utils.Put_Val (2);
25649 end Lib_Task;
25650
25651 function Ident (M : My_Int) return My_Int is
25652 begin
25653 return M;
25654 end Ident;
25655 end Decls;
25656
25657 with Decls;
25658 package Utils is
25659 procedure Put_Val (Arg : Decls.My_Int);
25660 end Utils;
25661
25662 with Text_IO;
25663 package body Utils is
25664 procedure Put_Val (Arg : Decls.My_Int) is
25665 begin
25666 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25667 end Put_Val;
25668 end Utils;
25669
25670 with Decls;
25671 procedure Main is
25672 begin
25673 Decls.Lib_Task.Start;
25674 end;
25675 @end smallexample
25676
25677 @noindent
25678 If the above example is compiled in the default static elaboration
25679 mode, then a circularity occurs. The circularity comes from the call
25680 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25681 this call occurs in elaboration code, we need an implicit pragma
25682 @code{Elaborate_All} for @code{Utils}. This means that not only must
25683 the spec and body of @code{Utils} be elaborated before the body
25684 of @code{Decls}, but also the spec and body of any unit that is
25685 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25686 the body of @code{Decls}. This is the transitive implication of
25687 pragma @code{Elaborate_All} and it makes sense, because in general
25688 the body of @code{Put_Val} might have a call to something in a
25689 @code{with'ed} unit.
25690
25691 In this case, the body of Utils (actually its spec) @code{with's}
25692 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25693 must be elaborated before itself, in case there is a call from the
25694 body of @code{Utils}.
25695
25696 Here is the exact chain of events we are worrying about:
25697
25698 @enumerate
25699 @item
25700 In the body of @code{Decls} a call is made from within the body of a library
25701 task to a subprogram in the package @code{Utils}. Since this call may
25702 occur at elaboration time (given that the task is activated at elaboration
25703 time), we have to assume the worst, i.e., that the
25704 call does happen at elaboration time.
25705
25706 @item
25707 This means that the body and spec of @code{Util} must be elaborated before
25708 the body of @code{Decls} so that this call does not cause an access before
25709 elaboration.
25710
25711 @item
25712 Within the body of @code{Util}, specifically within the body of
25713 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25714 by this package.
25715
25716 @item
25717 One such @code{with}'ed package is package @code{Decls}, so there
25718 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
25719 In fact there is such a call in this example, but we would have to
25720 assume that there was such a call even if it were not there, since
25721 we are not supposed to write the body of @code{Decls} knowing what
25722 is in the body of @code{Utils}; certainly in the case of the
25723 static elaboration model, the compiler does not know what is in
25724 other bodies and must assume the worst.
25725
25726 @item
25727 This means that the spec and body of @code{Decls} must also be
25728 elaborated before we elaborate the unit containing the call, but
25729 that unit is @code{Decls}! This means that the body of @code{Decls}
25730 must be elaborated before itself, and that's a circularity.
25731 @end enumerate
25732
25733 @noindent
25734 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
25735 the body of @code{Decls} you will get a true Ada Reference Manual
25736 circularity that makes the program illegal.
25737
25738 In practice, we have found that problems with the static model of
25739 elaboration in existing code often arise from library tasks, so
25740 we must address this particular situation.
25741
25742 Note that if we compile and run the program above, using the dynamic model of
25743 elaboration (that is to say use the @option{-gnatE} switch),
25744 then it compiles, binds,
25745 links, and runs, printing the expected result of 2. Therefore in some sense
25746 the circularity here is only apparent, and we need to capture
25747 the properties of this program that distinguish it from other library-level
25748 tasks that have real elaboration problems.
25749
25750 We have four possible answers to this question:
25751
25752 @itemize @bullet
25753
25754 @item
25755 Use the dynamic model of elaboration.
25756
25757 If we use the @option{-gnatE} switch, then as noted above, the program works.
25758 Why is this? If we examine the task body, it is apparent that the task cannot
25759 proceed past the
25760 @code{accept} statement until after elaboration has been completed, because
25761 the corresponding entry call comes from the main program, not earlier.
25762 This is why the dynamic model works here. But that's really giving
25763 up on a precise analysis, and we prefer to take this approach only if we cannot
25764 solve the
25765 problem in any other manner. So let us examine two ways to reorganize
25766 the program to avoid the potential elaboration problem.
25767
25768 @item
25769 Split library tasks into separate packages.
25770
25771 Write separate packages, so that library tasks are isolated from
25772 other declarations as much as possible. Let us look at a variation on
25773 the above program.
25774
25775 @smallexample @c ada
25776 package Decls1 is
25777 task Lib_Task is
25778 entry Start;
25779 end Lib_Task;
25780 end Decls1;
25781
25782 with Utils;
25783 package body Decls1 is
25784 task body Lib_Task is
25785 begin
25786 accept Start;
25787 Utils.Put_Val (2);
25788 end Lib_Task;
25789 end Decls1;
25790
25791 package Decls2 is
25792 type My_Int is new Integer;
25793 function Ident (M : My_Int) return My_Int;
25794 end Decls2;
25795
25796 with Utils;
25797 package body Decls2 is
25798 function Ident (M : My_Int) return My_Int is
25799 begin
25800 return M;
25801 end Ident;
25802 end Decls2;
25803
25804 with Decls2;
25805 package Utils is
25806 procedure Put_Val (Arg : Decls2.My_Int);
25807 end Utils;
25808
25809 with Text_IO;
25810 package body Utils is
25811 procedure Put_Val (Arg : Decls2.My_Int) is
25812 begin
25813 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25814 end Put_Val;
25815 end Utils;
25816
25817 with Decls1;
25818 procedure Main is
25819 begin
25820 Decls1.Lib_Task.Start;
25821 end;
25822 @end smallexample
25823
25824 @noindent
25825 All we have done is to split @code{Decls} into two packages, one
25826 containing the library task, and one containing everything else. Now
25827 there is no cycle, and the program compiles, binds, links and executes
25828 using the default static model of elaboration.
25829
25830 @item
25831 Declare separate task types.
25832
25833 A significant part of the problem arises because of the use of the
25834 single task declaration form. This means that the elaboration of
25835 the task type, and the elaboration of the task itself (i.e.@: the
25836 creation of the task) happen at the same time. A good rule
25837 of style in Ada is to always create explicit task types. By
25838 following the additional step of placing task objects in separate
25839 packages from the task type declaration, many elaboration problems
25840 are avoided. Here is another modified example of the example program:
25841
25842 @smallexample @c ada
25843 package Decls is
25844 task type Lib_Task_Type is
25845 entry Start;
25846 end Lib_Task_Type;
25847
25848 type My_Int is new Integer;
25849
25850 function Ident (M : My_Int) return My_Int;
25851 end Decls;
25852
25853 with Utils;
25854 package body Decls is
25855 task body Lib_Task_Type is
25856 begin
25857 accept Start;
25858 Utils.Put_Val (2);
25859 end Lib_Task_Type;
25860
25861 function Ident (M : My_Int) return My_Int is
25862 begin
25863 return M;
25864 end Ident;
25865 end Decls;
25866
25867 with Decls;
25868 package Utils is
25869 procedure Put_Val (Arg : Decls.My_Int);
25870 end Utils;
25871
25872 with Text_IO;
25873 package body Utils is
25874 procedure Put_Val (Arg : Decls.My_Int) is
25875 begin
25876 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25877 end Put_Val;
25878 end Utils;
25879
25880 with Decls;
25881 package Declst is
25882 Lib_Task : Decls.Lib_Task_Type;
25883 end Declst;
25884
25885 with Declst;
25886 procedure Main is
25887 begin
25888 Declst.Lib_Task.Start;
25889 end;
25890 @end smallexample
25891
25892 @noindent
25893 What we have done here is to replace the @code{task} declaration in
25894 package @code{Decls} with a @code{task type} declaration. Then we
25895 introduce a separate package @code{Declst} to contain the actual
25896 task object. This separates the elaboration issues for
25897 the @code{task type}
25898 declaration, which causes no trouble, from the elaboration issues
25899 of the task object, which is also unproblematic, since it is now independent
25900 of the elaboration of @code{Utils}.
25901 This separation of concerns also corresponds to
25902 a generally sound engineering principle of separating declarations
25903 from instances. This version of the program also compiles, binds, links,
25904 and executes, generating the expected output.
25905
25906 @item
25907 Use No_Entry_Calls_In_Elaboration_Code restriction.
25908 @cindex No_Entry_Calls_In_Elaboration_Code
25909
25910 The previous two approaches described how a program can be restructured
25911 to avoid the special problems caused by library task bodies. in practice,
25912 however, such restructuring may be difficult to apply to existing legacy code,
25913 so we must consider solutions that do not require massive rewriting.
25914
25915 Let us consider more carefully why our original sample program works
25916 under the dynamic model of elaboration. The reason is that the code
25917 in the task body blocks immediately on the @code{accept}
25918 statement. Now of course there is nothing to prohibit elaboration
25919 code from making entry calls (for example from another library level task),
25920 so we cannot tell in isolation that
25921 the task will not execute the accept statement during elaboration.
25922
25923 However, in practice it is very unusual to see elaboration code
25924 make any entry calls, and the pattern of tasks starting
25925 at elaboration time and then immediately blocking on @code{accept} or
25926 @code{select} statements is very common. What this means is that
25927 the compiler is being too pessimistic when it analyzes the
25928 whole package body as though it might be executed at elaboration
25929 time.
25930
25931 If we know that the elaboration code contains no entry calls, (a very safe
25932 assumption most of the time, that could almost be made the default
25933 behavior), then we can compile all units of the program under control
25934 of the following configuration pragma:
25935
25936 @smallexample
25937 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25938 @end smallexample
25939
25940 @noindent
25941 This pragma can be placed in the @file{gnat.adc} file in the usual
25942 manner. If we take our original unmodified program and compile it
25943 in the presence of a @file{gnat.adc} containing the above pragma,
25944 then once again, we can compile, bind, link, and execute, obtaining
25945 the expected result. In the presence of this pragma, the compiler does
25946 not trace calls in a task body, that appear after the first @code{accept}
25947 or @code{select} statement, and therefore does not report a potential
25948 circularity in the original program.
25949
25950 The compiler will check to the extent it can that the above
25951 restriction is not violated, but it is not always possible to do a
25952 complete check at compile time, so it is important to use this
25953 pragma only if the stated restriction is in fact met, that is to say
25954 no task receives an entry call before elaboration of all units is completed.
25955
25956 @end itemize
25957
25958 @node Mixing Elaboration Models
25959 @section Mixing Elaboration Models
25960 @noindent
25961 So far, we have assumed that the entire program is either compiled
25962 using the dynamic model or static model, ensuring consistency. It
25963 is possible to mix the two models, but rules have to be followed
25964 if this mixing is done to ensure that elaboration checks are not
25965 omitted.
25966
25967 The basic rule is that @emph{a unit compiled with the static model cannot
25968 be @code{with'ed} by a unit compiled with the dynamic model}. The
25969 reason for this is that in the static model, a unit assumes that
25970 its clients guarantee to use (the equivalent of) pragma
25971 @code{Elaborate_All} so that no elaboration checks are required
25972 in inner subprograms, and this assumption is violated if the
25973 client is compiled with dynamic checks.
25974
25975 The precise rule is as follows. A unit that is compiled with dynamic
25976 checks can only @code{with} a unit that meets at least one of the
25977 following criteria:
25978
25979 @itemize @bullet
25980
25981 @item
25982 The @code{with'ed} unit is itself compiled with dynamic elaboration
25983 checks (that is with the @option{-gnatE} switch.
25984
25985 @item
25986 The @code{with'ed} unit is an internal GNAT implementation unit from
25987 the System, Interfaces, Ada, or GNAT hierarchies.
25988
25989 @item
25990 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25991
25992 @item
25993 The @code{with'ing} unit (that is the client) has an explicit pragma
25994 @code{Elaborate_All} for the @code{with'ed} unit.
25995
25996 @end itemize
25997
25998 @noindent
25999 If this rule is violated, that is if a unit with dynamic elaboration
26000 checks @code{with's} a unit that does not meet one of the above four
26001 criteria, then the binder (@code{gnatbind}) will issue a warning
26002 similar to that in the following example:
26003
26004 @smallexample
26005 warning: "x.ads" has dynamic elaboration checks and with's
26006 warning: "y.ads" which has static elaboration checks
26007 @end smallexample
26008
26009 @noindent
26010 These warnings indicate that the rule has been violated, and that as a result
26011 elaboration checks may be missed in the resulting executable file.
26012 This warning may be suppressed using the @option{-ws} binder switch
26013 in the usual manner.
26014
26015 One useful application of this mixing rule is in the case of a subsystem
26016 which does not itself @code{with} units from the remainder of the
26017 application. In this case, the entire subsystem can be compiled with
26018 dynamic checks to resolve a circularity in the subsystem, while
26019 allowing the main application that uses this subsystem to be compiled
26020 using the more reliable default static model.
26021
26022 @node What to Do If the Default Elaboration Behavior Fails
26023 @section What to Do If the Default Elaboration Behavior Fails
26024
26025 @noindent
26026 If the binder cannot find an acceptable order, it outputs detailed
26027 diagnostics. For example:
26028 @smallexample
26029 @group
26030 @iftex
26031 @leftskip=0cm
26032 @end iftex
26033 error: elaboration circularity detected
26034 info: "proc (body)" must be elaborated before "pack (body)"
26035 info: reason: Elaborate_All probably needed in unit "pack (body)"
26036 info: recompile "pack (body)" with -gnatwl
26037 info: for full details
26038 info: "proc (body)"
26039 info: is needed by its spec:
26040 info: "proc (spec)"
26041 info: which is withed by:
26042 info: "pack (body)"
26043 info: "pack (body)" must be elaborated before "proc (body)"
26044 info: reason: pragma Elaborate in unit "proc (body)"
26045 @end group
26046
26047 @end smallexample
26048
26049 @noindent
26050 In this case we have a cycle that the binder cannot break. On the one
26051 hand, there is an explicit pragma Elaborate in @code{proc} for
26052 @code{pack}. This means that the body of @code{pack} must be elaborated
26053 before the body of @code{proc}. On the other hand, there is elaboration
26054 code in @code{pack} that calls a subprogram in @code{proc}. This means
26055 that for maximum safety, there should really be a pragma
26056 Elaborate_All in @code{pack} for @code{proc} which would require that
26057 the body of @code{proc} be elaborated before the body of
26058 @code{pack}. Clearly both requirements cannot be satisfied.
26059 Faced with a circularity of this kind, you have three different options.
26060
26061 @table @asis
26062 @item Fix the program
26063 The most desirable option from the point of view of long-term maintenance
26064 is to rearrange the program so that the elaboration problems are avoided.
26065 One useful technique is to place the elaboration code into separate
26066 child packages. Another is to move some of the initialization code to
26067 explicitly called subprograms, where the program controls the order
26068 of initialization explicitly. Although this is the most desirable option,
26069 it may be impractical and involve too much modification, especially in
26070 the case of complex legacy code.
26071
26072 @item Perform dynamic checks
26073 If the compilations are done using the
26074 @option{-gnatE}
26075 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26076 manner. Dynamic checks are generated for all calls that could possibly result
26077 in raising an exception. With this switch, the compiler does not generate
26078 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26079 exactly as specified in the @cite{Ada Reference Manual}.
26080 The binder will generate
26081 an executable program that may or may not raise @code{Program_Error}, and then
26082 it is the programmer's job to ensure that it does not raise an exception. Note
26083 that it is important to compile all units with the switch, it cannot be used
26084 selectively.
26085
26086 @item Suppress checks
26087 The drawback of dynamic checks is that they generate a
26088 significant overhead at run time, both in space and time. If you
26089 are absolutely sure that your program cannot raise any elaboration
26090 exceptions, and you still want to use the dynamic elaboration model,
26091 then you can use the configuration pragma
26092 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26093 example this pragma could be placed in the @file{gnat.adc} file.
26094
26095 @item Suppress checks selectively
26096 When you know that certain calls or instantiations in elaboration code cannot
26097 possibly lead to an elaboration error, and the binder nevertheless complains
26098 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26099 elaboration circularities, it is possible to remove those warnings locally and
26100 obtain a program that will bind. Clearly this can be unsafe, and it is the
26101 responsibility of the programmer to make sure that the resulting program has no
26102 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26103 used with different granularity to suppress warnings and break elaboration
26104 circularities:
26105
26106 @itemize @bullet
26107 @item
26108 Place the pragma that names the called subprogram in the declarative part
26109 that contains the call.
26110
26111 @item
26112 Place the pragma in the declarative part, without naming an entity. This
26113 disables warnings on all calls in the corresponding declarative region.
26114
26115 @item
26116 Place the pragma in the package spec that declares the called subprogram,
26117 and name the subprogram. This disables warnings on all elaboration calls to
26118 that subprogram.
26119
26120 @item
26121 Place the pragma in the package spec that declares the called subprogram,
26122 without naming any entity. This disables warnings on all elaboration calls to
26123 all subprograms declared in this spec.
26124
26125 @item Use Pragma Elaborate
26126 As previously described in section @xref{Treatment of Pragma Elaborate},
26127 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26128 that no elaboration checks are required on calls to the designated unit.
26129 There may be cases in which the caller knows that no transitive calls
26130 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26131 case where @code{pragma Elaborate_All} would cause a circularity.
26132 @end itemize
26133
26134 @noindent
26135 These five cases are listed in order of decreasing safety, and therefore
26136 require increasing programmer care in their application. Consider the
26137 following program:
26138
26139 @smallexample @c adanocomment
26140 package Pack1 is
26141 function F1 return Integer;
26142 X1 : Integer;
26143 end Pack1;
26144
26145 package Pack2 is
26146 function F2 return Integer;
26147 function Pure (x : integer) return integer;
26148 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26149 -- pragma Suppress (Elaboration_Check); -- (4)
26150 end Pack2;
26151
26152 with Pack2;
26153 package body Pack1 is
26154 function F1 return Integer is
26155 begin
26156 return 100;
26157 end F1;
26158 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26159 begin
26160 declare
26161 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26162 -- pragma Suppress(Elaboration_Check); -- (2)
26163 begin
26164 X1 := Pack2.F2 + 1; -- Elab. call (2)
26165 end;
26166 end Pack1;
26167
26168 with Pack1;
26169 package body Pack2 is
26170 function F2 return Integer is
26171 begin
26172 return Pack1.F1;
26173 end F2;
26174 function Pure (x : integer) return integer is
26175 begin
26176 return x ** 3 - 3 * x;
26177 end;
26178 end Pack2;
26179
26180 with Pack1, Ada.Text_IO;
26181 procedure Proc3 is
26182 begin
26183 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26184 end Proc3;
26185 @end smallexample
26186 In the absence of any pragmas, an attempt to bind this program produces
26187 the following diagnostics:
26188 @smallexample
26189 @group
26190 @iftex
26191 @leftskip=.5cm
26192 @end iftex
26193 error: elaboration circularity detected
26194 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26195 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26196 info: recompile "pack1 (body)" with -gnatwl for full details
26197 info: "pack1 (body)"
26198 info: must be elaborated along with its spec:
26199 info: "pack1 (spec)"
26200 info: which is withed by:
26201 info: "pack2 (body)"
26202 info: which must be elaborated along with its spec:
26203 info: "pack2 (spec)"
26204 info: which is withed by:
26205 info: "pack1 (body)"
26206 @end group
26207 @end smallexample
26208 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26209 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26210 F2 is safe, even though F2 calls F1, because the call appears after the
26211 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26212 remove the warning on the call. It is also possible to use pragma (2)
26213 because there are no other potentially unsafe calls in the block.
26214
26215 @noindent
26216 The call to @code{Pure} is safe because this function does not depend on the
26217 state of @code{Pack2}. Therefore any call to this function is safe, and it
26218 is correct to place pragma (3) in the corresponding package spec.
26219
26220 @noindent
26221 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26222 warnings on all calls to functions declared therein. Note that this is not
26223 necessarily safe, and requires more detailed examination of the subprogram
26224 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26225 be already elaborated.
26226 @end table
26227
26228 @noindent
26229 It is hard to generalize on which of these four approaches should be
26230 taken. Obviously if it is possible to fix the program so that the default
26231 treatment works, this is preferable, but this may not always be practical.
26232 It is certainly simple enough to use
26233 @option{-gnatE}
26234 but the danger in this case is that, even if the GNAT binder
26235 finds a correct elaboration order, it may not always do so,
26236 and certainly a binder from another Ada compiler might not. A
26237 combination of testing and analysis (for which the warnings generated
26238 with the
26239 @option{-gnatwl}
26240 switch can be useful) must be used to ensure that the program is free
26241 of errors. One switch that is useful in this testing is the
26242 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26243 switch for
26244 @code{gnatbind}.
26245 Normally the binder tries to find an order that has the best chance
26246 of avoiding elaboration problems. However, if this switch is used, the binder
26247 plays a devil's advocate role, and tries to choose the order that
26248 has the best chance of failing. If your program works even with this
26249 switch, then it has a better chance of being error free, but this is still
26250 not a guarantee.
26251
26252 For an example of this approach in action, consider the C-tests (executable
26253 tests) from the ACVC suite. If these are compiled and run with the default
26254 treatment, then all but one of them succeed without generating any error
26255 diagnostics from the binder. However, there is one test that fails, and
26256 this is not surprising, because the whole point of this test is to ensure
26257 that the compiler can handle cases where it is impossible to determine
26258 a correct order statically, and it checks that an exception is indeed
26259 raised at run time.
26260
26261 This one test must be compiled and run using the
26262 @option{-gnatE}
26263 switch, and then it passes. Alternatively, the entire suite can
26264 be run using this switch. It is never wrong to run with the dynamic
26265 elaboration switch if your code is correct, and we assume that the
26266 C-tests are indeed correct (it is less efficient, but efficiency is
26267 not a factor in running the ACVC tests.)
26268
26269 @node Elaboration for Dispatching Calls
26270 @section Elaboration for Dispatching Calls
26271 @cindex Dispatching calls
26272
26273 @noindent
26274 In rare cases, the static elaboration model fails to prevent
26275 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26276 fall back to run-time checks; premature calls to any primitive
26277 operation of a tagged type before the body of the operation has been
26278 elaborated will raise @code{Program_Error}.
26279
26280 Access-to-subprogram types, however, are handled conservatively, and
26281 do not require run-time checks. This was not true in earlier versions
26282 of the compiler; you can use the @option{-gnatd.U} debug switch to
26283 revert to the old behavior if the new conservative behavior causes
26284 elaboration cycles.
26285
26286 @node Summary of Procedures for Elaboration Control
26287 @section Summary of Procedures for Elaboration Control
26288 @cindex Elaboration control
26289
26290 @noindent
26291 First, compile your program with the default options, using none of
26292 the special elaboration control switches. If the binder successfully
26293 binds your program, then you can be confident that, apart from issues
26294 raised by the use of access-to-subprogram types and dynamic dispatching,
26295 the program is free of elaboration errors. If it is important that the
26296 program be portable, then use the
26297 @option{-gnatwl}
26298 switch to generate warnings about missing @code{Elaborate} or
26299 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26300
26301 If the program fails to bind using the default static elaboration
26302 handling, then you can fix the program to eliminate the binder
26303 message, or recompile the entire program with the
26304 @option{-gnatE} switch to generate dynamic elaboration checks,
26305 and, if you are sure there really are no elaboration problems,
26306 use a global pragma @code{Suppress (Elaboration_Check)}.
26307
26308 @node Other Elaboration Order Considerations
26309 @section Other Elaboration Order Considerations
26310 @noindent
26311 This section has been entirely concerned with the issue of finding a valid
26312 elaboration order, as defined by the Ada Reference Manual. In a case
26313 where several elaboration orders are valid, the task is to find one
26314 of the possible valid elaboration orders (and the static model in GNAT
26315 will ensure that this is achieved).
26316
26317 The purpose of the elaboration rules in the Ada Reference Manual is to
26318 make sure that no entity is accessed before it has been elaborated. For
26319 a subprogram, this means that the spec and body must have been elaborated
26320 before the subprogram is called. For an object, this means that the object
26321 must have been elaborated before its value is read or written. A violation
26322 of either of these two requirements is an access before elaboration order,
26323 and this section has been all about avoiding such errors.
26324
26325 In the case where more than one order of elaboration is possible, in the
26326 sense that access before elaboration errors are avoided, then any one of
26327 the orders is ``correct'' in the sense that it meets the requirements of
26328 the Ada Reference Manual, and no such error occurs.
26329
26330 However, it may be the case for a given program, that there are
26331 constraints on the order of elaboration that come not from consideration
26332 of avoiding elaboration errors, but rather from extra-lingual logic
26333 requirements. Consider this example:
26334
26335 @smallexample @c ada
26336 with Init_Constants;
26337 package Constants is
26338 X : Integer := 0;
26339 Y : Integer := 0;
26340 end Constants;
26341
26342 package Init_Constants is
26343 procedure P; -- require a body
26344 end Init_Constants;
26345
26346 with Constants;
26347 package body Init_Constants is
26348 procedure P is begin null; end;
26349 begin
26350 Constants.X := 3;
26351 Constants.Y := 4;
26352 end Init_Constants;
26353
26354 with Constants;
26355 package Calc is
26356 Z : Integer := Constants.X + Constants.Y;
26357 end Calc;
26358
26359 with Calc;
26360 with Text_IO; use Text_IO;
26361 procedure Main is
26362 begin
26363 Put_Line (Calc.Z'Img);
26364 end Main;
26365 @end smallexample
26366
26367 @noindent
26368 In this example, there is more than one valid order of elaboration. For
26369 example both the following are correct orders:
26370
26371 @smallexample
26372 Init_Constants spec
26373 Constants spec
26374 Calc spec
26375 Init_Constants body
26376 Main body
26377
26378 and
26379
26380 Init_Constants spec
26381 Init_Constants body
26382 Constants spec
26383 Calc spec
26384 Main body
26385 @end smallexample
26386
26387 @noindent
26388 There is no language rule to prefer one or the other, both are correct
26389 from an order of elaboration point of view. But the programmatic effects
26390 of the two orders are very different. In the first, the elaboration routine
26391 of @code{Calc} initializes @code{Z} to zero, and then the main program
26392 runs with this value of zero. But in the second order, the elaboration
26393 routine of @code{Calc} runs after the body of Init_Constants has set
26394 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26395 runs.
26396
26397 One could perhaps by applying pretty clever non-artificial intelligence
26398 to the situation guess that it is more likely that the second order of
26399 elaboration is the one desired, but there is no formal linguistic reason
26400 to prefer one over the other. In fact in this particular case, GNAT will
26401 prefer the second order, because of the rule that bodies are elaborated
26402 as soon as possible, but it's just luck that this is what was wanted
26403 (if indeed the second order was preferred).
26404
26405 If the program cares about the order of elaboration routines in a case like
26406 this, it is important to specify the order required. In this particular
26407 case, that could have been achieved by adding to the spec of Calc:
26408
26409 @smallexample @c ada
26410 pragma Elaborate_All (Constants);
26411 @end smallexample
26412
26413 @noindent
26414 which requires that the body (if any) and spec of @code{Constants},
26415 as well as the body and spec of any unit @code{with}'ed by
26416 @code{Constants} be elaborated before @code{Calc} is elaborated.
26417
26418 Clearly no automatic method can always guess which alternative you require,
26419 and if you are working with legacy code that had constraints of this kind
26420 which were not properly specified by adding @code{Elaborate} or
26421 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26422 compilers can choose different orders.
26423
26424 However, GNAT does attempt to diagnose the common situation where there
26425 are uninitialized variables in the visible part of a package spec, and the
26426 corresponding package body has an elaboration block that directly or
26427 indirectly initialized one or more of these variables. This is the situation
26428 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26429 a warning that suggests this addition if it detects this situation.
26430
26431 The @code{gnatbind}
26432 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26433 out problems. This switch causes bodies to be elaborated as late as possible
26434 instead of as early as possible. In the example above, it would have forced
26435 the choice of the first elaboration order. If you get different results
26436 when using this switch, and particularly if one set of results is right,
26437 and one is wrong as far as you are concerned, it shows that you have some
26438 missing @code{Elaborate} pragmas. For the example above, we have the
26439 following output:
26440
26441 @smallexample
26442 gnatmake -f -q main
26443 main
26444 7
26445 gnatmake -f -q main -bargs -p
26446 main
26447 0
26448 @end smallexample
26449
26450 @noindent
26451 It is of course quite unlikely that both these results are correct, so
26452 it is up to you in a case like this to investigate the source of the
26453 difference, by looking at the two elaboration orders that are chosen,
26454 and figuring out which is correct, and then adding the necessary
26455 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26456
26457
26458 @c **********************************
26459 @node Overflow Check Handling in GNAT
26460 @appendix Overflow Check Handling in GNAT
26461 @cindex Overflow checks
26462 @cindex Checks (overflow)
26463 @c **********************************
26464
26465 @menu
26466 * Background::
26467 * Overflow Checking Modes in GNAT::
26468 * Specifying the Desired Mode::
26469 * Default Settings::
26470 * Implementation Notes::
26471 @end menu
26472
26473
26474 @node Background
26475 @section Background
26476
26477 @noindent
26478 Overflow checks are checks that the compiler may make to ensure
26479 that intermediate results are not out of range. For example:
26480
26481 @smallexample @c ada
26482 A : Integer;
26483 ...
26484 A := A + 1;
26485 @end smallexample
26486
26487 @noindent
26488 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26489 overflow since the result is out of range of the type @code{Integer}.
26490 In this case @code{Constraint_Error} will be raised if checks are
26491 enabled.
26492
26493 A trickier situation arises in examples like the following:
26494
26495 @smallexample @c ada
26496 A, C : Integer;
26497 ...
26498 A := (A + 1) + C;
26499 @end smallexample
26500
26501 @noindent
26502 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26503 Now the final result of the expression on the right hand side is
26504 @code{Integer'Last} which is in range, but the question arises whether the
26505 intermediate addition of @code{(A + 1)} raises an overflow error.
26506
26507 The (perhaps surprising) answer is that the Ada language
26508 definition does not answer this question. Instead it leaves
26509 it up to the implementation to do one of two things if overflow
26510 checks are enabled.
26511
26512 @itemize @bullet
26513 @item
26514 raise an exception (@code{Constraint_Error}), or
26515
26516 @item
26517 yield the correct mathematical result which is then used in
26518 subsequent operations.
26519 @end itemize
26520
26521 @noindent
26522 If the compiler chooses the first approach, then the assignment of this
26523 example will indeed raise @code{Constraint_Error} if overflow checking is
26524 enabled, or result in erroneous execution if overflow checks are suppressed.
26525
26526 But if the compiler
26527 chooses the second approach, then it can perform both additions yielding
26528 the correct mathematical result, which is in range, so no exception
26529 will be raised, and the right result is obtained, regardless of whether
26530 overflow checks are suppressed.
26531
26532 Note that in the first example an
26533 exception will be raised in either case, since if the compiler
26534 gives the correct mathematical result for the addition, it will
26535 be out of range of the target type of the assignment, and thus
26536 fails the range check.
26537
26538 This lack of specified behavior in the handling of overflow for
26539 intermediate results is a source of non-portability, and can thus
26540 be problematic when programs are ported. Most typically this arises
26541 in a situation where the original compiler did not raise an exception,
26542 and then the application is moved to a compiler where the check is
26543 performed on the intermediate result and an unexpected exception is
26544 raised.
26545
26546 Furthermore, when using Ada 2012's preconditions and other
26547 assertion forms, another issue arises. Consider:
26548
26549 @smallexample @c ada
26550 procedure P (A, B : Integer) with
26551 Pre => A + B <= Integer'Last;
26552 @end smallexample
26553
26554 @noindent
26555 One often wants to regard arithmetic in a context like this from
26556 a mathematical point of view. So for example, if the two actual parameters
26557 for a call to @code{P} are both @code{Integer'Last}, then
26558 the precondition should be regarded as False. If we are executing
26559 in a mode with run-time checks enabled for preconditions, then we would
26560 like this precondition to fail, rather than raising an exception
26561 because of the intermediate overflow.
26562
26563 However, the language definition leaves the specification of
26564 whether the above condition fails (raising @code{Assert_Error}) or
26565 causes an intermediate overflow (raising @code{Constraint_Error})
26566 up to the implementation.
26567
26568 The situation is worse in a case such as the following:
26569
26570 @smallexample @c ada
26571 procedure Q (A, B, C : Integer) with
26572 Pre => A + B + C <= Integer'Last;
26573 @end smallexample
26574
26575 @noindent
26576 Consider the call
26577
26578 @smallexample @c ada
26579 Q (A => Integer'Last, B => 1, C => -1);
26580 @end smallexample
26581
26582 @noindent
26583 From a mathematical point of view the precondition
26584 is True, but at run time we may (but are not guaranteed to) get an
26585 exception raised because of the intermediate overflow (and we really
26586 would prefer this precondition to be considered True at run time).
26587
26588 @node Overflow Checking Modes in GNAT
26589 @section Overflow Checking Modes in GNAT
26590
26591 @noindent
26592 To deal with the portability issue, and with the problem of
26593 mathematical versus run-time intepretation of the expressions in
26594 assertions, GNAT provides comprehensive control over the handling
26595 of intermediate overflow. GNAT can operate in three modes, and
26596 furthemore, permits separate selection of operating modes for
26597 the expressions within assertions (here the term ``assertions''
26598 is used in the technical sense, which includes preconditions and so forth)
26599 and for expressions appearing outside assertions.
26600
26601 The three modes are:
26602
26603 @itemize @bullet
26604 @item @i{Use base type for intermediate operations} (@code{STRICT})
26605
26606 In this mode, all intermediate results for predefined arithmetic
26607 operators are computed using the base type, and the result must
26608 be in range of the base type. If this is not the
26609 case then either an exception is raised (if overflow checks are
26610 enabled) or the execution is erroneous (if overflow checks are suppressed).
26611 This is the normal default mode.
26612
26613 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26614
26615 In this mode, the compiler attempts to avoid intermediate overflows by
26616 using a larger integer type, typically @code{Long_Long_Integer},
26617 as the type in which arithmetic is
26618 performed for predefined arithmetic operators. This may be slightly more
26619 expensive at
26620 run time (compared to suppressing intermediate overflow checks), though
26621 the cost is negligible on modern 64-bit machines. For the examples given
26622 earlier, no intermediate overflows would have resulted in exceptions,
26623 since the intermediate results are all in the range of
26624 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26625 of GNAT). In addition, if checks are enabled, this reduces the number of
26626 checks that must be made, so this choice may actually result in an
26627 improvement in space and time behavior.
26628
26629 However, there are cases where @code{Long_Long_Integer} is not large
26630 enough, consider the following example:
26631
26632 @smallexample @c ada
26633 procedure R (A, B, C, D : Integer) with
26634 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26635 @end smallexample
26636
26637 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26638 Now the intermediate results are
26639 out of the range of @code{Long_Long_Integer} even though the final result
26640 is in range and the precondition is True (from a mathematical point
26641 of view). In such a case, operating in this mode, an overflow occurs
26642 for the intermediate computation (which is why this mode
26643 says @i{most} intermediate overflows are avoided). In this case,
26644 an exception is raised if overflow checks are enabled, and the
26645 execution is erroneous if overflow checks are suppressed.
26646
26647 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
26648
26649 In this mode, the compiler avoids all intermediate overflows
26650 by using arbitrary precision arithmetic as required. In this
26651 mode, the above example with @code{A**2 * B**2} would
26652 not cause intermediate overflow, because the intermediate result
26653 would be evaluated using sufficient precision, and the result
26654 of evaluating the precondition would be True.
26655
26656 This mode has the advantage of avoiding any intermediate
26657 overflows, but at the expense of significant run-time overhead,
26658 including the use of a library (included automatically in this
26659 mode) for multiple-precision arithmetic.
26660
26661 This mode provides cleaner semantics for assertions, since now
26662 the run-time behavior emulates true arithmetic behavior for the
26663 predefined arithmetic operators, meaning that there is never a
26664 conflict between the mathematical view of the assertion, and its
26665 run-time behavior.
26666
26667 Note that in this mode, the behavior is unaffected by whether or
26668 not overflow checks are suppressed, since overflow does not occur.
26669 It is possible for gigantic intermediate expressions to raise
26670 @code{Storage_Error} as a result of attempting to compute the
26671 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26672 but overflow is impossible.
26673
26674
26675 @end itemize
26676
26677 @noindent
26678 Note that these modes apply only to the evaluation of predefined
26679 arithmetic, membership, and comparison operators for signed integer
26680 aritmetic.
26681
26682 For fixed-point arithmetic, checks can be suppressed. But if checks
26683 are enabled
26684 then fixed-point values are always checked for overflow against the
26685 base type for intermediate expressions (that is such checks always
26686 operate in the equivalent of @code{STRICT} mode).
26687
26688 For floating-point, on nearly all architectures, @code{Machine_Overflows}
26689 is False, and IEEE infinities are generated, so overflow exceptions
26690 are never raised. If you want to avoid infinities, and check that
26691 final results of expressions are in range, then you can declare a
26692 constrained floating-point type, and range checks will be carried
26693 out in the normal manner (with infinite values always failing all
26694 range checks).
26695
26696
26697 @c -------------------------
26698 @node Specifying the Desired Mode
26699 @section Specifying the Desired Mode
26700
26701 @noindent
26702 The desired mode of for handling intermediate overflow can be specified using
26703 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26704 The pragma has the form
26705 @cindex pragma @code{Overflow_Mode}
26706
26707 @smallexample @c ada
26708 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26709 @end smallexample
26710
26711 @noindent
26712 where @code{MODE} is one of
26713
26714 @itemize @bullet
26715 @item @code{STRICT}: intermediate overflows checked (using base type)
26716 @item @code{MINIMIZED}: minimize intermediate overflows
26717 @item @code{ELIMINATED}: eliminate intermediate overflows
26718 @end itemize
26719
26720 @noindent
26721 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
26722 @code{minimized} all have the same effect.
26723
26724 If only the @code{General} parameter is present, then the given @code{MODE}
26725 applies
26726 to expressions both within and outside assertions. If both arguments
26727 are present, then @code{General} applies to expressions outside assertions,
26728 and @code{Assertions} applies to expressions within assertions. For example:
26729
26730 @smallexample @c ada
26731 pragma Overflow_Mode
26732 (General => Minimized, Assertions => Eliminated);
26733 @end smallexample
26734
26735 @noindent
26736 specifies that general expressions outside assertions be evaluated
26737 in ``minimize intermediate overflows'' mode, and expressions within
26738 assertions be evaluated in ``eliminate intermediate overflows'' mode.
26739 This is often a reasonable choice, avoiding excessive overhead
26740 outside assertions, but assuring a high degree of portability
26741 when importing code from another compiler, while incurring
26742 the extra overhead for assertion expressions to ensure that
26743 the behavior at run time matches the expected mathematical
26744 behavior.
26745
26746 The @code{Overflow_Mode} pragma has the same scoping and placement
26747 rules as pragma @code{Suppress}, so it can occur either as a
26748 configuration pragma, specifying a default for the whole
26749 program, or in a declarative scope, where it applies to the
26750 remaining declarations and statements in that scope.
26751
26752 Note that pragma @code{Overflow_Mode} does not affect whether
26753 overflow checks are enabled or suppressed. It only controls the
26754 method used to compute intermediate values. To control whether
26755 overflow checking is enabled or suppressed, use pragma @code{Suppress}
26756 or @code{Unsuppress} in the usual manner
26757
26758 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
26759 can be used to control the checking mode default (which can be subsequently
26760 overridden using pragmas).
26761 @cindex @option{-gnato?} (gcc)
26762 @cindex @option{-gnato??} (gcc)
26763
26764 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
26765
26766 @itemize @bullet
26767 @item @code{1}:
26768 use base type for intermediate operations (@code{STRICT})
26769 @item @code{2}:
26770 minimize intermediate overflows (@code{MINIMIZED})
26771 @item @code{3}:
26772 eliminate intermediate overflows (@code{ELIMINATED})
26773 @end itemize
26774
26775 @noindent
26776 As with the pragma, if only one digit appears then it applies to all
26777 cases; if two digits are given, then the first applies outside
26778 assertions, and the second within assertions. Thus the equivalent
26779 of the example pragma above would be
26780 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
26781
26782 If no digits follow the @option{-gnato}, then it is equivalent to
26783 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
26784 causing all intermediate operations to be computed using the base
26785 type (@code{STRICT} mode).
26786
26787 In addition to setting the mode used for computation of intermediate
26788 results, the @code{-gnato} switch also enables overflow checking (which
26789 is suppressed by default). It thus combines the effect of using
26790 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
26791
26792
26793 @c -------------------------
26794 @node Default Settings
26795 @section Default Settings
26796
26797 The default mode for overflow checks is
26798
26799 @smallexample
26800 General => Strict
26801 @end smallexample
26802
26803 @noindent
26804 which causes all computations both inside and outside assertions to use
26805 the base type. In addition overflow checks are suppressed.
26806
26807 This retains compatibility with previous versions of
26808 GNAT which suppressed overflow checks by default and always
26809 used the base type for computation of intermediate results.
26810
26811 The switch @option{-gnato} (with no digits following) is equivalent to
26812 @cindex @option{-gnato} (gcc)
26813
26814 @smallexample
26815 General => Strict
26816 @end smallexample
26817
26818 @noindent
26819 which causes overflow checking of all intermediate overflows
26820 both inside and outside assertions against the base type.
26821 This provides compatibility
26822 with this switch as implemented in previous versions of GNAT.
26823
26824 The pragma @code{Suppress (Overflow_Check)} disables overflow
26825 checking, but it has no effect on the method used for computing
26826 intermediate results.
26827
26828 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26829 checking, but it has no effect on the method used for computing
26830 intermediate results.
26831
26832 @c -------------------------
26833 @node Implementation Notes
26834 @section Implementation Notes
26835
26836 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26837 reasonably efficient, and can be generally used. It also helps
26838 to ensure compatibility with code imported from some other
26839 compiler to GNAT.
26840
26841 Setting all intermediate overflows checking (@code{CHECKED} mode)
26842 makes sense if you want to
26843 make sure that your code is compatible with any other possible
26844 Ada implementation. This may be useful in ensuring portability
26845 for code that is to be exported to some other compiler than GNAT.
26846
26847
26848 The Ada standard allows the reassociation of expressions at
26849 the same precedence level if no parentheses are present. For
26850 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26851 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26852 introducing or eliminating an overflow exception. The GNAT
26853 compiler never takes advantage of this freedom, and the
26854 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26855 If you need the other order, you can write the parentheses
26856 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26857
26858 The use of @code{ELIMINATED} mode will cause the compiler to
26859 automatically include an appropriate arbitrary precision
26860 integer arithmetic package. The compiler will make calls
26861 to this package, though only in cases where it cannot be
26862 sure that @code{Long_Long_Integer} is sufficient to guard against
26863 intermediate overflows. This package does not use dynamic
26864 alllocation, but it does use the secondary stack, so an
26865 appropriate secondary stack package must be present (this
26866 is always true for standard full Ada, but may require
26867 specific steps for restricted run times such as ZFP).
26868
26869 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26870 precision arithmetic, avoiding overflow, the final result
26871 must be in an appropriate range. This is true even if the
26872 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26873 still has the same bounds as its associated constrained
26874 type at run-time.
26875
26876 Currently, the @code{ELIMINATED} mode is only available on target
26877 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26878 platforms).
26879
26880 @c *******************************
26881 @node Conditional Compilation
26882 @appendix Conditional Compilation
26883 @c *******************************
26884 @cindex Conditional compilation
26885
26886 @noindent
26887 It is often necessary to arrange for a single source program
26888 to serve multiple purposes, where it is compiled in different
26889 ways to achieve these different goals. Some examples of the
26890 need for this feature are
26891
26892 @itemize @bullet
26893 @item Adapting a program to a different hardware environment
26894 @item Adapting a program to a different target architecture
26895 @item Turning debugging features on and off
26896 @item Arranging for a program to compile with different compilers
26897 @end itemize
26898
26899 @noindent
26900 In C, or C++, the typical approach would be to use the preprocessor
26901 that is defined as part of the language. The Ada language does not
26902 contain such a feature. This is not an oversight, but rather a very
26903 deliberate design decision, based on the experience that overuse of
26904 the preprocessing features in C and C++ can result in programs that
26905 are extremely difficult to maintain. For example, if we have ten
26906 switches that can be on or off, this means that there are a thousand
26907 separate programs, any one of which might not even be syntactically
26908 correct, and even if syntactically correct, the resulting program
26909 might not work correctly. Testing all combinations can quickly become
26910 impossible.
26911
26912 Nevertheless, the need to tailor programs certainly exists, and in
26913 this Appendix we will discuss how this can
26914 be achieved using Ada in general, and GNAT in particular.
26915
26916 @menu
26917 * Use of Boolean Constants::
26918 * Debugging - A Special Case::
26919 * Conditionalizing Declarations::
26920 * Use of Alternative Implementations::
26921 * Preprocessing::
26922 @end menu
26923
26924 @node Use of Boolean Constants
26925 @section Use of Boolean Constants
26926
26927 @noindent
26928 In the case where the difference is simply which code
26929 sequence is executed, the cleanest solution is to use Boolean
26930 constants to control which code is executed.
26931
26932 @smallexample @c ada
26933 @group
26934 FP_Initialize_Required : constant Boolean := True;
26935 @dots{}
26936 if FP_Initialize_Required then
26937 @dots{}
26938 end if;
26939 @end group
26940 @end smallexample
26941
26942 @noindent
26943 Not only will the code inside the @code{if} statement not be executed if
26944 the constant Boolean is @code{False}, but it will also be completely
26945 deleted from the program.
26946 However, the code is only deleted after the @code{if} statement
26947 has been checked for syntactic and semantic correctness.
26948 (In contrast, with preprocessors the code is deleted before the
26949 compiler ever gets to see it, so it is not checked until the switch
26950 is turned on.)
26951 @cindex Preprocessors (contrasted with conditional compilation)
26952
26953 Typically the Boolean constants will be in a separate package,
26954 something like:
26955
26956 @smallexample @c ada
26957 @group
26958 package Config is
26959 FP_Initialize_Required : constant Boolean := True;
26960 Reset_Available : constant Boolean := False;
26961 @dots{}
26962 end Config;
26963 @end group
26964 @end smallexample
26965
26966 @noindent
26967 The @code{Config} package exists in multiple forms for the various targets,
26968 with an appropriate script selecting the version of @code{Config} needed.
26969 Then any other unit requiring conditional compilation can do a @code{with}
26970 of @code{Config} to make the constants visible.
26971
26972
26973 @node Debugging - A Special Case
26974 @section Debugging - A Special Case
26975
26976 @noindent
26977 A common use of conditional code is to execute statements (for example
26978 dynamic checks, or output of intermediate results) under control of a
26979 debug switch, so that the debugging behavior can be turned on and off.
26980 This can be done using a Boolean constant to control whether the code
26981 is active:
26982
26983 @smallexample @c ada
26984 @group
26985 if Debugging then
26986 Put_Line ("got to the first stage!");
26987 end if;
26988 @end group
26989 @end smallexample
26990
26991 @noindent
26992 or
26993
26994 @smallexample @c ada
26995 @group
26996 if Debugging and then Temperature > 999.0 then
26997 raise Temperature_Crazy;
26998 end if;
26999 @end group
27000 @end smallexample
27001
27002 @noindent
27003 Since this is a common case, there are special features to deal with
27004 this in a convenient manner. For the case of tests, Ada 2005 has added
27005 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27006 @cindex pragma @code{Assert}
27007 on the @code{Assert} pragma that has always been available in GNAT, so this
27008 feature may be used with GNAT even if you are not using Ada 2005 features.
27009 The use of pragma @code{Assert} is described in
27010 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27011 example, the last test could be written:
27012
27013 @smallexample @c ada
27014 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27015 @end smallexample
27016
27017 @noindent
27018 or simply
27019
27020 @smallexample @c ada
27021 pragma Assert (Temperature <= 999.0);
27022 @end smallexample
27023
27024 @noindent
27025 In both cases, if assertions are active and the temperature is excessive,
27026 the exception @code{Assert_Failure} will be raised, with the given string in
27027 the first case or a string indicating the location of the pragma in the second
27028 case used as the exception message.
27029
27030 You can turn assertions on and off by using the @code{Assertion_Policy}
27031 pragma.
27032 @cindex pragma @code{Assertion_Policy}
27033 This is an Ada 2005 pragma which is implemented in all modes by
27034 GNAT, but only in the latest versions of GNAT which include Ada 2005
27035 capability. Alternatively, you can use the @option{-gnata} switch
27036 @cindex @option{-gnata} switch
27037 to enable assertions from the command line (this is recognized by all versions
27038 of GNAT).
27039
27040 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27041 @code{Debug} can be used:
27042 @cindex pragma @code{Debug}
27043
27044 @smallexample @c ada
27045 pragma Debug (Put_Line ("got to the first stage!"));
27046 @end smallexample
27047
27048 @noindent
27049 If debug pragmas are enabled, the argument, which must be of the form of
27050 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27051 Only one call can be present, but of course a special debugging procedure
27052 containing any code you like can be included in the program and then
27053 called in a pragma @code{Debug} argument as needed.
27054
27055 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27056 construct is that pragma @code{Debug} can appear in declarative contexts,
27057 such as at the very beginning of a procedure, before local declarations have
27058 been elaborated.
27059
27060 Debug pragmas are enabled using either the @option{-gnata} switch that also
27061 controls assertions, or with a separate Debug_Policy pragma.
27062 @cindex pragma @code{Debug_Policy}
27063 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27064 in Ada 95 and Ada 83 programs as well), and is analogous to
27065 pragma @code{Assertion_Policy} to control assertions.
27066
27067 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27068 and thus they can appear in @file{gnat.adc} if you are not using a
27069 project file, or in the file designated to contain configuration pragmas
27070 in a project file.
27071 They then apply to all subsequent compilations. In practice the use of
27072 the @option{-gnata} switch is often the most convenient method of controlling
27073 the status of these pragmas.
27074
27075 Note that a pragma is not a statement, so in contexts where a statement
27076 sequence is required, you can't just write a pragma on its own. You have
27077 to add a @code{null} statement.
27078
27079 @smallexample @c ada
27080 @group
27081 if @dots{} then
27082 @dots{} -- some statements
27083 else
27084 pragma Assert (Num_Cases < 10);
27085 null;
27086 end if;
27087 @end group
27088 @end smallexample
27089
27090
27091 @node Conditionalizing Declarations
27092 @section Conditionalizing Declarations
27093
27094 @noindent
27095 In some cases, it may be necessary to conditionalize declarations to meet
27096 different requirements. For example we might want a bit string whose length
27097 is set to meet some hardware message requirement.
27098
27099 In some cases, it may be possible to do this using declare blocks controlled
27100 by conditional constants:
27101
27102 @smallexample @c ada
27103 @group
27104 if Small_Machine then
27105 declare
27106 X : Bit_String (1 .. 10);
27107 begin
27108 @dots{}
27109 end;
27110 else
27111 declare
27112 X : Large_Bit_String (1 .. 1000);
27113 begin
27114 @dots{}
27115 end;
27116 end if;
27117 @end group
27118 @end smallexample
27119
27120 @noindent
27121 Note that in this approach, both declarations are analyzed by the
27122 compiler so this can only be used where both declarations are legal,
27123 even though one of them will not be used.
27124
27125 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27126 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27127 that are parameterized by these constants. For example
27128
27129 @smallexample @c ada
27130 @group
27131 for Rec use
27132 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27133 end record;
27134 @end group
27135 @end smallexample
27136
27137 @noindent
27138 If @code{Bits_Per_Word} is set to 32, this generates either
27139
27140 @smallexample @c ada
27141 @group
27142 for Rec use
27143 Field1 at 0 range 0 .. 32;
27144 end record;
27145 @end group
27146 @end smallexample
27147
27148 @noindent
27149 for the big endian case, or
27150
27151 @smallexample @c ada
27152 @group
27153 for Rec use record
27154 Field1 at 0 range 10 .. 32;
27155 end record;
27156 @end group
27157 @end smallexample
27158
27159 @noindent
27160 for the little endian case. Since a powerful subset of Ada expression
27161 notation is usable for creating static constants, clever use of this
27162 feature can often solve quite difficult problems in conditionalizing
27163 compilation (note incidentally that in Ada 95, the little endian
27164 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27165 need to define this one yourself).
27166
27167
27168 @node Use of Alternative Implementations
27169 @section Use of Alternative Implementations
27170
27171 @noindent
27172 In some cases, none of the approaches described above are adequate. This
27173 can occur for example if the set of declarations required is radically
27174 different for two different configurations.
27175
27176 In this situation, the official Ada way of dealing with conditionalizing
27177 such code is to write separate units for the different cases. As long as
27178 this does not result in excessive duplication of code, this can be done
27179 without creating maintenance problems. The approach is to share common
27180 code as far as possible, and then isolate the code and declarations
27181 that are different. Subunits are often a convenient method for breaking
27182 out a piece of a unit that is to be conditionalized, with separate files
27183 for different versions of the subunit for different targets, where the
27184 build script selects the right one to give to the compiler.
27185 @cindex Subunits (and conditional compilation)
27186
27187 As an example, consider a situation where a new feature in Ada 2005
27188 allows something to be done in a really nice way. But your code must be able
27189 to compile with an Ada 95 compiler. Conceptually you want to say:
27190
27191 @smallexample @c ada
27192 @group
27193 if Ada_2005 then
27194 @dots{} neat Ada 2005 code
27195 else
27196 @dots{} not quite as neat Ada 95 code
27197 end if;
27198 @end group
27199 @end smallexample
27200
27201 @noindent
27202 where @code{Ada_2005} is a Boolean constant.
27203
27204 But this won't work when @code{Ada_2005} is set to @code{False},
27205 since the @code{then} clause will be illegal for an Ada 95 compiler.
27206 (Recall that although such unreachable code would eventually be deleted
27207 by the compiler, it still needs to be legal. If it uses features
27208 introduced in Ada 2005, it will be illegal in Ada 95.)
27209
27210 So instead we write
27211
27212 @smallexample @c ada
27213 procedure Insert is separate;
27214 @end smallexample
27215
27216 @noindent
27217 Then we have two files for the subunit @code{Insert}, with the two sets of
27218 code.
27219 If the package containing this is called @code{File_Queries}, then we might
27220 have two files
27221
27222 @itemize @bullet
27223 @item @file{file_queries-insert-2005.adb}
27224 @item @file{file_queries-insert-95.adb}
27225 @end itemize
27226
27227 @noindent
27228 and the build script renames the appropriate file to
27229
27230 @smallexample
27231 file_queries-insert.adb
27232 @end smallexample
27233
27234 @noindent
27235 and then carries out the compilation.
27236
27237 This can also be done with project files' naming schemes. For example:
27238
27239 @smallexample @c project
27240 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27241 @end smallexample
27242
27243 @noindent
27244 Note also that with project files it is desirable to use a different extension
27245 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27246 conflict may arise through another commonly used feature: to declare as part
27247 of the project a set of directories containing all the sources obeying the
27248 default naming scheme.
27249
27250 The use of alternative units is certainly feasible in all situations,
27251 and for example the Ada part of the GNAT run-time is conditionalized
27252 based on the target architecture using this approach. As a specific example,
27253 consider the implementation of the AST feature in VMS. There is one
27254 spec:
27255
27256 @smallexample
27257 s-asthan.ads
27258 @end smallexample
27259
27260 @noindent
27261 which is the same for all architectures, and three bodies:
27262
27263 @table @file
27264 @item s-asthan.adb
27265 used for all non-VMS operating systems
27266 @item s-asthan-vms-alpha.adb
27267 used for VMS on the Alpha
27268 @item s-asthan-vms-ia64.adb
27269 used for VMS on the ia64
27270 @end table
27271
27272 @noindent
27273 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27274 this operating system feature is not available, and the two remaining
27275 versions interface with the corresponding versions of VMS to provide
27276 VMS-compatible AST handling. The GNAT build script knows the architecture
27277 and operating system, and automatically selects the right version,
27278 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27279
27280 Another style for arranging alternative implementations is through Ada's
27281 access-to-subprogram facility.
27282 In case some functionality is to be conditionally included,
27283 you can declare an access-to-procedure variable @code{Ref} that is initialized
27284 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27285 when appropriate.
27286 In some library package, set @code{Ref} to @code{Proc'Access} for some
27287 procedure @code{Proc} that performs the relevant processing.
27288 The initialization only occurs if the library package is included in the
27289 program.
27290 The same idea can also be implemented using tagged types and dispatching
27291 calls.
27292
27293
27294 @node Preprocessing
27295 @section Preprocessing
27296 @cindex Preprocessing
27297
27298 @noindent
27299 Although it is quite possible to conditionalize code without the use of
27300 C-style preprocessing, as described earlier in this section, it is
27301 nevertheless convenient in some cases to use the C approach. Moreover,
27302 older Ada compilers have often provided some preprocessing capability,
27303 so legacy code may depend on this approach, even though it is not
27304 standard.
27305
27306 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27307 extent on the various preprocessors that have been used
27308 with legacy code on other compilers, to enable easier transition).
27309
27310 The preprocessor may be used in two separate modes. It can be used quite
27311 separately from the compiler, to generate a separate output source file
27312 that is then fed to the compiler as a separate step. This is the
27313 @code{gnatprep} utility, whose use is fully described in
27314 @ref{Preprocessing Using gnatprep}.
27315 @cindex @code{gnatprep}
27316
27317 The preprocessing language allows such constructs as
27318
27319 @smallexample
27320 @group
27321 #if DEBUG or PRIORITY > 4 then
27322 bunch of declarations
27323 #else
27324 completely different bunch of declarations
27325 #end if;
27326 @end group
27327 @end smallexample
27328
27329 @noindent
27330 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27331 defined either on the command line or in a separate file.
27332
27333 The other way of running the preprocessor is even closer to the C style and
27334 often more convenient. In this approach the preprocessing is integrated into
27335 the compilation process. The compiler is fed the preprocessor input which
27336 includes @code{#if} lines etc, and then the compiler carries out the
27337 preprocessing internally and processes the resulting output.
27338 For more details on this approach, see @ref{Integrated Preprocessing}.
27339
27340
27341 @c *******************************
27342 @node Inline Assembler
27343 @appendix Inline Assembler
27344 @c *******************************
27345
27346 @noindent
27347 If you need to write low-level software that interacts directly
27348 with the hardware, Ada provides two ways to incorporate assembly
27349 language code into your program. First, you can import and invoke
27350 external routines written in assembly language, an Ada feature fully
27351 supported by GNAT@. However, for small sections of code it may be simpler
27352 or more efficient to include assembly language statements directly
27353 in your Ada source program, using the facilities of the implementation-defined
27354 package @code{System.Machine_Code}, which incorporates the gcc
27355 Inline Assembler. The Inline Assembler approach offers a number of advantages,
27356 including the following:
27357
27358 @itemize @bullet
27359 @item No need to use non-Ada tools
27360 @item Consistent interface over different targets
27361 @item Automatic usage of the proper calling conventions
27362 @item Access to Ada constants and variables
27363 @item Definition of intrinsic routines
27364 @item Possibility of inlining a subprogram comprising assembler code
27365 @item Code optimizer can take Inline Assembler code into account
27366 @end itemize
27367
27368 This chapter presents a series of examples to show you how to use
27369 the Inline Assembler. Although it focuses on the Intel x86,
27370 the general approach applies also to other processors.
27371 It is assumed that you are familiar with Ada
27372 and with assembly language programming.
27373
27374 @menu
27375 * Basic Assembler Syntax::
27376 * A Simple Example of Inline Assembler::
27377 * Output Variables in Inline Assembler::
27378 * Input Variables in Inline Assembler::
27379 * Inlining Inline Assembler Code::
27380 * Other Asm Functionality::
27381 @end menu
27382
27383 @c ---------------------------------------------------------------------------
27384 @node Basic Assembler Syntax
27385 @section Basic Assembler Syntax
27386
27387 @noindent
27388 The assembler used by GNAT and gcc is based not on the Intel assembly
27389 language, but rather on a language that descends from the AT&T Unix
27390 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27391 The following table summarizes the main features of @emph{as} syntax
27392 and points out the differences from the Intel conventions.
27393 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27394 pre-processor) documentation for further information.
27395
27396 @table @asis
27397 @item Register names
27398 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27399 @*
27400 Intel: No extra punctuation; for example @code{eax}
27401
27402 @item Immediate operand
27403 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27404 @*
27405 Intel: No extra punctuation; for example @code{4}
27406
27407 @item Address
27408 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27409 @*
27410 Intel: No extra punctuation; for example @code{loc}
27411
27412 @item Memory contents
27413 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27414 @*
27415 Intel: Square brackets; for example @code{[loc]}
27416
27417 @item Register contents
27418 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27419 @*
27420 Intel: Square brackets; for example @code{[eax]}
27421
27422 @item Hexadecimal numbers
27423 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27424 @*
27425 Intel: Trailing ``h''; for example @code{A0h}
27426
27427 @item Operand size
27428 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27429 a 16-bit word
27430 @*
27431 Intel: Implicit, deduced by assembler; for example @code{mov}
27432
27433 @item Instruction repetition
27434 gcc / @emph{as}: Split into two lines; for example
27435 @*
27436 @code{rep}
27437 @*
27438 @code{stosl}
27439 @*
27440 Intel: Keep on one line; for example @code{rep stosl}
27441
27442 @item Order of operands
27443 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27444 @*
27445 Intel: Destination first; for example @code{mov eax, 4}
27446 @end table
27447
27448 @c ---------------------------------------------------------------------------
27449 @node A Simple Example of Inline Assembler
27450 @section A Simple Example of Inline Assembler
27451
27452 @noindent
27453 The following example will generate a single assembly language statement,
27454 @code{nop}, which does nothing. Despite its lack of run-time effect,
27455 the example will be useful in illustrating the basics of
27456 the Inline Assembler facility.
27457
27458 @smallexample @c ada
27459 @group
27460 with System.Machine_Code; use System.Machine_Code;
27461 procedure Nothing is
27462 begin
27463 Asm ("nop");
27464 end Nothing;
27465 @end group
27466 @end smallexample
27467
27468 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27469 here it takes one parameter, a @emph{template string} that must be a static
27470 expression and that will form the generated instruction.
27471 @code{Asm} may be regarded as a compile-time procedure that parses
27472 the template string and additional parameters (none here),
27473 from which it generates a sequence of assembly language instructions.
27474
27475 The examples in this chapter will illustrate several of the forms
27476 for invoking @code{Asm}; a complete specification of the syntax
27477 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27478 Manual}.
27479
27480 Under the standard GNAT conventions, the @code{Nothing} procedure
27481 should be in a file named @file{nothing.adb}.
27482 You can build the executable in the usual way:
27483 @smallexample
27484 gnatmake nothing
27485 @end smallexample
27486 However, the interesting aspect of this example is not its run-time behavior
27487 but rather the generated assembly code.
27488 To see this output, invoke the compiler as follows:
27489 @smallexample
27490 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27491 @end smallexample
27492 where the options are:
27493
27494 @table @code
27495 @item -c
27496 compile only (no bind or link)
27497 @item -S
27498 generate assembler listing
27499 @item -fomit-frame-pointer
27500 do not set up separate stack frames
27501 @item -gnatp
27502 do not add runtime checks
27503 @end table
27504
27505 This gives a human-readable assembler version of the code. The resulting
27506 file will have the same name as the Ada source file, but with a @code{.s}
27507 extension. In our example, the file @file{nothing.s} has the following
27508 contents:
27509
27510 @smallexample
27511 @group
27512 .file "nothing.adb"
27513 gcc2_compiled.:
27514 ___gnu_compiled_ada:
27515 .text
27516 .align 4
27517 .globl __ada_nothing
27518 __ada_nothing:
27519 #APP
27520 nop
27521 #NO_APP
27522 jmp L1
27523 .align 2,0x90
27524 L1:
27525 ret
27526 @end group
27527 @end smallexample
27528
27529 The assembly code you included is clearly indicated by
27530 the compiler, between the @code{#APP} and @code{#NO_APP}
27531 delimiters. The character before the 'APP' and 'NOAPP'
27532 can differ on different targets. For example, GNU/Linux uses '#APP' while
27533 on NT you will see '/APP'.
27534
27535 If you make a mistake in your assembler code (such as using the
27536 wrong size modifier, or using a wrong operand for the instruction) GNAT
27537 will report this error in a temporary file, which will be deleted when
27538 the compilation is finished. Generating an assembler file will help
27539 in such cases, since you can assemble this file separately using the
27540 @emph{as} assembler that comes with gcc.
27541
27542 Assembling the file using the command
27543
27544 @smallexample
27545 as @file{nothing.s}
27546 @end smallexample
27547 @noindent
27548 will give you error messages whose lines correspond to the assembler
27549 input file, so you can easily find and correct any mistakes you made.
27550 If there are no errors, @emph{as} will generate an object file
27551 @file{nothing.out}.
27552
27553 @c ---------------------------------------------------------------------------
27554 @node Output Variables in Inline Assembler
27555 @section Output Variables in Inline Assembler
27556
27557 @noindent
27558 The examples in this section, showing how to access the processor flags,
27559 illustrate how to specify the destination operands for assembly language
27560 statements.
27561
27562 @smallexample @c ada
27563 @group
27564 with Interfaces; use Interfaces;
27565 with Ada.Text_IO; use Ada.Text_IO;
27566 with System.Machine_Code; use System.Machine_Code;
27567 procedure Get_Flags is
27568 Flags : Unsigned_32;
27569 use ASCII;
27570 begin
27571 Asm ("pushfl" & LF & HT & -- push flags on stack
27572 "popl %%eax" & LF & HT & -- load eax with flags
27573 "movl %%eax, %0", -- store flags in variable
27574 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27575 Put_Line ("Flags register:" & Flags'Img);
27576 end Get_Flags;
27577 @end group
27578 @end smallexample
27579
27580 In order to have a nicely aligned assembly listing, we have separated
27581 multiple assembler statements in the Asm template string with linefeed
27582 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27583 The resulting section of the assembly output file is:
27584
27585 @smallexample
27586 @group
27587 #APP
27588 pushfl
27589 popl %eax
27590 movl %eax, -40(%ebp)
27591 #NO_APP
27592 @end group
27593 @end smallexample
27594
27595 It would have been legal to write the Asm invocation as:
27596
27597 @smallexample
27598 Asm ("pushfl popl %%eax movl %%eax, %0")
27599 @end smallexample
27600
27601 but in the generated assembler file, this would come out as:
27602
27603 @smallexample
27604 #APP
27605 pushfl popl %eax movl %eax, -40(%ebp)
27606 #NO_APP
27607 @end smallexample
27608
27609 which is not so convenient for the human reader.
27610
27611 We use Ada comments
27612 at the end of each line to explain what the assembler instructions
27613 actually do. This is a useful convention.
27614
27615 When writing Inline Assembler instructions, you need to precede each register
27616 and variable name with a percent sign. Since the assembler already requires
27617 a percent sign at the beginning of a register name, you need two consecutive
27618 percent signs for such names in the Asm template string, thus @code{%%eax}.
27619 In the generated assembly code, one of the percent signs will be stripped off.
27620
27621 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27622 variables: operands you later define using @code{Input} or @code{Output}
27623 parameters to @code{Asm}.
27624 An output variable is illustrated in
27625 the third statement in the Asm template string:
27626 @smallexample
27627 movl %%eax, %0
27628 @end smallexample
27629 The intent is to store the contents of the eax register in a variable that can
27630 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
27631 necessarily work, since the compiler might optimize by using a register
27632 to hold Flags, and the expansion of the @code{movl} instruction would not be
27633 aware of this optimization. The solution is not to store the result directly
27634 but rather to advise the compiler to choose the correct operand form;
27635 that is the purpose of the @code{%0} output variable.
27636
27637 Information about the output variable is supplied in the @code{Outputs}
27638 parameter to @code{Asm}:
27639 @smallexample
27640 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27641 @end smallexample
27642
27643 The output is defined by the @code{Asm_Output} attribute of the target type;
27644 the general format is
27645 @smallexample
27646 Type'Asm_Output (constraint_string, variable_name)
27647 @end smallexample
27648
27649 The constraint string directs the compiler how
27650 to store/access the associated variable. In the example
27651 @smallexample
27652 Unsigned_32'Asm_Output ("=m", Flags);
27653 @end smallexample
27654 the @code{"m"} (memory) constraint tells the compiler that the variable
27655 @code{Flags} should be stored in a memory variable, thus preventing
27656 the optimizer from keeping it in a register. In contrast,
27657 @smallexample
27658 Unsigned_32'Asm_Output ("=r", Flags);
27659 @end smallexample
27660 uses the @code{"r"} (register) constraint, telling the compiler to
27661 store the variable in a register.
27662
27663 If the constraint is preceded by the equal character (@strong{=}), it tells
27664 the compiler that the variable will be used to store data into it.
27665
27666 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27667 allowing the optimizer to choose whatever it deems best.
27668
27669 There are a fairly large number of constraints, but the ones that are
27670 most useful (for the Intel x86 processor) are the following:
27671
27672 @table @code
27673 @item =
27674 output constraint
27675 @item g
27676 global (i.e.@: can be stored anywhere)
27677 @item m
27678 in memory
27679 @item I
27680 a constant
27681 @item a
27682 use eax
27683 @item b
27684 use ebx
27685 @item c
27686 use ecx
27687 @item d
27688 use edx
27689 @item S
27690 use esi
27691 @item D
27692 use edi
27693 @item r
27694 use one of eax, ebx, ecx or edx
27695 @item q
27696 use one of eax, ebx, ecx, edx, esi or edi
27697 @end table
27698
27699 The full set of constraints is described in the gcc and @emph{as}
27700 documentation; note that it is possible to combine certain constraints
27701 in one constraint string.
27702
27703 You specify the association of an output variable with an assembler operand
27704 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27705 integer. Thus in
27706 @smallexample @c ada
27707 @group
27708 Asm ("pushfl" & LF & HT & -- push flags on stack
27709 "popl %%eax" & LF & HT & -- load eax with flags
27710 "movl %%eax, %0", -- store flags in variable
27711 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27712 @end group
27713 @end smallexample
27714 @noindent
27715 @code{%0} will be replaced in the expanded code by the appropriate operand,
27716 whatever
27717 the compiler decided for the @code{Flags} variable.
27718
27719 In general, you may have any number of output variables:
27720 @itemize @bullet
27721 @item
27722 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27723 @item
27724 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27725 of @code{Asm_Output} attributes
27726 @end itemize
27727
27728 For example:
27729 @smallexample @c ada
27730 @group
27731 Asm ("movl %%eax, %0" & LF & HT &
27732 "movl %%ebx, %1" & LF & HT &
27733 "movl %%ecx, %2",
27734 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
27735 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
27736 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
27737 @end group
27738 @end smallexample
27739 @noindent
27740 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
27741 in the Ada program.
27742
27743 As a variation on the @code{Get_Flags} example, we can use the constraints
27744 string to direct the compiler to store the eax register into the @code{Flags}
27745 variable, instead of including the store instruction explicitly in the
27746 @code{Asm} template string:
27747
27748 @smallexample @c ada
27749 @group
27750 with Interfaces; use Interfaces;
27751 with Ada.Text_IO; use Ada.Text_IO;
27752 with System.Machine_Code; use System.Machine_Code;
27753 procedure Get_Flags_2 is
27754 Flags : Unsigned_32;
27755 use ASCII;
27756 begin
27757 Asm ("pushfl" & LF & HT & -- push flags on stack
27758 "popl %%eax", -- save flags in eax
27759 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
27760 Put_Line ("Flags register:" & Flags'Img);
27761 end Get_Flags_2;
27762 @end group
27763 @end smallexample
27764
27765 @noindent
27766 The @code{"a"} constraint tells the compiler that the @code{Flags}
27767 variable will come from the eax register. Here is the resulting code:
27768
27769 @smallexample
27770 @group
27771 #APP
27772 pushfl
27773 popl %eax
27774 #NO_APP
27775 movl %eax,-40(%ebp)
27776 @end group
27777 @end smallexample
27778
27779 @noindent
27780 The compiler generated the store of eax into Flags after
27781 expanding the assembler code.
27782
27783 Actually, there was no need to pop the flags into the eax register;
27784 more simply, we could just pop the flags directly into the program variable:
27785
27786 @smallexample @c ada
27787 @group
27788 with Interfaces; use Interfaces;
27789 with Ada.Text_IO; use Ada.Text_IO;
27790 with System.Machine_Code; use System.Machine_Code;
27791 procedure Get_Flags_3 is
27792 Flags : Unsigned_32;
27793 use ASCII;
27794 begin
27795 Asm ("pushfl" & LF & HT & -- push flags on stack
27796 "pop %0", -- save flags in Flags
27797 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27798 Put_Line ("Flags register:" & Flags'Img);
27799 end Get_Flags_3;
27800 @end group
27801 @end smallexample
27802
27803 @c ---------------------------------------------------------------------------
27804 @node Input Variables in Inline Assembler
27805 @section Input Variables in Inline Assembler
27806
27807 @noindent
27808 The example in this section illustrates how to specify the source operands
27809 for assembly language statements.
27810 The program simply increments its input value by 1:
27811
27812 @smallexample @c ada
27813 @group
27814 with Interfaces; use Interfaces;
27815 with Ada.Text_IO; use Ada.Text_IO;
27816 with System.Machine_Code; use System.Machine_Code;
27817 procedure Increment is
27818
27819 function Incr (Value : Unsigned_32) return Unsigned_32 is
27820 Result : Unsigned_32;
27821 begin
27822 Asm ("incl %0",
27823 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27824 Inputs => Unsigned_32'Asm_Input ("a", Value));
27825 return Result;
27826 end Incr;
27827
27828 Value : Unsigned_32;
27829
27830 begin
27831 Value := 5;
27832 Put_Line ("Value before is" & Value'Img);
27833 Value := Incr (Value);
27834 Put_Line ("Value after is" & Value'Img);
27835 end Increment;
27836 @end group
27837 @end smallexample
27838
27839 The @code{Outputs} parameter to @code{Asm} specifies
27840 that the result will be in the eax register and that it is to be stored
27841 in the @code{Result} variable.
27842
27843 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27844 but with an @code{Asm_Input} attribute.
27845 The @code{"="} constraint, indicating an output value, is not present.
27846
27847 You can have multiple input variables, in the same way that you can have more
27848 than one output variable.
27849
27850 The parameter count (%0, %1) etc, still starts at the first output statement,
27851 and continues with the input statements.
27852
27853 Just as the @code{Outputs} parameter causes the register to be stored into the
27854 target variable after execution of the assembler statements, so does the
27855 @code{Inputs} parameter cause its variable to be loaded into the register
27856 before execution of the assembler statements.
27857
27858 Thus the effect of the @code{Asm} invocation is:
27859 @enumerate
27860 @item load the 32-bit value of @code{Value} into eax
27861 @item execute the @code{incl %eax} instruction
27862 @item store the contents of eax into the @code{Result} variable
27863 @end enumerate
27864
27865 The resulting assembler file (with @option{-O2} optimization) contains:
27866 @smallexample
27867 @group
27868 _increment__incr.1:
27869 subl $4,%esp
27870 movl 8(%esp),%eax
27871 #APP
27872 incl %eax
27873 #NO_APP
27874 movl %eax,%edx
27875 movl %ecx,(%esp)
27876 addl $4,%esp
27877 ret
27878 @end group
27879 @end smallexample
27880
27881 @c ---------------------------------------------------------------------------
27882 @node Inlining Inline Assembler Code
27883 @section Inlining Inline Assembler Code
27884
27885 @noindent
27886 For a short subprogram such as the @code{Incr} function in the previous
27887 section, the overhead of the call and return (creating / deleting the stack
27888 frame) can be significant, compared to the amount of code in the subprogram
27889 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27890 which directs the compiler to expand invocations of the subprogram at the
27891 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27892 Here is the resulting program:
27893
27894 @smallexample @c ada
27895 @group
27896 with Interfaces; use Interfaces;
27897 with Ada.Text_IO; use Ada.Text_IO;
27898 with System.Machine_Code; use System.Machine_Code;
27899 procedure Increment_2 is
27900
27901 function Incr (Value : Unsigned_32) return Unsigned_32 is
27902 Result : Unsigned_32;
27903 begin
27904 Asm ("incl %0",
27905 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27906 Inputs => Unsigned_32'Asm_Input ("a", Value));
27907 return Result;
27908 end Incr;
27909 pragma Inline (Increment);
27910
27911 Value : Unsigned_32;
27912
27913 begin
27914 Value := 5;
27915 Put_Line ("Value before is" & Value'Img);
27916 Value := Increment (Value);
27917 Put_Line ("Value after is" & Value'Img);
27918 end Increment_2;
27919 @end group
27920 @end smallexample
27921
27922 Compile the program with both optimization (@option{-O2}) and inlining
27923 (@option{-gnatn}) enabled.
27924
27925 The @code{Incr} function is still compiled as usual, but at the
27926 point in @code{Increment} where our function used to be called:
27927
27928 @smallexample
27929 @group
27930 pushl %edi
27931 call _increment__incr.1
27932 @end group
27933 @end smallexample
27934
27935 @noindent
27936 the code for the function body directly appears:
27937
27938 @smallexample
27939 @group
27940 movl %esi,%eax
27941 #APP
27942 incl %eax
27943 #NO_APP
27944 movl %eax,%edx
27945 @end group
27946 @end smallexample
27947
27948 @noindent
27949 thus saving the overhead of stack frame setup and an out-of-line call.
27950
27951 @c ---------------------------------------------------------------------------
27952 @node Other Asm Functionality
27953 @section Other @code{Asm} Functionality
27954
27955 @noindent
27956 This section describes two important parameters to the @code{Asm}
27957 procedure: @code{Clobber}, which identifies register usage;
27958 and @code{Volatile}, which inhibits unwanted optimizations.
27959
27960 @menu
27961 * The Clobber Parameter::
27962 * The Volatile Parameter::
27963 @end menu
27964
27965 @c ---------------------------------------------------------------------------
27966 @node The Clobber Parameter
27967 @subsection The @code{Clobber} Parameter
27968
27969 @noindent
27970 One of the dangers of intermixing assembly language and a compiled language
27971 such as Ada is that the compiler needs to be aware of which registers are
27972 being used by the assembly code. In some cases, such as the earlier examples,
27973 the constraint string is sufficient to indicate register usage (e.g.,
27974 @code{"a"} for
27975 the eax register). But more generally, the compiler needs an explicit
27976 identification of the registers that are used by the Inline Assembly
27977 statements.
27978
27979 Using a register that the compiler doesn't know about
27980 could be a side effect of an instruction (like @code{mull}
27981 storing its result in both eax and edx).
27982 It can also arise from explicit register usage in your
27983 assembly code; for example:
27984 @smallexample
27985 @group
27986 Asm ("movl %0, %%ebx" & LF & HT &
27987 "movl %%ebx, %1",
27988 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27989 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
27990 @end group
27991 @end smallexample
27992 @noindent
27993 where the compiler (since it does not analyze the @code{Asm} template string)
27994 does not know you are using the ebx register.
27995
27996 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27997 to identify the registers that will be used by your assembly code:
27998
27999 @smallexample
28000 @group
28001 Asm ("movl %0, %%ebx" & LF & HT &
28002 "movl %%ebx, %1",
28003 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28004 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28005 Clobber => "ebx");
28006 @end group
28007 @end smallexample
28008
28009 The Clobber parameter is a static string expression specifying the
28010 register(s) you are using. Note that register names are @emph{not} prefixed
28011 by a percent sign. Also, if more than one register is used then their names
28012 are separated by commas; e.g., @code{"eax, ebx"}
28013
28014 The @code{Clobber} parameter has several additional uses:
28015 @enumerate
28016 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28017 @item Use ``register'' name @code{memory} if you changed a memory location
28018 @end enumerate
28019
28020 @c ---------------------------------------------------------------------------
28021 @node The Volatile Parameter
28022 @subsection The @code{Volatile} Parameter
28023 @cindex Volatile parameter
28024
28025 @noindent
28026 Compiler optimizations in the presence of Inline Assembler may sometimes have
28027 unwanted effects. For example, when an @code{Asm} invocation with an input
28028 variable is inside a loop, the compiler might move the loading of the input
28029 variable outside the loop, regarding it as a one-time initialization.
28030
28031 If this effect is not desired, you can disable such optimizations by setting
28032 the @code{Volatile} parameter to @code{True}; for example:
28033
28034 @smallexample @c ada
28035 @group
28036 Asm ("movl %0, %%ebx" & LF & HT &
28037 "movl %%ebx, %1",
28038 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28039 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28040 Clobber => "ebx",
28041 Volatile => True);
28042 @end group
28043 @end smallexample
28044
28045 By default, @code{Volatile} is set to @code{False} unless there is no
28046 @code{Outputs} parameter.
28047
28048 Although setting @code{Volatile} to @code{True} prevents unwanted
28049 optimizations, it will also disable other optimizations that might be
28050 important for efficiency. In general, you should set @code{Volatile}
28051 to @code{True} only if the compiler's optimizations have created
28052 problems.
28053 @c END OF INLINE ASSEMBLER CHAPTER
28054 @c ===============================
28055
28056 @c ***********************************
28057 @c * Compatibility and Porting Guide *
28058 @c ***********************************
28059 @node Compatibility and Porting Guide
28060 @appendix Compatibility and Porting Guide
28061
28062 @noindent
28063 This chapter describes the compatibility issues that may arise between
28064 GNAT and other Ada compilation systems (including those for Ada 83),
28065 and shows how GNAT can expedite porting
28066 applications developed in other Ada environments.
28067
28068 @menu
28069 * Compatibility with Ada 83::
28070 * Compatibility between Ada 95 and Ada 2005::
28071 * Implementation-dependent characteristics::
28072 * Compatibility with Other Ada Systems::
28073 * Representation Clauses::
28074 @ifclear vms
28075 @c Brief section is only in non-VMS version
28076 @c Full chapter is in VMS version
28077 * Compatibility with HP Ada 83::
28078 @end ifclear
28079 @ifset vms
28080 * Transitioning to 64-Bit GNAT for OpenVMS::
28081 @end ifset
28082 @end menu
28083
28084 @node Compatibility with Ada 83
28085 @section Compatibility with Ada 83
28086 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28087
28088 @noindent
28089 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28090 particular, the design intention was that the difficulties associated
28091 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28092 that occur when moving from one Ada 83 system to another.
28093
28094 However, there are a number of points at which there are minor
28095 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28096 full details of these issues,
28097 and should be consulted for a complete treatment.
28098 In practice the
28099 following subsections treat the most likely issues to be encountered.
28100
28101 @menu
28102 * Legal Ada 83 programs that are illegal in Ada 95::
28103 * More deterministic semantics::
28104 * Changed semantics::
28105 * Other language compatibility issues::
28106 @end menu
28107
28108 @node Legal Ada 83 programs that are illegal in Ada 95
28109 @subsection Legal Ada 83 programs that are illegal in Ada 95
28110
28111 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28112 Ada 95 and thus also in Ada 2005:
28113
28114 @table @emph
28115 @item Character literals
28116 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28117 @code{Wide_Character} as a new predefined character type, some uses of
28118 character literals that were legal in Ada 83 are illegal in Ada 95.
28119 For example:
28120 @smallexample @c ada
28121 for Char in 'A' .. 'Z' loop @dots{} end loop;
28122 @end smallexample
28123
28124 @noindent
28125 The problem is that @code{'A'} and @code{'Z'} could be from either
28126 @code{Character} or @code{Wide_Character}. The simplest correction
28127 is to make the type explicit; e.g.:
28128 @smallexample @c ada
28129 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28130 @end smallexample
28131
28132 @item New reserved words
28133 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28134 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28135 Existing Ada 83 code using any of these identifiers must be edited to
28136 use some alternative name.
28137
28138 @item Freezing rules
28139 The rules in Ada 95 are slightly different with regard to the point at
28140 which entities are frozen, and representation pragmas and clauses are
28141 not permitted past the freeze point. This shows up most typically in
28142 the form of an error message complaining that a representation item
28143 appears too late, and the appropriate corrective action is to move
28144 the item nearer to the declaration of the entity to which it refers.
28145
28146 A particular case is that representation pragmas
28147 @ifset vms
28148 (including the
28149 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28150 @end ifset
28151 cannot be applied to a subprogram body. If necessary, a separate subprogram
28152 declaration must be introduced to which the pragma can be applied.
28153
28154 @item Optional bodies for library packages
28155 In Ada 83, a package that did not require a package body was nevertheless
28156 allowed to have one. This lead to certain surprises in compiling large
28157 systems (situations in which the body could be unexpectedly ignored by the
28158 binder). In Ada 95, if a package does not require a body then it is not
28159 permitted to have a body. To fix this problem, simply remove a redundant
28160 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28161 into the spec that makes the body required. One approach is to add a private
28162 part to the package declaration (if necessary), and define a parameterless
28163 procedure called @code{Requires_Body}, which must then be given a dummy
28164 procedure body in the package body, which then becomes required.
28165 Another approach (assuming that this does not introduce elaboration
28166 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28167 since one effect of this pragma is to require the presence of a package body.
28168
28169 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28170 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28171 @code{Constraint_Error}.
28172 This means that it is illegal to have separate exception handlers for
28173 the two exceptions. The fix is simply to remove the handler for the
28174 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28175 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28176
28177 @item Indefinite subtypes in generics
28178 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28179 as the actual for a generic formal private type, but then the instantiation
28180 would be illegal if there were any instances of declarations of variables
28181 of this type in the generic body. In Ada 95, to avoid this clear violation
28182 of the methodological principle known as the ``contract model'',
28183 the generic declaration explicitly indicates whether
28184 or not such instantiations are permitted. If a generic formal parameter
28185 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28186 subtype name, then it can be instantiated with indefinite types, but no
28187 stand-alone variables can be declared of this type. Any attempt to declare
28188 such a variable will result in an illegality at the time the generic is
28189 declared. If the @code{(<>)} notation is not used, then it is illegal
28190 to instantiate the generic with an indefinite type.
28191 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28192 It will show up as a compile time error, and
28193 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28194 @end table
28195
28196 @node More deterministic semantics
28197 @subsection More deterministic semantics
28198
28199 @table @emph
28200 @item Conversions
28201 Conversions from real types to integer types round away from 0. In Ada 83
28202 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28203 implementation freedom was intended to support unbiased rounding in
28204 statistical applications, but in practice it interfered with portability.
28205 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28206 is required. Numeric code may be affected by this change in semantics.
28207 Note, though, that this issue is no worse than already existed in Ada 83
28208 when porting code from one vendor to another.
28209
28210 @item Tasking
28211 The Real-Time Annex introduces a set of policies that define the behavior of
28212 features that were implementation dependent in Ada 83, such as the order in
28213 which open select branches are executed.
28214 @end table
28215
28216 @node Changed semantics
28217 @subsection Changed semantics
28218
28219 @noindent
28220 The worst kind of incompatibility is one where a program that is legal in
28221 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28222 possible in Ada 83. Fortunately this is extremely rare, but the one
28223 situation that you should be alert to is the change in the predefined type
28224 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28225
28226 @table @emph
28227 @item Range of type @code{Character}
28228 The range of @code{Standard.Character} is now the full 256 characters
28229 of Latin-1, whereas in most Ada 83 implementations it was restricted
28230 to 128 characters. Although some of the effects of
28231 this change will be manifest in compile-time rejection of legal
28232 Ada 83 programs it is possible for a working Ada 83 program to have
28233 a different effect in Ada 95, one that was not permitted in Ada 83.
28234 As an example, the expression
28235 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28236 delivers @code{255} as its value.
28237 In general, you should look at the logic of any
28238 character-processing Ada 83 program and see whether it needs to be adapted
28239 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28240 character handling package that may be relevant if code needs to be adapted
28241 to account for the additional Latin-1 elements.
28242 The desirable fix is to
28243 modify the program to accommodate the full character set, but in some cases
28244 it may be convenient to define a subtype or derived type of Character that
28245 covers only the restricted range.
28246 @cindex Latin-1
28247 @end table
28248
28249 @node Other language compatibility issues
28250 @subsection Other language compatibility issues
28251
28252 @table @emph
28253 @item @option{-gnat83} switch
28254 All implementations of GNAT provide a switch that causes GNAT to operate
28255 in Ada 83 mode. In this mode, some but not all compatibility problems
28256 of the type described above are handled automatically. For example, the
28257 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28258 as identifiers as in Ada 83.
28259 However,
28260 in practice, it is usually advisable to make the necessary modifications
28261 to the program to remove the need for using this switch.
28262 See @ref{Compiling Different Versions of Ada}.
28263
28264 @item Support for removed Ada 83 pragmas and attributes
28265 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28266 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28267 compilers are allowed, but not required, to implement these missing
28268 elements. In contrast with some other compilers, GNAT implements all
28269 such pragmas and attributes, eliminating this compatibility concern. These
28270 include @code{pragma Interface} and the floating point type attributes
28271 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28272 @end table
28273
28274
28275 @node Compatibility between Ada 95 and Ada 2005
28276 @section Compatibility between Ada 95 and Ada 2005
28277 @cindex Compatibility between Ada 95 and Ada 2005
28278
28279 @noindent
28280 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28281 a number of incompatibilities. Several are enumerated below;
28282 for a complete description please see the
28283 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28284 @cite{Rationale for Ada 2005}.
28285
28286 @table @emph
28287 @item New reserved words.
28288 The words @code{interface}, @code{overriding} and @code{synchronized} are
28289 reserved in Ada 2005.
28290 A pre-Ada 2005 program that uses any of these as an identifier will be
28291 illegal.
28292
28293 @item New declarations in predefined packages.
28294 A number of packages in the predefined environment contain new declarations:
28295 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28296 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28297 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28298 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28299 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28300 If an Ada 95 program does a @code{with} and @code{use} of any of these
28301 packages, the new declarations may cause name clashes.
28302
28303 @item Access parameters.
28304 A nondispatching subprogram with an access parameter cannot be renamed
28305 as a dispatching operation. This was permitted in Ada 95.
28306
28307 @item Access types, discriminants, and constraints.
28308 Rule changes in this area have led to some incompatibilities; for example,
28309 constrained subtypes of some access types are not permitted in Ada 2005.
28310
28311 @item Aggregates for limited types.
28312 The allowance of aggregates for limited types in Ada 2005 raises the
28313 possibility of ambiguities in legal Ada 95 programs, since additional types
28314 now need to be considered in expression resolution.
28315
28316 @item Fixed-point multiplication and division.
28317 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28318 were legal in Ada 95 and invoked the predefined versions of these operations,
28319 are now ambiguous.
28320 The ambiguity may be resolved either by applying a type conversion to the
28321 expression, or by explicitly invoking the operation from package
28322 @code{Standard}.
28323
28324 @item Return-by-reference types.
28325 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
28326 can declare a function returning a value from an anonymous access type.
28327 @end table
28328
28329
28330 @node Implementation-dependent characteristics
28331 @section Implementation-dependent characteristics
28332 @noindent
28333 Although the Ada language defines the semantics of each construct as
28334 precisely as practical, in some situations (for example for reasons of
28335 efficiency, or where the effect is heavily dependent on the host or target
28336 platform) the implementation is allowed some freedom. In porting Ada 83
28337 code to GNAT, you need to be aware of whether / how the existing code
28338 exercised such implementation dependencies. Such characteristics fall into
28339 several categories, and GNAT offers specific support in assisting the
28340 transition from certain Ada 83 compilers.
28341
28342 @menu
28343 * Implementation-defined pragmas::
28344 * Implementation-defined attributes::
28345 * Libraries::
28346 * Elaboration order::
28347 * Target-specific aspects::
28348 @end menu
28349
28350 @node Implementation-defined pragmas
28351 @subsection Implementation-defined pragmas
28352
28353 @noindent
28354 Ada compilers are allowed to supplement the language-defined pragmas, and
28355 these are a potential source of non-portability. All GNAT-defined pragmas
28356 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28357 Reference Manual}, and these include several that are specifically
28358 intended to correspond to other vendors' Ada 83 pragmas.
28359 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28360 For compatibility with HP Ada 83, GNAT supplies the pragmas
28361 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28362 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28363 and @code{Volatile}.
28364 Other relevant pragmas include @code{External} and @code{Link_With}.
28365 Some vendor-specific
28366 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28367 recognized, thus
28368 avoiding compiler rejection of units that contain such pragmas; they are not
28369 relevant in a GNAT context and hence are not otherwise implemented.
28370
28371 @node Implementation-defined attributes
28372 @subsection Implementation-defined attributes
28373
28374 Analogous to pragmas, the set of attributes may be extended by an
28375 implementation. All GNAT-defined attributes are described in
28376 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28377 Manual}, and these include several that are specifically intended
28378 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
28379 the attribute @code{VADS_Size} may be useful. For compatibility with HP
28380 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28381 @code{Type_Class}.
28382
28383 @node Libraries
28384 @subsection Libraries
28385 @noindent
28386 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
28387 code uses vendor-specific libraries then there are several ways to manage
28388 this in Ada 95 or Ada 2005:
28389 @enumerate
28390 @item
28391 If the source code for the libraries (specs and bodies) are
28392 available, then the libraries can be migrated in the same way as the
28393 application.
28394 @item
28395 If the source code for the specs but not the bodies are
28396 available, then you can reimplement the bodies.
28397 @item
28398 Some features introduced by Ada 95 obviate the need for library support. For
28399 example most Ada 83 vendors supplied a package for unsigned integers. The
28400 Ada 95 modular type feature is the preferred way to handle this need, so
28401 instead of migrating or reimplementing the unsigned integer package it may
28402 be preferable to retrofit the application using modular types.
28403 @end enumerate
28404
28405 @node Elaboration order
28406 @subsection Elaboration order
28407 @noindent
28408 The implementation can choose any elaboration order consistent with the unit
28409 dependency relationship. This freedom means that some orders can result in
28410 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28411 to invoke a subprogram its body has been elaborated, or to instantiate a
28412 generic before the generic body has been elaborated. By default GNAT
28413 attempts to choose a safe order (one that will not encounter access before
28414 elaboration problems) by implicitly inserting @code{Elaborate} or
28415 @code{Elaborate_All} pragmas where
28416 needed. However, this can lead to the creation of elaboration circularities
28417 and a resulting rejection of the program by gnatbind. This issue is
28418 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28419 In brief, there are several
28420 ways to deal with this situation:
28421
28422 @itemize @bullet
28423 @item
28424 Modify the program to eliminate the circularities, e.g.@: by moving
28425 elaboration-time code into explicitly-invoked procedures
28426 @item
28427 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28428 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28429 @code{Elaborate_All}
28430 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28431 (by selectively suppressing elaboration checks via pragma
28432 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28433 @end itemize
28434
28435 @node Target-specific aspects
28436 @subsection Target-specific aspects
28437 @noindent
28438 Low-level applications need to deal with machine addresses, data
28439 representations, interfacing with assembler code, and similar issues. If
28440 such an Ada 83 application is being ported to different target hardware (for
28441 example where the byte endianness has changed) then you will need to
28442 carefully examine the program logic; the porting effort will heavily depend
28443 on the robustness of the original design. Moreover, Ada 95 (and thus
28444 Ada 2005) are sometimes
28445 incompatible with typical Ada 83 compiler practices regarding implicit
28446 packing, the meaning of the Size attribute, and the size of access values.
28447 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28448
28449 @node Compatibility with Other Ada Systems
28450 @section Compatibility with Other Ada Systems
28451
28452 @noindent
28453 If programs avoid the use of implementation dependent and
28454 implementation defined features, as documented in the @cite{Ada
28455 Reference Manual}, there should be a high degree of portability between
28456 GNAT and other Ada systems. The following are specific items which
28457 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28458 compilers, but do not affect porting code to GNAT@.
28459 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28460 the following issues may or may not arise for Ada 2005 programs
28461 when other compilers appear.)
28462
28463 @table @emph
28464 @item Ada 83 Pragmas and Attributes
28465 Ada 95 compilers are allowed, but not required, to implement the missing
28466 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28467 GNAT implements all such pragmas and attributes, eliminating this as
28468 a compatibility concern, but some other Ada 95 compilers reject these
28469 pragmas and attributes.
28470
28471 @item Specialized Needs Annexes
28472 GNAT implements the full set of special needs annexes. At the
28473 current time, it is the only Ada 95 compiler to do so. This means that
28474 programs making use of these features may not be portable to other Ada
28475 95 compilation systems.
28476
28477 @item Representation Clauses
28478 Some other Ada 95 compilers implement only the minimal set of
28479 representation clauses required by the Ada 95 reference manual. GNAT goes
28480 far beyond this minimal set, as described in the next section.
28481 @end table
28482
28483 @node Representation Clauses
28484 @section Representation Clauses
28485
28486 @noindent
28487 The Ada 83 reference manual was quite vague in describing both the minimal
28488 required implementation of representation clauses, and also their precise
28489 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
28490 minimal set of capabilities required is still quite limited.
28491
28492 GNAT implements the full required set of capabilities in
28493 Ada 95 and Ada 2005, but also goes much further, and in particular
28494 an effort has been made to be compatible with existing Ada 83 usage to the
28495 greatest extent possible.
28496
28497 A few cases exist in which Ada 83 compiler behavior is incompatible with
28498 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
28499 intentional or accidental dependence on specific implementation dependent
28500 characteristics of these Ada 83 compilers. The following is a list of
28501 the cases most likely to arise in existing Ada 83 code.
28502
28503 @table @emph
28504 @item Implicit Packing
28505 Some Ada 83 compilers allowed a Size specification to cause implicit
28506 packing of an array or record. This could cause expensive implicit
28507 conversions for change of representation in the presence of derived
28508 types, and the Ada design intends to avoid this possibility.
28509 Subsequent AI's were issued to make it clear that such implicit
28510 change of representation in response to a Size clause is inadvisable,
28511 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28512 Reference Manuals as implementation advice that is followed by GNAT@.
28513 The problem will show up as an error
28514 message rejecting the size clause. The fix is simply to provide
28515 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28516 a Component_Size clause.
28517
28518 @item Meaning of Size Attribute
28519 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28520 the minimal number of bits required to hold values of the type. For example,
28521 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28522 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
28523 some 32 in this situation. This problem will usually show up as a compile
28524 time error, but not always. It is a good idea to check all uses of the
28525 'Size attribute when porting Ada 83 code. The GNAT specific attribute
28526 Object_Size can provide a useful way of duplicating the behavior of
28527 some Ada 83 compiler systems.
28528
28529 @item Size of Access Types
28530 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28531 and that therefore it will be the same size as a System.Address value. This
28532 assumption is true for GNAT in most cases with one exception. For the case of
28533 a pointer to an unconstrained array type (where the bounds may vary from one
28534 value of the access type to another), the default is to use a ``fat pointer'',
28535 which is represented as two separate pointers, one to the bounds, and one to
28536 the array. This representation has a number of advantages, including improved
28537 efficiency. However, it may cause some difficulties in porting existing Ada 83
28538 code which makes the assumption that, for example, pointers fit in 32 bits on
28539 a machine with 32-bit addressing.
28540
28541 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28542 access types in this case (where the designated type is an unconstrained array
28543 type). These thin pointers are indeed the same size as a System.Address value.
28544 To specify a thin pointer, use a size clause for the type, for example:
28545
28546 @smallexample @c ada
28547 type X is access all String;
28548 for X'Size use Standard'Address_Size;
28549 @end smallexample
28550
28551 @noindent
28552 which will cause the type X to be represented using a single pointer.
28553 When using this representation, the bounds are right behind the array.
28554 This representation is slightly less efficient, and does not allow quite
28555 such flexibility in the use of foreign pointers or in using the
28556 Unrestricted_Access attribute to create pointers to non-aliased objects.
28557 But for any standard portable use of the access type it will work in
28558 a functionally correct manner and allow porting of existing code.
28559 Note that another way of forcing a thin pointer representation
28560 is to use a component size clause for the element size in an array,
28561 or a record representation clause for an access field in a record.
28562 @end table
28563
28564 @ifclear vms
28565 @c This brief section is only in the non-VMS version
28566 @c The complete chapter on HP Ada is in the VMS version
28567 @node Compatibility with HP Ada 83
28568 @section Compatibility with HP Ada 83
28569
28570 @noindent
28571 The VMS version of GNAT fully implements all the pragmas and attributes
28572 provided by HP Ada 83, as well as providing the standard HP Ada 83
28573 libraries, including Starlet. In addition, data layouts and parameter
28574 passing conventions are highly compatible. This means that porting
28575 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28576 most other porting efforts. The following are some of the most
28577 significant differences between GNAT and HP Ada 83.
28578
28579 @table @emph
28580 @item Default floating-point representation
28581 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28582 it is VMS format. GNAT does implement the necessary pragmas
28583 (Long_Float, Float_Representation) for changing this default.
28584
28585 @item System
28586 The package System in GNAT exactly corresponds to the definition in the
28587 Ada 95 reference manual, which means that it excludes many of the
28588 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
28589 that contains the additional definitions, and a special pragma,
28590 Extend_System allows this package to be treated transparently as an
28591 extension of package System.
28592
28593 @item To_Address
28594 The definitions provided by Aux_DEC are exactly compatible with those
28595 in the HP Ada 83 version of System, with one exception.
28596 HP Ada provides the following declarations:
28597
28598 @smallexample @c ada
28599 TO_ADDRESS (INTEGER)
28600 TO_ADDRESS (UNSIGNED_LONGWORD)
28601 TO_ADDRESS (@i{universal_integer})
28602 @end smallexample
28603
28604 @noindent
28605 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28606 an extension to Ada 83 not strictly compatible with the reference manual.
28607 In GNAT, we are constrained to be exactly compatible with the standard,
28608 and this means we cannot provide this capability. In HP Ada 83, the
28609 point of this definition is to deal with a call like:
28610
28611 @smallexample @c ada
28612 TO_ADDRESS (16#12777#);
28613 @end smallexample
28614
28615 @noindent
28616 Normally, according to the Ada 83 standard, one would expect this to be
28617 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28618 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
28619 definition using @i{universal_integer} takes precedence.
28620
28621 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28622 is not possible to be 100% compatible. Since there are many programs using
28623 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28624 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28625 declarations provided in the GNAT version of AUX_Dec are:
28626
28627 @smallexample @c ada
28628 function To_Address (X : Integer) return Address;
28629 pragma Pure_Function (To_Address);
28630
28631 function To_Address_Long (X : Unsigned_Longword)
28632 return Address;
28633 pragma Pure_Function (To_Address_Long);
28634 @end smallexample
28635
28636 @noindent
28637 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28638 change the name to TO_ADDRESS_LONG@.
28639
28640 @item Task_Id values
28641 The Task_Id values assigned will be different in the two systems, and GNAT
28642 does not provide a specified value for the Task_Id of the environment task,
28643 which in GNAT is treated like any other declared task.
28644 @end table
28645
28646 @noindent
28647 For full details on these and other less significant compatibility issues,
28648 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28649 Overview and Comparison on HP Platforms}.
28650
28651 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28652 attributes are recognized, although only a subset of them can sensibly
28653 be implemented. The description of pragmas in @ref{Implementation
28654 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28655 indicates whether or not they are applicable to non-VMS systems.
28656 @end ifclear
28657
28658 @ifset vms
28659 @node Transitioning to 64-Bit GNAT for OpenVMS
28660 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28661
28662 @noindent
28663 This section is meant to assist users of pre-2006 @value{EDITION}
28664 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28665 the version of the GNAT technology supplied in 2006 and later for
28666 OpenVMS on both Alpha and I64.
28667
28668 @menu
28669 * Introduction to transitioning::
28670 * Migration of 32 bit code::
28671 * Taking advantage of 64 bit addressing::
28672 * Technical details::
28673 @end menu
28674
28675 @node Introduction to transitioning
28676 @subsection Introduction
28677
28678 @noindent
28679 64-bit @value{EDITION} for Open VMS has been designed to meet
28680 three main goals:
28681
28682 @enumerate
28683 @item
28684 Providing a full conforming implementation of Ada 95 and Ada 2005
28685
28686 @item
28687 Allowing maximum backward compatibility, thus easing migration of existing
28688 Ada source code
28689
28690 @item
28691 Supplying a path for exploiting the full 64-bit address range
28692 @end enumerate
28693
28694 @noindent
28695 Ada's strong typing semantics has made it
28696 impractical to have different 32-bit and 64-bit modes. As soon as
28697 one object could possibly be outside the 32-bit address space, this
28698 would make it necessary for the @code{System.Address} type to be 64 bits.
28699 In particular, this would cause inconsistencies if 32-bit code is
28700 called from 64-bit code that raises an exception.
28701
28702 This issue has been resolved by always using 64-bit addressing
28703 at the system level, but allowing for automatic conversions between
28704 32-bit and 64-bit addresses where required. Thus users who
28705 do not currently require 64-bit addressing capabilities, can
28706 recompile their code with only minimal changes (and indeed
28707 if the code is written in portable Ada, with no assumptions about
28708 the size of the @code{Address} type, then no changes at all are necessary).
28709 At the same time,
28710 this approach provides a simple, gradual upgrade path to future
28711 use of larger memories than available for 32-bit systems.
28712 Also, newly written applications or libraries will by default
28713 be fully compatible with future systems exploiting 64-bit
28714 addressing capabilities.
28715
28716 @ref{Migration of 32 bit code}, will focus on porting applications
28717 that do not require more than 2 GB of
28718 addressable memory. This code will be referred to as
28719 @emph{32-bit code}.
28720 For applications intending to exploit the full 64-bit address space,
28721 @ref{Taking advantage of 64 bit addressing},
28722 will consider further changes that may be required.
28723 Such code will be referred to below as @emph{64-bit code}.
28724
28725 @node Migration of 32 bit code
28726 @subsection Migration of 32-bit code
28727
28728 @menu
28729 * Address types::
28730 * Access types and 32/64-bit allocation::
28731 * Unchecked conversions::
28732 * Predefined constants::
28733 * Interfacing with C::
28734 * 32/64-bit descriptors::
28735 * Experience with source compatibility::
28736 @end menu
28737
28738 @node Address types
28739 @subsubsection Address types
28740
28741 @noindent
28742 To solve the problem of mixing 64-bit and 32-bit addressing,
28743 while maintaining maximum backward compatibility, the following
28744 approach has been taken:
28745
28746 @itemize @bullet
28747 @item
28748 @code{System.Address} always has a size of 64 bits
28749 @cindex @code{System.Address} size
28750 @cindex @code{Address} size
28751
28752 @item
28753 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
28754 @cindex @code{System.Short_Address} size
28755 @cindex @code{Short_Address} size
28756 @end itemize
28757
28758 @noindent
28759 Since @code{System.Short_Address} is a subtype of @code{System.Address},
28760 a @code{Short_Address}
28761 may be used where an @code{Address} is required, and vice versa, without
28762 needing explicit type conversions.
28763 By virtue of the Open VMS parameter passing conventions,
28764 even imported
28765 and exported subprograms that have 32-bit address parameters are
28766 compatible with those that have 64-bit address parameters.
28767 (See @ref{Making code 64 bit clean} for details.)
28768
28769 The areas that may need attention are those where record types have
28770 been defined that contain components of the type @code{System.Address}, and
28771 where objects of this type are passed to code expecting a record layout with
28772 32-bit addresses.
28773
28774 Different compilers on different platforms cannot be
28775 expected to represent the same type in the same way,
28776 since alignment constraints
28777 and other system-dependent properties affect the compiler's decision.
28778 For that reason, Ada code
28779 generally uses representation clauses to specify the expected
28780 layout where required.
28781
28782 If such a representation clause uses 32 bits for a component having
28783 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
28784 will detect that error and produce a specific diagnostic message.
28785 The developer should then determine whether the representation
28786 should be 64 bits or not and make either of two changes:
28787 change the size to 64 bits and leave the type as @code{System.Address}, or
28788 leave the size as 32 bits and change the type to @code{System.Short_Address}.
28789 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
28790 required in any code setting or accessing the field; the compiler will
28791 automatically perform any needed conversions between address
28792 formats.
28793
28794 @node Access types and 32/64-bit allocation
28795 @subsubsection Access types and 32/64-bit allocation
28796 @cindex 32-bit allocation
28797 @cindex 64-bit allocation
28798
28799 @noindent
28800 By default, objects designated by access values are always allocated in
28801 the 64-bit address space, and access values themselves are represented
28802 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
28803 is required (for example if the address of an allocated object is assigned
28804 to a @code{Short_Address} variable), then several alternatives are available:
28805
28806 @itemize @bullet
28807 @item
28808 A pool-specific access type (ie, an @w{Ada 83} access type, whose
28809 definition is @code{access T} versus @code{access all T} or
28810 @code{access constant T}), may be declared with a @code{'Size} representation
28811 clause that establishes the size as 32 bits.
28812 In such circumstances allocations for that type will
28813 be from the 32-bit heap. Such a clause is not permitted
28814 for a general access type (declared with @code{access all} or
28815 @code{access constant}) as values of such types must be able to refer
28816 to any object of the designated type, including objects residing outside
28817 the 32-bit address range. Existing @w{Ada 83} code will not contain such
28818 type definitions, however, since general access types were introduced
28819 in @w{Ada 95}.
28820
28821 @item
28822 Switches for @command{GNAT BIND} control whether the internal GNAT
28823 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28824 @cindex @code{__gnat_malloc}
28825 The switches are respectively @option{-H64} (the default) and
28826 @option{-H32}.
28827 @cindex @option{-H32} (@command{gnatbind})
28828 @cindex @option{-H64} (@command{gnatbind})
28829
28830 @item
28831 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28832 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28833 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28834 If this variable is left
28835 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28836 then the default (64-bit) allocation is used.
28837 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28838 then 32-bit allocation is used. The gnatbind qualifiers described above
28839 override this logical name.
28840
28841 @item
28842 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28843 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28844 at a low level to convert explicit calls to @code{malloc} and related
28845 functions from the C run-time library so that they perform allocations
28846 in the 32-bit heap.
28847 Since all internal allocations from GNAT use @code{__gnat_malloc},
28848 this switch is not required unless the program makes explicit calls on
28849 @code{malloc} (or related functions) from interfaced C code.
28850 @end itemize
28851
28852
28853 @node Unchecked conversions
28854 @subsubsection Unchecked conversions
28855
28856 @noindent
28857 In the case of an @code{Unchecked_Conversion} where the source type is a
28858 64-bit access type or the type @code{System.Address}, and the target
28859 type is a 32-bit type, the compiler will generate a warning.
28860 Even though the generated code will still perform the required
28861 conversions, it is highly recommended in these cases to use
28862 respectively a 32-bit access type or @code{System.Short_Address}
28863 as the source type.
28864
28865 @node Predefined constants
28866 @subsubsection Predefined constants
28867
28868 @noindent
28869 The following table shows the correspondence between pre-2006 versions of
28870 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28871 (``New''):
28872
28873 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28874 @item @b{Constant} @tab @b{Old} @tab @b{New}
28875 @item @code{System.Word_Size} @tab 32 @tab 64
28876 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
28877 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
28878 @item @code{System.Address_Size} @tab 32 @tab 64
28879 @end multitable
28880
28881 @noindent
28882 If you need to refer to the specific
28883 memory size of a 32-bit implementation, instead of the
28884 actual memory size, use @code{System.Short_Memory_Size}
28885 rather than @code{System.Memory_Size}.
28886 Similarly, references to @code{System.Address_Size} may need
28887 to be replaced by @code{System.Short_Address'Size}.
28888 The program @command{gnatfind} may be useful for locating
28889 references to the above constants, so that you can verify that they
28890 are still correct.
28891
28892 @node Interfacing with C
28893 @subsubsection Interfacing with C
28894
28895 @noindent
28896 In order to minimize the impact of the transition to 64-bit addresses on
28897 legacy programs, some fundamental types in the @code{Interfaces.C}
28898 package hierarchy continue to be represented in 32 bits.
28899 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28900 This eases integration with the default HP C layout choices, for example
28901 as found in the system routines in @code{DECC$SHR.EXE}.
28902 Because of this implementation choice, the type fully compatible with
28903 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28904 Depending on the context the compiler will issue a
28905 warning or an error when type @code{Address} is used, alerting the user to a
28906 potential problem. Otherwise 32-bit programs that use
28907 @code{Interfaces.C} should normally not require code modifications
28908
28909 The other issue arising with C interfacing concerns pragma @code{Convention}.
28910 For VMS 64-bit systems, there is an issue of the appropriate default size
28911 of C convention pointers in the absence of an explicit size clause. The HP
28912 C compiler can choose either 32 or 64 bits depending on compiler options.
28913 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28914 clause is given. This proves a better choice for porting 32-bit legacy
28915 applications. In order to have a 64-bit representation, it is necessary to
28916 specify a size representation clause. For example:
28917
28918 @smallexample @c ada
28919 type int_star is access Interfaces.C.int;
28920 pragma Convention(C, int_star);
28921 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
28922 @end smallexample
28923
28924 @node 32/64-bit descriptors
28925 @subsubsection 32/64-bit descriptors
28926
28927 @noindent
28928 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
28929 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
28930 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
28931 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
28932 @cindex @code{Short_Descriptor} mechanism for imported subprograms
28933
28934 If the configuration pragma @code{Short_Descriptors} is supplied, then
28935 all descriptors will be 32 bits.
28936 @cindex pragma @code{Short_Descriptors}
28937
28938 @node Experience with source compatibility
28939 @subsubsection Experience with source compatibility
28940
28941 @noindent
28942 The Security Server and STARLET on I64 provide an interesting ``test case''
28943 for source compatibility issues, since it is in such system code
28944 where assumptions about @code{Address} size might be expected to occur.
28945 Indeed, there were a small number of occasions in the Security Server
28946 file @file{jibdef.ads}
28947 where a representation clause for a record type specified
28948 32 bits for a component of type @code{Address}.
28949 All of these errors were detected by the compiler.
28950 The repair was obvious and immediate; to simply replace @code{Address} by
28951 @code{Short_Address}.
28952
28953 In the case of STARLET, there were several record types that should
28954 have had representation clauses but did not. In these record types
28955 there was an implicit assumption that an @code{Address} value occupied
28956 32 bits.
28957 These compiled without error, but their usage resulted in run-time error
28958 returns from STARLET system calls.
28959 Future GNAT technology enhancements may include a tool that detects and flags
28960 these sorts of potential source code porting problems.
28961
28962 @c ****************************************
28963 @node Taking advantage of 64 bit addressing
28964 @subsection Taking advantage of 64-bit addressing
28965
28966 @menu
28967 * Making code 64 bit clean::
28968 * Allocating memory from the 64 bit storage pool::
28969 * Restrictions on use of 64 bit objects::
28970 * STARLET and other predefined libraries::
28971 @end menu
28972
28973 @node Making code 64 bit clean
28974 @subsubsection Making code 64-bit clean
28975
28976 @noindent
28977 In order to prevent problems that may occur when (parts of) a
28978 system start using memory outside the 32-bit address range,
28979 we recommend some additional guidelines:
28980
28981 @itemize @bullet
28982 @item
28983 For imported subprograms that take parameters of the
28984 type @code{System.Address}, ensure that these subprograms can
28985 indeed handle 64-bit addresses. If not, or when in doubt,
28986 change the subprogram declaration to specify
28987 @code{System.Short_Address} instead.
28988
28989 @item
28990 Resolve all warnings related to size mismatches in
28991 unchecked conversions. Failing to do so causes
28992 erroneous execution if the source object is outside
28993 the 32-bit address space.
28994
28995 @item
28996 (optional) Explicitly use the 32-bit storage pool
28997 for access types used in a 32-bit context, or use
28998 generic access types where possible
28999 (@pxref{Restrictions on use of 64 bit objects}).
29000 @end itemize
29001
29002 @noindent
29003 If these rules are followed, the compiler will automatically insert
29004 any necessary checks to ensure that no addresses or access values
29005 passed to 32-bit code ever refer to objects outside the 32-bit
29006 address range.
29007 Any attempt to do this will raise @code{Constraint_Error}.
29008
29009 @node Allocating memory from the 64 bit storage pool
29010 @subsubsection Allocating memory from the 64-bit storage pool
29011
29012 @noindent
29013 By default, all allocations -- for both pool-specific and general
29014 access types -- use the 64-bit storage pool. To override
29015 this default, for an individual access type or globally, see
29016 @ref{Access types and 32/64-bit allocation}.
29017
29018 @node Restrictions on use of 64 bit objects
29019 @subsubsection Restrictions on use of 64-bit objects
29020
29021 @noindent
29022 Taking the address of an object allocated from a 64-bit storage pool,
29023 and then passing this address to a subprogram expecting
29024 @code{System.Short_Address},
29025 or assigning it to a variable of type @code{Short_Address}, will cause
29026 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29027 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29028 no exception is raised and execution
29029 will become erroneous.
29030
29031 @node STARLET and other predefined libraries
29032 @subsubsection STARLET and other predefined libraries
29033
29034 @noindent
29035 All code that comes as part of GNAT is 64-bit clean, but the
29036 restrictions given in @ref{Restrictions on use of 64 bit objects},
29037 still apply. Look at the package
29038 specs to see in which contexts objects allocated
29039 in 64-bit address space are acceptable.
29040
29041 @node Technical details
29042 @subsection Technical details
29043
29044 @noindent
29045 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29046 Ada standard with respect to the type of @code{System.Address}. Previous
29047 versions of @value{EDITION} have defined this type as private and implemented it as a
29048 modular type.
29049
29050 In order to allow defining @code{System.Short_Address} as a proper subtype,
29051 and to match the implicit sign extension in parameter passing,
29052 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29053 visible (i.e., non-private) integer type.
29054 Standard operations on the type, such as the binary operators ``+'', ``-'',
29055 etc., that take @code{Address} operands and return an @code{Address} result,
29056 have been hidden by declaring these
29057 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29058 ambiguities that would otherwise result from overloading.
29059 (Note that, although @code{Address} is a visible integer type,
29060 good programming practice dictates against exploiting the type's
29061 integer properties such as literals, since this will compromise
29062 code portability.)
29063
29064 Defining @code{Address} as a visible integer type helps achieve
29065 maximum compatibility for existing Ada code,
29066 without sacrificing the capabilities of the 64-bit architecture.
29067 @end ifset
29068
29069 @c ************************************************
29070 @node Microsoft Windows Topics
29071 @appendix Microsoft Windows Topics
29072 @cindex Windows NT
29073 @cindex Windows 95
29074 @cindex Windows 98
29075
29076 @noindent
29077 This chapter describes topics that are specific to the Microsoft Windows
29078 platforms (NT, 2000, and XP Professional).
29079
29080 @menu
29081 @ifclear FSFEDITION
29082 * Installing from the Command Line::
29083 @end ifclear
29084 * Using GNAT on Windows::
29085 * Using a network installation of GNAT::
29086 * CONSOLE and WINDOWS subsystems::
29087 * Temporary Files::
29088 * Mixed-Language Programming on Windows::
29089 * Windows Calling Conventions::
29090 * Introduction to Dynamic Link Libraries (DLLs)::
29091 * Using DLLs with GNAT::
29092 * Building DLLs with GNAT Project files::
29093 * Building DLLs with GNAT::
29094 * Building DLLs with gnatdll::
29095 * GNAT and Windows Resources::
29096 * Debugging a DLL::
29097 * Setting Stack Size from gnatlink::
29098 * Setting Heap Size from gnatlink::
29099 @end menu
29100
29101 @ifclear FSFEDITION
29102 @node Installing from the Command Line
29103 @section Installing from the Command Line
29104 @cindex Batch installation
29105 @cindex Silent installation
29106 @cindex Unassisted installation
29107
29108 @noindent
29109 By default the @value{EDITION} installers display a GUI that prompts the user
29110 to enter installation path and similar information, and guide him through the
29111 installation process. It is also possible to perform silent installations
29112 using the command-line interface.
29113
29114 In order to install one of the @value{EDITION} installers from the command
29115 line you should pass parameter @code{/S} (and, optionally,
29116 @code{/D=<directory>}) as command-line arguments.
29117
29118 @ifset PROEDITION
29119 For example, for an unattended installation of
29120 @value{EDITION} 7.0.2 into the default directory
29121 @code{C:\GNATPRO\7.0.2} you would run:
29122
29123 @smallexample
29124 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29125 @end smallexample
29126
29127 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29128
29129 @smallexample
29130 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29131 @end smallexample
29132 @end ifset
29133
29134 @ifset GPLEDITION
29135 For example, for an unattended installation of
29136 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29137
29138 @smallexample
29139 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29140 @end smallexample
29141 @end ifset
29142
29143 You can use the same syntax for all installers.
29144
29145 Note that unattended installations don't modify system path, nor create file
29146 associations, so such activities need to be done by hand.
29147 @end ifclear
29148
29149 @node Using GNAT on Windows
29150 @section Using GNAT on Windows
29151
29152 @noindent
29153 One of the strengths of the GNAT technology is that its tool set
29154 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29155 @code{gdb} debugger, etc.) is used in the same way regardless of the
29156 platform.
29157
29158 On Windows this tool set is complemented by a number of Microsoft-specific
29159 tools that have been provided to facilitate interoperability with Windows
29160 when this is required. With these tools:
29161
29162 @itemize @bullet
29163
29164 @item
29165 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29166 subsystems.
29167
29168 @item
29169 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29170 relocatable and non-relocatable DLLs are supported).
29171
29172 @item
29173 You can build Ada DLLs for use in other applications. These applications
29174 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29175 relocatable and non-relocatable Ada DLLs are supported.
29176
29177 @item
29178 You can include Windows resources in your Ada application.
29179
29180 @item
29181 You can use or create COM/DCOM objects.
29182 @end itemize
29183
29184 @noindent
29185 Immediately below are listed all known general GNAT-for-Windows restrictions.
29186 Other restrictions about specific features like Windows Resources and DLLs
29187 are listed in separate sections below.
29188
29189 @itemize @bullet
29190
29191 @item
29192 It is not possible to use @code{GetLastError} and @code{SetLastError}
29193 when tasking, protected records, or exceptions are used. In these
29194 cases, in order to implement Ada semantics, the GNAT run-time system
29195 calls certain Win32 routines that set the last error variable to 0 upon
29196 success. It should be possible to use @code{GetLastError} and
29197 @code{SetLastError} when tasking, protected record, and exception
29198 features are not used, but it is not guaranteed to work.
29199
29200 @item
29201 It is not possible to link against Microsoft C++ libraries except for
29202 import libraries. Interfacing must be done by the mean of DLLs.
29203
29204 @item
29205 It is possible to link against Microsoft C libraries. Yet the preferred
29206 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29207 doesn't require having two different development environments and makes the
29208 inter-language debugging experience smoother.
29209
29210 @item
29211 When the compilation environment is located on FAT32 drives, users may
29212 experience recompilations of the source files that have not changed if
29213 Daylight Saving Time (DST) state has changed since the last time files
29214 were compiled. NTFS drives do not have this problem.
29215
29216 @item
29217 No components of the GNAT toolset use any entries in the Windows
29218 registry. The only entries that can be created are file associations and
29219 PATH settings, provided the user has chosen to create them at installation
29220 time, as well as some minimal book-keeping information needed to correctly
29221 uninstall or integrate different GNAT products.
29222 @end itemize
29223
29224 @node Using a network installation of GNAT
29225 @section Using a network installation of GNAT
29226
29227 @noindent
29228 Make sure the system on which GNAT is installed is accessible from the
29229 current machine, i.e., the install location is shared over the network.
29230 Shared resources are accessed on Windows by means of UNC paths, which
29231 have the format @code{\\server\sharename\path}
29232
29233 In order to use such a network installation, simply add the UNC path of the
29234 @file{bin} directory of your GNAT installation in front of your PATH. For
29235 example, if GNAT is installed in @file{\GNAT} directory of a share location
29236 called @file{c-drive} on a machine @file{LOKI}, the following command will
29237 make it available:
29238
29239 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29240
29241 Be aware that every compilation using the network installation results in the
29242 transfer of large amounts of data across the network and will likely cause
29243 serious performance penalty.
29244
29245 @node CONSOLE and WINDOWS subsystems
29246 @section CONSOLE and WINDOWS subsystems
29247 @cindex CONSOLE Subsystem
29248 @cindex WINDOWS Subsystem
29249 @cindex -mwindows
29250
29251 @noindent
29252 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29253 (which is the default subsystem) will always create a console when
29254 launching the application. This is not something desirable when the
29255 application has a Windows GUI. To get rid of this console the
29256 application must be using the @code{WINDOWS} subsystem. To do so
29257 the @option{-mwindows} linker option must be specified.
29258
29259 @smallexample
29260 $ gnatmake winprog -largs -mwindows
29261 @end smallexample
29262
29263 @node Temporary Files
29264 @section Temporary Files
29265 @cindex Temporary files
29266
29267 @noindent
29268 It is possible to control where temporary files gets created by setting
29269 the @env{TMP} environment variable. The file will be created:
29270
29271 @itemize
29272 @item Under the directory pointed to by the @env{TMP} environment variable if
29273 this directory exists.
29274
29275 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29276 set (or not pointing to a directory) and if this directory exists.
29277
29278 @item Under the current working directory otherwise.
29279 @end itemize
29280
29281 @noindent
29282 This allows you to determine exactly where the temporary
29283 file will be created. This is particularly useful in networked
29284 environments where you may not have write access to some
29285 directories.
29286
29287 @node Mixed-Language Programming on Windows
29288 @section Mixed-Language Programming on Windows
29289
29290 @noindent
29291 Developing pure Ada applications on Windows is no different than on
29292 other GNAT-supported platforms. However, when developing or porting an
29293 application that contains a mix of Ada and C/C++, the choice of your
29294 Windows C/C++ development environment conditions your overall
29295 interoperability strategy.
29296
29297 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29298 your application, there are no Windows-specific restrictions that
29299 affect the overall interoperability with your Ada code. If you do want
29300 to use the Microsoft tools for your C++ code, you have two choices:
29301
29302 @enumerate
29303 @item
29304 Encapsulate your C++ code in a DLL to be linked with your Ada
29305 application. In this case, use the Microsoft or whatever environment to
29306 build the DLL and use GNAT to build your executable
29307 (@pxref{Using DLLs with GNAT}).
29308
29309 @item
29310 Or you can encapsulate your Ada code in a DLL to be linked with the
29311 other part of your application. In this case, use GNAT to build the DLL
29312 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29313 or whatever environment to build your executable.
29314 @end enumerate
29315
29316 In addition to the description about C main in
29317 @pxref{Mixed Language Programming} section, if the C main uses a
29318 stand-alone library it is required on x86-windows to
29319 setup the SEH context. For this the C main must looks like this:
29320
29321 @smallexample
29322 /* main.c */
29323 extern void adainit (void);
29324 extern void adafinal (void);
29325 extern void __gnat_initialize(void*);
29326 extern void call_to_ada (void);
29327
29328 int main (int argc, char *argv[])
29329 @{
29330 int SEH [2];
29331
29332 /* Initialize the SEH context */
29333 __gnat_initialize (&SEH);
29334
29335 adainit();
29336
29337 /* Then call Ada services in the stand-alone library */
29338
29339 call_to_ada();
29340
29341 adafinal();
29342 @}
29343 @end smallexample
29344
29345 Note that this is not needed on x86_64-windows where the Windows
29346 native SEH support is used.
29347
29348 @node Windows Calling Conventions
29349 @section Windows Calling Conventions
29350 @findex Stdcall
29351 @findex APIENTRY
29352
29353 This section pertain only to Win32. On Win64 there is a single native
29354 calling convention. All convention specifiers are ignored on this
29355 platform.
29356
29357 @menu
29358 * C Calling Convention::
29359 * Stdcall Calling Convention::
29360 * Win32 Calling Convention::
29361 * DLL Calling Convention::
29362 @end menu
29363
29364 @noindent
29365 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29366 (callee), there are several ways to push @code{G}'s parameters on the
29367 stack and there are several possible scenarios to clean up the stack
29368 upon @code{G}'s return. A calling convention is an agreed upon software
29369 protocol whereby the responsibilities between the caller (@code{F}) and
29370 the callee (@code{G}) are clearly defined. Several calling conventions
29371 are available for Windows:
29372
29373 @itemize @bullet
29374 @item
29375 @code{C} (Microsoft defined)
29376
29377 @item
29378 @code{Stdcall} (Microsoft defined)
29379
29380 @item
29381 @code{Win32} (GNAT specific)
29382
29383 @item
29384 @code{DLL} (GNAT specific)
29385 @end itemize
29386
29387 @node C Calling Convention
29388 @subsection @code{C} Calling Convention
29389
29390 @noindent
29391 This is the default calling convention used when interfacing to C/C++
29392 routines compiled with either @command{gcc} or Microsoft Visual C++.
29393
29394 In the @code{C} calling convention subprogram parameters are pushed on the
29395 stack by the caller from right to left. The caller itself is in charge of
29396 cleaning up the stack after the call. In addition, the name of a routine
29397 with @code{C} calling convention is mangled by adding a leading underscore.
29398
29399 The name to use on the Ada side when importing (or exporting) a routine
29400 with @code{C} calling convention is the name of the routine. For
29401 instance the C function:
29402
29403 @smallexample
29404 int get_val (long);
29405 @end smallexample
29406
29407 @noindent
29408 should be imported from Ada as follows:
29409
29410 @smallexample @c ada
29411 @group
29412 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29413 pragma Import (C, Get_Val, External_Name => "get_val");
29414 @end group
29415 @end smallexample
29416
29417 @noindent
29418 Note that in this particular case the @code{External_Name} parameter could
29419 have been omitted since, when missing, this parameter is taken to be the
29420 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29421 is missing, as in the above example, this parameter is set to be the
29422 @code{External_Name} with a leading underscore.
29423
29424 When importing a variable defined in C, you should always use the @code{C}
29425 calling convention unless the object containing the variable is part of a
29426 DLL (in which case you should use the @code{Stdcall} calling
29427 convention, @pxref{Stdcall Calling Convention}).
29428
29429 @node Stdcall Calling Convention
29430 @subsection @code{Stdcall} Calling Convention
29431
29432 @noindent
29433 This convention, which was the calling convention used for Pascal
29434 programs, is used by Microsoft for all the routines in the Win32 API for
29435 efficiency reasons. It must be used to import any routine for which this
29436 convention was specified.
29437
29438 In the @code{Stdcall} calling convention subprogram parameters are pushed
29439 on the stack by the caller from right to left. The callee (and not the
29440 caller) is in charge of cleaning the stack on routine exit. In addition,
29441 the name of a routine with @code{Stdcall} calling convention is mangled by
29442 adding a leading underscore (as for the @code{C} calling convention) and a
29443 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29444 bytes) of the parameters passed to the routine.
29445
29446 The name to use on the Ada side when importing a C routine with a
29447 @code{Stdcall} calling convention is the name of the C routine. The leading
29448 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29449 the compiler. For instance the Win32 function:
29450
29451 @smallexample
29452 @b{APIENTRY} int get_val (long);
29453 @end smallexample
29454
29455 @noindent
29456 should be imported from Ada as follows:
29457
29458 @smallexample @c ada
29459 @group
29460 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29461 pragma Import (Stdcall, Get_Val);
29462 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29463 @end group
29464 @end smallexample
29465
29466 @noindent
29467 As for the @code{C} calling convention, when the @code{External_Name}
29468 parameter is missing, it is taken to be the name of the Ada entity in lower
29469 case. If instead of writing the above import pragma you write:
29470
29471 @smallexample @c ada
29472 @group
29473 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29474 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29475 @end group
29476 @end smallexample
29477
29478 @noindent
29479 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29480 of specifying the @code{External_Name} parameter you specify the
29481 @code{Link_Name} as in the following example:
29482
29483 @smallexample @c ada
29484 @group
29485 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29486 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29487 @end group
29488 @end smallexample
29489
29490 @noindent
29491 then the imported routine is @code{retrieve_val}, that is, there is no
29492 decoration at all. No leading underscore and no Stdcall suffix
29493 @code{@@}@code{@var{nn}}.
29494
29495 @noindent
29496 This is especially important as in some special cases a DLL's entry
29497 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29498 name generated for a call has it.
29499
29500 @noindent
29501 It is also possible to import variables defined in a DLL by using an
29502 import pragma for a variable. As an example, if a DLL contains a
29503 variable defined as:
29504
29505 @smallexample
29506 int my_var;
29507 @end smallexample
29508
29509 @noindent
29510 then, to access this variable from Ada you should write:
29511
29512 @smallexample @c ada
29513 @group
29514 My_Var : Interfaces.C.int;
29515 pragma Import (Stdcall, My_Var);
29516 @end group
29517 @end smallexample
29518
29519 @noindent
29520 Note that to ease building cross-platform bindings this convention
29521 will be handled as a @code{C} calling convention on non-Windows platforms.
29522
29523 @node Win32 Calling Convention
29524 @subsection @code{Win32} Calling Convention
29525
29526 @noindent
29527 This convention, which is GNAT-specific is fully equivalent to the
29528 @code{Stdcall} calling convention described above.
29529
29530 @node DLL Calling Convention
29531 @subsection @code{DLL} Calling Convention
29532
29533 @noindent
29534 This convention, which is GNAT-specific is fully equivalent to the
29535 @code{Stdcall} calling convention described above.
29536
29537 @node Introduction to Dynamic Link Libraries (DLLs)
29538 @section Introduction to Dynamic Link Libraries (DLLs)
29539 @findex DLL
29540
29541 @noindent
29542 A Dynamically Linked Library (DLL) is a library that can be shared by
29543 several applications running under Windows. A DLL can contain any number of
29544 routines and variables.
29545
29546 One advantage of DLLs is that you can change and enhance them without
29547 forcing all the applications that depend on them to be relinked or
29548 recompiled. However, you should be aware than all calls to DLL routines are
29549 slower since, as you will understand below, such calls are indirect.
29550
29551 To illustrate the remainder of this section, suppose that an application
29552 wants to use the services of a DLL @file{API.dll}. To use the services
29553 provided by @file{API.dll} you must statically link against the DLL or
29554 an import library which contains a jump table with an entry for each
29555 routine and variable exported by the DLL. In the Microsoft world this
29556 import library is called @file{API.lib}. When using GNAT this import
29557 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29558 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29559
29560 After you have linked your application with the DLL or the import library
29561 and you run your application, here is what happens:
29562
29563 @enumerate
29564 @item
29565 Your application is loaded into memory.
29566
29567 @item
29568 The DLL @file{API.dll} is mapped into the address space of your
29569 application. This means that:
29570
29571 @itemize @bullet
29572 @item
29573 The DLL will use the stack of the calling thread.
29574
29575 @item
29576 The DLL will use the virtual address space of the calling process.
29577
29578 @item
29579 The DLL will allocate memory from the virtual address space of the calling
29580 process.
29581
29582 @item
29583 Handles (pointers) can be safely exchanged between routines in the DLL
29584 routines and routines in the application using the DLL.
29585 @end itemize
29586
29587 @item
29588 The entries in the jump table (from the import library @file{libAPI.dll.a}
29589 or @file{API.lib} or automatically created when linking against a DLL)
29590 which is part of your application are initialized with the addresses
29591 of the routines and variables in @file{API.dll}.
29592
29593 @item
29594 If present in @file{API.dll}, routines @code{DllMain} or
29595 @code{DllMainCRTStartup} are invoked. These routines typically contain
29596 the initialization code needed for the well-being of the routines and
29597 variables exported by the DLL.
29598 @end enumerate
29599
29600 @noindent
29601 There is an additional point which is worth mentioning. In the Windows
29602 world there are two kind of DLLs: relocatable and non-relocatable
29603 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29604 in the target application address space. If the addresses of two
29605 non-relocatable DLLs overlap and these happen to be used by the same
29606 application, a conflict will occur and the application will run
29607 incorrectly. Hence, when possible, it is always preferable to use and
29608 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29609 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29610 User's Guide) removes the debugging symbols from the DLL but the DLL can
29611 still be relocated.
29612
29613 As a side note, an interesting difference between Microsoft DLLs and
29614 Unix shared libraries, is the fact that on most Unix systems all public
29615 routines are exported by default in a Unix shared library, while under
29616 Windows it is possible (but not required) to list exported routines in
29617 a definition file (@pxref{The Definition File}).
29618
29619 @node Using DLLs with GNAT
29620 @section Using DLLs with GNAT
29621
29622 @menu
29623 * Creating an Ada Spec for the DLL Services::
29624 * Creating an Import Library::
29625 @end menu
29626
29627 @noindent
29628 To use the services of a DLL, say @file{API.dll}, in your Ada application
29629 you must have:
29630
29631 @enumerate
29632 @item
29633 The Ada spec for the routines and/or variables you want to access in
29634 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29635 header files provided with the DLL.
29636
29637 @item
29638 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29639 mentioned an import library is a statically linked library containing the
29640 import table which will be filled at load time to point to the actual
29641 @file{API.dll} routines. Sometimes you don't have an import library for the
29642 DLL you want to use. The following sections will explain how to build
29643 one. Note that this is optional.
29644
29645 @item
29646 The actual DLL, @file{API.dll}.
29647 @end enumerate
29648
29649 @noindent
29650 Once you have all the above, to compile an Ada application that uses the
29651 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29652 you simply issue the command
29653
29654 @smallexample
29655 $ gnatmake my_ada_app -largs -lAPI
29656 @end smallexample
29657
29658 @noindent
29659 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29660 tells the GNAT linker to look for an import library. The linker will
29661 look for a library name in this specific order:
29662
29663 @enumerate
29664 @item @file{libAPI.dll.a}
29665 @item @file{API.dll.a}
29666 @item @file{libAPI.a}
29667 @item @file{API.lib}
29668 @item @file{libAPI.dll}
29669 @item @file{API.dll}
29670 @end enumerate
29671
29672 The first three are the GNU style import libraries. The third is the
29673 Microsoft style import libraries. The last two are the actual DLL names.
29674
29675 Note that if the Ada package spec for @file{API.dll} contains the
29676 following pragma
29677
29678 @smallexample @c ada
29679 pragma Linker_Options ("-lAPI");
29680 @end smallexample
29681
29682 @noindent
29683 you do not have to add @option{-largs -lAPI} at the end of the
29684 @command{gnatmake} command.
29685
29686 If any one of the items above is missing you will have to create it
29687 yourself. The following sections explain how to do so using as an
29688 example a fictitious DLL called @file{API.dll}.
29689
29690 @node Creating an Ada Spec for the DLL Services
29691 @subsection Creating an Ada Spec for the DLL Services
29692
29693 @noindent
29694 A DLL typically comes with a C/C++ header file which provides the
29695 definitions of the routines and variables exported by the DLL. The Ada
29696 equivalent of this header file is a package spec that contains definitions
29697 for the imported entities. If the DLL you intend to use does not come with
29698 an Ada spec you have to generate one such spec yourself. For example if
29699 the header file of @file{API.dll} is a file @file{api.h} containing the
29700 following two definitions:
29701
29702 @smallexample
29703 @group
29704 @cartouche
29705 int some_var;
29706 int get (char *);
29707 @end cartouche
29708 @end group
29709 @end smallexample
29710
29711 @noindent
29712 then the equivalent Ada spec could be:
29713
29714 @smallexample @c ada
29715 @group
29716 @cartouche
29717 with Interfaces.C.Strings;
29718 package API is
29719 use Interfaces;
29720
29721 Some_Var : C.int;
29722 function Get (Str : C.Strings.Chars_Ptr) return C.int;
29723
29724 private
29725 pragma Import (C, Get);
29726 pragma Import (DLL, Some_Var);
29727 end API;
29728 @end cartouche
29729 @end group
29730 @end smallexample
29731
29732 @node Creating an Import Library
29733 @subsection Creating an Import Library
29734 @cindex Import library
29735
29736 @menu
29737 * The Definition File::
29738 * GNAT-Style Import Library::
29739 * Microsoft-Style Import Library::
29740 @end menu
29741
29742 @noindent
29743 If a Microsoft-style import library @file{API.lib} or a GNAT-style
29744 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
29745 with @file{API.dll} you can skip this section. You can also skip this
29746 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
29747 as in this case it is possible to link directly against the
29748 DLL. Otherwise read on.
29749
29750 @node The Definition File
29751 @subsubsection The Definition File
29752 @cindex Definition file
29753 @findex .def
29754
29755 @noindent
29756 As previously mentioned, and unlike Unix systems, the list of symbols
29757 that are exported from a DLL must be provided explicitly in Windows.
29758 The main goal of a definition file is precisely that: list the symbols
29759 exported by a DLL. A definition file (usually a file with a @code{.def}
29760 suffix) has the following structure:
29761
29762 @smallexample
29763 @group
29764 @cartouche
29765 @r{[}LIBRARY @var{name}@r{]}
29766 @r{[}DESCRIPTION @var{string}@r{]}
29767 EXPORTS
29768 @var{symbol1}
29769 @var{symbol2}
29770 @dots{}
29771 @end cartouche
29772 @end group
29773 @end smallexample
29774
29775 @table @code
29776 @item LIBRARY @var{name}
29777 This section, which is optional, gives the name of the DLL.
29778
29779 @item DESCRIPTION @var{string}
29780 This section, which is optional, gives a description string that will be
29781 embedded in the import library.
29782
29783 @item EXPORTS
29784 This section gives the list of exported symbols (procedures, functions or
29785 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
29786 section of @file{API.def} looks like:
29787
29788 @smallexample
29789 @group
29790 @cartouche
29791 EXPORTS
29792 some_var
29793 get
29794 @end cartouche
29795 @end group
29796 @end smallexample
29797 @end table
29798
29799 @noindent
29800 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
29801 (@pxref{Windows Calling Conventions}) for a Stdcall
29802 calling convention function in the exported symbols list.
29803
29804 @noindent
29805 There can actually be other sections in a definition file, but these
29806 sections are not relevant to the discussion at hand.
29807
29808 @node GNAT-Style Import Library
29809 @subsubsection GNAT-Style Import Library
29810
29811 @noindent
29812 To create a static import library from @file{API.dll} with the GNAT tools
29813 you should proceed as follows:
29814
29815 @enumerate
29816 @item
29817 Create the definition file @file{API.def} (@pxref{The Definition File}).
29818 For that use the @code{dll2def} tool as follows:
29819
29820 @smallexample
29821 $ dll2def API.dll > API.def
29822 @end smallexample
29823
29824 @noindent
29825 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
29826 to standard output the list of entry points in the DLL. Note that if
29827 some routines in the DLL have the @code{Stdcall} convention
29828 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
29829 suffix then you'll have to edit @file{api.def} to add it, and specify
29830 @option{-k} to @command{gnatdll} when creating the import library.
29831
29832 @noindent
29833 Here are some hints to find the right @code{@@}@var{nn} suffix.
29834
29835 @enumerate
29836 @item
29837 If you have the Microsoft import library (.lib), it is possible to get
29838 the right symbols by using Microsoft @code{dumpbin} tool (see the
29839 corresponding Microsoft documentation for further details).
29840
29841 @smallexample
29842 $ dumpbin /exports api.lib
29843 @end smallexample
29844
29845 @item
29846 If you have a message about a missing symbol at link time the compiler
29847 tells you what symbol is expected. You just have to go back to the
29848 definition file and add the right suffix.
29849 @end enumerate
29850
29851 @item
29852 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
29853 (@pxref{Using gnatdll}) as follows:
29854
29855 @smallexample
29856 $ gnatdll -e API.def -d API.dll
29857 @end smallexample
29858
29859 @noindent
29860 @code{gnatdll} takes as input a definition file @file{API.def} and the
29861 name of the DLL containing the services listed in the definition file
29862 @file{API.dll}. The name of the static import library generated is
29863 computed from the name of the definition file as follows: if the
29864 definition file name is @var{xyz}@code{.def}, the import library name will
29865 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29866 @option{-e} could have been removed because the name of the definition
29867 file (before the ``@code{.def}'' suffix) is the same as the name of the
29868 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29869 @end enumerate
29870
29871 @node Microsoft-Style Import Library
29872 @subsubsection Microsoft-Style Import Library
29873
29874 @noindent
29875 With GNAT you can either use a GNAT-style or Microsoft-style import
29876 library. A Microsoft import library is needed only if you plan to make an
29877 Ada DLL available to applications developed with Microsoft
29878 tools (@pxref{Mixed-Language Programming on Windows}).
29879
29880 To create a Microsoft-style import library for @file{API.dll} you
29881 should proceed as follows:
29882
29883 @enumerate
29884 @item
29885 Create the definition file @file{API.def} from the DLL. For this use either
29886 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29887 tool (see the corresponding Microsoft documentation for further details).
29888
29889 @item
29890 Build the actual import library using Microsoft's @code{lib} utility:
29891
29892 @smallexample
29893 $ lib -machine:IX86 -def:API.def -out:API.lib
29894 @end smallexample
29895
29896 @noindent
29897 If you use the above command the definition file @file{API.def} must
29898 contain a line giving the name of the DLL:
29899
29900 @smallexample
29901 LIBRARY "API"
29902 @end smallexample
29903
29904 @noindent
29905 See the Microsoft documentation for further details about the usage of
29906 @code{lib}.
29907 @end enumerate
29908
29909 @node Building DLLs with GNAT Project files
29910 @section Building DLLs with GNAT Project files
29911 @cindex DLLs, building
29912
29913 @noindent
29914 There is nothing specific to Windows in the build process.
29915 @pxref{Library Projects}.
29916
29917 @noindent
29918 Due to a system limitation, it is not possible under Windows to create threads
29919 when inside the @code{DllMain} routine which is used for auto-initialization
29920 of shared libraries, so it is not possible to have library level tasks in SALs.
29921
29922 @node Building DLLs with GNAT
29923 @section Building DLLs with GNAT
29924 @cindex DLLs, building
29925
29926 @noindent
29927 This section explain how to build DLLs using the GNAT built-in DLL
29928 support. With the following procedure it is straight forward to build
29929 and use DLLs with GNAT.
29930
29931 @enumerate
29932
29933 @item building object files
29934
29935 The first step is to build all objects files that are to be included
29936 into the DLL. This is done by using the standard @command{gnatmake} tool.
29937
29938 @item building the DLL
29939
29940 To build the DLL you must use @command{gcc}'s @option{-shared} and
29941 @option{-shared-libgcc} options. It is quite simple to use this method:
29942
29943 @smallexample
29944 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
29945 @end smallexample
29946
29947 It is important to note that in this case all symbols found in the
29948 object files are automatically exported. It is possible to restrict
29949 the set of symbols to export by passing to @command{gcc} a definition
29950 file, @pxref{The Definition File}. For example:
29951
29952 @smallexample
29953 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
29954 @end smallexample
29955
29956 If you use a definition file you must export the elaboration procedures
29957 for every package that required one. Elaboration procedures are named
29958 using the package name followed by "_E".
29959
29960 @item preparing DLL to be used
29961
29962 For the DLL to be used by client programs the bodies must be hidden
29963 from it and the .ali set with read-only attribute. This is very important
29964 otherwise GNAT will recompile all packages and will not actually use
29965 the code in the DLL. For example:
29966
29967 @smallexample
29968 $ mkdir apilib
29969 $ copy *.ads *.ali api.dll apilib
29970 $ attrib +R apilib\*.ali
29971 @end smallexample
29972
29973 @end enumerate
29974
29975 At this point it is possible to use the DLL by directly linking
29976 against it. Note that you must use the GNAT shared runtime when using
29977 GNAT shared libraries. This is achieved by using @option{-shared} binder's
29978 option.
29979
29980 @smallexample
29981 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29982 @end smallexample
29983
29984 @node Building DLLs with gnatdll
29985 @section Building DLLs with gnatdll
29986 @cindex DLLs, building
29987
29988 @menu
29989 * Limitations When Using Ada DLLs from Ada::
29990 * Exporting Ada Entities::
29991 * Ada DLLs and Elaboration::
29992 * Ada DLLs and Finalization::
29993 * Creating a Spec for Ada DLLs::
29994 * Creating the Definition File::
29995 * Using gnatdll::
29996 @end menu
29997
29998 @noindent
29999 Note that it is preferred to use GNAT Project files
30000 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30001 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30002
30003 This section explains how to build DLLs containing Ada code using
30004 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30005 remainder of this section.
30006
30007 The steps required to build an Ada DLL that is to be used by Ada as well as
30008 non-Ada applications are as follows:
30009
30010 @enumerate
30011 @item
30012 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30013 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30014 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30015 skip this step if you plan to use the Ada DLL only from Ada applications.
30016
30017 @item
30018 Your Ada code must export an initialization routine which calls the routine
30019 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30020 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30021 routine exported by the Ada DLL must be invoked by the clients of the DLL
30022 to initialize the DLL.
30023
30024 @item
30025 When useful, the DLL should also export a finalization routine which calls
30026 routine @code{adafinal} generated by @command{gnatbind} to perform the
30027 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30028 The finalization routine exported by the Ada DLL must be invoked by the
30029 clients of the DLL when the DLL services are no further needed.
30030
30031 @item
30032 You must provide a spec for the services exported by the Ada DLL in each
30033 of the programming languages to which you plan to make the DLL available.
30034
30035 @item
30036 You must provide a definition file listing the exported entities
30037 (@pxref{The Definition File}).
30038
30039 @item
30040 Finally you must use @code{gnatdll} to produce the DLL and the import
30041 library (@pxref{Using gnatdll}).
30042 @end enumerate
30043
30044 @noindent
30045 Note that a relocatable DLL stripped using the @code{strip}
30046 binutils tool will not be relocatable anymore. To build a DLL without
30047 debug information pass @code{-largs -s} to @code{gnatdll}. This
30048 restriction does not apply to a DLL built using a Library Project.
30049 @pxref{Library Projects}.
30050
30051 @node Limitations When Using Ada DLLs from Ada
30052 @subsection Limitations When Using Ada DLLs from Ada
30053
30054 @noindent
30055 When using Ada DLLs from Ada applications there is a limitation users
30056 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30057 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30058 each Ada DLL includes the services of the GNAT run time that are necessary
30059 to the Ada code inside the DLL. As a result, when an Ada program uses an
30060 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30061 one in the main program.
30062
30063 It is therefore not possible to exchange GNAT run-time objects between the
30064 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30065 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30066 types, etc.
30067
30068 It is completely safe to exchange plain elementary, array or record types,
30069 Windows object handles, etc.
30070
30071 @node Exporting Ada Entities
30072 @subsection Exporting Ada Entities
30073 @cindex Export table
30074
30075 @noindent
30076 Building a DLL is a way to encapsulate a set of services usable from any
30077 application. As a result, the Ada entities exported by a DLL should be
30078 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30079 any Ada name mangling. As an example here is an Ada package
30080 @code{API}, spec and body, exporting two procedures, a function, and a
30081 variable:
30082
30083 @smallexample @c ada
30084 @group
30085 @cartouche
30086 with Interfaces.C; use Interfaces;
30087 package API is
30088 Count : C.int := 0;
30089 function Factorial (Val : C.int) return C.int;
30090
30091 procedure Initialize_API;
30092 procedure Finalize_API;
30093 -- Initialization & Finalization routines. More in the next section.
30094 private
30095 pragma Export (C, Initialize_API);
30096 pragma Export (C, Finalize_API);
30097 pragma Export (C, Count);
30098 pragma Export (C, Factorial);
30099 end API;
30100 @end cartouche
30101 @end group
30102 @end smallexample
30103
30104 @smallexample @c ada
30105 @group
30106 @cartouche
30107 package body API is
30108 function Factorial (Val : C.int) return C.int is
30109 Fact : C.int := 1;
30110 begin
30111 Count := Count + 1;
30112 for K in 1 .. Val loop
30113 Fact := Fact * K;
30114 end loop;
30115 return Fact;
30116 end Factorial;
30117
30118 procedure Initialize_API is
30119 procedure Adainit;
30120 pragma Import (C, Adainit);
30121 begin
30122 Adainit;
30123 end Initialize_API;
30124
30125 procedure Finalize_API is
30126 procedure Adafinal;
30127 pragma Import (C, Adafinal);
30128 begin
30129 Adafinal;
30130 end Finalize_API;
30131 end API;
30132 @end cartouche
30133 @end group
30134 @end smallexample
30135
30136 @noindent
30137 If the Ada DLL you are building will only be used by Ada applications
30138 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30139 convention. As an example, the previous package could be written as
30140 follows:
30141
30142 @smallexample @c ada
30143 @group
30144 @cartouche
30145 package API is
30146 Count : Integer := 0;
30147 function Factorial (Val : Integer) return Integer;
30148
30149 procedure Initialize_API;
30150 procedure Finalize_API;
30151 -- Initialization and Finalization routines.
30152 end API;
30153 @end cartouche
30154 @end group
30155 @end smallexample
30156
30157 @smallexample @c ada
30158 @group
30159 @cartouche
30160 package body API is
30161 function Factorial (Val : Integer) return Integer is
30162 Fact : Integer := 1;
30163 begin
30164 Count := Count + 1;
30165 for K in 1 .. Val loop
30166 Fact := Fact * K;
30167 end loop;
30168 return Fact;
30169 end Factorial;
30170
30171 @dots{}
30172 -- The remainder of this package body is unchanged.
30173 end API;
30174 @end cartouche
30175 @end group
30176 @end smallexample
30177
30178 @noindent
30179 Note that if you do not export the Ada entities with a @code{C} or
30180 @code{Stdcall} convention you will have to provide the mangled Ada names
30181 in the definition file of the Ada DLL
30182 (@pxref{Creating the Definition File}).
30183
30184 @node Ada DLLs and Elaboration
30185 @subsection Ada DLLs and Elaboration
30186 @cindex DLLs and elaboration
30187
30188 @noindent
30189 The DLL that you are building contains your Ada code as well as all the
30190 routines in the Ada library that are needed by it. The first thing a
30191 user of your DLL must do is elaborate the Ada code
30192 (@pxref{Elaboration Order Handling in GNAT}).
30193
30194 To achieve this you must export an initialization routine
30195 (@code{Initialize_API} in the previous example), which must be invoked
30196 before using any of the DLL services. This elaboration routine must call
30197 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30198 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30199 @code{Initialize_Api} for an example. Note that the GNAT binder is
30200 automatically invoked during the DLL build process by the @code{gnatdll}
30201 tool (@pxref{Using gnatdll}).
30202
30203 When a DLL is loaded, Windows systematically invokes a routine called
30204 @code{DllMain}. It would therefore be possible to call @code{adainit}
30205 directly from @code{DllMain} without having to provide an explicit
30206 initialization routine. Unfortunately, it is not possible to call
30207 @code{adainit} from the @code{DllMain} if your program has library level
30208 tasks because access to the @code{DllMain} entry point is serialized by
30209 the system (that is, only a single thread can execute ``through'' it at a
30210 time), which means that the GNAT run time will deadlock waiting for the
30211 newly created task to complete its initialization.
30212
30213 @node Ada DLLs and Finalization
30214 @subsection Ada DLLs and Finalization
30215 @cindex DLLs and finalization
30216
30217 @noindent
30218 When the services of an Ada DLL are no longer needed, the client code should
30219 invoke the DLL finalization routine, if available. The DLL finalization
30220 routine is in charge of releasing all resources acquired by the DLL. In the
30221 case of the Ada code contained in the DLL, this is achieved by calling
30222 routine @code{adafinal} generated by the GNAT binder
30223 (@pxref{Binding with Non-Ada Main Programs}).
30224 See the body of @code{Finalize_Api} for an
30225 example. As already pointed out the GNAT binder is automatically invoked
30226 during the DLL build process by the @code{gnatdll} tool
30227 (@pxref{Using gnatdll}).
30228
30229 @node Creating a Spec for Ada DLLs
30230 @subsection Creating a Spec for Ada DLLs
30231
30232 @noindent
30233 To use the services exported by the Ada DLL from another programming
30234 language (e.g.@: C), you have to translate the specs of the exported Ada
30235 entities in that language. For instance in the case of @code{API.dll},
30236 the corresponding C header file could look like:
30237
30238 @smallexample
30239 @group
30240 @cartouche
30241 extern int *_imp__count;
30242 #define count (*_imp__count)
30243 int factorial (int);
30244 @end cartouche
30245 @end group
30246 @end smallexample
30247
30248 @noindent
30249 It is important to understand that when building an Ada DLL to be used by
30250 other Ada applications, you need two different specs for the packages
30251 contained in the DLL: one for building the DLL and the other for using
30252 the DLL. This is because the @code{DLL} calling convention is needed to
30253 use a variable defined in a DLL, but when building the DLL, the variable
30254 must have either the @code{Ada} or @code{C} calling convention. As an
30255 example consider a DLL comprising the following package @code{API}:
30256
30257 @smallexample @c ada
30258 @group
30259 @cartouche
30260 package API is
30261 Count : Integer := 0;
30262 @dots{}
30263 -- Remainder of the package omitted.
30264 end API;
30265 @end cartouche
30266 @end group
30267 @end smallexample
30268
30269 @noindent
30270 After producing a DLL containing package @code{API}, the spec that
30271 must be used to import @code{API.Count} from Ada code outside of the
30272 DLL is:
30273
30274 @smallexample @c ada
30275 @group
30276 @cartouche
30277 package API is
30278 Count : Integer;
30279 pragma Import (DLL, Count);
30280 end API;
30281 @end cartouche
30282 @end group
30283 @end smallexample
30284
30285 @node Creating the Definition File
30286 @subsection Creating the Definition File
30287
30288 @noindent
30289 The definition file is the last file needed to build the DLL. It lists
30290 the exported symbols. As an example, the definition file for a DLL
30291 containing only package @code{API} (where all the entities are exported
30292 with a @code{C} calling convention) is:
30293
30294 @smallexample
30295 @group
30296 @cartouche
30297 EXPORTS
30298 count
30299 factorial
30300 finalize_api
30301 initialize_api
30302 @end cartouche
30303 @end group
30304 @end smallexample
30305
30306 @noindent
30307 If the @code{C} calling convention is missing from package @code{API},
30308 then the definition file contains the mangled Ada names of the above
30309 entities, which in this case are:
30310
30311 @smallexample
30312 @group
30313 @cartouche
30314 EXPORTS
30315 api__count
30316 api__factorial
30317 api__finalize_api
30318 api__initialize_api
30319 @end cartouche
30320 @end group
30321 @end smallexample
30322
30323 @node Using gnatdll
30324 @subsection Using @code{gnatdll}
30325 @findex gnatdll
30326
30327 @menu
30328 * gnatdll Example::
30329 * gnatdll behind the Scenes::
30330 * Using dlltool::
30331 @end menu
30332
30333 @noindent
30334 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30335 and non-Ada sources that make up your DLL have been compiled.
30336 @code{gnatdll} is actually in charge of two distinct tasks: build the
30337 static import library for the DLL and the actual DLL. The form of the
30338 @code{gnatdll} command is
30339
30340 @smallexample
30341 @cartouche
30342 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30343 @c Expanding @ovar macro inline (explanation in macro def comments)
30344 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30345 @end cartouche
30346 @end smallexample
30347
30348 @noindent
30349 where @var{list-of-files} is a list of ALI and object files. The object
30350 file list must be the exact list of objects corresponding to the non-Ada
30351 sources whose services are to be included in the DLL. The ALI file list
30352 must be the exact list of ALI files for the corresponding Ada sources
30353 whose services are to be included in the DLL. If @var{list-of-files} is
30354 missing, only the static import library is generated.
30355
30356 @noindent
30357 You may specify any of the following switches to @code{gnatdll}:
30358
30359 @table @code
30360 @c @item -a@ovar{address}
30361 @c Expanding @ovar macro inline (explanation in macro def comments)
30362 @item -a@r{[}@var{address}@r{]}
30363 @cindex @option{-a} (@code{gnatdll})
30364 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30365 specified the default address @var{0x11000000} will be used. By default,
30366 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30367 advise the reader to build relocatable DLL.
30368
30369 @item -b @var{address}
30370 @cindex @option{-b} (@code{gnatdll})
30371 Set the relocatable DLL base address. By default the address is
30372 @code{0x11000000}.
30373
30374 @item -bargs @var{opts}
30375 @cindex @option{-bargs} (@code{gnatdll})
30376 Binder options. Pass @var{opts} to the binder.
30377
30378 @item -d @var{dllfile}
30379 @cindex @option{-d} (@code{gnatdll})
30380 @var{dllfile} is the name of the DLL. This switch must be present for
30381 @code{gnatdll} to do anything. The name of the generated import library is
30382 obtained algorithmically from @var{dllfile} as shown in the following
30383 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30384 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30385 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30386 as shown in the following example:
30387 if @var{dllfile} is @code{xyz.dll}, the definition
30388 file used is @code{xyz.def}.
30389
30390 @item -e @var{deffile}
30391 @cindex @option{-e} (@code{gnatdll})
30392 @var{deffile} is the name of the definition file.
30393
30394 @item -g
30395 @cindex @option{-g} (@code{gnatdll})
30396 Generate debugging information. This information is stored in the object
30397 file and copied from there to the final DLL file by the linker,
30398 where it can be read by the debugger. You must use the
30399 @option{-g} switch if you plan on using the debugger or the symbolic
30400 stack traceback.
30401
30402 @item -h
30403 @cindex @option{-h} (@code{gnatdll})
30404 Help mode. Displays @code{gnatdll} switch usage information.
30405
30406 @item -Idir
30407 @cindex @option{-I} (@code{gnatdll})
30408 Direct @code{gnatdll} to search the @var{dir} directory for source and
30409 object files needed to build the DLL.
30410 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30411
30412 @item -k
30413 @cindex @option{-k} (@code{gnatdll})
30414 Removes the @code{@@}@var{nn} suffix from the import library's exported
30415 names, but keeps them for the link names. You must specify this
30416 option if you want to use a @code{Stdcall} function in a DLL for which
30417 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30418 of the Windows NT DLL for example. This option has no effect when
30419 @option{-n} option is specified.
30420
30421 @item -l @var{file}
30422 @cindex @option{-l} (@code{gnatdll})
30423 The list of ALI and object files used to build the DLL are listed in
30424 @var{file}, instead of being given in the command line. Each line in
30425 @var{file} contains the name of an ALI or object file.
30426
30427 @item -n
30428 @cindex @option{-n} (@code{gnatdll})
30429 No Import. Do not create the import library.
30430
30431 @item -q
30432 @cindex @option{-q} (@code{gnatdll})
30433 Quiet mode. Do not display unnecessary messages.
30434
30435 @item -v
30436 @cindex @option{-v} (@code{gnatdll})
30437 Verbose mode. Display extra information.
30438
30439 @item -largs @var{opts}
30440 @cindex @option{-largs} (@code{gnatdll})
30441 Linker options. Pass @var{opts} to the linker.
30442 @end table
30443
30444 @node gnatdll Example
30445 @subsubsection @code{gnatdll} Example
30446
30447 @noindent
30448 As an example the command to build a relocatable DLL from @file{api.adb}
30449 once @file{api.adb} has been compiled and @file{api.def} created is
30450
30451 @smallexample
30452 $ gnatdll -d api.dll api.ali
30453 @end smallexample
30454
30455 @noindent
30456 The above command creates two files: @file{libapi.dll.a} (the import
30457 library) and @file{api.dll} (the actual DLL). If you want to create
30458 only the DLL, just type:
30459
30460 @smallexample
30461 $ gnatdll -d api.dll -n api.ali
30462 @end smallexample
30463
30464 @noindent
30465 Alternatively if you want to create just the import library, type:
30466
30467 @smallexample
30468 $ gnatdll -d api.dll
30469 @end smallexample
30470
30471 @node gnatdll behind the Scenes
30472 @subsubsection @code{gnatdll} behind the Scenes
30473
30474 @noindent
30475 This section details the steps involved in creating a DLL. @code{gnatdll}
30476 does these steps for you. Unless you are interested in understanding what
30477 goes on behind the scenes, you should skip this section.
30478
30479 We use the previous example of a DLL containing the Ada package @code{API},
30480 to illustrate the steps necessary to build a DLL. The starting point is a
30481 set of objects that will make up the DLL and the corresponding ALI
30482 files. In the case of this example this means that @file{api.o} and
30483 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30484 the following:
30485
30486 @enumerate
30487 @item
30488 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30489 the information necessary to generate relocation information for the
30490 DLL.
30491
30492 @smallexample
30493 @group
30494 $ gnatbind -n api
30495 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30496 @end group
30497 @end smallexample
30498
30499 @noindent
30500 In addition to the base file, the @command{gnatlink} command generates an
30501 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30502 asks @command{gnatlink} to generate the routines @code{DllMain} and
30503 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30504 is loaded into memory.
30505
30506 @item
30507 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30508 export table (@file{api.exp}). The export table contains the relocation
30509 information in a form which can be used during the final link to ensure
30510 that the Windows loader is able to place the DLL anywhere in memory.
30511
30512 @smallexample
30513 @group
30514 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30515 --output-exp api.exp
30516 @end group
30517 @end smallexample
30518
30519 @item
30520 @code{gnatdll} builds the base file using the new export table. Note that
30521 @command{gnatbind} must be called once again since the binder generated file
30522 has been deleted during the previous call to @command{gnatlink}.
30523
30524 @smallexample
30525 @group
30526 $ gnatbind -n api
30527 $ gnatlink api -o api.jnk api.exp -mdll
30528 -Wl,--base-file,api.base
30529 @end group
30530 @end smallexample
30531
30532 @item
30533 @code{gnatdll} builds the new export table using the new base file and
30534 generates the DLL import library @file{libAPI.dll.a}.
30535
30536 @smallexample
30537 @group
30538 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30539 --output-exp api.exp --output-lib libAPI.a
30540 @end group
30541 @end smallexample
30542
30543 @item
30544 Finally @code{gnatdll} builds the relocatable DLL using the final export
30545 table.
30546
30547 @smallexample
30548 @group
30549 $ gnatbind -n api
30550 $ gnatlink api api.exp -o api.dll -mdll
30551 @end group
30552 @end smallexample
30553 @end enumerate
30554
30555 @node Using dlltool
30556 @subsubsection Using @code{dlltool}
30557
30558 @noindent
30559 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30560 DLLs and static import libraries. This section summarizes the most
30561 common @code{dlltool} switches. The form of the @code{dlltool} command
30562 is
30563
30564 @smallexample
30565 @c $ dlltool @ovar{switches}
30566 @c Expanding @ovar macro inline (explanation in macro def comments)
30567 $ dlltool @r{[}@var{switches}@r{]}
30568 @end smallexample
30569
30570 @noindent
30571 @code{dlltool} switches include:
30572
30573 @table @option
30574 @item --base-file @var{basefile}
30575 @cindex @option{--base-file} (@command{dlltool})
30576 Read the base file @var{basefile} generated by the linker. This switch
30577 is used to create a relocatable DLL.
30578
30579 @item --def @var{deffile}
30580 @cindex @option{--def} (@command{dlltool})
30581 Read the definition file.
30582
30583 @item --dllname @var{name}
30584 @cindex @option{--dllname} (@command{dlltool})
30585 Gives the name of the DLL. This switch is used to embed the name of the
30586 DLL in the static import library generated by @code{dlltool} with switch
30587 @option{--output-lib}.
30588
30589 @item -k
30590 @cindex @option{-k} (@command{dlltool})
30591 Kill @code{@@}@var{nn} from exported names
30592 (@pxref{Windows Calling Conventions}
30593 for a discussion about @code{Stdcall}-style symbols.
30594
30595 @item --help
30596 @cindex @option{--help} (@command{dlltool})
30597 Prints the @code{dlltool} switches with a concise description.
30598
30599 @item --output-exp @var{exportfile}
30600 @cindex @option{--output-exp} (@command{dlltool})
30601 Generate an export file @var{exportfile}. The export file contains the
30602 export table (list of symbols in the DLL) and is used to create the DLL.
30603
30604 @item --output-lib @var{libfile}
30605 @cindex @option{--output-lib} (@command{dlltool})
30606 Generate a static import library @var{libfile}.
30607
30608 @item -v
30609 @cindex @option{-v} (@command{dlltool})
30610 Verbose mode.
30611
30612 @item --as @var{assembler-name}
30613 @cindex @option{--as} (@command{dlltool})
30614 Use @var{assembler-name} as the assembler. The default is @code{as}.
30615 @end table
30616
30617 @node GNAT and Windows Resources
30618 @section GNAT and Windows Resources
30619 @cindex Resources, windows
30620
30621 @menu
30622 * Building Resources::
30623 * Compiling Resources::
30624 * Using Resources::
30625 @end menu
30626
30627 @noindent
30628 Resources are an easy way to add Windows specific objects to your
30629 application. The objects that can be added as resources include:
30630
30631 @itemize @bullet
30632 @item menus
30633
30634 @item accelerators
30635
30636 @item dialog boxes
30637
30638 @item string tables
30639
30640 @item bitmaps
30641
30642 @item cursors
30643
30644 @item icons
30645
30646 @item fonts
30647
30648 @item version information
30649 @end itemize
30650
30651 For example, a version information resource can be defined as follow and
30652 embedded into an executable or DLL:
30653
30654 A version information resource can be used to embed information into an
30655 executable or a DLL. These information can be viewed using the file properties
30656 from the Windows Explorer. Here is an example of a version information
30657 resource:
30658
30659 @smallexample
30660 @group
30661 1 VERSIONINFO
30662 FILEVERSION 1,0,0,0
30663 PRODUCTVERSION 1,0,0,0
30664 BEGIN
30665 BLOCK "StringFileInfo"
30666 BEGIN
30667 BLOCK "080904E4"
30668 BEGIN
30669 VALUE "CompanyName", "My Company Name"
30670 VALUE "FileDescription", "My application"
30671 VALUE "FileVersion", "1.0"
30672 VALUE "InternalName", "my_app"
30673 VALUE "LegalCopyright", "My Name"
30674 VALUE "OriginalFilename", "my_app.exe"
30675 VALUE "ProductName", "My App"
30676 VALUE "ProductVersion", "1.0"
30677 END
30678 END
30679
30680 BLOCK "VarFileInfo"
30681 BEGIN
30682 VALUE "Translation", 0x809, 1252
30683 END
30684 END
30685 @end group
30686 @end smallexample
30687
30688 The value @code{0809} (langID) is for the U.K English language and
30689 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30690 multilingual.
30691
30692 @noindent
30693 This section explains how to build, compile and use resources. Note that this
30694 section does not cover all resource objects, for a complete description see
30695 the corresponding Microsoft documentation.
30696
30697 @node Building Resources
30698 @subsection Building Resources
30699 @cindex Resources, building
30700
30701 @noindent
30702 A resource file is an ASCII file. By convention resource files have an
30703 @file{.rc} extension.
30704 The easiest way to build a resource file is to use Microsoft tools
30705 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30706 @code{dlgedit.exe} to build dialogs.
30707 It is always possible to build an @file{.rc} file yourself by writing a
30708 resource script.
30709
30710 It is not our objective to explain how to write a resource file. A
30711 complete description of the resource script language can be found in the
30712 Microsoft documentation.
30713
30714 @node Compiling Resources
30715 @subsection Compiling Resources
30716 @findex rc
30717 @findex windres
30718 @cindex Resources, compiling
30719
30720 @noindent
30721 This section describes how to build a GNAT-compatible (COFF) object file
30722 containing the resources. This is done using the Resource Compiler
30723 @code{windres} as follows:
30724
30725 @smallexample
30726 $ windres -i myres.rc -o myres.o
30727 @end smallexample
30728
30729 @noindent
30730 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
30731 file. You can specify an alternate preprocessor (usually named
30732 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
30733 parameter. A list of all possible options may be obtained by entering
30734 the command @code{windres} @option{--help}.
30735
30736 It is also possible to use the Microsoft resource compiler @code{rc.exe}
30737 to produce a @file{.res} file (binary resource file). See the
30738 corresponding Microsoft documentation for further details. In this case
30739 you need to use @code{windres} to translate the @file{.res} file to a
30740 GNAT-compatible object file as follows:
30741
30742 @smallexample
30743 $ windres -i myres.res -o myres.o
30744 @end smallexample
30745
30746 @node Using Resources
30747 @subsection Using Resources
30748 @cindex Resources, using
30749
30750 @noindent
30751 To include the resource file in your program just add the
30752 GNAT-compatible object file for the resource(s) to the linker
30753 arguments. With @command{gnatmake} this is done by using the @option{-largs}
30754 option:
30755
30756 @smallexample
30757 $ gnatmake myprog -largs myres.o
30758 @end smallexample
30759
30760 @node Debugging a DLL
30761 @section Debugging a DLL
30762 @cindex DLL debugging
30763
30764 @menu
30765 * Program and DLL Both Built with GCC/GNAT::
30766 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
30767 @end menu
30768
30769 @noindent
30770 Debugging a DLL is similar to debugging a standard program. But
30771 we have to deal with two different executable parts: the DLL and the
30772 program that uses it. We have the following four possibilities:
30773
30774 @enumerate 1
30775 @item
30776 The program and the DLL are built with @code{GCC/GNAT}.
30777 @item
30778 The program is built with foreign tools and the DLL is built with
30779 @code{GCC/GNAT}.
30780 @item
30781 The program is built with @code{GCC/GNAT} and the DLL is built with
30782 foreign tools.
30783 @end enumerate
30784
30785 @noindent
30786 In this section we address only cases one and two above.
30787 There is no point in trying to debug
30788 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
30789 information in it. To do so you must use a debugger compatible with the
30790 tools suite used to build the DLL.
30791
30792 @node Program and DLL Both Built with GCC/GNAT
30793 @subsection Program and DLL Both Built with GCC/GNAT
30794
30795 @noindent
30796 This is the simplest case. Both the DLL and the program have @code{GDB}
30797 compatible debugging information. It is then possible to break anywhere in
30798 the process. Let's suppose here that the main procedure is named
30799 @code{ada_main} and that in the DLL there is an entry point named
30800 @code{ada_dll}.
30801
30802 @noindent
30803 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
30804 program must have been built with the debugging information (see GNAT -g
30805 switch). Here are the step-by-step instructions for debugging it:
30806
30807 @enumerate 1
30808 @item Launch @code{GDB} on the main program.
30809
30810 @smallexample
30811 $ gdb -nw ada_main
30812 @end smallexample
30813
30814 @item Start the program and stop at the beginning of the main procedure
30815
30816 @smallexample
30817 (gdb) start
30818 @end smallexample
30819
30820 @noindent
30821 This step is required to be able to set a breakpoint inside the DLL. As long
30822 as the program is not run, the DLL is not loaded. This has the
30823 consequence that the DLL debugging information is also not loaded, so it is not
30824 possible to set a breakpoint in the DLL.
30825
30826 @item Set a breakpoint inside the DLL
30827
30828 @smallexample
30829 (gdb) break ada_dll
30830 (gdb) cont
30831 @end smallexample
30832
30833 @end enumerate
30834
30835 @noindent
30836 At this stage a breakpoint is set inside the DLL. From there on
30837 you can use the standard approach to debug the whole program
30838 (@pxref{Running and Debugging Ada Programs}).
30839
30840 @ignore
30841 @c This used to work, probably because the DLLs were non-relocatable
30842 @c keep this section around until the problem is sorted out.
30843
30844 To break on the @code{DllMain} routine it is not possible to follow
30845 the procedure above. At the time the program stop on @code{ada_main}
30846 the @code{DllMain} routine as already been called. Either you can use
30847 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
30848
30849 @enumerate 1
30850 @item Launch @code{GDB} on the main program.
30851
30852 @smallexample
30853 $ gdb ada_main
30854 @end smallexample
30855
30856 @item Load DLL symbols
30857
30858 @smallexample
30859 (gdb) add-sym api.dll
30860 @end smallexample
30861
30862 @item Set a breakpoint inside the DLL
30863
30864 @smallexample
30865 (gdb) break ada_dll.adb:45
30866 @end smallexample
30867
30868 Note that at this point it is not possible to break using the routine symbol
30869 directly as the program is not yet running. The solution is to break
30870 on the proper line (break in @file{ada_dll.adb} line 45).
30871
30872 @item Start the program
30873
30874 @smallexample
30875 (gdb) run
30876 @end smallexample
30877
30878 @end enumerate
30879 @end ignore
30880
30881 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30882 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30883
30884 @menu
30885 * Debugging the DLL Directly::
30886 * Attaching to a Running Process::
30887 @end menu
30888
30889 @noindent
30890 In this case things are slightly more complex because it is not possible to
30891 start the main program and then break at the beginning to load the DLL and the
30892 associated DLL debugging information. It is not possible to break at the
30893 beginning of the program because there is no @code{GDB} debugging information,
30894 and therefore there is no direct way of getting initial control. This
30895 section addresses this issue by describing some methods that can be used
30896 to break somewhere in the DLL to debug it.
30897
30898 @noindent
30899 First suppose that the main procedure is named @code{main} (this is for
30900 example some C code built with Microsoft Visual C) and that there is a
30901 DLL named @code{test.dll} containing an Ada entry point named
30902 @code{ada_dll}.
30903
30904 @noindent
30905 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30906 been built with debugging information (see GNAT -g option).
30907
30908 @node Debugging the DLL Directly
30909 @subsubsection Debugging the DLL Directly
30910
30911 @enumerate 1
30912 @item
30913 Find out the executable starting address
30914
30915 @smallexample
30916 $ objdump --file-header main.exe
30917 @end smallexample
30918
30919 The starting address is reported on the last line. For example:
30920
30921 @smallexample
30922 main.exe: file format pei-i386
30923 architecture: i386, flags 0x0000010a:
30924 EXEC_P, HAS_DEBUG, D_PAGED
30925 start address 0x00401010
30926 @end smallexample
30927
30928 @item
30929 Launch the debugger on the executable.
30930
30931 @smallexample
30932 $ gdb main.exe
30933 @end smallexample
30934
30935 @item
30936 Set a breakpoint at the starting address, and launch the program.
30937
30938 @smallexample
30939 $ (gdb) break *0x00401010
30940 $ (gdb) run
30941 @end smallexample
30942
30943 The program will stop at the given address.
30944
30945 @item
30946 Set a breakpoint on a DLL subroutine.
30947
30948 @smallexample
30949 (gdb) break ada_dll.adb:45
30950 @end smallexample
30951
30952 Or if you want to break using a symbol on the DLL, you need first to
30953 select the Ada language (language used by the DLL).
30954
30955 @smallexample
30956 (gdb) set language ada
30957 (gdb) break ada_dll
30958 @end smallexample
30959
30960 @item
30961 Continue the program.
30962
30963 @smallexample
30964 (gdb) cont
30965 @end smallexample
30966
30967 @noindent
30968 This will run the program until it reaches the breakpoint that has been
30969 set. From that point you can use the standard way to debug a program
30970 as described in (@pxref{Running and Debugging Ada Programs}).
30971
30972 @end enumerate
30973
30974 @noindent
30975 It is also possible to debug the DLL by attaching to a running process.
30976
30977 @node Attaching to a Running Process
30978 @subsubsection Attaching to a Running Process
30979 @cindex DLL debugging, attach to process
30980
30981 @noindent
30982 With @code{GDB} it is always possible to debug a running process by
30983 attaching to it. It is possible to debug a DLL this way. The limitation
30984 of this approach is that the DLL must run long enough to perform the
30985 attach operation. It may be useful for instance to insert a time wasting
30986 loop in the code of the DLL to meet this criterion.
30987
30988 @enumerate 1
30989
30990 @item Launch the main program @file{main.exe}.
30991
30992 @smallexample
30993 $ main
30994 @end smallexample
30995
30996 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30997 that the process PID for @file{main.exe} is 208.
30998
30999 @item Launch gdb.
31000
31001 @smallexample
31002 $ gdb
31003 @end smallexample
31004
31005 @item Attach to the running process to be debugged.
31006
31007 @smallexample
31008 (gdb) attach 208
31009 @end smallexample
31010
31011 @item Load the process debugging information.
31012
31013 @smallexample
31014 (gdb) symbol-file main.exe
31015 @end smallexample
31016
31017 @item Break somewhere in the DLL.
31018
31019 @smallexample
31020 (gdb) break ada_dll
31021 @end smallexample
31022
31023 @item Continue process execution.
31024
31025 @smallexample
31026 (gdb) cont
31027 @end smallexample
31028
31029 @end enumerate
31030
31031 @noindent
31032 This last step will resume the process execution, and stop at
31033 the breakpoint we have set. From there you can use the standard
31034 approach to debug a program as described in
31035 (@pxref{Running and Debugging Ada Programs}).
31036
31037 @node Setting Stack Size from gnatlink
31038 @section Setting Stack Size from @command{gnatlink}
31039
31040 @noindent
31041 It is possible to specify the program stack size at link time. On modern
31042 versions of Windows, starting with XP, this is mostly useful to set the size of
31043 the main stack (environment task). The other task stacks are set with pragma
31044 Storage_Size or with the @command{gnatbind -d} command.
31045
31046 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31047 reserve size of individual tasks, the link-time stack size applies to all
31048 tasks, and pragma Storage_Size has no effect.
31049 In particular, Stack Overflow checks are made against this
31050 link-time specified size.
31051
31052 This setting can be done with
31053 @command{gnatlink} using either:
31054
31055 @itemize @bullet
31056
31057 @item using @option{-Xlinker} linker option
31058
31059 @smallexample
31060 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31061 @end smallexample
31062
31063 This sets the stack reserve size to 0x10000 bytes and the stack commit
31064 size to 0x1000 bytes.
31065
31066 @item using @option{-Wl} linker option
31067
31068 @smallexample
31069 $ gnatlink hello -Wl,--stack=0x1000000
31070 @end smallexample
31071
31072 This sets the stack reserve size to 0x1000000 bytes. Note that with
31073 @option{-Wl} option it is not possible to set the stack commit size
31074 because the coma is a separator for this option.
31075
31076 @end itemize
31077
31078 @node Setting Heap Size from gnatlink
31079 @section Setting Heap Size from @command{gnatlink}
31080
31081 @noindent
31082 Under Windows systems, it is possible to specify the program heap size from
31083 @command{gnatlink} using either:
31084
31085 @itemize @bullet
31086
31087 @item using @option{-Xlinker} linker option
31088
31089 @smallexample
31090 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31091 @end smallexample
31092
31093 This sets the heap reserve size to 0x10000 bytes and the heap commit
31094 size to 0x1000 bytes.
31095
31096 @item using @option{-Wl} linker option
31097
31098 @smallexample
31099 $ gnatlink hello -Wl,--heap=0x1000000
31100 @end smallexample
31101
31102 This sets the heap reserve size to 0x1000000 bytes. Note that with
31103 @option{-Wl} option it is not possible to set the heap commit size
31104 because the coma is a separator for this option.
31105
31106 @end itemize
31107
31108 @node Mac OS Topics
31109 @appendix Mac OS Topics
31110 @cindex OS X
31111
31112 @noindent
31113 This chapter describes topics that are specific to Apple's OS X
31114 platform.
31115
31116 @menu
31117 * Codesigning the Debugger::
31118 @end menu
31119
31120 @node Codesigning the Debugger
31121 @section Codesigning the Debugger
31122
31123 @noindent
31124 The Darwin Kernel requires the debugger to have special permissions
31125 before it is allowed to control other processes. These permissions
31126 are granted by codesigning the GDB executable. Without these
31127 permissions, the debugger will report error messages such as:
31128
31129 @smallexample
31130 Starting program: /x/y/foo
31131 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31132 (please check gdb is codesigned - see taskgated(8))
31133 @end smallexample
31134
31135 Codesigning requires a certificate. The following procedure explains
31136 how to create one:
31137
31138 @itemize @bullet
31139 @item Start the Keychain Access application (in
31140 /Applications/Utilities/Keychain Access.app)
31141
31142 @item Select the Keychain Access -> Certificate Assistant ->
31143 Create a Certificate... menu
31144
31145 @item Then:
31146
31147 @itemize @bullet
31148 @item Choose a name for the new certificate (this procedure will use
31149 "gdb-cert" as an example)
31150
31151 @item Set "Identity Type" to "Self Signed Root"
31152
31153 @item Set "Certificate Type" to "Code Signing"
31154
31155 @item Activate the "Let me override defaults" option
31156
31157 @end itemize
31158
31159 @item Click several times on "Continue" until the "Specify a Location
31160 For The Certificate" screen appears, then set "Keychain" to "System"
31161
31162 @item Click on "Continue" until the certificate is created
31163
31164 @item Finally, in the view, double-click on the new certificate,
31165 and set "When using this certificate" to "Always Trust"
31166
31167 @item Exit the Keychain Access application and restart the computer
31168 (this is unfortunately required)
31169
31170 @end itemize
31171
31172 Once a certificate has been created, the debugger can be codesigned
31173 as follow. In a Terminal, run the following command...
31174
31175 @smallexample
31176 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31177 @end smallexample
31178
31179 ... where "gdb-cert" should be replaced by the actual certificate
31180 name chosen above, and <gnat_install_prefix> should be replaced by
31181 the location where you installed GNAT.
31182
31183 @c **********************************
31184 @c * GNU Free Documentation License *
31185 @c **********************************
31186 @include fdl.texi
31187 @c GNU Free Documentation License
31188
31189 @node Index,,GNU Free Documentation License, Top
31190 @unnumbered Index
31191
31192 @printindex cp
31193
31194 @contents
31195 @c Put table of contents at end, otherwise it precedes the "title page" in
31196 @c the .txt version
31197 @c Edit the pdf file to move the contents to the beginning, after the title
31198 @c page
31199
31200 @bye