]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/ada/gnat_ugn.texi
[multiple changes]
[thirdparty/gcc.git] / gcc / ada / gnat_ugn.texi
1 f\input texinfo @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c o
6 @c GNAT DOCUMENTATION o
7 @c o
8 @c G N A T _ U G N o
9 @c o
10 @c GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). o
11 @c o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c GNAT_UGN Style Guide
31 @c
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
34 @c
35 @c @chapter
36 @c @section
37 @c @subsection
38 @c @subsubsection
39 @c @subsubsubsection
40 @c
41 @c @end smallexample
42 @c @end itemize
43 @c @end enumerate
44 @c
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
60 @c
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
63 @c
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
66 @c
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c or "ali".
69 @c
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
72 @c
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
76 @c
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
79 @c Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211 --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Rule exemption::
494 * Predefined Rules::
495
496 Sample Bodies Using gnatstub
497
498 * Running gnatstub::
499 * Switches for gnatstub::
500
501 Other Utility Programs
502
503 * Using Other Utility Programs with GNAT::
504 * The External Symbol Naming Scheme of GNAT::
505 * Converting Ada Files to html with gnathtml::
506
507 @ifclear vms
508 Code Coverage and Profiling
509
510 * Code Coverage of Ada Programs using gcov::
511 * Profiling an Ada Program using gprof::
512 @end ifclear
513
514 Running and Debugging Ada Programs
515
516 * The GNAT Debugger GDB::
517 * Running GDB::
518 * Introduction to GDB Commands::
519 * Using Ada Expressions::
520 * Calling User-Defined Subprograms::
521 * Using the Next Command in a Function::
522 * Ada Exceptions::
523 * Ada Tasks::
524 * Debugging Generic Units::
525 * GNAT Abnormal Termination or Failure to Terminate::
526 * Naming Conventions for GNAT Source Files::
527 * Getting Internal Debugging Information::
528 * Stack Traceback::
529
530 @ifset vms
531 * LSE::
532 @end ifset
533
534 @ifset vms
535 Compatibility with HP Ada
536
537 * Ada Language Compatibility::
538 * Differences in the Definition of Package System::
539 * Language-Related Features::
540 * The Package STANDARD::
541 * The Package SYSTEM::
542 * Tasking and Task-Related Features::
543 * Pragmas and Pragma-Related Features::
544 * Library of Predefined Units::
545 * Bindings::
546 * Main Program Definition::
547 * Implementation-Defined Attributes::
548 * Compiler and Run-Time Interfacing::
549 * Program Compilation and Library Management::
550 * Input-Output::
551 * Implementation Limits::
552 * Tools and Utilities::
553
554 Language-Related Features
555
556 * Integer Types and Representations::
557 * Floating-Point Types and Representations::
558 * Pragmas Float_Representation and Long_Float::
559 * Fixed-Point Types and Representations::
560 * Record and Array Component Alignment::
561 * Address Clauses::
562 * Other Representation Clauses::
563
564 Tasking and Task-Related Features
565
566 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
567 * Assigning Task IDs::
568 * Task IDs and Delays::
569 * Task-Related Pragmas::
570 * Scheduling and Task Priority::
571 * The Task Stack::
572 * External Interrupts::
573
574 Pragmas and Pragma-Related Features
575
576 * Restrictions on the Pragma INLINE::
577 * Restrictions on the Pragma INTERFACE::
578 * Restrictions on the Pragma SYSTEM_NAME::
579
580 Library of Predefined Units
581
582 * Changes to DECLIB::
583
584 Bindings
585
586 * Shared Libraries and Options Files::
587 * Interfaces to C::
588 @end ifset
589
590 Platform-Specific Information for the Run-Time Libraries
591
592 * Summary of Run-Time Configurations::
593 * Specifying a Run-Time Library::
594 * Choosing the Scheduling Policy::
595 * Solaris-Specific Considerations::
596 * Linux-Specific Considerations::
597 * AIX-Specific Considerations::
598 * Irix-Specific Considerations::
599
600 Example of Binder Output File
601
602 Elaboration Order Handling in GNAT
603
604 * Elaboration Code::
605 * Checking the Elaboration Order::
606 * Controlling the Elaboration Order::
607 * Controlling Elaboration in GNAT - Internal Calls::
608 * Controlling Elaboration in GNAT - External Calls::
609 * Default Behavior in GNAT - Ensuring Safety::
610 * Treatment of Pragma Elaborate::
611 * Elaboration Issues for Library Tasks::
612 * Mixing Elaboration Models::
613 * What to Do If the Default Elaboration Behavior Fails::
614 * Elaboration for Access-to-Subprogram Values::
615 * Summary of Procedures for Elaboration Control::
616 * Other Elaboration Order Considerations::
617
618 Conditional Compilation
619 * Use of Boolean Constants::
620 * Debugging - A Special Case::
621 * Conditionalizing Declarations::
622 * Use of Alternative Implementations::
623 * Preprocessing::
624
625 Inline Assembler
626
627 * Basic Assembler Syntax::
628 * A Simple Example of Inline Assembler::
629 * Output Variables in Inline Assembler::
630 * Input Variables in Inline Assembler::
631 * Inlining Inline Assembler Code::
632 * Other Asm Functionality::
633
634 Compatibility and Porting Guide
635
636 * Compatibility with Ada 83::
637 * Compatibility between Ada 95 and Ada 2005::
638 * Implementation-dependent characteristics::
639 @ifclear vms
640 @c This brief section is only in the non-VMS version
641 @c The complete chapter on HP Ada issues is in the VMS version
642 * Compatibility with HP Ada 83::
643 @end ifclear
644 * Compatibility with Other Ada Systems::
645 * Representation Clauses::
646 @ifset vms
647 * Transitioning to 64-Bit GNAT for OpenVMS::
648 @end ifset
649
650 @ifset unw
651 Microsoft Windows Topics
652
653 * Using GNAT on Windows::
654 * CONSOLE and WINDOWS subsystems::
655 * Temporary Files::
656 * Mixed-Language Programming on Windows::
657 * Windows Calling Conventions::
658 * Introduction to Dynamic Link Libraries (DLLs)::
659 * Using DLLs with GNAT::
660 * Building DLLs with GNAT::
661 * GNAT and Windows Resources::
662 * Debugging a DLL::
663 * Setting Stack Size from gnatlink::
664 * Setting Heap Size from gnatlink::
665 @end ifset
666
667 * Index::
668 @end menu
669 @end ifnottex
670
671 @node About This Guide
672 @unnumbered About This Guide
673
674 @noindent
675 @ifset vms
676 This guide describes the use of @value{EDITION},
677 a compiler and software development toolset for the full Ada
678 programming language, implemented on OpenVMS for HP's Alpha and
679 Integrity server (I64) platforms.
680 @end ifset
681 @ifclear vms
682 This guide describes the use of @value{EDITION},
683 a compiler and software development
684 toolset for the full Ada programming language.
685 @end ifclear
686 It documents the features of the compiler and tools, and explains
687 how to use them to build Ada applications.
688
689 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
690 Ada 83 compatibility mode.
691 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
692 but you can override with a compiler switch
693 (@pxref{Compiling Different Versions of Ada})
694 to explicitly specify the language version.
695 Throughout this manual, references to ``Ada'' without a year suffix
696 apply to both the Ada 95 and Ada 2005 versions of the language.
697
698
699 @ifclear FSFEDITION
700 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
701 ``GNAT'' in the remainder of this document.
702 @end ifclear
703
704
705
706
707 @menu
708 * What This Guide Contains::
709 * What You Should Know before Reading This Guide::
710 * Related Information::
711 * Conventions::
712 @end menu
713
714 @node What This Guide Contains
715 @unnumberedsec What This Guide Contains
716
717 @noindent
718 This guide contains the following chapters:
719 @itemize @bullet
720
721 @item
722 @ref{Getting Started with GNAT}, describes how to get started compiling
723 and running Ada programs with the GNAT Ada programming environment.
724 @item
725 @ref{The GNAT Compilation Model}, describes the compilation model used
726 by GNAT.
727
728 @item
729 @ref{Compiling Using gcc}, describes how to compile
730 Ada programs with @command{gcc}, the Ada compiler.
731
732 @item
733 @ref{Binding Using gnatbind}, describes how to
734 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
735 utility.
736
737 @item
738 @ref{Linking Using gnatlink},
739 describes @command{gnatlink}, a
740 program that provides for linking using the GNAT run-time library to
741 construct a program. @command{gnatlink} can also incorporate foreign language
742 object units into the executable.
743
744 @item
745 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
746 utility that automatically determines the set of sources
747 needed by an Ada compilation unit, and executes the necessary compilations
748 binding and link.
749
750 @item
751 @ref{Improving Performance}, shows various techniques for making your
752 Ada program run faster or take less space.
753 It discusses the effect of the compiler's optimization switch and
754 also describes the @command{gnatelim} tool and unused subprogram/data
755 elimination.
756
757 @item
758 @ref{Renaming Files Using gnatchop}, describes
759 @code{gnatchop}, a utility that allows you to preprocess a file that
760 contains Ada source code, and split it into one or more new files, one
761 for each compilation unit.
762
763 @item
764 @ref{Configuration Pragmas}, describes the configuration pragmas
765 handled by GNAT.
766
767 @item
768 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
769 shows how to override the default GNAT file naming conventions,
770 either for an individual unit or globally.
771
772 @item
773 @ref{GNAT Project Manager}, describes how to use project files
774 to organize large projects.
775
776 @item
777 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
778 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
779 way to navigate through sources.
780
781 @item
782 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
783 version of an Ada source file with control over casing, indentation,
784 comment placement, and other elements of program presentation style.
785
786 @item
787 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
788 metrics for an Ada source file, such as the number of types and subprograms,
789 and assorted complexity measures.
790
791 @item
792 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
793 file name krunching utility, used to handle shortened
794 file names on operating systems with a limit on the length of names.
795
796 @item
797 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
798 preprocessor utility that allows a single source file to be used to
799 generate multiple or parameterized source files by means of macro
800 substitution.
801
802 @ifset vms
803 @item
804 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
805 a tool for rebuilding the GNAT run time with user-supplied
806 configuration pragmas.
807 @end ifset
808
809 @item
810 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
811 utility that displays information about compiled units, including dependences
812 on the corresponding sources files, and consistency of compilations.
813
814 @item
815 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
816 to delete files that are produced by the compiler, binder and linker.
817
818 @ifclear vms
819 @item
820 @ref{GNAT and Libraries}, describes the process of creating and using
821 Libraries with GNAT. It also describes how to recompile the GNAT run-time
822 library.
823
824 @item
825 @ref{Using the GNU make Utility}, describes some techniques for using
826 the GNAT toolset in Makefiles.
827 @end ifclear
828
829 @item
830 @ref{Memory Management Issues}, describes some useful predefined storage pools
831 and in particular the GNAT Debug Pool facility, which helps detect incorrect
832 memory references.
833 @ifclear vms
834 It also describes @command{gnatmem}, a utility that monitors dynamic
835 allocation and deallocation and helps detect ``memory leaks''.
836 @end ifclear
837
838 @item
839 @ref{Stack Related Facilities}, describes some useful tools associated with
840 stack checking and analysis.
841
842 @item
843 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
844 a utility that checks Ada code against a set of rules.
845
846 @item
847 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
848 a utility that generates empty but compilable bodies for library units.
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{Conditional Compilation}, describes how to model conditional compilation,
896 both with Ada in general and with GNAT facilities in particular.
897
898 @item
899 @ref{Inline Assembler}, shows how to use the inline assembly facility
900 in an Ada program.
901
902 @item
903 @ref{Compatibility and Porting Guide}, contains sections on compatibility
904 of GNAT with other Ada development environments (including Ada 83 systems),
905 to assist in porting code from those environments.
906
907 @ifset unw
908 @item
909 @ref{Microsoft Windows Topics}, presents information relevant to the
910 Microsoft Windows platform.
911 @end ifset
912 @end itemize
913
914 @c *************************************************
915 @node What You Should Know before Reading This Guide
916 @c *************************************************
917 @unnumberedsec What You Should Know before Reading This Guide
918
919 @cindex Ada 95 Language Reference Manual
920 @cindex Ada 2005 Language Reference Manual
921 @noindent
922 This guide assumes a basic familiarity with the Ada 95 language, as
923 described in the International Standard ANSI/ISO/IEC-8652:1995, January
924 1995.
925 It does not require knowledge of the new features introduced by Ada 2005,
926 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
927 and Amendment 1).
928 Both reference manuals are included in the GNAT documentation
929 package.
930
931 @node Related Information
932 @unnumberedsec Related Information
933
934 @noindent
935 For further information about related tools, refer to the following
936 documents:
937
938 @itemize @bullet
939 @item
940 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
941 Reference Manual}, which contains all reference material for the GNAT
942 implementation of Ada.
943
944 @ifset unw
945 @item
946 @cite{Using the GNAT Programming Studio}, which describes the GPS
947 Integrated Development Environment.
948
949 @item
950 @cite{GNAT Programming Studio Tutorial}, which introduces the
951 main GPS features through examples.
952 @end ifset
953
954 @item
955 @cite{Ada 95 Reference Manual}, which contains reference
956 material for the Ada 95 programming language.
957
958 @item
959 @cite{Ada 2005 Reference Manual}, which contains reference
960 material for the Ada 2005 programming language.
961
962 @item
963 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
964 @ifset vms
965 in the GNU:[DOCS] directory,
966 @end ifset
967 for all details on the use of the GNU source-level debugger.
968
969 @item
970 @xref{Top,, The extensible self-documenting text editor, emacs,
971 GNU Emacs Manual},
972 @ifset vms
973 located in the GNU:[DOCS] directory if the EMACS kit is installed,
974 @end ifset
975 for full information on the extensible editor and programming
976 environment Emacs.
977
978 @end itemize
979
980 @c **************
981 @node Conventions
982 @unnumberedsec Conventions
983 @cindex Conventions
984 @cindex Typographical conventions
985
986 @noindent
987 Following are examples of the typographical and graphic conventions used
988 in this guide:
989
990 @itemize @bullet
991 @item
992 @code{Functions}, @command{utility program names}, @code{standard names},
993 and @code{classes}.
994
995 @item
996 @option{Option flags}
997
998 @item
999 @file{File names}, @samp{button names}, and @samp{field names}.
1000
1001 @item
1002 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1003 variables}.
1004
1005 @item
1006 @emph{Emphasis}.
1007
1008 @item
1009 @r{[}optional information or parameters@r{]}
1010
1011 @item
1012 Examples are described by text
1013 @smallexample
1014 and then shown this way.
1015 @end smallexample
1016 @end itemize
1017
1018 @noindent
1019 Commands that are entered by the user are preceded in this manual by the
1020 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1021 uses this sequence as a prompt, then the commands will appear exactly as
1022 you see them in the manual. If your system uses some other prompt, then
1023 the command will appear with the @code{$} replaced by whatever prompt
1024 character you are using.
1025
1026 @ifset unw
1027 Full file names are shown with the ``@code{/}'' character
1028 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1029 If you are using GNAT on a Windows platform, please note that
1030 the ``@code{\}'' character should be used instead.
1031 @end ifset
1032
1033 @c ****************************
1034 @node Getting Started with GNAT
1035 @chapter Getting Started with GNAT
1036
1037 @noindent
1038 This chapter describes some simple ways of using GNAT to build
1039 executable Ada programs.
1040 @ifset unw
1041 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1042 show how to use the command line environment.
1043 @ref{Introduction to GPS}, provides a brief
1044 introduction to the GNAT Programming Studio, a visually-oriented
1045 Integrated Development Environment for GNAT.
1046 GPS offers a graphical ``look and feel'', support for development in
1047 other programming languages, comprehensive browsing features, and
1048 many other capabilities.
1049 For information on GPS please refer to
1050 @cite{Using the GNAT Programming Studio}.
1051 @end ifset
1052
1053 @menu
1054 * Running GNAT::
1055 * Running a Simple Ada Program::
1056 * Running a Program with Multiple Units::
1057 * Using the gnatmake Utility::
1058 @ifset vms
1059 * Editing with Emacs::
1060 @end ifset
1061 @ifclear vms
1062 * Introduction to GPS::
1063 @end ifclear
1064 @end menu
1065
1066 @node Running GNAT
1067 @section Running GNAT
1068
1069 @noindent
1070 Three steps are needed to create an executable file from an Ada source
1071 file:
1072
1073 @enumerate
1074 @item
1075 The source file(s) must be compiled.
1076 @item
1077 The file(s) must be bound using the GNAT binder.
1078 @item
1079 All appropriate object files must be linked to produce an executable.
1080 @end enumerate
1081
1082 @noindent
1083 All three steps are most commonly handled by using the @command{gnatmake}
1084 utility program that, given the name of the main program, automatically
1085 performs the necessary compilation, binding and linking steps.
1086
1087 @node Running a Simple Ada Program
1088 @section Running a Simple Ada Program
1089
1090 @noindent
1091 Any text editor may be used to prepare an Ada program.
1092 (If @code{Emacs} is
1093 used, the optional Ada mode may be helpful in laying out the program.)
1094 The
1095 program text is a normal text file. We will assume in our initial
1096 example that you have used your editor to prepare the following
1097 standard format text file:
1098
1099 @smallexample @c ada
1100 @cartouche
1101 with Ada.Text_IO; use Ada.Text_IO;
1102 procedure Hello is
1103 begin
1104 Put_Line ("Hello WORLD!");
1105 end Hello;
1106 @end cartouche
1107 @end smallexample
1108
1109 @noindent
1110 This file should be named @file{hello.adb}.
1111 With the normal default file naming conventions, GNAT requires
1112 that each file
1113 contain a single compilation unit whose file name is the
1114 unit name,
1115 with periods replaced by hyphens; the
1116 extension is @file{ads} for a
1117 spec and @file{adb} for a body.
1118 You can override this default file naming convention by use of the
1119 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1120 Alternatively, if you want to rename your files according to this default
1121 convention, which is probably more convenient if you will be using GNAT
1122 for all your compilations, then the @code{gnatchop} utility
1123 can be used to generate correctly-named source files
1124 (@pxref{Renaming Files Using gnatchop}).
1125
1126 You can compile the program using the following command (@code{$} is used
1127 as the command prompt in the examples in this document):
1128
1129 @smallexample
1130 $ gcc -c hello.adb
1131 @end smallexample
1132
1133 @noindent
1134 @command{gcc} is the command used to run the compiler. This compiler is
1135 capable of compiling programs in several languages, including Ada and
1136 C. It assumes that you have given it an Ada program if the file extension is
1137 either @file{.ads} or @file{.adb}, and it will then call
1138 the GNAT compiler to compile the specified file.
1139
1140 @ifclear vms
1141 The @option{-c} switch is required. It tells @command{gcc} to only do a
1142 compilation. (For C programs, @command{gcc} can also do linking, but this
1143 capability is not used directly for Ada programs, so the @option{-c}
1144 switch must always be present.)
1145 @end ifclear
1146
1147 This compile command generates a file
1148 @file{hello.o}, which is the object
1149 file corresponding to your Ada program. It also generates
1150 an ``Ada Library Information'' file @file{hello.ali},
1151 which contains additional information used to check
1152 that an Ada program is consistent.
1153 To build an executable file,
1154 use @code{gnatbind} to bind the program
1155 and @command{gnatlink} to link it. The
1156 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1157 @file{ALI} file, but the default extension of @file{.ali} can
1158 be omitted. This means that in the most common case, the argument
1159 is simply the name of the main program:
1160
1161 @smallexample
1162 $ gnatbind hello
1163 $ gnatlink hello
1164 @end smallexample
1165
1166 @noindent
1167 A simpler method of carrying out these steps is to use
1168 @command{gnatmake},
1169 a master program that invokes all the required
1170 compilation, binding and linking tools in the correct order. In particular,
1171 @command{gnatmake} automatically recompiles any sources that have been
1172 modified since they were last compiled, or sources that depend
1173 on such modified sources, so that ``version skew'' is avoided.
1174 @cindex Version skew (avoided by @command{gnatmake})
1175
1176 @smallexample
1177 $ gnatmake hello.adb
1178 @end smallexample
1179
1180 @noindent
1181 The result is an executable program called @file{hello}, which can be
1182 run by entering:
1183
1184 @smallexample
1185 $ ^hello^RUN HELLO^
1186 @end smallexample
1187
1188 @noindent
1189 assuming that the current directory is on the search path
1190 for executable programs.
1191
1192 @noindent
1193 and, if all has gone well, you will see
1194
1195 @smallexample
1196 Hello WORLD!
1197 @end smallexample
1198
1199 @noindent
1200 appear in response to this command.
1201
1202 @c ****************************************
1203 @node Running a Program with Multiple Units
1204 @section Running a Program with Multiple Units
1205
1206 @noindent
1207 Consider a slightly more complicated example that has three files: a
1208 main program, and the spec and body of a package:
1209
1210 @smallexample @c ada
1211 @cartouche
1212 @group
1213 package Greetings is
1214 procedure Hello;
1215 procedure Goodbye;
1216 end Greetings;
1217
1218 with Ada.Text_IO; use Ada.Text_IO;
1219 package body Greetings is
1220 procedure Hello is
1221 begin
1222 Put_Line ("Hello WORLD!");
1223 end Hello;
1224
1225 procedure Goodbye is
1226 begin
1227 Put_Line ("Goodbye WORLD!");
1228 end Goodbye;
1229 end Greetings;
1230 @end group
1231
1232 @group
1233 with Greetings;
1234 procedure Gmain is
1235 begin
1236 Greetings.Hello;
1237 Greetings.Goodbye;
1238 end Gmain;
1239 @end group
1240 @end cartouche
1241 @end smallexample
1242
1243 @noindent
1244 Following the one-unit-per-file rule, place this program in the
1245 following three separate files:
1246
1247 @table @file
1248 @item greetings.ads
1249 spec of package @code{Greetings}
1250
1251 @item greetings.adb
1252 body of package @code{Greetings}
1253
1254 @item gmain.adb
1255 body of main program
1256 @end table
1257
1258 @noindent
1259 To build an executable version of
1260 this program, we could use four separate steps to compile, bind, and link
1261 the program, as follows:
1262
1263 @smallexample
1264 $ gcc -c gmain.adb
1265 $ gcc -c greetings.adb
1266 $ gnatbind gmain
1267 $ gnatlink gmain
1268 @end smallexample
1269
1270 @noindent
1271 Note that there is no required order of compilation when using GNAT.
1272 In particular it is perfectly fine to compile the main program first.
1273 Also, it is not necessary to compile package specs in the case where
1274 there is an accompanying body; you only need to compile the body. If you want
1275 to submit these files to the compiler for semantic checking and not code
1276 generation, then use the
1277 @option{-gnatc} switch:
1278
1279 @smallexample
1280 $ gcc -c greetings.ads -gnatc
1281 @end smallexample
1282
1283 @noindent
1284 Although the compilation can be done in separate steps as in the
1285 above example, in practice it is almost always more convenient
1286 to use the @command{gnatmake} tool. All you need to know in this case
1287 is the name of the main program's source file. The effect of the above four
1288 commands can be achieved with a single one:
1289
1290 @smallexample
1291 $ gnatmake gmain.adb
1292 @end smallexample
1293
1294 @noindent
1295 In the next section we discuss the advantages of using @command{gnatmake} in
1296 more detail.
1297
1298 @c *****************************
1299 @node Using the gnatmake Utility
1300 @section Using the @command{gnatmake} Utility
1301
1302 @noindent
1303 If you work on a program by compiling single components at a time using
1304 @command{gcc}, you typically keep track of the units you modify. In order to
1305 build a consistent system, you compile not only these units, but also any
1306 units that depend on the units you have modified.
1307 For example, in the preceding case,
1308 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1309 you edit @file{greetings.ads}, you must recompile both
1310 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1311 units that depend on @file{greetings.ads}.
1312
1313 @code{gnatbind} will warn you if you forget one of these compilation
1314 steps, so that it is impossible to generate an inconsistent program as a
1315 result of forgetting to do a compilation. Nevertheless it is tedious and
1316 error-prone to keep track of dependencies among units.
1317 One approach to handle the dependency-bookkeeping is to use a
1318 makefile. However, makefiles present maintenance problems of their own:
1319 if the dependencies change as you change the program, you must make
1320 sure that the makefile is kept up-to-date manually, which is also an
1321 error-prone process.
1322
1323 The @command{gnatmake} utility takes care of these details automatically.
1324 Invoke it using either one of the following forms:
1325
1326 @smallexample
1327 $ gnatmake gmain.adb
1328 $ gnatmake ^gmain^GMAIN^
1329 @end smallexample
1330
1331 @noindent
1332 The argument is the name of the file containing the main program;
1333 you may omit the extension. @command{gnatmake}
1334 examines the environment, automatically recompiles any files that need
1335 recompiling, and binds and links the resulting set of object files,
1336 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1337 In a large program, it
1338 can be extremely helpful to use @command{gnatmake}, because working out by hand
1339 what needs to be recompiled can be difficult.
1340
1341 Note that @command{gnatmake}
1342 takes into account all the Ada rules that
1343 establish dependencies among units. These include dependencies that result
1344 from inlining subprogram bodies, and from
1345 generic instantiation. Unlike some other
1346 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1347 found by the compiler on a previous compilation, which may possibly
1348 be wrong when sources change. @command{gnatmake} determines the exact set of
1349 dependencies from scratch each time it is run.
1350
1351 @ifset vms
1352 @node Editing with Emacs
1353 @section Editing with Emacs
1354 @cindex Emacs
1355
1356 @noindent
1357 Emacs is an extensible self-documenting text editor that is available in a
1358 separate VMSINSTAL kit.
1359
1360 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1361 click on the Emacs Help menu and run the Emacs Tutorial.
1362 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1363 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1364
1365 Documentation on Emacs and other tools is available in Emacs under the
1366 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1367 use the middle mouse button to select a topic (e.g.@: Emacs).
1368
1369 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1370 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1371 get to the Emacs manual.
1372 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1373 prompt.
1374
1375 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1376 which is sufficiently extensible to provide for a complete programming
1377 environment and shell for the sophisticated user.
1378 @end ifset
1379
1380 @ifclear vms
1381 @node Introduction to GPS
1382 @section Introduction to GPS
1383 @cindex GPS (GNAT Programming Studio)
1384 @cindex GNAT Programming Studio (GPS)
1385 @noindent
1386 Although the command line interface (@command{gnatmake}, etc.) alone
1387 is sufficient, a graphical Interactive Development
1388 Environment can make it easier for you to compose, navigate, and debug
1389 programs. This section describes the main features of GPS
1390 (``GNAT Programming Studio''), the GNAT graphical IDE.
1391 You will see how to use GPS to build and debug an executable, and
1392 you will also learn some of the basics of the GNAT ``project'' facility.
1393
1394 GPS enables you to do much more than is presented here;
1395 e.g., you can produce a call graph, interface to a third-party
1396 Version Control System, and inspect the generated assembly language
1397 for a program.
1398 Indeed, GPS also supports languages other than Ada.
1399 Such additional information, and an explanation of all of the GPS menu
1400 items. may be found in the on-line help, which includes
1401 a user's guide and a tutorial (these are also accessible from the GNAT
1402 startup menu).
1403
1404 @menu
1405 * Building a New Program with GPS::
1406 * Simple Debugging with GPS::
1407 @end menu
1408
1409 @node Building a New Program with GPS
1410 @subsection Building a New Program with GPS
1411 @noindent
1412 GPS invokes the GNAT compilation tools using information
1413 contained in a @emph{project} (also known as a @emph{project file}):
1414 a collection of properties such
1415 as source directories, identities of main subprograms, tool switches, etc.,
1416 and their associated values.
1417 See @ref{GNAT Project Manager} for details.
1418 In order to run GPS, you will need to either create a new project
1419 or else open an existing one.
1420
1421 This section will explain how you can use GPS to create a project,
1422 to associate Ada source files with a project, and to build and run
1423 programs.
1424
1425 @enumerate
1426 @item @emph{Creating a project}
1427
1428 Invoke GPS, either from the command line or the platform's IDE.
1429 After it starts, GPS will display a ``Welcome'' screen with three
1430 radio buttons:
1431
1432 @itemize @bullet
1433 @item
1434 @code{Start with default project in directory}
1435
1436 @item
1437 @code{Create new project with wizard}
1438
1439 @item
1440 @code{Open existing project}
1441 @end itemize
1442
1443 @noindent
1444 Select @code{Create new project with wizard} and press @code{OK}.
1445 A new window will appear. In the text box labeled with
1446 @code{Enter the name of the project to create}, type @file{sample}
1447 as the project name.
1448 In the next box, browse to choose the directory in which you
1449 would like to create the project file.
1450 After selecting an appropriate directory, press @code{Forward}.
1451
1452 A window will appear with the title
1453 @code{Version Control System Configuration}.
1454 Simply press @code{Forward}.
1455
1456 A window will appear with the title
1457 @code{Please select the source directories for this project}.
1458 The directory that you specified for the project file will be selected
1459 by default as the one to use for sources; simply press @code{Forward}.
1460
1461 A window will appear with the title
1462 @code{Please select the build directory for this project}.
1463 The directory that you specified for the project file will be selected
1464 by default for object files and executables;
1465 simply press @code{Forward}.
1466
1467 A window will appear with the title
1468 @code{Please select the main units for this project}.
1469 You will supply this information later, after creating the source file.
1470 Simply press @code{Forward} for now.
1471
1472 A window will appear with the title
1473 @code{Please select the switches to build the project}.
1474 Press @code{Apply}. This will create a project file named
1475 @file{sample.prj} in the directory that you had specified.
1476
1477 @item @emph{Creating and saving the source file}
1478
1479 After you create the new project, a GPS window will appear, which is
1480 partitioned into two main sections:
1481
1482 @itemize @bullet
1483 @item
1484 A @emph{Workspace area}, initially greyed out, which you will use for
1485 creating and editing source files
1486
1487 @item
1488 Directly below, a @emph{Messages area}, which initially displays a
1489 ``Welcome'' message.
1490 (If the Messages area is not visible, drag its border upward to expand it.)
1491 @end itemize
1492
1493 @noindent
1494 Select @code{File} on the menu bar, and then the @code{New} command.
1495 The Workspace area will become white, and you can now
1496 enter the source program explicitly.
1497 Type the following text
1498
1499 @smallexample @c ada
1500 @group
1501 with Ada.Text_IO; use Ada.Text_IO;
1502 procedure Hello is
1503 begin
1504 Put_Line("Hello from GPS!");
1505 end Hello;
1506 @end group
1507 @end smallexample
1508
1509 @noindent
1510 Select @code{File}, then @code{Save As}, and enter the source file name
1511 @file{hello.adb}.
1512 The file will be saved in the same directory you specified as the
1513 location of the default project file.
1514
1515 @item @emph{Updating the project file}
1516
1517 You need to add the new source file to the project.
1518 To do this, select
1519 the @code{Project} menu and then @code{Edit project properties}.
1520 Click the @code{Main files} tab on the left, and then the
1521 @code{Add} button.
1522 Choose @file{hello.adb} from the list, and press @code{Open}.
1523 The project settings window will reflect this action.
1524 Click @code{OK}.
1525
1526 @item @emph{Building and running the program}
1527
1528 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1529 and select @file{hello.adb}.
1530 The Messages window will display the resulting invocations of @command{gcc},
1531 @command{gnatbind}, and @command{gnatlink}
1532 (reflecting the default switch settings from the
1533 project file that you created) and then a ``successful compilation/build''
1534 message.
1535
1536 To run the program, choose the @code{Build} menu, then @code{Run}, and
1537 select @command{hello}.
1538 An @emph{Arguments Selection} window will appear.
1539 There are no command line arguments, so just click @code{OK}.
1540
1541 The Messages window will now display the program's output (the string
1542 @code{Hello from GPS}), and at the bottom of the GPS window a status
1543 update is displayed (@code{Run: hello}).
1544 Close the GPS window (or select @code{File}, then @code{Exit}) to
1545 terminate this GPS session.
1546 @end enumerate
1547
1548 @node Simple Debugging with GPS
1549 @subsection Simple Debugging with GPS
1550 @noindent
1551 This section illustrates basic debugging techniques (setting breakpoints,
1552 examining/modifying variables, single stepping).
1553
1554 @enumerate
1555 @item @emph{Opening a project}
1556
1557 Start GPS and select @code{Open existing project}; browse to
1558 specify the project file @file{sample.prj} that you had created in the
1559 earlier example.
1560
1561 @item @emph{Creating a source file}
1562
1563 Select @code{File}, then @code{New}, and type in the following program:
1564
1565 @smallexample @c ada
1566 @group
1567 with Ada.Text_IO; use Ada.Text_IO;
1568 procedure Example is
1569 Line : String (1..80);
1570 N : Natural;
1571 begin
1572 Put_Line("Type a line of text at each prompt; an empty line to exit");
1573 loop
1574 Put(": ");
1575 Get_Line (Line, N);
1576 Put_Line (Line (1..N) );
1577 exit when N=0;
1578 end loop;
1579 end Example;
1580 @end group
1581 @end smallexample
1582
1583 @noindent
1584 Select @code{File}, then @code{Save as}, and enter the file name
1585 @file{example.adb}.
1586
1587 @item @emph{Updating the project file}
1588
1589 Add @code{Example} as a new main unit for the project:
1590 @enumerate a
1591 @item
1592 Select @code{Project}, then @code{Edit Project Properties}.
1593
1594 @item
1595 Select the @code{Main files} tab, click @code{Add}, then
1596 select the file @file{example.adb} from the list, and
1597 click @code{Open}.
1598 You will see the file name appear in the list of main units
1599
1600 @item
1601 Click @code{OK}
1602 @end enumerate
1603
1604 @item @emph{Building/running the executable}
1605
1606 To build the executable
1607 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1608
1609 Run the program to see its effect (in the Messages area).
1610 Each line that you enter is displayed; an empty line will
1611 cause the loop to exit and the program to terminate.
1612
1613 @item @emph{Debugging the program}
1614
1615 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1616 which are required for debugging, are on by default when you create
1617 a new project.
1618 Thus unless you intentionally remove these settings, you will be able
1619 to debug any program that you develop using GPS.
1620
1621 @enumerate a
1622 @item @emph{Initializing}
1623
1624 Select @code{Debug}, then @code{Initialize}, then @file{example}
1625
1626 @item @emph{Setting a breakpoint}
1627
1628 After performing the initialization step, you will observe a small
1629 icon to the right of each line number.
1630 This serves as a toggle for breakpoints; clicking the icon will
1631 set a breakpoint at the corresponding line (the icon will change to
1632 a red circle with an ``x''), and clicking it again
1633 will remove the breakpoint / reset the icon.
1634
1635 For purposes of this example, set a breakpoint at line 10 (the
1636 statement @code{Put_Line@ (Line@ (1..N));}
1637
1638 @item @emph{Starting program execution}
1639
1640 Select @code{Debug}, then @code{Run}. When the
1641 @code{Program Arguments} window appears, click @code{OK}.
1642 A console window will appear; enter some line of text,
1643 e.g.@: @code{abcde}, at the prompt.
1644 The program will pause execution when it gets to the
1645 breakpoint, and the corresponding line is highlighted.
1646
1647 @item @emph{Examining a variable}
1648
1649 Move the mouse over one of the occurrences of the variable @code{N}.
1650 You will see the value (5) displayed, in ``tool tip'' fashion.
1651 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1652 You will see information about @code{N} appear in the @code{Debugger Data}
1653 pane, showing the value as 5.
1654
1655 @item @emph{Assigning a new value to a variable}
1656
1657 Right click on the @code{N} in the @code{Debugger Data} pane, and
1658 select @code{Set value of N}.
1659 When the input window appears, enter the value @code{4} and click
1660 @code{OK}.
1661 This value does not automatically appear in the @code{Debugger Data}
1662 pane; to see it, right click again on the @code{N} in the
1663 @code{Debugger Data} pane and select @code{Update value}.
1664 The new value, 4, will appear in red.
1665
1666 @item @emph{Single stepping}
1667
1668 Select @code{Debug}, then @code{Next}.
1669 This will cause the next statement to be executed, in this case the
1670 call of @code{Put_Line} with the string slice.
1671 Notice in the console window that the displayed string is simply
1672 @code{abcd} and not @code{abcde} which you had entered.
1673 This is because the upper bound of the slice is now 4 rather than 5.
1674
1675 @item @emph{Removing a breakpoint}
1676
1677 Toggle the breakpoint icon at line 10.
1678
1679 @item @emph{Resuming execution from a breakpoint}
1680
1681 Select @code{Debug}, then @code{Continue}.
1682 The program will reach the next iteration of the loop, and
1683 wait for input after displaying the prompt.
1684 This time, just hit the @kbd{Enter} key.
1685 The value of @code{N} will be 0, and the program will terminate.
1686 The console window will disappear.
1687 @end enumerate
1688 @end enumerate
1689 @end ifclear
1690
1691 @node The GNAT Compilation Model
1692 @chapter The GNAT Compilation Model
1693 @cindex GNAT compilation model
1694 @cindex Compilation model
1695
1696 @menu
1697 * Source Representation::
1698 * Foreign Language Representation::
1699 * File Naming Rules::
1700 * Using Other File Names::
1701 * Alternative File Naming Schemes::
1702 * Generating Object Files::
1703 * Source Dependencies::
1704 * The Ada Library Information Files::
1705 * Binding an Ada Program::
1706 * Mixed Language Programming::
1707 @ifclear vms
1708 * Building Mixed Ada & C++ Programs::
1709 * Comparison between GNAT and C/C++ Compilation Models::
1710 @end ifclear
1711 * Comparison between GNAT and Conventional Ada Library Models::
1712 @ifset vms
1713 * Placement of temporary files::
1714 @end ifset
1715 @end menu
1716
1717 @noindent
1718 This chapter describes the compilation model used by GNAT. Although
1719 similar to that used by other languages, such as C and C++, this model
1720 is substantially different from the traditional Ada compilation models,
1721 which are based on a library. The model is initially described without
1722 reference to the library-based model. If you have not previously used an
1723 Ada compiler, you need only read the first part of this chapter. The
1724 last section describes and discusses the differences between the GNAT
1725 model and the traditional Ada compiler models. If you have used other
1726 Ada compilers, this section will help you to understand those
1727 differences, and the advantages of the GNAT model.
1728
1729 @node Source Representation
1730 @section Source Representation
1731 @cindex Latin-1
1732
1733 @noindent
1734 Ada source programs are represented in standard text files, using
1735 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1736 7-bit ASCII set, plus additional characters used for
1737 representing foreign languages (@pxref{Foreign Language Representation}
1738 for support of non-USA character sets). The format effector characters
1739 are represented using their standard ASCII encodings, as follows:
1740
1741 @table @code
1742 @item VT
1743 @findex VT
1744 Vertical tab, @code{16#0B#}
1745
1746 @item HT
1747 @findex HT
1748 Horizontal tab, @code{16#09#}
1749
1750 @item CR
1751 @findex CR
1752 Carriage return, @code{16#0D#}
1753
1754 @item LF
1755 @findex LF
1756 Line feed, @code{16#0A#}
1757
1758 @item FF
1759 @findex FF
1760 Form feed, @code{16#0C#}
1761 @end table
1762
1763 @noindent
1764 Source files are in standard text file format. In addition, GNAT will
1765 recognize a wide variety of stream formats, in which the end of
1766 physical lines is marked by any of the following sequences:
1767 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1768 in accommodating files that are imported from other operating systems.
1769
1770 @cindex End of source file
1771 @cindex Source file, end
1772 @findex SUB
1773 The end of a source file is normally represented by the physical end of
1774 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1775 recognized as signalling the end of the source file. Again, this is
1776 provided for compatibility with other operating systems where this
1777 code is used to represent the end of file.
1778
1779 Each file contains a single Ada compilation unit, including any pragmas
1780 associated with the unit. For example, this means you must place a
1781 package declaration (a package @dfn{spec}) and the corresponding body in
1782 separate files. An Ada @dfn{compilation} (which is a sequence of
1783 compilation units) is represented using a sequence of files. Similarly,
1784 you will place each subunit or child unit in a separate file.
1785
1786 @node Foreign Language Representation
1787 @section Foreign Language Representation
1788
1789 @noindent
1790 GNAT supports the standard character sets defined in Ada as well as
1791 several other non-standard character sets for use in localized versions
1792 of the compiler (@pxref{Character Set Control}).
1793 @menu
1794 * Latin-1::
1795 * Other 8-Bit Codes::
1796 * Wide Character Encodings::
1797 @end menu
1798
1799 @node Latin-1
1800 @subsection Latin-1
1801 @cindex Latin-1
1802
1803 @noindent
1804 The basic character set is Latin-1. This character set is defined by ISO
1805 standard 8859, part 1. The lower half (character codes @code{16#00#}
1806 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1807 is used to represent additional characters. These include extended letters
1808 used by European languages, such as French accents, the vowels with umlauts
1809 used in German, and the extra letter A-ring used in Swedish.
1810
1811 @findex Ada.Characters.Latin_1
1812 For a complete list of Latin-1 codes and their encodings, see the source
1813 file of library unit @code{Ada.Characters.Latin_1} in file
1814 @file{a-chlat1.ads}.
1815 You may use any of these extended characters freely in character or
1816 string literals. In addition, the extended characters that represent
1817 letters can be used in identifiers.
1818
1819 @node Other 8-Bit Codes
1820 @subsection Other 8-Bit Codes
1821
1822 @noindent
1823 GNAT also supports several other 8-bit coding schemes:
1824
1825 @table @asis
1826 @item ISO 8859-2 (Latin-2)
1827 @cindex Latin-2
1828 @cindex ISO 8859-2
1829 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-3 (Latin-3)
1833 @cindex Latin-3
1834 @cindex ISO 8859-3
1835 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1836 equivalence.
1837
1838 @item ISO 8859-4 (Latin-4)
1839 @cindex Latin-4
1840 @cindex ISO 8859-4
1841 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1842 equivalence.
1843
1844 @item ISO 8859-5 (Cyrillic)
1845 @cindex ISO 8859-5
1846 @cindex Cyrillic
1847 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1848 lowercase equivalence.
1849
1850 @item ISO 8859-15 (Latin-9)
1851 @cindex ISO 8859-15
1852 @cindex Latin-9
1853 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1854 lowercase equivalence
1855
1856 @item IBM PC (code page 437)
1857 @cindex code page 437
1858 This code page is the normal default for PCs in the U.S. It corresponds
1859 to the original IBM PC character set. This set has some, but not all, of
1860 the extended Latin-1 letters, but these letters do not have the same
1861 encoding as Latin-1. In this mode, these letters are allowed in
1862 identifiers with uppercase and lowercase equivalence.
1863
1864 @item IBM PC (code page 850)
1865 @cindex code page 850
1866 This code page is a modification of 437 extended to include all the
1867 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1868 mode, all these letters are allowed in identifiers with uppercase and
1869 lowercase equivalence.
1870
1871 @item Full Upper 8-bit
1872 Any character in the range 80-FF allowed in identifiers, and all are
1873 considered distinct. In other words, there are no uppercase and lowercase
1874 equivalences in this range. This is useful in conjunction with
1875 certain encoding schemes used for some foreign character sets (e.g.,
1876 the typical method of representing Chinese characters on the PC).
1877
1878 @item No Upper-Half
1879 No upper-half characters in the range 80-FF are allowed in identifiers.
1880 This gives Ada 83 compatibility for identifier names.
1881 @end table
1882
1883 @noindent
1884 For precise data on the encodings permitted, and the uppercase and lowercase
1885 equivalences that are recognized, see the file @file{csets.adb} in
1886 the GNAT compiler sources. You will need to obtain a full source release
1887 of GNAT to obtain this file.
1888
1889 @node Wide Character Encodings
1890 @subsection Wide Character Encodings
1891
1892 @noindent
1893 GNAT allows wide character codes to appear in character and string
1894 literals, and also optionally in identifiers, by means of the following
1895 possible encoding schemes:
1896
1897 @table @asis
1898
1899 @item Hex Coding
1900 In this encoding, a wide character is represented by the following five
1901 character sequence:
1902
1903 @smallexample
1904 ESC a b c d
1905 @end smallexample
1906
1907 @noindent
1908 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1909 characters (using uppercase letters) of the wide character code. For
1910 example, ESC A345 is used to represent the wide character with code
1911 @code{16#A345#}.
1912 This scheme is compatible with use of the full Wide_Character set.
1913
1914 @item Upper-Half Coding
1915 @cindex Upper-Half Coding
1916 The wide character with encoding @code{16#abcd#} where the upper bit is on
1917 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1918 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1919 character, but is not required to be in the upper half. This method can
1920 be also used for shift-JIS or EUC, where the internal coding matches the
1921 external coding.
1922
1923 @item Shift JIS Coding
1924 @cindex Shift JIS Coding
1925 A wide character is represented by a two-character sequence,
1926 @code{16#ab#} and
1927 @code{16#cd#}, with the restrictions described for upper-half encoding as
1928 described above. The internal character code is the corresponding JIS
1929 character according to the standard algorithm for Shift-JIS
1930 conversion. Only characters defined in the JIS code set table can be
1931 used with this encoding method.
1932
1933 @item EUC Coding
1934 @cindex EUC Coding
1935 A wide character is represented by a two-character sequence
1936 @code{16#ab#} and
1937 @code{16#cd#}, with both characters being in the upper half. The internal
1938 character code is the corresponding JIS character according to the EUC
1939 encoding algorithm. Only characters defined in the JIS code set table
1940 can be used with this encoding method.
1941
1942 @item UTF-8 Coding
1943 A wide character is represented using
1944 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1945 10646-1/Am.2. Depending on the character value, the representation
1946 is a one, two, or three byte sequence:
1947 @smallexample
1948 @iftex
1949 @leftskip=.7cm
1950 @end iftex
1951 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1952 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1953 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1954
1955 @end smallexample
1956
1957 @noindent
1958 where the @var{xxx} bits correspond to the left-padded bits of the
1959 16-bit character value. Note that all lower half ASCII characters
1960 are represented as ASCII bytes and all upper half characters and
1961 other wide characters are represented as sequences of upper-half
1962 (The full UTF-8 scheme allows for encoding 31-bit characters as
1963 6-byte sequences, but in this implementation, all UTF-8 sequences
1964 of four or more bytes length will be treated as illegal).
1965 @item Brackets Coding
1966 In this encoding, a wide character is represented by the following eight
1967 character sequence:
1968
1969 @smallexample
1970 [ " a b c d " ]
1971 @end smallexample
1972
1973 @noindent
1974 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1975 characters (using uppercase letters) of the wide character code. For
1976 example, [``A345''] is used to represent the wide character with code
1977 @code{16#A345#}. It is also possible (though not required) to use the
1978 Brackets coding for upper half characters. For example, the code
1979 @code{16#A3#} can be represented as @code{[``A3'']}.
1980
1981 This scheme is compatible with use of the full Wide_Character set,
1982 and is also the method used for wide character encoding in the standard
1983 ACVC (Ada Compiler Validation Capability) test suite distributions.
1984
1985 @end table
1986
1987 @noindent
1988 Note: Some of these coding schemes do not permit the full use of the
1989 Ada character set. For example, neither Shift JIS, nor EUC allow the
1990 use of the upper half of the Latin-1 set.
1991
1992 @node File Naming Rules
1993 @section File Naming Rules
1994
1995 @noindent
1996 The default file name is determined by the name of the unit that the
1997 file contains. The name is formed by taking the full expanded name of
1998 the unit and replacing the separating dots with hyphens and using
1999 ^lowercase^uppercase^ for all letters.
2000
2001 An exception arises if the file name generated by the above rules starts
2002 with one of the characters
2003 @ifset vms
2004 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2005 @end ifset
2006 @ifclear vms
2007 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2008 @end ifclear
2009 and the second character is a
2010 minus. In this case, the character ^tilde^dollar sign^ is used in place
2011 of the minus. The reason for this special rule is to avoid clashes with
2012 the standard names for child units of the packages System, Ada,
2013 Interfaces, and GNAT, which use the prefixes
2014 @ifset vms
2015 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2016 @end ifset
2017 @ifclear vms
2018 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2019 @end ifclear
2020 respectively.
2021
2022 The file extension is @file{.ads} for a spec and
2023 @file{.adb} for a body. The following list shows some
2024 examples of these rules.
2025
2026 @table @file
2027 @item main.ads
2028 Main (spec)
2029 @item main.adb
2030 Main (body)
2031 @item arith_functions.ads
2032 Arith_Functions (package spec)
2033 @item arith_functions.adb
2034 Arith_Functions (package body)
2035 @item func-spec.ads
2036 Func.Spec (child package spec)
2037 @item func-spec.adb
2038 Func.Spec (child package body)
2039 @item main-sub.adb
2040 Sub (subunit of Main)
2041 @item ^a~bad.adb^A$BAD.ADB^
2042 A.Bad (child package body)
2043 @end table
2044
2045 @noindent
2046 Following these rules can result in excessively long
2047 file names if corresponding
2048 unit names are long (for example, if child units or subunits are
2049 heavily nested). An option is available to shorten such long file names
2050 (called file name ``krunching''). This may be particularly useful when
2051 programs being developed with GNAT are to be used on operating systems
2052 with limited file name lengths. @xref{Using gnatkr}.
2053
2054 Of course, no file shortening algorithm can guarantee uniqueness over
2055 all possible unit names; if file name krunching is used, it is your
2056 responsibility to ensure no name clashes occur. Alternatively you
2057 can specify the exact file names that you want used, as described
2058 in the next section. Finally, if your Ada programs are migrating from a
2059 compiler with a different naming convention, you can use the gnatchop
2060 utility to produce source files that follow the GNAT naming conventions.
2061 (For details @pxref{Renaming Files Using gnatchop}.)
2062
2063 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2064 systems, case is not significant. So for example on @code{Windows XP}
2065 if the canonical name is @code{main-sub.adb}, you can use the file name
2066 @code{Main-Sub.adb} instead. However, case is significant for other
2067 operating systems, so for example, if you want to use other than
2068 canonically cased file names on a Unix system, you need to follow
2069 the procedures described in the next section.
2070
2071 @node Using Other File Names
2072 @section Using Other File Names
2073 @cindex File names
2074
2075 @noindent
2076 In the previous section, we have described the default rules used by
2077 GNAT to determine the file name in which a given unit resides. It is
2078 often convenient to follow these default rules, and if you follow them,
2079 the compiler knows without being explicitly told where to find all
2080 the files it needs.
2081
2082 However, in some cases, particularly when a program is imported from
2083 another Ada compiler environment, it may be more convenient for the
2084 programmer to specify which file names contain which units. GNAT allows
2085 arbitrary file names to be used by means of the Source_File_Name pragma.
2086 The form of this pragma is as shown in the following examples:
2087 @cindex Source_File_Name pragma
2088
2089 @smallexample @c ada
2090 @cartouche
2091 pragma Source_File_Name (My_Utilities.Stacks,
2092 Spec_File_Name => "myutilst_a.ada");
2093 pragma Source_File_name (My_Utilities.Stacks,
2094 Body_File_Name => "myutilst.ada");
2095 @end cartouche
2096 @end smallexample
2097
2098 @noindent
2099 As shown in this example, the first argument for the pragma is the unit
2100 name (in this example a child unit). The second argument has the form
2101 of a named association. The identifier
2102 indicates whether the file name is for a spec or a body;
2103 the file name itself is given by a string literal.
2104
2105 The source file name pragma is a configuration pragma, which means that
2106 normally it will be placed in the @file{gnat.adc}
2107 file used to hold configuration
2108 pragmas that apply to a complete compilation environment.
2109 For more details on how the @file{gnat.adc} file is created and used
2110 see @ref{Handling of Configuration Pragmas}.
2111 @cindex @file{gnat.adc}
2112
2113 @ifclear vms
2114 GNAT allows completely arbitrary file names to be specified using the
2115 source file name pragma. However, if the file name specified has an
2116 extension other than @file{.ads} or @file{.adb} it is necessary to use
2117 a special syntax when compiling the file. The name in this case must be
2118 preceded by the special sequence @option{-x} followed by a space and the name
2119 of the language, here @code{ada}, as in:
2120
2121 @smallexample
2122 $ gcc -c -x ada peculiar_file_name.sim
2123 @end smallexample
2124 @end ifclear
2125
2126 @noindent
2127 @command{gnatmake} handles non-standard file names in the usual manner (the
2128 non-standard file name for the main program is simply used as the
2129 argument to gnatmake). Note that if the extension is also non-standard,
2130 then it must be included in the @command{gnatmake} command, it may not
2131 be omitted.
2132
2133 @node Alternative File Naming Schemes
2134 @section Alternative File Naming Schemes
2135 @cindex File naming schemes, alternative
2136 @cindex File names
2137
2138 In the previous section, we described the use of the @code{Source_File_Name}
2139 pragma to allow arbitrary names to be assigned to individual source files.
2140 However, this approach requires one pragma for each file, and especially in
2141 large systems can result in very long @file{gnat.adc} files, and also create
2142 a maintenance problem.
2143
2144 GNAT also provides a facility for specifying systematic file naming schemes
2145 other than the standard default naming scheme previously described. An
2146 alternative scheme for naming is specified by the use of
2147 @code{Source_File_Name} pragmas having the following format:
2148 @cindex Source_File_Name pragma
2149
2150 @smallexample @c ada
2151 pragma Source_File_Name (
2152 Spec_File_Name => FILE_NAME_PATTERN
2153 @r{[},Casing => CASING_SPEC@r{]}
2154 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2155
2156 pragma Source_File_Name (
2157 Body_File_Name => FILE_NAME_PATTERN
2158 @r{[},Casing => CASING_SPEC@r{]}
2159 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2160
2161 pragma Source_File_Name (
2162 Subunit_File_Name => FILE_NAME_PATTERN
2163 @r{[},Casing => CASING_SPEC@r{]}
2164 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2165
2166 FILE_NAME_PATTERN ::= STRING_LITERAL
2167 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2168 @end smallexample
2169
2170 @noindent
2171 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2172 It contains a single asterisk character, and the unit name is substituted
2173 systematically for this asterisk. The optional parameter
2174 @code{Casing} indicates
2175 whether the unit name is to be all upper-case letters, all lower-case letters,
2176 or mixed-case. If no
2177 @code{Casing} parameter is used, then the default is all
2178 ^lower-case^upper-case^.
2179
2180 The optional @code{Dot_Replacement} string is used to replace any periods
2181 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2182 argument is used then separating dots appear unchanged in the resulting
2183 file name.
2184 Although the above syntax indicates that the
2185 @code{Casing} argument must appear
2186 before the @code{Dot_Replacement} argument, but it
2187 is also permissible to write these arguments in the opposite order.
2188
2189 As indicated, it is possible to specify different naming schemes for
2190 bodies, specs, and subunits. Quite often the rule for subunits is the
2191 same as the rule for bodies, in which case, there is no need to give
2192 a separate @code{Subunit_File_Name} rule, and in this case the
2193 @code{Body_File_name} rule is used for subunits as well.
2194
2195 The separate rule for subunits can also be used to implement the rather
2196 unusual case of a compilation environment (e.g.@: a single directory) which
2197 contains a subunit and a child unit with the same unit name. Although
2198 both units cannot appear in the same partition, the Ada Reference Manual
2199 allows (but does not require) the possibility of the two units coexisting
2200 in the same environment.
2201
2202 The file name translation works in the following steps:
2203
2204 @itemize @bullet
2205
2206 @item
2207 If there is a specific @code{Source_File_Name} pragma for the given unit,
2208 then this is always used, and any general pattern rules are ignored.
2209
2210 @item
2211 If there is a pattern type @code{Source_File_Name} pragma that applies to
2212 the unit, then the resulting file name will be used if the file exists. If
2213 more than one pattern matches, the latest one will be tried first, and the
2214 first attempt resulting in a reference to a file that exists will be used.
2215
2216 @item
2217 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2218 for which the corresponding file exists, then the standard GNAT default
2219 naming rules are used.
2220
2221 @end itemize
2222
2223 @noindent
2224 As an example of the use of this mechanism, consider a commonly used scheme
2225 in which file names are all lower case, with separating periods copied
2226 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2227 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2228 two pragmas appear:
2229
2230 @smallexample @c ada
2231 pragma Source_File_Name
2232 (Spec_File_Name => "*.1.ada");
2233 pragma Source_File_Name
2234 (Body_File_Name => "*.2.ada");
2235 @end smallexample
2236
2237 @noindent
2238 The default GNAT scheme is actually implemented by providing the following
2239 default pragmas internally:
2240
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2244 pragma Source_File_Name
2245 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2246 @end smallexample
2247
2248 @noindent
2249 Our final example implements a scheme typically used with one of the
2250 Ada 83 compilers, where the separator character for subunits was ``__''
2251 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2252 by adding @file{.ADA}, and subunits by
2253 adding @file{.SEP}. All file names were
2254 upper case. Child units were not present of course since this was an
2255 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2256 the same double underscore separator for child units.
2257
2258 @smallexample @c ada
2259 pragma Source_File_Name
2260 (Spec_File_Name => "*_.ADA",
2261 Dot_Replacement => "__",
2262 Casing = Uppercase);
2263 pragma Source_File_Name
2264 (Body_File_Name => "*.ADA",
2265 Dot_Replacement => "__",
2266 Casing = Uppercase);
2267 pragma Source_File_Name
2268 (Subunit_File_Name => "*.SEP",
2269 Dot_Replacement => "__",
2270 Casing = Uppercase);
2271 @end smallexample
2272
2273 @node Generating Object Files
2274 @section Generating Object Files
2275
2276 @noindent
2277 An Ada program consists of a set of source files, and the first step in
2278 compiling the program is to generate the corresponding object files.
2279 These are generated by compiling a subset of these source files.
2280 The files you need to compile are the following:
2281
2282 @itemize @bullet
2283 @item
2284 If a package spec has no body, compile the package spec to produce the
2285 object file for the package.
2286
2287 @item
2288 If a package has both a spec and a body, compile the body to produce the
2289 object file for the package. The source file for the package spec need
2290 not be compiled in this case because there is only one object file, which
2291 contains the code for both the spec and body of the package.
2292
2293 @item
2294 For a subprogram, compile the subprogram body to produce the object file
2295 for the subprogram. The spec, if one is present, is as usual in a
2296 separate file, and need not be compiled.
2297
2298 @item
2299 @cindex Subunits
2300 In the case of subunits, only compile the parent unit. A single object
2301 file is generated for the entire subunit tree, which includes all the
2302 subunits.
2303
2304 @item
2305 Compile child units independently of their parent units
2306 (though, of course, the spec of all the ancestor unit must be present in order
2307 to compile a child unit).
2308
2309 @item
2310 @cindex Generics
2311 Compile generic units in the same manner as any other units. The object
2312 files in this case are small dummy files that contain at most the
2313 flag used for elaboration checking. This is because GNAT always handles generic
2314 instantiation by means of macro expansion. However, it is still necessary to
2315 compile generic units, for dependency checking and elaboration purposes.
2316 @end itemize
2317
2318 @noindent
2319 The preceding rules describe the set of files that must be compiled to
2320 generate the object files for a program. Each object file has the same
2321 name as the corresponding source file, except that the extension is
2322 @file{.o} as usual.
2323
2324 You may wish to compile other files for the purpose of checking their
2325 syntactic and semantic correctness. For example, in the case where a
2326 package has a separate spec and body, you would not normally compile the
2327 spec. However, it is convenient in practice to compile the spec to make
2328 sure it is error-free before compiling clients of this spec, because such
2329 compilations will fail if there is an error in the spec.
2330
2331 GNAT provides an option for compiling such files purely for the
2332 purposes of checking correctness; such compilations are not required as
2333 part of the process of building a program. To compile a file in this
2334 checking mode, use the @option{-gnatc} switch.
2335
2336 @node Source Dependencies
2337 @section Source Dependencies
2338
2339 @noindent
2340 A given object file clearly depends on the source file which is compiled
2341 to produce it. Here we are using @dfn{depends} in the sense of a typical
2342 @code{make} utility; in other words, an object file depends on a source
2343 file if changes to the source file require the object file to be
2344 recompiled.
2345 In addition to this basic dependency, a given object may depend on
2346 additional source files as follows:
2347
2348 @itemize @bullet
2349 @item
2350 If a file being compiled @code{with}'s a unit @var{X}, the object file
2351 depends on the file containing the spec of unit @var{X}. This includes
2352 files that are @code{with}'ed implicitly either because they are parents
2353 of @code{with}'ed child units or they are run-time units required by the
2354 language constructs used in a particular unit.
2355
2356 @item
2357 If a file being compiled instantiates a library level generic unit, the
2358 object file depends on both the spec and body files for this generic
2359 unit.
2360
2361 @item
2362 If a file being compiled instantiates a generic unit defined within a
2363 package, the object file depends on the body file for the package as
2364 well as the spec file.
2365
2366 @item
2367 @findex Inline
2368 @cindex @option{-gnatn} switch
2369 If a file being compiled contains a call to a subprogram for which
2370 pragma @code{Inline} applies and inlining is activated with the
2371 @option{-gnatn} switch, the object file depends on the file containing the
2372 body of this subprogram as well as on the file containing the spec. Note
2373 that for inlining to actually occur as a result of the use of this switch,
2374 it is necessary to compile in optimizing mode.
2375
2376 @cindex @option{-gnatN} switch
2377 The use of @option{-gnatN} activates inlining optimization
2378 that is performed by the front end of the compiler. This inlining does
2379 not require that the code generation be optimized. Like @option{-gnatn},
2380 the use of this switch generates additional dependencies.
2381
2382 When using a gcc-based back end (in practice this means using any version
2383 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2384 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2385 Historically front end inlining was more extensive than the gcc back end
2386 inlining, but that is no longer the case.
2387
2388 @item
2389 If an object file @file{O} depends on the proper body of a subunit through
2390 inlining or instantiation, it depends on the parent unit of the subunit.
2391 This means that any modification of the parent unit or one of its subunits
2392 affects the compilation of @file{O}.
2393
2394 @item
2395 The object file for a parent unit depends on all its subunit body files.
2396
2397 @item
2398 The previous two rules meant that for purposes of computing dependencies and
2399 recompilation, a body and all its subunits are treated as an indivisible whole.
2400
2401 @noindent
2402 These rules are applied transitively: if unit @code{A} @code{with}'s
2403 unit @code{B}, whose elaboration calls an inlined procedure in package
2404 @code{C}, the object file for unit @code{A} will depend on the body of
2405 @code{C}, in file @file{c.adb}.
2406
2407 The set of dependent files described by these rules includes all the
2408 files on which the unit is semantically dependent, as dictated by the
2409 Ada language standard. However, it is a superset of what the
2410 standard describes, because it includes generic, inline, and subunit
2411 dependencies.
2412
2413 An object file must be recreated by recompiling the corresponding source
2414 file if any of the source files on which it depends are modified. For
2415 example, if the @code{make} utility is used to control compilation,
2416 the rule for an Ada object file must mention all the source files on
2417 which the object file depends, according to the above definition.
2418 The determination of the necessary
2419 recompilations is done automatically when one uses @command{gnatmake}.
2420 @end itemize
2421
2422 @node The Ada Library Information Files
2423 @section The Ada Library Information Files
2424 @cindex Ada Library Information files
2425 @cindex @file{ALI} files
2426
2427 @noindent
2428 Each compilation actually generates two output files. The first of these
2429 is the normal object file that has a @file{.o} extension. The second is a
2430 text file containing full dependency information. It has the same
2431 name as the source file, but an @file{.ali} extension.
2432 This file is known as the Ada Library Information (@file{ALI}) file.
2433 The following information is contained in the @file{ALI} file.
2434
2435 @itemize @bullet
2436 @item
2437 Version information (indicates which version of GNAT was used to compile
2438 the unit(s) in question)
2439
2440 @item
2441 Main program information (including priority and time slice settings,
2442 as well as the wide character encoding used during compilation).
2443
2444 @item
2445 List of arguments used in the @command{gcc} command for the compilation
2446
2447 @item
2448 Attributes of the unit, including configuration pragmas used, an indication
2449 of whether the compilation was successful, exception model used etc.
2450
2451 @item
2452 A list of relevant restrictions applying to the unit (used for consistency)
2453 checking.
2454
2455 @item
2456 Categorization information (e.g.@: use of pragma @code{Pure}).
2457
2458 @item
2459 Information on all @code{with}'ed units, including presence of
2460 @code{Elaborate} or @code{Elaborate_All} pragmas.
2461
2462 @item
2463 Information from any @code{Linker_Options} pragmas used in the unit
2464
2465 @item
2466 Information on the use of @code{Body_Version} or @code{Version}
2467 attributes in the unit.
2468
2469 @item
2470 Dependency information. This is a list of files, together with
2471 time stamp and checksum information. These are files on which
2472 the unit depends in the sense that recompilation is required
2473 if any of these units are modified.
2474
2475 @item
2476 Cross-reference data. Contains information on all entities referenced
2477 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2478 provide cross-reference information.
2479
2480 @end itemize
2481
2482 @noindent
2483 For a full detailed description of the format of the @file{ALI} file,
2484 see the source of the body of unit @code{Lib.Writ}, contained in file
2485 @file{lib-writ.adb} in the GNAT compiler sources.
2486
2487 @node Binding an Ada Program
2488 @section Binding an Ada Program
2489
2490 @noindent
2491 When using languages such as C and C++, once the source files have been
2492 compiled the only remaining step in building an executable program
2493 is linking the object modules together. This means that it is possible to
2494 link an inconsistent version of a program, in which two units have
2495 included different versions of the same header.
2496
2497 The rules of Ada do not permit such an inconsistent program to be built.
2498 For example, if two clients have different versions of the same package,
2499 it is illegal to build a program containing these two clients.
2500 These rules are enforced by the GNAT binder, which also determines an
2501 elaboration order consistent with the Ada rules.
2502
2503 The GNAT binder is run after all the object files for a program have
2504 been created. It is given the name of the main program unit, and from
2505 this it determines the set of units required by the program, by reading the
2506 corresponding ALI files. It generates error messages if the program is
2507 inconsistent or if no valid order of elaboration exists.
2508
2509 If no errors are detected, the binder produces a main program, in Ada by
2510 default, that contains calls to the elaboration procedures of those
2511 compilation unit that require them, followed by
2512 a call to the main program. This Ada program is compiled to generate the
2513 object file for the main program. The name of
2514 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2515 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2516 main program unit.
2517
2518 Finally, the linker is used to build the resulting executable program,
2519 using the object from the main program from the bind step as well as the
2520 object files for the Ada units of the program.
2521
2522 @node Mixed Language Programming
2523 @section Mixed Language Programming
2524 @cindex Mixed Language Programming
2525
2526 @noindent
2527 This section describes how to develop a mixed-language program,
2528 specifically one that comprises units in both Ada and C.
2529
2530 @menu
2531 * Interfacing to C::
2532 * Calling Conventions::
2533 @end menu
2534
2535 @node Interfacing to C
2536 @subsection Interfacing to C
2537 @noindent
2538 Interfacing Ada with a foreign language such as C involves using
2539 compiler directives to import and/or export entity definitions in each
2540 language---using @code{extern} statements in C, for instance, and the
2541 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2542 A full treatment of these topics is provided in Appendix B, section 1
2543 of the Ada Reference Manual.
2544
2545 There are two ways to build a program using GNAT that contains some Ada
2546 sources and some foreign language sources, depending on whether or not
2547 the main subprogram is written in Ada. Here is a source example with
2548 the main subprogram in Ada:
2549
2550 @smallexample
2551 /* file1.c */
2552 #include <stdio.h>
2553
2554 void print_num (int num)
2555 @{
2556 printf ("num is %d.\n", num);
2557 return;
2558 @}
2559
2560 /* file2.c */
2561
2562 /* num_from_Ada is declared in my_main.adb */
2563 extern int num_from_Ada;
2564
2565 int get_num (void)
2566 @{
2567 return num_from_Ada;
2568 @}
2569 @end smallexample
2570
2571 @smallexample @c ada
2572 -- my_main.adb
2573 procedure My_Main is
2574
2575 -- Declare then export an Integer entity called num_from_Ada
2576 My_Num : Integer := 10;
2577 pragma Export (C, My_Num, "num_from_Ada");
2578
2579 -- Declare an Ada function spec for Get_Num, then use
2580 -- C function get_num for the implementation.
2581 function Get_Num return Integer;
2582 pragma Import (C, Get_Num, "get_num");
2583
2584 -- Declare an Ada procedure spec for Print_Num, then use
2585 -- C function print_num for the implementation.
2586 procedure Print_Num (Num : Integer);
2587 pragma Import (C, Print_Num, "print_num");
2588
2589 begin
2590 Print_Num (Get_Num);
2591 end My_Main;
2592 @end smallexample
2593
2594 @enumerate
2595 @item
2596 To build this example, first compile the foreign language files to
2597 generate object files:
2598 @smallexample
2599 ^gcc -c file1.c^gcc -c FILE1.C^
2600 ^gcc -c file2.c^gcc -c FILE2.C^
2601 @end smallexample
2602
2603 @item
2604 Then, compile the Ada units to produce a set of object files and ALI
2605 files:
2606 @smallexample
2607 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2608 @end smallexample
2609
2610 @item
2611 Run the Ada binder on the Ada main program:
2612 @smallexample
2613 gnatbind my_main.ali
2614 @end smallexample
2615
2616 @item
2617 Link the Ada main program, the Ada objects and the other language
2618 objects:
2619 @smallexample
2620 gnatlink my_main.ali file1.o file2.o
2621 @end smallexample
2622 @end enumerate
2623
2624 The last three steps can be grouped in a single command:
2625 @smallexample
2626 gnatmake my_main.adb -largs file1.o file2.o
2627 @end smallexample
2628
2629 @cindex Binder output file
2630 @noindent
2631 If the main program is in a language other than Ada, then you may have
2632 more than one entry point into the Ada subsystem. You must use a special
2633 binder option to generate callable routines that initialize and
2634 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2635 Calls to the initialization and finalization routines must be inserted
2636 in the main program, or some other appropriate point in the code. The
2637 call to initialize the Ada units must occur before the first Ada
2638 subprogram is called, and the call to finalize the Ada units must occur
2639 after the last Ada subprogram returns. The binder will place the
2640 initialization and finalization subprograms into the
2641 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2642 sources. To illustrate, we have the following example:
2643
2644 @smallexample
2645 /* main.c */
2646 extern void adainit (void);
2647 extern void adafinal (void);
2648 extern int add (int, int);
2649 extern int sub (int, int);
2650
2651 int main (int argc, char *argv[])
2652 @{
2653 int a = 21, b = 7;
2654
2655 adainit();
2656
2657 /* Should print "21 + 7 = 28" */
2658 printf ("%d + %d = %d\n", a, b, add (a, b));
2659 /* Should print "21 - 7 = 14" */
2660 printf ("%d - %d = %d\n", a, b, sub (a, b));
2661
2662 adafinal();
2663 @}
2664 @end smallexample
2665
2666 @smallexample @c ada
2667 -- unit1.ads
2668 package Unit1 is
2669 function Add (A, B : Integer) return Integer;
2670 pragma Export (C, Add, "add");
2671 end Unit1;
2672
2673 -- unit1.adb
2674 package body Unit1 is
2675 function Add (A, B : Integer) return Integer is
2676 begin
2677 return A + B;
2678 end Add;
2679 end Unit1;
2680
2681 -- unit2.ads
2682 package Unit2 is
2683 function Sub (A, B : Integer) return Integer;
2684 pragma Export (C, Sub, "sub");
2685 end Unit2;
2686
2687 -- unit2.adb
2688 package body Unit2 is
2689 function Sub (A, B : Integer) return Integer is
2690 begin
2691 return A - B;
2692 end Sub;
2693 end Unit2;
2694 @end smallexample
2695
2696 @enumerate
2697 @item
2698 The build procedure for this application is similar to the last
2699 example's. First, compile the foreign language files to generate object
2700 files:
2701 @smallexample
2702 ^gcc -c main.c^gcc -c main.c^
2703 @end smallexample
2704
2705 @item
2706 Next, compile the Ada units to produce a set of object files and ALI
2707 files:
2708 @smallexample
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2710 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2711 @end smallexample
2712
2713 @item
2714 Run the Ada binder on every generated ALI file. Make sure to use the
2715 @option{-n} option to specify a foreign main program:
2716 @smallexample
2717 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2718 @end smallexample
2719
2720 @item
2721 Link the Ada main program, the Ada objects and the foreign language
2722 objects. You need only list the last ALI file here:
2723 @smallexample
2724 gnatlink unit2.ali main.o -o exec_file
2725 @end smallexample
2726
2727 This procedure yields a binary executable called @file{exec_file}.
2728 @end enumerate
2729
2730 @noindent
2731 Depending on the circumstances (for example when your non-Ada main object
2732 does not provide symbol @code{main}), you may also need to instruct the
2733 GNAT linker not to include the standard startup objects by passing the
2734 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2735
2736 @node Calling Conventions
2737 @subsection Calling Conventions
2738 @cindex Foreign Languages
2739 @cindex Calling Conventions
2740 GNAT follows standard calling sequence conventions and will thus interface
2741 to any other language that also follows these conventions. The following
2742 Convention identifiers are recognized by GNAT:
2743
2744 @table @code
2745 @cindex Interfacing to Ada
2746 @cindex Other Ada compilers
2747 @cindex Convention Ada
2748 @item Ada
2749 This indicates that the standard Ada calling sequence will be
2750 used and all Ada data items may be passed without any limitations in the
2751 case where GNAT is used to generate both the caller and callee. It is also
2752 possible to mix GNAT generated code and code generated by another Ada
2753 compiler. In this case, the data types should be restricted to simple
2754 cases, including primitive types. Whether complex data types can be passed
2755 depends on the situation. Probably it is safe to pass simple arrays, such
2756 as arrays of integers or floats. Records may or may not work, depending
2757 on whether both compilers lay them out identically. Complex structures
2758 involving variant records, access parameters, tasks, or protected types,
2759 are unlikely to be able to be passed.
2760
2761 Note that in the case of GNAT running
2762 on a platform that supports HP Ada 83, a higher degree of compatibility
2763 can be guaranteed, and in particular records are layed out in an identical
2764 manner in the two compilers. Note also that if output from two different
2765 compilers is mixed, the program is responsible for dealing with elaboration
2766 issues. Probably the safest approach is to write the main program in the
2767 version of Ada other than GNAT, so that it takes care of its own elaboration
2768 requirements, and then call the GNAT-generated adainit procedure to ensure
2769 elaboration of the GNAT components. Consult the documentation of the other
2770 Ada compiler for further details on elaboration.
2771
2772 However, it is not possible to mix the tasking run time of GNAT and
2773 HP Ada 83, All the tasking operations must either be entirely within
2774 GNAT compiled sections of the program, or entirely within HP Ada 83
2775 compiled sections of the program.
2776
2777 @cindex Interfacing to Assembly
2778 @cindex Convention Assembler
2779 @item Assembler
2780 Specifies assembler as the convention. In practice this has the
2781 same effect as convention Ada (but is not equivalent in the sense of being
2782 considered the same convention).
2783
2784 @cindex Convention Asm
2785 @findex Asm
2786 @item Asm
2787 Equivalent to Assembler.
2788
2789 @cindex Interfacing to COBOL
2790 @cindex Convention COBOL
2791 @findex COBOL
2792 @item COBOL
2793 Data will be passed according to the conventions described
2794 in section B.4 of the Ada Reference Manual.
2795
2796 @findex C
2797 @cindex Interfacing to C
2798 @cindex Convention C
2799 @item C
2800 Data will be passed according to the conventions described
2801 in section B.3 of the Ada Reference Manual.
2802
2803 A note on interfacing to a C ``varargs'' function:
2804 @findex C varargs function
2805 @cindex Interfacing to C varargs function
2806 @cindex varargs function interfaces
2807
2808 @itemize @bullet
2809 @item
2810 In C, @code{varargs} allows a function to take a variable number of
2811 arguments. There is no direct equivalent in this to Ada. One
2812 approach that can be used is to create a C wrapper for each
2813 different profile and then interface to this C wrapper. For
2814 example, to print an @code{int} value using @code{printf},
2815 create a C function @code{printfi} that takes two arguments, a
2816 pointer to a string and an int, and calls @code{printf}.
2817 Then in the Ada program, use pragma @code{Import} to
2818 interface to @code{printfi}.
2819
2820 @item
2821 It may work on some platforms to directly interface to
2822 a @code{varargs} function by providing a specific Ada profile
2823 for a particular call. However, this does not work on
2824 all platforms, since there is no guarantee that the
2825 calling sequence for a two argument normal C function
2826 is the same as for calling a @code{varargs} C function with
2827 the same two arguments.
2828 @end itemize
2829
2830 @cindex Convention Default
2831 @findex Default
2832 @item Default
2833 Equivalent to C.
2834
2835 @cindex Convention External
2836 @findex External
2837 @item External
2838 Equivalent to C.
2839
2840 @ifclear vms
2841 @findex C++
2842 @cindex Interfacing to C++
2843 @cindex Convention C++
2844 @item C_Plus_Plus (or CPP)
2845 This stands for C++. For most purposes this is identical to C.
2846 See the separate description of the specialized GNAT pragmas relating to
2847 C++ interfacing for further details.
2848 @end ifclear
2849
2850 @findex Fortran
2851 @cindex Interfacing to Fortran
2852 @cindex Convention Fortran
2853 @item Fortran
2854 Data will be passed according to the conventions described
2855 in section B.5 of the Ada Reference Manual.
2856
2857 @item Intrinsic
2858 This applies to an intrinsic operation, as defined in the Ada
2859 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2860 this means that the body of the subprogram is provided by the compiler itself,
2861 usually by means of an efficient code sequence, and that the user does not
2862 supply an explicit body for it. In an application program, the pragma may
2863 be applied to the following sets of names:
2864
2865 @itemize @bullet
2866 @item
2867 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2868 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2869 two formal parameters. The
2870 first one must be a signed integer type or a modular type with a binary
2871 modulus, and the second parameter must be of type Natural.
2872 The return type must be the same as the type of the first argument. The size
2873 of this type can only be 8, 16, 32, or 64.
2874
2875 @item
2876 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2877 The corresponding operator declaration must have parameters and result type
2878 that have the same root numeric type (for example, all three are long_float
2879 types). This simplifies the definition of operations that use type checking
2880 to perform dimensional checks:
2881
2882 @smallexample @c ada
2883 type Distance is new Long_Float;
2884 type Time is new Long_Float;
2885 type Velocity is new Long_Float;
2886 function "/" (D : Distance; T : Time)
2887 return Velocity;
2888 pragma Import (Intrinsic, "/");
2889 @end smallexample
2890
2891 @noindent
2892 This common idiom is often programmed with a generic definition and an
2893 explicit body. The pragma makes it simpler to introduce such declarations.
2894 It incurs no overhead in compilation time or code size, because it is
2895 implemented as a single machine instruction.
2896
2897 @item
2898 General subprogram entities, to bind an Ada subprogram declaration to
2899 a compiler builtin by name with back-ends where such interfaces are
2900 available. A typical example is the set of ``__builtin'' functions
2901 exposed by the GCC back-end, as in the following example:
2902
2903 @smallexample @c ada
2904 function builtin_sqrt (F : Float) return Float;
2905 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2906 @end smallexample
2907
2908 Most of the GCC builtins are accessible this way, and as for other
2909 import conventions (e.g. C), it is the user's responsibility to ensure
2910 that the Ada subprogram profile matches the underlying builtin
2911 expectations.
2912 @end itemize
2913
2914 @noindent
2915
2916 @ifset unw
2917 @findex Stdcall
2918 @cindex Convention Stdcall
2919 @item Stdcall
2920 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2921 and specifies that the @code{Stdcall} calling sequence will be used,
2922 as defined by the NT API. Nevertheless, to ease building
2923 cross-platform bindings this convention will be handled as a @code{C} calling
2924 convention on non-Windows platforms.
2925
2926 @findex DLL
2927 @cindex Convention DLL
2928 @item DLL
2929 This is equivalent to @code{Stdcall}.
2930
2931 @findex Win32
2932 @cindex Convention Win32
2933 @item Win32
2934 This is equivalent to @code{Stdcall}.
2935 @end ifset
2936
2937 @findex Stubbed
2938 @cindex Convention Stubbed
2939 @item Stubbed
2940 This is a special convention that indicates that the compiler
2941 should provide a stub body that raises @code{Program_Error}.
2942 @end table
2943
2944 @noindent
2945 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2946 that can be used to parametrize conventions and allow additional synonyms
2947 to be specified. For example if you have legacy code in which the convention
2948 identifier Fortran77 was used for Fortran, you can use the configuration
2949 pragma:
2950
2951 @smallexample @c ada
2952 pragma Convention_Identifier (Fortran77, Fortran);
2953 @end smallexample
2954
2955 @noindent
2956 And from now on the identifier Fortran77 may be used as a convention
2957 identifier (for example in an @code{Import} pragma) with the same
2958 meaning as Fortran.
2959
2960 @ifclear vms
2961 @node Building Mixed Ada & C++ Programs
2962 @section Building Mixed Ada and C++ Programs
2963
2964 @noindent
2965 A programmer inexperienced with mixed-language development may find that
2966 building an application containing both Ada and C++ code can be a
2967 challenge. This section gives a few
2968 hints that should make this task easier. The first section addresses
2969 the differences between interfacing with C and interfacing with C++.
2970 The second section
2971 looks into the delicate problem of linking the complete application from
2972 its Ada and C++ parts. The last section gives some hints on how the GNAT
2973 run-time library can be adapted in order to allow inter-language dispatching
2974 with a new C++ compiler.
2975
2976 @menu
2977 * Interfacing to C++::
2978 * Linking a Mixed C++ & Ada Program::
2979 * A Simple Example::
2980 * Interfacing with C++ constructors::
2981 * Interfacing with C++ at the Class Level::
2982 @end menu
2983
2984 @node Interfacing to C++
2985 @subsection Interfacing to C++
2986
2987 @noindent
2988 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2989 generating code that is compatible with the G++ Application Binary
2990 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2991
2992 @noindent
2993 Interfacing can be done at 3 levels: simple data, subprograms, and
2994 classes. In the first two cases, GNAT offers a specific @code{Convention
2995 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2996 Usually, C++ mangles the names of subprograms. To generate proper mangled
2997 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2998 This problem can also be addressed manually in two ways:
2999
3000 @itemize @bullet
3001 @item
3002 by modifying the C++ code in order to force a C convention using
3003 the @code{extern "C"} syntax.
3004
3005 @item
3006 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3007 Link_Name argument of the pragma import.
3008 @end itemize
3009
3010 @noindent
3011 Interfacing at the class level can be achieved by using the GNAT specific
3012 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3013 gnat_rm, GNAT Reference Manual}, for additional information.
3014
3015 @node Linking a Mixed C++ & Ada Program
3016 @subsection Linking a Mixed C++ & Ada Program
3017
3018 @noindent
3019 Usually the linker of the C++ development system must be used to link
3020 mixed applications because most C++ systems will resolve elaboration
3021 issues (such as calling constructors on global class instances)
3022 transparently during the link phase. GNAT has been adapted to ease the
3023 use of a foreign linker for the last phase. Three cases can be
3024 considered:
3025 @enumerate
3026
3027 @item
3028 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3029 The C++ linker can simply be called by using the C++ specific driver
3030 called @code{g++}.
3031
3032 Note that if the C++ code uses inline functions, you will need to
3033 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3034 order to provide an existing function implementation that the Ada code can
3035 link with.
3036
3037 @smallexample
3038 $ g++ -c -fkeep-inline-functions file1.C
3039 $ g++ -c -fkeep-inline-functions file2.C
3040 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3041 @end smallexample
3042
3043 @item
3044 Using GNAT and G++ from two different GCC installations: If both
3045 compilers are on the @env{PATH}, the previous method may be used. It is
3046 important to note that environment variables such as
3047 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3048 @env{GCC_ROOT} will affect both compilers
3049 at the same time and may make one of the two compilers operate
3050 improperly if set during invocation of the wrong compiler. It is also
3051 very important that the linker uses the proper @file{libgcc.a} GCC
3052 library -- that is, the one from the C++ compiler installation. The
3053 implicit link command as suggested in the @command{gnatmake} command
3054 from the former example can be replaced by an explicit link command with
3055 the full-verbosity option in order to verify which library is used:
3056 @smallexample
3057 $ gnatbind ada_unit
3058 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3059 @end smallexample
3060 If there is a problem due to interfering environment variables, it can
3061 be worked around by using an intermediate script. The following example
3062 shows the proper script to use when GNAT has not been installed at its
3063 default location and g++ has been installed at its default location:
3064
3065 @smallexample
3066 $ cat ./my_script
3067 #!/bin/sh
3068 unset BINUTILS_ROOT
3069 unset GCC_ROOT
3070 c++ $*
3071 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3072 @end smallexample
3073
3074 @item
3075 Using a non-GNU C++ compiler: The commands previously described can be
3076 used to insure that the C++ linker is used. Nonetheless, you need to add
3077 a few more parameters to the link command line, depending on the exception
3078 mechanism used.
3079
3080 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3081 to the libgcc libraries are required:
3082
3083 @smallexample
3084 $ cat ./my_script
3085 #!/bin/sh
3086 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3087 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3088 @end smallexample
3089
3090 Where CC is the name of the non-GNU C++ compiler.
3091
3092 If the @code{zero cost} exception mechanism is used, and the platform
3093 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3094 paths to more objects are required:
3095
3096 @smallexample
3097 $ cat ./my_script
3098 #!/bin/sh
3099 CC `gcc -print-file-name=crtbegin.o` $* \
3100 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3101 `gcc -print-file-name=crtend.o`
3102 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3103 @end smallexample
3104
3105 If the @code{zero cost} exception mechanism is used, and the platform
3106 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3107 Tru64 or AIX), the simple approach described above will not work and
3108 a pre-linking phase using GNAT will be necessary.
3109
3110 @end enumerate
3111
3112 Another alternative is to use the @command{gprbuild} multi-language builder
3113 which has a large knowledge base and knows how to link Ada and C++ code
3114 together automatically in most cases.
3115
3116 @node A Simple Example
3117 @subsection A Simple Example
3118 @noindent
3119 The following example, provided as part of the GNAT examples, shows how
3120 to achieve procedural interfacing between Ada and C++ in both
3121 directions. The C++ class A has two methods. The first method is exported
3122 to Ada by the means of an extern C wrapper function. The second method
3123 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3124 a limited record with a layout comparable to the C++ class. The Ada
3125 subprogram, in turn, calls the C++ method. So, starting from the C++
3126 main program, the process passes back and forth between the two
3127 languages.
3128
3129 @noindent
3130 Here are the compilation commands:
3131 @smallexample
3132 $ gnatmake -c simple_cpp_interface
3133 $ g++ -c cpp_main.C
3134 $ g++ -c ex7.C
3135 $ gnatbind -n simple_cpp_interface
3136 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3137 -lstdc++ ex7.o cpp_main.o
3138 @end smallexample
3139
3140 @noindent
3141 Here are the corresponding sources:
3142 @smallexample
3143
3144 //cpp_main.C
3145
3146 #include "ex7.h"
3147
3148 extern "C" @{
3149 void adainit (void);
3150 void adafinal (void);
3151 void method1 (A *t);
3152 @}
3153
3154 void method1 (A *t)
3155 @{
3156 t->method1 ();
3157 @}
3158
3159 int main ()
3160 @{
3161 A obj;
3162 adainit ();
3163 obj.method2 (3030);
3164 adafinal ();
3165 @}
3166
3167 //ex7.h
3168
3169 class Origin @{
3170 public:
3171 int o_value;
3172 @};
3173 class A : public Origin @{
3174 public:
3175 void method1 (void);
3176 void method2 (int v);
3177 A();
3178 int a_value;
3179 @};
3180
3181 //ex7.C
3182
3183 #include "ex7.h"
3184 #include <stdio.h>
3185
3186 extern "C" @{ void ada_method2 (A *t, int v);@}
3187
3188 void A::method1 (void)
3189 @{
3190 a_value = 2020;
3191 printf ("in A::method1, a_value = %d \n",a_value);
3192
3193 @}
3194
3195 void A::method2 (int v)
3196 @{
3197 ada_method2 (this, v);
3198 printf ("in A::method2, a_value = %d \n",a_value);
3199
3200 @}
3201
3202 A::A(void)
3203 @{
3204 a_value = 1010;
3205 printf ("in A::A, a_value = %d \n",a_value);
3206 @}
3207 @end smallexample
3208
3209 @smallexample @c ada
3210 -- Ada sources
3211 package body Simple_Cpp_Interface is
3212
3213 procedure Ada_Method2 (This : in out A; V : Integer) is
3214 begin
3215 Method1 (This);
3216 This.A_Value := V;
3217 end Ada_Method2;
3218
3219 end Simple_Cpp_Interface;
3220
3221 with System;
3222 package Simple_Cpp_Interface is
3223 type A is limited
3224 record
3225 Vptr : System.Address;
3226 O_Value : Integer;
3227 A_Value : Integer;
3228 end record;
3229 pragma Convention (C, A);
3230
3231 procedure Method1 (This : in out A);
3232 pragma Import (C, Method1);
3233
3234 procedure Ada_Method2 (This : in out A; V : Integer);
3235 pragma Export (C, Ada_Method2);
3236
3237 end Simple_Cpp_Interface;
3238 @end smallexample
3239
3240 @node Interfacing with C++ constructors
3241 @subsection Interfacing with C++ constructors
3242 @noindent
3243
3244 In order to interface with C++ constructors GNAT provides the
3245 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3246 gnat_rm, GNAT Reference Manual}, for additional information).
3247 In this section we present some common uses of C++ constructors
3248 in mixed-languages programs in GNAT.
3249
3250 Let us assume that we need to interface with the following
3251 C++ class:
3252
3253 @smallexample
3254 @b{class} Root @{
3255 @b{public}:
3256 int a_value;
3257 int b_value;
3258 @b{virtual} int Get_Value ();
3259 Root(); // Default constructor
3260 Root(int v); // 1st non-default constructor
3261 Root(int v, int w); // 2nd non-default constructor
3262 @};
3263 @end smallexample
3264
3265 For this purpose we can write the following package spec (further
3266 information on how to build this spec is available in
3267 @ref{Interfacing with C++ at the Class Level} and
3268 @ref{Generating Ada Bindings for C and C++ headers}).
3269
3270 @smallexample @c ada
3271 with Interfaces.C; use Interfaces.C;
3272 package Pkg_Root is
3273 type Root is tagged limited record
3274 A_Value : int;
3275 B_Value : int;
3276 end record;
3277 pragma Import (CPP, Root);
3278
3279 function Get_Value (Obj : Root) return int;
3280 pragma Import (CPP, Get_Value);
3281
3282 function Constructor return Root;
3283 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3284
3285 function Constructor (v : Integer) return Root;
3286 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3287
3288 function Constructor (v, w : Integer) return Root;
3289 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3290 end Pkg_Root;
3291 @end smallexample
3292
3293 On the Ada side the constructor is represented by a function (whose
3294 name is arbitrary) that returns the classwide type corresponding to
3295 the imported C++ class. Although the constructor is described as a
3296 function, it is typically a procedure with an extra implicit argument
3297 (the object being initialized) at the implementation level. GNAT
3298 issues the appropriate call, whatever it is, to get the object
3299 properly initialized.
3300
3301 Constructors can only appear in the following contexts:
3302
3303 @itemize @bullet
3304 @item
3305 On the right side of an initialization of an object of type @var{T}.
3306 @item
3307 On the right side of an initialization of a record component of type @var{T}.
3308 @item
3309 In an Ada 2005 limited aggregate.
3310 @item
3311 In an Ada 2005 nested limited aggregate.
3312 @item
3313 In an Ada 2005 limited aggregate that initializes an object built in
3314 place by an extended return statement.
3315 @end itemize
3316
3317 @noindent
3318 In a declaration of an object whose type is a class imported from C++,
3319 either the default C++ constructor is implicitly called by GNAT, or
3320 else the required C++ constructor must be explicitly called in the
3321 expression that initializes the object. For example:
3322
3323 @smallexample @c ada
3324 Obj1 : Root;
3325 Obj2 : Root := Constructor;
3326 Obj3 : Root := Constructor (v => 10);
3327 Obj4 : Root := Constructor (30, 40);
3328 @end smallexample
3329
3330 The first two declarations are equivalent: in both cases the default C++
3331 constructor is invoked (in the former case the call to the constructor is
3332 implicit, and in the latter case the call is explicit in the object
3333 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3334 that takes an integer argument, and @code{Obj4} is initialized by the
3335 non-default C++ constructor that takes two integers.
3336
3337 Let us derive the imported C++ class in the Ada side. For example:
3338
3339 @smallexample @c ada
3340 type DT is new Root with record
3341 C_Value : Natural := 2009;
3342 end record;
3343 @end smallexample
3344
3345 In this case the components DT inherited from the C++ side must be
3346 initialized by a C++ constructor, and the additional Ada components
3347 of type DT are initialized by GNAT. The initialization of such an
3348 object is done either by default, or by means of a function returning
3349 an aggregate of type DT, or by means of an extension aggregate.
3350
3351 @smallexample @c ada
3352 Obj5 : DT;
3353 Obj6 : DT := Function_Returning_DT (50);
3354 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3355 @end smallexample
3356
3357 The declaration of @code{Obj5} invokes the default constructors: the
3358 C++ default constructor of the parent type takes care of the initialization
3359 of the components inherited from Root, and GNAT takes care of the default
3360 initialization of the additional Ada components of type DT (that is,
3361 @code{C_Value} is initialized to value 2009). The order of invocation of
3362 the constructors is consistent with the order of elaboration required by
3363 Ada and C++. That is, the constructor of the parent type is always called
3364 before the constructor of the derived type.
3365
3366 Let us now consider a record that has components whose type is imported
3367 from C++. For example:
3368
3369 @smallexample @c ada
3370 type Rec1 is limited record
3371 Data1 : Root := Constructor (10);
3372 Value : Natural := 1000;
3373 end record;
3374
3375 type Rec2 (D : Integer := 20) is limited record
3376 Rec : Rec1;
3377 Data2 : Root := Constructor (D, 30);
3378 end record;
3379 @end smallexample
3380
3381 The initialization of an object of type @code{Rec2} will call the
3382 non-default C++ constructors specified for the imported components.
3383 For example:
3384
3385 @smallexample @c ada
3386 Obj8 : Rec2 (40);
3387 @end smallexample
3388
3389 Using Ada 2005 we can use limited aggregates to initialize an object
3390 invoking C++ constructors that differ from those specified in the type
3391 declarations. For example:
3392
3393 @smallexample @c ada
3394 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3395 others => <>),
3396 others => <>);
3397 @end smallexample
3398
3399 The above declaration uses an Ada 2005 limited aggregate to
3400 initialize @code{Obj9}, and the C++ constructor that has two integer
3401 arguments is invoked to initialize the @code{Data1} component instead
3402 of the constructor specified in the declaration of type @code{Rec1}. In
3403 Ada 2005 the box in the aggregate indicates that unspecified components
3404 are initialized using the expression (if any) available in the component
3405 declaration. That is, in this case discriminant @code{D} is initialized
3406 to value @code{20}, @code{Value} is initialized to value 1000, and the
3407 non-default C++ constructor that handles two integers takes care of
3408 initializing component @code{Data2} with values @code{20,30}.
3409
3410 In Ada 2005 we can use the extended return statement to build the Ada
3411 equivalent to C++ non-default constructors. For example:
3412
3413 @smallexample @c ada
3414 function Constructor (V : Integer) return Rec2 is
3415 begin
3416 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3417 others => <>),
3418 others => <>) do
3419 -- Further actions required for construction of
3420 -- objects of type Rec2
3421 ...
3422 end record;
3423 end Constructor;
3424 @end smallexample
3425
3426 In this example the extended return statement construct is used to
3427 build in place the returned object whose components are initialized
3428 by means of a limited aggregate. Any further action associated with
3429 the constructor can be placed inside the construct.
3430
3431 @node Interfacing with C++ at the Class Level
3432 @subsection Interfacing with C++ at the Class Level
3433 @noindent
3434 In this section we demonstrate the GNAT features for interfacing with
3435 C++ by means of an example making use of Ada 2005 abstract interface
3436 types. This example consists of a classification of animals; classes
3437 have been used to model our main classification of animals, and
3438 interfaces provide support for the management of secondary
3439 classifications. We first demonstrate a case in which the types and
3440 constructors are defined on the C++ side and imported from the Ada
3441 side, and latter the reverse case.
3442
3443 The root of our derivation will be the @code{Animal} class, with a
3444 single private attribute (the @code{Age} of the animal) and two public
3445 primitives to set and get the value of this attribute.
3446
3447 @smallexample
3448 @b{class} Animal @{
3449 @b{public}:
3450 @b{virtual} void Set_Age (int New_Age);
3451 @b{virtual} int Age ();
3452 @b{private}:
3453 int Age_Count;
3454 @};
3455 @end smallexample
3456
3457 Abstract interface types are defined in C++ by means of classes with pure
3458 virtual functions and no data members. In our example we will use two
3459 interfaces that provide support for the common management of @code{Carnivore}
3460 and @code{Domestic} animals:
3461
3462 @smallexample
3463 @b{class} Carnivore @{
3464 @b{public}:
3465 @b{virtual} int Number_Of_Teeth () = 0;
3466 @};
3467
3468 @b{class} Domestic @{
3469 @b{public}:
3470 @b{virtual void} Set_Owner (char* Name) = 0;
3471 @};
3472 @end smallexample
3473
3474 Using these declarations, we can now say that a @code{Dog} is an animal that is
3475 both Carnivore and Domestic, that is:
3476
3477 @smallexample
3478 @b{class} Dog : Animal, Carnivore, Domestic @{
3479 @b{public}:
3480 @b{virtual} int Number_Of_Teeth ();
3481 @b{virtual} void Set_Owner (char* Name);
3482
3483 Dog(); // Constructor
3484 @b{private}:
3485 int Tooth_Count;
3486 char *Owner;
3487 @};
3488 @end smallexample
3489
3490 In the following examples we will assume that the previous declarations are
3491 located in a file named @code{animals.h}. The following package demonstrates
3492 how to import these C++ declarations from the Ada side:
3493
3494 @smallexample @c ada
3495 with Interfaces.C.Strings; use Interfaces.C.Strings;
3496 package Animals is
3497 type Carnivore is interface;
3498 pragma Convention (C_Plus_Plus, Carnivore);
3499 function Number_Of_Teeth (X : Carnivore)
3500 return Natural is abstract;
3501
3502 type Domestic is interface;
3503 pragma Convention (C_Plus_Plus, Set_Owner);
3504 procedure Set_Owner
3505 (X : in out Domestic;
3506 Name : Chars_Ptr) is abstract;
3507
3508 type Animal is tagged record
3509 Age : Natural := 0;
3510 end record;
3511 pragma Import (C_Plus_Plus, Animal);
3512
3513 procedure Set_Age (X : in out Animal; Age : Integer);
3514 pragma Import (C_Plus_Plus, Set_Age);
3515
3516 function Age (X : Animal) return Integer;
3517 pragma Import (C_Plus_Plus, Age);
3518
3519 type Dog is new Animal and Carnivore and Domestic with record
3520 Tooth_Count : Natural;
3521 Owner : String (1 .. 30);
3522 end record;
3523 pragma Import (C_Plus_Plus, Dog);
3524
3525 function Number_Of_Teeth (A : Dog) return Integer;
3526 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3527
3528 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3529 pragma Import (C_Plus_Plus, Set_Owner);
3530
3531 function New_Dog return Dog;
3532 pragma CPP_Constructor (New_Dog);
3533 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3534 end Animals;
3535 @end smallexample
3536
3537 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3538 interfacing with these C++ classes is easy. The only requirement is that all
3539 the primitives and components must be declared exactly in the same order in
3540 the two languages.
3541
3542 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3543 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3544 the arguments to the called primitives will be the same as for C++. For the
3545 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3546 to indicate that they have been defined on the C++ side; this is required
3547 because the dispatch table associated with these tagged types will be built
3548 in the C++ side and therefore will not contain the predefined Ada primitives
3549 which Ada would otherwise expect.
3550
3551 As the reader can see there is no need to indicate the C++ mangled names
3552 associated with each subprogram because it is assumed that all the calls to
3553 these primitives will be dispatching calls. The only exception is the
3554 constructor, which must be registered with the compiler by means of
3555 @code{pragma CPP_Constructor} and needs to provide its associated C++
3556 mangled name because the Ada compiler generates direct calls to it.
3557
3558 With the above packages we can now declare objects of type Dog on the Ada side
3559 and dispatch calls to the corresponding subprograms on the C++ side. We can
3560 also extend the tagged type Dog with further fields and primitives, and
3561 override some of its C++ primitives on the Ada side. For example, here we have
3562 a type derivation defined on the Ada side that inherits all the dispatching
3563 primitives of the ancestor from the C++ side.
3564
3565 @smallexample
3566 @b{with} Animals; @b{use} Animals;
3567 @b{package} Vaccinated_Animals @b{is}
3568 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3569 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3570 @b{end} Vaccinated_Animals;
3571 @end smallexample
3572
3573 It is important to note that, because of the ABI compatibility, the programmer
3574 does not need to add any further information to indicate either the object
3575 layout or the dispatch table entry associated with each dispatching operation.
3576
3577 Now let us define all the types and constructors on the Ada side and export
3578 them to C++, using the same hierarchy of our previous example:
3579
3580 @smallexample @c ada
3581 with Interfaces.C.Strings;
3582 use Interfaces.C.Strings;
3583 package Animals is
3584 type Carnivore is interface;
3585 pragma Convention (C_Plus_Plus, Carnivore);
3586 function Number_Of_Teeth (X : Carnivore)
3587 return Natural is abstract;
3588
3589 type Domestic is interface;
3590 pragma Convention (C_Plus_Plus, Set_Owner);
3591 procedure Set_Owner
3592 (X : in out Domestic;
3593 Name : Chars_Ptr) is abstract;
3594
3595 type Animal is tagged record
3596 Age : Natural := 0;
3597 end record;
3598 pragma Convention (C_Plus_Plus, Animal);
3599
3600 procedure Set_Age (X : in out Animal; Age : Integer);
3601 pragma Export (C_Plus_Plus, Set_Age);
3602
3603 function Age (X : Animal) return Integer;
3604 pragma Export (C_Plus_Plus, Age);
3605
3606 type Dog is new Animal and Carnivore and Domestic with record
3607 Tooth_Count : Natural;
3608 Owner : String (1 .. 30);
3609 end record;
3610 pragma Convention (C_Plus_Plus, Dog);
3611
3612 function Number_Of_Teeth (A : Dog) return Integer;
3613 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3614
3615 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3616 pragma Export (C_Plus_Plus, Set_Owner);
3617
3618 function New_Dog return Dog'Class;
3619 pragma Export (C_Plus_Plus, New_Dog);
3620 end Animals;
3621 @end smallexample
3622
3623 Compared with our previous example the only difference is the use of
3624 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3625 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3626 nothing else to be done; as explained above, the only requirement is that all
3627 the primitives and components are declared in exactly the same order.
3628
3629 For completeness, let us see a brief C++ main program that uses the
3630 declarations available in @code{animals.h} (presented in our first example) to
3631 import and use the declarations from the Ada side, properly initializing and
3632 finalizing the Ada run-time system along the way:
3633
3634 @smallexample
3635 @b{#include} "animals.h"
3636 @b{#include} <iostream>
3637 @b{using namespace} std;
3638
3639 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3640 void Check_Domestic (Domestic *obj) @{@dots{}@}
3641 void Check_Animal (Animal *obj) @{@dots{}@}
3642 void Check_Dog (Dog *obj) @{@dots{}@}
3643
3644 @b{extern} "C" @{
3645 void adainit (void);
3646 void adafinal (void);
3647 Dog* new_dog ();
3648 @}
3649
3650 void test ()
3651 @{
3652 Dog *obj = new_dog(); // Ada constructor
3653 Check_Carnivore (obj); // Check secondary DT
3654 Check_Domestic (obj); // Check secondary DT
3655 Check_Animal (obj); // Check primary DT
3656 Check_Dog (obj); // Check primary DT
3657 @}
3658
3659 int main ()
3660 @{
3661 adainit (); test(); adafinal ();
3662 return 0;
3663 @}
3664 @end smallexample
3665
3666 @node Comparison between GNAT and C/C++ Compilation Models
3667 @section Comparison between GNAT and C/C++ Compilation Models
3668
3669 @noindent
3670 The GNAT model of compilation is close to the C and C++ models. You can
3671 think of Ada specs as corresponding to header files in C. As in C, you
3672 don't need to compile specs; they are compiled when they are used. The
3673 Ada @code{with} is similar in effect to the @code{#include} of a C
3674 header.
3675
3676 One notable difference is that, in Ada, you may compile specs separately
3677 to check them for semantic and syntactic accuracy. This is not always
3678 possible with C headers because they are fragments of programs that have
3679 less specific syntactic or semantic rules.
3680
3681 The other major difference is the requirement for running the binder,
3682 which performs two important functions. First, it checks for
3683 consistency. In C or C++, the only defense against assembling
3684 inconsistent programs lies outside the compiler, in a makefile, for
3685 example. The binder satisfies the Ada requirement that it be impossible
3686 to construct an inconsistent program when the compiler is used in normal
3687 mode.
3688
3689 @cindex Elaboration order control
3690 The other important function of the binder is to deal with elaboration
3691 issues. There are also elaboration issues in C++ that are handled
3692 automatically. This automatic handling has the advantage of being
3693 simpler to use, but the C++ programmer has no control over elaboration.
3694 Where @code{gnatbind} might complain there was no valid order of
3695 elaboration, a C++ compiler would simply construct a program that
3696 malfunctioned at run time.
3697 @end ifclear
3698
3699 @node Comparison between GNAT and Conventional Ada Library Models
3700 @section Comparison between GNAT and Conventional Ada Library Models
3701
3702 @noindent
3703 This section is intended for Ada programmers who have
3704 used an Ada compiler implementing the traditional Ada library
3705 model, as described in the Ada Reference Manual.
3706
3707 @cindex GNAT library
3708 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3709 source files themselves acts as the library. Compiling Ada programs does
3710 not generate any centralized information, but rather an object file and
3711 a ALI file, which are of interest only to the binder and linker.
3712 In a traditional system, the compiler reads information not only from
3713 the source file being compiled, but also from the centralized library.
3714 This means that the effect of a compilation depends on what has been
3715 previously compiled. In particular:
3716
3717 @itemize @bullet
3718 @item
3719 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3720 to the version of the unit most recently compiled into the library.
3721
3722 @item
3723 Inlining is effective only if the necessary body has already been
3724 compiled into the library.
3725
3726 @item
3727 Compiling a unit may obsolete other units in the library.
3728 @end itemize
3729
3730 @noindent
3731 In GNAT, compiling one unit never affects the compilation of any other
3732 units because the compiler reads only source files. Only changes to source
3733 files can affect the results of a compilation. In particular:
3734
3735 @itemize @bullet
3736 @item
3737 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3738 to the source version of the unit that is currently accessible to the
3739 compiler.
3740
3741 @item
3742 @cindex Inlining
3743 Inlining requires the appropriate source files for the package or
3744 subprogram bodies to be available to the compiler. Inlining is always
3745 effective, independent of the order in which units are complied.
3746
3747 @item
3748 Compiling a unit never affects any other compilations. The editing of
3749 sources may cause previous compilations to be out of date if they
3750 depended on the source file being modified.
3751 @end itemize
3752
3753 @noindent
3754 The most important result of these differences is that order of compilation
3755 is never significant in GNAT. There is no situation in which one is
3756 required to do one compilation before another. What shows up as order of
3757 compilation requirements in the traditional Ada library becomes, in
3758 GNAT, simple source dependencies; in other words, there is only a set
3759 of rules saying what source files must be present when a file is
3760 compiled.
3761
3762 @ifset vms
3763 @node Placement of temporary files
3764 @section Placement of temporary files
3765 @cindex Temporary files (user control over placement)
3766
3767 @noindent
3768 GNAT creates temporary files in the directory designated by the environment
3769 variable @env{TMPDIR}.
3770 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3771 for detailed information on how environment variables are resolved.
3772 For most users the easiest way to make use of this feature is to simply
3773 define @env{TMPDIR} as a job level logical name).
3774 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3775 for compiler temporary files, then you can include something like the
3776 following command in your @file{LOGIN.COM} file:
3777
3778 @smallexample
3779 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3780 @end smallexample
3781
3782 @noindent
3783 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3784 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3785 designated by @env{TEMP}.
3786 If none of these environment variables are defined then GNAT uses the
3787 directory designated by the logical name @code{SYS$SCRATCH:}
3788 (by default the user's home directory). If all else fails
3789 GNAT uses the current directory for temporary files.
3790 @end ifset
3791
3792 @c *************************
3793 @node Compiling Using gcc
3794 @chapter Compiling Using @command{gcc}
3795
3796 @noindent
3797 This chapter discusses how to compile Ada programs using the @command{gcc}
3798 command. It also describes the set of switches
3799 that can be used to control the behavior of the compiler.
3800 @menu
3801 * Compiling Programs::
3802 * Switches for gcc::
3803 * Search Paths and the Run-Time Library (RTL)::
3804 * Order of Compilation Issues::
3805 * Examples::
3806 @end menu
3807
3808 @node Compiling Programs
3809 @section Compiling Programs
3810
3811 @noindent
3812 The first step in creating an executable program is to compile the units
3813 of the program using the @command{gcc} command. You must compile the
3814 following files:
3815
3816 @itemize @bullet
3817 @item
3818 the body file (@file{.adb}) for a library level subprogram or generic
3819 subprogram
3820
3821 @item
3822 the spec file (@file{.ads}) for a library level package or generic
3823 package that has no body
3824
3825 @item
3826 the body file (@file{.adb}) for a library level package
3827 or generic package that has a body
3828
3829 @end itemize
3830
3831 @noindent
3832 You need @emph{not} compile the following files
3833
3834 @itemize @bullet
3835
3836 @item
3837 the spec of a library unit which has a body
3838
3839 @item
3840 subunits
3841 @end itemize
3842
3843 @noindent
3844 because they are compiled as part of compiling related units. GNAT
3845 package specs
3846 when the corresponding body is compiled, and subunits when the parent is
3847 compiled.
3848
3849 @cindex cannot generate code
3850 If you attempt to compile any of these files, you will get one of the
3851 following error messages (where @var{fff} is the name of the file you compiled):
3852
3853 @smallexample
3854 cannot generate code for file @var{fff} (package spec)
3855 to check package spec, use -gnatc
3856
3857 cannot generate code for file @var{fff} (missing subunits)
3858 to check parent unit, use -gnatc
3859
3860 cannot generate code for file @var{fff} (subprogram spec)
3861 to check subprogram spec, use -gnatc
3862
3863 cannot generate code for file @var{fff} (subunit)
3864 to check subunit, use -gnatc
3865 @end smallexample
3866
3867 @noindent
3868 As indicated by the above error messages, if you want to submit
3869 one of these files to the compiler to check for correct semantics
3870 without generating code, then use the @option{-gnatc} switch.
3871
3872 The basic command for compiling a file containing an Ada unit is
3873
3874 @smallexample
3875 $ gcc -c @ovar{switches} @file{file name}
3876 @end smallexample
3877
3878 @noindent
3879 where @var{file name} is the name of the Ada file (usually
3880 having an extension
3881 @file{.ads} for a spec or @file{.adb} for a body).
3882 @ifclear vms
3883 You specify the
3884 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3885 @end ifclear
3886 The result of a successful compilation is an object file, which has the
3887 same name as the source file but an extension of @file{.o} and an Ada
3888 Library Information (ALI) file, which also has the same name as the
3889 source file, but with @file{.ali} as the extension. GNAT creates these
3890 two output files in the current directory, but you may specify a source
3891 file in any directory using an absolute or relative path specification
3892 containing the directory information.
3893
3894 @findex gnat1
3895 @command{gcc} is actually a driver program that looks at the extensions of
3896 the file arguments and loads the appropriate compiler. For example, the
3897 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3898 These programs are in directories known to the driver program (in some
3899 configurations via environment variables you set), but need not be in
3900 your path. The @command{gcc} driver also calls the assembler and any other
3901 utilities needed to complete the generation of the required object
3902 files.
3903
3904 It is possible to supply several file names on the same @command{gcc}
3905 command. This causes @command{gcc} to call the appropriate compiler for
3906 each file. For example, the following command lists three separate
3907 files to be compiled:
3908
3909 @smallexample
3910 $ gcc -c x.adb y.adb z.c
3911 @end smallexample
3912
3913 @noindent
3914 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3915 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3916 The compiler generates three object files @file{x.o}, @file{y.o} and
3917 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3918 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3919 @ifclear vms
3920 except for
3921 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3922 @end ifclear
3923
3924 @node Switches for gcc
3925 @section Switches for @command{gcc}
3926
3927 @noindent
3928 The @command{gcc} command accepts switches that control the
3929 compilation process. These switches are fully described in this section.
3930 First we briefly list all the switches, in alphabetical order, then we
3931 describe the switches in more detail in functionally grouped sections.
3932
3933 More switches exist for GCC than those documented here, especially
3934 for specific targets. However, their use is not recommended as
3935 they may change code generation in ways that are incompatible with
3936 the Ada run-time library, or can cause inconsistencies between
3937 compilation units.
3938
3939 @menu
3940 * Output and Error Message Control::
3941 * Warning Message Control::
3942 * Debugging and Assertion Control::
3943 * Validity Checking::
3944 * Style Checking::
3945 * Run-Time Checks::
3946 * Using gcc for Syntax Checking::
3947 * Using gcc for Semantic Checking::
3948 * Compiling Different Versions of Ada::
3949 * Character Set Control::
3950 * File Naming Control::
3951 * Subprogram Inlining Control::
3952 * Auxiliary Output Control::
3953 * Debugging Control::
3954 * Exception Handling Control::
3955 * Units to Sources Mapping Files::
3956 * Integrated Preprocessing::
3957 * Code Generation Control::
3958 @ifset vms
3959 * Return Codes::
3960 @end ifset
3961 @end menu
3962
3963 @table @option
3964 @c !sort!
3965 @ifclear vms
3966 @cindex @option{-b} (@command{gcc})
3967 @item -b @var{target}
3968 Compile your program to run on @var{target}, which is the name of a
3969 system configuration. You must have a GNAT cross-compiler built if
3970 @var{target} is not the same as your host system.
3971
3972 @item -B@var{dir}
3973 @cindex @option{-B} (@command{gcc})
3974 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3975 from @var{dir} instead of the default location. Only use this switch
3976 when multiple versions of the GNAT compiler are available.
3977 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3978 GNU Compiler Collection (GCC)}, for further details. You would normally
3979 use the @option{-b} or @option{-V} switch instead.
3980
3981 @item -c
3982 @cindex @option{-c} (@command{gcc})
3983 Compile. Always use this switch when compiling Ada programs.
3984
3985 Note: for some other languages when using @command{gcc}, notably in
3986 the case of C and C++, it is possible to use
3987 use @command{gcc} without a @option{-c} switch to
3988 compile and link in one step. In the case of GNAT, you
3989 cannot use this approach, because the binder must be run
3990 and @command{gcc} cannot be used to run the GNAT binder.
3991 @end ifclear
3992
3993 @item -fno-inline
3994 @cindex @option{-fno-inline} (@command{gcc})
3995 Suppresses all back-end inlining, even if other optimization or inlining
3996 switches are set.
3997 This includes suppression of inlining that results
3998 from the use of the pragma @code{Inline_Always}.
3999 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4000 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4001 effect if this switch is present.
4002
4003 @item -fno-inline-functions
4004 @cindex @option{-fno-inline-functions} (@command{gcc})
4005 Suppresses automatic inlining of simple subprograms, which is enabled
4006 if @option{-O3} is used.
4007
4008 @item -fno-inline-small-functions
4009 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4010 Suppresses automatic inlining of small subprograms, which is enabled
4011 if @option{-O2} is used.
4012
4013 @item -fno-inline-functions-called-once
4014 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4015 Suppresses inlining of subprograms local to the unit and called once
4016 from within it, which is enabled if @option{-O1} is used.
4017
4018 @item -fno-ivopts
4019 @cindex @option{-fno-ivopts} (@command{gcc})
4020 Suppresses high-level loop induction variable optimizations, which are
4021 enabled if @option{-O1} is used. These optimizations are generally
4022 profitable but, for some specific cases of loops with numerous uses
4023 of the iteration variable that follow a common pattern, they may end
4024 up destroying the regularity that could be exploited at a lower level
4025 and thus producing inferior code.
4026
4027 @item -fno-strict-aliasing
4028 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4029 Causes the compiler to avoid assumptions regarding non-aliasing
4030 of objects of different types. See
4031 @ref{Optimization and Strict Aliasing} for details.
4032
4033 @item -fstack-check
4034 @cindex @option{-fstack-check} (@command{gcc})
4035 Activates stack checking.
4036 See @ref{Stack Overflow Checking} for details.
4037
4038 @item -fstack-usage
4039 @cindex @option{-fstack-usage} (@command{gcc})
4040 Makes the compiler output stack usage information for the program, on a
4041 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4042
4043 @item -fcallgraph-info@r{[}=su@r{]}
4044 @cindex @option{-fcallgraph-info} (@command{gcc})
4045 Makes the compiler output callgraph information for the program, on a
4046 per-file basis. The information is generated in the VCG format. It can
4047 be decorated with stack-usage per-node information.
4048
4049 @item ^-g^/DEBUG^
4050 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4051 Generate debugging information. This information is stored in the object
4052 file and copied from there to the final executable file by the linker,
4053 where it can be read by the debugger. You must use the
4054 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4055
4056 @item -gnat83
4057 @cindex @option{-gnat83} (@command{gcc})
4058 Enforce Ada 83 restrictions.
4059
4060 @item -gnat95
4061 @cindex @option{-gnat95} (@command{gcc})
4062 Enforce Ada 95 restrictions.
4063
4064 @item -gnat05
4065 @cindex @option{-gnat05} (@command{gcc})
4066 Allow full Ada 2005 features.
4067
4068 @item -gnata
4069 @cindex @option{-gnata} (@command{gcc})
4070 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4071 activated. Note that these pragmas can also be controlled using the
4072 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4073 It also activates pragmas @code{Check}, @code{Precondition}, and
4074 @code{Postcondition}. Note that these pragmas can also be controlled
4075 using the configuration pragma @code{Check_Policy}.
4076
4077 @item -gnatA
4078 @cindex @option{-gnatA} (@command{gcc})
4079 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4080 it will be ignored.
4081
4082 @item -gnatb
4083 @cindex @option{-gnatb} (@command{gcc})
4084 Generate brief messages to @file{stderr} even if verbose mode set.
4085
4086 @item -gnatB
4087 @cindex @option{-gnatB} (@command{gcc})
4088 Assume no invalid (bad) values except for 'Valid attribute use
4089 (@pxref{Validity Checking}).
4090
4091 @item -gnatc
4092 @cindex @option{-gnatc} (@command{gcc})
4093 Check syntax and semantics only (no code generation attempted).
4094
4095 @item -gnatC
4096 @cindex @option{-gnatC} (@command{gcc})
4097 Generate CodePeer information (no code generation attempted).
4098 This switch will generate an intermediate representation suitable for
4099 use by CodePeer (@file{.scil} files). This switch is not compatible with
4100 code generation (it will, among other things, disable some switches such
4101 as -gnatn, and enable others such as -gnata).
4102
4103 @item -gnatd
4104 @cindex @option{-gnatd} (@command{gcc})
4105 Specify debug options for the compiler. The string of characters after
4106 the @option{-gnatd} specify the specific debug options. The possible
4107 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4108 compiler source file @file{debug.adb} for details of the implemented
4109 debug options. Certain debug options are relevant to applications
4110 programmers, and these are documented at appropriate points in this
4111 users guide.
4112
4113 @ifclear vms
4114 @item -gnatD
4115 @cindex @option{-gnatD[nn]} (@command{gcc})
4116 @end ifclear
4117 @ifset vms
4118 @item /XDEBUG /LXDEBUG=nnn
4119 @end ifset
4120 Create expanded source files for source level debugging. This switch
4121 also suppress generation of cross-reference information
4122 (see @option{-gnatx}).
4123
4124 @item -gnatec=@var{path}
4125 @cindex @option{-gnatec} (@command{gcc})
4126 Specify a configuration pragma file
4127 @ifclear vms
4128 (the equal sign is optional)
4129 @end ifclear
4130 (@pxref{The Configuration Pragmas Files}).
4131
4132 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4133 @cindex @option{-gnateD} (@command{gcc})
4134 Defines a symbol, associated with @var{value}, for preprocessing.
4135 (@pxref{Integrated Preprocessing}).
4136
4137 @item -gnatef
4138 @cindex @option{-gnatef} (@command{gcc})
4139 Display full source path name in brief error messages.
4140
4141 @item -gnateG
4142 @cindex @option{-gnateG} (@command{gcc})
4143 Save result of preprocessing in a text file.
4144
4145 @item -gnatem=@var{path}
4146 @cindex @option{-gnatem} (@command{gcc})
4147 Specify a mapping file
4148 @ifclear vms
4149 (the equal sign is optional)
4150 @end ifclear
4151 (@pxref{Units to Sources Mapping Files}).
4152
4153 @item -gnatep=@var{file}
4154 @cindex @option{-gnatep} (@command{gcc})
4155 Specify a preprocessing data file
4156 @ifclear vms
4157 (the equal sign is optional)
4158 @end ifclear
4159 (@pxref{Integrated Preprocessing}).
4160
4161 @item -gnateS
4162 @cindex @option{-gnateS} (@command{gcc})
4163 Generate SCO (Source Coverage Obligation) information in the ALI
4164 file. This information is used by advanced coverage tools. See
4165 unit @file{SCOs} in the compiler sources for details in files
4166 @file{scos.ads} and @file{scos.adb}.
4167
4168 @item -gnatE
4169 @cindex @option{-gnatE} (@command{gcc})
4170 Full dynamic elaboration checks.
4171
4172 @item -gnatf
4173 @cindex @option{-gnatf} (@command{gcc})
4174 Full errors. Multiple errors per line, all undefined references, do not
4175 attempt to suppress cascaded errors.
4176
4177 @item -gnatF
4178 @cindex @option{-gnatF} (@command{gcc})
4179 Externals names are folded to all uppercase.
4180
4181 @item ^-gnatg^/GNAT_INTERNAL^
4182 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4183 Internal GNAT implementation mode. This should not be used for
4184 applications programs, it is intended only for use by the compiler
4185 and its run-time library. For documentation, see the GNAT sources.
4186 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4187 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4188 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4189 so that all standard warnings and all standard style options are turned on.
4190 All warnings and style error messages are treated as errors.
4191
4192 @ifclear vms
4193 @item -gnatG=nn
4194 @cindex @option{-gnatG[nn]} (@command{gcc})
4195 @end ifclear
4196 @ifset vms
4197 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4198 @end ifset
4199 List generated expanded code in source form.
4200
4201 @item ^-gnath^/HELP^
4202 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4203 Output usage information. The output is written to @file{stdout}.
4204
4205 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4206 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4207 Identifier character set
4208 @ifclear vms
4209 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4210 @end ifclear
4211 For details of the possible selections for @var{c},
4212 see @ref{Character Set Control}.
4213
4214 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4215 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4216 Ignore representation clauses. When this switch is used,
4217 representation clauses are treated as comments. This is useful
4218 when initially porting code where you want to ignore rep clause
4219 problems, and also for compiling foreign code (particularly
4220 for use with ASIS). The representation clauses that are ignored
4221 are: enumeration_representation_clause, record_representation_clause,
4222 and attribute_definition_clause for the following attributes:
4223 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4224 Object_Size, Size, Small, Stream_Size, and Value_Size.
4225 Note that this option should be used only for compiling -- the
4226 code is likely to malfunction at run time.
4227
4228 @item -gnatjnn
4229 @cindex @option{-gnatjnn} (@command{gcc})
4230 Reformat error messages to fit on nn character lines
4231
4232 @item -gnatk=@var{n}
4233 @cindex @option{-gnatk} (@command{gcc})
4234 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4235
4236 @item -gnatl
4237 @cindex @option{-gnatl} (@command{gcc})
4238 Output full source listing with embedded error messages.
4239
4240 @item -gnatL
4241 @cindex @option{-gnatL} (@command{gcc})
4242 Used in conjunction with -gnatG or -gnatD to intersperse original
4243 source lines (as comment lines with line numbers) in the expanded
4244 source output.
4245
4246 @item -gnatm=@var{n}
4247 @cindex @option{-gnatm} (@command{gcc})
4248 Limit number of detected error or warning messages to @var{n}
4249 where @var{n} is in the range 1..999999. The default setting if
4250 no switch is given is 9999. If the number of warnings reaches this
4251 limit, then a message is output and further warnings are suppressed,
4252 but the compilation is continued. If the number of error messages
4253 reaches this limit, then a message is output and the compilation
4254 is abandoned. The equal sign here is optional. A value of zero
4255 means that no limit applies.
4256
4257 @item -gnatn
4258 @cindex @option{-gnatn} (@command{gcc})
4259 Activate inlining for subprograms for which
4260 pragma @code{inline} is specified. This inlining is performed
4261 by the GCC back-end.
4262
4263 @item -gnatN
4264 @cindex @option{-gnatN} (@command{gcc})
4265 Activate front end inlining for subprograms for which
4266 pragma @code{Inline} is specified. This inlining is performed
4267 by the front end and will be visible in the
4268 @option{-gnatG} output.
4269
4270 When using a gcc-based back end (in practice this means using any version
4271 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4272 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4273 Historically front end inlining was more extensive than the gcc back end
4274 inlining, but that is no longer the case.
4275
4276 @item -gnato
4277 @cindex @option{-gnato} (@command{gcc})
4278 Enable numeric overflow checking (which is not normally enabled by
4279 default). Note that division by zero is a separate check that is not
4280 controlled by this switch (division by zero checking is on by default).
4281
4282 @item -gnatp
4283 @cindex @option{-gnatp} (@command{gcc})
4284 Suppress all checks. See @ref{Run-Time Checks} for details.
4285
4286 @item -gnatP
4287 @cindex @option{-gnatP} (@command{gcc})
4288 Enable polling. This is required on some systems (notably Windows NT) to
4289 obtain asynchronous abort and asynchronous transfer of control capability.
4290 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4291 details.
4292
4293 @item -gnatq
4294 @cindex @option{-gnatq} (@command{gcc})
4295 Don't quit. Try semantics, even if parse errors.
4296
4297 @item -gnatQ
4298 @cindex @option{-gnatQ} (@command{gcc})
4299 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4300
4301 @item -gnatr
4302 @cindex @option{-gnatr} (@command{gcc})
4303 Treat pragma Restrictions as Restriction_Warnings.
4304
4305 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4306 @cindex @option{-gnatR} (@command{gcc})
4307 Output representation information for declared types and objects.
4308
4309 @item -gnats
4310 @cindex @option{-gnats} (@command{gcc})
4311 Syntax check only.
4312
4313 @item -gnatS
4314 @cindex @option{-gnatS} (@command{gcc})
4315 Print package Standard.
4316
4317 @item -gnatt
4318 @cindex @option{-gnatt} (@command{gcc})
4319 Generate tree output file.
4320
4321 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4322 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4323 All compiler tables start at @var{nnn} times usual starting size.
4324
4325 @item -gnatu
4326 @cindex @option{-gnatu} (@command{gcc})
4327 List units for this compilation.
4328
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 Tag all error messages with the unique string ``error:''
4332
4333 @item -gnatv
4334 @cindex @option{-gnatv} (@command{gcc})
4335 Verbose mode. Full error output with source lines to @file{stdout}.
4336
4337 @item -gnatV
4338 @cindex @option{-gnatV} (@command{gcc})
4339 Control level of validity checking (@pxref{Validity Checking}).
4340
4341 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4342 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4343 Warning mode where
4344 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4345 the exact warnings that
4346 are enabled or disabled (@pxref{Warning Message Control}).
4347
4348 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4349 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4350 Wide character encoding method
4351 @ifclear vms
4352 (@var{e}=n/h/u/s/e/8).
4353 @end ifclear
4354 @ifset vms
4355 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4356 @end ifset
4357
4358 @item -gnatx
4359 @cindex @option{-gnatx} (@command{gcc})
4360 Suppress generation of cross-reference information.
4361
4362 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4363 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4364 Enable built-in style checks (@pxref{Style Checking}).
4365
4366 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4367 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4368 Distribution stub generation and compilation
4369 @ifclear vms
4370 (@var{m}=r/c for receiver/caller stubs).
4371 @end ifclear
4372 @ifset vms
4373 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4374 to be generated and compiled).
4375 @end ifset
4376
4377 @item ^-I^/SEARCH=^@var{dir}
4378 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4379 @cindex RTL
4380 Direct GNAT to search the @var{dir} directory for source files needed by
4381 the current compilation
4382 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4383
4384 @item ^-I-^/NOCURRENT_DIRECTORY^
4385 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4386 @cindex RTL
4387 Except for the source file named in the command line, do not look for source
4388 files in the directory containing the source file named in the command line
4389 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4390
4391 @ifclear vms
4392 @item -mbig-switch
4393 @cindex @option{-mbig-switch} (@command{gcc})
4394 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4395 This standard gcc switch causes the compiler to use larger offsets in its
4396 jump table representation for @code{case} statements.
4397 This may result in less efficient code, but is sometimes necessary
4398 (for example on HP-UX targets)
4399 @cindex HP-UX and @option{-mbig-switch} option
4400 in order to compile large and/or nested @code{case} statements.
4401
4402 @item -o @var{file}
4403 @cindex @option{-o} (@command{gcc})
4404 This switch is used in @command{gcc} to redirect the generated object file
4405 and its associated ALI file. Beware of this switch with GNAT, because it may
4406 cause the object file and ALI file to have different names which in turn
4407 may confuse the binder and the linker.
4408 @end ifclear
4409
4410 @item -nostdinc
4411 @cindex @option{-nostdinc} (@command{gcc})
4412 Inhibit the search of the default location for the GNAT Run Time
4413 Library (RTL) source files.
4414
4415 @item -nostdlib
4416 @cindex @option{-nostdlib} (@command{gcc})
4417 Inhibit the search of the default location for the GNAT Run Time
4418 Library (RTL) ALI files.
4419
4420 @ifclear vms
4421 @item -O@ovar{n}
4422 @cindex @option{-O} (@command{gcc})
4423 @var{n} controls the optimization level.
4424
4425 @table @asis
4426 @item n = 0
4427 No optimization, the default setting if no @option{-O} appears
4428
4429 @item n = 1
4430 Normal optimization, the default if you specify @option{-O} without
4431 an operand. A good compromise between code quality and compilation
4432 time.
4433
4434 @item n = 2
4435 Extensive optimization, may improve execution time, possibly at the cost of
4436 substantially increased compilation time.
4437
4438 @item n = 3
4439 Same as @option{-O2}, and also includes inline expansion for small subprograms
4440 in the same unit.
4441
4442 @item n = s
4443 Optimize space usage
4444 @end table
4445
4446 @noindent
4447 See also @ref{Optimization Levels}.
4448 @end ifclear
4449
4450 @ifset vms
4451 @item /NOOPTIMIZE
4452 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4453 Equivalent to @option{/OPTIMIZE=NONE}.
4454 This is the default behavior in the absence of an @option{/OPTIMIZE}
4455 qualifier.
4456
4457 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4458 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4459 Selects the level of optimization for your program. The supported
4460 keywords are as follows:
4461 @table @code
4462 @item ALL
4463 Perform most optimizations, including those that
4464 are expensive.
4465 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4466 without keyword options.
4467
4468 @item NONE
4469 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4470
4471 @item SOME
4472 Perform some optimizations, but omit ones that are costly.
4473
4474 @item DEVELOPMENT
4475 Same as @code{SOME}.
4476
4477 @item INLINING
4478 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4479 automatic inlining of small subprograms within a unit
4480
4481 @item UNROLL_LOOPS
4482 Try to unroll loops. This keyword may be specified together with
4483 any keyword above other than @code{NONE}. Loop unrolling
4484 usually, but not always, improves the performance of programs.
4485
4486 @item SPACE
4487 Optimize space usage
4488 @end table
4489
4490 @noindent
4491 See also @ref{Optimization Levels}.
4492 @end ifset
4493
4494 @ifclear vms
4495 @item -pass-exit-codes
4496 @cindex @option{-pass-exit-codes} (@command{gcc})
4497 Catch exit codes from the compiler and use the most meaningful as
4498 exit status.
4499 @end ifclear
4500
4501 @item --RTS=@var{rts-path}
4502 @cindex @option{--RTS} (@command{gcc})
4503 Specifies the default location of the runtime library. Same meaning as the
4504 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4505
4506 @item ^-S^/ASM^
4507 @cindex @option{^-S^/ASM^} (@command{gcc})
4508 ^Used in place of @option{-c} to^Used to^
4509 cause the assembler source file to be
4510 generated, using @file{^.s^.S^} as the extension,
4511 instead of the object file.
4512 This may be useful if you need to examine the generated assembly code.
4513
4514 @item ^-fverbose-asm^/VERBOSE_ASM^
4515 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4516 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4517 to cause the generated assembly code file to be annotated with variable
4518 names, making it significantly easier to follow.
4519
4520 @item ^-v^/VERBOSE^
4521 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4522 Show commands generated by the @command{gcc} driver. Normally used only for
4523 debugging purposes or if you need to be sure what version of the
4524 compiler you are executing.
4525
4526 @ifclear vms
4527 @item -V @var{ver}
4528 @cindex @option{-V} (@command{gcc})
4529 Execute @var{ver} version of the compiler. This is the @command{gcc}
4530 version, not the GNAT version.
4531 @end ifclear
4532
4533 @item ^-w^/NO_BACK_END_WARNINGS^
4534 @cindex @option{-w} (@command{gcc})
4535 Turn off warnings generated by the back end of the compiler. Use of
4536 this switch also causes the default for front end warnings to be set
4537 to suppress (as though @option{-gnatws} had appeared at the start of
4538 the options).
4539
4540 @end table
4541
4542 @ifclear vms
4543 @c Combining qualifiers does not work on VMS
4544 You may combine a sequence of GNAT switches into a single switch. For
4545 example, the combined switch
4546
4547 @cindex Combining GNAT switches
4548 @smallexample
4549 -gnatofi3
4550 @end smallexample
4551
4552 @noindent
4553 is equivalent to specifying the following sequence of switches:
4554
4555 @smallexample
4556 -gnato -gnatf -gnati3
4557 @end smallexample
4558 @end ifclear
4559
4560 @noindent
4561 The following restrictions apply to the combination of switches
4562 in this manner:
4563
4564 @itemize @bullet
4565 @item
4566 The switch @option{-gnatc} if combined with other switches must come
4567 first in the string.
4568
4569 @item
4570 The switch @option{-gnats} if combined with other switches must come
4571 first in the string.
4572
4573 @item
4574 The switches
4575 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4576 may not be combined with any other switches.
4577
4578 @ifclear vms
4579 @item
4580 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4581 switch), then all further characters in the switch are interpreted
4582 as style modifiers (see description of @option{-gnaty}).
4583
4584 @item
4585 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4586 switch), then all further characters in the switch are interpreted
4587 as debug flags (see description of @option{-gnatd}).
4588
4589 @item
4590 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4591 switch), then all further characters in the switch are interpreted
4592 as warning mode modifiers (see description of @option{-gnatw}).
4593
4594 @item
4595 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4596 switch), then all further characters in the switch are interpreted
4597 as validity checking options (@pxref{Validity Checking}).
4598 @end ifclear
4599 @end itemize
4600
4601 @node Output and Error Message Control
4602 @subsection Output and Error Message Control
4603 @findex stderr
4604
4605 @noindent
4606 The standard default format for error messages is called ``brief format''.
4607 Brief format messages are written to @file{stderr} (the standard error
4608 file) and have the following form:
4609
4610 @smallexample
4611 e.adb:3:04: Incorrect spelling of keyword "function"
4612 e.adb:4:20: ";" should be "is"
4613 @end smallexample
4614
4615 @noindent
4616 The first integer after the file name is the line number in the file,
4617 and the second integer is the column number within the line.
4618 @ifclear vms
4619 @code{GPS} can parse the error messages
4620 and point to the referenced character.
4621 @end ifclear
4622 The following switches provide control over the error message
4623 format:
4624
4625 @table @option
4626 @c !sort!
4627 @item -gnatv
4628 @cindex @option{-gnatv} (@command{gcc})
4629 @findex stdout
4630 @ifclear vms
4631 The v stands for verbose.
4632 @end ifclear
4633 The effect of this setting is to write long-format error
4634 messages to @file{stdout} (the standard output file.
4635 The same program compiled with the
4636 @option{-gnatv} switch would generate:
4637
4638 @smallexample
4639 @cartouche
4640 3. funcion X (Q : Integer)
4641 |
4642 >>> Incorrect spelling of keyword "function"
4643 4. return Integer;
4644 |
4645 >>> ";" should be "is"
4646 @end cartouche
4647 @end smallexample
4648
4649 @noindent
4650 The vertical bar indicates the location of the error, and the @samp{>>>}
4651 prefix can be used to search for error messages. When this switch is
4652 used the only source lines output are those with errors.
4653
4654 @item -gnatl
4655 @cindex @option{-gnatl} (@command{gcc})
4656 @ifclear vms
4657 The @code{l} stands for list.
4658 @end ifclear
4659 This switch causes a full listing of
4660 the file to be generated. In the case where a body is
4661 compiled, the corresponding spec is also listed, along
4662 with any subunits. Typical output from compiling a package
4663 body @file{p.adb} might look like:
4664
4665 @smallexample @c ada
4666 @cartouche
4667 Compiling: p.adb
4668
4669 1. package body p is
4670 2. procedure a;
4671 3. procedure a is separate;
4672 4. begin
4673 5. null
4674 |
4675 >>> missing ";"
4676
4677 6. end;
4678
4679 Compiling: p.ads
4680
4681 1. package p is
4682 2. pragma Elaborate_Body
4683 |
4684 >>> missing ";"
4685
4686 3. end p;
4687
4688 Compiling: p-a.adb
4689
4690 1. separate p
4691 |
4692 >>> missing "("
4693
4694 2. procedure a is
4695 3. begin
4696 4. null
4697 |
4698 >>> missing ";"
4699
4700 5. end;
4701 @end cartouche
4702 @end smallexample
4703
4704 @noindent
4705 @findex stderr
4706 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4707 standard output is redirected, a brief summary is written to
4708 @file{stderr} (standard error) giving the number of error messages and
4709 warning messages generated.
4710
4711 @item -^gnatl^OUTPUT_FILE^=file
4712 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4713 This has the same effect as @option{-gnatl} except that the output is
4714 written to a file instead of to standard output. If the given name
4715 @file{fname} does not start with a period, then it is the full name
4716 of the file to be written. If @file{fname} is an extension, it is
4717 appended to the name of the file being compiled. For example, if
4718 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4719 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4720
4721 @item -gnatU
4722 @cindex @option{-gnatU} (@command{gcc})
4723 This switch forces all error messages to be preceded by the unique
4724 string ``error:''. This means that error messages take a few more
4725 characters in space, but allows easy searching for and identification
4726 of error messages.
4727
4728 @item -gnatb
4729 @cindex @option{-gnatb} (@command{gcc})
4730 @ifclear vms
4731 The @code{b} stands for brief.
4732 @end ifclear
4733 This switch causes GNAT to generate the
4734 brief format error messages to @file{stderr} (the standard error
4735 file) as well as the verbose
4736 format message or full listing (which as usual is written to
4737 @file{stdout} (the standard output file).
4738
4739 @item -gnatm=@var{n}
4740 @cindex @option{-gnatm} (@command{gcc})
4741 @ifclear vms
4742 The @code{m} stands for maximum.
4743 @end ifclear
4744 @var{n} is a decimal integer in the
4745 range of 1 to 999999 and limits the number of error or warning
4746 messages to be generated. For example, using
4747 @option{-gnatm2} might yield
4748
4749 @smallexample
4750 e.adb:3:04: Incorrect spelling of keyword "function"
4751 e.adb:5:35: missing ".."
4752 fatal error: maximum number of errors detected
4753 compilation abandoned
4754 @end smallexample
4755
4756 @noindent
4757 The default setting if
4758 no switch is given is 9999. If the number of warnings reaches this
4759 limit, then a message is output and further warnings are suppressed,
4760 but the compilation is continued. If the number of error messages
4761 reaches this limit, then a message is output and the compilation
4762 is abandoned. A value of zero means that no limit applies.
4763
4764 @noindent
4765 Note that the equal sign is optional, so the switches
4766 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4767
4768 @item -gnatf
4769 @cindex @option{-gnatf} (@command{gcc})
4770 @cindex Error messages, suppressing
4771 @ifclear vms
4772 The @code{f} stands for full.
4773 @end ifclear
4774 Normally, the compiler suppresses error messages that are likely to be
4775 redundant. This switch causes all error
4776 messages to be generated. In particular, in the case of
4777 references to undefined variables. If a given variable is referenced
4778 several times, the normal format of messages is
4779 @smallexample
4780 e.adb:7:07: "V" is undefined (more references follow)
4781 @end smallexample
4782
4783 @noindent
4784 where the parenthetical comment warns that there are additional
4785 references to the variable @code{V}. Compiling the same program with the
4786 @option{-gnatf} switch yields
4787
4788 @smallexample
4789 e.adb:7:07: "V" is undefined
4790 e.adb:8:07: "V" is undefined
4791 e.adb:8:12: "V" is undefined
4792 e.adb:8:16: "V" is undefined
4793 e.adb:9:07: "V" is undefined
4794 e.adb:9:12: "V" is undefined
4795 @end smallexample
4796
4797 @noindent
4798 The @option{-gnatf} switch also generates additional information for
4799 some error messages. Some examples are:
4800
4801 @itemize @bullet
4802 @item
4803 Details on possibly non-portable unchecked conversion
4804 @item
4805 List possible interpretations for ambiguous calls
4806 @item
4807 Additional details on incorrect parameters
4808 @end itemize
4809
4810 @item -gnatjnn
4811 @cindex @option{-gnatjnn} (@command{gcc})
4812 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4813 with continuation lines are treated as though the continuation lines were
4814 separate messages (and so a warning with two continuation lines counts as
4815 three warnings, and is listed as three separate messages).
4816
4817 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4818 messages are output in a different manner. A message and all its continuation
4819 lines are treated as a unit, and count as only one warning or message in the
4820 statistics totals. Furthermore, the message is reformatted so that no line
4821 is longer than nn characters.
4822
4823 @item -gnatq
4824 @cindex @option{-gnatq} (@command{gcc})
4825 @ifclear vms
4826 The @code{q} stands for quit (really ``don't quit'').
4827 @end ifclear
4828 In normal operation mode, the compiler first parses the program and
4829 determines if there are any syntax errors. If there are, appropriate
4830 error messages are generated and compilation is immediately terminated.
4831 This switch tells
4832 GNAT to continue with semantic analysis even if syntax errors have been
4833 found. This may enable the detection of more errors in a single run. On
4834 the other hand, the semantic analyzer is more likely to encounter some
4835 internal fatal error when given a syntactically invalid tree.
4836
4837 @item -gnatQ
4838 @cindex @option{-gnatQ} (@command{gcc})
4839 In normal operation mode, the @file{ALI} file is not generated if any
4840 illegalities are detected in the program. The use of @option{-gnatQ} forces
4841 generation of the @file{ALI} file. This file is marked as being in
4842 error, so it cannot be used for binding purposes, but it does contain
4843 reasonably complete cross-reference information, and thus may be useful
4844 for use by tools (e.g., semantic browsing tools or integrated development
4845 environments) that are driven from the @file{ALI} file. This switch
4846 implies @option{-gnatq}, since the semantic phase must be run to get a
4847 meaningful ALI file.
4848
4849 In addition, if @option{-gnatt} is also specified, then the tree file is
4850 generated even if there are illegalities. It may be useful in this case
4851 to also specify @option{-gnatq} to ensure that full semantic processing
4852 occurs. The resulting tree file can be processed by ASIS, for the purpose
4853 of providing partial information about illegal units, but if the error
4854 causes the tree to be badly malformed, then ASIS may crash during the
4855 analysis.
4856
4857 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4858 being in error, @command{gnatmake} will attempt to recompile the source when it
4859 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4860
4861 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4862 since ALI files are never generated if @option{-gnats} is set.
4863
4864 @end table
4865
4866 @node Warning Message Control
4867 @subsection Warning Message Control
4868 @cindex Warning messages
4869 @noindent
4870 In addition to error messages, which correspond to illegalities as defined
4871 in the Ada Reference Manual, the compiler detects two kinds of warning
4872 situations.
4873
4874 First, the compiler considers some constructs suspicious and generates a
4875 warning message to alert you to a possible error. Second, if the
4876 compiler detects a situation that is sure to raise an exception at
4877 run time, it generates a warning message. The following shows an example
4878 of warning messages:
4879 @smallexample
4880 e.adb:4:24: warning: creation of object may raise Storage_Error
4881 e.adb:10:17: warning: static value out of range
4882 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4883 @end smallexample
4884
4885 @noindent
4886 GNAT considers a large number of situations as appropriate
4887 for the generation of warning messages. As always, warnings are not
4888 definite indications of errors. For example, if you do an out-of-range
4889 assignment with the deliberate intention of raising a
4890 @code{Constraint_Error} exception, then the warning that may be
4891 issued does not indicate an error. Some of the situations for which GNAT
4892 issues warnings (at least some of the time) are given in the following
4893 list. This list is not complete, and new warnings are often added to
4894 subsequent versions of GNAT. The list is intended to give a general idea
4895 of the kinds of warnings that are generated.
4896
4897 @itemize @bullet
4898 @item
4899 Possible infinitely recursive calls
4900
4901 @item
4902 Out-of-range values being assigned
4903
4904 @item
4905 Possible order of elaboration problems
4906
4907 @item
4908 Assertions (pragma Assert) that are sure to fail
4909
4910 @item
4911 Unreachable code
4912
4913 @item
4914 Address clauses with possibly unaligned values, or where an attempt is
4915 made to overlay a smaller variable with a larger one.
4916
4917 @item
4918 Fixed-point type declarations with a null range
4919
4920 @item
4921 Direct_IO or Sequential_IO instantiated with a type that has access values
4922
4923 @item
4924 Variables that are never assigned a value
4925
4926 @item
4927 Variables that are referenced before being initialized
4928
4929 @item
4930 Task entries with no corresponding @code{accept} statement
4931
4932 @item
4933 Duplicate accepts for the same task entry in a @code{select}
4934
4935 @item
4936 Objects that take too much storage
4937
4938 @item
4939 Unchecked conversion between types of differing sizes
4940
4941 @item
4942 Missing @code{return} statement along some execution path in a function
4943
4944 @item
4945 Incorrect (unrecognized) pragmas
4946
4947 @item
4948 Incorrect external names
4949
4950 @item
4951 Allocation from empty storage pool
4952
4953 @item
4954 Potentially blocking operation in protected type
4955
4956 @item
4957 Suspicious parenthesization of expressions
4958
4959 @item
4960 Mismatching bounds in an aggregate
4961
4962 @item
4963 Attempt to return local value by reference
4964
4965 @item
4966 Premature instantiation of a generic body
4967
4968 @item
4969 Attempt to pack aliased components
4970
4971 @item
4972 Out of bounds array subscripts
4973
4974 @item
4975 Wrong length on string assignment
4976
4977 @item
4978 Violations of style rules if style checking is enabled
4979
4980 @item
4981 Unused @code{with} clauses
4982
4983 @item
4984 @code{Bit_Order} usage that does not have any effect
4985
4986 @item
4987 @code{Standard.Duration} used to resolve universal fixed expression
4988
4989 @item
4990 Dereference of possibly null value
4991
4992 @item
4993 Declaration that is likely to cause storage error
4994
4995 @item
4996 Internal GNAT unit @code{with}'ed by application unit
4997
4998 @item
4999 Values known to be out of range at compile time
5000
5001 @item
5002 Unreferenced labels and variables
5003
5004 @item
5005 Address overlays that could clobber memory
5006
5007 @item
5008 Unexpected initialization when address clause present
5009
5010 @item
5011 Bad alignment for address clause
5012
5013 @item
5014 Useless type conversions
5015
5016 @item
5017 Redundant assignment statements and other redundant constructs
5018
5019 @item
5020 Useless exception handlers
5021
5022 @item
5023 Accidental hiding of name by child unit
5024
5025 @item
5026 Access before elaboration detected at compile time
5027
5028 @item
5029 A range in a @code{for} loop that is known to be null or might be null
5030
5031 @end itemize
5032
5033 @noindent
5034 The following section lists compiler switches that are available
5035 to control the handling of warning messages. It is also possible
5036 to exercise much finer control over what warnings are issued and
5037 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5038 gnat_rm, GNAT Reference manual}.
5039
5040 @table @option
5041 @c !sort!
5042 @item -gnatwa
5043 @emph{Activate all optional errors.}
5044 @cindex @option{-gnatwa} (@command{gcc})
5045 This switch activates most optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled. The warnings that are not turned on by this
5048 switch are
5049 @option{-gnatwd} (implicit dereferencing),
5050 @option{-gnatwh} (hiding),
5051 @option{-gnatwl} (elaboration warnings),
5052 @option{-gnatw.o} (warn on values set by out parameters ignored)
5053 and @option{-gnatwt} (tracking of deleted conditional code).
5054 All other optional warnings are turned on.
5055
5056 @item -gnatwA
5057 @emph{Suppress all optional errors.}
5058 @cindex @option{-gnatwA} (@command{gcc})
5059 This switch suppresses all optional warning messages, see remaining list
5060 in this section for details on optional warning messages that can be
5061 individually controlled.
5062
5063 @item -gnatw.a
5064 @emph{Activate warnings on failing assertions.}
5065 @cindex @option{-gnatw.a} (@command{gcc})
5066 @cindex Assert failures
5067 This switch activates warnings for assertions where the compiler can tell at
5068 compile time that the assertion will fail. Note that this warning is given
5069 even if assertions are disabled. The default is that such warnings are
5070 generated.
5071
5072 @item -gnatw.A
5073 @emph{Suppress warnings on failing assertions.}
5074 @cindex @option{-gnatw.A} (@command{gcc})
5075 @cindex Assert failures
5076 This switch suppresses warnings for assertions where the compiler can tell at
5077 compile time that the assertion will fail.
5078
5079 @item -gnatwb
5080 @emph{Activate warnings on bad fixed values.}
5081 @cindex @option{-gnatwb} (@command{gcc})
5082 @cindex Bad fixed values
5083 @cindex Fixed-point Small value
5084 @cindex Small value
5085 This switch activates warnings for static fixed-point expressions whose
5086 value is not an exact multiple of Small. Such values are implementation
5087 dependent, since an implementation is free to choose either of the multiples
5088 that surround the value. GNAT always chooses the closer one, but this is not
5089 required behavior, and it is better to specify a value that is an exact
5090 multiple, ensuring predictable execution. The default is that such warnings
5091 are not generated.
5092
5093 @item -gnatwB
5094 @emph{Suppress warnings on bad fixed values.}
5095 @cindex @option{-gnatwB} (@command{gcc})
5096 This switch suppresses warnings for static fixed-point expressions whose
5097 value is not an exact multiple of Small.
5098
5099 @item -gnatw.b
5100 @emph{Activate warnings on biased representation.}
5101 @cindex @option{-gnatw.b} (@command{gcc})
5102 @cindex Biased representation
5103 This switch activates warnings when a size clause, value size clause, component
5104 clause, or component size clause forces the use of biased representation for an
5105 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5106 to represent 10/11). The default is that such warnings are generated.
5107
5108 @item -gnatw.B
5109 @emph{Suppress warnings on biased representation.}
5110 @cindex @option{-gnatwB} (@command{gcc})
5111 This switch suppresses warnings for representation clauses that force the use
5112 of biased representation.
5113
5114 @item -gnatwc
5115 @emph{Activate warnings on conditionals.}
5116 @cindex @option{-gnatwc} (@command{gcc})
5117 @cindex Conditionals, constant
5118 This switch activates warnings for conditional expressions used in
5119 tests that are known to be True or False at compile time. The default
5120 is that such warnings are not generated.
5121 Note that this warning does
5122 not get issued for the use of boolean variables or constants whose
5123 values are known at compile time, since this is a standard technique
5124 for conditional compilation in Ada, and this would generate too many
5125 false positive warnings.
5126
5127 This warning option also activates a special test for comparisons using
5128 the operators ``>='' and`` <=''.
5129 If the compiler can tell that only the equality condition is possible,
5130 then it will warn that the ``>'' or ``<'' part of the test
5131 is useless and that the operator could be replaced by ``=''.
5132 An example would be comparing a @code{Natural} variable <= 0.
5133
5134 This warning option also generates warnings if
5135 one or both tests is optimized away in a membership test for integer
5136 values if the result can be determined at compile time. Range tests on
5137 enumeration types are not included, since it is common for such tests
5138 to include an end point.
5139
5140 This warning can also be turned on using @option{-gnatwa}.
5141
5142 @item -gnatwC
5143 @emph{Suppress warnings on conditionals.}
5144 @cindex @option{-gnatwC} (@command{gcc})
5145 This switch suppresses warnings for conditional expressions used in
5146 tests that are known to be True or False at compile time.
5147
5148 @item -gnatw.c
5149 @emph{Activate warnings on missing component clauses.}
5150 @cindex @option{-gnatw.c} (@command{gcc})
5151 @cindex Component clause, missing
5152 This switch activates warnings for record components where a record
5153 representation clause is present and has component clauses for the
5154 majority, but not all, of the components. A warning is given for each
5155 component for which no component clause is present.
5156
5157 This warning can also be turned on using @option{-gnatwa}.
5158
5159 @item -gnatw.C
5160 @emph{Suppress warnings on missing component clauses.}
5161 @cindex @option{-gnatwC} (@command{gcc})
5162 This switch suppresses warnings for record components that are
5163 missing a component clause in the situation described above.
5164
5165 @item -gnatwd
5166 @emph{Activate warnings on implicit dereferencing.}
5167 @cindex @option{-gnatwd} (@command{gcc})
5168 If this switch is set, then the use of a prefix of an access type
5169 in an indexed component, slice, or selected component without an
5170 explicit @code{.all} will generate a warning. With this warning
5171 enabled, access checks occur only at points where an explicit
5172 @code{.all} appears in the source code (assuming no warnings are
5173 generated as a result of this switch). The default is that such
5174 warnings are not generated.
5175 Note that @option{-gnatwa} does not affect the setting of
5176 this warning option.
5177
5178 @item -gnatwD
5179 @emph{Suppress warnings on implicit dereferencing.}
5180 @cindex @option{-gnatwD} (@command{gcc})
5181 @cindex Implicit dereferencing
5182 @cindex Dereferencing, implicit
5183 This switch suppresses warnings for implicit dereferences in
5184 indexed components, slices, and selected components.
5185
5186 @item -gnatwe
5187 @emph{Treat warnings as errors.}
5188 @cindex @option{-gnatwe} (@command{gcc})
5189 @cindex Warnings, treat as error
5190 This switch causes warning messages to be treated as errors.
5191 The warning string still appears, but the warning messages are counted
5192 as errors, and prevent the generation of an object file.
5193
5194 @item -gnatw.e
5195 @emph{Activate every optional warning}
5196 @cindex @option{-gnatw.e} (@command{gcc})
5197 @cindex Warnings, activate every optional warning
5198 This switch activates all optional warnings, including those which
5199 are not activated by @code{-gnatwa}.
5200
5201 @item -gnatwf
5202 @emph{Activate warnings on unreferenced formals.}
5203 @cindex @option{-gnatwf} (@command{gcc})
5204 @cindex Formals, unreferenced
5205 This switch causes a warning to be generated if a formal parameter
5206 is not referenced in the body of the subprogram. This warning can
5207 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5208 default is that these warnings are not generated.
5209
5210 @item -gnatwF
5211 @emph{Suppress warnings on unreferenced formals.}
5212 @cindex @option{-gnatwF} (@command{gcc})
5213 This switch suppresses warnings for unreferenced formal
5214 parameters. Note that the
5215 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5216 effect of warning on unreferenced entities other than subprogram
5217 formals.
5218
5219 @item -gnatwg
5220 @emph{Activate warnings on unrecognized pragmas.}
5221 @cindex @option{-gnatwg} (@command{gcc})
5222 @cindex Pragmas, unrecognized
5223 This switch causes a warning to be generated if an unrecognized
5224 pragma is encountered. Apart from issuing this warning, the
5225 pragma is ignored and has no effect. This warning can
5226 also be turned on using @option{-gnatwa}. The default
5227 is that such warnings are issued (satisfying the Ada Reference
5228 Manual requirement that such warnings appear).
5229
5230 @item -gnatwG
5231 @emph{Suppress warnings on unrecognized pragmas.}
5232 @cindex @option{-gnatwG} (@command{gcc})
5233 This switch suppresses warnings for unrecognized pragmas.
5234
5235 @item -gnatwh
5236 @emph{Activate warnings on hiding.}
5237 @cindex @option{-gnatwh} (@command{gcc})
5238 @cindex Hiding of Declarations
5239 This switch activates warnings on hiding declarations.
5240 A declaration is considered hiding
5241 if it is for a non-overloadable entity, and it declares an entity with the
5242 same name as some other entity that is directly or use-visible. The default
5243 is that such warnings are not generated.
5244 Note that @option{-gnatwa} does not affect the setting of this warning option.
5245
5246 @item -gnatwH
5247 @emph{Suppress warnings on hiding.}
5248 @cindex @option{-gnatwH} (@command{gcc})
5249 This switch suppresses warnings on hiding declarations.
5250
5251 @item -gnatwi
5252 @emph{Activate warnings on implementation units.}
5253 @cindex @option{-gnatwi} (@command{gcc})
5254 This switch activates warnings for a @code{with} of an internal GNAT
5255 implementation unit, defined as any unit from the @code{Ada},
5256 @code{Interfaces}, @code{GNAT},
5257 ^^@code{DEC},^ or @code{System}
5258 hierarchies that is not
5259 documented in either the Ada Reference Manual or the GNAT
5260 Programmer's Reference Manual. Such units are intended only
5261 for internal implementation purposes and should not be @code{with}'ed
5262 by user programs. The default is that such warnings are generated
5263 This warning can also be turned on using @option{-gnatwa}.
5264
5265 @item -gnatwI
5266 @emph{Disable warnings on implementation units.}
5267 @cindex @option{-gnatwI} (@command{gcc})
5268 This switch disables warnings for a @code{with} of an internal GNAT
5269 implementation unit.
5270
5271 @item -gnatw.i
5272 @emph{Activate warnings on overlapping actuals.}
5273 @cindex @option{-gnatw.i} (@command{gcc})
5274 This switch enables a warning on statically detectable overlapping actuals in
5275 a subprogram call, when one of the actuals is an in-out parameter, and the
5276 types of the actuals are not by-copy types. The warning is off by default,
5277 and is not included under -gnatwa.
5278
5279 @item -gnatw.I
5280 @emph{Disable warnings on overlapping actuals.}
5281 @cindex @option{-gnatw.I} (@command{gcc})
5282 This switch disables warnings on overlapping actuals in a call..
5283
5284 @item -gnatwj
5285 @emph{Activate warnings on obsolescent features (Annex J).}
5286 @cindex @option{-gnatwj} (@command{gcc})
5287 @cindex Features, obsolescent
5288 @cindex Obsolescent features
5289 If this warning option is activated, then warnings are generated for
5290 calls to subprograms marked with @code{pragma Obsolescent} and
5291 for use of features in Annex J of the Ada Reference Manual. In the
5292 case of Annex J, not all features are flagged. In particular use
5293 of the renamed packages (like @code{Text_IO}) and use of package
5294 @code{ASCII} are not flagged, since these are very common and
5295 would generate many annoying positive warnings. The default is that
5296 such warnings are not generated. This warning is also turned on by
5297 the use of @option{-gnatwa}.
5298
5299 In addition to the above cases, warnings are also generated for
5300 GNAT features that have been provided in past versions but which
5301 have been superseded (typically by features in the new Ada standard).
5302 For example, @code{pragma Ravenscar} will be flagged since its
5303 function is replaced by @code{pragma Profile(Ravenscar)}.
5304
5305 Note that this warning option functions differently from the
5306 restriction @code{No_Obsolescent_Features} in two respects.
5307 First, the restriction applies only to annex J features.
5308 Second, the restriction does flag uses of package @code{ASCII}.
5309
5310 @item -gnatwJ
5311 @emph{Suppress warnings on obsolescent features (Annex J).}
5312 @cindex @option{-gnatwJ} (@command{gcc})
5313 This switch disables warnings on use of obsolescent features.
5314
5315 @item -gnatwk
5316 @emph{Activate warnings on variables that could be constants.}
5317 @cindex @option{-gnatwk} (@command{gcc})
5318 This switch activates warnings for variables that are initialized but
5319 never modified, and then could be declared constants. The default is that
5320 such warnings are not given.
5321 This warning can also be turned on using @option{-gnatwa}.
5322
5323 @item -gnatwK
5324 @emph{Suppress warnings on variables that could be constants.}
5325 @cindex @option{-gnatwK} (@command{gcc})
5326 This switch disables warnings on variables that could be declared constants.
5327
5328 @item -gnatwl
5329 @emph{Activate warnings for elaboration pragmas.}
5330 @cindex @option{-gnatwl} (@command{gcc})
5331 @cindex Elaboration, warnings
5332 This switch activates warnings on missing
5333 @code{Elaborate_All} and @code{Elaborate} pragmas.
5334 See the section in this guide on elaboration checking for details on
5335 when such pragmas should be used. In dynamic elaboration mode, this switch
5336 generations warnings about the need to add elaboration pragmas. Note however,
5337 that if you blindly follow these warnings, and add @code{Elaborate_All}
5338 warnings wherever they are recommended, you basically end up with the
5339 equivalent of the static elaboration model, which may not be what you want for
5340 legacy code for which the static model does not work.
5341
5342 For the static model, the messages generated are labeled "info:" (for
5343 information messages). They are not warnings to add elaboration pragmas,
5344 merely informational messages showing what implicit elaboration pragmas
5345 have been added, for use in analyzing elaboration circularity problems.
5346
5347 Warnings are also generated if you
5348 are using the static mode of elaboration, and a @code{pragma Elaborate}
5349 is encountered. The default is that such warnings
5350 are not generated.
5351 This warning is not automatically turned on by the use of @option{-gnatwa}.
5352
5353 @item -gnatwL
5354 @emph{Suppress warnings for elaboration pragmas.}
5355 @cindex @option{-gnatwL} (@command{gcc})
5356 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5357 See the section in this guide on elaboration checking for details on
5358 when such pragmas should be used.
5359
5360 @item -gnatwm
5361 @emph{Activate warnings on modified but unreferenced variables.}
5362 @cindex @option{-gnatwm} (@command{gcc})
5363 This switch activates warnings for variables that are assigned (using
5364 an initialization value or with one or more assignment statements) but
5365 whose value is never read. The warning is suppressed for volatile
5366 variables and also for variables that are renamings of other variables
5367 or for which an address clause is given.
5368 This warning can also be turned on using @option{-gnatwa}.
5369 The default is that these warnings are not given.
5370
5371 @item -gnatwM
5372 @emph{Disable warnings on modified but unreferenced variables.}
5373 @cindex @option{-gnatwM} (@command{gcc})
5374 This switch disables warnings for variables that are assigned or
5375 initialized, but never read.
5376
5377 @item -gnatw.m
5378 @emph{Activate warnings on suspicious modulus values.}
5379 @cindex @option{-gnatw.m} (@command{gcc})
5380 This switch activates warnings for modulus values that seem suspicious.
5381 The cases caught are where the size is the same as the modulus (e.g.
5382 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5383 with no size clause. The guess in both cases is that 2**x was intended
5384 rather than x. The default is that these warnings are given.
5385
5386 @item -gnatw.M
5387 @emph{Disable warnings on suspicious modulus values.}
5388 @cindex @option{-gnatw.M} (@command{gcc})
5389 This switch disables warnings for suspicious modulus values.
5390
5391 @item -gnatwn
5392 @emph{Set normal warnings mode.}
5393 @cindex @option{-gnatwn} (@command{gcc})
5394 This switch sets normal warning mode, in which enabled warnings are
5395 issued and treated as warnings rather than errors. This is the default
5396 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5397 an explicit @option{-gnatws} or
5398 @option{-gnatwe}. It also cancels the effect of the
5399 implicit @option{-gnatwe} that is activated by the
5400 use of @option{-gnatg}.
5401
5402 @item -gnatwo
5403 @emph{Activate warnings on address clause overlays.}
5404 @cindex @option{-gnatwo} (@command{gcc})
5405 @cindex Address Clauses, warnings
5406 This switch activates warnings for possibly unintended initialization
5407 effects of defining address clauses that cause one variable to overlap
5408 another. The default is that such warnings are generated.
5409 This warning can also be turned on using @option{-gnatwa}.
5410
5411 @item -gnatwO
5412 @emph{Suppress warnings on address clause overlays.}
5413 @cindex @option{-gnatwO} (@command{gcc})
5414 This switch suppresses warnings on possibly unintended initialization
5415 effects of defining address clauses that cause one variable to overlap
5416 another.
5417
5418 @item -gnatw.o
5419 @emph{Activate warnings on modified but unreferenced out parameters.}
5420 @cindex @option{-gnatw.o} (@command{gcc})
5421 This switch activates warnings for variables that are modified by using
5422 them as actuals for a call to a procedure with an out mode formal, where
5423 the resulting assigned value is never read. It is applicable in the case
5424 where there is more than one out mode formal. If there is only one out
5425 mode formal, the warning is issued by default (controlled by -gnatwu).
5426 The warning is suppressed for volatile
5427 variables and also for variables that are renamings of other variables
5428 or for which an address clause is given.
5429 The default is that these warnings are not given. Note that this warning
5430 is not included in -gnatwa, it must be activated explicitly.
5431
5432 @item -gnatw.O
5433 @emph{Disable warnings on modified but unreferenced out parameters.}
5434 @cindex @option{-gnatw.O} (@command{gcc})
5435 This switch suppresses warnings for variables that are modified by using
5436 them as actuals for a call to a procedure with an out mode formal, where
5437 the resulting assigned value is never read.
5438
5439 @item -gnatwp
5440 @emph{Activate warnings on ineffective pragma Inlines.}
5441 @cindex @option{-gnatwp} (@command{gcc})
5442 @cindex Inlining, warnings
5443 This switch activates warnings for failure of front end inlining
5444 (activated by @option{-gnatN}) to inline a particular call. There are
5445 many reasons for not being able to inline a call, including most
5446 commonly that the call is too complex to inline. The default is
5447 that such warnings are not given.
5448 This warning can also be turned on using @option{-gnatwa}.
5449 Warnings on ineffective inlining by the gcc back-end can be activated
5450 separately, using the gcc switch -Winline.
5451
5452 @item -gnatwP
5453 @emph{Suppress warnings on ineffective pragma Inlines.}
5454 @cindex @option{-gnatwP} (@command{gcc})
5455 This switch suppresses warnings on ineffective pragma Inlines. If the
5456 inlining mechanism cannot inline a call, it will simply ignore the
5457 request silently.
5458
5459 @item -gnatw.p
5460 @emph{Activate warnings on parameter ordering.}
5461 @cindex @option{-gnatw.p} (@command{gcc})
5462 @cindex Parameter order, warnings
5463 This switch activates warnings for cases of suspicious parameter
5464 ordering when the list of arguments are all simple identifiers that
5465 match the names of the formals, but are in a different order. The
5466 warning is suppressed if any use of named parameter notation is used,
5467 so this is the appropriate way to suppress a false positive (and
5468 serves to emphasize that the "misordering" is deliberate). The
5469 default is
5470 that such warnings are not given.
5471 This warning can also be turned on using @option{-gnatwa}.
5472
5473 @item -gnatw.P
5474 @emph{Suppress warnings on parameter ordering.}
5475 @cindex @option{-gnatw.P} (@command{gcc})
5476 This switch suppresses warnings on cases of suspicious parameter
5477 ordering.
5478
5479 @item -gnatwq
5480 @emph{Activate warnings on questionable missing parentheses.}
5481 @cindex @option{-gnatwq} (@command{gcc})
5482 @cindex Parentheses, warnings
5483 This switch activates warnings for cases where parentheses are not used and
5484 the result is potential ambiguity from a readers point of view. For example
5485 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5486 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5487 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5488 follow the rule of always parenthesizing to make the association clear, and
5489 this warning switch warns if such parentheses are not present. The default
5490 is that these warnings are given.
5491 This warning can also be turned on using @option{-gnatwa}.
5492
5493 @item -gnatwQ
5494 @emph{Suppress warnings on questionable missing parentheses.}
5495 @cindex @option{-gnatwQ} (@command{gcc})
5496 This switch suppresses warnings for cases where the association is not
5497 clear and the use of parentheses is preferred.
5498
5499 @item -gnatwr
5500 @emph{Activate warnings on redundant constructs.}
5501 @cindex @option{-gnatwr} (@command{gcc})
5502 This switch activates warnings for redundant constructs. The following
5503 is the current list of constructs regarded as redundant:
5504
5505 @itemize @bullet
5506 @item
5507 Assignment of an item to itself.
5508 @item
5509 Type conversion that converts an expression to its own type.
5510 @item
5511 Use of the attribute @code{Base} where @code{typ'Base} is the same
5512 as @code{typ}.
5513 @item
5514 Use of pragma @code{Pack} when all components are placed by a record
5515 representation clause.
5516 @item
5517 Exception handler containing only a reraise statement (raise with no
5518 operand) which has no effect.
5519 @item
5520 Use of the operator abs on an operand that is known at compile time
5521 to be non-negative
5522 @item
5523 Comparison of boolean expressions to an explicit True value.
5524 @end itemize
5525
5526 This warning can also be turned on using @option{-gnatwa}.
5527 The default is that warnings for redundant constructs are not given.
5528
5529 @item -gnatwR
5530 @emph{Suppress warnings on redundant constructs.}
5531 @cindex @option{-gnatwR} (@command{gcc})
5532 This switch suppresses warnings for redundant constructs.
5533
5534 @item -gnatw.r
5535 @emph{Activate warnings for object renaming function.}
5536 @cindex @option{-gnatw.r} (@command{gcc})
5537 This switch activates warnings for an object renaming that renames a
5538 function call, which is equivalent to a constant declaration (as
5539 opposed to renaming the function itself). The default is that these
5540 warnings are given. This warning can also be turned on using
5541 @option{-gnatwa}.
5542
5543 @item -gnatw.R
5544 @emph{Suppress warnings for object renaming function.}
5545 @cindex @option{-gnatwT} (@command{gcc})
5546 This switch suppresses warnings for object renaming function.
5547
5548 @item -gnatws
5549 @emph{Suppress all warnings.}
5550 @cindex @option{-gnatws} (@command{gcc})
5551 This switch completely suppresses the
5552 output of all warning messages from the GNAT front end.
5553 Note that it does not suppress warnings from the @command{gcc} back end.
5554 To suppress these back end warnings as well, use the switch @option{-w}
5555 in addition to @option{-gnatws}.
5556
5557 @item -gnatwt
5558 @emph{Activate warnings for tracking of deleted conditional code.}
5559 @cindex @option{-gnatwt} (@command{gcc})
5560 @cindex Deactivated code, warnings
5561 @cindex Deleted code, warnings
5562 This switch activates warnings for tracking of code in conditionals (IF and
5563 CASE statements) that is detected to be dead code which cannot be executed, and
5564 which is removed by the front end. This warning is off by default, and is not
5565 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5566 useful for detecting deactivated code in certified applications.
5567
5568 @item -gnatwT
5569 @emph{Suppress warnings for tracking of deleted conditional code.}
5570 @cindex @option{-gnatwT} (@command{gcc})
5571 This switch suppresses warnings for tracking of deleted conditional code.
5572
5573 @item -gnatwu
5574 @emph{Activate warnings on unused entities.}
5575 @cindex @option{-gnatwu} (@command{gcc})
5576 This switch activates warnings to be generated for entities that
5577 are declared but not referenced, and for units that are @code{with}'ed
5578 and not
5579 referenced. In the case of packages, a warning is also generated if
5580 no entities in the package are referenced. This means that if the package
5581 is referenced but the only references are in @code{use}
5582 clauses or @code{renames}
5583 declarations, a warning is still generated. A warning is also generated
5584 for a generic package that is @code{with}'ed but never instantiated.
5585 In the case where a package or subprogram body is compiled, and there
5586 is a @code{with} on the corresponding spec
5587 that is only referenced in the body,
5588 a warning is also generated, noting that the
5589 @code{with} can be moved to the body. The default is that
5590 such warnings are not generated.
5591 This switch also activates warnings on unreferenced formals
5592 (it includes the effect of @option{-gnatwf}).
5593 This warning can also be turned on using @option{-gnatwa}.
5594
5595 @item -gnatwU
5596 @emph{Suppress warnings on unused entities.}
5597 @cindex @option{-gnatwU} (@command{gcc})
5598 This switch suppresses warnings for unused entities and packages.
5599 It also turns off warnings on unreferenced formals (and thus includes
5600 the effect of @option{-gnatwF}).
5601
5602 @item -gnatwv
5603 @emph{Activate warnings on unassigned variables.}
5604 @cindex @option{-gnatwv} (@command{gcc})
5605 @cindex Unassigned variable warnings
5606 This switch activates warnings for access to variables which
5607 may not be properly initialized. The default is that
5608 such warnings are generated.
5609 This warning can also be turned on using @option{-gnatwa}.
5610
5611 @item -gnatwV
5612 @emph{Suppress warnings on unassigned variables.}
5613 @cindex @option{-gnatwV} (@command{gcc})
5614 This switch suppresses warnings for access to variables which
5615 may not be properly initialized.
5616 For variables of a composite type, the warning can also be suppressed in
5617 Ada 2005 by using a default initialization with a box. For example, if
5618 Table is an array of records whose components are only partially uninitialized,
5619 then the following code:
5620
5621 @smallexample @c ada
5622 Tab : Table := (others => <>);
5623 @end smallexample
5624
5625 will suppress warnings on subsequent statements that access components
5626 of variable Tab.
5627
5628 @item -gnatww
5629 @emph{Activate warnings on wrong low bound assumption.}
5630 @cindex @option{-gnatww} (@command{gcc})
5631 @cindex String indexing warnings
5632 This switch activates warnings for indexing an unconstrained string parameter
5633 with a literal or S'Length. This is a case where the code is assuming that the
5634 low bound is one, which is in general not true (for example when a slice is
5635 passed). The default is that such warnings are generated.
5636 This warning can also be turned on using @option{-gnatwa}.
5637
5638 @item -gnatwW
5639 @emph{Suppress warnings on wrong low bound assumption.}
5640 @cindex @option{-gnatwW} (@command{gcc})
5641 This switch suppresses warnings for indexing an unconstrained string parameter
5642 with a literal or S'Length. Note that this warning can also be suppressed
5643 in a particular case by adding an
5644 assertion that the lower bound is 1,
5645 as shown in the following example.
5646
5647 @smallexample @c ada
5648 procedure K (S : String) is
5649 pragma Assert (S'First = 1);
5650 @dots{}
5651 @end smallexample
5652
5653 @item -gnatw.w
5654 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5655 @cindex @option{-gnatw.w} (@command{gcc})
5656 @cindex Warnings Off control
5657 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5658 where either the pragma is entirely useless (because it suppresses no
5659 warnings), or it could be replaced by @code{pragma Unreferenced} or
5660 @code{pragma Unmodified}.The default is that these warnings are not given.
5661 Note that this warning is not included in -gnatwa, it must be
5662 activated explicitly.
5663
5664 @item -gnatw.W
5665 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5666 @cindex @option{-gnatw.W} (@command{gcc})
5667 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5668
5669 @item -gnatwx
5670 @emph{Activate warnings on Export/Import pragmas.}
5671 @cindex @option{-gnatwx} (@command{gcc})
5672 @cindex Export/Import pragma warnings
5673 This switch activates warnings on Export/Import pragmas when
5674 the compiler detects a possible conflict between the Ada and
5675 foreign language calling sequences. For example, the use of
5676 default parameters in a convention C procedure is dubious
5677 because the C compiler cannot supply the proper default, so
5678 a warning is issued. The default is that such warnings are
5679 generated.
5680 This warning can also be turned on using @option{-gnatwa}.
5681
5682 @item -gnatwX
5683 @emph{Suppress warnings on Export/Import pragmas.}
5684 @cindex @option{-gnatwX} (@command{gcc})
5685 This switch suppresses warnings on Export/Import pragmas.
5686 The sense of this is that you are telling the compiler that
5687 you know what you are doing in writing the pragma, and it
5688 should not complain at you.
5689
5690 @item -gnatw.x
5691 @emph{Activate warnings for No_Exception_Propagation mode.}
5692 @cindex @option{-gnatwm} (@command{gcc})
5693 This switch activates warnings for exception usage when pragma Restrictions
5694 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5695 explicit exception raises which are not covered by a local handler, and for
5696 exception handlers which do not cover a local raise. The default is that these
5697 warnings are not given.
5698
5699 @item -gnatw.X
5700 @emph{Disable warnings for No_Exception_Propagation mode.}
5701 This switch disables warnings for exception usage when pragma Restrictions
5702 (No_Exception_Propagation) is in effect.
5703
5704 @item -gnatwy
5705 @emph{Activate warnings for Ada 2005 compatibility issues.}
5706 @cindex @option{-gnatwy} (@command{gcc})
5707 @cindex Ada 2005 compatibility issues warnings
5708 For the most part Ada 2005 is upwards compatible with Ada 95,
5709 but there are some exceptions (for example the fact that
5710 @code{interface} is now a reserved word in Ada 2005). This
5711 switch activates several warnings to help in identifying
5712 and correcting such incompatibilities. The default is that
5713 these warnings are generated. Note that at one point Ada 2005
5714 was called Ada 0Y, hence the choice of character.
5715 This warning can also be turned on using @option{-gnatwa}.
5716
5717 @item -gnatwY
5718 @emph{Disable warnings for Ada 2005 compatibility issues.}
5719 @cindex @option{-gnatwY} (@command{gcc})
5720 @cindex Ada 2005 compatibility issues warnings
5721 This switch suppresses several warnings intended to help in identifying
5722 incompatibilities between Ada 95 and Ada 2005.
5723
5724 @item -gnatwz
5725 @emph{Activate warnings on unchecked conversions.}
5726 @cindex @option{-gnatwz} (@command{gcc})
5727 @cindex Unchecked_Conversion warnings
5728 This switch activates warnings for unchecked conversions
5729 where the types are known at compile time to have different
5730 sizes. The default
5731 is that such warnings are generated. Warnings are also
5732 generated for subprogram pointers with different conventions,
5733 and, on VMS only, for data pointers with different conventions.
5734 This warning can also be turned on using @option{-gnatwa}.
5735
5736 @item -gnatwZ
5737 @emph{Suppress warnings on unchecked conversions.}
5738 @cindex @option{-gnatwZ} (@command{gcc})
5739 This switch suppresses warnings for unchecked conversions
5740 where the types are known at compile time to have different
5741 sizes or conventions.
5742
5743 @item ^-Wunused^WARNINGS=UNUSED^
5744 @cindex @option{-Wunused}
5745 The warnings controlled by the @option{-gnatw} switch are generated by
5746 the front end of the compiler. The @option{GCC} back end can provide
5747 additional warnings and they are controlled by the @option{-W} switch.
5748 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5749 warnings for entities that are declared but not referenced.
5750
5751 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5752 @cindex @option{-Wuninitialized}
5753 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5754 the back end warning for uninitialized variables. This switch must be
5755 used in conjunction with an optimization level greater than zero.
5756
5757 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5758 @cindex @option{-Wall}
5759 This switch enables all the above warnings from the @option{GCC} back end.
5760 The code generator detects a number of warning situations that are missed
5761 by the @option{GNAT} front end, and this switch can be used to activate them.
5762 The use of this switch also sets the default front end warning mode to
5763 @option{-gnatwa}, that is, most front end warnings activated as well.
5764
5765 @item ^-w^/NO_BACK_END_WARNINGS^
5766 @cindex @option{-w}
5767 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5768 The use of this switch also sets the default front end warning mode to
5769 @option{-gnatws}, that is, front end warnings suppressed as well.
5770
5771 @end table
5772
5773 @noindent
5774 @ifclear vms
5775 A string of warning parameters can be used in the same parameter. For example:
5776
5777 @smallexample
5778 -gnatwaLe
5779 @end smallexample
5780
5781 @noindent
5782 will turn on all optional warnings except for elaboration pragma warnings,
5783 and also specify that warnings should be treated as errors.
5784 @end ifclear
5785 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5786
5787 @table @option
5788 @c !sort!
5789 @item -gnatwC
5790 @item -gnatwD
5791 @item -gnatwF
5792 @item -gnatwg
5793 @item -gnatwH
5794 @item -gnatwi
5795 @item -gnatwJ
5796 @item -gnatwK
5797 @item -gnatwL
5798 @item -gnatwM
5799 @item -gnatwn
5800 @item -gnatwo
5801 @item -gnatwP
5802 @item -gnatwR
5803 @item -gnatwU
5804 @item -gnatwv
5805 @item -gnatwz
5806 @item -gnatwx
5807
5808 @end table
5809
5810 @node Debugging and Assertion Control
5811 @subsection Debugging and Assertion Control
5812
5813 @table @option
5814 @item -gnata
5815 @cindex @option{-gnata} (@command{gcc})
5816 @findex Assert
5817 @findex Debug
5818 @cindex Assertions
5819
5820 @noindent
5821 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5822 are ignored. This switch, where @samp{a} stands for assert, causes
5823 @code{Assert} and @code{Debug} pragmas to be activated.
5824
5825 The pragmas have the form:
5826
5827 @smallexample
5828 @cartouche
5829 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5830 @var{static-string-expression}@r{]})
5831 @b{pragma} Debug (@var{procedure call})
5832 @end cartouche
5833 @end smallexample
5834
5835 @noindent
5836 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5837 If the result is @code{True}, the pragma has no effect (other than
5838 possible side effects from evaluating the expression). If the result is
5839 @code{False}, the exception @code{Assert_Failure} declared in the package
5840 @code{System.Assertions} is
5841 raised (passing @var{static-string-expression}, if present, as the
5842 message associated with the exception). If no string expression is
5843 given the default is a string giving the file name and line number
5844 of the pragma.
5845
5846 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5847 @code{pragma Debug} may appear within a declaration sequence, allowing
5848 debugging procedures to be called between declarations.
5849
5850 @ifset vms
5851 @item /DEBUG@r{[}=debug-level@r{]}
5852 @itemx /NODEBUG
5853 Specifies how much debugging information is to be included in
5854 the resulting object file where 'debug-level' is one of the following:
5855 @table @code
5856 @item TRACEBACK
5857 Include both debugger symbol records and traceback
5858 the object file.
5859 This is the default setting.
5860 @item ALL
5861 Include both debugger symbol records and traceback in
5862 object file.
5863 @item NONE
5864 Excludes both debugger symbol records and traceback
5865 the object file. Same as /NODEBUG.
5866 @item SYMBOLS
5867 Includes only debugger symbol records in the object
5868 file. Note that this doesn't include traceback information.
5869 @end table
5870 @end ifset
5871 @end table
5872
5873 @node Validity Checking
5874 @subsection Validity Checking
5875 @findex Validity Checking
5876
5877 @noindent
5878 The Ada Reference Manual defines the concept of invalid values (see
5879 RM 13.9.1). The primary source of invalid values is uninitialized
5880 variables. A scalar variable that is left uninitialized may contain
5881 an invalid value; the concept of invalid does not apply to access or
5882 composite types.
5883
5884 It is an error to read an invalid value, but the RM does not require
5885 run-time checks to detect such errors, except for some minimal
5886 checking to prevent erroneous execution (i.e. unpredictable
5887 behavior). This corresponds to the @option{-gnatVd} switch below,
5888 which is the default. For example, by default, if the expression of a
5889 case statement is invalid, it will raise Constraint_Error rather than
5890 causing a wild jump, and if an array index on the left-hand side of an
5891 assignment is invalid, it will raise Constraint_Error rather than
5892 overwriting an arbitrary memory location.
5893
5894 The @option{-gnatVa} may be used to enable additional validity checks,
5895 which are not required by the RM. These checks are often very
5896 expensive (which is why the RM does not require them). These checks
5897 are useful in tracking down uninitialized variables, but they are
5898 not usually recommended for production builds.
5899
5900 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5901 control; you can enable whichever validity checks you desire. However,
5902 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5903 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5904 sufficient for non-debugging use.
5905
5906 The @option{-gnatB} switch tells the compiler to assume that all
5907 values are valid (that is, within their declared subtype range)
5908 except in the context of a use of the Valid attribute. This means
5909 the compiler can generate more efficient code, since the range
5910 of values is better known at compile time. However, an uninitialized
5911 variable can cause wild jumps and memory corruption in this mode.
5912
5913 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5914 checking mode as described below.
5915 @ifclear vms
5916 The @code{x} argument is a string of letters that
5917 indicate validity checks that are performed or not performed in addition
5918 to the default checks required by Ada as described above.
5919 @end ifclear
5920 @ifset vms
5921 The options allowed for this qualifier
5922 indicate validity checks that are performed or not performed in addition
5923 to the default checks required by Ada as described above.
5924 @end ifset
5925
5926 @table @option
5927 @c !sort!
5928 @item -gnatVa
5929 @emph{All validity checks.}
5930 @cindex @option{-gnatVa} (@command{gcc})
5931 All validity checks are turned on.
5932 @ifclear vms
5933 That is, @option{-gnatVa} is
5934 equivalent to @option{gnatVcdfimorst}.
5935 @end ifclear
5936
5937 @item -gnatVc
5938 @emph{Validity checks for copies.}
5939 @cindex @option{-gnatVc} (@command{gcc})
5940 The right hand side of assignments, and the initializing values of
5941 object declarations are validity checked.
5942
5943 @item -gnatVd
5944 @emph{Default (RM) validity checks.}
5945 @cindex @option{-gnatVd} (@command{gcc})
5946 Some validity checks are done by default following normal Ada semantics
5947 (RM 13.9.1 (9-11)).
5948 A check is done in case statements that the expression is within the range
5949 of the subtype. If it is not, Constraint_Error is raised.
5950 For assignments to array components, a check is done that the expression used
5951 as index is within the range. If it is not, Constraint_Error is raised.
5952 Both these validity checks may be turned off using switch @option{-gnatVD}.
5953 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5954 switch @option{-gnatVd} will leave the checks turned on.
5955 Switch @option{-gnatVD} should be used only if you are sure that all such
5956 expressions have valid values. If you use this switch and invalid values
5957 are present, then the program is erroneous, and wild jumps or memory
5958 overwriting may occur.
5959
5960 @item -gnatVe
5961 @emph{Validity checks for elementary components.}
5962 @cindex @option{-gnatVe} (@command{gcc})
5963 In the absence of this switch, assignments to record or array components are
5964 not validity checked, even if validity checks for assignments generally
5965 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5966 require valid data, but assignment of individual components does. So for
5967 example, there is a difference between copying the elements of an array with a
5968 slice assignment, compared to assigning element by element in a loop. This
5969 switch allows you to turn off validity checking for components, even when they
5970 are assigned component by component.
5971
5972 @item -gnatVf
5973 @emph{Validity checks for floating-point values.}
5974 @cindex @option{-gnatVf} (@command{gcc})
5975 In the absence of this switch, validity checking occurs only for discrete
5976 values. If @option{-gnatVf} is specified, then validity checking also applies
5977 for floating-point values, and NaNs and infinities are considered invalid,
5978 as well as out of range values for constrained types. Note that this means
5979 that standard IEEE infinity mode is not allowed. The exact contexts
5980 in which floating-point values are checked depends on the setting of other
5981 options. For example,
5982 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5983 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5984 (the order does not matter) specifies that floating-point parameters of mode
5985 @code{in} should be validity checked.
5986
5987 @item -gnatVi
5988 @emph{Validity checks for @code{in} mode parameters}
5989 @cindex @option{-gnatVi} (@command{gcc})
5990 Arguments for parameters of mode @code{in} are validity checked in function
5991 and procedure calls at the point of call.
5992
5993 @item -gnatVm
5994 @emph{Validity checks for @code{in out} mode parameters.}
5995 @cindex @option{-gnatVm} (@command{gcc})
5996 Arguments for parameters of mode @code{in out} are validity checked in
5997 procedure calls at the point of call. The @code{'m'} here stands for
5998 modify, since this concerns parameters that can be modified by the call.
5999 Note that there is no specific option to test @code{out} parameters,
6000 but any reference within the subprogram will be tested in the usual
6001 manner, and if an invalid value is copied back, any reference to it
6002 will be subject to validity checking.
6003
6004 @item -gnatVn
6005 @emph{No validity checks.}
6006 @cindex @option{-gnatVn} (@command{gcc})
6007 This switch turns off all validity checking, including the default checking
6008 for case statements and left hand side subscripts. Note that the use of
6009 the switch @option{-gnatp} suppresses all run-time checks, including
6010 validity checks, and thus implies @option{-gnatVn}. When this switch
6011 is used, it cancels any other @option{-gnatV} previously issued.
6012
6013 @item -gnatVo
6014 @emph{Validity checks for operator and attribute operands.}
6015 @cindex @option{-gnatVo} (@command{gcc})
6016 Arguments for predefined operators and attributes are validity checked.
6017 This includes all operators in package @code{Standard},
6018 the shift operators defined as intrinsic in package @code{Interfaces}
6019 and operands for attributes such as @code{Pos}. Checks are also made
6020 on individual component values for composite comparisons, and on the
6021 expressions in type conversions and qualified expressions. Checks are
6022 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6023
6024 @item -gnatVp
6025 @emph{Validity checks for parameters.}
6026 @cindex @option{-gnatVp} (@command{gcc})
6027 This controls the treatment of parameters within a subprogram (as opposed
6028 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6029 of parameters on a call. If either of these call options is used, then
6030 normally an assumption is made within a subprogram that the input arguments
6031 have been validity checking at the point of call, and do not need checking
6032 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6033 is not made, and parameters are not assumed to be valid, so their validity
6034 will be checked (or rechecked) within the subprogram.
6035
6036 @item -gnatVr
6037 @emph{Validity checks for function returns.}
6038 @cindex @option{-gnatVr} (@command{gcc})
6039 The expression in @code{return} statements in functions is validity
6040 checked.
6041
6042 @item -gnatVs
6043 @emph{Validity checks for subscripts.}
6044 @cindex @option{-gnatVs} (@command{gcc})
6045 All subscripts expressions are checked for validity, whether they appear
6046 on the right side or left side (in default mode only left side subscripts
6047 are validity checked).
6048
6049 @item -gnatVt
6050 @emph{Validity checks for tests.}
6051 @cindex @option{-gnatVt} (@command{gcc})
6052 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6053 statements are checked, as well as guard expressions in entry calls.
6054
6055 @end table
6056
6057 @noindent
6058 The @option{-gnatV} switch may be followed by
6059 ^a string of letters^a list of options^
6060 to turn on a series of validity checking options.
6061 For example,
6062 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6063 specifies that in addition to the default validity checking, copies and
6064 function return expressions are to be validity checked.
6065 In order to make it easier
6066 to specify the desired combination of effects,
6067 @ifclear vms
6068 the upper case letters @code{CDFIMORST} may
6069 be used to turn off the corresponding lower case option.
6070 @end ifclear
6071 @ifset vms
6072 the prefix @code{NO} on an option turns off the corresponding validity
6073 checking:
6074 @itemize @bullet
6075 @item @code{NOCOPIES}
6076 @item @code{NODEFAULT}
6077 @item @code{NOFLOATS}
6078 @item @code{NOIN_PARAMS}
6079 @item @code{NOMOD_PARAMS}
6080 @item @code{NOOPERANDS}
6081 @item @code{NORETURNS}
6082 @item @code{NOSUBSCRIPTS}
6083 @item @code{NOTESTS}
6084 @end itemize
6085 @end ifset
6086 Thus
6087 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6088 turns on all validity checking options except for
6089 checking of @code{@b{in out}} procedure arguments.
6090
6091 The specification of additional validity checking generates extra code (and
6092 in the case of @option{-gnatVa} the code expansion can be substantial).
6093 However, these additional checks can be very useful in detecting
6094 uninitialized variables, incorrect use of unchecked conversion, and other
6095 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6096 is useful in conjunction with the extra validity checking, since this
6097 ensures that wherever possible uninitialized variables have invalid values.
6098
6099 See also the pragma @code{Validity_Checks} which allows modification of
6100 the validity checking mode at the program source level, and also allows for
6101 temporary disabling of validity checks.
6102
6103 @node Style Checking
6104 @subsection Style Checking
6105 @findex Style checking
6106
6107 @noindent
6108 The @option{-gnaty^x^(option,option,@dots{})^} switch
6109 @cindex @option{-gnaty} (@command{gcc})
6110 causes the compiler to
6111 enforce specified style rules. A limited set of style rules has been used
6112 in writing the GNAT sources themselves. This switch allows user programs
6113 to activate all or some of these checks. If the source program fails a
6114 specified style check, an appropriate warning message is given, preceded by
6115 the character sequence ``(style)''.
6116 @ifset vms
6117 @code{(option,option,@dots{})} is a sequence of keywords
6118 @end ifset
6119 @ifclear vms
6120 The string @var{x} is a sequence of letters or digits
6121 @end ifclear
6122 indicating the particular style
6123 checks to be performed. The following checks are defined:
6124
6125 @table @option
6126 @c !sort!
6127 @item 0-9
6128 @emph{Specify indentation level.}
6129 If a digit from 1-9 appears
6130 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6131 then proper indentation is checked, with the digit indicating the
6132 indentation level required. A value of zero turns off this style check.
6133 The general style of required indentation is as specified by
6134 the examples in the Ada Reference Manual. Full line comments must be
6135 aligned with the @code{--} starting on a column that is a multiple of
6136 the alignment level, or they may be aligned the same way as the following
6137 non-blank line (this is useful when full line comments appear in the middle
6138 of a statement.
6139
6140 @item ^a^ATTRIBUTE^
6141 @emph{Check attribute casing.}
6142 Attribute names, including the case of keywords such as @code{digits}
6143 used as attributes names, must be written in mixed case, that is, the
6144 initial letter and any letter following an underscore must be uppercase.
6145 All other letters must be lowercase.
6146
6147 @item ^A^ARRAY_INDEXES^
6148 @emph{Use of array index numbers in array attributes.}
6149 When using the array attributes First, Last, Range,
6150 or Length, the index number must be omitted for one-dimensional arrays
6151 and is required for multi-dimensional arrays.
6152
6153 @item ^b^BLANKS^
6154 @emph{Blanks not allowed at statement end.}
6155 Trailing blanks are not allowed at the end of statements. The purpose of this
6156 rule, together with h (no horizontal tabs), is to enforce a canonical format
6157 for the use of blanks to separate source tokens.
6158
6159 @item ^B^BOOLEAN_OPERATORS^
6160 @emph{Check Boolean operators.}
6161 The use of AND/OR operators is not permitted except in the cases of modular
6162 operands, array operands, and simple stand-alone boolean variables or
6163 boolean constants. In all other cases AND THEN/OR ELSE are required.
6164
6165 @item ^c^COMMENTS^
6166 @emph{Check comments.}
6167 Comments must meet the following set of rules:
6168
6169 @itemize @bullet
6170
6171 @item
6172 The ``@code{--}'' that starts the column must either start in column one,
6173 or else at least one blank must precede this sequence.
6174
6175 @item
6176 Comments that follow other tokens on a line must have at least one blank
6177 following the ``@code{--}'' at the start of the comment.
6178
6179 @item
6180 Full line comments must have two blanks following the ``@code{--}'' that
6181 starts the comment, with the following exceptions.
6182
6183 @item
6184 A line consisting only of the ``@code{--}'' characters, possibly preceded
6185 by blanks is permitted.
6186
6187 @item
6188 A comment starting with ``@code{--x}'' where @code{x} is a special character
6189 is permitted.
6190 This allows proper processing of the output generated by specialized tools
6191 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6192 annotation
6193 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6194 special character is defined as being in one of the ASCII ranges
6195 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6196 Note that this usage is not permitted
6197 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6198
6199 @item
6200 A line consisting entirely of minus signs, possibly preceded by blanks, is
6201 permitted. This allows the construction of box comments where lines of minus
6202 signs are used to form the top and bottom of the box.
6203
6204 @item
6205 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6206 least one blank follows the initial ``@code{--}''. Together with the preceding
6207 rule, this allows the construction of box comments, as shown in the following
6208 example:
6209 @smallexample
6210 ---------------------------
6211 -- This is a box comment --
6212 -- with two text lines. --
6213 ---------------------------
6214 @end smallexample
6215 @end itemize
6216
6217 @item ^d^DOS_LINE_ENDINGS^
6218 @emph{Check no DOS line terminators present.}
6219 All lines must be terminated by a single ASCII.LF
6220 character (in particular the DOS line terminator sequence CR/LF is not
6221 allowed).
6222
6223 @item ^e^END^
6224 @emph{Check end/exit labels.}
6225 Optional labels on @code{end} statements ending subprograms and on
6226 @code{exit} statements exiting named loops, are required to be present.
6227
6228 @item ^f^VTABS^
6229 @emph{No form feeds or vertical tabs.}
6230 Neither form feeds nor vertical tab characters are permitted
6231 in the source text.
6232
6233 @item ^g^GNAT^
6234 @emph{GNAT style mode}
6235 The set of style check switches is set to match that used by the GNAT sources.
6236 This may be useful when developing code that is eventually intended to be
6237 incorporated into GNAT. For further details, see GNAT sources.
6238
6239 @item ^h^HTABS^
6240 @emph{No horizontal tabs.}
6241 Horizontal tab characters are not permitted in the source text.
6242 Together with the b (no blanks at end of line) check, this
6243 enforces a canonical form for the use of blanks to separate
6244 source tokens.
6245
6246 @item ^i^IF_THEN^
6247 @emph{Check if-then layout.}
6248 The keyword @code{then} must appear either on the same
6249 line as corresponding @code{if}, or on a line on its own, lined
6250 up under the @code{if} with at least one non-blank line in between
6251 containing all or part of the condition to be tested.
6252
6253 @item ^I^IN_MODE^
6254 @emph{check mode IN keywords}
6255 Mode @code{in} (the default mode) is not
6256 allowed to be given explicitly. @code{in out} is fine,
6257 but not @code{in} on its own.
6258
6259 @item ^k^KEYWORD^
6260 @emph{Check keyword casing.}
6261 All keywords must be in lower case (with the exception of keywords
6262 such as @code{digits} used as attribute names to which this check
6263 does not apply).
6264
6265 @item ^l^LAYOUT^
6266 @emph{Check layout.}
6267 Layout of statement and declaration constructs must follow the
6268 recommendations in the Ada Reference Manual, as indicated by the
6269 form of the syntax rules. For example an @code{else} keyword must
6270 be lined up with the corresponding @code{if} keyword.
6271
6272 There are two respects in which the style rule enforced by this check
6273 option are more liberal than those in the Ada Reference Manual. First
6274 in the case of record declarations, it is permissible to put the
6275 @code{record} keyword on the same line as the @code{type} keyword, and
6276 then the @code{end} in @code{end record} must line up under @code{type}.
6277 This is also permitted when the type declaration is split on two lines.
6278 For example, any of the following three layouts is acceptable:
6279
6280 @smallexample @c ada
6281 @cartouche
6282 type q is record
6283 a : integer;
6284 b : integer;
6285 end record;
6286
6287 type q is
6288 record
6289 a : integer;
6290 b : integer;
6291 end record;
6292
6293 type q is
6294 record
6295 a : integer;
6296 b : integer;
6297 end record;
6298
6299 @end cartouche
6300 @end smallexample
6301
6302 @noindent
6303 Second, in the case of a block statement, a permitted alternative
6304 is to put the block label on the same line as the @code{declare} or
6305 @code{begin} keyword, and then line the @code{end} keyword up under
6306 the block label. For example both the following are permitted:
6307
6308 @smallexample @c ada
6309 @cartouche
6310 Block : declare
6311 A : Integer := 3;
6312 begin
6313 Proc (A, A);
6314 end Block;
6315
6316 Block :
6317 declare
6318 A : Integer := 3;
6319 begin
6320 Proc (A, A);
6321 end Block;
6322 @end cartouche
6323 @end smallexample
6324
6325 @noindent
6326 The same alternative format is allowed for loops. For example, both of
6327 the following are permitted:
6328
6329 @smallexample @c ada
6330 @cartouche
6331 Clear : while J < 10 loop
6332 A (J) := 0;
6333 end loop Clear;
6334
6335 Clear :
6336 while J < 10 loop
6337 A (J) := 0;
6338 end loop Clear;
6339 @end cartouche
6340 @end smallexample
6341
6342 @item ^Lnnn^MAX_NESTING=nnn^
6343 @emph{Set maximum nesting level}
6344 The maximum level of nesting of constructs (including subprograms, loops,
6345 blocks, packages, and conditionals) may not exceed the given value
6346 @option{nnn}. A value of zero disconnects this style check.
6347
6348 @item ^m^LINE_LENGTH^
6349 @emph{Check maximum line length.}
6350 The length of source lines must not exceed 79 characters, including
6351 any trailing blanks. The value of 79 allows convenient display on an
6352 80 character wide device or window, allowing for possible special
6353 treatment of 80 character lines. Note that this count is of
6354 characters in the source text. This means that a tab character counts
6355 as one character in this count but a wide character sequence counts as
6356 a single character (however many bytes are needed in the encoding).
6357
6358 @item ^Mnnn^MAX_LENGTH=nnn^
6359 @emph{Set maximum line length.}
6360 The length of lines must not exceed the
6361 given value @option{nnn}. The maximum value that can be specified is 32767.
6362
6363 @item ^n^STANDARD_CASING^
6364 @emph{Check casing of entities in Standard.}
6365 Any identifier from Standard must be cased
6366 to match the presentation in the Ada Reference Manual (for example,
6367 @code{Integer} and @code{ASCII.NUL}).
6368
6369 @item ^N^NONE^
6370 @emph{Turn off all style checks}
6371 All style check options are turned off.
6372
6373 @item ^o^ORDERED_SUBPROGRAMS^
6374 @emph{Check order of subprogram bodies.}
6375 All subprogram bodies in a given scope
6376 (e.g.@: a package body) must be in alphabetical order. The ordering
6377 rule uses normal Ada rules for comparing strings, ignoring casing
6378 of letters, except that if there is a trailing numeric suffix, then
6379 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6380 before Junk10).
6381
6382 @item ^O^OVERRIDING_INDICATORS^
6383 @emph{Check that overriding subprograms are explicitly marked as such.}
6384 The declaration of a primitive operation of a type extension that overrides
6385 an inherited operation must carry an overriding indicator.
6386
6387 @item ^p^PRAGMA^
6388 @emph{Check pragma casing.}
6389 Pragma names must be written in mixed case, that is, the
6390 initial letter and any letter following an underscore must be uppercase.
6391 All other letters must be lowercase.
6392
6393 @item ^r^REFERENCES^
6394 @emph{Check references.}
6395 All identifier references must be cased in the same way as the
6396 corresponding declaration. No specific casing style is imposed on
6397 identifiers. The only requirement is for consistency of references
6398 with declarations.
6399
6400 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6401 @emph{Check no statements after THEN/ELSE.}
6402 No statements are allowed
6403 on the same line as a THEN or ELSE keyword following the
6404 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6405 and a special exception allows a pragma to appear after ELSE.
6406
6407 @item ^s^SPECS^
6408 @emph{Check separate specs.}
6409 Separate declarations (``specs'') are required for subprograms (a
6410 body is not allowed to serve as its own declaration). The only
6411 exception is that parameterless library level procedures are
6412 not required to have a separate declaration. This exception covers
6413 the most frequent form of main program procedures.
6414
6415 @item ^t^TOKEN^
6416 @emph{Check token spacing.}
6417 The following token spacing rules are enforced:
6418
6419 @itemize @bullet
6420
6421 @item
6422 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6423
6424 @item
6425 The token @code{=>} must be surrounded by spaces.
6426
6427 @item
6428 The token @code{<>} must be preceded by a space or a left parenthesis.
6429
6430 @item
6431 Binary operators other than @code{**} must be surrounded by spaces.
6432 There is no restriction on the layout of the @code{**} binary operator.
6433
6434 @item
6435 Colon must be surrounded by spaces.
6436
6437 @item
6438 Colon-equal (assignment, initialization) must be surrounded by spaces.
6439
6440 @item
6441 Comma must be the first non-blank character on the line, or be
6442 immediately preceded by a non-blank character, and must be followed
6443 by a space.
6444
6445 @item
6446 If the token preceding a left parenthesis ends with a letter or digit, then
6447 a space must separate the two tokens.
6448
6449 @item
6450 if the token following a right parenthesis starts with a letter or digit, then
6451 a space must separate the two tokens.
6452
6453 @item
6454 A right parenthesis must either be the first non-blank character on
6455 a line, or it must be preceded by a non-blank character.
6456
6457 @item
6458 A semicolon must not be preceded by a space, and must not be followed by
6459 a non-blank character.
6460
6461 @item
6462 A unary plus or minus may not be followed by a space.
6463
6464 @item
6465 A vertical bar must be surrounded by spaces.
6466 @end itemize
6467
6468 @item ^u^UNNECESSARY_BLANK_LINES^
6469 @emph{Check unnecessary blank lines.}
6470 Unnecessary blank lines are not allowed. A blank line is considered
6471 unnecessary if it appears at the end of the file, or if more than
6472 one blank line occurs in sequence.
6473
6474 @item ^x^XTRA_PARENS^
6475 @emph{Check extra parentheses.}
6476 Unnecessary extra level of parentheses (C-style) are not allowed
6477 around conditions in @code{if} statements, @code{while} statements and
6478 @code{exit} statements.
6479
6480 @item ^y^ALL_BUILTIN^
6481 @emph{Set all standard style check options}
6482 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6483 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6484 @option{-gnatyS}, @option{-gnatyLnnn},
6485 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6486
6487 @ifclear vms
6488 @item -
6489 @emph{Remove style check options}
6490 This causes any subsequent options in the string to act as canceling the
6491 corresponding style check option. To cancel maximum nesting level control,
6492 use @option{L} parameter witout any integer value after that, because any
6493 digit following @option{-} in the parameter string of the @option{-gnaty}
6494 option will be threated as canceling indentation check. The same is true
6495 for @option{M} parameter. @option{y} and @option{N} parameters are not
6496 allowed after @option{-}.
6497
6498 @item +
6499 This causes any subsequent options in the string to enable the corresponding
6500 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6501 if any.
6502 @end ifclear
6503
6504 @ifset vms
6505 @item NOxxx
6506 @emph{Removing style check options}
6507 If the name of a style check is preceded by @option{NO} then the corresponding
6508 style check is turned off. For example @option{NOCOMMENTS} turns off style
6509 checking for comments.
6510 @end ifset
6511 @end table
6512
6513 @noindent
6514 In the above rules, appearing in column one is always permitted, that is,
6515 counts as meeting either a requirement for a required preceding space,
6516 or as meeting a requirement for no preceding space.
6517
6518 Appearing at the end of a line is also always permitted, that is, counts
6519 as meeting either a requirement for a following space, or as meeting
6520 a requirement for no following space.
6521
6522 @noindent
6523 If any of these style rules is violated, a message is generated giving
6524 details on the violation. The initial characters of such messages are
6525 always ``@code{(style)}''. Note that these messages are treated as warning
6526 messages, so they normally do not prevent the generation of an object
6527 file. The @option{-gnatwe} switch can be used to treat warning messages,
6528 including style messages, as fatal errors.
6529
6530 The switch
6531 @ifclear vms
6532 @option{-gnaty} on its own (that is not
6533 followed by any letters or digits), then the effect is equivalent
6534 to the use of @option{-gnatyy}, as described above, that is all
6535 built-in standard style check options are enabled.
6536
6537 @end ifclear
6538 @ifset vms
6539 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6540 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6541 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6542 @end ifset
6543
6544 The switch
6545 @ifclear vms
6546 @option{-gnatyN}
6547 @end ifclear
6548 @ifset vms
6549 /STYLE_CHECKS=NONE
6550 @end ifset
6551 clears any previously set style checks.
6552
6553 @node Run-Time Checks
6554 @subsection Run-Time Checks
6555 @cindex Division by zero
6556 @cindex Access before elaboration
6557 @cindex Checks, division by zero
6558 @cindex Checks, access before elaboration
6559 @cindex Checks, stack overflow checking
6560
6561 @noindent
6562 By default, the following checks are suppressed: integer overflow
6563 checks, stack overflow checks, and checks for access before
6564 elaboration on subprogram calls. All other checks, including range
6565 checks and array bounds checks, are turned on by default. The
6566 following @command{gcc} switches refine this default behavior.
6567
6568 @table @option
6569 @c !sort!
6570 @item -gnatp
6571 @cindex @option{-gnatp} (@command{gcc})
6572 @cindex Suppressing checks
6573 @cindex Checks, suppressing
6574 @findex Suppress
6575 This switch causes the unit to be compiled
6576 as though @code{pragma Suppress (All_checks)}
6577 had been present in the source. Validity checks are also eliminated (in
6578 other words @option{-gnatp} also implies @option{-gnatVn}.
6579 Use this switch to improve the performance
6580 of the code at the expense of safety in the presence of invalid data or
6581 program bugs.
6582
6583 Note that when checks are suppressed, the compiler is allowed, but not
6584 required, to omit the checking code. If the run-time cost of the
6585 checking code is zero or near-zero, the compiler will generate it even
6586 if checks are suppressed. In particular, if the compiler can prove
6587 that a certain check will necessarily fail, it will generate code to
6588 do an unconditional ``raise'', even if checks are suppressed. The
6589 compiler warns in this case. Another case in which checks may not be
6590 eliminated is when they are embedded in certain run time routines such
6591 as math library routines.
6592
6593 Of course, run-time checks are omitted whenever the compiler can prove
6594 that they will not fail, whether or not checks are suppressed.
6595
6596 Note that if you suppress a check that would have failed, program
6597 execution is erroneous, which means the behavior is totally
6598 unpredictable. The program might crash, or print wrong answers, or
6599 do anything else. It might even do exactly what you wanted it to do
6600 (and then it might start failing mysteriously next week or next
6601 year). The compiler will generate code based on the assumption that
6602 the condition being checked is true, which can result in disaster if
6603 that assumption is wrong.
6604
6605 @item -gnato
6606 @cindex @option{-gnato} (@command{gcc})
6607 @cindex Overflow checks
6608 @cindex Check, overflow
6609 Enables overflow checking for integer operations.
6610 This causes GNAT to generate slower and larger executable
6611 programs by adding code to check for overflow (resulting in raising
6612 @code{Constraint_Error} as required by standard Ada
6613 semantics). These overflow checks correspond to situations in which
6614 the true value of the result of an operation may be outside the base
6615 range of the result type. The following example shows the distinction:
6616
6617 @smallexample @c ada
6618 X1 : Integer := "Integer'Last";
6619 X2 : Integer range 1 .. 5 := "5";
6620 X3 : Integer := "Integer'Last";
6621 X4 : Integer range 1 .. 5 := "5";
6622 F : Float := "2.0E+20";
6623 @dots{}
6624 X1 := X1 + 1;
6625 X2 := X2 + 1;
6626 X3 := Integer (F);
6627 X4 := Integer (F);
6628 @end smallexample
6629
6630 @noindent
6631 Note that if explicit values are assigned at compile time, the
6632 compiler may be able to detect overflow at compile time, in which case
6633 no actual run-time checking code is required, and Constraint_Error
6634 will be raised unconditionally, with or without
6635 @option{-gnato}. That's why the assigned values in the above fragment
6636 are in quotes, the meaning is "assign a value not known to the
6637 compiler that happens to be equal to ...". The remaining discussion
6638 assumes that the compiler cannot detect the values at compile time.
6639
6640 Here the first addition results in a value that is outside the base range
6641 of Integer, and hence requires an overflow check for detection of the
6642 constraint error. Thus the first assignment to @code{X1} raises a
6643 @code{Constraint_Error} exception only if @option{-gnato} is set.
6644
6645 The second increment operation results in a violation of the explicit
6646 range constraint; such range checks are performed by default, and are
6647 unaffected by @option{-gnato}.
6648
6649 The two conversions of @code{F} both result in values that are outside
6650 the base range of type @code{Integer} and thus will raise
6651 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6652 The fact that the result of the second conversion is assigned to
6653 variable @code{X4} with a restricted range is irrelevant, since the problem
6654 is in the conversion, not the assignment.
6655
6656 Basically the rule is that in the default mode (@option{-gnato} not
6657 used), the generated code assures that all integer variables stay
6658 within their declared ranges, or within the base range if there is
6659 no declared range. This prevents any serious problems like indexes
6660 out of range for array operations.
6661
6662 What is not checked in default mode is an overflow that results in
6663 an in-range, but incorrect value. In the above example, the assignments
6664 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6665 range of the target variable, but the result is wrong in the sense that
6666 it is too large to be represented correctly. Typically the assignment
6667 to @code{X1} will result in wrap around to the largest negative number.
6668 The conversions of @code{F} will result in some @code{Integer} value
6669 and if that integer value is out of the @code{X4} range then the
6670 subsequent assignment would generate an exception.
6671
6672 @findex Machine_Overflows
6673 Note that the @option{-gnato} switch does not affect the code generated
6674 for any floating-point operations; it applies only to integer
6675 semantics).
6676 For floating-point, GNAT has the @code{Machine_Overflows}
6677 attribute set to @code{False} and the normal mode of operation is to
6678 generate IEEE NaN and infinite values on overflow or invalid operations
6679 (such as dividing 0.0 by 0.0).
6680
6681 The reason that we distinguish overflow checking from other kinds of
6682 range constraint checking is that a failure of an overflow check, unlike
6683 for example the failure of a range check, can result in an incorrect
6684 value, but cannot cause random memory destruction (like an out of range
6685 subscript), or a wild jump (from an out of range case value). Overflow
6686 checking is also quite expensive in time and space, since in general it
6687 requires the use of double length arithmetic.
6688
6689 Note again that @option{-gnato} is off by default, so overflow checking is
6690 not performed in default mode. This means that out of the box, with the
6691 default settings, GNAT does not do all the checks expected from the
6692 language description in the Ada Reference Manual. If you want all constraint
6693 checks to be performed, as described in this Manual, then you must
6694 explicitly use the -gnato switch either on the @command{gnatmake} or
6695 @command{gcc} command.
6696
6697 @item -gnatE
6698 @cindex @option{-gnatE} (@command{gcc})
6699 @cindex Elaboration checks
6700 @cindex Check, elaboration
6701 Enables dynamic checks for access-before-elaboration
6702 on subprogram calls and generic instantiations.
6703 Note that @option{-gnatE} is not necessary for safety, because in the
6704 default mode, GNAT ensures statically that the checks would not fail.
6705 For full details of the effect and use of this switch,
6706 @xref{Compiling Using gcc}.
6707
6708 @item -fstack-check
6709 @cindex @option{-fstack-check} (@command{gcc})
6710 @cindex Stack Overflow Checking
6711 @cindex Checks, stack overflow checking
6712 Activates stack overflow checking. For full details of the effect and use of
6713 this switch see @ref{Stack Overflow Checking}.
6714 @end table
6715
6716 @findex Unsuppress
6717 @noindent
6718 The setting of these switches only controls the default setting of the
6719 checks. You may modify them using either @code{Suppress} (to remove
6720 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6721 the program source.
6722
6723 @node Using gcc for Syntax Checking
6724 @subsection Using @command{gcc} for Syntax Checking
6725 @table @option
6726 @item -gnats
6727 @cindex @option{-gnats} (@command{gcc})
6728 @ifclear vms
6729
6730 @noindent
6731 The @code{s} stands for ``syntax''.
6732 @end ifclear
6733
6734 Run GNAT in syntax checking only mode. For
6735 example, the command
6736
6737 @smallexample
6738 $ gcc -c -gnats x.adb
6739 @end smallexample
6740
6741 @noindent
6742 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6743 series of files in a single command
6744 @ifclear vms
6745 , and can use wild cards to specify such a group of files.
6746 Note that you must specify the @option{-c} (compile
6747 only) flag in addition to the @option{-gnats} flag.
6748 @end ifclear
6749 .
6750 You may use other switches in conjunction with @option{-gnats}. In
6751 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6752 format of any generated error messages.
6753
6754 When the source file is empty or contains only empty lines and/or comments,
6755 the output is a warning:
6756
6757 @smallexample
6758 $ gcc -c -gnats -x ada toto.txt
6759 toto.txt:1:01: warning: empty file, contains no compilation units
6760 $
6761 @end smallexample
6762
6763 Otherwise, the output is simply the error messages, if any. No object file or
6764 ALI file is generated by a syntax-only compilation. Also, no units other
6765 than the one specified are accessed. For example, if a unit @code{X}
6766 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6767 check only mode does not access the source file containing unit
6768 @code{Y}.
6769
6770 @cindex Multiple units, syntax checking
6771 Normally, GNAT allows only a single unit in a source file. However, this
6772 restriction does not apply in syntax-check-only mode, and it is possible
6773 to check a file containing multiple compilation units concatenated
6774 together. This is primarily used by the @code{gnatchop} utility
6775 (@pxref{Renaming Files Using gnatchop}).
6776 @end table
6777
6778 @node Using gcc for Semantic Checking
6779 @subsection Using @command{gcc} for Semantic Checking
6780 @table @option
6781 @item -gnatc
6782 @cindex @option{-gnatc} (@command{gcc})
6783
6784 @ifclear vms
6785 @noindent
6786 The @code{c} stands for ``check''.
6787 @end ifclear
6788 Causes the compiler to operate in semantic check mode,
6789 with full checking for all illegalities specified in the
6790 Ada Reference Manual, but without generation of any object code
6791 (no object file is generated).
6792
6793 Because dependent files must be accessed, you must follow the GNAT
6794 semantic restrictions on file structuring to operate in this mode:
6795
6796 @itemize @bullet
6797 @item
6798 The needed source files must be accessible
6799 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6800
6801 @item
6802 Each file must contain only one compilation unit.
6803
6804 @item
6805 The file name and unit name must match (@pxref{File Naming Rules}).
6806 @end itemize
6807
6808 The output consists of error messages as appropriate. No object file is
6809 generated. An @file{ALI} file is generated for use in the context of
6810 cross-reference tools, but this file is marked as not being suitable
6811 for binding (since no object file is generated).
6812 The checking corresponds exactly to the notion of
6813 legality in the Ada Reference Manual.
6814
6815 Any unit can be compiled in semantics-checking-only mode, including
6816 units that would not normally be compiled (subunits,
6817 and specifications where a separate body is present).
6818 @end table
6819
6820 @node Compiling Different Versions of Ada
6821 @subsection Compiling Different Versions of Ada
6822
6823 @noindent
6824 The switches described in this section allow you to explicitly specify
6825 the version of the Ada language that your programs are written in.
6826 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6827 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6828 indicate Ada 83 compatibility mode.
6829
6830 @table @option
6831 @cindex Compatibility with Ada 83
6832
6833 @item -gnat83 (Ada 83 Compatibility Mode)
6834 @cindex @option{-gnat83} (@command{gcc})
6835 @cindex ACVC, Ada 83 tests
6836 @cindex Ada 83 mode
6837
6838 @noindent
6839 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6840 specifies that the program is to be compiled in Ada 83 mode. With
6841 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6842 semantics where this can be done easily.
6843 It is not possible to guarantee this switch does a perfect
6844 job; some subtle tests, such as are
6845 found in earlier ACVC tests (and that have been removed from the ACATS suite
6846 for Ada 95), might not compile correctly.
6847 Nevertheless, this switch may be useful in some circumstances, for example
6848 where, due to contractual reasons, existing code needs to be maintained
6849 using only Ada 83 features.
6850
6851 With few exceptions (most notably the need to use @code{<>} on
6852 @cindex Generic formal parameters
6853 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6854 reserved words, and the use of packages
6855 with optional bodies), it is not necessary to specify the
6856 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6857 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6858 a correct Ada 83 program is usually also a correct program
6859 in these later versions of the language standard.
6860 For further information, please refer to @ref{Compatibility and Porting Guide}.
6861
6862 @item -gnat95 (Ada 95 mode)
6863 @cindex @option{-gnat95} (@command{gcc})
6864 @cindex Ada 95 mode
6865
6866 @noindent
6867 This switch directs the compiler to implement the Ada 95 version of the
6868 language.
6869 Since Ada 95 is almost completely upwards
6870 compatible with Ada 83, Ada 83 programs may generally be compiled using
6871 this switch (see the description of the @option{-gnat83} switch for further
6872 information about Ada 83 mode).
6873 If an Ada 2005 program is compiled in Ada 95 mode,
6874 uses of the new Ada 2005 features will cause error
6875 messages or warnings.
6876
6877 This switch also can be used to cancel the effect of a previous
6878 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6879
6880 @item -gnat05 (Ada 2005 mode)
6881 @cindex @option{-gnat05} (@command{gcc})
6882 @cindex Ada 2005 mode
6883
6884 @noindent
6885 This switch directs the compiler to implement the Ada 2005 version of the
6886 language.
6887 Since Ada 2005 is almost completely upwards
6888 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6889 may generally be compiled using this switch (see the description of the
6890 @option{-gnat83} and @option{-gnat95} switches for further
6891 information).
6892
6893 For information about the approved ``Ada Issues'' that have been incorporated
6894 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6895 Included with GNAT releases is a file @file{features-ada0y} that describes
6896 the set of implemented Ada 2005 features.
6897 @end table
6898
6899
6900 @node Character Set Control
6901 @subsection Character Set Control
6902 @table @option
6903 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6904 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6905
6906 @noindent
6907 Normally GNAT recognizes the Latin-1 character set in source program
6908 identifiers, as described in the Ada Reference Manual.
6909 This switch causes
6910 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6911 single character ^^or word^ indicating the character set, as follows:
6912
6913 @table @code
6914 @item 1
6915 ISO 8859-1 (Latin-1) identifiers
6916
6917 @item 2
6918 ISO 8859-2 (Latin-2) letters allowed in identifiers
6919
6920 @item 3
6921 ISO 8859-3 (Latin-3) letters allowed in identifiers
6922
6923 @item 4
6924 ISO 8859-4 (Latin-4) letters allowed in identifiers
6925
6926 @item 5
6927 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6928
6929 @item 9
6930 ISO 8859-15 (Latin-9) letters allowed in identifiers
6931
6932 @item ^p^PC^
6933 IBM PC letters (code page 437) allowed in identifiers
6934
6935 @item ^8^PC850^
6936 IBM PC letters (code page 850) allowed in identifiers
6937
6938 @item ^f^FULL_UPPER^
6939 Full upper-half codes allowed in identifiers
6940
6941 @item ^n^NO_UPPER^
6942 No upper-half codes allowed in identifiers
6943
6944 @item ^w^WIDE^
6945 Wide-character codes (that is, codes greater than 255)
6946 allowed in identifiers
6947 @end table
6948
6949 @xref{Foreign Language Representation}, for full details on the
6950 implementation of these character sets.
6951
6952 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6953 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6954 Specify the method of encoding for wide characters.
6955 @var{e} is one of the following:
6956
6957 @table @code
6958
6959 @item ^h^HEX^
6960 Hex encoding (brackets coding also recognized)
6961
6962 @item ^u^UPPER^
6963 Upper half encoding (brackets encoding also recognized)
6964
6965 @item ^s^SHIFT_JIS^
6966 Shift/JIS encoding (brackets encoding also recognized)
6967
6968 @item ^e^EUC^
6969 EUC encoding (brackets encoding also recognized)
6970
6971 @item ^8^UTF8^
6972 UTF-8 encoding (brackets encoding also recognized)
6973
6974 @item ^b^BRACKETS^
6975 Brackets encoding only (default value)
6976 @end table
6977 For full details on these encoding
6978 methods see @ref{Wide Character Encodings}.
6979 Note that brackets coding is always accepted, even if one of the other
6980 options is specified, so for example @option{-gnatW8} specifies that both
6981 brackets and UTF-8 encodings will be recognized. The units that are
6982 with'ed directly or indirectly will be scanned using the specified
6983 representation scheme, and so if one of the non-brackets scheme is
6984 used, it must be used consistently throughout the program. However,
6985 since brackets encoding is always recognized, it may be conveniently
6986 used in standard libraries, allowing these libraries to be used with
6987 any of the available coding schemes.
6988 scheme.
6989
6990 If no @option{-gnatW?} parameter is present, then the default
6991 representation is normally Brackets encoding only. However, if the
6992 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6993 byte order mark or BOM for UTF-8), then these three characters are
6994 skipped and the default representation for the file is set to UTF-8.
6995
6996 Note that the wide character representation that is specified (explicitly
6997 or by default) for the main program also acts as the default encoding used
6998 for Wide_Text_IO files if not specifically overridden by a WCEM form
6999 parameter.
7000
7001 @end table
7002 @node File Naming Control
7003 @subsection File Naming Control
7004
7005 @table @option
7006 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7007 @cindex @option{-gnatk} (@command{gcc})
7008 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7009 1-999, indicates the maximum allowable length of a file name (not
7010 including the @file{.ads} or @file{.adb} extension). The default is not
7011 to enable file name krunching.
7012
7013 For the source file naming rules, @xref{File Naming Rules}.
7014 @end table
7015
7016 @node Subprogram Inlining Control
7017 @subsection Subprogram Inlining Control
7018
7019 @table @option
7020 @c !sort!
7021 @item -gnatn
7022 @cindex @option{-gnatn} (@command{gcc})
7023 @ifclear vms
7024 The @code{n} here is intended to suggest the first syllable of the
7025 word ``inline''.
7026 @end ifclear
7027 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7028 inlining to actually occur, optimization must be enabled. To enable
7029 inlining of subprograms specified by pragma @code{Inline},
7030 you must also specify this switch.
7031 In the absence of this switch, GNAT does not attempt
7032 inlining and does not need to access the bodies of
7033 subprograms for which @code{pragma Inline} is specified if they are not
7034 in the current unit.
7035
7036 If you specify this switch the compiler will access these bodies,
7037 creating an extra source dependency for the resulting object file, and
7038 where possible, the call will be inlined.
7039 For further details on when inlining is possible
7040 see @ref{Inlining of Subprograms}.
7041
7042 @item -gnatN
7043 @cindex @option{-gnatN} (@command{gcc})
7044 This switch activates front-end inlining which also
7045 generates additional dependencies.
7046
7047 When using a gcc-based back end (in practice this means using any version
7048 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7049 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7050 Historically front end inlining was more extensive than the gcc back end
7051 inlining, but that is no longer the case.
7052 @end table
7053
7054 @node Auxiliary Output Control
7055 @subsection Auxiliary Output Control
7056
7057 @table @option
7058 @item -gnatt
7059 @cindex @option{-gnatt} (@command{gcc})
7060 @cindex Writing internal trees
7061 @cindex Internal trees, writing to file
7062 Causes GNAT to write the internal tree for a unit to a file (with the
7063 extension @file{.adt}.
7064 This not normally required, but is used by separate analysis tools.
7065 Typically
7066 these tools do the necessary compilations automatically, so you should
7067 not have to specify this switch in normal operation.
7068 Note that the combination of switches @option{-gnatct}
7069 generates a tree in the form required by ASIS applications.
7070
7071 @item -gnatu
7072 @cindex @option{-gnatu} (@command{gcc})
7073 Print a list of units required by this compilation on @file{stdout}.
7074 The listing includes all units on which the unit being compiled depends
7075 either directly or indirectly.
7076
7077 @ifclear vms
7078 @item -pass-exit-codes
7079 @cindex @option{-pass-exit-codes} (@command{gcc})
7080 If this switch is not used, the exit code returned by @command{gcc} when
7081 compiling multiple files indicates whether all source files have
7082 been successfully used to generate object files or not.
7083
7084 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7085 exit status and allows an integrated development environment to better
7086 react to a compilation failure. Those exit status are:
7087
7088 @table @asis
7089 @item 5
7090 There was an error in at least one source file.
7091 @item 3
7092 At least one source file did not generate an object file.
7093 @item 2
7094 The compiler died unexpectedly (internal error for example).
7095 @item 0
7096 An object file has been generated for every source file.
7097 @end table
7098 @end ifclear
7099 @end table
7100
7101 @node Debugging Control
7102 @subsection Debugging Control
7103
7104 @table @option
7105 @c !sort!
7106 @cindex Debugging options
7107 @ifclear vms
7108 @item -gnatd@var{x}
7109 @cindex @option{-gnatd} (@command{gcc})
7110 Activate internal debugging switches. @var{x} is a letter or digit, or
7111 string of letters or digits, which specifies the type of debugging
7112 outputs desired. Normally these are used only for internal development
7113 or system debugging purposes. You can find full documentation for these
7114 switches in the body of the @code{Debug} unit in the compiler source
7115 file @file{debug.adb}.
7116 @end ifclear
7117
7118 @item -gnatG[=nn]
7119 @cindex @option{-gnatG} (@command{gcc})
7120 This switch causes the compiler to generate auxiliary output containing
7121 a pseudo-source listing of the generated expanded code. Like most Ada
7122 compilers, GNAT works by first transforming the high level Ada code into
7123 lower level constructs. For example, tasking operations are transformed
7124 into calls to the tasking run-time routines. A unique capability of GNAT
7125 is to list this expanded code in a form very close to normal Ada source.
7126 This is very useful in understanding the implications of various Ada
7127 usage on the efficiency of the generated code. There are many cases in
7128 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7129 generate a lot of run-time code. By using @option{-gnatG} you can identify
7130 these cases, and consider whether it may be desirable to modify the coding
7131 approach to improve efficiency.
7132
7133 The optional parameter @code{nn} if present after -gnatG specifies an
7134 alternative maximum line length that overrides the normal default of 72.
7135 This value is in the range 40-999999, values less than 40 being silently
7136 reset to 40. The equal sign is optional.
7137
7138 The format of the output is very similar to standard Ada source, and is
7139 easily understood by an Ada programmer. The following special syntactic
7140 additions correspond to low level features used in the generated code that
7141 do not have any exact analogies in pure Ada source form. The following
7142 is a partial list of these special constructions. See the spec
7143 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7144
7145 If the switch @option{-gnatL} is used in conjunction with
7146 @cindex @option{-gnatL} (@command{gcc})
7147 @option{-gnatG}, then the original source lines are interspersed
7148 in the expanded source (as comment lines with the original line number).
7149
7150 @table @code
7151 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7152 Shows the storage pool being used for an allocator.
7153
7154 @item at end @var{procedure-name};
7155 Shows the finalization (cleanup) procedure for a scope.
7156
7157 @item (if @var{expr} then @var{expr} else @var{expr})
7158 Conditional expression equivalent to the @code{x?y:z} construction in C.
7159
7160 @item @var{target}^^^(@var{source})
7161 A conversion with floating-point truncation instead of rounding.
7162
7163 @item @var{target}?(@var{source})
7164 A conversion that bypasses normal Ada semantic checking. In particular
7165 enumeration types and fixed-point types are treated simply as integers.
7166
7167 @item @var{target}?^^^(@var{source})
7168 Combines the above two cases.
7169
7170 @item @var{x} #/ @var{y}
7171 @itemx @var{x} #mod @var{y}
7172 @itemx @var{x} #* @var{y}
7173 @itemx @var{x} #rem @var{y}
7174 A division or multiplication of fixed-point values which are treated as
7175 integers without any kind of scaling.
7176
7177 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7178 Shows the storage pool associated with a @code{free} statement.
7179
7180 @item [subtype or type declaration]
7181 Used to list an equivalent declaration for an internally generated
7182 type that is referenced elsewhere in the listing.
7183
7184 @item freeze @var{type-name} @ovar{actions}
7185 Shows the point at which @var{type-name} is frozen, with possible
7186 associated actions to be performed at the freeze point.
7187
7188 @item reference @var{itype}
7189 Reference (and hence definition) to internal type @var{itype}.
7190
7191 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7192 Intrinsic function call.
7193
7194 @item @var{label-name} : label
7195 Declaration of label @var{labelname}.
7196
7197 @item #$ @var{subprogram-name}
7198 An implicit call to a run-time support routine
7199 (to meet the requirement of H.3.1(9) in a
7200 convenient manner).
7201
7202 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7203 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7204 @var{expr}, but handled more efficiently).
7205
7206 @item [constraint_error]
7207 Raise the @code{Constraint_Error} exception.
7208
7209 @item @var{expression}'reference
7210 A pointer to the result of evaluating @var{expression}.
7211
7212 @item @var{target-type}!(@var{source-expression})
7213 An unchecked conversion of @var{source-expression} to @var{target-type}.
7214
7215 @item [@var{numerator}/@var{denominator}]
7216 Used to represent internal real literals (that) have no exact
7217 representation in base 2-16 (for example, the result of compile time
7218 evaluation of the expression 1.0/27.0).
7219 @end table
7220
7221 @item -gnatD[=nn]
7222 @cindex @option{-gnatD} (@command{gcc})
7223 When used in conjunction with @option{-gnatG}, this switch causes
7224 the expanded source, as described above for
7225 @option{-gnatG} to be written to files with names
7226 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7227 instead of to the standard output file. For
7228 example, if the source file name is @file{hello.adb}, then a file
7229 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7230 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7231 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7232 you to do source level debugging using the generated code which is
7233 sometimes useful for complex code, for example to find out exactly
7234 which part of a complex construction raised an exception. This switch
7235 also suppress generation of cross-reference information (see
7236 @option{-gnatx}) since otherwise the cross-reference information
7237 would refer to the @file{^.dg^.DG^} file, which would cause
7238 confusion since this is not the original source file.
7239
7240 Note that @option{-gnatD} actually implies @option{-gnatG}
7241 automatically, so it is not necessary to give both options.
7242 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7243
7244 If the switch @option{-gnatL} is used in conjunction with
7245 @cindex @option{-gnatL} (@command{gcc})
7246 @option{-gnatDG}, then the original source lines are interspersed
7247 in the expanded source (as comment lines with the original line number).
7248
7249 The optional parameter @code{nn} if present after -gnatD specifies an
7250 alternative maximum line length that overrides the normal default of 72.
7251 This value is in the range 40-999999, values less than 40 being silently
7252 reset to 40. The equal sign is optional.
7253
7254 @item -gnatr
7255 @cindex @option{-gnatr} (@command{gcc})
7256 @cindex pragma Restrictions
7257 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7258 so that violation of restrictions causes warnings rather than illegalities.
7259 This is useful during the development process when new restrictions are added
7260 or investigated. The switch also causes pragma Profile to be treated as
7261 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7262 restriction warnings rather than restrictions.
7263
7264 @ifclear vms
7265 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7266 @cindex @option{-gnatR} (@command{gcc})
7267 This switch controls output from the compiler of a listing showing
7268 representation information for declared types and objects. For
7269 @option{-gnatR0}, no information is output (equivalent to omitting
7270 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7271 so @option{-gnatR} with no parameter has the same effect), size and alignment
7272 information is listed for declared array and record types. For
7273 @option{-gnatR2}, size and alignment information is listed for all
7274 declared types and objects. Finally @option{-gnatR3} includes symbolic
7275 expressions for values that are computed at run time for
7276 variant records. These symbolic expressions have a mostly obvious
7277 format with #n being used to represent the value of the n'th
7278 discriminant. See source files @file{repinfo.ads/adb} in the
7279 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7280 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7281 the output is to a file with the name @file{^file.rep^file_REP^} where
7282 file is the name of the corresponding source file.
7283 @end ifclear
7284 @ifset vms
7285 @item /REPRESENTATION_INFO
7286 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7287 This qualifier controls output from the compiler of a listing showing
7288 representation information for declared types and objects. For
7289 @option{/REPRESENTATION_INFO=NONE}, no information is output
7290 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7291 @option{/REPRESENTATION_INFO} without option is equivalent to
7292 @option{/REPRESENTATION_INFO=ARRAYS}.
7293 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7294 information is listed for declared array and record types. For
7295 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7296 is listed for all expression information for values that are computed
7297 at run time for variant records. These symbolic expressions have a mostly
7298 obvious format with #n being used to represent the value of the n'th
7299 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7300 @code{GNAT} sources for full details on the format of
7301 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7302 If _FILE is added at the end of an option
7303 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7304 then the output is to a file with the name @file{file_REP} where
7305 file is the name of the corresponding source file.
7306 @end ifset
7307 Note that it is possible for record components to have zero size. In
7308 this case, the component clause uses an obvious extension of permitted
7309 Ada syntax, for example @code{at 0 range 0 .. -1}.
7310
7311 Representation information requires that code be generated (since it is the
7312 code generator that lays out complex data structures). If an attempt is made
7313 to output representation information when no code is generated, for example
7314 when a subunit is compiled on its own, then no information can be generated
7315 and the compiler outputs a message to this effect.
7316
7317 @item -gnatS
7318 @cindex @option{-gnatS} (@command{gcc})
7319 The use of the switch @option{-gnatS} for an
7320 Ada compilation will cause the compiler to output a
7321 representation of package Standard in a form very
7322 close to standard Ada. It is not quite possible to
7323 do this entirely in standard Ada (since new
7324 numeric base types cannot be created in standard
7325 Ada), but the output is easily
7326 readable to any Ada programmer, and is useful to
7327 determine the characteristics of target dependent
7328 types in package Standard.
7329
7330 @item -gnatx
7331 @cindex @option{-gnatx} (@command{gcc})
7332 Normally the compiler generates full cross-referencing information in
7333 the @file{ALI} file. This information is used by a number of tools,
7334 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7335 suppresses this information. This saves some space and may slightly
7336 speed up compilation, but means that these tools cannot be used.
7337 @end table
7338
7339 @node Exception Handling Control
7340 @subsection Exception Handling Control
7341
7342 @noindent
7343 GNAT uses two methods for handling exceptions at run-time. The
7344 @code{setjmp/longjmp} method saves the context when entering
7345 a frame with an exception handler. Then when an exception is
7346 raised, the context can be restored immediately, without the
7347 need for tracing stack frames. This method provides very fast
7348 exception propagation, but introduces significant overhead for
7349 the use of exception handlers, even if no exception is raised.
7350
7351 The other approach is called ``zero cost'' exception handling.
7352 With this method, the compiler builds static tables to describe
7353 the exception ranges. No dynamic code is required when entering
7354 a frame containing an exception handler. When an exception is
7355 raised, the tables are used to control a back trace of the
7356 subprogram invocation stack to locate the required exception
7357 handler. This method has considerably poorer performance for
7358 the propagation of exceptions, but there is no overhead for
7359 exception handlers if no exception is raised. Note that in this
7360 mode and in the context of mixed Ada and C/C++ programming,
7361 to propagate an exception through a C/C++ code, the C/C++ code
7362 must be compiled with the @option{-funwind-tables} GCC's
7363 option.
7364
7365 The following switches may be used to control which of the
7366 two exception handling methods is used.
7367
7368 @table @option
7369 @c !sort!
7370
7371 @item --RTS=sjlj
7372 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7373 This switch causes the setjmp/longjmp run-time (when available) to be used
7374 for exception handling. If the default
7375 mechanism for the target is zero cost exceptions, then
7376 this switch can be used to modify this default, and must be
7377 used for all units in the partition.
7378 This option is rarely used. One case in which it may be
7379 advantageous is if you have an application where exception
7380 raising is common and the overall performance of the
7381 application is improved by favoring exception propagation.
7382
7383 @item --RTS=zcx
7384 @cindex @option{--RTS=zcx} (@command{gnatmake})
7385 @cindex Zero Cost Exceptions
7386 This switch causes the zero cost approach to be used
7387 for exception handling. If this is the default mechanism for the
7388 target (see below), then this switch is unneeded. If the default
7389 mechanism for the target is setjmp/longjmp exceptions, then
7390 this switch can be used to modify this default, and must be
7391 used for all units in the partition.
7392 This option can only be used if the zero cost approach
7393 is available for the target in use, otherwise it will generate an error.
7394 @end table
7395
7396 @noindent
7397 The same option @option{--RTS} must be used both for @command{gcc}
7398 and @command{gnatbind}. Passing this option to @command{gnatmake}
7399 (@pxref{Switches for gnatmake}) will ensure the required consistency
7400 through the compilation and binding steps.
7401
7402 @node Units to Sources Mapping Files
7403 @subsection Units to Sources Mapping Files
7404
7405 @table @option
7406
7407 @item -gnatem=@var{path}
7408 @cindex @option{-gnatem} (@command{gcc})
7409 A mapping file is a way to communicate to the compiler two mappings:
7410 from unit names to file names (without any directory information) and from
7411 file names to path names (with full directory information). These mappings
7412 are used by the compiler to short-circuit the path search.
7413
7414 The use of mapping files is not required for correct operation of the
7415 compiler, but mapping files can improve efficiency, particularly when
7416 sources are read over a slow network connection. In normal operation,
7417 you need not be concerned with the format or use of mapping files,
7418 and the @option{-gnatem} switch is not a switch that you would use
7419 explicitly. It is intended primarily for use by automatic tools such as
7420 @command{gnatmake} running under the project file facility. The
7421 description here of the format of mapping files is provided
7422 for completeness and for possible use by other tools.
7423
7424 A mapping file is a sequence of sets of three lines. In each set, the
7425 first line is the unit name, in lower case, with @code{%s} appended
7426 for specs and @code{%b} appended for bodies; the second line is the
7427 file name; and the third line is the path name.
7428
7429 Example:
7430 @smallexample
7431 main%b
7432 main.2.ada
7433 /gnat/project1/sources/main.2.ada
7434 @end smallexample
7435
7436 When the switch @option{-gnatem} is specified, the compiler will
7437 create in memory the two mappings from the specified file. If there is
7438 any problem (nonexistent file, truncated file or duplicate entries),
7439 no mapping will be created.
7440
7441 Several @option{-gnatem} switches may be specified; however, only the
7442 last one on the command line will be taken into account.
7443
7444 When using a project file, @command{gnatmake} creates a temporary
7445 mapping file and communicates it to the compiler using this switch.
7446
7447 @end table
7448
7449 @node Integrated Preprocessing
7450 @subsection Integrated Preprocessing
7451
7452 @noindent
7453 GNAT sources may be preprocessed immediately before compilation.
7454 In this case, the actual
7455 text of the source is not the text of the source file, but is derived from it
7456 through a process called preprocessing. Integrated preprocessing is specified
7457 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7458 indicates, through a text file, the preprocessing data to be used.
7459 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7460
7461 @noindent
7462 Note that when integrated preprocessing is used, the output from the
7463 preprocessor is not written to any external file. Instead it is passed
7464 internally to the compiler. If you need to preserve the result of
7465 preprocessing in a file, then you should use @command{gnatprep}
7466 to perform the desired preprocessing in stand-alone mode.
7467
7468 @noindent
7469 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7470 used when Integrated Preprocessing is used. The reason is that preprocessing
7471 with another Preprocessing Data file without changing the sources will
7472 not trigger recompilation without this switch.
7473
7474 @noindent
7475 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7476 always trigger recompilation for sources that are preprocessed,
7477 because @command{gnatmake} cannot compute the checksum of the source after
7478 preprocessing.
7479
7480 @noindent
7481 The actual preprocessing function is described in details in section
7482 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7483 preprocessing is triggered and parameterized.
7484
7485 @table @code
7486
7487 @item -gnatep=@var{file}
7488 @cindex @option{-gnatep} (@command{gcc})
7489 This switch indicates to the compiler the file name (without directory
7490 information) of the preprocessor data file to use. The preprocessor data file
7491 should be found in the source directories.
7492
7493 @noindent
7494 A preprocessing data file is a text file with significant lines indicating
7495 how should be preprocessed either a specific source or all sources not
7496 mentioned in other lines. A significant line is a nonempty, non-comment line.
7497 Comments are similar to Ada comments.
7498
7499 @noindent
7500 Each significant line starts with either a literal string or the character '*'.
7501 A literal string is the file name (without directory information) of the source
7502 to preprocess. A character '*' indicates the preprocessing for all the sources
7503 that are not specified explicitly on other lines (order of the lines is not
7504 significant). It is an error to have two lines with the same file name or two
7505 lines starting with the character '*'.
7506
7507 @noindent
7508 After the file name or the character '*', another optional literal string
7509 indicating the file name of the definition file to be used for preprocessing
7510 (@pxref{Form of Definitions File}). The definition files are found by the
7511 compiler in one of the source directories. In some cases, when compiling
7512 a source in a directory other than the current directory, if the definition
7513 file is in the current directory, it may be necessary to add the current
7514 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7515 the compiler would not find the definition file.
7516
7517 @noindent
7518 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7519 be found. Those ^switches^switches^ are:
7520
7521 @table @code
7522
7523 @item -b
7524 Causes both preprocessor lines and the lines deleted by
7525 preprocessing to be replaced by blank lines, preserving the line number.
7526 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7527 it cancels the effect of @option{-c}.
7528
7529 @item -c
7530 Causes both preprocessor lines and the lines deleted
7531 by preprocessing to be retained as comments marked
7532 with the special string ``@code{--! }''.
7533
7534 @item -Dsymbol=value
7535 Define or redefine a symbol, associated with value. A symbol is an Ada
7536 identifier, or an Ada reserved word, with the exception of @code{if},
7537 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7538 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7539 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7540 same name defined in a definition file.
7541
7542 @item -s
7543 Causes a sorted list of symbol names and values to be
7544 listed on the standard output file.
7545
7546 @item -u
7547 Causes undefined symbols to be treated as having the value @code{FALSE}
7548 in the context
7549 of a preprocessor test. In the absence of this option, an undefined symbol in
7550 a @code{#if} or @code{#elsif} test will be treated as an error.
7551
7552 @end table
7553
7554 @noindent
7555 Examples of valid lines in a preprocessor data file:
7556
7557 @smallexample
7558 "toto.adb" "prep.def" -u
7559 -- preprocess "toto.adb", using definition file "prep.def",
7560 -- undefined symbol are False.
7561
7562 * -c -DVERSION=V101
7563 -- preprocess all other sources without a definition file;
7564 -- suppressed lined are commented; symbol VERSION has the value V101.
7565
7566 "titi.adb" "prep2.def" -s
7567 -- preprocess "titi.adb", using definition file "prep2.def";
7568 -- list all symbols with their values.
7569 @end smallexample
7570
7571 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7572 @cindex @option{-gnateD} (@command{gcc})
7573 Define or redefine a preprocessing symbol, associated with value. If no value
7574 is given on the command line, then the value of the symbol is @code{True}.
7575 A symbol is an identifier, following normal Ada (case-insensitive)
7576 rules for its syntax, and value is any sequence (including an empty sequence)
7577 of characters from the set (letters, digits, period, underline).
7578 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7579 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7580
7581 @noindent
7582 A symbol declared with this ^switch^switch^ on the command line replaces a
7583 symbol with the same name either in a definition file or specified with a
7584 ^switch^switch^ -D in the preprocessor data file.
7585
7586 @noindent
7587 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7588
7589 @item -gnateG
7590 When integrated preprocessing is performed and the preprocessor modifies
7591 the source text, write the result of this preprocessing into a file
7592 <source>^.prep^_prep^.
7593
7594 @end table
7595
7596 @node Code Generation Control
7597 @subsection Code Generation Control
7598
7599 @noindent
7600
7601 The GCC technology provides a wide range of target dependent
7602 @option{-m} switches for controlling
7603 details of code generation with respect to different versions of
7604 architectures. This includes variations in instruction sets (e.g.@:
7605 different members of the power pc family), and different requirements
7606 for optimal arrangement of instructions (e.g.@: different members of
7607 the x86 family). The list of available @option{-m} switches may be
7608 found in the GCC documentation.
7609
7610 Use of these @option{-m} switches may in some cases result in improved
7611 code performance.
7612
7613 The GNAT Pro technology is tested and qualified without any
7614 @option{-m} switches,
7615 so generally the most reliable approach is to avoid the use of these
7616 switches. However, we generally expect most of these switches to work
7617 successfully with GNAT Pro, and many customers have reported successful
7618 use of these options.
7619
7620 Our general advice is to avoid the use of @option{-m} switches unless
7621 special needs lead to requirements in this area. In particular,
7622 there is no point in using @option{-m} switches to improve performance
7623 unless you actually see a performance improvement.
7624
7625 @ifset vms
7626 @node Return Codes
7627 @subsection Return Codes
7628 @cindex Return Codes
7629 @cindex @option{/RETURN_CODES=VMS}
7630
7631 @noindent
7632 On VMS, GNAT compiled programs return POSIX-style codes by default,
7633 e.g.@: @option{/RETURN_CODES=POSIX}.
7634
7635 To enable VMS style return codes, use GNAT BIND and LINK with the option
7636 @option{/RETURN_CODES=VMS}. For example:
7637
7638 @smallexample
7639 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7640 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7641 @end smallexample
7642
7643 @noindent
7644 Programs built with /RETURN_CODES=VMS are suitable to be called in
7645 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7646 are suitable for spawning with appropriate GNAT RTL routines.
7647
7648 @end ifset
7649
7650 @node Search Paths and the Run-Time Library (RTL)
7651 @section Search Paths and the Run-Time Library (RTL)
7652
7653 @noindent
7654 With the GNAT source-based library system, the compiler must be able to
7655 find source files for units that are needed by the unit being compiled.
7656 Search paths are used to guide this process.
7657
7658 The compiler compiles one source file whose name must be given
7659 explicitly on the command line. In other words, no searching is done
7660 for this file. To find all other source files that are needed (the most
7661 common being the specs of units), the compiler examines the following
7662 directories, in the following order:
7663
7664 @enumerate
7665 @item
7666 The directory containing the source file of the main unit being compiled
7667 (the file name on the command line).
7668
7669 @item
7670 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7671 @command{gcc} command line, in the order given.
7672
7673 @item
7674 @findex ADA_PRJ_INCLUDE_FILE
7675 Each of the directories listed in the text file whose name is given
7676 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7677
7678 @noindent
7679 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7680 driver when project files are used. It should not normally be set
7681 by other means.
7682
7683 @item
7684 @findex ADA_INCLUDE_PATH
7685 Each of the directories listed in the value of the
7686 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7687 @ifclear vms
7688 Construct this value
7689 exactly as the @env{PATH} environment variable: a list of directory
7690 names separated by colons (semicolons when working with the NT version).
7691 @end ifclear
7692 @ifset vms
7693 Normally, define this value as a logical name containing a comma separated
7694 list of directory names.
7695
7696 This variable can also be defined by means of an environment string
7697 (an argument to the HP C exec* set of functions).
7698
7699 Logical Name:
7700 @smallexample
7701 DEFINE ANOTHER_PATH FOO:[BAG]
7702 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7703 @end smallexample
7704
7705 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7706 first, followed by the standard Ada
7707 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7708 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7709 (Text_IO, Sequential_IO, etc)
7710 instead of the standard Ada packages. Thus, in order to get the standard Ada
7711 packages by default, ADA_INCLUDE_PATH must be redefined.
7712 @end ifset
7713
7714 @item
7715 The content of the @file{ada_source_path} file which is part of the GNAT
7716 installation tree and is used to store standard libraries such as the
7717 GNAT Run Time Library (RTL) source files.
7718 @ifclear vms
7719 @ref{Installing a library}
7720 @end ifclear
7721 @end enumerate
7722
7723 @noindent
7724 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7725 inhibits the use of the directory
7726 containing the source file named in the command line. You can still
7727 have this directory on your search path, but in this case it must be
7728 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7729
7730 Specifying the switch @option{-nostdinc}
7731 inhibits the search of the default location for the GNAT Run Time
7732 Library (RTL) source files.
7733
7734 The compiler outputs its object files and ALI files in the current
7735 working directory.
7736 @ifclear vms
7737 Caution: The object file can be redirected with the @option{-o} switch;
7738 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7739 so the @file{ALI} file will not go to the right place. Therefore, you should
7740 avoid using the @option{-o} switch.
7741 @end ifclear
7742
7743 @findex System.IO
7744 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7745 children make up the GNAT RTL, together with the simple @code{System.IO}
7746 package used in the @code{"Hello World"} example. The sources for these units
7747 are needed by the compiler and are kept together in one directory. Not
7748 all of the bodies are needed, but all of the sources are kept together
7749 anyway. In a normal installation, you need not specify these directory
7750 names when compiling or binding. Either the environment variables or
7751 the built-in defaults cause these files to be found.
7752
7753 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7754 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7755 consisting of child units of @code{GNAT}. This is a collection of generally
7756 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7757 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7758
7759 Besides simplifying access to the RTL, a major use of search paths is
7760 in compiling sources from multiple directories. This can make
7761 development environments much more flexible.
7762
7763 @node Order of Compilation Issues
7764 @section Order of Compilation Issues
7765
7766 @noindent
7767 If, in our earlier example, there was a spec for the @code{hello}
7768 procedure, it would be contained in the file @file{hello.ads}; yet this
7769 file would not have to be explicitly compiled. This is the result of the
7770 model we chose to implement library management. Some of the consequences
7771 of this model are as follows:
7772
7773 @itemize @bullet
7774 @item
7775 There is no point in compiling specs (except for package
7776 specs with no bodies) because these are compiled as needed by clients. If
7777 you attempt a useless compilation, you will receive an error message.
7778 It is also useless to compile subunits because they are compiled as needed
7779 by the parent.
7780
7781 @item
7782 There are no order of compilation requirements: performing a
7783 compilation never obsoletes anything. The only way you can obsolete
7784 something and require recompilations is to modify one of the
7785 source files on which it depends.
7786
7787 @item
7788 There is no library as such, apart from the ALI files
7789 (@pxref{The Ada Library Information Files}, for information on the format
7790 of these files). For now we find it convenient to create separate ALI files,
7791 but eventually the information therein may be incorporated into the object
7792 file directly.
7793
7794 @item
7795 When you compile a unit, the source files for the specs of all units
7796 that it @code{with}'s, all its subunits, and the bodies of any generics it
7797 instantiates must be available (reachable by the search-paths mechanism
7798 described above), or you will receive a fatal error message.
7799 @end itemize
7800
7801 @node Examples
7802 @section Examples
7803
7804 @noindent
7805 The following are some typical Ada compilation command line examples:
7806
7807 @table @code
7808 @item $ gcc -c xyz.adb
7809 Compile body in file @file{xyz.adb} with all default options.
7810
7811 @ifclear vms
7812 @item $ gcc -c -O2 -gnata xyz-def.adb
7813 @end ifclear
7814 @ifset vms
7815 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7816 @end ifset
7817
7818 Compile the child unit package in file @file{xyz-def.adb} with extensive
7819 optimizations, and pragma @code{Assert}/@code{Debug} statements
7820 enabled.
7821
7822 @item $ gcc -c -gnatc abc-def.adb
7823 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7824 mode.
7825 @end table
7826
7827 @node Binding Using gnatbind
7828 @chapter Binding Using @code{gnatbind}
7829 @findex gnatbind
7830
7831 @menu
7832 * Running gnatbind::
7833 * Switches for gnatbind::
7834 * Command-Line Access::
7835 * Search Paths for gnatbind::
7836 * Examples of gnatbind Usage::
7837 @end menu
7838
7839 @noindent
7840 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7841 to bind compiled GNAT objects.
7842
7843 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7844 driver (see @ref{The GNAT Driver and Project Files}).
7845
7846 The @code{gnatbind} program performs four separate functions:
7847
7848 @enumerate
7849 @item
7850 Checks that a program is consistent, in accordance with the rules in
7851 Chapter 10 of the Ada Reference Manual. In particular, error
7852 messages are generated if a program uses inconsistent versions of a
7853 given unit.
7854
7855 @item
7856 Checks that an acceptable order of elaboration exists for the program
7857 and issues an error message if it cannot find an order of elaboration
7858 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7859
7860 @item
7861 Generates a main program incorporating the given elaboration order.
7862 This program is a small Ada package (body and spec) that
7863 must be subsequently compiled
7864 using the GNAT compiler. The necessary compilation step is usually
7865 performed automatically by @command{gnatlink}. The two most important
7866 functions of this program
7867 are to call the elaboration routines of units in an appropriate order
7868 and to call the main program.
7869
7870 @item
7871 Determines the set of object files required by the given main program.
7872 This information is output in the forms of comments in the generated program,
7873 to be read by the @command{gnatlink} utility used to link the Ada application.
7874 @end enumerate
7875
7876 @node Running gnatbind
7877 @section Running @code{gnatbind}
7878
7879 @noindent
7880 The form of the @code{gnatbind} command is
7881
7882 @smallexample
7883 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7884 @end smallexample
7885
7886 @noindent
7887 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7888 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7889 package in two files whose names are
7890 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7891 For example, if given the
7892 parameter @file{hello.ali}, for a main program contained in file
7893 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7894 and @file{b~hello.adb}.
7895
7896 When doing consistency checking, the binder takes into consideration
7897 any source files it can locate. For example, if the binder determines
7898 that the given main program requires the package @code{Pack}, whose
7899 @file{.ALI}
7900 file is @file{pack.ali} and whose corresponding source spec file is
7901 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7902 (using the same search path conventions as previously described for the
7903 @command{gcc} command). If it can locate this source file, it checks that
7904 the time stamps
7905 or source checksums of the source and its references to in @file{ALI} files
7906 match. In other words, any @file{ALI} files that mentions this spec must have
7907 resulted from compiling this version of the source file (or in the case
7908 where the source checksums match, a version close enough that the
7909 difference does not matter).
7910
7911 @cindex Source files, use by binder
7912 The effect of this consistency checking, which includes source files, is
7913 that the binder ensures that the program is consistent with the latest
7914 version of the source files that can be located at bind time. Editing a
7915 source file without compiling files that depend on the source file cause
7916 error messages to be generated by the binder.
7917
7918 For example, suppose you have a main program @file{hello.adb} and a
7919 package @code{P}, from file @file{p.ads} and you perform the following
7920 steps:
7921
7922 @enumerate
7923 @item
7924 Enter @code{gcc -c hello.adb} to compile the main program.
7925
7926 @item
7927 Enter @code{gcc -c p.ads} to compile package @code{P}.
7928
7929 @item
7930 Edit file @file{p.ads}.
7931
7932 @item
7933 Enter @code{gnatbind hello}.
7934 @end enumerate
7935
7936 @noindent
7937 At this point, the file @file{p.ali} contains an out-of-date time stamp
7938 because the file @file{p.ads} has been edited. The attempt at binding
7939 fails, and the binder generates the following error messages:
7940
7941 @smallexample
7942 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7943 error: "p.ads" has been modified and must be recompiled
7944 @end smallexample
7945
7946 @noindent
7947 Now both files must be recompiled as indicated, and then the bind can
7948 succeed, generating a main program. You need not normally be concerned
7949 with the contents of this file, but for reference purposes a sample
7950 binder output file is given in @ref{Example of Binder Output File}.
7951
7952 In most normal usage, the default mode of @command{gnatbind} which is to
7953 generate the main package in Ada, as described in the previous section.
7954 In particular, this means that any Ada programmer can read and understand
7955 the generated main program. It can also be debugged just like any other
7956 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7957 @command{gnatbind} and @command{gnatlink}.
7958
7959 However for some purposes it may be convenient to generate the main
7960 program in C rather than Ada. This may for example be helpful when you
7961 are generating a mixed language program with the main program in C. The
7962 GNAT compiler itself is an example.
7963 The use of the @option{^-C^/BIND_FILE=C^} switch
7964 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7965 be generated in C (and compiled using the gnu C compiler).
7966
7967 @node Switches for gnatbind
7968 @section Switches for @command{gnatbind}
7969
7970 @noindent
7971 The following switches are available with @code{gnatbind}; details will
7972 be presented in subsequent sections.
7973
7974 @menu
7975 * Consistency-Checking Modes::
7976 * Binder Error Message Control::
7977 * Elaboration Control::
7978 * Output Control::
7979 * Binding with Non-Ada Main Programs::
7980 * Binding Programs with No Main Subprogram::
7981 @end menu
7982
7983 @table @option
7984 @c !sort!
7985
7986 @item --version
7987 @cindex @option{--version} @command{gnatbind}
7988 Display Copyright and version, then exit disregarding all other options.
7989
7990 @item --help
7991 @cindex @option{--help} @command{gnatbind}
7992 If @option{--version} was not used, display usage, then exit disregarding
7993 all other options.
7994
7995 @item -a
7996 @cindex @option{-a} @command{gnatbind}
7997 Indicates that, if supported by the platform, the adainit procedure should
7998 be treated as an initialisation routine by the linker (a constructor). This
7999 is intended to be used by the Project Manager to automatically initialize
8000 shared Stand-Alone Libraries.
8001
8002 @item ^-aO^/OBJECT_SEARCH^
8003 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8004 Specify directory to be searched for ALI files.
8005
8006 @item ^-aI^/SOURCE_SEARCH^
8007 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8008 Specify directory to be searched for source file.
8009
8010 @item ^-A^/BIND_FILE=ADA^
8011 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
8012 Generate binder program in Ada (default)
8013
8014 @item ^-b^/REPORT_ERRORS=BRIEF^
8015 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8016 Generate brief messages to @file{stderr} even if verbose mode set.
8017
8018 @item ^-c^/NOOUTPUT^
8019 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8020 Check only, no generation of binder output file.
8021
8022 @item ^-C^/BIND_FILE=C^
8023 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8024 Generate binder program in C
8025
8026 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8027 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8028 This switch can be used to change the default task stack size value
8029 to a specified size @var{nn}, which is expressed in bytes by default, or
8030 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8031 with @var{m}.
8032 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8033 in effect, to completing all task specs with
8034 @smallexample @c ada
8035 pragma Storage_Size (nn);
8036 @end smallexample
8037 When they do not already have such a pragma.
8038
8039 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8040 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8041 This switch can be used to change the default secondary stack size value
8042 to a specified size @var{nn}, which is expressed in bytes by default, or
8043 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8044 with @var{m}.
8045
8046 The secondary stack is used to deal with functions that return a variable
8047 sized result, for example a function returning an unconstrained
8048 String. There are two ways in which this secondary stack is allocated.
8049
8050 For most targets, the secondary stack is growing on demand and is allocated
8051 as a chain of blocks in the heap. The -D option is not very
8052 relevant. It only give some control over the size of the allocated
8053 blocks (whose size is the minimum of the default secondary stack size value,
8054 and the actual size needed for the current allocation request).
8055
8056 For certain targets, notably VxWorks 653,
8057 the secondary stack is allocated by carving off a fixed ratio chunk of the
8058 primary task stack. The -D option is used to define the
8059 size of the environment task's secondary stack.
8060
8061 @item ^-e^/ELABORATION_DEPENDENCIES^
8062 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8063 Output complete list of elaboration-order dependencies.
8064
8065 @item ^-E^/STORE_TRACEBACKS^
8066 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8067 Store tracebacks in exception occurrences when the target supports it.
8068 This is the default with the zero cost exception mechanism.
8069 @ignore
8070 @c The following may get moved to an appendix
8071 This option is currently supported on the following targets:
8072 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8073 @end ignore
8074 See also the packages @code{GNAT.Traceback} and
8075 @code{GNAT.Traceback.Symbolic} for more information.
8076 @ifclear vms
8077 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8078 @command{gcc} option.
8079 @end ifclear
8080
8081 @item ^-F^/FORCE_ELABS_FLAGS^
8082 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8083 Force the checks of elaboration flags. @command{gnatbind} does not normally
8084 generate checks of elaboration flags for the main executable, except when
8085 a Stand-Alone Library is used. However, there are cases when this cannot be
8086 detected by gnatbind. An example is importing an interface of a Stand-Alone
8087 Library through a pragma Import and only specifying through a linker switch
8088 this Stand-Alone Library. This switch is used to guarantee that elaboration
8089 flag checks are generated.
8090
8091 @item ^-h^/HELP^
8092 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8093 Output usage (help) information
8094
8095 @item ^-I^/SEARCH^
8096 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8097 Specify directory to be searched for source and ALI files.
8098
8099 @item ^-I-^/NOCURRENT_DIRECTORY^
8100 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8101 Do not look for sources in the current directory where @code{gnatbind} was
8102 invoked, and do not look for ALI files in the directory containing the
8103 ALI file named in the @code{gnatbind} command line.
8104
8105 @item ^-l^/ORDER_OF_ELABORATION^
8106 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8107 Output chosen elaboration order.
8108
8109 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8110 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8111 Bind the units for library building. In this case the adainit and
8112 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8113 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8114 ^@var{xxx}final^@var{XXX}FINAL^.
8115 Implies ^-n^/NOCOMPILE^.
8116 @ifclear vms
8117 (@xref{GNAT and Libraries}, for more details.)
8118 @end ifclear
8119 @ifset vms
8120 On OpenVMS, these init and final procedures are exported in uppercase
8121 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8122 the init procedure will be "TOTOINIT" and the exported name of the final
8123 procedure will be "TOTOFINAL".
8124 @end ifset
8125
8126 @item ^-Mxyz^/RENAME_MAIN=xyz^
8127 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8128 Rename generated main program from main to xyz. This option is
8129 supported on cross environments only.
8130
8131 @item ^-m^/ERROR_LIMIT=^@var{n}
8132 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8133 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8134 in the range 1..999999. The default value if no switch is
8135 given is 9999. If the number of warnings reaches this limit, then a
8136 message is output and further warnings are suppressed, the bind
8137 continues in this case. If the number of errors reaches this
8138 limit, then a message is output and the bind is abandoned.
8139 A value of zero means that no limit is enforced. The equal
8140 sign is optional.
8141
8142 @ifset unw
8143 Furthermore, under Windows, the sources pointed to by the libraries path
8144 set in the registry are not searched for.
8145 @end ifset
8146
8147 @item ^-n^/NOMAIN^
8148 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8149 No main program.
8150
8151 @item -nostdinc
8152 @cindex @option{-nostdinc} (@command{gnatbind})
8153 Do not look for sources in the system default directory.
8154
8155 @item -nostdlib
8156 @cindex @option{-nostdlib} (@command{gnatbind})
8157 Do not look for library files in the system default directory.
8158
8159 @item --RTS=@var{rts-path}
8160 @cindex @option{--RTS} (@code{gnatbind})
8161 Specifies the default location of the runtime library. Same meaning as the
8162 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8163
8164 @item ^-o ^/OUTPUT=^@var{file}
8165 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8166 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8167 Note that if this option is used, then linking must be done manually,
8168 gnatlink cannot be used.
8169
8170 @item ^-O^/OBJECT_LIST^
8171 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8172 Output object list.
8173
8174 @item ^-p^/PESSIMISTIC_ELABORATION^
8175 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8176 Pessimistic (worst-case) elaboration order
8177
8178 @item ^-R^-R^
8179 @cindex @option{^-R^-R^} (@command{gnatbind})
8180 Output closure source list.
8181
8182 @item ^-s^/READ_SOURCES=ALL^
8183 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8184 Require all source files to be present.
8185
8186 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8187 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8188 Specifies the value to be used when detecting uninitialized scalar
8189 objects with pragma Initialize_Scalars.
8190 The @var{xxx} ^string specified with the switch^option^ may be either
8191 @itemize @bullet
8192 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8193 @item ``@option{^lo^LOW^}'' for the lowest possible value
8194 @item ``@option{^hi^HIGH^}'' for the highest possible value
8195 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8196 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8197 @end itemize
8198
8199 In addition, you can specify @option{-Sev} to indicate that the value is
8200 to be set at run time. In this case, the program will look for an environment
8201 @cindex GNAT_INIT_SCALARS
8202 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8203 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8204 If no environment variable is found, or if it does not have a valid value,
8205 then the default is @option{in} (invalid values).
8206
8207 @ifclear vms
8208 @item -static
8209 @cindex @option{-static} (@code{gnatbind})
8210 Link against a static GNAT run time.
8211
8212 @item -shared
8213 @cindex @option{-shared} (@code{gnatbind})
8214 Link against a shared GNAT run time when available.
8215 @end ifclear
8216
8217 @item ^-t^/NOTIME_STAMP_CHECK^
8218 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8219 Tolerate time stamp and other consistency errors
8220
8221 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8222 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8223 Set the time slice value to @var{n} milliseconds. If the system supports
8224 the specification of a specific time slice value, then the indicated value
8225 is used. If the system does not support specific time slice values, but
8226 does support some general notion of round-robin scheduling, then any
8227 nonzero value will activate round-robin scheduling.
8228
8229 A value of zero is treated specially. It turns off time
8230 slicing, and in addition, indicates to the tasking run time that the
8231 semantics should match as closely as possible the Annex D
8232 requirements of the Ada RM, and in particular sets the default
8233 scheduling policy to @code{FIFO_Within_Priorities}.
8234
8235 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8236 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8237 Enable dynamic stack usage, with @var{n} results stored and displayed
8238 at program termination. A result is generated when a task
8239 terminates. Results that can't be stored are displayed on the fly, at
8240 task termination. This option is currently not supported on Itanium
8241 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8242
8243 @item ^-v^/REPORT_ERRORS=VERBOSE^
8244 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8245 Verbose mode. Write error messages, header, summary output to
8246 @file{stdout}.
8247
8248 @ifclear vms
8249 @item -w@var{x}
8250 @cindex @option{-w} (@code{gnatbind})
8251 Warning mode (@var{x}=s/e for suppress/treat as error)
8252 @end ifclear
8253
8254 @ifset vms
8255 @item /WARNINGS=NORMAL
8256 @cindex @option{/WARNINGS} (@code{gnatbind})
8257 Normal warnings mode. Warnings are issued but ignored
8258
8259 @item /WARNINGS=SUPPRESS
8260 @cindex @option{/WARNINGS} (@code{gnatbind})
8261 All warning messages are suppressed
8262
8263 @item /WARNINGS=ERROR
8264 @cindex @option{/WARNINGS} (@code{gnatbind})
8265 Warning messages are treated as fatal errors
8266 @end ifset
8267
8268 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8269 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8270 Override default wide character encoding for standard Text_IO files.
8271
8272 @item ^-x^/READ_SOURCES=NONE^
8273 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8274 Exclude source files (check object consistency only).
8275
8276 @ifset vms
8277 @item /READ_SOURCES=AVAILABLE
8278 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8279 Default mode, in which sources are checked for consistency only if
8280 they are available.
8281 @end ifset
8282
8283 @item ^-y^/ENABLE_LEAP_SECONDS^
8284 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8285 Enable leap seconds support in @code{Ada.Calendar} and its children.
8286
8287 @item ^-z^/ZERO_MAIN^
8288 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8289 No main subprogram.
8290 @end table
8291
8292 @ifclear vms
8293 @noindent
8294 You may obtain this listing of switches by running @code{gnatbind} with
8295 no arguments.
8296 @end ifclear
8297
8298 @node Consistency-Checking Modes
8299 @subsection Consistency-Checking Modes
8300
8301 @noindent
8302 As described earlier, by default @code{gnatbind} checks
8303 that object files are consistent with one another and are consistent
8304 with any source files it can locate. The following switches control binder
8305 access to sources.
8306
8307 @table @option
8308 @c !sort!
8309 @item ^-s^/READ_SOURCES=ALL^
8310 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8311 Require source files to be present. In this mode, the binder must be
8312 able to locate all source files that are referenced, in order to check
8313 their consistency. In normal mode, if a source file cannot be located it
8314 is simply ignored. If you specify this switch, a missing source
8315 file is an error.
8316
8317 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8318 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8319 Override default wide character encoding for standard Text_IO files.
8320 Normally the default wide character encoding method used for standard
8321 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8322 the main source input (see description of switch
8323 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8324 use of this switch for the binder (which has the same set of
8325 possible arguments) overrides this default as specified.
8326
8327 @item ^-x^/READ_SOURCES=NONE^
8328 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8329 Exclude source files. In this mode, the binder only checks that ALI
8330 files are consistent with one another. Source files are not accessed.
8331 The binder runs faster in this mode, and there is still a guarantee that
8332 the resulting program is self-consistent.
8333 If a source file has been edited since it was last compiled, and you
8334 specify this switch, the binder will not detect that the object
8335 file is out of date with respect to the source file. Note that this is the
8336 mode that is automatically used by @command{gnatmake} because in this
8337 case the checking against sources has already been performed by
8338 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8339
8340 @ifset vms
8341 @item /READ_SOURCES=AVAILABLE
8342 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8343 This is the default mode in which source files are checked if they are
8344 available, and ignored if they are not available.
8345 @end ifset
8346 @end table
8347
8348 @node Binder Error Message Control
8349 @subsection Binder Error Message Control
8350
8351 @noindent
8352 The following switches provide control over the generation of error
8353 messages from the binder:
8354
8355 @table @option
8356 @c !sort!
8357 @item ^-v^/REPORT_ERRORS=VERBOSE^
8358 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8359 Verbose mode. In the normal mode, brief error messages are generated to
8360 @file{stderr}. If this switch is present, a header is written
8361 to @file{stdout} and any error messages are directed to @file{stdout}.
8362 All that is written to @file{stderr} is a brief summary message.
8363
8364 @item ^-b^/REPORT_ERRORS=BRIEF^
8365 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8366 Generate brief error messages to @file{stderr} even if verbose mode is
8367 specified. This is relevant only when used with the
8368 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8369
8370 @ifclear vms
8371 @item -m@var{n}
8372 @cindex @option{-m} (@code{gnatbind})
8373 Limits the number of error messages to @var{n}, a decimal integer in the
8374 range 1-999. The binder terminates immediately if this limit is reached.
8375
8376 @item -M@var{xxx}
8377 @cindex @option{-M} (@code{gnatbind})
8378 Renames the generated main program from @code{main} to @code{xxx}.
8379 This is useful in the case of some cross-building environments, where
8380 the actual main program is separate from the one generated
8381 by @code{gnatbind}.
8382 @end ifclear
8383
8384 @item ^-ws^/WARNINGS=SUPPRESS^
8385 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8386 @cindex Warnings
8387 Suppress all warning messages.
8388
8389 @item ^-we^/WARNINGS=ERROR^
8390 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8391 Treat any warning messages as fatal errors.
8392
8393 @ifset vms
8394 @item /WARNINGS=NORMAL
8395 Standard mode with warnings generated, but warnings do not get treated
8396 as errors.
8397 @end ifset
8398
8399 @item ^-t^/NOTIME_STAMP_CHECK^
8400 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8401 @cindex Time stamp checks, in binder
8402 @cindex Binder consistency checks
8403 @cindex Consistency checks, in binder
8404 The binder performs a number of consistency checks including:
8405
8406 @itemize @bullet
8407 @item
8408 Check that time stamps of a given source unit are consistent
8409 @item
8410 Check that checksums of a given source unit are consistent
8411 @item
8412 Check that consistent versions of @code{GNAT} were used for compilation
8413 @item
8414 Check consistency of configuration pragmas as required
8415 @end itemize
8416
8417 @noindent
8418 Normally failure of such checks, in accordance with the consistency
8419 requirements of the Ada Reference Manual, causes error messages to be
8420 generated which abort the binder and prevent the output of a binder
8421 file and subsequent link to obtain an executable.
8422
8423 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8424 into warnings, so that
8425 binding and linking can continue to completion even in the presence of such
8426 errors. The result may be a failed link (due to missing symbols), or a
8427 non-functional executable which has undefined semantics.
8428 @emph{This means that
8429 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8430 with extreme care.}
8431 @end table
8432
8433 @node Elaboration Control
8434 @subsection Elaboration Control
8435
8436 @noindent
8437 The following switches provide additional control over the elaboration
8438 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8439
8440 @table @option
8441 @item ^-p^/PESSIMISTIC_ELABORATION^
8442 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8443 Normally the binder attempts to choose an elaboration order that is
8444 likely to minimize the likelihood of an elaboration order error resulting
8445 in raising a @code{Program_Error} exception. This switch reverses the
8446 action of the binder, and requests that it deliberately choose an order
8447 that is likely to maximize the likelihood of an elaboration error.
8448 This is useful in ensuring portability and avoiding dependence on
8449 accidental fortuitous elaboration ordering.
8450
8451 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8452 switch if dynamic
8453 elaboration checking is used (@option{-gnatE} switch used for compilation).
8454 This is because in the default static elaboration mode, all necessary
8455 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8456 These implicit pragmas are still respected by the binder in
8457 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8458 safe elaboration order is assured.
8459 @end table
8460
8461 @node Output Control
8462 @subsection Output Control
8463
8464 @noindent
8465 The following switches allow additional control over the output
8466 generated by the binder.
8467
8468 @table @option
8469 @c !sort!
8470
8471 @item ^-A^/BIND_FILE=ADA^
8472 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8473 Generate binder program in Ada (default). The binder program is named
8474 @file{b~@var{mainprog}.adb} by default. This can be changed with
8475 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8476
8477 @item ^-c^/NOOUTPUT^
8478 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8479 Check only. Do not generate the binder output file. In this mode the
8480 binder performs all error checks but does not generate an output file.
8481
8482 @item ^-C^/BIND_FILE=C^
8483 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8484 Generate binder program in C. The binder program is named
8485 @file{b_@var{mainprog}.c}.
8486 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8487 option.
8488
8489 @item ^-e^/ELABORATION_DEPENDENCIES^
8490 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8491 Output complete list of elaboration-order dependencies, showing the
8492 reason for each dependency. This output can be rather extensive but may
8493 be useful in diagnosing problems with elaboration order. The output is
8494 written to @file{stdout}.
8495
8496 @item ^-h^/HELP^
8497 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8498 Output usage information. The output is written to @file{stdout}.
8499
8500 @item ^-K^/LINKER_OPTION_LIST^
8501 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8502 Output linker options to @file{stdout}. Includes library search paths,
8503 contents of pragmas Ident and Linker_Options, and libraries added
8504 by @code{gnatbind}.
8505
8506 @item ^-l^/ORDER_OF_ELABORATION^
8507 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8508 Output chosen elaboration order. The output is written to @file{stdout}.
8509
8510 @item ^-O^/OBJECT_LIST^
8511 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8512 Output full names of all the object files that must be linked to provide
8513 the Ada component of the program. The output is written to @file{stdout}.
8514 This list includes the files explicitly supplied and referenced by the user
8515 as well as implicitly referenced run-time unit files. The latter are
8516 omitted if the corresponding units reside in shared libraries. The
8517 directory names for the run-time units depend on the system configuration.
8518
8519 @item ^-o ^/OUTPUT=^@var{file}
8520 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8521 Set name of output file to @var{file} instead of the normal
8522 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8523 binder generated body filename. In C mode you would normally give
8524 @var{file} an extension of @file{.c} because it will be a C source program.
8525 Note that if this option is used, then linking must be done manually.
8526 It is not possible to use gnatlink in this case, since it cannot locate
8527 the binder file.
8528
8529 @item ^-r^/RESTRICTION_LIST^
8530 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8531 Generate list of @code{pragma Restrictions} that could be applied to
8532 the current unit. This is useful for code audit purposes, and also may
8533 be used to improve code generation in some cases.
8534
8535 @end table
8536
8537 @node Binding with Non-Ada Main Programs
8538 @subsection Binding with Non-Ada Main Programs
8539
8540 @noindent
8541 In our description so far we have assumed that the main
8542 program is in Ada, and that the task of the binder is to generate a
8543 corresponding function @code{main} that invokes this Ada main
8544 program. GNAT also supports the building of executable programs where
8545 the main program is not in Ada, but some of the called routines are
8546 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8547 The following switch is used in this situation:
8548
8549 @table @option
8550 @item ^-n^/NOMAIN^
8551 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8552 No main program. The main program is not in Ada.
8553 @end table
8554
8555 @noindent
8556 In this case, most of the functions of the binder are still required,
8557 but instead of generating a main program, the binder generates a file
8558 containing the following callable routines:
8559
8560 @table @code
8561 @item adainit
8562 @findex adainit
8563 You must call this routine to initialize the Ada part of the program by
8564 calling the necessary elaboration routines. A call to @code{adainit} is
8565 required before the first call to an Ada subprogram.
8566
8567 Note that it is assumed that the basic execution environment must be setup
8568 to be appropriate for Ada execution at the point where the first Ada
8569 subprogram is called. In particular, if the Ada code will do any
8570 floating-point operations, then the FPU must be setup in an appropriate
8571 manner. For the case of the x86, for example, full precision mode is
8572 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8573 that the FPU is in the right state.
8574
8575 @item adafinal
8576 @findex adafinal
8577 You must call this routine to perform any library-level finalization
8578 required by the Ada subprograms. A call to @code{adafinal} is required
8579 after the last call to an Ada subprogram, and before the program
8580 terminates.
8581 @end table
8582
8583 @noindent
8584 If the @option{^-n^/NOMAIN^} switch
8585 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8586 @cindex Binder, multiple input files
8587 is given, more than one ALI file may appear on
8588 the command line for @code{gnatbind}. The normal @dfn{closure}
8589 calculation is performed for each of the specified units. Calculating
8590 the closure means finding out the set of units involved by tracing
8591 @code{with} references. The reason it is necessary to be able to
8592 specify more than one ALI file is that a given program may invoke two or
8593 more quite separate groups of Ada units.
8594
8595 The binder takes the name of its output file from the last specified ALI
8596 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8597 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8598 The output is an Ada unit in source form that can
8599 be compiled with GNAT unless the -C switch is used in which case the
8600 output is a C source file, which must be compiled using the C compiler.
8601 This compilation occurs automatically as part of the @command{gnatlink}
8602 processing.
8603
8604 Currently the GNAT run time requires a FPU using 80 bits mode
8605 precision. Under targets where this is not the default it is required to
8606 call GNAT.Float_Control.Reset before using floating point numbers (this
8607 include float computation, float input and output) in the Ada code. A
8608 side effect is that this could be the wrong mode for the foreign code
8609 where floating point computation could be broken after this call.
8610
8611 @node Binding Programs with No Main Subprogram
8612 @subsection Binding Programs with No Main Subprogram
8613
8614 @noindent
8615 It is possible to have an Ada program which does not have a main
8616 subprogram. This program will call the elaboration routines of all the
8617 packages, then the finalization routines.
8618
8619 The following switch is used to bind programs organized in this manner:
8620
8621 @table @option
8622 @item ^-z^/ZERO_MAIN^
8623 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8624 Normally the binder checks that the unit name given on the command line
8625 corresponds to a suitable main subprogram. When this switch is used,
8626 a list of ALI files can be given, and the execution of the program
8627 consists of elaboration of these units in an appropriate order. Note
8628 that the default wide character encoding method for standard Text_IO
8629 files is always set to Brackets if this switch is set (you can use
8630 the binder switch
8631 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8632 @end table
8633
8634 @node Command-Line Access
8635 @section Command-Line Access
8636
8637 @noindent
8638 The package @code{Ada.Command_Line} provides access to the command-line
8639 arguments and program name. In order for this interface to operate
8640 correctly, the two variables
8641
8642 @smallexample
8643 @group
8644 int gnat_argc;
8645 char **gnat_argv;
8646 @end group
8647 @end smallexample
8648
8649 @noindent
8650 @findex gnat_argv
8651 @findex gnat_argc
8652 are declared in one of the GNAT library routines. These variables must
8653 be set from the actual @code{argc} and @code{argv} values passed to the
8654 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8655 generates the C main program to automatically set these variables.
8656 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8657 set these variables. If they are not set, the procedures in
8658 @code{Ada.Command_Line} will not be available, and any attempt to use
8659 them will raise @code{Constraint_Error}. If command line access is
8660 required, your main program must set @code{gnat_argc} and
8661 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8662 it.
8663
8664 @node Search Paths for gnatbind
8665 @section Search Paths for @code{gnatbind}
8666
8667 @noindent
8668 The binder takes the name of an ALI file as its argument and needs to
8669 locate source files as well as other ALI files to verify object consistency.
8670
8671 For source files, it follows exactly the same search rules as @command{gcc}
8672 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8673 directories searched are:
8674
8675 @enumerate
8676 @item
8677 The directory containing the ALI file named in the command line, unless
8678 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8679
8680 @item
8681 All directories specified by @option{^-I^/SEARCH^}
8682 switches on the @code{gnatbind}
8683 command line, in the order given.
8684
8685 @item
8686 @findex ADA_PRJ_OBJECTS_FILE
8687 Each of the directories listed in the text file whose name is given
8688 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8689
8690 @noindent
8691 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8692 driver when project files are used. It should not normally be set
8693 by other means.
8694
8695 @item
8696 @findex ADA_OBJECTS_PATH
8697 Each of the directories listed in the value of the
8698 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8699 @ifset unw
8700 Construct this value
8701 exactly as the @env{PATH} environment variable: a list of directory
8702 names separated by colons (semicolons when working with the NT version
8703 of GNAT).
8704 @end ifset
8705 @ifset vms
8706 Normally, define this value as a logical name containing a comma separated
8707 list of directory names.
8708
8709 This variable can also be defined by means of an environment string
8710 (an argument to the HP C exec* set of functions).
8711
8712 Logical Name:
8713 @smallexample
8714 DEFINE ANOTHER_PATH FOO:[BAG]
8715 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8716 @end smallexample
8717
8718 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8719 first, followed by the standard Ada
8720 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8721 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8722 (Text_IO, Sequential_IO, etc)
8723 instead of the standard Ada packages. Thus, in order to get the standard Ada
8724 packages by default, ADA_OBJECTS_PATH must be redefined.
8725 @end ifset
8726
8727 @item
8728 The content of the @file{ada_object_path} file which is part of the GNAT
8729 installation tree and is used to store standard libraries such as the
8730 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8731 specified.
8732 @ifclear vms
8733 @ref{Installing a library}
8734 @end ifclear
8735 @end enumerate
8736
8737 @noindent
8738 In the binder the switch @option{^-I^/SEARCH^}
8739 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8740 is used to specify both source and
8741 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8742 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8743 instead if you want to specify
8744 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8745 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8746 if you want to specify library paths
8747 only. This means that for the binder
8748 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8749 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8750 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8751 The binder generates the bind file (a C language source file) in the
8752 current working directory.
8753
8754 @findex Ada
8755 @findex System
8756 @findex Interfaces
8757 @findex GNAT
8758 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8759 children make up the GNAT Run-Time Library, together with the package
8760 GNAT and its children, which contain a set of useful additional
8761 library functions provided by GNAT. The sources for these units are
8762 needed by the compiler and are kept together in one directory. The ALI
8763 files and object files generated by compiling the RTL are needed by the
8764 binder and the linker and are kept together in one directory, typically
8765 different from the directory containing the sources. In a normal
8766 installation, you need not specify these directory names when compiling
8767 or binding. Either the environment variables or the built-in defaults
8768 cause these files to be found.
8769
8770 Besides simplifying access to the RTL, a major use of search paths is
8771 in compiling sources from multiple directories. This can make
8772 development environments much more flexible.
8773
8774 @node Examples of gnatbind Usage
8775 @section Examples of @code{gnatbind} Usage
8776
8777 @noindent
8778 This section contains a number of examples of using the GNAT binding
8779 utility @code{gnatbind}.
8780
8781 @table @code
8782 @item gnatbind hello
8783 The main program @code{Hello} (source program in @file{hello.adb}) is
8784 bound using the standard switch settings. The generated main program is
8785 @file{b~hello.adb}. This is the normal, default use of the binder.
8786
8787 @ifclear vms
8788 @item gnatbind hello -o mainprog.adb
8789 @end ifclear
8790 @ifset vms
8791 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8792 @end ifset
8793 The main program @code{Hello} (source program in @file{hello.adb}) is
8794 bound using the standard switch settings. The generated main program is
8795 @file{mainprog.adb} with the associated spec in
8796 @file{mainprog.ads}. Note that you must specify the body here not the
8797 spec, in the case where the output is in Ada. Note that if this option
8798 is used, then linking must be done manually, since gnatlink will not
8799 be able to find the generated file.
8800
8801 @ifclear vms
8802 @item gnatbind main -C -o mainprog.c -x
8803 @end ifclear
8804 @ifset vms
8805 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8806 @end ifset
8807 The main program @code{Main} (source program in
8808 @file{main.adb}) is bound, excluding source files from the
8809 consistency checking, generating
8810 the file @file{mainprog.c}.
8811
8812 @ifclear vms
8813 @item gnatbind -x main_program -C -o mainprog.c
8814 This command is exactly the same as the previous example. Switches may
8815 appear anywhere in the command line, and single letter switches may be
8816 combined into a single switch.
8817 @end ifclear
8818
8819 @ifclear vms
8820 @item gnatbind -n math dbase -C -o ada-control.c
8821 @end ifclear
8822 @ifset vms
8823 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8824 @end ifset
8825 The main program is in a language other than Ada, but calls to
8826 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8827 to @code{gnatbind} generates the file @file{ada-control.c} containing
8828 the @code{adainit} and @code{adafinal} routines to be called before and
8829 after accessing the Ada units.
8830 @end table
8831
8832 @c ------------------------------------
8833 @node Linking Using gnatlink
8834 @chapter Linking Using @command{gnatlink}
8835 @c ------------------------------------
8836 @findex gnatlink
8837
8838 @noindent
8839 This chapter discusses @command{gnatlink}, a tool that links
8840 an Ada program and builds an executable file. This utility
8841 invokes the system linker ^(via the @command{gcc} command)^^
8842 with a correct list of object files and library references.
8843 @command{gnatlink} automatically determines the list of files and
8844 references for the Ada part of a program. It uses the binder file
8845 generated by the @command{gnatbind} to determine this list.
8846
8847 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8848 driver (see @ref{The GNAT Driver and Project Files}).
8849
8850 @menu
8851 * Running gnatlink::
8852 * Switches for gnatlink::
8853 @end menu
8854
8855 @node Running gnatlink
8856 @section Running @command{gnatlink}
8857
8858 @noindent
8859 The form of the @command{gnatlink} command is
8860
8861 @smallexample
8862 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8863 @ovar{non-Ada objects} @ovar{linker options}
8864 @end smallexample
8865
8866 @noindent
8867 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8868 non-Ada objects
8869 or linker options) may be in any order, provided that no non-Ada object may
8870 be mistaken for a main @file{ALI} file.
8871 Any file name @file{F} without the @file{.ali}
8872 extension will be taken as the main @file{ALI} file if a file exists
8873 whose name is the concatenation of @file{F} and @file{.ali}.
8874
8875 @noindent
8876 @file{@var{mainprog}.ali} references the ALI file of the main program.
8877 The @file{.ali} extension of this file can be omitted. From this
8878 reference, @command{gnatlink} locates the corresponding binder file
8879 @file{b~@var{mainprog}.adb} and, using the information in this file along
8880 with the list of non-Ada objects and linker options, constructs a
8881 linker command file to create the executable.
8882
8883 The arguments other than the @command{gnatlink} switches and the main
8884 @file{ALI} file are passed to the linker uninterpreted.
8885 They typically include the names of
8886 object files for units written in other languages than Ada and any library
8887 references required to resolve references in any of these foreign language
8888 units, or in @code{Import} pragmas in any Ada units.
8889
8890 @var{linker options} is an optional list of linker specific
8891 switches.
8892 The default linker called by gnatlink is @command{gcc} which in
8893 turn calls the appropriate system linker.
8894 Standard options for the linker such as @option{-lmy_lib} or
8895 @option{-Ldir} can be added as is.
8896 For options that are not recognized by
8897 @command{gcc} as linker options, use the @command{gcc} switches
8898 @option{-Xlinker} or @option{-Wl,}.
8899 Refer to the GCC documentation for
8900 details. Here is an example showing how to generate a linker map:
8901
8902 @smallexample
8903 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8904 @end smallexample
8905
8906 Using @var{linker options} it is possible to set the program stack and
8907 heap size.
8908 @ifset unw
8909 See @ref{Setting Stack Size from gnatlink} and
8910 @ref{Setting Heap Size from gnatlink}.
8911 @end ifset
8912
8913 @command{gnatlink} determines the list of objects required by the Ada
8914 program and prepends them to the list of objects passed to the linker.
8915 @command{gnatlink} also gathers any arguments set by the use of
8916 @code{pragma Linker_Options} and adds them to the list of arguments
8917 presented to the linker.
8918
8919 @ifset vms
8920 @command{gnatlink} accepts the following types of extra files on the command
8921 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8922 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8923 handled according to their extension.
8924 @end ifset
8925
8926 @node Switches for gnatlink
8927 @section Switches for @command{gnatlink}
8928
8929 @noindent
8930 The following switches are available with the @command{gnatlink} utility:
8931
8932 @table @option
8933 @c !sort!
8934
8935 @item --version
8936 @cindex @option{--version} @command{gnatlink}
8937 Display Copyright and version, then exit disregarding all other options.
8938
8939 @item --help
8940 @cindex @option{--help} @command{gnatlink}
8941 If @option{--version} was not used, display usage, then exit disregarding
8942 all other options.
8943
8944 @item ^-A^/BIND_FILE=ADA^
8945 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8946 The binder has generated code in Ada. This is the default.
8947
8948 @item ^-C^/BIND_FILE=C^
8949 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8950 If instead of generating a file in Ada, the binder has generated one in
8951 C, then the linker needs to know about it. Use this switch to signal
8952 to @command{gnatlink} that the binder has generated C code rather than
8953 Ada code.
8954
8955 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8956 @cindex Command line length
8957 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8958 On some targets, the command line length is limited, and @command{gnatlink}
8959 will generate a separate file for the linker if the list of object files
8960 is too long.
8961 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8962 to be generated even if
8963 the limit is not exceeded. This is useful in some cases to deal with
8964 special situations where the command line length is exceeded.
8965
8966 @item ^-g^/DEBUG^
8967 @cindex Debugging information, including
8968 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8969 The option to include debugging information causes the Ada bind file (in
8970 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8971 @option{^-g^/DEBUG^}.
8972 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8973 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8974 Without @option{^-g^/DEBUG^}, the binder removes these files by
8975 default. The same procedure apply if a C bind file was generated using
8976 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8977 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8978
8979 @item ^-n^/NOCOMPILE^
8980 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8981 Do not compile the file generated by the binder. This may be used when
8982 a link is rerun with different options, but there is no need to recompile
8983 the binder file.
8984
8985 @item ^-v^/VERBOSE^
8986 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8987 Causes additional information to be output, including a full list of the
8988 included object files. This switch option is most useful when you want
8989 to see what set of object files are being used in the link step.
8990
8991 @item ^-v -v^/VERBOSE/VERBOSE^
8992 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8993 Very verbose mode. Requests that the compiler operate in verbose mode when
8994 it compiles the binder file, and that the system linker run in verbose mode.
8995
8996 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8997 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8998 @var{exec-name} specifies an alternate name for the generated
8999 executable program. If this switch is omitted, the executable has the same
9000 name as the main unit. For example, @code{gnatlink try.ali} creates
9001 an executable called @file{^try^TRY.EXE^}.
9002
9003 @ifclear vms
9004 @item -b @var{target}
9005 @cindex @option{-b} (@command{gnatlink})
9006 Compile your program to run on @var{target}, which is the name of a
9007 system configuration. You must have a GNAT cross-compiler built if
9008 @var{target} is not the same as your host system.
9009
9010 @item -B@var{dir}
9011 @cindex @option{-B} (@command{gnatlink})
9012 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9013 from @var{dir} instead of the default location. Only use this switch
9014 when multiple versions of the GNAT compiler are available.
9015 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9016 for further details. You would normally use the @option{-b} or
9017 @option{-V} switch instead.
9018
9019 @item --GCC=@var{compiler_name}
9020 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9021 Program used for compiling the binder file. The default is
9022 @command{gcc}. You need to use quotes around @var{compiler_name} if
9023 @code{compiler_name} contains spaces or other separator characters.
9024 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9025 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9026 inserted after your command name. Thus in the above example the compiler
9027 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9028 A limitation of this syntax is that the name and path name of the executable
9029 itself must not include any embedded spaces. If the compiler executable is
9030 different from the default one (gcc or <prefix>-gcc), then the back-end
9031 switches in the ALI file are not used to compile the binder generated source.
9032 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9033 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9034 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9035 is taken into account. However, all the additional switches are also taken
9036 into account. Thus,
9037 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9038 @option{--GCC="bar -x -y -z -t"}.
9039
9040 @item --LINK=@var{name}
9041 @cindex @option{--LINK=} (@command{gnatlink})
9042 @var{name} is the name of the linker to be invoked. This is especially
9043 useful in mixed language programs since languages such as C++ require
9044 their own linker to be used. When this switch is omitted, the default
9045 name for the linker is @command{gcc}. When this switch is used, the
9046 specified linker is called instead of @command{gcc} with exactly the same
9047 parameters that would have been passed to @command{gcc} so if the desired
9048 linker requires different parameters it is necessary to use a wrapper
9049 script that massages the parameters before invoking the real linker. It
9050 may be useful to control the exact invocation by using the verbose
9051 switch.
9052
9053 @end ifclear
9054
9055 @ifset vms
9056 @item /DEBUG=TRACEBACK
9057 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9058 This qualifier causes sufficient information to be included in the
9059 executable file to allow a traceback, but does not include the full
9060 symbol information needed by the debugger.
9061
9062 @item /IDENTIFICATION="<string>"
9063 @code{"<string>"} specifies the string to be stored in the image file
9064 identification field in the image header.
9065 It overrides any pragma @code{Ident} specified string.
9066
9067 @item /NOINHIBIT-EXEC
9068 Generate the executable file even if there are linker warnings.
9069
9070 @item /NOSTART_FILES
9071 Don't link in the object file containing the ``main'' transfer address.
9072 Used when linking with a foreign language main program compiled with an
9073 HP compiler.
9074
9075 @item /STATIC
9076 Prefer linking with object libraries over sharable images, even without
9077 /DEBUG.
9078 @end ifset
9079
9080 @end table
9081
9082 @node The GNAT Make Program gnatmake
9083 @chapter The GNAT Make Program @command{gnatmake}
9084 @findex gnatmake
9085
9086 @menu
9087 * Running gnatmake::
9088 * Switches for gnatmake::
9089 * Mode Switches for gnatmake::
9090 * Notes on the Command Line::
9091 * How gnatmake Works::
9092 * Examples of gnatmake Usage::
9093 @end menu
9094 @noindent
9095 A typical development cycle when working on an Ada program consists of
9096 the following steps:
9097
9098 @enumerate
9099 @item
9100 Edit some sources to fix bugs.
9101
9102 @item
9103 Add enhancements.
9104
9105 @item
9106 Compile all sources affected.
9107
9108 @item
9109 Rebind and relink.
9110
9111 @item
9112 Test.
9113 @end enumerate
9114
9115 @noindent
9116 The third step can be tricky, because not only do the modified files
9117 @cindex Dependency rules
9118 have to be compiled, but any files depending on these files must also be
9119 recompiled. The dependency rules in Ada can be quite complex, especially
9120 in the presence of overloading, @code{use} clauses, generics and inlined
9121 subprograms.
9122
9123 @command{gnatmake} automatically takes care of the third and fourth steps
9124 of this process. It determines which sources need to be compiled,
9125 compiles them, and binds and links the resulting object files.
9126
9127 Unlike some other Ada make programs, the dependencies are always
9128 accurately recomputed from the new sources. The source based approach of
9129 the GNAT compilation model makes this possible. This means that if
9130 changes to the source program cause corresponding changes in
9131 dependencies, they will always be tracked exactly correctly by
9132 @command{gnatmake}.
9133
9134 @node Running gnatmake
9135 @section Running @command{gnatmake}
9136
9137 @noindent
9138 The usual form of the @command{gnatmake} command is
9139
9140 @smallexample
9141 $ gnatmake @ovar{switches} @var{file_name}
9142 @ovar{file_names} @ovar{mode_switches}
9143 @end smallexample
9144
9145 @noindent
9146 The only required argument is one @var{file_name}, which specifies
9147 a compilation unit that is a main program. Several @var{file_names} can be
9148 specified: this will result in several executables being built.
9149 If @code{switches} are present, they can be placed before the first
9150 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9151 If @var{mode_switches} are present, they must always be placed after
9152 the last @var{file_name} and all @code{switches}.
9153
9154 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9155 extension may be omitted from the @var{file_name} arguments. However, if
9156 you are using non-standard extensions, then it is required that the
9157 extension be given. A relative or absolute directory path can be
9158 specified in a @var{file_name}, in which case, the input source file will
9159 be searched for in the specified directory only. Otherwise, the input
9160 source file will first be searched in the directory where
9161 @command{gnatmake} was invoked and if it is not found, it will be search on
9162 the source path of the compiler as described in
9163 @ref{Search Paths and the Run-Time Library (RTL)}.
9164
9165 All @command{gnatmake} output (except when you specify
9166 @option{^-M^/DEPENDENCIES_LIST^}) is to
9167 @file{stderr}. The output produced by the
9168 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9169 @file{stdout}.
9170
9171 @node Switches for gnatmake
9172 @section Switches for @command{gnatmake}
9173
9174 @noindent
9175 You may specify any of the following switches to @command{gnatmake}:
9176
9177 @table @option
9178 @c !sort!
9179
9180 @item --version
9181 @cindex @option{--version} @command{gnatmake}
9182 Display Copyright and version, then exit disregarding all other options.
9183
9184 @item --help
9185 @cindex @option{--help} @command{gnatmake}
9186 If @option{--version} was not used, display usage, then exit disregarding
9187 all other options.
9188
9189 @ifclear vms
9190 @item --GCC=@var{compiler_name}
9191 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9192 Program used for compiling. The default is `@command{gcc}'. You need to use
9193 quotes around @var{compiler_name} if @code{compiler_name} contains
9194 spaces or other separator characters. As an example @option{--GCC="foo -x
9195 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9196 compiler. A limitation of this syntax is that the name and path name of
9197 the executable itself must not include any embedded spaces. Note that
9198 switch @option{-c} is always inserted after your command name. Thus in the
9199 above example the compiler command that will be used by @command{gnatmake}
9200 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9201 used, only the last @var{compiler_name} is taken into account. However,
9202 all the additional switches are also taken into account. Thus,
9203 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9204 @option{--GCC="bar -x -y -z -t"}.
9205
9206 @item --GNATBIND=@var{binder_name}
9207 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9208 Program used for binding. The default is `@code{gnatbind}'. You need to
9209 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9210 or other separator characters. As an example @option{--GNATBIND="bar -x
9211 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9212 binder. Binder switches that are normally appended by @command{gnatmake}
9213 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9214 A limitation of this syntax is that the name and path name of the executable
9215 itself must not include any embedded spaces.
9216
9217 @item --GNATLINK=@var{linker_name}
9218 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9219 Program used for linking. The default is `@command{gnatlink}'. You need to
9220 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9221 or other separator characters. As an example @option{--GNATLINK="lan -x
9222 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9223 linker. Linker switches that are normally appended by @command{gnatmake} to
9224 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9225 A limitation of this syntax is that the name and path name of the executable
9226 itself must not include any embedded spaces.
9227
9228 @end ifclear
9229
9230 @item ^-a^/ALL_FILES^
9231 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9232 Consider all files in the make process, even the GNAT internal system
9233 files (for example, the predefined Ada library files), as well as any
9234 locked files. Locked files are files whose ALI file is write-protected.
9235 By default,
9236 @command{gnatmake} does not check these files,
9237 because the assumption is that the GNAT internal files are properly up
9238 to date, and also that any write protected ALI files have been properly
9239 installed. Note that if there is an installation problem, such that one
9240 of these files is not up to date, it will be properly caught by the
9241 binder.
9242 You may have to specify this switch if you are working on GNAT
9243 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9244 in conjunction with @option{^-f^/FORCE_COMPILE^}
9245 if you need to recompile an entire application,
9246 including run-time files, using special configuration pragmas,
9247 such as a @code{Normalize_Scalars} pragma.
9248
9249 By default
9250 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9251 internal files with
9252 @ifclear vms
9253 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9254 @end ifclear
9255 @ifset vms
9256 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9257 @end ifset
9258
9259 @item ^-b^/ACTIONS=BIND^
9260 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9261 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9262 compilation and binding, but no link.
9263 Can be combined with @option{^-l^/ACTIONS=LINK^}
9264 to do binding and linking. When not combined with
9265 @option{^-c^/ACTIONS=COMPILE^}
9266 all the units in the closure of the main program must have been previously
9267 compiled and must be up to date. The root unit specified by @var{file_name}
9268 may be given without extension, with the source extension or, if no GNAT
9269 Project File is specified, with the ALI file extension.
9270
9271 @item ^-c^/ACTIONS=COMPILE^
9272 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9273 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9274 is also specified. Do not perform linking, except if both
9275 @option{^-b^/ACTIONS=BIND^} and
9276 @option{^-l^/ACTIONS=LINK^} are also specified.
9277 If the root unit specified by @var{file_name} is not a main unit, this is the
9278 default. Otherwise @command{gnatmake} will attempt binding and linking
9279 unless all objects are up to date and the executable is more recent than
9280 the objects.
9281
9282 @item ^-C^/MAPPING^
9283 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9284 Use a temporary mapping file. A mapping file is a way to communicate
9285 to the compiler two mappings: from unit names to file names (without
9286 any directory information) and from file names to path names (with
9287 full directory information). A mapping file can make the compiler's
9288 file searches faster, especially if there are many source directories,
9289 or the sources are read over a slow network connection. If
9290 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9291 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9292 is initially populated based on the project file. If
9293 @option{^-C^/MAPPING^} is used without
9294 @option{^-P^/PROJECT_FILE^},
9295 the mapping file is initially empty. Each invocation of the compiler
9296 will add any newly accessed sources to the mapping file.
9297
9298 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9299 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9300 Use a specific mapping file. The file, specified as a path name (absolute or
9301 relative) by this switch, should already exist, otherwise the switch is
9302 ineffective. The specified mapping file will be communicated to the compiler.
9303 This switch is not compatible with a project file
9304 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9305 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9306
9307 @item ^-d^/DISPLAY_PROGRESS^
9308 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9309 Display progress for each source, up to date or not, as a single line
9310
9311 @smallexample
9312 completed x out of y (zz%)
9313 @end smallexample
9314
9315 If the file needs to be compiled this is displayed after the invocation of
9316 the compiler. These lines are displayed even in quiet output mode.
9317
9318 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9319 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9320 Put all object files and ALI file in directory @var{dir}.
9321 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9322 and ALI files go in the current working directory.
9323
9324 This switch cannot be used when using a project file.
9325
9326 @ifclear vms
9327 @item -eL
9328 @cindex @option{-eL} (@command{gnatmake})
9329 Follow all symbolic links when processing project files.
9330 @end ifclear
9331
9332 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9333 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9334 Output the commands for the compiler, the binder and the linker
9335 on ^standard output^SYS$OUTPUT^,
9336 instead of ^standard error^SYS$ERROR^.
9337
9338 @item ^-f^/FORCE_COMPILE^
9339 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9340 Force recompilations. Recompile all sources, even though some object
9341 files may be up to date, but don't recompile predefined or GNAT internal
9342 files or locked files (files with a write-protected ALI file),
9343 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9344
9345 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9346 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9347 When using project files, if some errors or warnings are detected during
9348 parsing and verbose mode is not in effect (no use of switch
9349 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9350 file, rather than its simple file name.
9351
9352 @item ^-g^/DEBUG^
9353 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9354 Enable debugging. This switch is simply passed to the compiler and to the
9355 linker.
9356
9357 @item ^-i^/IN_PLACE^
9358 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9359 In normal mode, @command{gnatmake} compiles all object files and ALI files
9360 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9361 then instead object files and ALI files that already exist are overwritten
9362 in place. This means that once a large project is organized into separate
9363 directories in the desired manner, then @command{gnatmake} will automatically
9364 maintain and update this organization. If no ALI files are found on the
9365 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9366 the new object and ALI files are created in the
9367 directory containing the source being compiled. If another organization
9368 is desired, where objects and sources are kept in different directories,
9369 a useful technique is to create dummy ALI files in the desired directories.
9370 When detecting such a dummy file, @command{gnatmake} will be forced to
9371 recompile the corresponding source file, and it will be put the resulting
9372 object and ALI files in the directory where it found the dummy file.
9373
9374 @item ^-j^/PROCESSES=^@var{n}
9375 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9376 @cindex Parallel make
9377 Use @var{n} processes to carry out the (re)compilations. On a
9378 multiprocessor machine compilations will occur in parallel. In the
9379 event of compilation errors, messages from various compilations might
9380 get interspersed (but @command{gnatmake} will give you the full ordered
9381 list of failing compiles at the end). If this is problematic, rerun
9382 the make process with n set to 1 to get a clean list of messages.
9383
9384 @item ^-k^/CONTINUE_ON_ERROR^
9385 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9386 Keep going. Continue as much as possible after a compilation error. To
9387 ease the programmer's task in case of compilation errors, the list of
9388 sources for which the compile fails is given when @command{gnatmake}
9389 terminates.
9390
9391 If @command{gnatmake} is invoked with several @file{file_names} and with this
9392 switch, if there are compilation errors when building an executable,
9393 @command{gnatmake} will not attempt to build the following executables.
9394
9395 @item ^-l^/ACTIONS=LINK^
9396 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9397 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9398 and linking. Linking will not be performed if combined with
9399 @option{^-c^/ACTIONS=COMPILE^}
9400 but not with @option{^-b^/ACTIONS=BIND^}.
9401 When not combined with @option{^-b^/ACTIONS=BIND^}
9402 all the units in the closure of the main program must have been previously
9403 compiled and must be up to date, and the main program needs to have been bound.
9404 The root unit specified by @var{file_name}
9405 may be given without extension, with the source extension or, if no GNAT
9406 Project File is specified, with the ALI file extension.
9407
9408 @item ^-m^/MINIMAL_RECOMPILATION^
9409 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9410 Specify that the minimum necessary amount of recompilations
9411 be performed. In this mode @command{gnatmake} ignores time
9412 stamp differences when the only
9413 modifications to a source file consist in adding/removing comments,
9414 empty lines, spaces or tabs. This means that if you have changed the
9415 comments in a source file or have simply reformatted it, using this
9416 switch will tell @command{gnatmake} not to recompile files that depend on it
9417 (provided other sources on which these files depend have undergone no
9418 semantic modifications). Note that the debugging information may be
9419 out of date with respect to the sources if the @option{-m} switch causes
9420 a compilation to be switched, so the use of this switch represents a
9421 trade-off between compilation time and accurate debugging information.
9422
9423 @item ^-M^/DEPENDENCIES_LIST^
9424 @cindex Dependencies, producing list
9425 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9426 Check if all objects are up to date. If they are, output the object
9427 dependences to @file{stdout} in a form that can be directly exploited in
9428 a @file{Makefile}. By default, each source file is prefixed with its
9429 (relative or absolute) directory name. This name is whatever you
9430 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9431 and @option{^-I^/SEARCH^} switches. If you use
9432 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9433 @option{^-q^/QUIET^}
9434 (see below), only the source file names,
9435 without relative paths, are output. If you just specify the
9436 @option{^-M^/DEPENDENCIES_LIST^}
9437 switch, dependencies of the GNAT internal system files are omitted. This
9438 is typically what you want. If you also specify
9439 the @option{^-a^/ALL_FILES^} switch,
9440 dependencies of the GNAT internal files are also listed. Note that
9441 dependencies of the objects in external Ada libraries (see switch
9442 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9443 are never reported.
9444
9445 @item ^-n^/DO_OBJECT_CHECK^
9446 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9447 Don't compile, bind, or link. Checks if all objects are up to date.
9448 If they are not, the full name of the first file that needs to be
9449 recompiled is printed.
9450 Repeated use of this option, followed by compiling the indicated source
9451 file, will eventually result in recompiling all required units.
9452
9453 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9454 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9455 Output executable name. The name of the final executable program will be
9456 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9457 name for the executable will be the name of the input file in appropriate form
9458 for an executable file on the host system.
9459
9460 This switch cannot be used when invoking @command{gnatmake} with several
9461 @file{file_names}.
9462
9463 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9464 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9465 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9466 automatically missing object directories, library directories and exec
9467 directories.
9468
9469 @item ^-P^/PROJECT_FILE=^@var{project}
9470 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9471 Use project file @var{project}. Only one such switch can be used.
9472 @xref{gnatmake and Project Files}.
9473
9474 @item ^-q^/QUIET^
9475 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9476 Quiet. When this flag is not set, the commands carried out by
9477 @command{gnatmake} are displayed.
9478
9479 @item ^-s^/SWITCH_CHECK/^
9480 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9481 Recompile if compiler switches have changed since last compilation.
9482 All compiler switches but -I and -o are taken into account in the
9483 following way:
9484 orders between different ``first letter'' switches are ignored, but
9485 orders between same switches are taken into account. For example,
9486 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9487 is equivalent to @option{-O -g}.
9488
9489 This switch is recommended when Integrated Preprocessing is used.
9490
9491 @item ^-u^/UNIQUE^
9492 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9493 Unique. Recompile at most the main files. It implies -c. Combined with
9494 -f, it is equivalent to calling the compiler directly. Note that using
9495 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9496 (@pxref{Project Files and Main Subprograms}).
9497
9498 @item ^-U^/ALL_PROJECTS^
9499 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9500 When used without a project file or with one or several mains on the command
9501 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9502 on the command line, all sources of all project files are checked and compiled
9503 if not up to date, and libraries are rebuilt, if necessary.
9504
9505 @item ^-v^/REASONS^
9506 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9507 Verbose. Display the reason for all recompilations @command{gnatmake}
9508 decides are necessary, with the highest verbosity level.
9509
9510 @item ^-vl^/LOW_VERBOSITY^
9511 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9512 Verbosity level Low. Display fewer lines than in verbosity Medium.
9513
9514 @item ^-vm^/MEDIUM_VERBOSITY^
9515 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9516 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9517
9518 @item ^-vh^/HIGH_VERBOSITY^
9519 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9520 Verbosity level High. Equivalent to ^-v^/REASONS^.
9521
9522 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9523 Indicate the verbosity of the parsing of GNAT project files.
9524 @xref{Switches Related to Project Files}.
9525
9526 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9527 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9528 Indicate that sources that are not part of any Project File may be compiled.
9529 Normally, when using Project Files, only sources that are part of a Project
9530 File may be compile. When this switch is used, a source outside of all Project
9531 Files may be compiled. The ALI file and the object file will be put in the
9532 object directory of the main Project. The compilation switches used will only
9533 be those specified on the command line. Even when
9534 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9535 command line need to be sources of a project file.
9536
9537 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9538 Indicate that external variable @var{name} has the value @var{value}.
9539 The Project Manager will use this value for occurrences of
9540 @code{external(name)} when parsing the project file.
9541 @xref{Switches Related to Project Files}.
9542
9543 @item ^-z^/NOMAIN^
9544 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9545 No main subprogram. Bind and link the program even if the unit name
9546 given on the command line is a package name. The resulting executable
9547 will execute the elaboration routines of the package and its closure,
9548 then the finalization routines.
9549
9550 @end table
9551
9552 @table @asis
9553 @item @command{gcc} @asis{switches}
9554 @ifclear vms
9555 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9556 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9557 @end ifclear
9558 @ifset vms
9559 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9560 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9561 automatically treated as a compiler switch, and passed on to all
9562 compilations that are carried out.
9563 @end ifset
9564 @end table
9565
9566 @noindent
9567 Source and library search path switches:
9568
9569 @table @option
9570 @c !sort!
9571 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9572 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9573 When looking for source files also look in directory @var{dir}.
9574 The order in which source files search is undertaken is
9575 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9576
9577 @item ^-aL^/SKIP_MISSING=^@var{dir}
9578 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9579 Consider @var{dir} as being an externally provided Ada library.
9580 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9581 files have been located in directory @var{dir}. This allows you to have
9582 missing bodies for the units in @var{dir} and to ignore out of date bodies
9583 for the same units. You still need to specify
9584 the location of the specs for these units by using the switches
9585 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9586 or @option{^-I^/SEARCH=^@var{dir}}.
9587 Note: this switch is provided for compatibility with previous versions
9588 of @command{gnatmake}. The easier method of causing standard libraries
9589 to be excluded from consideration is to write-protect the corresponding
9590 ALI files.
9591
9592 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9593 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9594 When searching for library and object files, look in directory
9595 @var{dir}. The order in which library files are searched is described in
9596 @ref{Search Paths for gnatbind}.
9597
9598 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9599 @cindex Search paths, for @command{gnatmake}
9600 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9601 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9602 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9603
9604 @item ^-I^/SEARCH=^@var{dir}
9605 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9606 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9607 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9608
9609 @item ^-I-^/NOCURRENT_DIRECTORY^
9610 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9611 @cindex Source files, suppressing search
9612 Do not look for source files in the directory containing the source
9613 file named in the command line.
9614 Do not look for ALI or object files in the directory
9615 where @command{gnatmake} was invoked.
9616
9617 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9618 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9619 @cindex Linker libraries
9620 Add directory @var{dir} to the list of directories in which the linker
9621 will search for libraries. This is equivalent to
9622 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9623 @ifclear vms
9624 Furthermore, under Windows, the sources pointed to by the libraries path
9625 set in the registry are not searched for.
9626 @end ifclear
9627
9628 @item -nostdinc
9629 @cindex @option{-nostdinc} (@command{gnatmake})
9630 Do not look for source files in the system default directory.
9631
9632 @item -nostdlib
9633 @cindex @option{-nostdlib} (@command{gnatmake})
9634 Do not look for library files in the system default directory.
9635
9636 @item --RTS=@var{rts-path}
9637 @cindex @option{--RTS} (@command{gnatmake})
9638 Specifies the default location of the runtime library. GNAT looks for the
9639 runtime
9640 in the following directories, and stops as soon as a valid runtime is found
9641 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9642 @file{ada_object_path} present):
9643
9644 @itemize @bullet
9645 @item <current directory>/$rts_path
9646
9647 @item <default-search-dir>/$rts_path
9648
9649 @item <default-search-dir>/rts-$rts_path
9650 @end itemize
9651
9652 @noindent
9653 The selected path is handled like a normal RTS path.
9654
9655 @end table
9656
9657 @node Mode Switches for gnatmake
9658 @section Mode Switches for @command{gnatmake}
9659
9660 @noindent
9661 The mode switches (referred to as @code{mode_switches}) allow the
9662 inclusion of switches that are to be passed to the compiler itself, the
9663 binder or the linker. The effect of a mode switch is to cause all
9664 subsequent switches up to the end of the switch list, or up to the next
9665 mode switch, to be interpreted as switches to be passed on to the
9666 designated component of GNAT.
9667
9668 @table @option
9669 @c !sort!
9670 @item -cargs @var{switches}
9671 @cindex @option{-cargs} (@command{gnatmake})
9672 Compiler switches. Here @var{switches} is a list of switches
9673 that are valid switches for @command{gcc}. They will be passed on to
9674 all compile steps performed by @command{gnatmake}.
9675
9676 @item -bargs @var{switches}
9677 @cindex @option{-bargs} (@command{gnatmake})
9678 Binder switches. Here @var{switches} is a list of switches
9679 that are valid switches for @code{gnatbind}. They will be passed on to
9680 all bind steps performed by @command{gnatmake}.
9681
9682 @item -largs @var{switches}
9683 @cindex @option{-largs} (@command{gnatmake})
9684 Linker switches. Here @var{switches} is a list of switches
9685 that are valid switches for @command{gnatlink}. They will be passed on to
9686 all link steps performed by @command{gnatmake}.
9687
9688 @item -margs @var{switches}
9689 @cindex @option{-margs} (@command{gnatmake})
9690 Make switches. The switches are directly interpreted by @command{gnatmake},
9691 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9692 or @option{-largs}.
9693 @end table
9694
9695 @node Notes on the Command Line
9696 @section Notes on the Command Line
9697
9698 @noindent
9699 This section contains some additional useful notes on the operation
9700 of the @command{gnatmake} command.
9701
9702 @itemize @bullet
9703 @item
9704 @cindex Recompilation, by @command{gnatmake}
9705 If @command{gnatmake} finds no ALI files, it recompiles the main program
9706 and all other units required by the main program.
9707 This means that @command{gnatmake}
9708 can be used for the initial compile, as well as during subsequent steps of
9709 the development cycle.
9710
9711 @item
9712 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9713 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9714 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9715 warning.
9716
9717 @item
9718 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9719 is used to specify both source and
9720 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9721 instead if you just want to specify
9722 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9723 if you want to specify library paths
9724 only.
9725
9726 @item
9727 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9728 This may conveniently be used to exclude standard libraries from
9729 consideration and in particular it means that the use of the
9730 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9731 unless @option{^-a^/ALL_FILES^} is also specified.
9732
9733 @item
9734 @command{gnatmake} has been designed to make the use of Ada libraries
9735 particularly convenient. Assume you have an Ada library organized
9736 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9737 of your Ada compilation units,
9738 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9739 specs of these units, but no bodies. Then to compile a unit
9740 stored in @code{main.adb}, which uses this Ada library you would just type
9741
9742 @smallexample
9743 @ifclear vms
9744 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9745 @end ifclear
9746 @ifset vms
9747 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9748 /SKIP_MISSING=@i{[OBJ_DIR]} main
9749 @end ifset
9750 @end smallexample
9751
9752 @item
9753 Using @command{gnatmake} along with the
9754 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9755 switch provides a mechanism for avoiding unnecessary recompilations. Using
9756 this switch,
9757 you can update the comments/format of your
9758 source files without having to recompile everything. Note, however, that
9759 adding or deleting lines in a source files may render its debugging
9760 info obsolete. If the file in question is a spec, the impact is rather
9761 limited, as that debugging info will only be useful during the
9762 elaboration phase of your program. For bodies the impact can be more
9763 significant. In all events, your debugger will warn you if a source file
9764 is more recent than the corresponding object, and alert you to the fact
9765 that the debugging information may be out of date.
9766 @end itemize
9767
9768 @node How gnatmake Works
9769 @section How @command{gnatmake} Works
9770
9771 @noindent
9772 Generally @command{gnatmake} automatically performs all necessary
9773 recompilations and you don't need to worry about how it works. However,
9774 it may be useful to have some basic understanding of the @command{gnatmake}
9775 approach and in particular to understand how it uses the results of
9776 previous compilations without incorrectly depending on them.
9777
9778 First a definition: an object file is considered @dfn{up to date} if the
9779 corresponding ALI file exists and if all the source files listed in the
9780 dependency section of this ALI file have time stamps matching those in
9781 the ALI file. This means that neither the source file itself nor any
9782 files that it depends on have been modified, and hence there is no need
9783 to recompile this file.
9784
9785 @command{gnatmake} works by first checking if the specified main unit is up
9786 to date. If so, no compilations are required for the main unit. If not,
9787 @command{gnatmake} compiles the main program to build a new ALI file that
9788 reflects the latest sources. Then the ALI file of the main unit is
9789 examined to find all the source files on which the main program depends,
9790 and @command{gnatmake} recursively applies the above procedure on all these
9791 files.
9792
9793 This process ensures that @command{gnatmake} only trusts the dependencies
9794 in an existing ALI file if they are known to be correct. Otherwise it
9795 always recompiles to determine a new, guaranteed accurate set of
9796 dependencies. As a result the program is compiled ``upside down'' from what may
9797 be more familiar as the required order of compilation in some other Ada
9798 systems. In particular, clients are compiled before the units on which
9799 they depend. The ability of GNAT to compile in any order is critical in
9800 allowing an order of compilation to be chosen that guarantees that
9801 @command{gnatmake} will recompute a correct set of new dependencies if
9802 necessary.
9803
9804 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9805 imported by several of the executables, it will be recompiled at most once.
9806
9807 Note: when using non-standard naming conventions
9808 (@pxref{Using Other File Names}), changing through a configuration pragmas
9809 file the version of a source and invoking @command{gnatmake} to recompile may
9810 have no effect, if the previous version of the source is still accessible
9811 by @command{gnatmake}. It may be necessary to use the switch
9812 ^-f^/FORCE_COMPILE^.
9813
9814 @node Examples of gnatmake Usage
9815 @section Examples of @command{gnatmake} Usage
9816
9817 @table @code
9818 @item gnatmake hello.adb
9819 Compile all files necessary to bind and link the main program
9820 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9821 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9822
9823 @item gnatmake main1 main2 main3
9824 Compile all files necessary to bind and link the main programs
9825 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9826 (containing unit @code{Main2}) and @file{main3.adb}
9827 (containing unit @code{Main3}) and bind and link the resulting object files
9828 to generate three executable files @file{^main1^MAIN1.EXE^},
9829 @file{^main2^MAIN2.EXE^}
9830 and @file{^main3^MAIN3.EXE^}.
9831
9832 @ifclear vms
9833 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9834 @end ifclear
9835
9836 @ifset vms
9837 @item gnatmake Main_Unit /QUIET
9838 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9839 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9840 @end ifset
9841 Compile all files necessary to bind and link the main program unit
9842 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9843 be done with optimization level 2 and the order of elaboration will be
9844 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9845 displaying commands it is executing.
9846 @end table
9847
9848 @c *************************
9849 @node Improving Performance
9850 @chapter Improving Performance
9851 @cindex Improving performance
9852
9853 @noindent
9854 This chapter presents several topics related to program performance.
9855 It first describes some of the tradeoffs that need to be considered
9856 and some of the techniques for making your program run faster.
9857 It then documents the @command{gnatelim} tool and unused subprogram/data
9858 elimination feature, which can reduce the size of program executables.
9859
9860 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9861 driver (see @ref{The GNAT Driver and Project Files}).
9862
9863 @ifnottex
9864 @menu
9865 * Performance Considerations::
9866 * Text_IO Suggestions::
9867 * Reducing Size of Ada Executables with gnatelim::
9868 * Reducing Size of Executables with unused subprogram/data elimination::
9869 @end menu
9870 @end ifnottex
9871
9872 @c *****************************
9873 @node Performance Considerations
9874 @section Performance Considerations
9875
9876 @noindent
9877 The GNAT system provides a number of options that allow a trade-off
9878 between
9879
9880 @itemize @bullet
9881 @item
9882 performance of the generated code
9883
9884 @item
9885 speed of compilation
9886
9887 @item
9888 minimization of dependences and recompilation
9889
9890 @item
9891 the degree of run-time checking.
9892 @end itemize
9893
9894 @noindent
9895 The defaults (if no options are selected) aim at improving the speed
9896 of compilation and minimizing dependences, at the expense of performance
9897 of the generated code:
9898
9899 @itemize @bullet
9900 @item
9901 no optimization
9902
9903 @item
9904 no inlining of subprogram calls
9905
9906 @item
9907 all run-time checks enabled except overflow and elaboration checks
9908 @end itemize
9909
9910 @noindent
9911 These options are suitable for most program development purposes. This
9912 chapter describes how you can modify these choices, and also provides
9913 some guidelines on debugging optimized code.
9914
9915 @menu
9916 * Controlling Run-Time Checks::
9917 * Use of Restrictions::
9918 * Optimization Levels::
9919 * Debugging Optimized Code::
9920 * Inlining of Subprograms::
9921 * Other Optimization Switches::
9922 * Optimization and Strict Aliasing::
9923
9924 @ifset vms
9925 * Coverage Analysis::
9926 @end ifset
9927 @end menu
9928
9929 @node Controlling Run-Time Checks
9930 @subsection Controlling Run-Time Checks
9931
9932 @noindent
9933 By default, GNAT generates all run-time checks, except integer overflow
9934 checks, stack overflow checks, and checks for access before elaboration on
9935 subprogram calls. The latter are not required in default mode, because all
9936 necessary checking is done at compile time.
9937 @cindex @option{-gnatp} (@command{gcc})
9938 @cindex @option{-gnato} (@command{gcc})
9939 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9940 be modified. @xref{Run-Time Checks}.
9941
9942 Our experience is that the default is suitable for most development
9943 purposes.
9944
9945 We treat integer overflow specially because these
9946 are quite expensive and in our experience are not as important as other
9947 run-time checks in the development process. Note that division by zero
9948 is not considered an overflow check, and divide by zero checks are
9949 generated where required by default.
9950
9951 Elaboration checks are off by default, and also not needed by default, since
9952 GNAT uses a static elaboration analysis approach that avoids the need for
9953 run-time checking. This manual contains a full chapter discussing the issue
9954 of elaboration checks, and if the default is not satisfactory for your use,
9955 you should read this chapter.
9956
9957 For validity checks, the minimal checks required by the Ada Reference
9958 Manual (for case statements and assignments to array elements) are on
9959 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9960 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9961 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9962 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9963 are also suppressed entirely if @option{-gnatp} is used.
9964
9965 @cindex Overflow checks
9966 @cindex Checks, overflow
9967 @findex Suppress
9968 @findex Unsuppress
9969 @cindex pragma Suppress
9970 @cindex pragma Unsuppress
9971 Note that the setting of the switches controls the default setting of
9972 the checks. They may be modified using either @code{pragma Suppress} (to
9973 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9974 checks) in the program source.
9975
9976 @node Use of Restrictions
9977 @subsection Use of Restrictions
9978
9979 @noindent
9980 The use of pragma Restrictions allows you to control which features are
9981 permitted in your program. Apart from the obvious point that if you avoid
9982 relatively expensive features like finalization (enforceable by the use
9983 of pragma Restrictions (No_Finalization), the use of this pragma does not
9984 affect the generated code in most cases.
9985
9986 One notable exception to this rule is that the possibility of task abort
9987 results in some distributed overhead, particularly if finalization or
9988 exception handlers are used. The reason is that certain sections of code
9989 have to be marked as non-abortable.
9990
9991 If you use neither the @code{abort} statement, nor asynchronous transfer
9992 of control (@code{select @dots{} then abort}), then this distributed overhead
9993 is removed, which may have a general positive effect in improving
9994 overall performance. Especially code involving frequent use of tasking
9995 constructs and controlled types will show much improved performance.
9996 The relevant restrictions pragmas are
9997
9998 @smallexample @c ada
9999 pragma Restrictions (No_Abort_Statements);
10000 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10001 @end smallexample
10002
10003 @noindent
10004 It is recommended that these restriction pragmas be used if possible. Note
10005 that this also means that you can write code without worrying about the
10006 possibility of an immediate abort at any point.
10007
10008 @node Optimization Levels
10009 @subsection Optimization Levels
10010 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10011
10012 @noindent
10013 Without any optimization ^option,^qualifier,^
10014 the compiler's goal is to reduce the cost of
10015 compilation and to make debugging produce the expected results.
10016 Statements are independent: if you stop the program with a breakpoint between
10017 statements, you can then assign a new value to any variable or change
10018 the program counter to any other statement in the subprogram and get exactly
10019 the results you would expect from the source code.
10020
10021 Turning on optimization makes the compiler attempt to improve the
10022 performance and/or code size at the expense of compilation time and
10023 possibly the ability to debug the program.
10024
10025 If you use multiple
10026 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10027 the last such option is the one that is effective.
10028
10029 @noindent
10030 The default is optimization off. This results in the fastest compile
10031 times, but GNAT makes absolutely no attempt to optimize, and the
10032 generated programs are considerably larger and slower than when
10033 optimization is enabled. You can use the
10034 @ifclear vms
10035 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10036 @option{-O2}, @option{-O3}, and @option{-Os})
10037 @end ifclear
10038 @ifset vms
10039 @code{OPTIMIZE} qualifier
10040 @end ifset
10041 to @command{gcc} to control the optimization level:
10042
10043 @table @option
10044 @item ^-O0^/OPTIMIZE=NONE^
10045 No optimization (the default);
10046 generates unoptimized code but has
10047 the fastest compilation time.
10048
10049 Note that many other compilers do fairly extensive optimization
10050 even if ``no optimization'' is specified. With gcc, it is
10051 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10052 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10053 really does mean no optimization at all. This difference between
10054 gcc and other compilers should be kept in mind when doing
10055 performance comparisons.
10056
10057 @item ^-O1^/OPTIMIZE=SOME^
10058 Moderate optimization;
10059 optimizes reasonably well but does not
10060 degrade compilation time significantly.
10061
10062 @item ^-O2^/OPTIMIZE=ALL^
10063 @ifset vms
10064 @itemx /OPTIMIZE=DEVELOPMENT
10065 @end ifset
10066 Full optimization;
10067 generates highly optimized code and has
10068 the slowest compilation time.
10069
10070 @item ^-O3^/OPTIMIZE=INLINING^
10071 Full optimization as in @option{-O2},
10072 and also attempts automatic inlining of small
10073 subprograms within a unit (@pxref{Inlining of Subprograms}).
10074
10075 @item ^-Os^/OPTIMIZE=SPACE^
10076 Optimize space usage of resulting program.
10077 @end table
10078
10079 @noindent
10080 Higher optimization levels perform more global transformations on the
10081 program and apply more expensive analysis algorithms in order to generate
10082 faster and more compact code. The price in compilation time, and the
10083 resulting improvement in execution time,
10084 both depend on the particular application and the hardware environment.
10085 You should experiment to find the best level for your application.
10086
10087 Since the precise set of optimizations done at each level will vary from
10088 release to release (and sometime from target to target), it is best to think
10089 of the optimization settings in general terms.
10090 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10091 the GNU Compiler Collection (GCC)}, for details about
10092 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10093 individually enable or disable specific optimizations.
10094
10095 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10096 been tested extensively at all optimization levels. There are some bugs
10097 which appear only with optimization turned on, but there have also been
10098 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10099 level of optimization does not improve the reliability of the code
10100 generator, which in practice is highly reliable at all optimization
10101 levels.
10102
10103 Note regarding the use of @option{-O3}: The use of this optimization level
10104 is generally discouraged with GNAT, since it often results in larger
10105 executables which run more slowly. See further discussion of this point
10106 in @ref{Inlining of Subprograms}.
10107
10108 @node Debugging Optimized Code
10109 @subsection Debugging Optimized Code
10110 @cindex Debugging optimized code
10111 @cindex Optimization and debugging
10112
10113 @noindent
10114 Although it is possible to do a reasonable amount of debugging at
10115 @ifclear vms
10116 nonzero optimization levels,
10117 the higher the level the more likely that
10118 @end ifclear
10119 @ifset vms
10120 @option{/OPTIMIZE} settings other than @code{NONE},
10121 such settings will make it more likely that
10122 @end ifset
10123 source-level constructs will have been eliminated by optimization.
10124 For example, if a loop is strength-reduced, the loop
10125 control variable may be completely eliminated and thus cannot be
10126 displayed in the debugger.
10127 This can only happen at @option{-O2} or @option{-O3}.
10128 Explicit temporary variables that you code might be eliminated at
10129 ^level^setting^ @option{-O1} or higher.
10130
10131 The use of the @option{^-g^/DEBUG^} switch,
10132 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10133 which is needed for source-level debugging,
10134 affects the size of the program executable on disk,
10135 and indeed the debugging information can be quite large.
10136 However, it has no effect on the generated code (and thus does not
10137 degrade performance)
10138
10139 Since the compiler generates debugging tables for a compilation unit before
10140 it performs optimizations, the optimizing transformations may invalidate some
10141 of the debugging data. You therefore need to anticipate certain
10142 anomalous situations that may arise while debugging optimized code.
10143 These are the most common cases:
10144
10145 @enumerate
10146 @item
10147 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10148 commands show
10149 the PC bouncing back and forth in the code. This may result from any of
10150 the following optimizations:
10151
10152 @itemize @bullet
10153 @item
10154 @i{Common subexpression elimination:} using a single instance of code for a
10155 quantity that the source computes several times. As a result you
10156 may not be able to stop on what looks like a statement.
10157
10158 @item
10159 @i{Invariant code motion:} moving an expression that does not change within a
10160 loop, to the beginning of the loop.
10161
10162 @item
10163 @i{Instruction scheduling:} moving instructions so as to
10164 overlap loads and stores (typically) with other code, or in
10165 general to move computations of values closer to their uses. Often
10166 this causes you to pass an assignment statement without the assignment
10167 happening and then later bounce back to the statement when the
10168 value is actually needed. Placing a breakpoint on a line of code
10169 and then stepping over it may, therefore, not always cause all the
10170 expected side-effects.
10171 @end itemize
10172
10173 @item
10174 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10175 two identical pieces of code are merged and the program counter suddenly
10176 jumps to a statement that is not supposed to be executed, simply because
10177 it (and the code following) translates to the same thing as the code
10178 that @emph{was} supposed to be executed. This effect is typically seen in
10179 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10180 a @code{break} in a C @code{^switch^switch^} statement.
10181
10182 @item
10183 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10184 There are various reasons for this effect:
10185
10186 @itemize @bullet
10187 @item
10188 In a subprogram prologue, a parameter may not yet have been moved to its
10189 ``home''.
10190
10191 @item
10192 A variable may be dead, and its register re-used. This is
10193 probably the most common cause.
10194
10195 @item
10196 As mentioned above, the assignment of a value to a variable may
10197 have been moved.
10198
10199 @item
10200 A variable may be eliminated entirely by value propagation or
10201 other means. In this case, GCC may incorrectly generate debugging
10202 information for the variable
10203 @end itemize
10204
10205 @noindent
10206 In general, when an unexpected value appears for a local variable or parameter
10207 you should first ascertain if that value was actually computed by
10208 your program, as opposed to being incorrectly reported by the debugger.
10209 Record fields or
10210 array elements in an object designated by an access value
10211 are generally less of a problem, once you have ascertained that the access
10212 value is sensible.
10213 Typically, this means checking variables in the preceding code and in the
10214 calling subprogram to verify that the value observed is explainable from other
10215 values (one must apply the procedure recursively to those
10216 other values); or re-running the code and stopping a little earlier
10217 (perhaps before the call) and stepping to better see how the variable obtained
10218 the value in question; or continuing to step @emph{from} the point of the
10219 strange value to see if code motion had simply moved the variable's
10220 assignments later.
10221 @end enumerate
10222
10223 @noindent
10224 In light of such anomalies, a recommended technique is to use @option{-O0}
10225 early in the software development cycle, when extensive debugging capabilities
10226 are most needed, and then move to @option{-O1} and later @option{-O2} as
10227 the debugger becomes less critical.
10228 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10229 a release management issue.
10230 @ifclear vms
10231 Note that if you use @option{-g} you can then use the @command{strip} program
10232 on the resulting executable,
10233 which removes both debugging information and global symbols.
10234 @end ifclear
10235
10236 @node Inlining of Subprograms
10237 @subsection Inlining of Subprograms
10238
10239 @noindent
10240 A call to a subprogram in the current unit is inlined if all the
10241 following conditions are met:
10242
10243 @itemize @bullet
10244 @item
10245 The optimization level is at least @option{-O1}.
10246
10247 @item
10248 The called subprogram is suitable for inlining: It must be small enough
10249 and not contain something that @command{gcc} cannot support in inlined
10250 subprograms.
10251
10252 @item
10253 @cindex pragma Inline
10254 @findex Inline
10255 Either @code{pragma Inline} applies to the subprogram, or it is local
10256 to the unit and called once from within it, or it is small and automatic
10257 inlining (optimization level @option{-O3}) is specified.
10258 @end itemize
10259
10260 @noindent
10261 Calls to subprograms in @code{with}'ed units are normally not inlined.
10262 To achieve actual inlining (that is, replacement of the call by the code
10263 in the body of the subprogram), the following conditions must all be true.
10264
10265 @itemize @bullet
10266 @item
10267 The optimization level is at least @option{-O1}.
10268
10269 @item
10270 The called subprogram is suitable for inlining: It must be small enough
10271 and not contain something that @command{gcc} cannot support in inlined
10272 subprograms.
10273
10274 @item
10275 The call appears in a body (not in a package spec).
10276
10277 @item
10278 There is a @code{pragma Inline} for the subprogram.
10279
10280 @item
10281 @cindex @option{-gnatn} (@command{gcc})
10282 The @option{^-gnatn^/INLINE^} switch
10283 is used in the @command{gcc} command line
10284 @end itemize
10285
10286 Even if all these conditions are met, it may not be possible for
10287 the compiler to inline the call, due to the length of the body,
10288 or features in the body that make it impossible for the compiler
10289 to do the inlining.
10290
10291 Note that specifying the @option{-gnatn} switch causes additional
10292 compilation dependencies. Consider the following:
10293
10294 @smallexample @c ada
10295 @cartouche
10296 package R is
10297 procedure Q;
10298 pragma Inline (Q);
10299 end R;
10300 package body R is
10301 @dots{}
10302 end R;
10303
10304 with R;
10305 procedure Main is
10306 begin
10307 @dots{}
10308 R.Q;
10309 end Main;
10310 @end cartouche
10311 @end smallexample
10312
10313 @noindent
10314 With the default behavior (no @option{-gnatn} switch specified), the
10315 compilation of the @code{Main} procedure depends only on its own source,
10316 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10317 means that editing the body of @code{R} does not require recompiling
10318 @code{Main}.
10319
10320 On the other hand, the call @code{R.Q} is not inlined under these
10321 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10322 is compiled, the call will be inlined if the body of @code{Q} is small
10323 enough, but now @code{Main} depends on the body of @code{R} in
10324 @file{r.adb} as well as on the spec. This means that if this body is edited,
10325 the main program must be recompiled. Note that this extra dependency
10326 occurs whether or not the call is in fact inlined by @command{gcc}.
10327
10328 The use of front end inlining with @option{-gnatN} generates similar
10329 additional dependencies.
10330
10331 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10332 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10333 can be used to prevent
10334 all inlining. This switch overrides all other conditions and ensures
10335 that no inlining occurs. The extra dependences resulting from
10336 @option{-gnatn} will still be active, even if
10337 this switch is used to suppress the resulting inlining actions.
10338
10339 @cindex @option{-fno-inline-functions} (@command{gcc})
10340 Note: The @option{-fno-inline-functions} switch can be used to prevent
10341 automatic inlining of small subprograms if @option{-O3} is used.
10342
10343 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10344 Note: The @option{-fno-inline-functions-called-once} switch
10345 can be used to prevent inlining of subprograms local to the unit
10346 and called once from within it if @option{-O1} is used.
10347
10348 Note regarding the use of @option{-O3}: There is no difference in inlining
10349 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10350 pragma @code{Inline} assuming the use of @option{-gnatn}
10351 or @option{-gnatN} (the switches that activate inlining). If you have used
10352 pragma @code{Inline} in appropriate cases, then it is usually much better
10353 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10354 in this case only has the effect of inlining subprograms you did not
10355 think should be inlined. We often find that the use of @option{-O3} slows
10356 down code by performing excessive inlining, leading to increased instruction
10357 cache pressure from the increased code size. So the bottom line here is
10358 that you should not automatically assume that @option{-O3} is better than
10359 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10360 it actually improves performance.
10361
10362 @node Other Optimization Switches
10363 @subsection Other Optimization Switches
10364 @cindex Optimization Switches
10365
10366 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10367 @command{gcc} optimization switches are potentially usable. These switches
10368 have not been extensively tested with GNAT but can generally be expected
10369 to work. Examples of switches in this category are
10370 @option{-funroll-loops} and
10371 the various target-specific @option{-m} options (in particular, it has been
10372 observed that @option{-march=pentium4} can significantly improve performance
10373 on appropriate machines). For full details of these switches, see
10374 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10375 the GNU Compiler Collection (GCC)}.
10376
10377 @node Optimization and Strict Aliasing
10378 @subsection Optimization and Strict Aliasing
10379 @cindex Aliasing
10380 @cindex Strict Aliasing
10381 @cindex No_Strict_Aliasing
10382
10383 @noindent
10384 The strong typing capabilities of Ada allow an optimizer to generate
10385 efficient code in situations where other languages would be forced to
10386 make worst case assumptions preventing such optimizations. Consider
10387 the following example:
10388
10389 @smallexample @c ada
10390 @cartouche
10391 procedure R is
10392 type Int1 is new Integer;
10393 type Int2 is new Integer;
10394 type Int1A is access Int1;
10395 type Int2A is access Int2;
10396 Int1V : Int1A;
10397 Int2V : Int2A;
10398 @dots{}
10399
10400 begin
10401 @dots{}
10402 for J in Data'Range loop
10403 if Data (J) = Int1V.all then
10404 Int2V.all := Int2V.all + 1;
10405 end if;
10406 end loop;
10407 @dots{}
10408 end R;
10409 @end cartouche
10410 @end smallexample
10411
10412 @noindent
10413 In this example, since the variable @code{Int1V} can only access objects
10414 of type @code{Int1}, and @code{Int2V} can only access objects of type
10415 @code{Int2}, there is no possibility that the assignment to
10416 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10417 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10418 for all iterations of the loop and avoid the extra memory reference
10419 required to dereference it each time through the loop.
10420
10421 This kind of optimization, called strict aliasing analysis, is
10422 triggered by specifying an optimization level of @option{-O2} or
10423 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10424 when access values are involved.
10425
10426 However, although this optimization is always correct in terms of
10427 the formal semantics of the Ada Reference Manual, difficulties can
10428 arise if features like @code{Unchecked_Conversion} are used to break
10429 the typing system. Consider the following complete program example:
10430
10431 @smallexample @c ada
10432 @cartouche
10433 package p1 is
10434 type int1 is new integer;
10435 type int2 is new integer;
10436 type a1 is access int1;
10437 type a2 is access int2;
10438 end p1;
10439
10440 with p1; use p1;
10441 package p2 is
10442 function to_a2 (Input : a1) return a2;
10443 end p2;
10444
10445 with Unchecked_Conversion;
10446 package body p2 is
10447 function to_a2 (Input : a1) return a2 is
10448 function to_a2u is
10449 new Unchecked_Conversion (a1, a2);
10450 begin
10451 return to_a2u (Input);
10452 end to_a2;
10453 end p2;
10454
10455 with p2; use p2;
10456 with p1; use p1;
10457 with Text_IO; use Text_IO;
10458 procedure m is
10459 v1 : a1 := new int1;
10460 v2 : a2 := to_a2 (v1);
10461 begin
10462 v1.all := 1;
10463 v2.all := 0;
10464 put_line (int1'image (v1.all));
10465 end;
10466 @end cartouche
10467 @end smallexample
10468
10469 @noindent
10470 This program prints out 0 in @option{-O0} or @option{-O1}
10471 mode, but it prints out 1 in @option{-O2} mode. That's
10472 because in strict aliasing mode, the compiler can and
10473 does assume that the assignment to @code{v2.all} could not
10474 affect the value of @code{v1.all}, since different types
10475 are involved.
10476
10477 This behavior is not a case of non-conformance with the standard, since
10478 the Ada RM specifies that an unchecked conversion where the resulting
10479 bit pattern is not a correct value of the target type can result in an
10480 abnormal value and attempting to reference an abnormal value makes the
10481 execution of a program erroneous. That's the case here since the result
10482 does not point to an object of type @code{int2}. This means that the
10483 effect is entirely unpredictable.
10484
10485 However, although that explanation may satisfy a language
10486 lawyer, in practice an applications programmer expects an
10487 unchecked conversion involving pointers to create true
10488 aliases and the behavior of printing 1 seems plain wrong.
10489 In this case, the strict aliasing optimization is unwelcome.
10490
10491 Indeed the compiler recognizes this possibility, and the
10492 unchecked conversion generates a warning:
10493
10494 @smallexample
10495 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10496 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10497 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10498 @end smallexample
10499
10500 @noindent
10501 Unfortunately the problem is recognized when compiling the body of
10502 package @code{p2}, but the actual "bad" code is generated while
10503 compiling the body of @code{m} and this latter compilation does not see
10504 the suspicious @code{Unchecked_Conversion}.
10505
10506 As implied by the warning message, there are approaches you can use to
10507 avoid the unwanted strict aliasing optimization in a case like this.
10508
10509 One possibility is to simply avoid the use of @option{-O2}, but
10510 that is a bit drastic, since it throws away a number of useful
10511 optimizations that do not involve strict aliasing assumptions.
10512
10513 A less drastic approach is to compile the program using the
10514 option @option{-fno-strict-aliasing}. Actually it is only the
10515 unit containing the dereferencing of the suspicious pointer
10516 that needs to be compiled. So in this case, if we compile
10517 unit @code{m} with this switch, then we get the expected
10518 value of zero printed. Analyzing which units might need
10519 the switch can be painful, so a more reasonable approach
10520 is to compile the entire program with options @option{-O2}
10521 and @option{-fno-strict-aliasing}. If the performance is
10522 satisfactory with this combination of options, then the
10523 advantage is that the entire issue of possible "wrong"
10524 optimization due to strict aliasing is avoided.
10525
10526 To avoid the use of compiler switches, the configuration
10527 pragma @code{No_Strict_Aliasing} with no parameters may be
10528 used to specify that for all access types, the strict
10529 aliasing optimization should be suppressed.
10530
10531 However, these approaches are still overkill, in that they causes
10532 all manipulations of all access values to be deoptimized. A more
10533 refined approach is to concentrate attention on the specific
10534 access type identified as problematic.
10535
10536 First, if a careful analysis of uses of the pointer shows
10537 that there are no possible problematic references, then
10538 the warning can be suppressed by bracketing the
10539 instantiation of @code{Unchecked_Conversion} to turn
10540 the warning off:
10541
10542 @smallexample @c ada
10543 pragma Warnings (Off);
10544 function to_a2u is
10545 new Unchecked_Conversion (a1, a2);
10546 pragma Warnings (On);
10547 @end smallexample
10548
10549 @noindent
10550 Of course that approach is not appropriate for this particular
10551 example, since indeed there is a problematic reference. In this
10552 case we can take one of two other approaches.
10553
10554 The first possibility is to move the instantiation of unchecked
10555 conversion to the unit in which the type is declared. In
10556 this example, we would move the instantiation of
10557 @code{Unchecked_Conversion} from the body of package
10558 @code{p2} to the spec of package @code{p1}. Now the
10559 warning disappears. That's because any use of the
10560 access type knows there is a suspicious unchecked
10561 conversion, and the strict aliasing optimization
10562 is automatically suppressed for the type.
10563
10564 If it is not practical to move the unchecked conversion to the same unit
10565 in which the destination access type is declared (perhaps because the
10566 source type is not visible in that unit), you may use pragma
10567 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10568 same declarative sequence as the declaration of the access type:
10569
10570 @smallexample @c ada
10571 type a2 is access int2;
10572 pragma No_Strict_Aliasing (a2);
10573 @end smallexample
10574
10575 @noindent
10576 Here again, the compiler now knows that the strict aliasing optimization
10577 should be suppressed for any reference to type @code{a2} and the
10578 expected behavior is obtained.
10579
10580 Finally, note that although the compiler can generate warnings for
10581 simple cases of unchecked conversions, there are tricker and more
10582 indirect ways of creating type incorrect aliases which the compiler
10583 cannot detect. Examples are the use of address overlays and unchecked
10584 conversions involving composite types containing access types as
10585 components. In such cases, no warnings are generated, but there can
10586 still be aliasing problems. One safe coding practice is to forbid the
10587 use of address clauses for type overlaying, and to allow unchecked
10588 conversion only for primitive types. This is not really a significant
10589 restriction since any possible desired effect can be achieved by
10590 unchecked conversion of access values.
10591
10592 The aliasing analysis done in strict aliasing mode can certainly
10593 have significant benefits. We have seen cases of large scale
10594 application code where the time is increased by up to 5% by turning
10595 this optimization off. If you have code that includes significant
10596 usage of unchecked conversion, you might want to just stick with
10597 @option{-O1} and avoid the entire issue. If you get adequate
10598 performance at this level of optimization level, that's probably
10599 the safest approach. If tests show that you really need higher
10600 levels of optimization, then you can experiment with @option{-O2}
10601 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10602 has on size and speed of the code. If you really need to use
10603 @option{-O2} with strict aliasing in effect, then you should
10604 review any uses of unchecked conversion of access types,
10605 particularly if you are getting the warnings described above.
10606
10607 @ifset vms
10608 @node Coverage Analysis
10609 @subsection Coverage Analysis
10610
10611 @noindent
10612 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10613 the user to determine the distribution of execution time across a program,
10614 @pxref{Profiling} for details of usage.
10615 @end ifset
10616
10617
10618 @node Text_IO Suggestions
10619 @section @code{Text_IO} Suggestions
10620 @cindex @code{Text_IO} and performance
10621
10622 @noindent
10623 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10624 the requirement of maintaining page and line counts. If performance
10625 is critical, a recommendation is to use @code{Stream_IO} instead of
10626 @code{Text_IO} for volume output, since this package has less overhead.
10627
10628 If @code{Text_IO} must be used, note that by default output to the standard
10629 output and standard error files is unbuffered (this provides better
10630 behavior when output statements are used for debugging, or if the
10631 progress of a program is observed by tracking the output, e.g. by
10632 using the Unix @command{tail -f} command to watch redirected output.
10633
10634 If you are generating large volumes of output with @code{Text_IO} and
10635 performance is an important factor, use a designated file instead
10636 of the standard output file, or change the standard output file to
10637 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10638
10639
10640
10641 @node Reducing Size of Ada Executables with gnatelim
10642 @section Reducing Size of Ada Executables with @code{gnatelim}
10643 @findex gnatelim
10644
10645 @noindent
10646 This section describes @command{gnatelim}, a tool which detects unused
10647 subprograms and helps the compiler to create a smaller executable for your
10648 program.
10649
10650 @menu
10651 * About gnatelim::
10652 * Running gnatelim::
10653 * Correcting the List of Eliminate Pragmas::
10654 * Making Your Executables Smaller::
10655 * Summary of the gnatelim Usage Cycle::
10656 @end menu
10657
10658 @node About gnatelim
10659 @subsection About @code{gnatelim}
10660
10661 @noindent
10662 When a program shares a set of Ada
10663 packages with other programs, it may happen that this program uses
10664 only a fraction of the subprograms defined in these packages. The code
10665 created for these unused subprograms increases the size of the executable.
10666
10667 @code{gnatelim} tracks unused subprograms in an Ada program and
10668 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10669 subprograms that are declared but never called. By placing the list of
10670 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10671 recompiling your program, you may decrease the size of its executable,
10672 because the compiler will not generate the code for 'eliminated' subprograms.
10673 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10674 information about this pragma.
10675
10676 @code{gnatelim} needs as its input data the name of the main subprogram
10677 and a bind file for a main subprogram.
10678
10679 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10680 the main subprogram. @code{gnatelim} can work with both Ada and C
10681 bind files; when both are present, it uses the Ada bind file.
10682 The following commands will build the program and create the bind file:
10683
10684 @smallexample
10685 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10686 $ gnatbind main_prog
10687 @end smallexample
10688
10689 Note that @code{gnatelim} needs neither object nor ALI files.
10690
10691 @node Running gnatelim
10692 @subsection Running @code{gnatelim}
10693
10694 @noindent
10695 @code{gnatelim} has the following command-line interface:
10696
10697 @smallexample
10698 $ gnatelim @ovar{options} name
10699 @end smallexample
10700
10701 @noindent
10702 @code{name} should be a name of a source file that contains the main subprogram
10703 of a program (partition).
10704
10705 @code{gnatelim} has the following switches:
10706
10707 @table @option
10708 @c !sort!
10709 @item ^-q^/QUIET^
10710 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10711 Quiet mode: by default @code{gnatelim} outputs to the standard error
10712 stream the number of program units left to be processed. This option turns
10713 this trace off.
10714
10715 @item ^-v^/VERBOSE^
10716 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10717 Verbose mode: @code{gnatelim} version information is printed as Ada
10718 comments to the standard output stream. Also, in addition to the number of
10719 program units left @code{gnatelim} will output the name of the current unit
10720 being processed.
10721
10722 @item ^-a^/ALL^
10723 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10724 Also look for subprograms from the GNAT run time that can be eliminated. Note
10725 that when @file{gnat.adc} is produced using this switch, the entire program
10726 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10727
10728 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10729 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10730 When looking for source files also look in directory @var{dir}. Specifying
10731 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10732 sources in the current directory.
10733
10734 @item ^-b^/BIND_FILE=^@var{bind_file}
10735 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10736 Specifies @var{bind_file} as the bind file to process. If not set, the name
10737 of the bind file is computed from the full expanded Ada name
10738 of a main subprogram.
10739
10740 @item ^-C^/CONFIG_FILE=^@var{config_file}
10741 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10742 Specifies a file @var{config_file} that contains configuration pragmas. The
10743 file must be specified with full path.
10744
10745 @item ^--GCC^/COMPILER^=@var{compiler_name}
10746 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10747 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10748 available on the path.
10749
10750 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10751 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10752 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10753 available on the path.
10754 @end table
10755
10756 @noindent
10757 @code{gnatelim} sends its output to the standard output stream, and all the
10758 tracing and debug information is sent to the standard error stream.
10759 In order to produce a proper GNAT configuration file
10760 @file{gnat.adc}, redirection must be used:
10761
10762 @smallexample
10763 @ifset vms
10764 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10765 @end ifset
10766 @ifclear vms
10767 $ gnatelim main_prog.adb > gnat.adc
10768 @end ifclear
10769 @end smallexample
10770
10771 @ifclear vms
10772 @noindent
10773 or
10774
10775 @smallexample
10776 $ gnatelim main_prog.adb >> gnat.adc
10777 @end smallexample
10778
10779 @noindent
10780 in order to append the @code{gnatelim} output to the existing contents of
10781 @file{gnat.adc}.
10782 @end ifclear
10783
10784 @node Correcting the List of Eliminate Pragmas
10785 @subsection Correcting the List of Eliminate Pragmas
10786
10787 @noindent
10788 In some rare cases @code{gnatelim} may try to eliminate
10789 subprograms that are actually called in the program. In this case, the
10790 compiler will generate an error message of the form:
10791
10792 @smallexample
10793 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10794 @end smallexample
10795
10796 @noindent
10797 You will need to manually remove the wrong @code{Eliminate} pragmas from
10798 the @file{gnat.adc} file. You should recompile your program
10799 from scratch after that, because you need a consistent @file{gnat.adc} file
10800 during the entire compilation.
10801
10802 @node Making Your Executables Smaller
10803 @subsection Making Your Executables Smaller
10804
10805 @noindent
10806 In order to get a smaller executable for your program you now have to
10807 recompile the program completely with the new @file{gnat.adc} file
10808 created by @code{gnatelim} in your current directory:
10809
10810 @smallexample
10811 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10812 @end smallexample
10813
10814 @noindent
10815 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10816 recompile everything
10817 with the set of pragmas @code{Eliminate} that you have obtained with
10818 @command{gnatelim}).
10819
10820 Be aware that the set of @code{Eliminate} pragmas is specific to each
10821 program. It is not recommended to merge sets of @code{Eliminate}
10822 pragmas created for different programs in one @file{gnat.adc} file.
10823
10824 @node Summary of the gnatelim Usage Cycle
10825 @subsection Summary of the gnatelim Usage Cycle
10826
10827 @noindent
10828 Here is a quick summary of the steps to be taken in order to reduce
10829 the size of your executables with @code{gnatelim}. You may use
10830 other GNAT options to control the optimization level,
10831 to produce the debugging information, to set search path, etc.
10832
10833 @enumerate
10834 @item
10835 Produce a bind file
10836
10837 @smallexample
10838 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10839 $ gnatbind main_prog
10840 @end smallexample
10841
10842 @item
10843 Generate a list of @code{Eliminate} pragmas
10844 @smallexample
10845 @ifset vms
10846 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10847 @end ifset
10848 @ifclear vms
10849 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10850 @end ifclear
10851 @end smallexample
10852
10853 @item
10854 Recompile the application
10855
10856 @smallexample
10857 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10858 @end smallexample
10859
10860 @end enumerate
10861
10862 @node Reducing Size of Executables with unused subprogram/data elimination
10863 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10864 @findex unused subprogram/data elimination
10865
10866 @noindent
10867 This section describes how you can eliminate unused subprograms and data from
10868 your executable just by setting options at compilation time.
10869
10870 @menu
10871 * About unused subprogram/data elimination::
10872 * Compilation options::
10873 * Example of unused subprogram/data elimination::
10874 @end menu
10875
10876 @node About unused subprogram/data elimination
10877 @subsection About unused subprogram/data elimination
10878
10879 @noindent
10880 By default, an executable contains all code and data of its composing objects
10881 (directly linked or coming from statically linked libraries), even data or code
10882 never used by this executable.
10883
10884 This feature will allow you to eliminate such unused code from your
10885 executable, making it smaller (in disk and in memory).
10886
10887 This functionality is available on all Linux platforms except for the IA-64
10888 architecture and on all cross platforms using the ELF binary file format.
10889 In both cases GNU binutils version 2.16 or later are required to enable it.
10890
10891 @node Compilation options
10892 @subsection Compilation options
10893
10894 @noindent
10895 The operation of eliminating the unused code and data from the final executable
10896 is directly performed by the linker.
10897
10898 In order to do this, it has to work with objects compiled with the
10899 following options:
10900 @option{-ffunction-sections} @option{-fdata-sections}.
10901 @cindex @option{-ffunction-sections} (@command{gcc})
10902 @cindex @option{-fdata-sections} (@command{gcc})
10903 These options are usable with C and Ada files.
10904 They will place respectively each
10905 function or data in a separate section in the resulting object file.
10906
10907 Once the objects and static libraries are created with these options, the
10908 linker can perform the dead code elimination. You can do this by setting
10909 the @option{-Wl,--gc-sections} option to gcc command or in the
10910 @option{-largs} section of @command{gnatmake}. This will perform a
10911 garbage collection of code and data never referenced.
10912
10913 If the linker performs a partial link (@option{-r} ld linker option), then you
10914 will need to provide one or several entry point using the
10915 @option{-e} / @option{--entry} ld option.
10916
10917 Note that objects compiled without the @option{-ffunction-sections} and
10918 @option{-fdata-sections} options can still be linked with the executable.
10919 However, no dead code elimination will be performed on those objects (they will
10920 be linked as is).
10921
10922 The GNAT static library is now compiled with -ffunction-sections and
10923 -fdata-sections on some platforms. This allows you to eliminate the unused code
10924 and data of the GNAT library from your executable.
10925
10926 @node Example of unused subprogram/data elimination
10927 @subsection Example of unused subprogram/data elimination
10928
10929 @noindent
10930 Here is a simple example:
10931
10932 @smallexample @c ada
10933 with Aux;
10934
10935 procedure Test is
10936 begin
10937 Aux.Used (10);
10938 end Test;
10939
10940 package Aux is
10941 Used_Data : Integer;
10942 Unused_Data : Integer;
10943
10944 procedure Used (Data : Integer);
10945 procedure Unused (Data : Integer);
10946 end Aux;
10947
10948 package body Aux is
10949 procedure Used (Data : Integer) is
10950 begin
10951 Used_Data := Data;
10952 end Used;
10953
10954 procedure Unused (Data : Integer) is
10955 begin
10956 Unused_Data := Data;
10957 end Unused;
10958 end Aux;
10959 @end smallexample
10960
10961 @noindent
10962 @code{Unused} and @code{Unused_Data} are never referenced in this code
10963 excerpt, and hence they may be safely removed from the final executable.
10964
10965 @smallexample
10966 $ gnatmake test
10967
10968 $ nm test | grep used
10969 020015f0 T aux__unused
10970 02005d88 B aux__unused_data
10971 020015cc T aux__used
10972 02005d84 B aux__used_data
10973
10974 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10975 -largs -Wl,--gc-sections
10976
10977 $ nm test | grep used
10978 02005350 T aux__used
10979 0201ffe0 B aux__used_data
10980 @end smallexample
10981
10982 @noindent
10983 It can be observed that the procedure @code{Unused} and the object
10984 @code{Unused_Data} are removed by the linker when using the
10985 appropriate options.
10986
10987 @c ********************************
10988 @node Renaming Files Using gnatchop
10989 @chapter Renaming Files Using @code{gnatchop}
10990 @findex gnatchop
10991
10992 @noindent
10993 This chapter discusses how to handle files with multiple units by using
10994 the @code{gnatchop} utility. This utility is also useful in renaming
10995 files to meet the standard GNAT default file naming conventions.
10996
10997 @menu
10998 * Handling Files with Multiple Units::
10999 * Operating gnatchop in Compilation Mode::
11000 * Command Line for gnatchop::
11001 * Switches for gnatchop::
11002 * Examples of gnatchop Usage::
11003 @end menu
11004
11005 @node Handling Files with Multiple Units
11006 @section Handling Files with Multiple Units
11007
11008 @noindent
11009 The basic compilation model of GNAT requires that a file submitted to the
11010 compiler have only one unit and there be a strict correspondence
11011 between the file name and the unit name.
11012
11013 The @code{gnatchop} utility allows both of these rules to be relaxed,
11014 allowing GNAT to process files which contain multiple compilation units
11015 and files with arbitrary file names. @code{gnatchop}
11016 reads the specified file and generates one or more output files,
11017 containing one unit per file. The unit and the file name correspond,
11018 as required by GNAT.
11019
11020 If you want to permanently restructure a set of ``foreign'' files so that
11021 they match the GNAT rules, and do the remaining development using the
11022 GNAT structure, you can simply use @command{gnatchop} once, generate the
11023 new set of files and work with them from that point on.
11024
11025 Alternatively, if you want to keep your files in the ``foreign'' format,
11026 perhaps to maintain compatibility with some other Ada compilation
11027 system, you can set up a procedure where you use @command{gnatchop} each
11028 time you compile, regarding the source files that it writes as temporary
11029 files that you throw away.
11030
11031 Note that if your file containing multiple units starts with a byte order
11032 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11033 will each start with a copy of this BOM, meaning that they can be compiled
11034 automatically in UTF-8 mode without needing to specify an explicit encoding.
11035
11036 @node Operating gnatchop in Compilation Mode
11037 @section Operating gnatchop in Compilation Mode
11038
11039 @noindent
11040 The basic function of @code{gnatchop} is to take a file with multiple units
11041 and split it into separate files. The boundary between files is reasonably
11042 clear, except for the issue of comments and pragmas. In default mode, the
11043 rule is that any pragmas between units belong to the previous unit, except
11044 that configuration pragmas always belong to the following unit. Any comments
11045 belong to the following unit. These rules
11046 almost always result in the right choice of
11047 the split point without needing to mark it explicitly and most users will
11048 find this default to be what they want. In this default mode it is incorrect to
11049 submit a file containing only configuration pragmas, or one that ends in
11050 configuration pragmas, to @code{gnatchop}.
11051
11052 However, using a special option to activate ``compilation mode'',
11053 @code{gnatchop}
11054 can perform another function, which is to provide exactly the semantics
11055 required by the RM for handling of configuration pragmas in a compilation.
11056 In the absence of configuration pragmas (at the main file level), this
11057 option has no effect, but it causes such configuration pragmas to be handled
11058 in a quite different manner.
11059
11060 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11061 only configuration pragmas, then this file is appended to the
11062 @file{gnat.adc} file in the current directory. This behavior provides
11063 the required behavior described in the RM for the actions to be taken
11064 on submitting such a file to the compiler, namely that these pragmas
11065 should apply to all subsequent compilations in the same compilation
11066 environment. Using GNAT, the current directory, possibly containing a
11067 @file{gnat.adc} file is the representation
11068 of a compilation environment. For more information on the
11069 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11070
11071 Second, in compilation mode, if @code{gnatchop}
11072 is given a file that starts with
11073 configuration pragmas, and contains one or more units, then these
11074 configuration pragmas are prepended to each of the chopped files. This
11075 behavior provides the required behavior described in the RM for the
11076 actions to be taken on compiling such a file, namely that the pragmas
11077 apply to all units in the compilation, but not to subsequently compiled
11078 units.
11079
11080 Finally, if configuration pragmas appear between units, they are appended
11081 to the previous unit. This results in the previous unit being illegal,
11082 since the compiler does not accept configuration pragmas that follow
11083 a unit. This provides the required RM behavior that forbids configuration
11084 pragmas other than those preceding the first compilation unit of a
11085 compilation.
11086
11087 For most purposes, @code{gnatchop} will be used in default mode. The
11088 compilation mode described above is used only if you need exactly
11089 accurate behavior with respect to compilations, and you have files
11090 that contain multiple units and configuration pragmas. In this
11091 circumstance the use of @code{gnatchop} with the compilation mode
11092 switch provides the required behavior, and is for example the mode
11093 in which GNAT processes the ACVC tests.
11094
11095 @node Command Line for gnatchop
11096 @section Command Line for @code{gnatchop}
11097
11098 @noindent
11099 The @code{gnatchop} command has the form:
11100
11101 @smallexample
11102 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11103 @ovar{directory}
11104 @end smallexample
11105
11106 @noindent
11107 The only required argument is the file name of the file to be chopped.
11108 There are no restrictions on the form of this file name. The file itself
11109 contains one or more Ada units, in normal GNAT format, concatenated
11110 together. As shown, more than one file may be presented to be chopped.
11111
11112 When run in default mode, @code{gnatchop} generates one output file in
11113 the current directory for each unit in each of the files.
11114
11115 @var{directory}, if specified, gives the name of the directory to which
11116 the output files will be written. If it is not specified, all files are
11117 written to the current directory.
11118
11119 For example, given a
11120 file called @file{hellofiles} containing
11121
11122 @smallexample @c ada
11123 @group
11124 @cartouche
11125 procedure hello;
11126
11127 with Text_IO; use Text_IO;
11128 procedure hello is
11129 begin
11130 Put_Line ("Hello");
11131 end hello;
11132 @end cartouche
11133 @end group
11134 @end smallexample
11135
11136 @noindent
11137 the command
11138
11139 @smallexample
11140 $ gnatchop ^hellofiles^HELLOFILES.^
11141 @end smallexample
11142
11143 @noindent
11144 generates two files in the current directory, one called
11145 @file{hello.ads} containing the single line that is the procedure spec,
11146 and the other called @file{hello.adb} containing the remaining text. The
11147 original file is not affected. The generated files can be compiled in
11148 the normal manner.
11149
11150 @noindent
11151 When gnatchop is invoked on a file that is empty or that contains only empty
11152 lines and/or comments, gnatchop will not fail, but will not produce any
11153 new sources.
11154
11155 For example, given a
11156 file called @file{toto.txt} containing
11157
11158 @smallexample @c ada
11159 @group
11160 @cartouche
11161 -- Just a comment
11162 @end cartouche
11163 @end group
11164 @end smallexample
11165
11166 @noindent
11167 the command
11168
11169 @smallexample
11170 $ gnatchop ^toto.txt^TOT.TXT^
11171 @end smallexample
11172
11173 @noindent
11174 will not produce any new file and will result in the following warnings:
11175
11176 @smallexample
11177 toto.txt:1:01: warning: empty file, contains no compilation units
11178 no compilation units found
11179 no source files written
11180 @end smallexample
11181
11182 @node Switches for gnatchop
11183 @section Switches for @code{gnatchop}
11184
11185 @noindent
11186 @command{gnatchop} recognizes the following switches:
11187
11188 @table @option
11189 @c !sort!
11190
11191 @item --version
11192 @cindex @option{--version} @command{gnatchop}
11193 Display Copyright and version, then exit disregarding all other options.
11194
11195 @item --help
11196 @cindex @option{--help} @command{gnatchop}
11197 If @option{--version} was not used, display usage, then exit disregarding
11198 all other options.
11199
11200 @item ^-c^/COMPILATION^
11201 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11202 Causes @code{gnatchop} to operate in compilation mode, in which
11203 configuration pragmas are handled according to strict RM rules. See
11204 previous section for a full description of this mode.
11205
11206 @ifclear vms
11207 @item -gnat@var{xxx}
11208 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11209 used to parse the given file. Not all @var{xxx} options make sense,
11210 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11211 process a source file that uses Latin-2 coding for identifiers.
11212 @end ifclear
11213
11214 @item ^-h^/HELP^
11215 Causes @code{gnatchop} to generate a brief help summary to the standard
11216 output file showing usage information.
11217
11218 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11219 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11220 Limit generated file names to the specified number @code{mm}
11221 of characters.
11222 This is useful if the
11223 resulting set of files is required to be interoperable with systems
11224 which limit the length of file names.
11225 @ifset vms
11226 If no value is given, or
11227 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11228 a default of 39, suitable for OpenVMS Alpha
11229 Systems, is assumed
11230 @end ifset
11231 @ifclear vms
11232 No space is allowed between the @option{-k} and the numeric value. The numeric
11233 value may be omitted in which case a default of @option{-k8},
11234 suitable for use
11235 with DOS-like file systems, is used. If no @option{-k} switch
11236 is present then
11237 there is no limit on the length of file names.
11238 @end ifclear
11239
11240 @item ^-p^/PRESERVE^
11241 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11242 Causes the file ^modification^creation^ time stamp of the input file to be
11243 preserved and used for the time stamp of the output file(s). This may be
11244 useful for preserving coherency of time stamps in an environment where
11245 @code{gnatchop} is used as part of a standard build process.
11246
11247 @item ^-q^/QUIET^
11248 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11249 Causes output of informational messages indicating the set of generated
11250 files to be suppressed. Warnings and error messages are unaffected.
11251
11252 @item ^-r^/REFERENCE^
11253 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11254 @findex Source_Reference
11255 Generate @code{Source_Reference} pragmas. Use this switch if the output
11256 files are regarded as temporary and development is to be done in terms
11257 of the original unchopped file. This switch causes
11258 @code{Source_Reference} pragmas to be inserted into each of the
11259 generated files to refers back to the original file name and line number.
11260 The result is that all error messages refer back to the original
11261 unchopped file.
11262 In addition, the debugging information placed into the object file (when
11263 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11264 specified)
11265 also refers back to this original file so that tools like profilers and
11266 debuggers will give information in terms of the original unchopped file.
11267
11268 If the original file to be chopped itself contains
11269 a @code{Source_Reference}
11270 pragma referencing a third file, then gnatchop respects
11271 this pragma, and the generated @code{Source_Reference} pragmas
11272 in the chopped file refer to the original file, with appropriate
11273 line numbers. This is particularly useful when @code{gnatchop}
11274 is used in conjunction with @code{gnatprep} to compile files that
11275 contain preprocessing statements and multiple units.
11276
11277 @item ^-v^/VERBOSE^
11278 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11279 Causes @code{gnatchop} to operate in verbose mode. The version
11280 number and copyright notice are output, as well as exact copies of
11281 the gnat1 commands spawned to obtain the chop control information.
11282
11283 @item ^-w^/OVERWRITE^
11284 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11285 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11286 fatal error if there is already a file with the same name as a
11287 file it would otherwise output, in other words if the files to be
11288 chopped contain duplicated units. This switch bypasses this
11289 check, and causes all but the last instance of such duplicated
11290 units to be skipped.
11291
11292 @ifclear vms
11293 @item --GCC=@var{xxxx}
11294 @cindex @option{--GCC=} (@code{gnatchop})
11295 Specify the path of the GNAT parser to be used. When this switch is used,
11296 no attempt is made to add the prefix to the GNAT parser executable.
11297 @end ifclear
11298 @end table
11299
11300 @node Examples of gnatchop Usage
11301 @section Examples of @code{gnatchop} Usage
11302
11303 @table @code
11304 @ifset vms
11305 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11306 @end ifset
11307 @ifclear vms
11308 @item gnatchop -w hello_s.ada prerelease/files
11309 @end ifclear
11310
11311 Chops the source file @file{hello_s.ada}. The output files will be
11312 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11313 overwriting any
11314 files with matching names in that directory (no files in the current
11315 directory are modified).
11316
11317 @item gnatchop ^archive^ARCHIVE.^
11318 Chops the source file @file{^archive^ARCHIVE.^}
11319 into the current directory. One
11320 useful application of @code{gnatchop} is in sending sets of sources
11321 around, for example in email messages. The required sources are simply
11322 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11323 command), and then
11324 @command{gnatchop} is used at the other end to reconstitute the original
11325 file names.
11326
11327 @item gnatchop file1 file2 file3 direc
11328 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11329 the resulting files in the directory @file{direc}. Note that if any units
11330 occur more than once anywhere within this set of files, an error message
11331 is generated, and no files are written. To override this check, use the
11332 @option{^-w^/OVERWRITE^} switch,
11333 in which case the last occurrence in the last file will
11334 be the one that is output, and earlier duplicate occurrences for a given
11335 unit will be skipped.
11336 @end table
11337
11338 @node Configuration Pragmas
11339 @chapter Configuration Pragmas
11340 @cindex Configuration pragmas
11341 @cindex Pragmas, configuration
11342
11343 @noindent
11344 Configuration pragmas include those pragmas described as
11345 such in the Ada Reference Manual, as well as
11346 implementation-dependent pragmas that are configuration pragmas.
11347 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11348 for details on these additional GNAT-specific configuration pragmas.
11349 Most notably, the pragma @code{Source_File_Name}, which allows
11350 specifying non-default names for source files, is a configuration
11351 pragma. The following is a complete list of configuration pragmas
11352 recognized by GNAT:
11353
11354 @smallexample
11355 Ada_83
11356 Ada_95
11357 Ada_05
11358 Ada_2005
11359 Assertion_Policy
11360 Assume_No_Invalid_Values
11361 C_Pass_By_Copy
11362 Check_Name
11363 Check_Policy
11364 Compile_Time_Error
11365 Compile_Time_Warning
11366 Compiler_Unit
11367 Component_Alignment
11368 Convention_Identifier
11369 Debug_Policy
11370 Detect_Blocking
11371 Discard_Names
11372 Elaboration_Checks
11373 Eliminate
11374 Extend_System
11375 Extensions_Allowed
11376 External_Name_Casing
11377 Fast_Math
11378 Favor_Top_Level
11379 Float_Representation
11380 Implicit_Packing
11381 Initialize_Scalars
11382 Interrupt_State
11383 License
11384 Locking_Policy
11385 Long_Float
11386 No_Run_Time
11387 No_Strict_Aliasing
11388 Normalize_Scalars
11389 Optimize_Alignment
11390 Persistent_BSS
11391 Polling
11392 Priority_Specific_Dispatching
11393 Profile
11394 Profile_Warnings
11395 Propagate_Exceptions
11396 Queuing_Policy
11397 Ravenscar
11398 Restricted_Run_Time
11399 Restrictions
11400 Restrictions_Warnings
11401 Reviewable
11402 Source_File_Name
11403 Source_File_Name_Project
11404 Style_Checks
11405 Suppress
11406 Suppress_Exception_Locations
11407 Task_Dispatching_Policy
11408 Universal_Data
11409 Unsuppress
11410 Use_VADS_Size
11411 Validity_Checks
11412 Warnings
11413 Wide_Character_Encoding
11414
11415 @end smallexample
11416
11417 @menu
11418 * Handling of Configuration Pragmas::
11419 * The Configuration Pragmas Files::
11420 @end menu
11421
11422 @node Handling of Configuration Pragmas
11423 @section Handling of Configuration Pragmas
11424
11425 Configuration pragmas may either appear at the start of a compilation
11426 unit, in which case they apply only to that unit, or they may apply to
11427 all compilations performed in a given compilation environment.
11428
11429 GNAT also provides the @code{gnatchop} utility to provide an automatic
11430 way to handle configuration pragmas following the semantics for
11431 compilations (that is, files with multiple units), described in the RM.
11432 See @ref{Operating gnatchop in Compilation Mode} for details.
11433 However, for most purposes, it will be more convenient to edit the
11434 @file{gnat.adc} file that contains configuration pragmas directly,
11435 as described in the following section.
11436
11437 @node The Configuration Pragmas Files
11438 @section The Configuration Pragmas Files
11439 @cindex @file{gnat.adc}
11440
11441 @noindent
11442 In GNAT a compilation environment is defined by the current
11443 directory at the time that a compile command is given. This current
11444 directory is searched for a file whose name is @file{gnat.adc}. If
11445 this file is present, it is expected to contain one or more
11446 configuration pragmas that will be applied to the current compilation.
11447 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11448 considered.
11449
11450 Configuration pragmas may be entered into the @file{gnat.adc} file
11451 either by running @code{gnatchop} on a source file that consists only of
11452 configuration pragmas, or more conveniently by
11453 direct editing of the @file{gnat.adc} file, which is a standard format
11454 source file.
11455
11456 In addition to @file{gnat.adc}, additional files containing configuration
11457 pragmas may be applied to the current compilation using the switch
11458 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11459 contains only configuration pragmas. These configuration pragmas are
11460 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11461 is present and switch @option{-gnatA} is not used).
11462
11463 It is allowed to specify several switches @option{-gnatec}, all of which
11464 will be taken into account.
11465
11466 If you are using project file, a separate mechanism is provided using
11467 project attributes, see @ref{Specifying Configuration Pragmas} for more
11468 details.
11469
11470 @ifset vms
11471 Of special interest to GNAT OpenVMS Alpha is the following
11472 configuration pragma:
11473
11474 @smallexample @c ada
11475 @cartouche
11476 pragma Extend_System (Aux_DEC);
11477 @end cartouche
11478 @end smallexample
11479
11480 @noindent
11481 In the presence of this pragma, GNAT adds to the definition of the
11482 predefined package SYSTEM all the additional types and subprograms that are
11483 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11484 @end ifset
11485
11486 @node Handling Arbitrary File Naming Conventions Using gnatname
11487 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11488 @cindex Arbitrary File Naming Conventions
11489
11490 @menu
11491 * Arbitrary File Naming Conventions::
11492 * Running gnatname::
11493 * Switches for gnatname::
11494 * Examples of gnatname Usage::
11495 @end menu
11496
11497 @node Arbitrary File Naming Conventions
11498 @section Arbitrary File Naming Conventions
11499
11500 @noindent
11501 The GNAT compiler must be able to know the source file name of a compilation
11502 unit. When using the standard GNAT default file naming conventions
11503 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11504 does not need additional information.
11505
11506 @noindent
11507 When the source file names do not follow the standard GNAT default file naming
11508 conventions, the GNAT compiler must be given additional information through
11509 a configuration pragmas file (@pxref{Configuration Pragmas})
11510 or a project file.
11511 When the non-standard file naming conventions are well-defined,
11512 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11513 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11514 if the file naming conventions are irregular or arbitrary, a number
11515 of pragma @code{Source_File_Name} for individual compilation units
11516 must be defined.
11517 To help maintain the correspondence between compilation unit names and
11518 source file names within the compiler,
11519 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11520 set of files.
11521
11522 @node Running gnatname
11523 @section Running @code{gnatname}
11524
11525 @noindent
11526 The usual form of the @code{gnatname} command is
11527
11528 @smallexample
11529 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11530 @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11531 @end smallexample
11532
11533 @noindent
11534 All of the arguments are optional. If invoked without any argument,
11535 @code{gnatname} will display its usage.
11536
11537 @noindent
11538 When used with at least one naming pattern, @code{gnatname} will attempt to
11539 find all the compilation units in files that follow at least one of the
11540 naming patterns. To find these compilation units,
11541 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11542 regular files.
11543
11544 @noindent
11545 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11546 Each Naming Pattern is enclosed between double quotes.
11547 A Naming Pattern is a regular expression similar to the wildcard patterns
11548 used in file names by the Unix shells or the DOS prompt.
11549
11550 @noindent
11551 @code{gnatname} may be called with several sections of directories/patterns.
11552 Sections are separated by switch @code{--and}. In each section, there must be
11553 at least one pattern. If no directory is specified in a section, the current
11554 directory (or the project directory is @code{-P} is used) is implied.
11555 The options other that the directory switches and the patterns apply globally
11556 even if they are in different sections.
11557
11558 @noindent
11559 Examples of Naming Patterns are
11560
11561 @smallexample
11562 "*.[12].ada"
11563 "*.ad[sb]*"
11564 "body_*" "spec_*"
11565 @end smallexample
11566
11567 @noindent
11568 For a more complete description of the syntax of Naming Patterns,
11569 see the second kind of regular expressions described in @file{g-regexp.ads}
11570 (the ``Glob'' regular expressions).
11571
11572 @noindent
11573 When invoked with no switch @code{-P}, @code{gnatname} will create a
11574 configuration pragmas file @file{gnat.adc} in the current working directory,
11575 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11576 unit.
11577
11578 @node Switches for gnatname
11579 @section Switches for @code{gnatname}
11580
11581 @noindent
11582 Switches for @code{gnatname} must precede any specified Naming Pattern.
11583
11584 @noindent
11585 You may specify any of the following switches to @code{gnatname}:
11586
11587 @table @option
11588 @c !sort!
11589
11590 @item --version
11591 @cindex @option{--version} @command{gnatname}
11592 Display Copyright and version, then exit disregarding all other options.
11593
11594 @item --help
11595 @cindex @option{--help} @command{gnatname}
11596 If @option{--version} was not used, display usage, then exit disregarding
11597 all other options.
11598
11599 @item --and
11600 Start another section of directories/patterns.
11601
11602 @item ^-c^/CONFIG_FILE=^@file{file}
11603 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11604 Create a configuration pragmas file @file{file} (instead of the default
11605 @file{gnat.adc}).
11606 @ifclear vms
11607 There may be zero, one or more space between @option{-c} and
11608 @file{file}.
11609 @end ifclear
11610 @file{file} may include directory information. @file{file} must be
11611 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11612 When a switch @option{^-c^/CONFIG_FILE^} is
11613 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11614
11615 @item ^-d^/SOURCE_DIRS=^@file{dir}
11616 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11617 Look for source files in directory @file{dir}. There may be zero, one or more
11618 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11619 When a switch @option{^-d^/SOURCE_DIRS^}
11620 is specified, the current working directory will not be searched for source
11621 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11622 or @option{^-D^/DIR_FILES^} switch.
11623 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11624 If @file{dir} is a relative path, it is relative to the directory of
11625 the configuration pragmas file specified with switch
11626 @option{^-c^/CONFIG_FILE^},
11627 or to the directory of the project file specified with switch
11628 @option{^-P^/PROJECT_FILE^} or,
11629 if neither switch @option{^-c^/CONFIG_FILE^}
11630 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11631 current working directory. The directory
11632 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11633
11634 @item ^-D^/DIRS_FILE=^@file{file}
11635 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11636 Look for source files in all directories listed in text file @file{file}.
11637 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11638 and @file{file}.
11639 @file{file} must be an existing, readable text file.
11640 Each nonempty line in @file{file} must be a directory.
11641 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11642 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11643 @file{file}.
11644
11645 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11646 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11647 Foreign patterns. Using this switch, it is possible to add sources of languages
11648 other than Ada to the list of sources of a project file.
11649 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11650 For example,
11651 @smallexample
11652 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11653 @end smallexample
11654 @noindent
11655 will look for Ada units in all files with the @file{.ada} extension,
11656 and will add to the list of file for project @file{prj.gpr} the C files
11657 with extension @file{.^c^C^}.
11658
11659 @item ^-h^/HELP^
11660 @cindex @option{^-h^/HELP^} (@code{gnatname})
11661 Output usage (help) information. The output is written to @file{stdout}.
11662
11663 @item ^-P^/PROJECT_FILE=^@file{proj}
11664 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11665 Create or update project file @file{proj}. There may be zero, one or more space
11666 between @option{-P} and @file{proj}. @file{proj} may include directory
11667 information. @file{proj} must be writable.
11668 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11669 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11670 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11671
11672 @item ^-v^/VERBOSE^
11673 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11674 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11675 This includes name of the file written, the name of the directories to search
11676 and, for each file in those directories whose name matches at least one of
11677 the Naming Patterns, an indication of whether the file contains a unit,
11678 and if so the name of the unit.
11679
11680 @item ^-v -v^/VERBOSE /VERBOSE^
11681 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11682 Very Verbose mode. In addition to the output produced in verbose mode,
11683 for each file in the searched directories whose name matches none of
11684 the Naming Patterns, an indication is given that there is no match.
11685
11686 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11687 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11688 Excluded patterns. Using this switch, it is possible to exclude some files
11689 that would match the name patterns. For example,
11690 @smallexample
11691 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11692 @end smallexample
11693 @noindent
11694 will look for Ada units in all files with the @file{.ada} extension,
11695 except those whose names end with @file{_nt.ada}.
11696
11697 @end table
11698
11699 @node Examples of gnatname Usage
11700 @section Examples of @code{gnatname} Usage
11701
11702 @ifset vms
11703 @smallexample
11704 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11705 @end smallexample
11706 @end ifset
11707
11708 @ifclear vms
11709 @smallexample
11710 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11711 @end smallexample
11712 @end ifclear
11713
11714 @noindent
11715 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11716 and be writable. In addition, the directory
11717 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11718 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11719
11720 @ifclear vms
11721 Note the optional spaces after @option{-c} and @option{-d}.
11722 @end ifclear
11723
11724 @smallexample
11725 @ifclear vms
11726 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11727 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11728 @end ifclear
11729 @ifset vms
11730 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11731 /EXCLUDED_PATTERN=*_nt_body.ada
11732 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11733 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11734 @end ifset
11735 @end smallexample
11736
11737 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11738 even in conjunction with one or several switches
11739 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11740 are used in this example.
11741
11742 @c *****************************************
11743 @c * G N A T P r o j e c t M a n a g e r *
11744 @c *****************************************
11745 @node GNAT Project Manager
11746 @chapter GNAT Project Manager
11747
11748 @menu
11749 * Introduction::
11750 * Examples of Project Files::
11751 * Project File Syntax::
11752 * Objects and Sources in Project Files::
11753 * Importing Projects::
11754 * Project Extension::
11755 * Project Hierarchy Extension::
11756 * External References in Project Files::
11757 * Packages in Project Files::
11758 * Variables from Imported Projects::
11759 * Naming Schemes::
11760 * Library Projects::
11761 * Stand-alone Library Projects::
11762 * Switches Related to Project Files::
11763 * Tools Supporting Project Files::
11764 * An Extended Example::
11765 * Project File Complete Syntax::
11766 @end menu
11767
11768 @c ****************
11769 @c * Introduction *
11770 @c ****************
11771
11772 @node Introduction
11773 @section Introduction
11774
11775 @noindent
11776 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11777 you to manage complex builds involving a number of source files, directories,
11778 and compilation options for different system configurations. In particular,
11779 project files allow you to specify:
11780 @itemize @bullet
11781 @item
11782 The directory or set of directories containing the source files, and/or the
11783 names of the specific source files themselves
11784 @item
11785 The directory in which the compiler's output
11786 (@file{ALI} files, object files, tree files) is to be placed
11787 @item
11788 The directory in which the executable programs is to be placed
11789 @item
11790 ^Switch^Switch^ settings for any of the project-enabled tools
11791 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11792 @code{gnatfind}); you can apply these settings either globally or to individual
11793 compilation units.
11794 @item
11795 The source files containing the main subprogram(s) to be built
11796 @item
11797 The source programming language(s) (currently Ada and/or C)
11798 @item
11799 Source file naming conventions; you can specify these either globally or for
11800 individual compilation units
11801 @end itemize
11802
11803 @menu
11804 * Project Files::
11805 @end menu
11806
11807 @node Project Files
11808 @subsection Project Files
11809
11810 @noindent
11811 Project files are written in a syntax close to that of Ada, using familiar
11812 notions such as packages, context clauses, declarations, default values,
11813 assignments, and inheritance. Finally, project files can be built
11814 hierarchically from other project files, simplifying complex system
11815 integration and project reuse.
11816
11817 A @dfn{project} is a specific set of values for various compilation properties.
11818 The settings for a given project are described by means of
11819 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11820 Property values in project files are either strings or lists of strings.
11821 Properties that are not explicitly set receive default values. A project
11822 file may interrogate the values of @dfn{external variables} (user-defined
11823 command-line switches or environment variables), and it may specify property
11824 settings conditionally, based on the value of such variables.
11825
11826 In simple cases, a project's source files depend only on other source files
11827 in the same project, or on the predefined libraries. (@emph{Dependence} is
11828 used in
11829 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11830 the Project Manager also allows more sophisticated arrangements,
11831 where the source files in one project depend on source files in other
11832 projects:
11833 @itemize @bullet
11834 @item
11835 One project can @emph{import} other projects containing needed source files.
11836 @item
11837 You can organize GNAT projects in a hierarchy: a @emph{child} project
11838 can extend a @emph{parent} project, inheriting the parent's source files and
11839 optionally overriding any of them with alternative versions
11840 @end itemize
11841
11842 @noindent
11843 More generally, the Project Manager lets you structure large development
11844 efforts into hierarchical subsystems, where build decisions are delegated
11845 to the subsystem level, and thus different compilation environments
11846 (^switch^switch^ settings) used for different subsystems.
11847
11848 The Project Manager is invoked through the
11849 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11850 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11851 @ifclear vms
11852 There may be zero, one or more spaces between @option{-P} and
11853 @option{@emph{projectfile}}.
11854 @end ifclear
11855 If you want to define (on the command line) an external variable that is
11856 queried by the project file, you must use the
11857 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11858 The Project Manager parses and interprets the project file, and drives the
11859 invoked tool based on the project settings.
11860
11861 The Project Manager supports a wide range of development strategies,
11862 for systems of all sizes. Here are some typical practices that are
11863 easily handled:
11864 @itemize @bullet
11865 @item
11866 Using a common set of source files, but generating object files in different
11867 directories via different ^switch^switch^ settings
11868 @item
11869 Using a mostly-shared set of source files, but with different versions of
11870 some unit or units
11871 @end itemize
11872
11873 @noindent
11874 The destination of an executable can be controlled inside a project file
11875 using the @option{^-o^-o^}
11876 ^switch^switch^.
11877 In the absence of such a ^switch^switch^ either inside
11878 the project file or on the command line, any executable files generated by
11879 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11880 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11881 in the object directory of the project.
11882
11883 You can use project files to achieve some of the effects of a source
11884 versioning system (for example, defining separate projects for
11885 the different sets of sources that comprise different releases) but the
11886 Project Manager is independent of any source configuration management tools
11887 that might be used by the developers.
11888
11889 The next section introduces the main features of GNAT's project facility
11890 through a sequence of examples; subsequent sections will present the syntax
11891 and semantics in more detail. A more formal description of the project
11892 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11893 Reference Manual}.
11894
11895 @c *****************************
11896 @c * Examples of Project Files *
11897 @c *****************************
11898
11899 @node Examples of Project Files
11900 @section Examples of Project Files
11901 @noindent
11902 This section illustrates some of the typical uses of project files and
11903 explains their basic structure and behavior.
11904
11905 @menu
11906 * Common Sources with Different ^Switches^Switches^ and Directories::
11907 * Using External Variables::
11908 * Importing Other Projects::
11909 * Extending a Project::
11910 @end menu
11911
11912 @node Common Sources with Different ^Switches^Switches^ and Directories
11913 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11914
11915 @menu
11916 * Source Files::
11917 * Specifying the Object Directory::
11918 * Specifying the Exec Directory::
11919 * Project File Packages::
11920 * Specifying ^Switch^Switch^ Settings::
11921 * Main Subprograms::
11922 * Executable File Names::
11923 * Source File Naming Conventions::
11924 * Source Language(s)::
11925 @end menu
11926
11927 @noindent
11928 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11929 @file{proc.adb} are in the @file{/common} directory. The file
11930 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11931 package @code{Pack}. We want to compile these source files under two sets
11932 of ^switches^switches^:
11933 @itemize @bullet
11934 @item
11935 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11936 and the @option{^-gnata^-gnata^},
11937 @option{^-gnato^-gnato^},
11938 and @option{^-gnatE^-gnatE^} switches to the
11939 compiler; the compiler's output is to appear in @file{/common/debug}
11940 @item
11941 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11942 to the compiler; the compiler's output is to appear in @file{/common/release}
11943 @end itemize
11944
11945 @noindent
11946 The GNAT project files shown below, respectively @file{debug.gpr} and
11947 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11948
11949 Schematically:
11950 @smallexample
11951 @group
11952 ^/common^[COMMON]^
11953 debug.gpr
11954 release.gpr
11955 pack.ads
11956 pack.adb
11957 proc.adb
11958 @end group
11959 @group
11960 ^/common/debug^[COMMON.DEBUG]^
11961 proc.ali, proc.o
11962 pack.ali, pack.o
11963 @end group
11964 @group
11965 ^/common/release^[COMMON.RELEASE]^
11966 proc.ali, proc.o
11967 pack.ali, pack.o
11968 @end group
11969 @end smallexample
11970 Here are the corresponding project files:
11971
11972 @smallexample @c projectfile
11973 @group
11974 project Debug is
11975 for Object_Dir use "debug";
11976 for Main use ("proc");
11977
11978 package Builder is
11979 for ^Default_Switches^Default_Switches^ ("Ada")
11980 use ("^-g^-g^");
11981 for Executable ("proc.adb") use "proc1";
11982 end Builder;
11983 @end group
11984
11985 @group
11986 package Compiler is
11987 for ^Default_Switches^Default_Switches^ ("Ada")
11988 use ("-fstack-check",
11989 "^-gnata^-gnata^",
11990 "^-gnato^-gnato^",
11991 "^-gnatE^-gnatE^");
11992 end Compiler;
11993 end Debug;
11994 @end group
11995 @end smallexample
11996
11997 @smallexample @c projectfile
11998 @group
11999 project Release is
12000 for Object_Dir use "release";
12001 for Exec_Dir use ".";
12002 for Main use ("proc");
12003
12004 package Compiler is
12005 for ^Default_Switches^Default_Switches^ ("Ada")
12006 use ("^-O2^-O2^");
12007 end Compiler;
12008 end Release;
12009 @end group
12010 @end smallexample
12011
12012 @noindent
12013 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12014 insensitive), and analogously the project defined by @file{release.gpr} is
12015 @code{"Release"}. For consistency the file should have the same name as the
12016 project, and the project file's extension should be @code{"gpr"}. These
12017 conventions are not required, but a warning is issued if they are not followed.
12018
12019 If the current directory is @file{^/temp^[TEMP]^}, then the command
12020 @smallexample
12021 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12022 @end smallexample
12023
12024 @noindent
12025 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12026 as well as the @code{^proc1^PROC1.EXE^} executable,
12027 using the ^switch^switch^ settings defined in the project file.
12028
12029 Likewise, the command
12030 @smallexample
12031 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12032 @end smallexample
12033
12034 @noindent
12035 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12036 and the @code{^proc^PROC.EXE^}
12037 executable in @file{^/common^[COMMON]^},
12038 using the ^switch^switch^ settings from the project file.
12039
12040 @node Source Files
12041 @unnumberedsubsubsec Source Files
12042
12043 @noindent
12044 If a project file does not explicitly specify a set of source directories or
12045 a set of source files, then by default the project's source files are the
12046 Ada source files in the project file directory. Thus @file{pack.ads},
12047 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12048
12049 @node Specifying the Object Directory
12050 @unnumberedsubsubsec Specifying the Object Directory
12051
12052 @noindent
12053 Several project properties are modeled by Ada-style @emph{attributes};
12054 a property is defined by supplying the equivalent of an Ada attribute
12055 definition clause in the project file.
12056 A project's object directory is another such a property; the corresponding
12057 attribute is @code{Object_Dir}, and its value is also a string expression,
12058 specified either as absolute or relative. In the later case,
12059 it is relative to the project file directory. Thus the compiler's
12060 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12061 (for the @code{Debug} project)
12062 and to @file{^/common/release^[COMMON.RELEASE]^}
12063 (for the @code{Release} project).
12064 If @code{Object_Dir} is not specified, then the default is the project file
12065 directory itself.
12066
12067 @node Specifying the Exec Directory
12068 @unnumberedsubsubsec Specifying the Exec Directory
12069
12070 @noindent
12071 A project's exec directory is another property; the corresponding
12072 attribute is @code{Exec_Dir}, and its value is also a string expression,
12073 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12074 then the default is the object directory (which may also be the project file
12075 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12076 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12077 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12078 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12079
12080 @node Project File Packages
12081 @unnumberedsubsubsec Project File Packages
12082
12083 @noindent
12084 A GNAT tool that is integrated with the Project Manager is modeled by a
12085 corresponding package in the project file. In the example above,
12086 The @code{Debug} project defines the packages @code{Builder}
12087 (for @command{gnatmake}) and @code{Compiler};
12088 the @code{Release} project defines only the @code{Compiler} package.
12089
12090 The Ada-like package syntax is not to be taken literally. Although packages in
12091 project files bear a surface resemblance to packages in Ada source code, the
12092 notation is simply a way to convey a grouping of properties for a named
12093 entity. Indeed, the package names permitted in project files are restricted
12094 to a predefined set, corresponding to the project-aware tools, and the contents
12095 of packages are limited to a small set of constructs.
12096 The packages in the example above contain attribute definitions.
12097
12098 @node Specifying ^Switch^Switch^ Settings
12099 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12100
12101 @noindent
12102 ^Switch^Switch^ settings for a project-aware tool can be specified through
12103 attributes in the package that corresponds to the tool.
12104 The example above illustrates one of the relevant attributes,
12105 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12106 in both project files.
12107 Unlike simple attributes like @code{Source_Dirs},
12108 @code{^Default_Switches^Default_Switches^} is
12109 known as an @emph{associative array}. When you define this attribute, you must
12110 supply an ``index'' (a literal string), and the effect of the attribute
12111 definition is to set the value of the array at the specified index.
12112 For the @code{^Default_Switches^Default_Switches^} attribute,
12113 the index is a programming language (in our case, Ada),
12114 and the value specified (after @code{use}) must be a list
12115 of string expressions.
12116
12117 The attributes permitted in project files are restricted to a predefined set.
12118 Some may appear at project level, others in packages.
12119 For any attribute that is an associative array, the index must always be a
12120 literal string, but the restrictions on this string (e.g., a file name or a
12121 language name) depend on the individual attribute.
12122 Also depending on the attribute, its specified value will need to be either a
12123 string or a string list.
12124
12125 In the @code{Debug} project, we set the switches for two tools,
12126 @command{gnatmake} and the compiler, and thus we include the two corresponding
12127 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12128 attribute with index @code{"Ada"}.
12129 Note that the package corresponding to
12130 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
12131 similar, but only includes the @code{Compiler} package.
12132
12133 In project @code{Debug} above, the ^switches^switches^ starting with
12134 @option{-gnat} that are specified in package @code{Compiler}
12135 could have been placed in package @code{Builder}, since @command{gnatmake}
12136 transmits all such ^switches^switches^ to the compiler.
12137
12138 @node Main Subprograms
12139 @unnumberedsubsubsec Main Subprograms
12140
12141 @noindent
12142 One of the specifiable properties of a project is a list of files that contain
12143 main subprograms. This property is captured in the @code{Main} attribute,
12144 whose value is a list of strings. If a project defines the @code{Main}
12145 attribute, it is not necessary to identify the main subprogram(s) when
12146 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12147
12148 @node Executable File Names
12149 @unnumberedsubsubsec Executable File Names
12150
12151 @noindent
12152 By default, the executable file name corresponding to a main source is
12153 deduced from the main source file name. Through the attributes
12154 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12155 it is possible to change this default.
12156 In project @code{Debug} above, the executable file name
12157 for main source @file{^proc.adb^PROC.ADB^} is
12158 @file{^proc1^PROC1.EXE^}.
12159 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12160 of the executable files, when no attribute @code{Executable} applies:
12161 its value replace the platform-specific executable suffix.
12162 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12163 specify a non-default executable file name when several mains are built at once
12164 in a single @command{gnatmake} command.
12165
12166 @node Source File Naming Conventions
12167 @unnumberedsubsubsec Source File Naming Conventions
12168
12169 @noindent
12170 Since the project files above do not specify any source file naming
12171 conventions, the GNAT defaults are used. The mechanism for defining source
12172 file naming conventions -- a package named @code{Naming} --
12173 is described below (@pxref{Naming Schemes}).
12174
12175 @node Source Language(s)
12176 @unnumberedsubsubsec Source Language(s)
12177
12178 @noindent
12179 Since the project files do not specify a @code{Languages} attribute, by
12180 default the GNAT tools assume that the language of the project file is Ada.
12181 More generally, a project can comprise source files
12182 in Ada, C, and/or other languages.
12183
12184 @node Using External Variables
12185 @subsection Using External Variables
12186
12187 @noindent
12188 Instead of supplying different project files for debug and release, we can
12189 define a single project file that queries an external variable (set either
12190 on the command line or via an ^environment variable^logical name^) in order to
12191 conditionally define the appropriate settings. Again, assume that the
12192 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12193 located in directory @file{^/common^[COMMON]^}. The following project file,
12194 @file{build.gpr}, queries the external variable named @code{STYLE} and
12195 defines an object directory and ^switch^switch^ settings based on whether
12196 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12197 the default is @code{"deb"}.
12198
12199 @smallexample @c projectfile
12200 @group
12201 project Build is
12202 for Main use ("proc");
12203
12204 type Style_Type is ("deb", "rel");
12205 Style : Style_Type := external ("STYLE", "deb");
12206
12207 case Style is
12208 when "deb" =>
12209 for Object_Dir use "debug";
12210
12211 when "rel" =>
12212 for Object_Dir use "release";
12213 for Exec_Dir use ".";
12214 end case;
12215 @end group
12216
12217 @group
12218 package Builder is
12219
12220 case Style is
12221 when "deb" =>
12222 for ^Default_Switches^Default_Switches^ ("Ada")
12223 use ("^-g^-g^");
12224 for Executable ("proc") use "proc1";
12225 when others =>
12226 null;
12227 end case;
12228
12229 end Builder;
12230 @end group
12231
12232 @group
12233 package Compiler is
12234
12235 case Style is
12236 when "deb" =>
12237 for ^Default_Switches^Default_Switches^ ("Ada")
12238 use ("^-gnata^-gnata^",
12239 "^-gnato^-gnato^",
12240 "^-gnatE^-gnatE^");
12241
12242 when "rel" =>
12243 for ^Default_Switches^Default_Switches^ ("Ada")
12244 use ("^-O2^-O2^");
12245 end case;
12246
12247 end Compiler;
12248
12249 end Build;
12250 @end group
12251 @end smallexample
12252
12253 @noindent
12254 @code{Style_Type} is an example of a @emph{string type}, which is the project
12255 file analog of an Ada enumeration type but whose components are string literals
12256 rather than identifiers. @code{Style} is declared as a variable of this type.
12257
12258 The form @code{external("STYLE", "deb")} is known as an
12259 @emph{external reference}; its first argument is the name of an
12260 @emph{external variable}, and the second argument is a default value to be
12261 used if the external variable doesn't exist. You can define an external
12262 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12263 or you can use ^an environment variable^a logical name^
12264 as an external variable.
12265
12266 Each @code{case} construct is expanded by the Project Manager based on the
12267 value of @code{Style}. Thus the command
12268 @ifclear vms
12269 @smallexample
12270 gnatmake -P/common/build.gpr -XSTYLE=deb
12271 @end smallexample
12272 @end ifclear
12273
12274 @ifset vms
12275 @smallexample
12276 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12277 @end smallexample
12278 @end ifset
12279
12280 @noindent
12281 is equivalent to the @command{gnatmake} invocation using the project file
12282 @file{debug.gpr} in the earlier example. So is the command
12283 @smallexample
12284 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12285 @end smallexample
12286
12287 @noindent
12288 since @code{"deb"} is the default for @code{STYLE}.
12289
12290 Analogously,
12291
12292 @ifclear vms
12293 @smallexample
12294 gnatmake -P/common/build.gpr -XSTYLE=rel
12295 @end smallexample
12296 @end ifclear
12297
12298 @ifset vms
12299 @smallexample
12300 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12301 @end smallexample
12302 @end ifset
12303
12304 @noindent
12305 is equivalent to the @command{gnatmake} invocation using the project file
12306 @file{release.gpr} in the earlier example.
12307
12308 @node Importing Other Projects
12309 @subsection Importing Other Projects
12310 @cindex @code{ADA_PROJECT_PATH}
12311 @cindex @code{GPR_PROJECT_PATH}
12312
12313 @noindent
12314 A compilation unit in a source file in one project may depend on compilation
12315 units in source files in other projects. To compile this unit under
12316 control of a project file, the
12317 dependent project must @emph{import} the projects containing the needed source
12318 files.
12319 This effect is obtained using syntax similar to an Ada @code{with} clause,
12320 but where @code{with}ed entities are strings that denote project files.
12321
12322 As an example, suppose that the two projects @code{GUI_Proj} and
12323 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12324 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12325 and @file{^/comm^[COMM]^}, respectively.
12326 Suppose that the source files for @code{GUI_Proj} are
12327 @file{gui.ads} and @file{gui.adb}, and that the source files for
12328 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12329 files is located in its respective project file directory. Schematically:
12330
12331 @smallexample
12332 @group
12333 ^/gui^[GUI]^
12334 gui_proj.gpr
12335 gui.ads
12336 gui.adb
12337 @end group
12338
12339 @group
12340 ^/comm^[COMM]^
12341 comm_proj.gpr
12342 comm.ads
12343 comm.adb
12344 @end group
12345 @end smallexample
12346
12347 @noindent
12348 We want to develop an application in directory @file{^/app^[APP]^} that
12349 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12350 the corresponding project files (e.g.@: the ^switch^switch^ settings
12351 and object directory).
12352 Skeletal code for a main procedure might be something like the following:
12353
12354 @smallexample @c ada
12355 @group
12356 with GUI, Comm;
12357 procedure App_Main is
12358 @dots{}
12359 begin
12360 @dots{}
12361 end App_Main;
12362 @end group
12363 @end smallexample
12364
12365 @noindent
12366 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12367 effect:
12368
12369 @smallexample @c projectfile
12370 @group
12371 with "/gui/gui_proj", "/comm/comm_proj";
12372 project App_Proj is
12373 for Main use ("app_main");
12374 end App_Proj;
12375 @end group
12376 @end smallexample
12377
12378 @noindent
12379 Building an executable is achieved through the command:
12380 @smallexample
12381 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12382 @end smallexample
12383 @noindent
12384 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12385 in the directory where @file{app_proj.gpr} resides.
12386
12387 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12388 (as illustrated above) the @code{with} clause can omit the extension.
12389
12390 Our example specified an absolute path for each imported project file.
12391 Alternatively, the directory name of an imported object can be omitted
12392 if either
12393 @itemize @bullet
12394 @item
12395 The imported project file is in the same directory as the importing project
12396 file, or
12397 @item
12398 You have defined one or two ^environment variables^logical names^
12399 that includes the directory containing
12400 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12401 @code{ADA_PROJECT_PATH} is the same as
12402 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12403 directory names separated by colons (semicolons on Windows).
12404 @end itemize
12405
12406 @noindent
12407 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12408 to include @file{^/gui^[GUI]^} and
12409 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12410 as follows:
12411
12412 @smallexample @c projectfile
12413 @group
12414 with "gui_proj", "comm_proj";
12415 project App_Proj is
12416 for Main use ("app_main");
12417 end App_Proj;
12418 @end group
12419 @end smallexample
12420
12421 @noindent
12422 Importing other projects can create ambiguities.
12423 For example, the same unit might be present in different imported projects, or
12424 it might be present in both the importing project and in an imported project.
12425 Both of these conditions are errors. Note that in the current version of
12426 the Project Manager, it is illegal to have an ambiguous unit even if the
12427 unit is never referenced by the importing project. This restriction may be
12428 relaxed in a future release.
12429
12430 @node Extending a Project
12431 @subsection Extending a Project
12432
12433 @noindent
12434 In large software systems it is common to have multiple
12435 implementations of a common interface; in Ada terms, multiple versions of a
12436 package body for the same spec. For example, one implementation
12437 might be safe for use in tasking programs, while another might only be used
12438 in sequential applications. This can be modeled in GNAT using the concept
12439 of @emph{project extension}. If one project (the ``child'') @emph{extends}
12440 another project (the ``parent'') then by default all source files of the
12441 parent project are inherited by the child, but the child project can
12442 override any of the parent's source files with new versions, and can also
12443 add new files. This facility is the project analog of a type extension in
12444 Object-Oriented Programming. Project hierarchies are permitted (a child
12445 project may be the parent of yet another project), and a project that
12446 inherits one project can also import other projects.
12447
12448 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12449 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12450 @file{pack.adb}, and @file{proc.adb}:
12451
12452 @smallexample
12453 @group
12454 ^/seq^[SEQ]^
12455 pack.ads
12456 pack.adb
12457 proc.adb
12458 seq_proj.gpr
12459 @end group
12460 @end smallexample
12461
12462 @noindent
12463 Note that the project file can simply be empty (that is, no attribute or
12464 package is defined):
12465
12466 @smallexample @c projectfile
12467 @group
12468 project Seq_Proj is
12469 end Seq_Proj;
12470 @end group
12471 @end smallexample
12472
12473 @noindent
12474 implying that its source files are all the Ada source files in the project
12475 directory.
12476
12477 Suppose we want to supply an alternate version of @file{pack.adb}, in
12478 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12479 @file{pack.ads} and @file{proc.adb}. We can define a project
12480 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12481
12482 @smallexample
12483 @group
12484 ^/tasking^[TASKING]^
12485 pack.adb
12486 tasking_proj.gpr
12487 @end group
12488
12489 @group
12490 project Tasking_Proj extends "/seq/seq_proj" is
12491 end Tasking_Proj;
12492 @end group
12493 @end smallexample
12494
12495 @noindent
12496 The version of @file{pack.adb} used in a build depends on which project file
12497 is specified.
12498
12499 Note that we could have obtained the desired behavior using project import
12500 rather than project inheritance; a @code{base} project would contain the
12501 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12502 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12503 would import @code{base} and add a different version of @file{pack.adb}. The
12504 choice depends on whether other sources in the original project need to be
12505 overridden. If they do, then project extension is necessary, otherwise,
12506 importing is sufficient.
12507
12508 @noindent
12509 In a project file that extends another project file, it is possible to
12510 indicate that an inherited source is not part of the sources of the extending
12511 project. This is necessary sometimes when a package spec has been overloaded
12512 and no longer requires a body: in this case, it is necessary to indicate that
12513 the inherited body is not part of the sources of the project, otherwise there
12514 will be a compilation error when compiling the spec.
12515
12516 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12517 Its value is a string list: a list of file names. It is also possible to use
12518 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12519 the file name of a text file containing a list of file names, one per line.
12520
12521 @smallexample @c @projectfile
12522 project B extends "a" is
12523 for Source_Files use ("pkg.ads");
12524 -- New spec of Pkg does not need a completion
12525 for Excluded_Source_Files use ("pkg.adb");
12526 end B;
12527 @end smallexample
12528
12529 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12530 is still needed: if it is possible to build using @command{gnatmake} when such
12531 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12532 it is possible to remove the source completely from a system that includes
12533 project P.
12534
12535 @c ***********************
12536 @c * Project File Syntax *
12537 @c ***********************
12538
12539 @node Project File Syntax
12540 @section Project File Syntax
12541
12542 @menu
12543 * Basic Syntax::
12544 * Qualified Projects::
12545 * Packages::
12546 * Expressions::
12547 * String Types::
12548 * Variables::
12549 * Attributes::
12550 * Associative Array Attributes::
12551 * case Constructions::
12552 @end menu
12553
12554 @noindent
12555 This section describes the structure of project files.
12556
12557 A project may be an @emph{independent project}, entirely defined by a single
12558 project file. Any Ada source file in an independent project depends only
12559 on the predefined library and other Ada source files in the same project.
12560
12561 @noindent
12562 A project may also @dfn{depend on} other projects, in either or both of
12563 the following ways:
12564 @itemize @bullet
12565 @item It may import any number of projects
12566 @item It may extend at most one other project
12567 @end itemize
12568
12569 @noindent
12570 The dependence relation is a directed acyclic graph (the subgraph reflecting
12571 the ``extends'' relation is a tree).
12572
12573 A project's @dfn{immediate sources} are the source files directly defined by
12574 that project, either implicitly by residing in the project file's directory,
12575 or explicitly through any of the source-related attributes described below.
12576 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12577 of @var{proj} together with the immediate sources (unless overridden) of any
12578 project on which @var{proj} depends (either directly or indirectly).
12579
12580 @node Basic Syntax
12581 @subsection Basic Syntax
12582
12583 @noindent
12584 As seen in the earlier examples, project files have an Ada-like syntax.
12585 The minimal project file is:
12586 @smallexample @c projectfile
12587 @group
12588 project Empty is
12589
12590 end Empty;
12591 @end group
12592 @end smallexample
12593
12594 @noindent
12595 The identifier @code{Empty} is the name of the project.
12596 This project name must be present after the reserved
12597 word @code{end} at the end of the project file, followed by a semi-colon.
12598
12599 Any name in a project file, such as the project name or a variable name,
12600 has the same syntax as an Ada identifier.
12601
12602 The reserved words of project files are the Ada 95 reserved words plus
12603 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
12604 reserved words currently used in project file syntax are:
12605
12606 @itemize @bullet
12607 @item
12608 @code{all}
12609 @item
12610 @code{at}
12611 @item
12612 @code{case}
12613 @item
12614 @code{end}
12615 @item
12616 @code{for}
12617 @item
12618 @code{is}
12619 @item
12620 @code{limited}
12621 @item
12622 @code{null}
12623 @item
12624 @code{others}
12625 @item
12626 @code{package}
12627 @item
12628 @code{renames}
12629 @item
12630 @code{type}
12631 @item
12632 @code{use}
12633 @item
12634 @code{when}
12635 @item
12636 @code{with}
12637 @end itemize
12638
12639 @noindent
12640 Comments in project files have the same syntax as in Ada, two consecutive
12641 hyphens through the end of the line.
12642
12643 @node Qualified Projects
12644 @subsection Qualified Projects
12645
12646 @noindent
12647 Before the reserved @code{project}, there may be one or two "qualifiers", that
12648 is identifiers or other reserved words, to qualify the project.
12649
12650 The current list of qualifiers is:
12651
12652 @itemize @bullet
12653 @item
12654 @code{abstract}: qualify a project with no sources. A qualified abstract
12655 project must either have no declaration of attributes @code{Source_Dirs},
12656 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12657 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12658 as empty. If it extends another project, the project it extends must also be a
12659 qualified abstract project.
12660
12661 @item
12662 @code{standard}: a standard project is a non library project with sources.
12663
12664 @item
12665 @code{aggregate}: for future extension
12666
12667 @item
12668 @code{aggregate library}: for future extension
12669
12670 @item
12671 @code{library}: a library project must declare both attributes
12672 @code{Library_Name} and @code{Library_Dir}.
12673
12674 @item
12675 @code{configuration}: a configuration project cannot be in a project tree.
12676 @end itemize
12677
12678 @node Packages
12679 @subsection Packages
12680
12681 @noindent
12682 A project file may contain @emph{packages}. The name of a package must be one
12683 of the identifiers from the following list. A package
12684 with a given name may only appear once in a project file. Package names are
12685 case insensitive. The following package names are legal:
12686
12687 @itemize @bullet
12688 @item
12689 @code{Naming}
12690 @item
12691 @code{Builder}
12692 @item
12693 @code{Compiler}
12694 @item
12695 @code{Binder}
12696 @item
12697 @code{Linker}
12698 @item
12699 @code{Finder}
12700 @item
12701 @code{Cross_Reference}
12702 @item
12703 @code{Eliminate}
12704 @item
12705 @code{Pretty_Printer}
12706 @item
12707 @code{Metrics}
12708 @item
12709 @code{gnatls}
12710 @item
12711 @code{gnatstub}
12712 @item
12713 @code{IDE}
12714 @item
12715 @code{Language_Processing}
12716 @end itemize
12717
12718 @noindent
12719 In its simplest form, a package may be empty:
12720
12721 @smallexample @c projectfile
12722 @group
12723 project Simple is
12724 package Builder is
12725 end Builder;
12726 end Simple;
12727 @end group
12728 @end smallexample
12729
12730 @noindent
12731 A package may contain @emph{attribute declarations},
12732 @emph{variable declarations} and @emph{case constructions}, as will be
12733 described below.
12734
12735 When there is ambiguity between a project name and a package name,
12736 the name always designates the project. To avoid possible confusion, it is
12737 always a good idea to avoid naming a project with one of the
12738 names allowed for packages or any name that starts with @code{gnat}.
12739
12740 @node Expressions
12741 @subsection Expressions
12742
12743 @noindent
12744 An @emph{expression} is either a @emph{string expression} or a
12745 @emph{string list expression}.
12746
12747 A @emph{string expression} is either a @emph{simple string expression} or a
12748 @emph{compound string expression}.
12749
12750 A @emph{simple string expression} is one of the following:
12751 @itemize @bullet
12752 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12753 @item A string-valued variable reference (@pxref{Variables})
12754 @item A string-valued attribute reference (@pxref{Attributes})
12755 @item An external reference (@pxref{External References in Project Files})
12756 @end itemize
12757
12758 @noindent
12759 A @emph{compound string expression} is a concatenation of string expressions,
12760 using the operator @code{"&"}
12761 @smallexample
12762 Path & "/" & File_Name & ".ads"
12763 @end smallexample
12764
12765 @noindent
12766 A @emph{string list expression} is either a
12767 @emph{simple string list expression} or a
12768 @emph{compound string list expression}.
12769
12770 A @emph{simple string list expression} is one of the following:
12771 @itemize @bullet
12772 @item A parenthesized list of zero or more string expressions,
12773 separated by commas
12774 @smallexample
12775 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12776 Empty_List := ();
12777 @end smallexample
12778 @item A string list-valued variable reference
12779 @item A string list-valued attribute reference
12780 @end itemize
12781
12782 @noindent
12783 A @emph{compound string list expression} is the concatenation (using
12784 @code{"&"}) of a simple string list expression and an expression. Note that
12785 each term in a compound string list expression, except the first, may be
12786 either a string expression or a string list expression.
12787
12788 @smallexample @c projectfile
12789 @group
12790 File_Name_List := () & File_Name; -- One string in this list
12791 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12792 -- Two strings
12793 Big_List := File_Name_List & Extended_File_Name_List;
12794 -- Concatenation of two string lists: three strings
12795 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12796 -- Illegal: must start with a string list
12797 @end group
12798 @end smallexample
12799
12800 @node String Types
12801 @subsection String Types
12802
12803 @noindent
12804 A @emph{string type declaration} introduces a discrete set of string literals.
12805 If a string variable is declared to have this type, its value
12806 is restricted to the given set of literals.
12807
12808 Here is an example of a string type declaration:
12809
12810 @smallexample @c projectfile
12811 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12812 @end smallexample
12813
12814 @noindent
12815 Variables of a string type are called @emph{typed variables}; all other
12816 variables are called @emph{untyped variables}. Typed variables are
12817 particularly useful in @code{case} constructions, to support conditional
12818 attribute declarations.
12819 (@pxref{case Constructions}).
12820
12821 The string literals in the list are case sensitive and must all be different.
12822 They may include any graphic characters allowed in Ada, including spaces.
12823
12824 A string type may only be declared at the project level, not inside a package.
12825
12826 A string type may be referenced by its name if it has been declared in the same
12827 project file, or by an expanded name whose prefix is the name of the project
12828 in which it is declared.
12829
12830 @node Variables
12831 @subsection Variables
12832
12833 @noindent
12834 A variable may be declared at the project file level, or within a package.
12835 Here are some examples of variable declarations:
12836
12837 @smallexample @c projectfile
12838 @group
12839 This_OS : OS := external ("OS"); -- a typed variable declaration
12840 That_OS := "GNU/Linux"; -- an untyped variable declaration
12841 @end group
12842 @end smallexample
12843
12844 @noindent
12845 The syntax of a @emph{typed variable declaration} is identical to the Ada
12846 syntax for an object declaration. By contrast, the syntax of an untyped
12847 variable declaration is identical to an Ada assignment statement. In fact,
12848 variable declarations in project files have some of the characteristics of
12849 an assignment, in that successive declarations for the same variable are
12850 allowed. Untyped variable declarations do establish the expected kind of the
12851 variable (string or string list), and successive declarations for it must
12852 respect the initial kind.
12853
12854 @noindent
12855 A string variable declaration (typed or untyped) declares a variable
12856 whose value is a string. This variable may be used as a string expression.
12857 @smallexample @c projectfile
12858 File_Name := "readme.txt";
12859 Saved_File_Name := File_Name & ".saved";
12860 @end smallexample
12861
12862 @noindent
12863 A string list variable declaration declares a variable whose value is a list
12864 of strings. The list may contain any number (zero or more) of strings.
12865
12866 @smallexample @c projectfile
12867 Empty_List := ();
12868 List_With_One_Element := ("^-gnaty^-gnaty^");
12869 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12870 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12871 "pack2.ada", "util_.ada", "util.ada");
12872 @end smallexample
12873
12874 @noindent
12875 The same typed variable may not be declared more than once at project level,
12876 and it may not be declared more than once in any package; it is in effect
12877 a constant.
12878
12879 The same untyped variable may be declared several times. Declarations are
12880 elaborated in the order in which they appear, so the new value replaces
12881 the old one, and any subsequent reference to the variable uses the new value.
12882 However, as noted above, if a variable has been declared as a string, all
12883 subsequent
12884 declarations must give it a string value. Similarly, if a variable has
12885 been declared as a string list, all subsequent declarations
12886 must give it a string list value.
12887
12888 A @emph{variable reference} may take several forms:
12889
12890 @itemize @bullet
12891 @item The simple variable name, for a variable in the current package (if any)
12892 or in the current project
12893 @item An expanded name, whose prefix is a context name.
12894 @end itemize
12895
12896 @noindent
12897 A @emph{context} may be one of the following:
12898
12899 @itemize @bullet
12900 @item The name of an existing package in the current project
12901 @item The name of an imported project of the current project
12902 @item The name of an ancestor project (i.e., a project extended by the current
12903 project, either directly or indirectly)
12904 @item An expanded name whose prefix is an imported/parent project name, and
12905 whose selector is a package name in that project.
12906 @end itemize
12907
12908 @noindent
12909 A variable reference may be used in an expression.
12910
12911 @node Attributes
12912 @subsection Attributes
12913
12914 @noindent
12915 A project (and its packages) may have @emph{attributes} that define
12916 the project's properties. Some attributes have values that are strings;
12917 others have values that are string lists.
12918
12919 There are two categories of attributes: @emph{simple attributes}
12920 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12921
12922 Legal project attribute names, and attribute names for each legal package are
12923 listed below. Attributes names are case-insensitive.
12924
12925 The following attributes are defined on projects (all are simple attributes):
12926
12927 @multitable @columnfractions .4 .3
12928 @item @emph{Attribute Name}
12929 @tab @emph{Value}
12930 @item @code{Source_Files}
12931 @tab string list
12932 @item @code{Source_Dirs}
12933 @tab string list
12934 @item @code{Source_List_File}
12935 @tab string
12936 @item @code{Object_Dir}
12937 @tab string
12938 @item @code{Exec_Dir}
12939 @tab string
12940 @item @code{Excluded_Source_Dirs}
12941 @tab string list
12942 @item @code{Excluded_Source_Files}
12943 @tab string list
12944 @item @code{Excluded_Source_List_File}
12945 @tab string
12946 @item @code{Languages}
12947 @tab string list
12948 @item @code{Main}
12949 @tab string list
12950 @item @code{Library_Dir}
12951 @tab string
12952 @item @code{Library_Name}
12953 @tab string
12954 @item @code{Library_Kind}
12955 @tab string
12956 @item @code{Library_Version}
12957 @tab string
12958 @item @code{Library_Interface}
12959 @tab string
12960 @item @code{Library_Auto_Init}
12961 @tab string
12962 @item @code{Library_Options}
12963 @tab string list
12964 @item @code{Library_Src_Dir}
12965 @tab string
12966 @item @code{Library_ALI_Dir}
12967 @tab string
12968 @item @code{Library_GCC}
12969 @tab string
12970 @item @code{Library_Symbol_File}
12971 @tab string
12972 @item @code{Library_Symbol_Policy}
12973 @tab string
12974 @item @code{Library_Reference_Symbol_File}
12975 @tab string
12976 @item @code{Externally_Built}
12977 @tab string
12978 @end multitable
12979
12980 @noindent
12981 The following attributes are defined for package @code{Naming}
12982 (@pxref{Naming Schemes}):
12983
12984 @multitable @columnfractions .4 .2 .2 .2
12985 @item Attribute Name @tab Category @tab Index @tab Value
12986 @item @code{Spec_Suffix}
12987 @tab associative array
12988 @tab language name
12989 @tab string
12990 @item @code{Body_Suffix}
12991 @tab associative array
12992 @tab language name
12993 @tab string
12994 @item @code{Separate_Suffix}
12995 @tab simple attribute
12996 @tab n/a
12997 @tab string
12998 @item @code{Casing}
12999 @tab simple attribute
13000 @tab n/a
13001 @tab string
13002 @item @code{Dot_Replacement}
13003 @tab simple attribute
13004 @tab n/a
13005 @tab string
13006 @item @code{Spec}
13007 @tab associative array
13008 @tab Ada unit name
13009 @tab string
13010 @item @code{Body}
13011 @tab associative array
13012 @tab Ada unit name
13013 @tab string
13014 @item @code{Specification_Exceptions}
13015 @tab associative array
13016 @tab language name
13017 @tab string list
13018 @item @code{Implementation_Exceptions}
13019 @tab associative array
13020 @tab language name
13021 @tab string list
13022 @end multitable
13023
13024 @noindent
13025 The following attributes are defined for packages @code{Builder},
13026 @code{Compiler}, @code{Binder},
13027 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13028 (@pxref{^Switches^Switches^ and Project Files}).
13029
13030 @multitable @columnfractions .4 .2 .2 .2
13031 @item Attribute Name @tab Category @tab Index @tab Value
13032 @item @code{^Default_Switches^Default_Switches^}
13033 @tab associative array
13034 @tab language name
13035 @tab string list
13036 @item @code{^Switches^Switches^}
13037 @tab associative array
13038 @tab file name
13039 @tab string list
13040 @end multitable
13041
13042 @noindent
13043 In addition, package @code{Compiler} has a single string attribute
13044 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13045 string attribute @code{Global_Configuration_Pragmas}.
13046
13047 @noindent
13048 Each simple attribute has a default value: the empty string (for string-valued
13049 attributes) and the empty list (for string list-valued attributes).
13050
13051 An attribute declaration defines a new value for an attribute.
13052
13053 Examples of simple attribute declarations:
13054
13055 @smallexample @c projectfile
13056 for Object_Dir use "objects";
13057 for Source_Dirs use ("units", "test/drivers");
13058 @end smallexample
13059
13060 @noindent
13061 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13062 attribute definition clause in Ada.
13063
13064 Attributes references may be appear in expressions.
13065 The general form for such a reference is @code{<entity>'<attribute>}:
13066 Associative array attributes are functions. Associative
13067 array attribute references must have an argument that is a string literal.
13068
13069 Examples are:
13070
13071 @smallexample @c projectfile
13072 project'Object_Dir
13073 Naming'Dot_Replacement
13074 Imported_Project'Source_Dirs
13075 Imported_Project.Naming'Casing
13076 Builder'^Default_Switches^Default_Switches^("Ada")
13077 @end smallexample
13078
13079 @noindent
13080 The prefix of an attribute may be:
13081 @itemize @bullet
13082 @item @code{project} for an attribute of the current project
13083 @item The name of an existing package of the current project
13084 @item The name of an imported project
13085 @item The name of a parent project that is extended by the current project
13086 @item An expanded name whose prefix is imported/parent project name,
13087 and whose selector is a package name
13088 @end itemize
13089
13090 @noindent
13091 Example:
13092 @smallexample @c projectfile
13093 @group
13094 project Prj is
13095 for Source_Dirs use project'Source_Dirs & "units";
13096 for Source_Dirs use project'Source_Dirs & "test/drivers"
13097 end Prj;
13098 @end group
13099 @end smallexample
13100
13101 @noindent
13102 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13103 has the default value: an empty string list. After this declaration,
13104 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13105 After the second attribute declaration @code{Source_Dirs} is a string list of
13106 two elements: @code{"units"} and @code{"test/drivers"}.
13107
13108 Note: this example is for illustration only. In practice,
13109 the project file would contain only one attribute declaration:
13110
13111 @smallexample @c projectfile
13112 for Source_Dirs use ("units", "test/drivers");
13113 @end smallexample
13114
13115 @node Associative Array Attributes
13116 @subsection Associative Array Attributes
13117
13118 @noindent
13119 Some attributes are defined as @emph{associative arrays}. An associative
13120 array may be regarded as a function that takes a string as a parameter
13121 and delivers a string or string list value as its result.
13122
13123 Here are some examples of single associative array attribute associations:
13124
13125 @smallexample @c projectfile
13126 for Body ("main") use "Main.ada";
13127 for ^Switches^Switches^ ("main.ada")
13128 use ("^-v^-v^",
13129 "^-gnatv^-gnatv^");
13130 for ^Switches^Switches^ ("main.ada")
13131 use Builder'^Switches^Switches^ ("main.ada")
13132 & "^-g^-g^";
13133 @end smallexample
13134
13135 @noindent
13136 Like untyped variables and simple attributes, associative array attributes
13137 may be declared several times. Each declaration supplies a new value for the
13138 attribute, and replaces the previous setting.
13139
13140 @noindent
13141 An associative array attribute may be declared as a full associative array
13142 declaration, with the value of the same attribute in an imported or extended
13143 project.
13144
13145 @smallexample @c projectfile
13146 package Builder is
13147 for Default_Switches use Default.Builder'Default_Switches;
13148 end Builder;
13149 @end smallexample
13150
13151 @noindent
13152 In this example, @code{Default} must be either a project imported by the
13153 current project, or the project that the current project extends. If the
13154 attribute is in a package (in this case, in package @code{Builder}), the same
13155 package needs to be specified.
13156
13157 @noindent
13158 A full associative array declaration replaces any other declaration for the
13159 attribute, including other full associative array declaration. Single
13160 associative array associations may be declare after a full associative
13161 declaration, modifying the value for a single association of the attribute.
13162
13163 @node case Constructions
13164 @subsection @code{case} Constructions
13165
13166 @noindent
13167 A @code{case} construction is used in a project file to effect conditional
13168 behavior.
13169 Here is a typical example:
13170
13171 @smallexample @c projectfile
13172 @group
13173 project MyProj is
13174 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13175
13176 OS : OS_Type := external ("OS", "GNU/Linux");
13177 @end group
13178
13179 @group
13180 package Compiler is
13181 case OS is
13182 when "GNU/Linux" | "Unix" =>
13183 for ^Default_Switches^Default_Switches^ ("Ada")
13184 use ("^-gnath^-gnath^");
13185 when "NT" =>
13186 for ^Default_Switches^Default_Switches^ ("Ada")
13187 use ("^-gnatP^-gnatP^");
13188 when others =>
13189 end case;
13190 end Compiler;
13191 end MyProj;
13192 @end group
13193 @end smallexample
13194
13195 @noindent
13196 The syntax of a @code{case} construction is based on the Ada case statement
13197 (although there is no @code{null} construction for empty alternatives).
13198
13199 The case expression must be a typed string variable.
13200 Each alternative comprises the reserved word @code{when}, either a list of
13201 literal strings separated by the @code{"|"} character or the reserved word
13202 @code{others}, and the @code{"=>"} token.
13203 Each literal string must belong to the string type that is the type of the
13204 case variable.
13205 An @code{others} alternative, if present, must occur last.
13206
13207 After each @code{=>}, there are zero or more constructions. The only
13208 constructions allowed in a case construction are other case constructions,
13209 attribute declarations and variable declarations. String type declarations and
13210 package declarations are not allowed. Variable declarations are restricted to
13211 variables that have already been declared before the case construction.
13212
13213 The value of the case variable is often given by an external reference
13214 (@pxref{External References in Project Files}).
13215
13216 @c ****************************************
13217 @c * Objects and Sources in Project Files *
13218 @c ****************************************
13219
13220 @node Objects and Sources in Project Files
13221 @section Objects and Sources in Project Files
13222
13223 @menu
13224 * Object Directory::
13225 * Exec Directory::
13226 * Source Directories::
13227 * Source File Names::
13228 @end menu
13229
13230 @noindent
13231 Each project has exactly one object directory and one or more source
13232 directories. The source directories must contain at least one source file,
13233 unless the project file explicitly specifies that no source files are present
13234 (@pxref{Source File Names}).
13235
13236 @node Object Directory
13237 @subsection Object Directory
13238
13239 @noindent
13240 The object directory for a project is the directory containing the compiler's
13241 output (such as @file{ALI} files and object files) for the project's immediate
13242 sources.
13243
13244 The object directory is given by the value of the attribute @code{Object_Dir}
13245 in the project file.
13246
13247 @smallexample @c projectfile
13248 for Object_Dir use "objects";
13249 @end smallexample
13250
13251 @noindent
13252 The attribute @code{Object_Dir} has a string value, the path name of the object
13253 directory. The path name may be absolute or relative to the directory of the
13254 project file. This directory must already exist, and be readable and writable.
13255
13256 By default, when the attribute @code{Object_Dir} is not given an explicit value
13257 or when its value is the empty string, the object directory is the same as the
13258 directory containing the project file.
13259
13260 @node Exec Directory
13261 @subsection Exec Directory
13262
13263 @noindent
13264 The exec directory for a project is the directory containing the executables
13265 for the project's main subprograms.
13266
13267 The exec directory is given by the value of the attribute @code{Exec_Dir}
13268 in the project file.
13269
13270 @smallexample @c projectfile
13271 for Exec_Dir use "executables";
13272 @end smallexample
13273
13274 @noindent
13275 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13276 directory. The path name may be absolute or relative to the directory of the
13277 project file. This directory must already exist, and be writable.
13278
13279 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13280 or when its value is the empty string, the exec directory is the same as the
13281 object directory of the project file.
13282
13283 @node Source Directories
13284 @subsection Source Directories
13285
13286 @noindent
13287 The source directories of a project are specified by the project file
13288 attribute @code{Source_Dirs}.
13289
13290 This attribute's value is a string list. If the attribute is not given an
13291 explicit value, then there is only one source directory, the one where the
13292 project file resides.
13293
13294 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13295 as in
13296
13297 @smallexample @c projectfile
13298 for Source_Dirs use ();
13299 @end smallexample
13300
13301 @noindent
13302 indicates that the project contains no source files.
13303
13304 Otherwise, each string in the string list designates one or more
13305 source directories.
13306
13307 @smallexample @c projectfile
13308 for Source_Dirs use ("sources", "test/drivers");
13309 @end smallexample
13310
13311 @noindent
13312 If a string in the list ends with @code{"/**"}, then the directory whose path
13313 name precedes the two asterisks, as well as all its subdirectories
13314 (recursively), are source directories.
13315
13316 @smallexample @c projectfile
13317 for Source_Dirs use ("/system/sources/**");
13318 @end smallexample
13319
13320 @noindent
13321 Here the directory @code{/system/sources} and all of its subdirectories
13322 (recursively) are source directories.
13323
13324 To specify that the source directories are the directory of the project file
13325 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13326 @smallexample @c projectfile
13327 for Source_Dirs use ("./**");
13328 @end smallexample
13329
13330 @noindent
13331 Each of the source directories must exist and be readable.
13332
13333 @node Source File Names
13334 @subsection Source File Names
13335
13336 @noindent
13337 In a project that contains source files, their names may be specified by the
13338 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13339 (a string). Source file names never include any directory information.
13340
13341 If the attribute @code{Source_Files} is given an explicit value, then each
13342 element of the list is a source file name.
13343
13344 @smallexample @c projectfile
13345 for Source_Files use ("main.adb");
13346 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13347 @end smallexample
13348
13349 @noindent
13350 If the attribute @code{Source_Files} is not given an explicit value,
13351 but the attribute @code{Source_List_File} is given a string value,
13352 then the source file names are contained in the text file whose path name
13353 (absolute or relative to the directory of the project file) is the
13354 value of the attribute @code{Source_List_File}.
13355
13356 Each line in the file that is not empty or is not a comment
13357 contains a source file name.
13358
13359 @smallexample @c projectfile
13360 for Source_List_File use "source_list.txt";
13361 @end smallexample
13362
13363 @noindent
13364 By default, if neither the attribute @code{Source_Files} nor the attribute
13365 @code{Source_List_File} is given an explicit value, then each file in the
13366 source directories that conforms to the project's naming scheme
13367 (@pxref{Naming Schemes}) is an immediate source of the project.
13368
13369 A warning is issued if both attributes @code{Source_Files} and
13370 @code{Source_List_File} are given explicit values. In this case, the attribute
13371 @code{Source_Files} prevails.
13372
13373 Each source file name must be the name of one existing source file
13374 in one of the source directories.
13375
13376 A @code{Source_Files} attribute whose value is an empty list
13377 indicates that there are no source files in the project.
13378
13379 If the order of the source directories is known statically, that is if
13380 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13381 be several files with the same source file name. In this case, only the file
13382 in the first directory is considered as an immediate source of the project
13383 file. If the order of the source directories is not known statically, it is
13384 an error to have several files with the same source file name.
13385
13386 Projects can be specified to have no Ada source
13387 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13388 list, or the @code{"Ada"} may be absent from @code{Languages}:
13389
13390 @smallexample @c projectfile
13391 for Source_Dirs use ();
13392 for Source_Files use ();
13393 for Languages use ("C", "C++");
13394 @end smallexample
13395
13396 @noindent
13397 Otherwise, a project must contain at least one immediate source.
13398
13399 Projects with no source files are useful as template packages
13400 (@pxref{Packages in Project Files}) for other projects; in particular to
13401 define a package @code{Naming} (@pxref{Naming Schemes}).
13402
13403 @c ****************************
13404 @c * Importing Projects *
13405 @c ****************************
13406
13407 @node Importing Projects
13408 @section Importing Projects
13409 @cindex @code{ADA_PROJECT_PATH}
13410 @cindex @code{GPR_PROJECT_PATH}
13411
13412 @noindent
13413 An immediate source of a project P may depend on source files that
13414 are neither immediate sources of P nor in the predefined library.
13415 To get this effect, P must @emph{import} the projects that contain the needed
13416 source files.
13417
13418 @smallexample @c projectfile
13419 @group
13420 with "project1", "utilities.gpr";
13421 with "/namings/apex.gpr";
13422 project Main is
13423 @dots{}
13424 @end group
13425 @end smallexample
13426
13427 @noindent
13428 As can be seen in this example, the syntax for importing projects is similar
13429 to the syntax for importing compilation units in Ada. However, project files
13430 use literal strings instead of names, and the @code{with} clause identifies
13431 project files rather than packages.
13432
13433 Each literal string is the file name or path name (absolute or relative) of a
13434 project file. If a string corresponds to a file name, with no path or a
13435 relative path, then its location is determined by the @emph{project path}. The
13436 latter can be queried using @code{gnatls -v}. It contains:
13437
13438 @itemize @bullet
13439 @item
13440 In first position, the directory containing the current project file.
13441 @item
13442 In last position, the default project directory. This default project directory
13443 is part of the GNAT installation and is the standard place to install project
13444 files giving access to standard support libraries.
13445 @ifclear vms
13446 @ref{Installing a library}
13447 @end ifclear
13448
13449 @item
13450 In between, all the directories referenced in the
13451 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13452 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13453 @end itemize
13454
13455 @noindent
13456 If a relative pathname is used, as in
13457
13458 @smallexample @c projectfile
13459 with "tests/proj";
13460 @end smallexample
13461
13462 @noindent
13463 then the full path for the project is constructed by concatenating this
13464 relative path to those in the project path, in order, until a matching file is
13465 found. Any symbolic link will be fully resolved in the directory of the
13466 importing project file before the imported project file is examined.
13467
13468 If the @code{with}'ed project file name does not have an extension,
13469 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13470 then the file name as specified in the @code{with} clause (no extension) will
13471 be used. In the above example, if a file @code{project1.gpr} is found, then it
13472 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13473 then it will be used; if neither file exists, this is an error.
13474
13475 A warning is issued if the name of the project file does not match the
13476 name of the project; this check is case insensitive.
13477
13478 Any source file that is an immediate source of the imported project can be
13479 used by the immediate sources of the importing project, transitively. Thus
13480 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13481 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13482 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13483 because if and when @code{B} ceases to import @code{C}, some sources in
13484 @code{A} will no longer compile.
13485
13486 A side effect of this capability is that normally cyclic dependencies are not
13487 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13488 is not allowed to import @code{A}. However, there are cases when cyclic
13489 dependencies would be beneficial. For these cases, another form of import
13490 between projects exists, the @code{limited with}: a project @code{A} that
13491 imports a project @code{B} with a straight @code{with} may also be imported,
13492 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13493 to @code{A} include at least one @code{limited with}.
13494
13495 @smallexample @c 0projectfile
13496 with "../b/b.gpr";
13497 with "../c/c.gpr";
13498 project A is
13499 end A;
13500
13501 limited with "../a/a.gpr";
13502 project B is
13503 end B;
13504
13505 with "../d/d.gpr";
13506 project C is
13507 end C;
13508
13509 limited with "../a/a.gpr";
13510 project D is
13511 end D;
13512 @end smallexample
13513
13514 @noindent
13515 In the above legal example, there are two project cycles:
13516 @itemize @bullet
13517 @item A-> B-> A
13518 @item A -> C -> D -> A
13519 @end itemize
13520
13521 @noindent
13522 In each of these cycle there is one @code{limited with}: import of @code{A}
13523 from @code{B} and import of @code{A} from @code{D}.
13524
13525 The difference between straight @code{with} and @code{limited with} is that
13526 the name of a project imported with a @code{limited with} cannot be used in the
13527 project that imports it. In particular, its packages cannot be renamed and
13528 its variables cannot be referred to.
13529
13530 An exception to the above rules for @code{limited with} is that for the main
13531 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13532 @code{limited with} is equivalent to a straight @code{with}. For example,
13533 in the example above, projects @code{B} and @code{D} could not be main
13534 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13535 each have a @code{limited with} that is the only one in a cycle of importing
13536 projects.
13537
13538 @c *********************
13539 @c * Project Extension *
13540 @c *********************
13541
13542 @node Project Extension
13543 @section Project Extension
13544
13545 @noindent
13546 During development of a large system, it is sometimes necessary to use
13547 modified versions of some of the source files, without changing the original
13548 sources. This can be achieved through the @emph{project extension} facility.
13549
13550 @smallexample @c projectfile
13551 project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13552 @end smallexample
13553
13554 @noindent
13555 A project extension declaration introduces an extending project
13556 (the @emph{child}) and a project being extended (the @emph{parent}).
13557
13558 By default, a child project inherits all the sources of its parent.
13559 However, inherited sources can be overridden: a unit in a parent is hidden
13560 by a unit of the same name in the child.
13561
13562 Inherited sources are considered to be sources (but not immediate sources)
13563 of the child project; see @ref{Project File Syntax}.
13564
13565 An inherited source file retains any switches specified in the parent project.
13566
13567 For example if the project @code{Utilities} contains the spec and the
13568 body of an Ada package @code{Util_IO}, then the project
13569 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13570 The original body of @code{Util_IO} will not be considered in program builds.
13571 However, the package spec will still be found in the project
13572 @code{Utilities}.
13573
13574 A child project can have only one parent, except when it is qualified as
13575 abstract. But it may import any number of other projects.
13576
13577 A project is not allowed to import directly or indirectly at the same time a
13578 child project and any of its ancestors.
13579
13580 @c *******************************
13581 @c * Project Hierarchy Extension *
13582 @c *******************************
13583
13584 @node Project Hierarchy Extension
13585 @section Project Hierarchy Extension
13586
13587 @noindent
13588 When extending a large system spanning multiple projects, it is often
13589 inconvenient to extend every project in the hierarchy that is impacted by a
13590 small change introduced. In such cases, it is possible to create a virtual
13591 extension of entire hierarchy using @code{extends all} relationship.
13592
13593 When the project is extended using @code{extends all} inheritance, all projects
13594 that are imported by it, both directly and indirectly, are considered virtually
13595 extended. That is, the Project Manager creates "virtual projects"
13596 that extend every project in the hierarchy; all these virtual projects have
13597 no sources of their own and have as object directory the object directory of
13598 the root of "extending all" project.
13599
13600 It is possible to explicitly extend one or more projects in the hierarchy
13601 in order to modify the sources. These extending projects must be imported by
13602 the "extending all" project, which will replace the corresponding virtual
13603 projects with the explicit ones.
13604
13605 When building such a project hierarchy extension, the Project Manager will
13606 ensure that both modified sources and sources in virtual extending projects
13607 that depend on them, are recompiled.
13608
13609 By means of example, consider the following hierarchy of projects.
13610
13611 @enumerate
13612 @item
13613 project A, containing package P1
13614 @item
13615 project B importing A and containing package P2 which depends on P1
13616 @item
13617 project C importing B and containing package P3 which depends on P2
13618 @end enumerate
13619
13620 @noindent
13621 We want to modify packages P1 and P3.
13622
13623 This project hierarchy will need to be extended as follows:
13624
13625 @enumerate
13626 @item
13627 Create project A1 that extends A, placing modified P1 there:
13628
13629 @smallexample @c 0projectfile
13630 project A1 extends "(@dots{})/A" is
13631 end A1;
13632 @end smallexample
13633
13634 @item
13635 Create project C1 that "extends all" C and imports A1, placing modified
13636 P3 there:
13637
13638 @smallexample @c 0projectfile
13639 with "(@dots{})/A1";
13640 project C1 extends all "(@dots{})/C" is
13641 end C1;
13642 @end smallexample
13643 @end enumerate
13644
13645 When you build project C1, your entire modified project space will be
13646 recompiled, including the virtual project B1 that has been impacted by the
13647 "extending all" inheritance of project C.
13648
13649 Note that if a Library Project in the hierarchy is virtually extended,
13650 the virtual project that extends the Library Project is not a Library Project.
13651
13652 @c ****************************************
13653 @c * External References in Project Files *
13654 @c ****************************************
13655
13656 @node External References in Project Files
13657 @section External References in Project Files
13658
13659 @noindent
13660 A project file may contain references to external variables; such references
13661 are called @emph{external references}.
13662
13663 An external variable is either defined as part of the environment (an
13664 environment variable in Unix, for example) or else specified on the command
13665 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13666 If both, then the command line value is used.
13667
13668 The value of an external reference is obtained by means of the built-in
13669 function @code{external}, which returns a string value.
13670 This function has two forms:
13671 @itemize @bullet
13672 @item @code{external (external_variable_name)}
13673 @item @code{external (external_variable_name, default_value)}
13674 @end itemize
13675
13676 @noindent
13677 Each parameter must be a string literal. For example:
13678
13679 @smallexample @c projectfile
13680 external ("USER")
13681 external ("OS", "GNU/Linux")
13682 @end smallexample
13683
13684 @noindent
13685 In the form with one parameter, the function returns the value of
13686 the external variable given as parameter. If this name is not present in the
13687 environment, the function returns an empty string.
13688
13689 In the form with two string parameters, the second argument is
13690 the value returned when the variable given as the first argument is not
13691 present in the environment. In the example above, if @code{"OS"} is not
13692 the name of ^an environment variable^a logical name^ and is not passed on
13693 the command line, then the returned value is @code{"GNU/Linux"}.
13694
13695 An external reference may be part of a string expression or of a string
13696 list expression, and can therefore appear in a variable declaration or
13697 an attribute declaration.
13698
13699 @smallexample @c projectfile
13700 @group
13701 type Mode_Type is ("Debug", "Release");
13702 Mode : Mode_Type := external ("MODE");
13703 case Mode is
13704 when "Debug" =>
13705 @dots{}
13706 @end group
13707 @end smallexample
13708
13709 @c *****************************
13710 @c * Packages in Project Files *
13711 @c *****************************
13712
13713 @node Packages in Project Files
13714 @section Packages in Project Files
13715
13716 @noindent
13717 A @emph{package} defines the settings for project-aware tools within a
13718 project.
13719 For each such tool one can declare a package; the names for these
13720 packages are preset (@pxref{Packages}).
13721 A package may contain variable declarations, attribute declarations, and case
13722 constructions.
13723
13724 @smallexample @c projectfile
13725 @group
13726 project Proj is
13727 package Builder is -- used by gnatmake
13728 for ^Default_Switches^Default_Switches^ ("Ada")
13729 use ("^-v^-v^",
13730 "^-g^-g^");
13731 end Builder;
13732 end Proj;
13733 @end group
13734 @end smallexample
13735
13736 @noindent
13737 The syntax of package declarations mimics that of package in Ada.
13738
13739 Most of the packages have an attribute
13740 @code{^Default_Switches^Default_Switches^}.
13741 This attribute is an associative array, and its value is a string list.
13742 The index of the associative array is the name of a programming language (case
13743 insensitive). This attribute indicates the ^switch^switch^
13744 or ^switches^switches^ to be used
13745 with the corresponding tool.
13746
13747 Some packages also have another attribute, @code{^Switches^Switches^},
13748 an associative array whose value is a string list.
13749 The index is the name of a source file.
13750 This attribute indicates the ^switch^switch^
13751 or ^switches^switches^ to be used by the corresponding
13752 tool when dealing with this specific file.
13753
13754 Further information on these ^switch^switch^-related attributes is found in
13755 @ref{^Switches^Switches^ and Project Files}.
13756
13757 A package may be declared as a @emph{renaming} of another package; e.g., from
13758 the project file for an imported project.
13759
13760 @smallexample @c projectfile
13761 @group
13762 with "/global/apex.gpr";
13763 project Example is
13764 package Naming renames Apex.Naming;
13765 @dots{}
13766 end Example;
13767 @end group
13768 @end smallexample
13769
13770 @noindent
13771 Packages that are renamed in other project files often come from project files
13772 that have no sources: they are just used as templates. Any modification in the
13773 template will be reflected automatically in all the project files that rename
13774 a package from the template.
13775
13776 In addition to the tool-oriented packages, you can also declare a package
13777 named @code{Naming} to establish specialized source file naming conventions
13778 (@pxref{Naming Schemes}).
13779
13780 @c ************************************
13781 @c * Variables from Imported Projects *
13782 @c ************************************
13783
13784 @node Variables from Imported Projects
13785 @section Variables from Imported Projects
13786
13787 @noindent
13788 An attribute or variable defined in an imported or parent project can
13789 be used in expressions in the importing / extending project.
13790 Such an attribute or variable is denoted by an expanded name whose prefix
13791 is either the name of the project or the expanded name of a package within
13792 a project.
13793
13794 @smallexample @c projectfile
13795 @group
13796 with "imported";
13797 project Main extends "base" is
13798 Var1 := Imported.Var;
13799 Var2 := Base.Var & ".new";
13800 @end group
13801
13802 @group
13803 package Builder is
13804 for ^Default_Switches^Default_Switches^ ("Ada")
13805 use Imported.Builder'Ada_^Switches^Switches^ &
13806 "^-gnatg^-gnatg^" &
13807 "^-v^-v^";
13808 end Builder;
13809 @end group
13810
13811 @group
13812 package Compiler is
13813 for ^Default_Switches^Default_Switches^ ("Ada")
13814 use Base.Compiler'Ada_^Switches^Switches^;
13815 end Compiler;
13816 end Main;
13817 @end group
13818 @end smallexample
13819
13820 @noindent
13821 In this example:
13822
13823 @itemize @bullet
13824 @item
13825 The value of @code{Var1} is a copy of the variable @code{Var} defined
13826 in the project file @file{"imported.gpr"}
13827 @item
13828 the value of @code{Var2} is a copy of the value of variable @code{Var}
13829 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13830 @item
13831 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13832 @code{Builder} is a string list that includes in its value a copy of the value
13833 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13834 in project file @file{imported.gpr} plus two new elements:
13835 @option{"^-gnatg^-gnatg^"}
13836 and @option{"^-v^-v^"};
13837 @item
13838 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13839 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13840 defined in the @code{Compiler} package in project file @file{base.gpr},
13841 the project being extended.
13842 @end itemize
13843
13844 @c ******************
13845 @c * Naming Schemes *
13846 @c ******************
13847
13848 @node Naming Schemes
13849 @section Naming Schemes
13850
13851 @noindent
13852 Sometimes an Ada software system is ported from a foreign compilation
13853 environment to GNAT, and the file names do not use the default GNAT
13854 conventions. Instead of changing all the file names (which for a variety
13855 of reasons might not be possible), you can define the relevant file
13856 naming scheme in the @code{Naming} package in your project file.
13857
13858 @noindent
13859 Note that the use of pragmas described in
13860 @ref{Alternative File Naming Schemes} by mean of a configuration
13861 pragmas file is not supported when using project files. You must use
13862 the features described in this paragraph. You can however use specify
13863 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13864
13865 @ifclear vms
13866 For example, the following
13867 package models the Apex file naming rules:
13868
13869 @smallexample @c projectfile
13870 @group
13871 package Naming is
13872 for Casing use "lowercase";
13873 for Dot_Replacement use ".";
13874 for Spec_Suffix ("Ada") use ".1.ada";
13875 for Body_Suffix ("Ada") use ".2.ada";
13876 end Naming;
13877 @end group
13878 @end smallexample
13879 @end ifclear
13880
13881 @ifset vms
13882 For example, the following package models the HP Ada file naming rules:
13883
13884 @smallexample @c projectfile
13885 @group
13886 package Naming is
13887 for Casing use "lowercase";
13888 for Dot_Replacement use "__";
13889 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13890 for Body_Suffix ("Ada") use ".^ada^ada^";
13891 end Naming;
13892 @end group
13893 @end smallexample
13894
13895 @noindent
13896 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13897 names in lower case)
13898 @end ifset
13899
13900 @noindent
13901 You can define the following attributes in package @code{Naming}:
13902
13903 @table @code
13904
13905 @item @code{Casing}
13906 This must be a string with one of the three values @code{"lowercase"},
13907 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13908
13909 @noindent
13910 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13911
13912 @item @code{Dot_Replacement}
13913 This must be a string whose value satisfies the following conditions:
13914
13915 @itemize @bullet
13916 @item It must not be empty
13917 @item It cannot start or end with an alphanumeric character
13918 @item It cannot be a single underscore
13919 @item It cannot start with an underscore followed by an alphanumeric
13920 @item It cannot contain a dot @code{'.'} except if the entire string
13921 is @code{"."}
13922 @end itemize
13923
13924 @noindent
13925 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13926
13927 @item @code{Spec_Suffix}
13928 This is an associative array (indexed by the programming language name, case
13929 insensitive) whose value is a string that must satisfy the following
13930 conditions:
13931
13932 @itemize @bullet
13933 @item It must not be empty
13934 @item It must include at least one dot
13935 @end itemize
13936 @noindent
13937 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13938 @code{"^.ads^.ADS^"}.
13939
13940 @item @code{Body_Suffix}
13941 This is an associative array (indexed by the programming language name, case
13942 insensitive) whose value is a string that must satisfy the following
13943 conditions:
13944
13945 @itemize @bullet
13946 @item It must not be empty
13947 @item It must include at least one dot
13948 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13949 @end itemize
13950 @noindent
13951 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13952 same string, then a file name that ends with the longest of these two suffixes
13953 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13954 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13955
13956 If the suffix does not start with a '.', a file with a name exactly equal
13957 to the suffix will also be part of the project (for instance if you define
13958 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13959 of the project. This is not interesting in general when using projects to
13960 compile. However, it might become useful when a project is also used to
13961 find the list of source files in an editor, like the GNAT Programming System
13962 (GPS).
13963
13964 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13965 @code{"^.adb^.ADB^"}.
13966
13967 @item @code{Separate_Suffix}
13968 This must be a string whose value satisfies the same conditions as
13969 @code{Body_Suffix}. The same "longest suffix" rules apply.
13970
13971 @noindent
13972 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13973 value as @code{Body_Suffix ("Ada")}.
13974
13975 @item @code{Spec}
13976 @noindent
13977 You can use the associative array attribute @code{Spec} to define
13978 the source file name for an individual Ada compilation unit's spec. The array
13979 index must be a string literal that identifies the Ada unit (case insensitive).
13980 The value of this attribute must be a string that identifies the file that
13981 contains this unit's spec (case sensitive or insensitive depending on the
13982 operating system).
13983
13984 @smallexample @c projectfile
13985 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13986 @end smallexample
13987
13988 When the source file contains several units, you can indicate at what
13989 position the unit occurs in the file, with the following. The first unit
13990 in the file has index 1
13991
13992 @smallexample @c projectfile
13993 for Body ("top") use "foo.a" at 1;
13994 for Body ("foo") use "foo.a" at 2;
13995 @end smallexample
13996
13997 @item @code{Body}
13998
13999 You can use the associative array attribute @code{Body} to
14000 define the source file name for an individual Ada compilation unit's body
14001 (possibly a subunit). The array index must be a string literal that identifies
14002 the Ada unit (case insensitive). The value of this attribute must be a string
14003 that identifies the file that contains this unit's body or subunit (case
14004 sensitive or insensitive depending on the operating system).
14005
14006 @smallexample @c projectfile
14007 for Body ("MyPack.MyChild") use "mypack.mychild.body";
14008 @end smallexample
14009 @end table
14010
14011 @c ********************
14012 @c * Library Projects *
14013 @c ********************
14014
14015 @node Library Projects
14016 @section Library Projects
14017
14018 @noindent
14019 @emph{Library projects} are projects whose object code is placed in a library.
14020 (Note that this facility is not yet supported on all platforms).
14021
14022 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14023 single archive, which might either be a shared or a static library. This
14024 library can later on be linked with multiple executables, potentially
14025 reducing their sizes.
14026
14027 If your project file specifies languages other than Ada, but you are still
14028 using @code{gnatmake} to compile and link, the latter will not try to
14029 compile your sources other than Ada (you should use @code{gprbuild} if that
14030 is your intent). However, @code{gnatmake} will automatically link all object
14031 files found in the object directory, whether or not they were compiled from
14032 an Ada source file. This specific behavior only applies when multiple
14033 languages are specified.
14034
14035 To create a library project, you need to define in its project file
14036 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14037 Additionally, you may define other library-related attributes such as
14038 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14039 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14040
14041 The @code{Library_Name} attribute has a string value. There is no restriction
14042 on the name of a library. It is the responsibility of the developer to
14043 choose a name that will be accepted by the platform. It is recommended to
14044 choose names that could be Ada identifiers; such names are almost guaranteed
14045 to be acceptable on all platforms.
14046
14047 The @code{Library_Dir} attribute has a string value that designates the path
14048 (absolute or relative) of the directory where the library will reside.
14049 It must designate an existing directory, and this directory must be writable,
14050 different from the project's object directory and from any source directory
14051 in the project tree.
14052
14053 If both @code{Library_Name} and @code{Library_Dir} are specified and
14054 are legal, then the project file defines a library project. The optional
14055 library-related attributes are checked only for such project files.
14056
14057 The @code{Library_Kind} attribute has a string value that must be one of the
14058 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14059 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14060 attribute is not specified, the library is a static library, that is
14061 an archive of object files that can be potentially linked into a
14062 static executable. Otherwise, the library may be dynamic or
14063 relocatable, that is a library that is loaded only at the start of execution.
14064
14065 If you need to build both a static and a dynamic library, you should use two
14066 different object directories, since in some cases some extra code needs to
14067 be generated for the latter. For such cases, it is recommended to either use
14068 two different project files, or a single one which uses external variables
14069 to indicate what kind of library should be build.
14070
14071 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14072 directory where the ALI files of the library will be copied. When it is
14073 not specified, the ALI files are copied to the directory specified in
14074 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14075 must be writable and different from the project's object directory and from
14076 any source directory in the project tree.
14077
14078 The @code{Library_Version} attribute has a string value whose interpretation
14079 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14080 used only for dynamic/relocatable libraries as the internal name of the
14081 library (the @code{"soname"}). If the library file name (built from the
14082 @code{Library_Name}) is different from the @code{Library_Version}, then the
14083 library file will be a symbolic link to the actual file whose name will be
14084 @code{Library_Version}.
14085
14086 Example (on Unix):
14087
14088 @smallexample @c projectfile
14089 @group
14090 project Plib is
14091
14092 Version := "1";
14093
14094 for Library_Dir use "lib_dir";
14095 for Library_Name use "dummy";
14096 for Library_Kind use "relocatable";
14097 for Library_Version use "libdummy.so." & Version;
14098
14099 end Plib;
14100 @end group
14101 @end smallexample
14102
14103 @noindent
14104 Directory @file{lib_dir} will contain the internal library file whose name
14105 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14106 @file{libdummy.so.1}.
14107
14108 When @command{gnatmake} detects that a project file
14109 is a library project file, it will check all immediate sources of the project
14110 and rebuild the library if any of the sources have been recompiled.
14111
14112 Standard project files can import library project files. In such cases,
14113 the libraries will only be rebuilt if some of its sources are recompiled
14114 because they are in the closure of some other source in an importing project.
14115 Sources of the library project files that are not in such a closure will
14116 not be checked, unless the full library is checked, because one of its sources
14117 needs to be recompiled.
14118
14119 For instance, assume the project file @code{A} imports the library project file
14120 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14121 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14122 @file{l2.ads}, @file{l2.adb}.
14123
14124 If @file{l1.adb} has been modified, then the library associated with @code{L}
14125 will be rebuilt when compiling all the immediate sources of @code{A} only
14126 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14127 @code{"with L1;"}.
14128
14129 To be sure that all the sources in the library associated with @code{L} are
14130 up to date, and that all the sources of project @code{A} are also up to date,
14131 the following two commands needs to be used:
14132
14133 @smallexample
14134 gnatmake -Pl.gpr
14135 gnatmake -Pa.gpr
14136 @end smallexample
14137
14138 When a library is built or rebuilt, an attempt is made first to delete all
14139 files in the library directory.
14140 All @file{ALI} files will also be copied from the object directory to the
14141 library directory. To build executables, @command{gnatmake} will use the
14142 library rather than the individual object files.
14143
14144 @ifclear vms
14145 It is also possible to create library project files for third-party libraries
14146 that are precompiled and cannot be compiled locally thanks to the
14147 @code{externally_built} attribute. (See @ref{Installing a library}).
14148 @end ifclear
14149
14150 @c *******************************
14151 @c * Stand-alone Library Projects *
14152 @c *******************************
14153
14154 @node Stand-alone Library Projects
14155 @section Stand-alone Library Projects
14156
14157 @noindent
14158 A Stand-alone Library is a library that contains the necessary code to
14159 elaborate the Ada units that are included in the library. A Stand-alone
14160 Library is suitable to be used in an executable when the main is not
14161 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14162 subprogram.
14163
14164 A Stand-alone Library Project is a Library Project where the library is
14165 a Stand-alone Library.
14166
14167 To be a Stand-alone Library Project, in addition to the two attributes
14168 that make a project a Library Project (@code{Library_Name} and
14169 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14170 @code{Library_Interface} must be defined.
14171
14172 @smallexample @c projectfile
14173 @group
14174 for Library_Dir use "lib_dir";
14175 for Library_Name use "dummy";
14176 for Library_Interface use ("int1", "int1.child");
14177 @end group
14178 @end smallexample
14179
14180 Attribute @code{Library_Interface} has a nonempty string list value,
14181 each string in the list designating a unit contained in an immediate source
14182 of the project file.
14183
14184 When a Stand-alone Library is built, first the binder is invoked to build
14185 a package whose name depends on the library name
14186 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14187 This binder-generated package includes initialization and
14188 finalization procedures whose
14189 names depend on the library name (dummyinit and dummyfinal in the example
14190 above). The object corresponding to this package is included in the library.
14191
14192 A dynamic or relocatable Stand-alone Library is automatically initialized
14193 if automatic initialization of Stand-alone Libraries is supported on the
14194 platform and if attribute @code{Library_Auto_Init} is not specified or
14195 is specified with the value "true". A static Stand-alone Library is never
14196 automatically initialized.
14197
14198 Single string attribute @code{Library_Auto_Init} may be specified with only
14199 two possible values: "false" or "true" (case-insensitive). Specifying
14200 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14201 initialization of dynamic or relocatable libraries.
14202
14203 When a non-automatically initialized Stand-alone Library is used
14204 in an executable, its initialization procedure must be called before
14205 any service of the library is used.
14206 When the main subprogram is in Ada, it may mean that the initialization
14207 procedure has to be called during elaboration of another package.
14208
14209 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14210 (those that are listed in attribute @code{Library_Interface}) are copied to
14211 the Library Directory. As a consequence, only the Interface Units may be
14212 imported from Ada units outside of the library. If other units are imported,
14213 the binding phase will fail.
14214
14215 When a Stand-Alone Library is bound, the switches that are specified in
14216 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14217 used in the call to @command{gnatbind}.
14218
14219 The string list attribute @code{Library_Options} may be used to specified
14220 additional switches to the call to @command{gcc} to link the library.
14221
14222 The attribute @code{Library_Src_Dir}, may be specified for a
14223 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14224 single string value. Its value must be the path (absolute or relative to the
14225 project directory) of an existing directory. This directory cannot be the
14226 object directory or one of the source directories, but it can be the same as
14227 the library directory. The sources of the Interface
14228 Units of the library, necessary to an Ada client of the library, will be
14229 copied to the designated directory, called Interface Copy directory.
14230 These sources includes the specs of the Interface Units, but they may also
14231 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14232 are used, or when there is a generic units in the spec. Before the sources
14233 are copied to the Interface Copy directory, an attempt is made to delete all
14234 files in the Interface Copy directory.
14235
14236 @c *************************************
14237 @c * Switches Related to Project Files *
14238 @c *************************************
14239 @node Switches Related to Project Files
14240 @section Switches Related to Project Files
14241
14242 @noindent
14243 The following switches are used by GNAT tools that support project files:
14244
14245 @table @option
14246
14247 @item ^-P^/PROJECT_FILE=^@var{project}
14248 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14249 Indicates the name of a project file. This project file will be parsed with
14250 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14251 if any, and using the external references indicated
14252 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14253 @ifclear vms
14254 There may zero, one or more spaces between @option{-P} and @var{project}.
14255 @end ifclear
14256
14257 @noindent
14258 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14259
14260 @noindent
14261 Since the Project Manager parses the project file only after all the switches
14262 on the command line are checked, the order of the switches
14263 @option{^-P^/PROJECT_FILE^},
14264 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14265 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14266
14267 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14268 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14269 Indicates that external variable @var{name} has the value @var{value}.
14270 The Project Manager will use this value for occurrences of
14271 @code{external(name)} when parsing the project file.
14272
14273 @ifclear vms
14274 @noindent
14275 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14276 put between quotes.
14277 @smallexample
14278 -XOS=NT
14279 -X"user=John Doe"
14280 @end smallexample
14281 @end ifclear
14282
14283 @noindent
14284 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14285 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14286 @var{name}, only the last one is used.
14287
14288 @noindent
14289 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14290 takes precedence over the value of the same name in the environment.
14291
14292 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14293 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14294 Indicates the verbosity of the parsing of GNAT project files.
14295
14296 @ifclear vms
14297 @option{-vP0} means Default;
14298 @option{-vP1} means Medium;
14299 @option{-vP2} means High.
14300 @end ifclear
14301
14302 @ifset vms
14303 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14304 HIGH.
14305 @end ifset
14306
14307 @noindent
14308 The default is ^Default^DEFAULT^: no output for syntactically correct
14309 project files.
14310 @noindent
14311 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14312 only the last one is used.
14313
14314 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14315 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14316 Add directory <dir> at the beginning of the project search path, in order,
14317 after the current working directory.
14318
14319 @ifclear vms
14320 @item -eL
14321 @cindex @option{-eL} (any project-aware tool)
14322 Follow all symbolic links when processing project files.
14323 @end ifclear
14324
14325 @item ^--subdirs^/SUBDIRS^=<subdir>
14326 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14327 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14328 directories (except the source directories) are the subdirectories <subdir>
14329 of the directories specified in the project files. This applies in particular
14330 to object directories, library directories and exec directories. If the
14331 subdirectories do not exist, they are created automatically.
14332
14333 @end table
14334
14335 @c **********************************
14336 @c * Tools Supporting Project Files *
14337 @c **********************************
14338
14339 @node Tools Supporting Project Files
14340 @section Tools Supporting Project Files
14341
14342 @menu
14343 * gnatmake and Project Files::
14344 * The GNAT Driver and Project Files::
14345 @end menu
14346
14347 @node gnatmake and Project Files
14348 @subsection gnatmake and Project Files
14349
14350 @noindent
14351 This section covers several topics related to @command{gnatmake} and
14352 project files: defining ^switches^switches^ for @command{gnatmake}
14353 and for the tools that it invokes; specifying configuration pragmas;
14354 the use of the @code{Main} attribute; building and rebuilding library project
14355 files.
14356
14357 @menu
14358 * ^Switches^Switches^ and Project Files::
14359 * Specifying Configuration Pragmas::
14360 * Project Files and Main Subprograms::
14361 * Library Project Files::
14362 @end menu
14363
14364 @node ^Switches^Switches^ and Project Files
14365 @subsubsection ^Switches^Switches^ and Project Files
14366
14367 @ifset vms
14368 It is not currently possible to specify VMS style qualifiers in the project
14369 files; only Unix style ^switches^switches^ may be specified.
14370 @end ifset
14371
14372 @noindent
14373 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14374 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14375 attribute, a @code{^Switches^Switches^} attribute, or both;
14376 as their names imply, these ^switch^switch^-related
14377 attributes affect the ^switches^switches^ that are used for each of these GNAT
14378 components when
14379 @command{gnatmake} is invoked. As will be explained below, these
14380 component-specific ^switches^switches^ precede
14381 the ^switches^switches^ provided on the @command{gnatmake} command line.
14382
14383 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14384 array indexed by language name (case insensitive) whose value is a string list.
14385 For example:
14386
14387 @smallexample @c projectfile
14388 @group
14389 package Compiler is
14390 for ^Default_Switches^Default_Switches^ ("Ada")
14391 use ("^-gnaty^-gnaty^",
14392 "^-v^-v^");
14393 end Compiler;
14394 @end group
14395 @end smallexample
14396
14397 @noindent
14398 The @code{^Switches^Switches^} attribute is also an associative array,
14399 indexed by a file name (which may or may not be case sensitive, depending
14400 on the operating system) whose value is a string list. For example:
14401
14402 @smallexample @c projectfile
14403 @group
14404 package Builder is
14405 for ^Switches^Switches^ ("main1.adb")
14406 use ("^-O2^-O2^");
14407 for ^Switches^Switches^ ("main2.adb")
14408 use ("^-g^-g^");
14409 end Builder;
14410 @end group
14411 @end smallexample
14412
14413 @noindent
14414 For the @code{Builder} package, the file names must designate source files
14415 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
14416 file names must designate @file{ALI} or source files for main subprograms.
14417 In each case just the file name without an explicit extension is acceptable.
14418
14419 For each tool used in a program build (@command{gnatmake}, the compiler, the
14420 binder, and the linker), the corresponding package @dfn{contributes} a set of
14421 ^switches^switches^ for each file on which the tool is invoked, based on the
14422 ^switch^switch^-related attributes defined in the package.
14423 In particular, the ^switches^switches^
14424 that each of these packages contributes for a given file @var{f} comprise:
14425
14426 @itemize @bullet
14427 @item
14428 the value of attribute @code{^Switches^Switches^ (@var{f})},
14429 if it is specified in the package for the given file,
14430 @item
14431 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14432 if it is specified in the package.
14433 @end itemize
14434
14435 @noindent
14436 If neither of these attributes is defined in the package, then the package does
14437 not contribute any ^switches^switches^ for the given file.
14438
14439 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14440 two sets, in the following order: those contributed for the file
14441 by the @code{Builder} package;
14442 and the switches passed on the command line.
14443
14444 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14445 the ^switches^switches^ passed to the tool comprise three sets,
14446 in the following order:
14447
14448 @enumerate
14449 @item
14450 the applicable ^switches^switches^ contributed for the file
14451 by the @code{Builder} package in the project file supplied on the command line;
14452
14453 @item
14454 those contributed for the file by the package (in the relevant project file --
14455 see below) corresponding to the tool; and
14456
14457 @item
14458 the applicable switches passed on the command line.
14459 @end enumerate
14460
14461 @noindent
14462 The term @emph{applicable ^switches^switches^} reflects the fact that
14463 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14464 tools, depending on the individual ^switch^switch^.
14465
14466 @command{gnatmake} may invoke the compiler on source files from different
14467 projects. The Project Manager will use the appropriate project file to
14468 determine the @code{Compiler} package for each source file being compiled.
14469 Likewise for the @code{Binder} and @code{Linker} packages.
14470
14471 As an example, consider the following package in a project file:
14472
14473 @smallexample @c projectfile
14474 @group
14475 project Proj1 is
14476 package Compiler is
14477 for ^Default_Switches^Default_Switches^ ("Ada")
14478 use ("^-g^-g^");
14479 for ^Switches^Switches^ ("a.adb")
14480 use ("^-O1^-O1^");
14481 for ^Switches^Switches^ ("b.adb")
14482 use ("^-O2^-O2^",
14483 "^-gnaty^-gnaty^");
14484 end Compiler;
14485 end Proj1;
14486 @end group
14487 @end smallexample
14488
14489 @noindent
14490 If @command{gnatmake} is invoked with this project file, and it needs to
14491 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14492 @file{a.adb} will be compiled with the ^switch^switch^
14493 @option{^-O1^-O1^},
14494 @file{b.adb} with ^switches^switches^
14495 @option{^-O2^-O2^}
14496 and @option{^-gnaty^-gnaty^},
14497 and @file{c.adb} with @option{^-g^-g^}.
14498
14499 The following example illustrates the ordering of the ^switches^switches^
14500 contributed by different packages:
14501
14502 @smallexample @c projectfile
14503 @group
14504 project Proj2 is
14505 package Builder is
14506 for ^Switches^Switches^ ("main.adb")
14507 use ("^-g^-g^",
14508 "^-O1^-)1^",
14509 "^-f^-f^");
14510 end Builder;
14511 @end group
14512
14513 @group
14514 package Compiler is
14515 for ^Switches^Switches^ ("main.adb")
14516 use ("^-O2^-O2^");
14517 end Compiler;
14518 end Proj2;
14519 @end group
14520 @end smallexample
14521
14522 @noindent
14523 If you issue the command:
14524
14525 @smallexample
14526 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14527 @end smallexample
14528
14529 @noindent
14530 then the compiler will be invoked on @file{main.adb} with the following
14531 sequence of ^switches^switches^
14532
14533 @smallexample
14534 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14535 @end smallexample
14536
14537 with the last @option{^-O^-O^}
14538 ^switch^switch^ having precedence over the earlier ones;
14539 several other ^switches^switches^
14540 (such as @option{^-c^-c^}) are added implicitly.
14541
14542 The ^switches^switches^
14543 @option{^-g^-g^}
14544 and @option{^-O1^-O1^} are contributed by package
14545 @code{Builder}, @option{^-O2^-O2^} is contributed
14546 by the package @code{Compiler}
14547 and @option{^-O0^-O0^} comes from the command line.
14548
14549 The @option{^-g^-g^}
14550 ^switch^switch^ will also be passed in the invocation of
14551 @command{Gnatlink.}
14552
14553 A final example illustrates switch contributions from packages in different
14554 project files:
14555
14556 @smallexample @c projectfile
14557 @group
14558 project Proj3 is
14559 for Source_Files use ("pack.ads", "pack.adb");
14560 package Compiler is
14561 for ^Default_Switches^Default_Switches^ ("Ada")
14562 use ("^-gnata^-gnata^");
14563 end Compiler;
14564 end Proj3;
14565 @end group
14566
14567 @group
14568 with "Proj3";
14569 project Proj4 is
14570 for Source_Files use ("foo_main.adb", "bar_main.adb");
14571 package Builder is
14572 for ^Switches^Switches^ ("foo_main.adb")
14573 use ("^-s^-s^",
14574 "^-g^-g^");
14575 end Builder;
14576 end Proj4;
14577 @end group
14578
14579 @group
14580 -- Ada source file:
14581 with Pack;
14582 procedure Foo_Main is
14583 @dots{}
14584 end Foo_Main;
14585 @end group
14586 @end smallexample
14587
14588 If the command is
14589 @smallexample
14590 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14591 @end smallexample
14592
14593 @noindent
14594 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14595 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14596 @option{^-gnato^-gnato^} (passed on the command line).
14597 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14598 are @option{^-g^-g^} from @code{Proj4.Builder},
14599 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14600 and @option{^-gnato^-gnato^} from the command line.
14601
14602 @noindent
14603 When using @command{gnatmake} with project files, some ^switches^switches^ or
14604 arguments may be expressed as relative paths. As the working directory where
14605 compilation occurs may change, these relative paths are converted to absolute
14606 paths. For the ^switches^switches^ found in a project file, the relative paths
14607 are relative to the project file directory, for the switches on the command
14608 line, they are relative to the directory where @command{gnatmake} is invoked.
14609 The ^switches^switches^ for which this occurs are:
14610 ^-I^-I^,
14611 ^-A^-A^,
14612 ^-L^-L^,
14613 ^-aO^-aO^,
14614 ^-aL^-aL^,
14615 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14616 ^switch^switch^
14617 ^-o^-o^, object files specified in package @code{Linker} or after
14618 -largs on the command line). The exception to this rule is the ^switch^switch^
14619 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14620
14621 @node Specifying Configuration Pragmas
14622 @subsubsection Specifying Configuration Pragmas
14623
14624 When using @command{gnatmake} with project files, if there exists a file
14625 @file{gnat.adc} that contains configuration pragmas, this file will be
14626 ignored.
14627
14628 Configuration pragmas can be defined by means of the following attributes in
14629 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14630 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14631
14632 Both these attributes are single string attributes. Their values is the path
14633 name of a file containing configuration pragmas. If a path name is relative,
14634 then it is relative to the project directory of the project file where the
14635 attribute is defined.
14636
14637 When compiling a source, the configuration pragmas used are, in order,
14638 those listed in the file designated by attribute
14639 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14640 project file, if it is specified, and those listed in the file designated by
14641 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14642 the project file of the source, if it exists.
14643
14644 @node Project Files and Main Subprograms
14645 @subsubsection Project Files and Main Subprograms
14646
14647 @noindent
14648 When using a project file, you can invoke @command{gnatmake}
14649 with one or several main subprograms, by specifying their source files on the
14650 command line.
14651
14652 @smallexample
14653 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14654 @end smallexample
14655
14656 @noindent
14657 Each of these needs to be a source file of the same project, except
14658 when the switch ^-u^/UNIQUE^ is used.
14659
14660 @noindent
14661 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14662 same project, one of the project in the tree rooted at the project specified
14663 on the command line. The package @code{Builder} of this common project, the
14664 "main project" is the one that is considered by @command{gnatmake}.
14665
14666 @noindent
14667 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14668 imported directly or indirectly by the project specified on the command line.
14669 Note that if such a source file is not part of the project specified on the
14670 command line, the ^switches^switches^ found in package @code{Builder} of the
14671 project specified on the command line, if any, that are transmitted
14672 to the compiler will still be used, not those found in the project file of
14673 the source file.
14674
14675 @noindent
14676 When using a project file, you can also invoke @command{gnatmake} without
14677 explicitly specifying any main, and the effect depends on whether you have
14678 defined the @code{Main} attribute. This attribute has a string list value,
14679 where each element in the list is the name of a source file (the file
14680 extension is optional) that contains a unit that can be a main subprogram.
14681
14682 If the @code{Main} attribute is defined in a project file as a non-empty
14683 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14684 line, then invoking @command{gnatmake} with this project file but without any
14685 main on the command line is equivalent to invoking @command{gnatmake} with all
14686 the file names in the @code{Main} attribute on the command line.
14687
14688 Example:
14689 @smallexample @c projectfile
14690 @group
14691 project Prj is
14692 for Main use ("main1", "main2", "main3");
14693 end Prj;
14694 @end group
14695 @end smallexample
14696
14697 @noindent
14698 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14699 is equivalent to
14700 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14701
14702 When the project attribute @code{Main} is not specified, or is specified
14703 as an empty string list, or when the switch @option{-u} is used on the command
14704 line, then invoking @command{gnatmake} with no main on the command line will
14705 result in all immediate sources of the project file being checked, and
14706 potentially recompiled. Depending on the presence of the switch @option{-u},
14707 sources from other project files on which the immediate sources of the main
14708 project file depend are also checked and potentially recompiled. In other
14709 words, the @option{-u} switch is applied to all of the immediate sources of the
14710 main project file.
14711
14712 When no main is specified on the command line and attribute @code{Main} exists
14713 and includes several mains, or when several mains are specified on the
14714 command line, the default ^switches^switches^ in package @code{Builder} will
14715 be used for all mains, even if there are specific ^switches^switches^
14716 specified for one or several mains.
14717
14718 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14719 the specific ^switches^switches^ for each main, if they are specified.
14720
14721 @node Library Project Files
14722 @subsubsection Library Project Files
14723
14724 @noindent
14725 When @command{gnatmake} is invoked with a main project file that is a library
14726 project file, it is not allowed to specify one or more mains on the command
14727 line.
14728
14729 @noindent
14730 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14731 ^-l^/ACTION=LINK^ have special meanings.
14732
14733 @itemize @bullet
14734 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14735 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14736 library.
14737
14738 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14739 to @command{gnatmake} that the binder generated file should be compiled
14740 (in the case of a stand-alone library) and that the library should be built.
14741
14742 @end itemize
14743
14744 @node The GNAT Driver and Project Files
14745 @subsection The GNAT Driver and Project Files
14746
14747 @noindent
14748 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14749 can benefit from project files:
14750 @command{^gnatbind^gnatbind^},
14751 @command{^gnatcheck^gnatcheck^}),
14752 @command{^gnatclean^gnatclean^}),
14753 @command{^gnatelim^gnatelim^},
14754 @command{^gnatfind^gnatfind^},
14755 @command{^gnatlink^gnatlink^},
14756 @command{^gnatls^gnatls^},
14757 @command{^gnatmetric^gnatmetric^},
14758 @command{^gnatpp^gnatpp^},
14759 @command{^gnatstub^gnatstub^},
14760 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14761 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14762 They must be invoked through the @command{gnat} driver.
14763
14764 The @command{gnat} driver is a wrapper that accepts a number of commands and
14765 calls the corresponding tool. It was designed initially for VMS platforms (to
14766 convert VMS qualifiers to Unix-style switches), but it is now available on all
14767 GNAT platforms.
14768
14769 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14770 (case insensitive):
14771
14772 @itemize @bullet
14773 @item
14774 BIND to invoke @command{^gnatbind^gnatbind^}
14775 @item
14776 CHOP to invoke @command{^gnatchop^gnatchop^}
14777 @item
14778 CLEAN to invoke @command{^gnatclean^gnatclean^}
14779 @item
14780 COMP or COMPILE to invoke the compiler
14781 @item
14782 ELIM to invoke @command{^gnatelim^gnatelim^}
14783 @item
14784 FIND to invoke @command{^gnatfind^gnatfind^}
14785 @item
14786 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14787 @item
14788 LINK to invoke @command{^gnatlink^gnatlink^}
14789 @item
14790 LS or LIST to invoke @command{^gnatls^gnatls^}
14791 @item
14792 MAKE to invoke @command{^gnatmake^gnatmake^}
14793 @item
14794 NAME to invoke @command{^gnatname^gnatname^}
14795 @item
14796 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14797 @item
14798 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14799 @item
14800 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14801 @item
14802 STUB to invoke @command{^gnatstub^gnatstub^}
14803 @item
14804 XREF to invoke @command{^gnatxref^gnatxref^}
14805 @end itemize
14806
14807 @noindent
14808 (note that the compiler is invoked using the command
14809 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14810
14811 @noindent
14812 On non-VMS platforms, between @command{gnat} and the command, two
14813 special switches may be used:
14814
14815 @itemize @bullet
14816 @item
14817 @command{-v} to display the invocation of the tool.
14818 @item
14819 @command{-dn} to prevent the @command{gnat} driver from removing
14820 the temporary files it has created. These temporary files are
14821 configuration files and temporary file list files.
14822 @end itemize
14823
14824 @noindent
14825 The command may be followed by switches and arguments for the invoked
14826 tool.
14827
14828 @smallexample
14829 gnat bind -C main.ali
14830 gnat ls -a main
14831 gnat chop foo.txt
14832 @end smallexample
14833
14834 @noindent
14835 Switches may also be put in text files, one switch per line, and the text
14836 files may be specified with their path name preceded by '@@'.
14837
14838 @smallexample
14839 gnat bind @@args.txt main.ali
14840 @end smallexample
14841
14842 @noindent
14843 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14844 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14845 (@option{^-P^/PROJECT_FILE^},
14846 @option{^-X^/EXTERNAL_REFERENCE^} and
14847 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14848 the switches of the invoking tool.
14849
14850 @noindent
14851 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14852 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14853 the immediate sources of the specified project file.
14854
14855 @noindent
14856 When GNAT METRIC is used with a project file, but with no source
14857 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14858 with all the immediate sources of the specified project file and with
14859 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14860 of the project.
14861
14862 @noindent
14863 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14864 a project file, no source is specified on the command line and
14865 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14866 the underlying tool (^gnatpp^gnatpp^ or
14867 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14868 not only for the immediate sources of the main project.
14869 @ifclear vms
14870 (-U stands for Universal or Union of the project files of the project tree)
14871 @end ifclear
14872
14873 @noindent
14874 For each of the following commands, there is optionally a corresponding
14875 package in the main project.
14876
14877 @itemize @bullet
14878 @item
14879 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14880
14881 @item
14882 package @code{Check} for command CHECK (invoking
14883 @code{^gnatcheck^gnatcheck^})
14884
14885 @item
14886 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14887
14888 @item
14889 package @code{Cross_Reference} for command XREF (invoking
14890 @code{^gnatxref^gnatxref^})
14891
14892 @item
14893 package @code{Eliminate} for command ELIM (invoking
14894 @code{^gnatelim^gnatelim^})
14895
14896 @item
14897 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14898
14899 @item
14900 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14901
14902 @item
14903 package @code{Gnatstub} for command STUB
14904 (invoking @code{^gnatstub^gnatstub^})
14905
14906 @item
14907 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14908
14909 @item
14910 package @code{Metrics} for command METRIC
14911 (invoking @code{^gnatmetric^gnatmetric^})
14912
14913 @item
14914 package @code{Pretty_Printer} for command PP or PRETTY
14915 (invoking @code{^gnatpp^gnatpp^})
14916
14917 @end itemize
14918
14919 @noindent
14920 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14921 a simple variable with a string list value. It contains ^switches^switches^
14922 for the invocation of @code{^gnatls^gnatls^}.
14923
14924 @smallexample @c projectfile
14925 @group
14926 project Proj1 is
14927 package gnatls is
14928 for ^Switches^Switches^
14929 use ("^-a^-a^",
14930 "^-v^-v^");
14931 end gnatls;
14932 end Proj1;
14933 @end group
14934 @end smallexample
14935
14936 @noindent
14937 All other packages have two attribute @code{^Switches^Switches^} and
14938 @code{^Default_Switches^Default_Switches^}.
14939
14940 @noindent
14941 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14942 source file name, that has a string list value: the ^switches^switches^ to be
14943 used when the tool corresponding to the package is invoked for the specific
14944 source file.
14945
14946 @noindent
14947 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14948 indexed by the programming language that has a string list value.
14949 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14950 ^switches^switches^ for the invocation of the tool corresponding
14951 to the package, except if a specific @code{^Switches^Switches^} attribute
14952 is specified for the source file.
14953
14954 @smallexample @c projectfile
14955 @group
14956 project Proj is
14957
14958 for Source_Dirs use ("./**");
14959
14960 package gnatls is
14961 for ^Switches^Switches^ use
14962 ("^-a^-a^",
14963 "^-v^-v^");
14964 end gnatls;
14965 @end group
14966 @group
14967
14968 package Compiler is
14969 for ^Default_Switches^Default_Switches^ ("Ada")
14970 use ("^-gnatv^-gnatv^",
14971 "^-gnatwa^-gnatwa^");
14972 end Binder;
14973 @end group
14974 @group
14975
14976 package Binder is
14977 for ^Default_Switches^Default_Switches^ ("Ada")
14978 use ("^-C^-C^",
14979 "^-e^-e^");
14980 end Binder;
14981 @end group
14982 @group
14983
14984 package Linker is
14985 for ^Default_Switches^Default_Switches^ ("Ada")
14986 use ("^-C^-C^");
14987 for ^Switches^Switches^ ("main.adb")
14988 use ("^-C^-C^",
14989 "^-v^-v^",
14990 "^-v^-v^");
14991 end Linker;
14992 @end group
14993 @group
14994
14995 package Finder is
14996 for ^Default_Switches^Default_Switches^ ("Ada")
14997 use ("^-a^-a^",
14998 "^-f^-f^");
14999 end Finder;
15000 @end group
15001 @group
15002
15003 package Cross_Reference is
15004 for ^Default_Switches^Default_Switches^ ("Ada")
15005 use ("^-a^-a^",
15006 "^-f^-f^",
15007 "^-d^-d^",
15008 "^-u^-u^");
15009 end Cross_Reference;
15010 end Proj;
15011 @end group
15012 @end smallexample
15013
15014 @noindent
15015 With the above project file, commands such as
15016
15017 @smallexample
15018 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15019 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15020 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15021 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15022 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15023 @end smallexample
15024
15025 @noindent
15026 will set up the environment properly and invoke the tool with the switches
15027 found in the package corresponding to the tool:
15028 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15029 except @code{^Switches^Switches^ ("main.adb")}
15030 for @code{^gnatlink^gnatlink^}.
15031 It is also possible to invoke some of the tools,
15032 @code{^gnatcheck^gnatcheck^}),
15033 @code{^gnatmetric^gnatmetric^}),
15034 and @code{^gnatpp^gnatpp^})
15035 on a set of project units thanks to the combination of the switches
15036 @option{-P}, @option{-U} and possibly the main unit when one is interested
15037 in its closure. For instance,
15038 @smallexample
15039 gnat metric -Pproj
15040 @end smallexample
15041 will compute the metrics for all the immediate units of project
15042 @code{proj}.
15043 @smallexample
15044 gnat metric -Pproj -U
15045 @end smallexample
15046 will compute the metrics for all the units of the closure of projects
15047 rooted at @code{proj}.
15048 @smallexample
15049 gnat metric -Pproj -U main_unit
15050 @end smallexample
15051 will compute the metrics for the closure of units rooted at
15052 @code{main_unit}. This last possibility relies implicitly
15053 on @command{gnatbind}'s option @option{-R}.
15054
15055 @c **********************
15056 @node An Extended Example
15057 @section An Extended Example
15058
15059 @noindent
15060 Suppose that we have two programs, @var{prog1} and @var{prog2},
15061 whose sources are in corresponding directories. We would like
15062 to build them with a single @command{gnatmake} command, and we want to place
15063 their object files into @file{build} subdirectories of the source directories.
15064 Furthermore, we want to have to have two separate subdirectories
15065 in @file{build} -- @file{release} and @file{debug} -- which will contain
15066 the object files compiled with different set of compilation flags.
15067
15068 In other words, we have the following structure:
15069
15070 @smallexample
15071 @group
15072 main
15073 |- prog1
15074 | |- build
15075 | | debug
15076 | | release
15077 |- prog2
15078 |- build
15079 | debug
15080 | release
15081 @end group
15082 @end smallexample
15083
15084 @noindent
15085 Here are the project files that we must place in a directory @file{main}
15086 to maintain this structure:
15087
15088 @enumerate
15089
15090 @item We create a @code{Common} project with a package @code{Compiler} that
15091 specifies the compilation ^switches^switches^:
15092
15093 @smallexample
15094 File "common.gpr":
15095 @group
15096 @b{project} Common @b{is}
15097
15098 @b{for} Source_Dirs @b{use} (); -- No source files
15099 @end group
15100
15101 @group
15102 @b{type} Build_Type @b{is} ("release", "debug");
15103 Build : Build_Type := External ("BUILD", "debug");
15104 @end group
15105 @group
15106 @b{package} Compiler @b{is}
15107 @b{case} Build @b{is}
15108 @b{when} "release" =>
15109 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15110 @b{use} ("^-O2^-O2^");
15111 @b{when} "debug" =>
15112 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15113 @b{use} ("^-g^-g^");
15114 @b{end case};
15115 @b{end} Compiler;
15116
15117 @b{end} Common;
15118 @end group
15119 @end smallexample
15120
15121 @item We create separate projects for the two programs:
15122
15123 @smallexample
15124 @group
15125 File "prog1.gpr":
15126
15127 @b{with} "common";
15128 @b{project} Prog1 @b{is}
15129
15130 @b{for} Source_Dirs @b{use} ("prog1");
15131 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
15132
15133 @b{package} Compiler @b{renames} Common.Compiler;
15134
15135 @b{end} Prog1;
15136 @end group
15137 @end smallexample
15138
15139 @smallexample
15140 @group
15141 File "prog2.gpr":
15142
15143 @b{with} "common";
15144 @b{project} Prog2 @b{is}
15145
15146 @b{for} Source_Dirs @b{use} ("prog2");
15147 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
15148
15149 @b{package} Compiler @b{renames} Common.Compiler;
15150
15151 @end group
15152 @b{end} Prog2;
15153 @end smallexample
15154
15155 @item We create a wrapping project @code{Main}:
15156
15157 @smallexample
15158 @group
15159 File "main.gpr":
15160
15161 @b{with} "common";
15162 @b{with} "prog1";
15163 @b{with} "prog2";
15164 @b{project} Main @b{is}
15165
15166 @b{package} Compiler @b{renames} Common.Compiler;
15167
15168 @b{end} Main;
15169 @end group
15170 @end smallexample
15171
15172 @item Finally we need to create a dummy procedure that @code{with}s (either
15173 explicitly or implicitly) all the sources of our two programs.
15174
15175 @end enumerate
15176
15177 @noindent
15178 Now we can build the programs using the command
15179
15180 @smallexample
15181 gnatmake ^-P^/PROJECT_FILE=^main dummy
15182 @end smallexample
15183
15184 @noindent
15185 for the Debug mode, or
15186
15187 @ifclear vms
15188 @smallexample
15189 gnatmake -Pmain -XBUILD=release
15190 @end smallexample
15191 @end ifclear
15192
15193 @ifset vms
15194 @smallexample
15195 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15196 @end smallexample
15197 @end ifset
15198
15199 @noindent
15200 for the Release mode.
15201
15202 @c ********************************
15203 @c * Project File Complete Syntax *
15204 @c ********************************
15205
15206 @node Project File Complete Syntax
15207 @section Project File Complete Syntax
15208
15209 @smallexample
15210 project ::=
15211 context_clause project_declaration
15212
15213 context_clause ::=
15214 @{with_clause@}
15215
15216 with_clause ::=
15217 @b{with} path_name @{ , path_name @} ;
15218
15219 path_name ::=
15220 string_literal
15221
15222 project_declaration ::=
15223 simple_project_declaration | project_extension
15224
15225 simple_project_declaration ::=
15226 @b{project} <project_>simple_name @b{is}
15227 @{declarative_item@}
15228 @b{end} <project_>simple_name;
15229
15230 project_extension ::=
15231 @b{project} <project_>simple_name @b{extends} path_name @b{is}
15232 @{declarative_item@}
15233 @b{end} <project_>simple_name;
15234
15235 declarative_item ::=
15236 package_declaration |
15237 typed_string_declaration |
15238 other_declarative_item
15239
15240 package_declaration ::=
15241 package_spec | package_renaming
15242
15243 package_spec ::=
15244 @b{package} package_identifier @b{is}
15245 @{simple_declarative_item@}
15246 @b{end} package_identifier ;
15247
15248 package_identifier ::=
15249 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15250 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
15251 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
15252
15253 package_renaming ::==
15254 @b{package} package_identifier @b{renames}
15255 <project_>simple_name.package_identifier ;
15256
15257 typed_string_declaration ::=
15258 @b{type} <typed_string_>_simple_name @b{is}
15259 ( string_literal @{, string_literal@} );
15260
15261 other_declarative_item ::=
15262 attribute_declaration |
15263 typed_variable_declaration |
15264 variable_declaration |
15265 case_construction
15266
15267 attribute_declaration ::=
15268 full_associative_array_declaration |
15269 @b{for} attribute_designator @b{use} expression ;
15270
15271 full_associative_array_declaration ::=
15272 @b{for} <associative_array_attribute_>simple_name @b{use}
15273 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15274
15275 attribute_designator ::=
15276 <simple_attribute_>simple_name |
15277 <associative_array_attribute_>simple_name ( string_literal )
15278
15279 typed_variable_declaration ::=
15280 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
15281
15282 variable_declaration ::=
15283 <variable_>simple_name := expression;
15284
15285 expression ::=
15286 term @{& term@}
15287
15288 term ::=
15289 literal_string |
15290 string_list |
15291 <variable_>name |
15292 external_value |
15293 attribute_reference
15294
15295 string_literal ::=
15296 (same as Ada)
15297
15298 string_list ::=
15299 ( <string_>expression @{ , <string_>expression @} )
15300
15301 external_value ::=
15302 @b{external} ( string_literal [, string_literal] )
15303
15304 attribute_reference ::=
15305 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15306
15307 attribute_prefix ::=
15308 @b{project} |
15309 <project_>simple_name | package_identifier |
15310 <project_>simple_name . package_identifier
15311
15312 case_construction ::=
15313 @b{case} <typed_variable_>name @b{is}
15314 @{case_item@}
15315 @b{end case} ;
15316
15317 case_item ::=
15318 @b{when} discrete_choice_list =>
15319 @{case_construction | attribute_declaration@}
15320
15321 discrete_choice_list ::=
15322 string_literal @{| string_literal@} |
15323 @b{others}
15324
15325 name ::=
15326 simple_name @{. simple_name@}
15327
15328 simple_name ::=
15329 identifier (same as Ada)
15330
15331 @end smallexample
15332
15333 @node The Cross-Referencing Tools gnatxref and gnatfind
15334 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15335 @findex gnatxref
15336 @findex gnatfind
15337
15338 @noindent
15339 The compiler generates cross-referencing information (unless
15340 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15341 This information indicates where in the source each entity is declared and
15342 referenced. Note that entities in package Standard are not included, but
15343 entities in all other predefined units are included in the output.
15344
15345 Before using any of these two tools, you need to compile successfully your
15346 application, so that GNAT gets a chance to generate the cross-referencing
15347 information.
15348
15349 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15350 information to provide the user with the capability to easily locate the
15351 declaration and references to an entity. These tools are quite similar,
15352 the difference being that @code{gnatfind} is intended for locating
15353 definitions and/or references to a specified entity or entities, whereas
15354 @code{gnatxref} is oriented to generating a full report of all
15355 cross-references.
15356
15357 To use these tools, you must not compile your application using the
15358 @option{-gnatx} switch on the @command{gnatmake} command line
15359 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15360 information will not be generated.
15361
15362 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15363 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15364
15365 @menu
15366 * gnatxref Switches::
15367 * gnatfind Switches::
15368 * Project Files for gnatxref and gnatfind::
15369 * Regular Expressions in gnatfind and gnatxref::
15370 * Examples of gnatxref Usage::
15371 * Examples of gnatfind Usage::
15372 @end menu
15373
15374 @node gnatxref Switches
15375 @section @code{gnatxref} Switches
15376
15377 @noindent
15378 The command invocation for @code{gnatxref} is:
15379 @smallexample
15380 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15381 @end smallexample
15382
15383 @noindent
15384 where
15385
15386 @table @var
15387 @item sourcefile1
15388 @itemx sourcefile2
15389 identifies the source files for which a report is to be generated. The
15390 ``with''ed units will be processed too. You must provide at least one file.
15391
15392 These file names are considered to be regular expressions, so for instance
15393 specifying @file{source*.adb} is the same as giving every file in the current
15394 directory whose name starts with @file{source} and whose extension is
15395 @file{adb}.
15396
15397 You shouldn't specify any directory name, just base names. @command{gnatxref}
15398 and @command{gnatfind} will be able to locate these files by themselves using
15399 the source path. If you specify directories, no result is produced.
15400
15401 @end table
15402
15403 @noindent
15404 The switches can be:
15405 @table @option
15406 @c !sort!
15407 @item --version
15408 @cindex @option{--version} @command{gnatxref}
15409 Display Copyright and version, then exit disregarding all other options.
15410
15411 @item --help
15412 @cindex @option{--help} @command{gnatxref}
15413 If @option{--version} was not used, display usage, then exit disregarding
15414 all other options.
15415
15416 @item ^-a^/ALL_FILES^
15417 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15418 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15419 the read-only files found in the library search path. Otherwise, these files
15420 will be ignored. This option can be used to protect Gnat sources or your own
15421 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15422 much faster, and their output much smaller. Read-only here refers to access
15423 or permissions status in the file system for the current user.
15424
15425 @item -aIDIR
15426 @cindex @option{-aIDIR} (@command{gnatxref})
15427 When looking for source files also look in directory DIR. The order in which
15428 source file search is undertaken is the same as for @command{gnatmake}.
15429
15430 @item -aODIR
15431 @cindex @option{-aODIR} (@command{gnatxref})
15432 When searching for library and object files, look in directory
15433 DIR. The order in which library files are searched is the same as for
15434 @command{gnatmake}.
15435
15436 @item -nostdinc
15437 @cindex @option{-nostdinc} (@command{gnatxref})
15438 Do not look for sources in the system default directory.
15439
15440 @item -nostdlib
15441 @cindex @option{-nostdlib} (@command{gnatxref})
15442 Do not look for library files in the system default directory.
15443
15444 @item --RTS=@var{rts-path}
15445 @cindex @option{--RTS} (@command{gnatxref})
15446 Specifies the default location of the runtime library. Same meaning as the
15447 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15448
15449 @item ^-d^/DERIVED_TYPES^
15450 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15451 If this switch is set @code{gnatxref} will output the parent type
15452 reference for each matching derived types.
15453
15454 @item ^-f^/FULL_PATHNAME^
15455 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15456 If this switch is set, the output file names will be preceded by their
15457 directory (if the file was found in the search path). If this switch is
15458 not set, the directory will not be printed.
15459
15460 @item ^-g^/IGNORE_LOCALS^
15461 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15462 If this switch is set, information is output only for library-level
15463 entities, ignoring local entities. The use of this switch may accelerate
15464 @code{gnatfind} and @code{gnatxref}.
15465
15466 @item -IDIR
15467 @cindex @option{-IDIR} (@command{gnatxref})
15468 Equivalent to @samp{-aODIR -aIDIR}.
15469
15470 @item -pFILE
15471 @cindex @option{-pFILE} (@command{gnatxref})
15472 Specify a project file to use @xref{Project Files}.
15473 If you need to use the @file{.gpr}
15474 project files, you should use gnatxref through the GNAT driver
15475 (@command{gnat xref -Pproject}).
15476
15477 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15478 project file in the current directory.
15479
15480 If a project file is either specified or found by the tools, then the content
15481 of the source directory and object directory lines are added as if they
15482 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15483 and @samp{^-aO^OBJECT_SEARCH^}.
15484 @item ^-u^/UNUSED^
15485 Output only unused symbols. This may be really useful if you give your
15486 main compilation unit on the command line, as @code{gnatxref} will then
15487 display every unused entity and 'with'ed package.
15488
15489 @ifclear vms
15490 @item -v
15491 Instead of producing the default output, @code{gnatxref} will generate a
15492 @file{tags} file that can be used by vi. For examples how to use this
15493 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15494 to the standard output, thus you will have to redirect it to a file.
15495 @end ifclear
15496
15497 @end table
15498
15499 @noindent
15500 All these switches may be in any order on the command line, and may even
15501 appear after the file names. They need not be separated by spaces, thus
15502 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15503 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15504
15505 @node gnatfind Switches
15506 @section @code{gnatfind} Switches
15507
15508 @noindent
15509 The command line for @code{gnatfind} is:
15510
15511 @smallexample
15512 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15513 @r{[}@var{file1} @var{file2} @dots{}]
15514 @end smallexample
15515
15516 @noindent
15517 where
15518
15519 @table @var
15520 @item pattern
15521 An entity will be output only if it matches the regular expression found
15522 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15523
15524 Omitting the pattern is equivalent to specifying @samp{*}, which
15525 will match any entity. Note that if you do not provide a pattern, you
15526 have to provide both a sourcefile and a line.
15527
15528 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15529 for matching purposes. At the current time there is no support for
15530 8-bit codes other than Latin-1, or for wide characters in identifiers.
15531
15532 @item sourcefile
15533 @code{gnatfind} will look for references, bodies or declarations
15534 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15535 and column @var{column}. See @ref{Examples of gnatfind Usage}
15536 for syntax examples.
15537
15538 @item line
15539 is a decimal integer identifying the line number containing
15540 the reference to the entity (or entities) to be located.
15541
15542 @item column
15543 is a decimal integer identifying the exact location on the
15544 line of the first character of the identifier for the
15545 entity reference. Columns are numbered from 1.
15546
15547 @item file1 file2 @dots{}
15548 The search will be restricted to these source files. If none are given, then
15549 the search will be done for every library file in the search path.
15550 These file must appear only after the pattern or sourcefile.
15551
15552 These file names are considered to be regular expressions, so for instance
15553 specifying @file{source*.adb} is the same as giving every file in the current
15554 directory whose name starts with @file{source} and whose extension is
15555 @file{adb}.
15556
15557 The location of the spec of the entity will always be displayed, even if it
15558 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
15559 occurrences of the entity in the separate units of the ones given on the
15560 command line will also be displayed.
15561
15562 Note that if you specify at least one file in this part, @code{gnatfind} may
15563 sometimes not be able to find the body of the subprograms.
15564
15565 @end table
15566
15567 @noindent
15568 At least one of 'sourcefile' or 'pattern' has to be present on
15569 the command line.
15570
15571 The following switches are available:
15572 @table @option
15573 @c !sort!
15574
15575 @cindex @option{--version} @command{gnatfind}
15576 Display Copyright and version, then exit disregarding all other options.
15577
15578 @item --help
15579 @cindex @option{--help} @command{gnatfind}
15580 If @option{--version} was not used, display usage, then exit disregarding
15581 all other options.
15582
15583 @item ^-a^/ALL_FILES^
15584 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15585 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15586 the read-only files found in the library search path. Otherwise, these files
15587 will be ignored. This option can be used to protect Gnat sources or your own
15588 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15589 much faster, and their output much smaller. Read-only here refers to access
15590 or permission status in the file system for the current user.
15591
15592 @item -aIDIR
15593 @cindex @option{-aIDIR} (@command{gnatfind})
15594 When looking for source files also look in directory DIR. The order in which
15595 source file search is undertaken is the same as for @command{gnatmake}.
15596
15597 @item -aODIR
15598 @cindex @option{-aODIR} (@command{gnatfind})
15599 When searching for library and object files, look in directory
15600 DIR. The order in which library files are searched is the same as for
15601 @command{gnatmake}.
15602
15603 @item -nostdinc
15604 @cindex @option{-nostdinc} (@command{gnatfind})
15605 Do not look for sources in the system default directory.
15606
15607 @item -nostdlib
15608 @cindex @option{-nostdlib} (@command{gnatfind})
15609 Do not look for library files in the system default directory.
15610
15611 @item --ext=@var{extension}
15612 @cindex @option{--ext} (@command{gnatfind})
15613 Specify an alternate ali file extension. The default is @code{ali} and other
15614 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15615 switch. Note that if this switch overrides the default, which means that only
15616 the new extension will be considered.
15617
15618 @item --RTS=@var{rts-path}
15619 @cindex @option{--RTS} (@command{gnatfind})
15620 Specifies the default location of the runtime library. Same meaning as the
15621 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15622
15623 @item ^-d^/DERIVED_TYPE_INFORMATION^
15624 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15625 If this switch is set, then @code{gnatfind} will output the parent type
15626 reference for each matching derived types.
15627
15628 @item ^-e^/EXPRESSIONS^
15629 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15630 By default, @code{gnatfind} accept the simple regular expression set for
15631 @samp{pattern}. If this switch is set, then the pattern will be
15632 considered as full Unix-style regular expression.
15633
15634 @item ^-f^/FULL_PATHNAME^
15635 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15636 If this switch is set, the output file names will be preceded by their
15637 directory (if the file was found in the search path). If this switch is
15638 not set, the directory will not be printed.
15639
15640 @item ^-g^/IGNORE_LOCALS^
15641 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15642 If this switch is set, information is output only for library-level
15643 entities, ignoring local entities. The use of this switch may accelerate
15644 @code{gnatfind} and @code{gnatxref}.
15645
15646 @item -IDIR
15647 @cindex @option{-IDIR} (@command{gnatfind})
15648 Equivalent to @samp{-aODIR -aIDIR}.
15649
15650 @item -pFILE
15651 @cindex @option{-pFILE} (@command{gnatfind})
15652 Specify a project file (@pxref{Project Files}) to use.
15653 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15654 project file in the current directory.
15655
15656 If a project file is either specified or found by the tools, then the content
15657 of the source directory and object directory lines are added as if they
15658 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15659 @samp{^-aO^/OBJECT_SEARCH^}.
15660
15661 @item ^-r^/REFERENCES^
15662 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15663 By default, @code{gnatfind} will output only the information about the
15664 declaration, body or type completion of the entities. If this switch is
15665 set, the @code{gnatfind} will locate every reference to the entities in
15666 the files specified on the command line (or in every file in the search
15667 path if no file is given on the command line).
15668
15669 @item ^-s^/PRINT_LINES^
15670 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15671 If this switch is set, then @code{gnatfind} will output the content
15672 of the Ada source file lines were the entity was found.
15673
15674 @item ^-t^/TYPE_HIERARCHY^
15675 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15676 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15677 the specified type. It act like -d option but recursively from parent
15678 type to parent type. When this switch is set it is not possible to
15679 specify more than one file.
15680
15681 @end table
15682
15683 @noindent
15684 All these switches may be in any order on the command line, and may even
15685 appear after the file names. They need not be separated by spaces, thus
15686 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15687 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15688
15689 As stated previously, gnatfind will search in every directory in the
15690 search path. You can force it to look only in the current directory if
15691 you specify @code{*} at the end of the command line.
15692
15693 @node Project Files for gnatxref and gnatfind
15694 @section Project Files for @command{gnatxref} and @command{gnatfind}
15695
15696 @noindent
15697 Project files allow a programmer to specify how to compile its
15698 application, where to find sources, etc. These files are used
15699 @ifclear vms
15700 primarily by GPS, but they can also be used
15701 @end ifclear
15702 by the two tools
15703 @code{gnatxref} and @code{gnatfind}.
15704
15705 A project file name must end with @file{.gpr}. If a single one is
15706 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15707 extract the information from it. If multiple project files are found, none of
15708 them is read, and you have to use the @samp{-p} switch to specify the one
15709 you want to use.
15710
15711 The following lines can be included, even though most of them have default
15712 values which can be used in most cases.
15713 The lines can be entered in any order in the file.
15714 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15715 each line. If you have multiple instances, only the last one is taken into
15716 account.
15717
15718 @table @code
15719 @item src_dir=DIR
15720 [default: @code{"^./^[]^"}]
15721 specifies a directory where to look for source files. Multiple @code{src_dir}
15722 lines can be specified and they will be searched in the order they
15723 are specified.
15724
15725 @item obj_dir=DIR
15726 [default: @code{"^./^[]^"}]
15727 specifies a directory where to look for object and library files. Multiple
15728 @code{obj_dir} lines can be specified, and they will be searched in the order
15729 they are specified
15730
15731 @item comp_opt=SWITCHES
15732 [default: @code{""}]
15733 creates a variable which can be referred to subsequently by using
15734 the @code{$@{comp_opt@}} notation. This is intended to store the default
15735 switches given to @command{gnatmake} and @command{gcc}.
15736
15737 @item bind_opt=SWITCHES
15738 [default: @code{""}]
15739 creates a variable which can be referred to subsequently by using
15740 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15741 switches given to @command{gnatbind}.
15742
15743 @item link_opt=SWITCHES
15744 [default: @code{""}]
15745 creates a variable which can be referred to subsequently by using
15746 the @samp{$@{link_opt@}} notation. This is intended to store the default
15747 switches given to @command{gnatlink}.
15748
15749 @item main=EXECUTABLE
15750 [default: @code{""}]
15751 specifies the name of the executable for the application. This variable can
15752 be referred to in the following lines by using the @samp{$@{main@}} notation.
15753
15754 @ifset vms
15755 @item comp_cmd=COMMAND
15756 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15757 @end ifset
15758 @ifclear vms
15759 @item comp_cmd=COMMAND
15760 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15761 @end ifclear
15762 specifies the command used to compile a single file in the application.
15763
15764 @ifset vms
15765 @item make_cmd=COMMAND
15766 [default: @code{"GNAT MAKE $@{main@}
15767 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15768 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15769 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15770 @end ifset
15771 @ifclear vms
15772 @item make_cmd=COMMAND
15773 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15774 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15775 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15776 @end ifclear
15777 specifies the command used to recompile the whole application.
15778
15779 @item run_cmd=COMMAND
15780 [default: @code{"$@{main@}"}]
15781 specifies the command used to run the application.
15782
15783 @item debug_cmd=COMMAND
15784 [default: @code{"gdb $@{main@}"}]
15785 specifies the command used to debug the application
15786
15787 @end table
15788
15789 @noindent
15790 @command{gnatxref} and @command{gnatfind} only take into account the
15791 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15792
15793 @node Regular Expressions in gnatfind and gnatxref
15794 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15795
15796 @noindent
15797 As specified in the section about @command{gnatfind}, the pattern can be a
15798 regular expression. Actually, there are to set of regular expressions
15799 which are recognized by the program:
15800
15801 @table @code
15802 @item globbing patterns
15803 These are the most usual regular expression. They are the same that you
15804 generally used in a Unix shell command line, or in a DOS session.
15805
15806 Here is a more formal grammar:
15807 @smallexample
15808 @group
15809 @iftex
15810 @leftskip=.5cm
15811 @end iftex
15812 regexp ::= term
15813 term ::= elmt -- matches elmt
15814 term ::= elmt elmt -- concatenation (elmt then elmt)
15815 term ::= * -- any string of 0 or more characters
15816 term ::= ? -- matches any character
15817 term ::= [char @{char@}] -- matches any character listed
15818 term ::= [char - char] -- matches any character in range
15819 @end group
15820 @end smallexample
15821
15822 @item full regular expression
15823 The second set of regular expressions is much more powerful. This is the
15824 type of regular expressions recognized by utilities such a @file{grep}.
15825
15826 The following is the form of a regular expression, expressed in Ada
15827 reference manual style BNF is as follows
15828
15829 @smallexample
15830 @iftex
15831 @leftskip=.5cm
15832 @end iftex
15833 @group
15834 regexp ::= term @{| term@} -- alternation (term or term @dots{})
15835
15836 term ::= item @{item@} -- concatenation (item then item)
15837
15838 item ::= elmt -- match elmt
15839 item ::= elmt * -- zero or more elmt's
15840 item ::= elmt + -- one or more elmt's
15841 item ::= elmt ? -- matches elmt or nothing
15842 @end group
15843 @group
15844 elmt ::= nschar -- matches given character
15845 elmt ::= [nschar @{nschar@}] -- matches any character listed
15846 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15847 elmt ::= [char - char] -- matches chars in given range
15848 elmt ::= \ char -- matches given character
15849 elmt ::= . -- matches any single character
15850 elmt ::= ( regexp ) -- parens used for grouping
15851
15852 char ::= any character, including special characters
15853 nschar ::= any character except ()[].*+?^^^
15854 @end group
15855 @end smallexample
15856
15857 Following are a few examples:
15858
15859 @table @samp
15860 @item abcde|fghi
15861 will match any of the two strings @samp{abcde} and @samp{fghi},
15862
15863 @item abc*d
15864 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15865 @samp{abcccd}, and so on,
15866
15867 @item [a-z]+
15868 will match any string which has only lowercase characters in it (and at
15869 least one character.
15870
15871 @end table
15872 @end table
15873
15874 @node Examples of gnatxref Usage
15875 @section Examples of @code{gnatxref} Usage
15876
15877 @subsection General Usage
15878
15879 @noindent
15880 For the following examples, we will consider the following units:
15881
15882 @smallexample @c ada
15883 @group
15884 @cartouche
15885 main.ads:
15886 1: with Bar;
15887 2: package Main is
15888 3: procedure Foo (B : in Integer);
15889 4: C : Integer;
15890 5: private
15891 6: D : Integer;
15892 7: end Main;
15893
15894 main.adb:
15895 1: package body Main is
15896 2: procedure Foo (B : in Integer) is
15897 3: begin
15898 4: C := B;
15899 5: D := B;
15900 6: Bar.Print (B);
15901 7: Bar.Print (C);
15902 8: end Foo;
15903 9: end Main;
15904
15905 bar.ads:
15906 1: package Bar is
15907 2: procedure Print (B : Integer);
15908 3: end bar;
15909 @end cartouche
15910 @end group
15911 @end smallexample
15912
15913 @table @code
15914
15915 @noindent
15916 The first thing to do is to recompile your application (for instance, in
15917 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15918 the cross-referencing information.
15919 You can then issue any of the following commands:
15920
15921 @item gnatxref main.adb
15922 @code{gnatxref} generates cross-reference information for main.adb
15923 and every unit 'with'ed by main.adb.
15924
15925 The output would be:
15926 @smallexample
15927 @iftex
15928 @leftskip=0cm
15929 @end iftex
15930 B Type: Integer
15931 Decl: bar.ads 2:22
15932 B Type: Integer
15933 Decl: main.ads 3:20
15934 Body: main.adb 2:20
15935 Ref: main.adb 4:13 5:13 6:19
15936 Bar Type: Unit
15937 Decl: bar.ads 1:9
15938 Ref: main.adb 6:8 7:8
15939 main.ads 1:6
15940 C Type: Integer
15941 Decl: main.ads 4:5
15942 Modi: main.adb 4:8
15943 Ref: main.adb 7:19
15944 D Type: Integer
15945 Decl: main.ads 6:5
15946 Modi: main.adb 5:8
15947 Foo Type: Unit
15948 Decl: main.ads 3:15
15949 Body: main.adb 2:15
15950 Main Type: Unit
15951 Decl: main.ads 2:9
15952 Body: main.adb 1:14
15953 Print Type: Unit
15954 Decl: bar.ads 2:15
15955 Ref: main.adb 6:12 7:12
15956 @end smallexample
15957
15958 @noindent
15959 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15960 its body is in main.adb, line 1, column 14 and is not referenced any where.
15961
15962 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15963 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15964
15965 @item gnatxref package1.adb package2.ads
15966 @code{gnatxref} will generates cross-reference information for
15967 package1.adb, package2.ads and any other package 'with'ed by any
15968 of these.
15969
15970 @end table
15971
15972 @ifclear vms
15973 @subsection Using gnatxref with vi
15974
15975 @code{gnatxref} can generate a tags file output, which can be used
15976 directly from @command{vi}. Note that the standard version of @command{vi}
15977 will not work properly with overloaded symbols. Consider using another
15978 free implementation of @command{vi}, such as @command{vim}.
15979
15980 @smallexample
15981 $ gnatxref -v gnatfind.adb > tags
15982 @end smallexample
15983
15984 @noindent
15985 will generate the tags file for @code{gnatfind} itself (if the sources
15986 are in the search path!).
15987
15988 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15989 (replacing @var{entity} by whatever you are looking for), and vi will
15990 display a new file with the corresponding declaration of entity.
15991 @end ifclear
15992
15993 @node Examples of gnatfind Usage
15994 @section Examples of @code{gnatfind} Usage
15995
15996 @table @code
15997
15998 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15999 Find declarations for all entities xyz referenced at least once in
16000 main.adb. The references are search in every library file in the search
16001 path.
16002
16003 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16004 switch is set)
16005
16006 The output will look like:
16007 @smallexample
16008 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16009 ^directory/^[directory]^main.adb:24:10: xyz <= body
16010 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16011 @end smallexample
16012
16013 @noindent
16014 that is to say, one of the entities xyz found in main.adb is declared at
16015 line 12 of main.ads (and its body is in main.adb), and another one is
16016 declared at line 45 of foo.ads
16017
16018 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16019 This is the same command as the previous one, instead @code{gnatfind} will
16020 display the content of the Ada source file lines.
16021
16022 The output will look like:
16023
16024 @smallexample
16025 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16026 procedure xyz;
16027 ^directory/^[directory]^main.adb:24:10: xyz <= body
16028 procedure xyz is
16029 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16030 xyz : Integer;
16031 @end smallexample
16032
16033 @noindent
16034 This can make it easier to find exactly the location your are looking
16035 for.
16036
16037 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16038 Find references to all entities containing an x that are
16039 referenced on line 123 of main.ads.
16040 The references will be searched only in main.ads and foo.adb.
16041
16042 @item gnatfind main.ads:123
16043 Find declarations and bodies for all entities that are referenced on
16044 line 123 of main.ads.
16045
16046 This is the same as @code{gnatfind "*":main.adb:123}.
16047
16048 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16049 Find the declaration for the entity referenced at column 45 in
16050 line 123 of file main.adb in directory mydir. Note that it
16051 is usual to omit the identifier name when the column is given,
16052 since the column position identifies a unique reference.
16053
16054 The column has to be the beginning of the identifier, and should not
16055 point to any character in the middle of the identifier.
16056
16057 @end table
16058
16059 @c *********************************
16060 @node The GNAT Pretty-Printer gnatpp
16061 @chapter The GNAT Pretty-Printer @command{gnatpp}
16062 @findex gnatpp
16063 @cindex Pretty-Printer
16064
16065 @noindent
16066 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16067 for source reformatting / pretty-printing.
16068 It takes an Ada source file as input and generates a reformatted
16069 version as output.
16070 You can specify various style directives via switches; e.g.,
16071 identifier case conventions, rules of indentation, and comment layout.
16072
16073 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16074 tree for the input source and thus requires the input to be syntactically and
16075 semantically legal.
16076 If this condition is not met, @command{gnatpp} will terminate with an
16077 error message; no output file will be generated.
16078
16079 If the source files presented to @command{gnatpp} contain
16080 preprocessing directives, then the output file will
16081 correspond to the generated source after all
16082 preprocessing is carried out. There is no way
16083 using @command{gnatpp} to obtain pretty printed files that
16084 include the preprocessing directives.
16085
16086 If the compilation unit
16087 contained in the input source depends semantically upon units located
16088 outside the current directory, you have to provide the source search path
16089 when invoking @command{gnatpp}, if these units are contained in files with
16090 names that do not follow the GNAT file naming rules, you have to provide
16091 the configuration file describing the corresponding naming scheme;
16092 see the description of the @command{gnatpp}
16093 switches below. Another possibility is to use a project file and to
16094 call @command{gnatpp} through the @command{gnat} driver
16095
16096 The @command{gnatpp} command has the form
16097
16098 @smallexample
16099 $ gnatpp @ovar{switches} @var{filename}
16100 @end smallexample
16101
16102 @noindent
16103 where
16104 @itemize @bullet
16105 @item
16106 @var{switches} is an optional sequence of switches defining such properties as
16107 the formatting rules, the source search path, and the destination for the
16108 output source file
16109
16110 @item
16111 @var{filename} is the name (including the extension) of the source file to
16112 reformat; ``wildcards'' or several file names on the same gnatpp command are
16113 allowed. The file name may contain path information; it does not have to
16114 follow the GNAT file naming rules
16115 @end itemize
16116
16117 @menu
16118 * Switches for gnatpp::
16119 * Formatting Rules::
16120 @end menu
16121
16122 @node Switches for gnatpp
16123 @section Switches for @command{gnatpp}
16124
16125 @noindent
16126 The following subsections describe the various switches accepted by
16127 @command{gnatpp}, organized by category.
16128
16129 @ifclear vms
16130 You specify a switch by supplying a name and generally also a value.
16131 In many cases the values for a switch with a given name are incompatible with
16132 each other
16133 (for example the switch that controls the casing of a reserved word may have
16134 exactly one value: upper case, lower case, or
16135 mixed case) and thus exactly one such switch can be in effect for an
16136 invocation of @command{gnatpp}.
16137 If more than one is supplied, the last one is used.
16138 However, some values for the same switch are mutually compatible.
16139 You may supply several such switches to @command{gnatpp}, but then
16140 each must be specified in full, with both the name and the value.
16141 Abbreviated forms (the name appearing once, followed by each value) are
16142 not permitted.
16143 For example, to set
16144 the alignment of the assignment delimiter both in declarations and in
16145 assignment statements, you must write @option{-A2A3}
16146 (or @option{-A2 -A3}), but not @option{-A23}.
16147 @end ifclear
16148
16149 @ifset vms
16150 In many cases the set of options for a given qualifier are incompatible with
16151 each other (for example the qualifier that controls the casing of a reserved
16152 word may have exactly one option, which specifies either upper case, lower
16153 case, or mixed case), and thus exactly one such option can be in effect for
16154 an invocation of @command{gnatpp}.
16155 If more than one is supplied, the last one is used.
16156 However, some qualifiers have options that are mutually compatible,
16157 and then you may then supply several such options when invoking
16158 @command{gnatpp}.
16159 @end ifset
16160
16161 In most cases, it is obvious whether or not the
16162 ^values for a switch with a given name^options for a given qualifier^
16163 are compatible with each other.
16164 When the semantics might not be evident, the summaries below explicitly
16165 indicate the effect.
16166
16167 @menu
16168 * Alignment Control::
16169 * Casing Control::
16170 * Construct Layout Control::
16171 * General Text Layout Control::
16172 * Other Formatting Options::
16173 * Setting the Source Search Path::
16174 * Output File Control::
16175 * Other gnatpp Switches::
16176 @end menu
16177
16178 @node Alignment Control
16179 @subsection Alignment Control
16180 @cindex Alignment control in @command{gnatpp}
16181
16182 @noindent
16183 Programs can be easier to read if certain constructs are vertically aligned.
16184 By default all alignments are set ON.
16185 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16186 OFF, and then use one or more of the other
16187 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16188 to activate alignment for specific constructs.
16189
16190 @table @option
16191 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16192
16193 @ifset vms
16194 @item /ALIGN=ON
16195 Set all alignments to ON
16196 @end ifset
16197
16198 @item ^-A0^/ALIGN=OFF^
16199 Set all alignments to OFF
16200
16201 @item ^-A1^/ALIGN=COLONS^
16202 Align @code{:} in declarations
16203
16204 @item ^-A2^/ALIGN=DECLARATIONS^
16205 Align @code{:=} in initializations in declarations
16206
16207 @item ^-A3^/ALIGN=STATEMENTS^
16208 Align @code{:=} in assignment statements
16209
16210 @item ^-A4^/ALIGN=ARROWS^
16211 Align @code{=>} in associations
16212
16213 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16214 Align @code{at} keywords in the component clauses in record
16215 representation clauses
16216 @end table
16217
16218 @noindent
16219 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16220 is allowed.
16221
16222 @node Casing Control
16223 @subsection Casing Control
16224 @cindex Casing control in @command{gnatpp}
16225
16226 @noindent
16227 @command{gnatpp} allows you to specify the casing for reserved words,
16228 pragma names, attribute designators and identifiers.
16229 For identifiers you may define a
16230 general rule for name casing but also override this rule
16231 via a set of dictionary files.
16232
16233 Three types of casing are supported: lower case, upper case, and mixed case.
16234 Lower and upper case are self-explanatory (but since some letters in
16235 Latin1 and other GNAT-supported character sets
16236 exist only in lower-case form, an upper case conversion will have no
16237 effect on them.)
16238 ``Mixed case'' means that the first letter, and also each letter immediately
16239 following an underscore, are converted to their uppercase forms;
16240 all the other letters are converted to their lowercase forms.
16241
16242 @table @option
16243 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16244 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16245 Attribute designators are lower case
16246
16247 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16248 Attribute designators are upper case
16249
16250 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16251 Attribute designators are mixed case (this is the default)
16252
16253 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16254 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16255 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16256 lower case (this is the default)
16257
16258 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16259 Keywords are upper case
16260
16261 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16262 @item ^-nD^/NAME_CASING=AS_DECLARED^
16263 Name casing for defining occurrences are as they appear in the source file
16264 (this is the default)
16265
16266 @item ^-nU^/NAME_CASING=UPPER_CASE^
16267 Names are in upper case
16268
16269 @item ^-nL^/NAME_CASING=LOWER_CASE^
16270 Names are in lower case
16271
16272 @item ^-nM^/NAME_CASING=MIXED_CASE^
16273 Names are in mixed case
16274
16275 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16276 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16277 Pragma names are lower case
16278
16279 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16280 Pragma names are upper case
16281
16282 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16283 Pragma names are mixed case (this is the default)
16284
16285 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16286 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16287 Use @var{file} as a @emph{dictionary file} that defines
16288 the casing for a set of specified names,
16289 thereby overriding the effect on these names by
16290 any explicit or implicit
16291 ^-n^/NAME_CASING^ switch.
16292 To supply more than one dictionary file,
16293 use ^several @option{-D} switches^a list of files as options^.
16294
16295 @noindent
16296 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16297 to define the casing for the Ada predefined names and
16298 the names declared in the GNAT libraries.
16299
16300 @item ^-D-^/SPECIFIC_CASING^
16301 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16302 Do not use the default dictionary file;
16303 instead, use the casing
16304 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16305 dictionary file(s)
16306 @end table
16307
16308 @noindent
16309 The structure of a dictionary file, and details on the conventions
16310 used in the default dictionary file, are defined in @ref{Name Casing}.
16311
16312 The @option{^-D-^/SPECIFIC_CASING^} and
16313 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16314 compatible.
16315
16316 @node Construct Layout Control
16317 @subsection Construct Layout Control
16318 @cindex Layout control in @command{gnatpp}
16319
16320 @noindent
16321 This group of @command{gnatpp} switches controls the layout of comments and
16322 complex syntactic constructs. See @ref{Formatting Comments} for details
16323 on their effect.
16324
16325 @table @option
16326 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16327 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16328 All the comments remain unchanged
16329
16330 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16331 GNAT-style comment line indentation (this is the default).
16332
16333 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16334 Reference-manual comment line indentation.
16335
16336 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16337 GNAT-style comment beginning
16338
16339 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16340 Reformat comment blocks
16341
16342 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16343 Keep unchanged special form comments
16344
16345 Reformat comment blocks
16346
16347 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16348 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16349 GNAT-style layout (this is the default)
16350
16351 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16352 Compact layout
16353
16354 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16355 Uncompact layout
16356
16357 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16358 @item ^-N^/NOTABS^
16359 All the VT characters are removed from the comment text. All the HT characters
16360 are expanded with the sequences of space characters to get to the next tab
16361 stops.
16362
16363 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16364 @item ^--no-separate-is^/NO_SEPARATE_IS^
16365 Do not place the keyword @code{is} on a separate line in a subprogram body in
16366 case if the spec occupies more then one line.
16367
16368 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16369 @item ^--separate-label^/SEPARATE_LABEL^
16370 Place statement label(s) on a separate line, with the following statement
16371 on the next line.
16372
16373 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16374 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16375 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16376 keyword @code{then} in IF statements on a separate line.
16377
16378 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16379 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16380 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16381 keyword @code{then} in IF statements on a separate line. This option is
16382 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16383
16384 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16385 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16386 Start each USE clause in a context clause from a separate line.
16387
16388 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16389 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16390 Use a separate line for a loop or block statement name, but do not use an extra
16391 indentation level for the statement itself.
16392
16393 @end table
16394
16395 @ifclear vms
16396 @noindent
16397 The @option{-c1} and @option{-c2} switches are incompatible.
16398 The @option{-c3} and @option{-c4} switches are compatible with each other and
16399 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16400 the other comment formatting switches.
16401
16402 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16403 @end ifclear
16404
16405 @ifset vms
16406 @noindent
16407 For the @option{/COMMENTS_LAYOUT} qualifier:
16408 @itemize @bullet
16409 @item
16410 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16411 @item
16412 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16413 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16414 @end itemize
16415
16416 @noindent
16417 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16418 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16419 @end ifset
16420
16421 @node General Text Layout Control
16422 @subsection General Text Layout Control
16423
16424 @noindent
16425 These switches allow control over line length and indentation.
16426
16427 @table @option
16428 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16429 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16430 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16431
16432 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16433 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16434 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16435
16436 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16437 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16438 Indentation level for continuation lines (relative to the line being
16439 continued), @var{nnn} from 1@dots{}9.
16440 The default
16441 value is one less then the (normal) indentation level, unless the
16442 indentation is set to 1 (in which case the default value for continuation
16443 line indentation is also 1)
16444 @end table
16445
16446 @node Other Formatting Options
16447 @subsection Other Formatting Options
16448
16449 @noindent
16450 These switches control the inclusion of missing end/exit labels, and
16451 the indentation level in @b{case} statements.
16452
16453 @table @option
16454 @item ^-e^/NO_MISSED_LABELS^
16455 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16456 Do not insert missing end/exit labels. An end label is the name of
16457 a construct that may optionally be repeated at the end of the
16458 construct's declaration;
16459 e.g., the names of packages, subprograms, and tasks.
16460 An exit label is the name of a loop that may appear as target
16461 of an exit statement within the loop.
16462 By default, @command{gnatpp} inserts these end/exit labels when
16463 they are absent from the original source. This option suppresses such
16464 insertion, so that the formatted source reflects the original.
16465
16466 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16467 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16468 Insert a Form Feed character after a pragma Page.
16469
16470 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16471 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16472 Do not use an additional indentation level for @b{case} alternatives
16473 and variants if there are @var{nnn} or more (the default
16474 value is 10).
16475 If @var{nnn} is 0, an additional indentation level is
16476 used for @b{case} alternatives and variants regardless of their number.
16477 @end table
16478
16479 @node Setting the Source Search Path
16480 @subsection Setting the Source Search Path
16481
16482 @noindent
16483 To define the search path for the input source file, @command{gnatpp}
16484 uses the same switches as the GNAT compiler, with the same effects.
16485
16486 @table @option
16487 @item ^-I^/SEARCH=^@var{dir}
16488 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16489 The same as the corresponding gcc switch
16490
16491 @item ^-I-^/NOCURRENT_DIRECTORY^
16492 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16493 The same as the corresponding gcc switch
16494
16495 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16496 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16497 The same as the corresponding gcc switch
16498
16499 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16500 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16501 The same as the corresponding gcc switch
16502
16503 @end table
16504
16505 @node Output File Control
16506 @subsection Output File Control
16507
16508 @noindent
16509 By default the output is sent to the file whose name is obtained by appending
16510 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16511 (if the file with this name already exists, it is unconditionally overwritten).
16512 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16513 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16514 as output file.
16515 The output may be redirected by the following switches:
16516
16517 @table @option
16518 @item ^-pipe^/STANDARD_OUTPUT^
16519 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16520 Send the output to @code{Standard_Output}
16521
16522 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16523 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16524 Write the output into @var{output_file}.
16525 If @var{output_file} already exists, @command{gnatpp} terminates without
16526 reading or processing the input file.
16527
16528 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16529 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16530 Write the output into @var{output_file}, overwriting the existing file
16531 (if one is present).
16532
16533 @item ^-r^/REPLACE^
16534 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16535 Replace the input source file with the reformatted output, and copy the
16536 original input source into the file whose name is obtained by appending the
16537 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16538 If a file with this name already exists, @command{gnatpp} terminates without
16539 reading or processing the input file.
16540
16541 @item ^-rf^/OVERRIDING_REPLACE^
16542 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16543 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16544 already exists, it is overwritten.
16545
16546 @item ^-rnb^/REPLACE_NO_BACKUP^
16547 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16548 Replace the input source file with the reformatted output without
16549 creating any backup copy of the input source.
16550
16551 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16552 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16553 Specifies the format of the reformatted output file. The @var{xxx}
16554 ^string specified with the switch^option^ may be either
16555 @itemize @bullet
16556 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16557 @item ``@option{^crlf^CRLF^}''
16558 the same as @option{^crlf^CRLF^}
16559 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16560 @item ``@option{^lf^LF^}''
16561 the same as @option{^unix^UNIX^}
16562 @end itemize
16563
16564 @item ^-W^/RESULT_ENCODING=^@var{e}
16565 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16566 Specify the wide character encoding method used to write the code in the
16567 result file
16568 @var{e} is one of the following:
16569
16570 @itemize @bullet
16571
16572 @item ^h^HEX^
16573 Hex encoding
16574
16575 @item ^u^UPPER^
16576 Upper half encoding
16577
16578 @item ^s^SHIFT_JIS^
16579 Shift/JIS encoding
16580
16581 @item ^e^EUC^
16582 EUC encoding
16583
16584 @item ^8^UTF8^
16585 UTF-8 encoding
16586
16587 @item ^b^BRACKETS^
16588 Brackets encoding (default value)
16589 @end itemize
16590
16591 @end table
16592
16593 @noindent
16594 Options @option{^-pipe^/STANDARD_OUTPUT^},
16595 @option{^-o^/OUTPUT^} and
16596 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16597 contains only one file to reformat.
16598 Option
16599 @option{^--eol^/END_OF_LINE^}
16600 and
16601 @option{^-W^/RESULT_ENCODING^}
16602 cannot be used together
16603 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16604
16605 @node Other gnatpp Switches
16606 @subsection Other @code{gnatpp} Switches
16607
16608 @noindent
16609 The additional @command{gnatpp} switches are defined in this subsection.
16610
16611 @table @option
16612 @item ^-files @var{filename}^/FILES=@var{output_file}^
16613 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16614 Take the argument source files from the specified file. This file should be an
16615 ordinary textual file containing file names separated by spaces or
16616 line breaks. You can use this switch more then once in the same call to
16617 @command{gnatpp}. You also can combine this switch with explicit list of
16618 files.
16619
16620 @item ^-v^/VERBOSE^
16621 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16622 Verbose mode;
16623 @command{gnatpp} generates version information and then
16624 a trace of the actions it takes to produce or obtain the ASIS tree.
16625
16626 @item ^-w^/WARNINGS^
16627 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16628 Warning mode;
16629 @command{gnatpp} generates a warning whenever it cannot provide
16630 a required layout in the result source.
16631 @end table
16632
16633 @node Formatting Rules
16634 @section Formatting Rules
16635
16636 @noindent
16637 The following subsections show how @command{gnatpp} treats ``white space'',
16638 comments, program layout, and name casing.
16639 They provide the detailed descriptions of the switches shown above.
16640
16641 @menu
16642 * White Space and Empty Lines::
16643 * Formatting Comments::
16644 * Construct Layout::
16645 * Name Casing::
16646 @end menu
16647
16648 @node White Space and Empty Lines
16649 @subsection White Space and Empty Lines
16650
16651 @noindent
16652 @command{gnatpp} does not have an option to control space characters.
16653 It will add or remove spaces according to the style illustrated by the
16654 examples in the @cite{Ada Reference Manual}.
16655
16656 The only format effectors
16657 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16658 that will appear in the output file are platform-specific line breaks,
16659 and also format effectors within (but not at the end of) comments.
16660 In particular, each horizontal tab character that is not inside
16661 a comment will be treated as a space and thus will appear in the
16662 output file as zero or more spaces depending on
16663 the reformatting of the line in which it appears.
16664 The only exception is a Form Feed character, which is inserted after a
16665 pragma @code{Page} when @option{-ff} is set.
16666
16667 The output file will contain no lines with trailing ``white space'' (spaces,
16668 format effectors).
16669
16670 Empty lines in the original source are preserved
16671 only if they separate declarations or statements.
16672 In such contexts, a
16673 sequence of two or more empty lines is replaced by exactly one empty line.
16674 Note that a blank line will be removed if it separates two ``comment blocks''
16675 (a comment block is a sequence of whole-line comments).
16676 In order to preserve a visual separation between comment blocks, use an
16677 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16678 Likewise, if for some reason you wish to have a sequence of empty lines,
16679 use a sequence of empty comments instead.
16680
16681 @node Formatting Comments
16682 @subsection Formatting Comments
16683
16684 @noindent
16685 Comments in Ada code are of two kinds:
16686 @itemize @bullet
16687 @item
16688 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16689 ``white space'') on a line
16690
16691 @item
16692 an @emph{end-of-line comment}, which follows some other Ada lexical element
16693 on the same line.
16694 @end itemize
16695
16696 @noindent
16697 The indentation of a whole-line comment is that of either
16698 the preceding or following line in
16699 the formatted source, depending on switch settings as will be described below.
16700
16701 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16702 between the end of the preceding Ada lexical element and the beginning
16703 of the comment as appear in the original source,
16704 unless either the comment has to be split to
16705 satisfy the line length limitation, or else the next line contains a
16706 whole line comment that is considered a continuation of this end-of-line
16707 comment (because it starts at the same position).
16708 In the latter two
16709 cases, the start of the end-of-line comment is moved right to the nearest
16710 multiple of the indentation level.
16711 This may result in a ``line overflow'' (the right-shifted comment extending
16712 beyond the maximum line length), in which case the comment is split as
16713 described below.
16714
16715 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16716 (GNAT-style comment line indentation)
16717 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16718 (reference-manual comment line indentation).
16719 With reference-manual style, a whole-line comment is indented as if it
16720 were a declaration or statement at the same place
16721 (i.e., according to the indentation of the preceding line(s)).
16722 With GNAT style, a whole-line comment that is immediately followed by an
16723 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16724 word @b{begin}, is indented based on the construct that follows it.
16725
16726 For example:
16727 @smallexample @c ada
16728 @cartouche
16729 if A then
16730 null;
16731 -- some comment
16732 else
16733 null;
16734 end if;
16735 @end cartouche
16736 @end smallexample
16737
16738 @noindent
16739 Reference-manual indentation produces:
16740
16741 @smallexample @c ada
16742 @cartouche
16743 if A then
16744 null;
16745 -- some comment
16746 else
16747 null;
16748 end if;
16749 @end cartouche
16750 @end smallexample
16751
16752 @noindent
16753 while GNAT-style indentation produces:
16754
16755 @smallexample @c ada
16756 @cartouche
16757 if A then
16758 null;
16759 -- some comment
16760 else
16761 null;
16762 end if;
16763 @end cartouche
16764 @end smallexample
16765
16766 @noindent
16767 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16768 (GNAT style comment beginning) has the following
16769 effect:
16770
16771 @itemize @bullet
16772 @item
16773 For each whole-line comment that does not end with two hyphens,
16774 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16775 to ensure that there are at least two spaces between these hyphens and the
16776 first non-blank character of the comment.
16777 @end itemize
16778
16779 @noindent
16780 For an end-of-line comment, if in the original source the next line is a
16781 whole-line comment that starts at the same position
16782 as the end-of-line comment,
16783 then the whole-line comment (and all whole-line comments
16784 that follow it and that start at the same position)
16785 will start at this position in the output file.
16786
16787 @noindent
16788 That is, if in the original source we have:
16789
16790 @smallexample @c ada
16791 @cartouche
16792 begin
16793 A := B + C; -- B must be in the range Low1..High1
16794 -- C must be in the range Low2..High2
16795 --B+C will be in the range Low1+Low2..High1+High2
16796 X := X + 1;
16797 @end cartouche
16798 @end smallexample
16799
16800 @noindent
16801 Then in the formatted source we get
16802
16803 @smallexample @c ada
16804 @cartouche
16805 begin
16806 A := B + C; -- B must be in the range Low1..High1
16807 -- C must be in the range Low2..High2
16808 -- B+C will be in the range Low1+Low2..High1+High2
16809 X := X + 1;
16810 @end cartouche
16811 @end smallexample
16812
16813 @noindent
16814 A comment that exceeds the line length limit will be split.
16815 Unless switch
16816 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16817 the line belongs to a reformattable block, splitting the line generates a
16818 @command{gnatpp} warning.
16819 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16820 comments may be reformatted in typical
16821 word processor style (that is, moving words between lines and putting as
16822 many words in a line as possible).
16823
16824 @noindent
16825 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16826 that has a special format (that is, a character that is neither a letter nor digit
16827 not white space nor line break immediately following the leading @code{--} of
16828 the comment) should be without any change moved from the argument source
16829 into reformatted source. This switch allows to preserve comments that are used
16830 as a special marks in the code (e.g.@: SPARK annotation).
16831
16832 @node Construct Layout
16833 @subsection Construct Layout
16834
16835 @noindent
16836 In several cases the suggested layout in the Ada Reference Manual includes
16837 an extra level of indentation that many programmers prefer to avoid. The
16838 affected cases include:
16839
16840 @itemize @bullet
16841
16842 @item Record type declaration (RM 3.8)
16843
16844 @item Record representation clause (RM 13.5.1)
16845
16846 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16847
16848 @item Block statement in case if a block has a statement identifier (RM 5.6)
16849 @end itemize
16850
16851 @noindent
16852 In compact mode (when GNAT style layout or compact layout is set),
16853 the pretty printer uses one level of indentation instead
16854 of two. This is achieved in the record definition and record representation
16855 clause cases by putting the @code{record} keyword on the same line as the
16856 start of the declaration or representation clause, and in the block and loop
16857 case by putting the block or loop header on the same line as the statement
16858 identifier.
16859
16860 @noindent
16861 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16862 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16863 layout on the one hand, and uncompact layout
16864 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16865 can be illustrated by the following examples:
16866
16867 @iftex
16868 @cartouche
16869 @multitable @columnfractions .5 .5
16870 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16871
16872 @item
16873 @smallexample @c ada
16874 type q is record
16875 a : integer;
16876 b : integer;
16877 end record;
16878 @end smallexample
16879 @tab
16880 @smallexample @c ada
16881 type q is
16882 record
16883 a : integer;
16884 b : integer;
16885 end record;
16886 @end smallexample
16887
16888 @item
16889 @smallexample @c ada
16890 for q use record
16891 a at 0 range 0 .. 31;
16892 b at 4 range 0 .. 31;
16893 end record;
16894 @end smallexample
16895 @tab
16896 @smallexample @c ada
16897 for q use
16898 record
16899 a at 0 range 0 .. 31;
16900 b at 4 range 0 .. 31;
16901 end record;
16902 @end smallexample
16903
16904 @item
16905 @smallexample @c ada
16906 Block : declare
16907 A : Integer := 3;
16908 begin
16909 Proc (A, A);
16910 end Block;
16911 @end smallexample
16912 @tab
16913 @smallexample @c ada
16914 Block :
16915 declare
16916 A : Integer := 3;
16917 begin
16918 Proc (A, A);
16919 end Block;
16920 @end smallexample
16921
16922 @item
16923 @smallexample @c ada
16924 Clear : for J in 1 .. 10 loop
16925 A (J) := 0;
16926 end loop Clear;
16927 @end smallexample
16928 @tab
16929 @smallexample @c ada
16930 Clear :
16931 for J in 1 .. 10 loop
16932 A (J) := 0;
16933 end loop Clear;
16934 @end smallexample
16935 @end multitable
16936 @end cartouche
16937 @end iftex
16938
16939 @ifnottex
16940 @smallexample
16941 @cartouche
16942 GNAT style, compact layout Uncompact layout
16943
16944 type q is record type q is
16945 a : integer; record
16946 b : integer; a : integer;
16947 end record; b : integer;
16948 end record;
16949
16950 for q use record for q use
16951 a at 0 range 0 .. 31; record
16952 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16953 end record; b at 4 range 0 .. 31;
16954 end record;
16955
16956 Block : declare Block :
16957 A : Integer := 3; declare
16958 begin A : Integer := 3;
16959 Proc (A, A); begin
16960 end Block; Proc (A, A);
16961 end Block;
16962
16963 Clear : for J in 1 .. 10 loop Clear :
16964 A (J) := 0; for J in 1 .. 10 loop
16965 end loop Clear; A (J) := 0;
16966 end loop Clear;
16967 @end cartouche
16968 @end smallexample
16969 @end ifnottex
16970
16971 @noindent
16972 A further difference between GNAT style layout and compact layout is that
16973 GNAT style layout inserts empty lines as separation for
16974 compound statements, return statements and bodies.
16975
16976 Note that the layout specified by
16977 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16978 for named block and loop statements overrides the layout defined by these
16979 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16980 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16981 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16982
16983 @node Name Casing
16984 @subsection Name Casing
16985
16986 @noindent
16987 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16988 the same casing as the corresponding defining identifier.
16989
16990 You control the casing for defining occurrences via the
16991 @option{^-n^/NAME_CASING^} switch.
16992 @ifclear vms
16993 With @option{-nD} (``as declared'', which is the default),
16994 @end ifclear
16995 @ifset vms
16996 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16997 @end ifset
16998 defining occurrences appear exactly as in the source file
16999 where they are declared.
17000 The other ^values for this switch^options for this qualifier^ ---
17001 @option{^-nU^UPPER_CASE^},
17002 @option{^-nL^LOWER_CASE^},
17003 @option{^-nM^MIXED_CASE^} ---
17004 result in
17005 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17006 If @command{gnatpp} changes the casing of a defining
17007 occurrence, it analogously changes the casing of all the
17008 usage occurrences of this name.
17009
17010 If the defining occurrence of a name is not in the source compilation unit
17011 currently being processed by @command{gnatpp}, the casing of each reference to
17012 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17013 switch (subject to the dictionary file mechanism described below).
17014 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17015 had affected the
17016 casing for the defining occurrence of the name.
17017
17018 Some names may need to be spelled with casing conventions that are not
17019 covered by the upper-, lower-, and mixed-case transformations.
17020 You can arrange correct casing by placing such names in a
17021 @emph{dictionary file},
17022 and then supplying a @option{^-D^/DICTIONARY^} switch.
17023 The casing of names from dictionary files overrides
17024 any @option{^-n^/NAME_CASING^} switch.
17025
17026 To handle the casing of Ada predefined names and the names from GNAT libraries,
17027 @command{gnatpp} assumes a default dictionary file.
17028 The name of each predefined entity is spelled with the same casing as is used
17029 for the entity in the @cite{Ada Reference Manual}.
17030 The name of each entity in the GNAT libraries is spelled with the same casing
17031 as is used in the declaration of that entity.
17032
17033 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17034 default dictionary file.
17035 Instead, the casing for predefined and GNAT-defined names will be established
17036 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17037 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17038 will appear as just shown,
17039 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17040 To ensure that even such names are rendered in uppercase,
17041 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17042 (or else, less conveniently, place these names in upper case in a dictionary
17043 file).
17044
17045 A dictionary file is
17046 a plain text file; each line in this file can be either a blank line
17047 (containing only space characters and ASCII.HT characters), an Ada comment
17048 line, or the specification of exactly one @emph{casing schema}.
17049
17050 A casing schema is a string that has the following syntax:
17051
17052 @smallexample
17053 @cartouche
17054 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17055
17056 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17057 @end cartouche
17058 @end smallexample
17059
17060 @noindent
17061 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17062 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17063
17064 The casing schema string can be followed by white space and/or an Ada-style
17065 comment; any amount of white space is allowed before the string.
17066
17067 If a dictionary file is passed as
17068 @ifclear vms
17069 the value of a @option{-D@var{file}} switch
17070 @end ifclear
17071 @ifset vms
17072 an option to the @option{/DICTIONARY} qualifier
17073 @end ifset
17074 then for every
17075 simple name and every identifier, @command{gnatpp} checks if the dictionary
17076 defines the casing for the name or for some of its parts (the term ``subword''
17077 is used below to denote the part of a name which is delimited by ``_'' or by
17078 the beginning or end of the word and which does not contain any ``_'' inside):
17079
17080 @itemize @bullet
17081 @item
17082 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17083 the casing defined by the dictionary; no subwords are checked for this word
17084
17085 @item
17086 for every subword @command{gnatpp} checks if the dictionary contains the
17087 corresponding string of the form @code{*@var{simple_identifier}*},
17088 and if it does, the casing of this @var{simple_identifier} is used
17089 for this subword
17090
17091 @item
17092 if the whole name does not contain any ``_'' inside, and if for this name
17093 the dictionary contains two entries - one of the form @var{identifier},
17094 and another - of the form *@var{simple_identifier}*, then the first one
17095 is applied to define the casing of this name
17096
17097 @item
17098 if more than one dictionary file is passed as @command{gnatpp} switches, each
17099 dictionary adds new casing exceptions and overrides all the existing casing
17100 exceptions set by the previous dictionaries
17101
17102 @item
17103 when @command{gnatpp} checks if the word or subword is in the dictionary,
17104 this check is not case sensitive
17105 @end itemize
17106
17107 @noindent
17108 For example, suppose we have the following source to reformat:
17109
17110 @smallexample @c ada
17111 @cartouche
17112 procedure test is
17113 name1 : integer := 1;
17114 name4_name3_name2 : integer := 2;
17115 name2_name3_name4 : Boolean;
17116 name1_var : Float;
17117 begin
17118 name2_name3_name4 := name4_name3_name2 > name1;
17119 end;
17120 @end cartouche
17121 @end smallexample
17122
17123 @noindent
17124 And suppose we have two dictionaries:
17125
17126 @smallexample
17127 @cartouche
17128 @i{dict1:}
17129 NAME1
17130 *NaMe3*
17131 *Name1*
17132 @end cartouche
17133
17134 @cartouche
17135 @i{dict2:}
17136 *NAME3*
17137 @end cartouche
17138 @end smallexample
17139
17140 @noindent
17141 If @command{gnatpp} is called with the following switches:
17142
17143 @smallexample
17144 @ifclear vms
17145 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17146 @end ifclear
17147 @ifset vms
17148 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17149 @end ifset
17150 @end smallexample
17151
17152 @noindent
17153 then we will get the following name casing in the @command{gnatpp} output:
17154
17155 @smallexample @c ada
17156 @cartouche
17157 procedure Test is
17158 NAME1 : Integer := 1;
17159 Name4_NAME3_Name2 : Integer := 2;
17160 Name2_NAME3_Name4 : Boolean;
17161 Name1_Var : Float;
17162 begin
17163 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17164 end Test;
17165 @end cartouche
17166 @end smallexample
17167
17168 @c *********************************
17169 @node The GNAT Metric Tool gnatmetric
17170 @chapter The GNAT Metric Tool @command{gnatmetric}
17171 @findex gnatmetric
17172 @cindex Metric tool
17173
17174 @noindent
17175 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17176 for computing various program metrics.
17177 It takes an Ada source file as input and generates a file containing the
17178 metrics data as output. Various switches control which
17179 metrics are computed and output.
17180
17181 @command{gnatmetric} generates and uses the ASIS
17182 tree for the input source and thus requires the input to be syntactically and
17183 semantically legal.
17184 If this condition is not met, @command{gnatmetric} will generate
17185 an error message; no metric information for this file will be
17186 computed and reported.
17187
17188 If the compilation unit contained in the input source depends semantically
17189 upon units in files located outside the current directory, you have to provide
17190 the source search path when invoking @command{gnatmetric}.
17191 If it depends semantically upon units that are contained
17192 in files with names that do not follow the GNAT file naming rules, you have to
17193 provide the configuration file describing the corresponding naming scheme (see
17194 the description of the @command{gnatmetric} switches below.)
17195 Alternatively, you may use a project file and invoke @command{gnatmetric}
17196 through the @command{gnat} driver.
17197
17198 The @command{gnatmetric} command has the form
17199
17200 @smallexample
17201 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17202 @end smallexample
17203
17204 @noindent
17205 where
17206 @itemize @bullet
17207 @item
17208 @var{switches} specify the metrics to compute and define the destination for
17209 the output
17210
17211 @item
17212 Each @var{filename} is the name (including the extension) of a source
17213 file to process. ``Wildcards'' are allowed, and
17214 the file name may contain path information.
17215 If no @var{filename} is supplied, then the @var{switches} list must contain
17216 at least one
17217 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17218 Including both a @option{-files} switch and one or more
17219 @var{filename} arguments is permitted.
17220
17221 @item
17222 @samp{-cargs @var{gcc_switches}} is a list of switches for
17223 @command{gcc}. They will be passed on to all compiler invocations made by
17224 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17225 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17226 and use the @option{-gnatec} switch to set the configuration file.
17227 @end itemize
17228
17229 @menu
17230 * Switches for gnatmetric::
17231 @end menu
17232
17233 @node Switches for gnatmetric
17234 @section Switches for @command{gnatmetric}
17235
17236 @noindent
17237 The following subsections describe the various switches accepted by
17238 @command{gnatmetric}, organized by category.
17239
17240 @menu
17241 * Output Files Control::
17242 * Disable Metrics For Local Units::
17243 * Specifying a set of metrics to compute::
17244 * Other gnatmetric Switches::
17245 * Generate project-wide metrics::
17246 @end menu
17247
17248 @node Output Files Control
17249 @subsection Output File Control
17250 @cindex Output file control in @command{gnatmetric}
17251
17252 @noindent
17253 @command{gnatmetric} has two output formats. It can generate a
17254 textual (human-readable) form, and also XML. By default only textual
17255 output is generated.
17256
17257 When generating the output in textual form, @command{gnatmetric} creates
17258 for each Ada source file a corresponding text file
17259 containing the computed metrics, except for the case when the set of metrics
17260 specified by gnatmetric parameters consists only of metrics that are computed
17261 for the whole set of analyzed sources, but not for each Ada source.
17262 By default, this file is placed in the same directory as where the source
17263 file is located, and its name is obtained
17264 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17265 input file.
17266
17267 All the output information generated in XML format is placed in a single
17268 file. By default this file is placed in the current directory and has the
17269 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17270
17271 Some of the computed metrics are summed over the units passed to
17272 @command{gnatmetric}; for example, the total number of lines of code.
17273 By default this information is sent to @file{stdout}, but a file
17274 can be specified with the @option{-og} switch.
17275
17276 The following switches control the @command{gnatmetric} output:
17277
17278 @table @option
17279 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17280 @item ^-x^/XML^
17281 Generate the XML output
17282
17283 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17284 @item ^-xs^/XSD^
17285 Generate the XML output and the XML schema file that describes the structure
17286 of the XML metric report, this schema is assigned to the XML file. The schema
17287 file has the same name as the XML output file with @file{.xml} suffix replaced
17288 with @file{.xsd}
17289
17290 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17291 @item ^-nt^/NO_TEXT^
17292 Do not generate the output in text form (implies @option{^-x^/XML^})
17293
17294 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17295 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17296 Put textual files with detailed metrics into @var{output_dir}
17297
17298 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17299 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17300 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17301 in the name of the output file.
17302
17303 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17304 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17305 Put global metrics into @var{file_name}
17306
17307 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17308 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17309 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17310
17311 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17312 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17313 Use ``short'' source file names in the output. (The @command{gnatmetric}
17314 output includes the name(s) of the Ada source file(s) from which the metrics
17315 are computed. By default each name includes the absolute path. The
17316 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17317 to exclude all directory information from the file names that are output.)
17318
17319 @end table
17320
17321 @node Disable Metrics For Local Units
17322 @subsection Disable Metrics For Local Units
17323 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17324
17325 @noindent
17326 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17327 one compilation
17328 unit per one source file. It computes line metrics for the whole source
17329 file, and it also computes syntax
17330 and complexity metrics for the file's outermost unit.
17331
17332 By default, @command{gnatmetric} will also compute all metrics for certain
17333 kinds of locally declared program units:
17334
17335 @itemize @bullet
17336 @item
17337 subprogram (and generic subprogram) bodies;
17338
17339 @item
17340 package (and generic package) specs and bodies;
17341
17342 @item
17343 task object and type specifications and bodies;
17344
17345 @item
17346 protected object and type specifications and bodies.
17347 @end itemize
17348
17349 @noindent
17350 These kinds of entities will be referred to as
17351 @emph{eligible local program units}, or simply @emph{eligible local units},
17352 @cindex Eligible local unit (for @command{gnatmetric})
17353 in the discussion below.
17354
17355 Note that a subprogram declaration, generic instantiation,
17356 or renaming declaration only receives metrics
17357 computation when it appear as the outermost entity
17358 in a source file.
17359
17360 Suppression of metrics computation for eligible local units can be
17361 obtained via the following switch:
17362
17363 @table @option
17364 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17365 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17366 Do not compute detailed metrics for eligible local program units
17367
17368 @end table
17369
17370 @node Specifying a set of metrics to compute
17371 @subsection Specifying a set of metrics to compute
17372
17373 @noindent
17374 By default all the metrics are computed and reported. The switches
17375 described in this subsection allow you to control, on an individual
17376 basis, whether metrics are computed and
17377 reported. If at least one positive metric
17378 switch is specified (that is, a switch that defines that a given
17379 metric or set of metrics is to be computed), then only
17380 explicitly specified metrics are reported.
17381
17382 @menu
17383 * Line Metrics Control::
17384 * Syntax Metrics Control::
17385 * Complexity Metrics Control::
17386 * Object-Oriented Metrics Control::
17387 @end menu
17388
17389 @node Line Metrics Control
17390 @subsubsection Line Metrics Control
17391 @cindex Line metrics control in @command{gnatmetric}
17392
17393 @noindent
17394 For any (legal) source file, and for each of its
17395 eligible local program units, @command{gnatmetric} computes the following
17396 metrics:
17397
17398 @itemize @bullet
17399 @item
17400 the total number of lines;
17401
17402 @item
17403 the total number of code lines (i.e., non-blank lines that are not comments)
17404
17405 @item
17406 the number of comment lines
17407
17408 @item
17409 the number of code lines containing end-of-line comments;
17410
17411 @item
17412 the comment percentage: the ratio between the number of lines that contain
17413 comments and the number of all non-blank lines, expressed as a percentage;
17414
17415 @item
17416 the number of empty lines and lines containing only space characters and/or
17417 format effectors (blank lines)
17418
17419 @item
17420 the average number of code lines in subprogram bodies, task bodies, entry
17421 bodies and statement sequences in package bodies (this metric is only computed
17422 across the whole set of the analyzed units)
17423
17424 @end itemize
17425
17426 @noindent
17427 @command{gnatmetric} sums the values of the line metrics for all the
17428 files being processed and then generates the cumulative results. The tool
17429 also computes for all the files being processed the average number of code
17430 lines in bodies.
17431
17432 You can use the following switches to select the specific line metrics
17433 to be computed and reported.
17434
17435 @table @option
17436 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17437
17438 @ifclear vms
17439 @cindex @option{--no-lines@var{x}}
17440 @end ifclear
17441
17442 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17443 Report all the line metrics
17444
17445 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17446 Do not report any of line metrics
17447
17448 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17449 Report the number of all lines
17450
17451 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17452 Do not report the number of all lines
17453
17454 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17455 Report the number of code lines
17456
17457 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17458 Do not report the number of code lines
17459
17460 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17461 Report the number of comment lines
17462
17463 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17464 Do not report the number of comment lines
17465
17466 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17467 Report the number of code lines containing
17468 end-of-line comments
17469
17470 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17471 Do not report the number of code lines containing
17472 end-of-line comments
17473
17474 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17475 Report the comment percentage in the program text
17476
17477 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17478 Do not report the comment percentage in the program text
17479
17480 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17481 Report the number of blank lines
17482
17483 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17484 Do not report the number of blank lines
17485
17486 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17487 Report the average number of code lines in subprogram bodies, task bodies,
17488 entry bodies and statement sequences in package bodies. The metric is computed
17489 and reported for the whole set of processed Ada sources only.
17490
17491 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17492 Do not report the average number of code lines in subprogram bodies,
17493 task bodies, entry bodies and statement sequences in package bodies.
17494
17495 @end table
17496
17497 @node Syntax Metrics Control
17498 @subsubsection Syntax Metrics Control
17499 @cindex Syntax metrics control in @command{gnatmetric}
17500
17501 @noindent
17502 @command{gnatmetric} computes various syntactic metrics for the
17503 outermost unit and for each eligible local unit:
17504
17505 @table @emph
17506 @item LSLOC (``Logical Source Lines Of Code'')
17507 The total number of declarations and the total number of statements
17508
17509 @item Maximal static nesting level of inner program units
17510 According to
17511 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17512 package, a task unit, a protected unit, a
17513 protected entry, a generic unit, or an explicitly declared subprogram other
17514 than an enumeration literal.''
17515
17516 @item Maximal nesting level of composite syntactic constructs
17517 This corresponds to the notion of the
17518 maximum nesting level in the GNAT built-in style checks
17519 (@pxref{Style Checking})
17520 @end table
17521
17522 @noindent
17523 For the outermost unit in the file, @command{gnatmetric} additionally computes
17524 the following metrics:
17525
17526 @table @emph
17527 @item Public subprograms
17528 This metric is computed for package specs. It is the
17529 number of subprograms and generic subprograms declared in the visible
17530 part (including the visible part of nested packages, protected objects, and
17531 protected types).
17532
17533 @item All subprograms
17534 This metric is computed for bodies and subunits. The
17535 metric is equal to a total number of subprogram bodies in the compilation
17536 unit.
17537 Neither generic instantiations nor renamings-as-a-body nor body stubs
17538 are counted. Any subprogram body is counted, independently of its nesting
17539 level and enclosing constructs. Generic bodies and bodies of protected
17540 subprograms are counted in the same way as ``usual'' subprogram bodies.
17541
17542 @item Public types
17543 This metric is computed for package specs and
17544 generic package declarations. It is the total number of types
17545 that can be referenced from outside this compilation unit, plus the
17546 number of types from all the visible parts of all the visible generic
17547 packages. Generic formal types are not counted. Only types, not subtypes,
17548 are included.
17549
17550 @noindent
17551 Along with the total number of public types, the following
17552 types are counted and reported separately:
17553
17554 @itemize @bullet
17555 @item
17556 Abstract types
17557
17558 @item
17559 Root tagged types (abstract, non-abstract, private, non-private). Type
17560 extensions are @emph{not} counted
17561
17562 @item
17563 Private types (including private extensions)
17564
17565 @item
17566 Task types
17567
17568 @item
17569 Protected types
17570
17571 @end itemize
17572
17573 @item All types
17574 This metric is computed for any compilation unit. It is equal to the total
17575 number of the declarations of different types given in the compilation unit.
17576 The private and the corresponding full type declaration are counted as one
17577 type declaration. Incomplete type declarations and generic formal types
17578 are not counted.
17579 No distinction is made among different kinds of types (abstract,
17580 private etc.); the total number of types is computed and reported.
17581
17582 @end table
17583
17584 @noindent
17585 By default, all the syntax metrics are computed and reported. You can use the
17586 following switches to select specific syntax metrics.
17587
17588 @table @option
17589
17590 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17591
17592 @ifclear vms
17593 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17594 @end ifclear
17595
17596 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17597 Report all the syntax metrics
17598
17599 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17600 Do not report any of syntax metrics
17601
17602 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17603 Report the total number of declarations
17604
17605 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17606 Do not report the total number of declarations
17607
17608 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17609 Report the total number of statements
17610
17611 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17612 Do not report the total number of statements
17613
17614 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17615 Report the number of public subprograms in a compilation unit
17616
17617 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17618 Do not report the number of public subprograms in a compilation unit
17619
17620 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17621 Report the number of all the subprograms in a compilation unit
17622
17623 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17624 Do not report the number of all the subprograms in a compilation unit
17625
17626 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17627 Report the number of public types in a compilation unit
17628
17629 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17630 Do not report the number of public types in a compilation unit
17631
17632 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17633 Report the number of all the types in a compilation unit
17634
17635 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17636 Do not report the number of all the types in a compilation unit
17637
17638 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17639 Report the maximal program unit nesting level
17640
17641 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17642 Do not report the maximal program unit nesting level
17643
17644 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17645 Report the maximal construct nesting level
17646
17647 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17648 Do not report the maximal construct nesting level
17649
17650 @end table
17651
17652 @node Complexity Metrics Control
17653 @subsubsection Complexity Metrics Control
17654 @cindex Complexity metrics control in @command{gnatmetric}
17655
17656 @noindent
17657 For a program unit that is an executable body (a subprogram body (including
17658 generic bodies), task body, entry body or a package body containing
17659 its own statement sequence) @command{gnatmetric} computes the following
17660 complexity metrics:
17661
17662 @itemize @bullet
17663 @item
17664 McCabe cyclomatic complexity;
17665
17666 @item
17667 McCabe essential complexity;
17668
17669 @item
17670 maximal loop nesting level
17671
17672 @end itemize
17673
17674 @noindent
17675 The McCabe complexity metrics are defined
17676 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17677
17678 According to McCabe, both control statements and short-circuit control forms
17679 should be taken into account when computing cyclomatic complexity. For each
17680 body, we compute three metric values:
17681
17682 @itemize @bullet
17683 @item
17684 the complexity introduced by control
17685 statements only, without taking into account short-circuit forms,
17686
17687 @item
17688 the complexity introduced by short-circuit control forms only, and
17689
17690 @item
17691 the total
17692 cyclomatic complexity, which is the sum of these two values.
17693 @end itemize
17694
17695 @noindent
17696 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17697 the code in the exception handlers and in all the nested program units.
17698
17699 By default, all the complexity metrics are computed and reported.
17700 For more fine-grained control you can use
17701 the following switches:
17702
17703 @table @option
17704 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17705
17706 @ifclear vms
17707 @cindex @option{--no-complexity@var{x}}
17708 @end ifclear
17709
17710 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17711 Report all the complexity metrics
17712
17713 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17714 Do not report any of complexity metrics
17715
17716 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17717 Report the McCabe Cyclomatic Complexity
17718
17719 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17720 Do not report the McCabe Cyclomatic Complexity
17721
17722 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17723 Report the Essential Complexity
17724
17725 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17726 Do not report the Essential Complexity
17727
17728 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17729 Report maximal loop nesting level
17730
17731 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17732 Do not report maximal loop nesting level
17733
17734 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17735 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17736 task bodies, entry bodies and statement sequences in package bodies.
17737 The metric is computed and reported for whole set of processed Ada sources
17738 only.
17739
17740 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17741 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17742 bodies, task bodies, entry bodies and statement sequences in package bodies
17743
17744 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17745 @item ^-ne^/NO_EXITS_AS_GOTOS^
17746 Do not consider @code{exit} statements as @code{goto}s when
17747 computing Essential Complexity
17748
17749 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17750 Report the extra exit points for subprogram bodies. As an exit point, this
17751 metric counts @code{return} statements and raise statements in case when the
17752 raised exception is not handled in the same body. In case of a function this
17753 metric subtracts 1 from the number of exit points, because a function body
17754 must contain at least one @code{return} statement.
17755
17756 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17757 Do not report the extra exit points for subprogram bodies
17758 @end table
17759
17760
17761 @node Object-Oriented Metrics Control
17762 @subsubsection Object-Oriented Metrics Control
17763 @cindex Object-Oriented metrics control in @command{gnatmetric}
17764
17765 @noindent
17766 @cindex Coupling metrics (in in @command{gnatmetric})
17767 Coupling metrics are object-oriented metrics that measure the
17768 dependencies between a given class (or a group of classes) and the
17769 ``external world'' (that is, the other classes in the program). In this
17770 subsection the term ``class'' is used in its
17771 traditional object-oriented programming sense
17772 (an instantiable module that contains data and/or method members).
17773 A @emph{category} (of classes)
17774 is a group of closely related classes that are reused and/or
17775 modified together.
17776
17777 A class @code{K}'s @emph{efferent coupling} is the number of classes
17778 that @code{K} depends upon.
17779 A category's efferent coupling is the number of classes outside the
17780 category that the classes inside the category depend upon.
17781
17782 A class @code{K}'s @emph{afferent coupling} is the number of classes
17783 that depend upon @code{K}.
17784 A category's afferent coupling is the number of classes outside the
17785 category that depend on classes belonging to the category.
17786
17787 Ada's implementation of the object-oriented paradigm does not use the
17788 traditional class notion, so the definition of the coupling
17789 metrics for Ada maps the class and class category notions
17790 onto Ada constructs.
17791
17792 For the coupling metrics, several kinds of modules -- a library package,
17793 a library generic package, and a library generic package instantiation --
17794 that define a tagged type or an interface type are
17795 considered to be a class. A category consists of a library package (or
17796 a library generic package) that defines a tagged or an interface type,
17797 together with all its descendant (generic) packages that define tagged
17798 or interface types. For any package counted as a class,
17799 its body and subunits (if any) are considered
17800 together with its spec when counting the dependencies, and coupling
17801 metrics are reported for spec units only. For dependencies
17802 between classes, the Ada semantic dependencies are considered.
17803 For coupling metrics, only dependencies on units that are considered as
17804 classes, are considered.
17805
17806 When computing coupling metrics, @command{gnatmetric} counts only
17807 dependencies between units that are arguments of the gnatmetric call.
17808 Coupling metrics are program-wide (or project-wide) metrics, so to
17809 get a valid result, you should call @command{gnatmetric} for
17810 the whole set of sources that make up your program. It can be done
17811 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17812 option (see See @ref{The GNAT Driver and Project Files} for details.
17813
17814 By default, all the coupling metrics are disabled. You can use the following
17815 switches to specify the coupling metrics to be computed and reported:
17816
17817 @table @option
17818
17819 @ifclear vms
17820 @cindex @option{--package@var{x}} (@command{gnatmetric})
17821 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17822 @cindex @option{--category@var{x}} (@command{gnatmetric})
17823 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17824 @end ifclear
17825
17826 @ifset vms
17827 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17828 @end ifset
17829
17830 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17831 Report all the coupling metrics
17832
17833 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17834 Do not report any of metrics
17835
17836 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17837 Report package efferent coupling
17838
17839 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17840 Do not report package efferent coupling
17841
17842 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17843 Report package afferent coupling
17844
17845 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17846 Do not report package afferent coupling
17847
17848 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17849 Report category efferent coupling
17850
17851 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17852 Do not report category efferent coupling
17853
17854 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17855 Report category afferent coupling
17856
17857 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17858 Do not report category afferent coupling
17859
17860 @end table
17861
17862 @node Other gnatmetric Switches
17863 @subsection Other @code{gnatmetric} Switches
17864
17865 @noindent
17866 Additional @command{gnatmetric} switches are as follows:
17867
17868 @table @option
17869 @item ^-files @var{filename}^/FILES=@var{filename}^
17870 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17871 Take the argument source files from the specified file. This file should be an
17872 ordinary text file containing file names separated by spaces or
17873 line breaks. You can use this switch more then once in the same call to
17874 @command{gnatmetric}. You also can combine this switch with
17875 an explicit list of files.
17876
17877 @item ^-v^/VERBOSE^
17878 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17879 Verbose mode;
17880 @command{gnatmetric} generates version information and then
17881 a trace of sources being processed.
17882
17883 @item ^-dv^/DEBUG_OUTPUT^
17884 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17885 Debug mode;
17886 @command{gnatmetric} generates various messages useful to understand what
17887 happens during the metrics computation
17888
17889 @item ^-q^/QUIET^
17890 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17891 Quiet mode.
17892 @end table
17893
17894 @node Generate project-wide metrics
17895 @subsection Generate project-wide metrics
17896
17897 In order to compute metrics on all units of a given project, you can use
17898 the @command{gnat} driver along with the @option{-P} option:
17899 @smallexample
17900 gnat metric -Pproj
17901 @end smallexample
17902
17903 @noindent
17904 If the project @code{proj} depends upon other projects, you can compute
17905 the metrics on the project closure using the @option{-U} option:
17906 @smallexample
17907 gnat metric -Pproj -U
17908 @end smallexample
17909
17910 @noindent
17911 Finally, if not all the units are relevant to a particular main
17912 program in the project closure, you can generate metrics for the set
17913 of units needed to create a given main program (unit closure) using
17914 the @option{-U} option followed by the name of the main unit:
17915 @smallexample
17916 gnat metric -Pproj -U main
17917 @end smallexample
17918
17919
17920 @c ***********************************
17921 @node File Name Krunching Using gnatkr
17922 @chapter File Name Krunching Using @code{gnatkr}
17923 @findex gnatkr
17924
17925 @noindent
17926 This chapter discusses the method used by the compiler to shorten
17927 the default file names chosen for Ada units so that they do not
17928 exceed the maximum length permitted. It also describes the
17929 @code{gnatkr} utility that can be used to determine the result of
17930 applying this shortening.
17931 @menu
17932 * About gnatkr::
17933 * Using gnatkr::
17934 * Krunching Method::
17935 * Examples of gnatkr Usage::
17936 @end menu
17937
17938 @node About gnatkr
17939 @section About @code{gnatkr}
17940
17941 @noindent
17942 The default file naming rule in GNAT
17943 is that the file name must be derived from
17944 the unit name. The exact default rule is as follows:
17945 @itemize @bullet
17946 @item
17947 Take the unit name and replace all dots by hyphens.
17948 @item
17949 If such a replacement occurs in the
17950 second character position of a name, and the first character is
17951 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17952 then replace the dot by the character
17953 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17954 instead of a minus.
17955 @end itemize
17956 The reason for this exception is to avoid clashes
17957 with the standard names for children of System, Ada, Interfaces,
17958 and GNAT, which use the prefixes
17959 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17960 respectively.
17961
17962 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17963 switch of the compiler activates a ``krunching''
17964 circuit that limits file names to nn characters (where nn is a decimal
17965 integer). For example, using OpenVMS,
17966 where the maximum file name length is
17967 39, the value of nn is usually set to 39, but if you want to generate
17968 a set of files that would be usable if ported to a system with some
17969 different maximum file length, then a different value can be specified.
17970 The default value of 39 for OpenVMS need not be specified.
17971
17972 The @code{gnatkr} utility can be used to determine the krunched name for
17973 a given file, when krunched to a specified maximum length.
17974
17975 @node Using gnatkr
17976 @section Using @code{gnatkr}
17977
17978 @noindent
17979 The @code{gnatkr} command has the form
17980
17981 @ifclear vms
17982 @smallexample
17983 $ gnatkr @var{name} @ovar{length}
17984 @end smallexample
17985 @end ifclear
17986
17987 @ifset vms
17988 @smallexample
17989 $ gnatkr @var{name} /COUNT=nn
17990 @end smallexample
17991 @end ifset
17992
17993 @noindent
17994 @var{name} is the uncrunched file name, derived from the name of the unit
17995 in the standard manner described in the previous section (i.e., in particular
17996 all dots are replaced by hyphens). The file name may or may not have an
17997 extension (defined as a suffix of the form period followed by arbitrary
17998 characters other than period). If an extension is present then it will
17999 be preserved in the output. For example, when krunching @file{hellofile.ads}
18000 to eight characters, the result will be hellofil.ads.
18001
18002 Note: for compatibility with previous versions of @code{gnatkr} dots may
18003 appear in the name instead of hyphens, but the last dot will always be
18004 taken as the start of an extension. So if @code{gnatkr} is given an argument
18005 such as @file{Hello.World.adb} it will be treated exactly as if the first
18006 period had been a hyphen, and for example krunching to eight characters
18007 gives the result @file{hellworl.adb}.
18008
18009 Note that the result is always all lower case (except on OpenVMS where it is
18010 all upper case). Characters of the other case are folded as required.
18011
18012 @var{length} represents the length of the krunched name. The default
18013 when no argument is given is ^8^39^ characters. A length of zero stands for
18014 unlimited, in other words do not chop except for system files where the
18015 implied crunching length is always eight characters.
18016
18017 @noindent
18018 The output is the krunched name. The output has an extension only if the
18019 original argument was a file name with an extension.
18020
18021 @node Krunching Method
18022 @section Krunching Method
18023
18024 @noindent
18025 The initial file name is determined by the name of the unit that the file
18026 contains. The name is formed by taking the full expanded name of the
18027 unit and replacing the separating dots with hyphens and
18028 using ^lowercase^uppercase^
18029 for all letters, except that a hyphen in the second character position is
18030 replaced by a ^tilde^dollar sign^ if the first character is
18031 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18032 The extension is @code{.ads} for a
18033 spec and @code{.adb} for a body.
18034 Krunching does not affect the extension, but the file name is shortened to
18035 the specified length by following these rules:
18036
18037 @itemize @bullet
18038 @item
18039 The name is divided into segments separated by hyphens, tildes or
18040 underscores and all hyphens, tildes, and underscores are
18041 eliminated. If this leaves the name short enough, we are done.
18042
18043 @item
18044 If the name is too long, the longest segment is located (left-most
18045 if there are two of equal length), and shortened by dropping
18046 its last character. This is repeated until the name is short enough.
18047
18048 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18049 to fit the name into 8 characters as required by some operating systems.
18050
18051 @smallexample
18052 our-strings-wide_fixed 22
18053 our strings wide fixed 19
18054 our string wide fixed 18
18055 our strin wide fixed 17
18056 our stri wide fixed 16
18057 our stri wide fixe 15
18058 our str wide fixe 14
18059 our str wid fixe 13
18060 our str wid fix 12
18061 ou str wid fix 11
18062 ou st wid fix 10
18063 ou st wi fix 9
18064 ou st wi fi 8
18065 Final file name: oustwifi.adb
18066 @end smallexample
18067
18068 @item
18069 The file names for all predefined units are always krunched to eight
18070 characters. The krunching of these predefined units uses the following
18071 special prefix replacements:
18072
18073 @table @file
18074 @item ada-
18075 replaced by @file{^a^A^-}
18076
18077 @item gnat-
18078 replaced by @file{^g^G^-}
18079
18080 @item interfaces-
18081 replaced by @file{^i^I^-}
18082
18083 @item system-
18084 replaced by @file{^s^S^-}
18085 @end table
18086
18087 These system files have a hyphen in the second character position. That
18088 is why normal user files replace such a character with a
18089 ^tilde^dollar sign^, to
18090 avoid confusion with system file names.
18091
18092 As an example of this special rule, consider
18093 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18094
18095 @smallexample
18096 ada-strings-wide_fixed 22
18097 a- strings wide fixed 18
18098 a- string wide fixed 17
18099 a- strin wide fixed 16
18100 a- stri wide fixed 15
18101 a- stri wide fixe 14
18102 a- str wide fixe 13
18103 a- str wid fixe 12
18104 a- str wid fix 11
18105 a- st wid fix 10
18106 a- st wi fix 9
18107 a- st wi fi 8
18108 Final file name: a-stwifi.adb
18109 @end smallexample
18110 @end itemize
18111
18112 Of course no file shortening algorithm can guarantee uniqueness over all
18113 possible unit names, and if file name krunching is used then it is your
18114 responsibility to ensure that no name clashes occur. The utility
18115 program @code{gnatkr} is supplied for conveniently determining the
18116 krunched name of a file.
18117
18118 @node Examples of gnatkr Usage
18119 @section Examples of @code{gnatkr} Usage
18120
18121 @smallexample
18122 @iftex
18123 @leftskip=0cm
18124 @end iftex
18125 @ifclear vms
18126 $ gnatkr very_long_unit_name.ads --> velounna.ads
18127 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18128 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18129 $ gnatkr grandparent-parent-child --> grparchi
18130 @end ifclear
18131 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18132 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18133 @end smallexample
18134
18135 @node Preprocessing Using gnatprep
18136 @chapter Preprocessing Using @code{gnatprep}
18137 @findex gnatprep
18138
18139 @noindent
18140 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18141 preprocessing.
18142 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18143 special GNAT features.
18144 For further discussion of conditional compilation in general, see
18145 @ref{Conditional Compilation}.
18146
18147 @menu
18148 * Preprocessing Symbols::
18149 * Using gnatprep::
18150 * Switches for gnatprep::
18151 * Form of Definitions File::
18152 * Form of Input Text for gnatprep::
18153 @end menu
18154
18155 @node Preprocessing Symbols
18156 @section Preprocessing Symbols
18157
18158 @noindent
18159 Preprocessing symbols are defined in definition files and referred to in
18160 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18161 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18162 all characters need to be in the ASCII set (no accented letters).
18163
18164 @node Using gnatprep
18165 @section Using @code{gnatprep}
18166
18167 @noindent
18168 To call @code{gnatprep} use
18169
18170 @smallexample
18171 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18172 @end smallexample
18173
18174 @noindent
18175 where
18176 @table @var
18177 @item switches
18178 is an optional sequence of switches as described in the next section.
18179
18180 @item infile
18181 is the full name of the input file, which is an Ada source
18182 file containing preprocessor directives.
18183
18184 @item outfile
18185 is the full name of the output file, which is an Ada source
18186 in standard Ada form. When used with GNAT, this file name will
18187 normally have an ads or adb suffix.
18188
18189 @item deffile
18190 is the full name of a text file containing definitions of
18191 preprocessing symbols to be referenced by the preprocessor. This argument is
18192 optional, and can be replaced by the use of the @option{-D} switch.
18193
18194 @end table
18195
18196 @node Switches for gnatprep
18197 @section Switches for @code{gnatprep}
18198
18199 @table @option
18200 @c !sort!
18201
18202 @item ^-b^/BLANK_LINES^
18203 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18204 Causes both preprocessor lines and the lines deleted by
18205 preprocessing to be replaced by blank lines in the output source file,
18206 preserving line numbers in the output file.
18207
18208 @item ^-c^/COMMENTS^
18209 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18210 Causes both preprocessor lines and the lines deleted
18211 by preprocessing to be retained in the output source as comments marked
18212 with the special string @code{"--! "}. This option will result in line numbers
18213 being preserved in the output file.
18214
18215 @item ^-C^/REPLACE_IN_COMMENTS^
18216 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18217 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18218 If this option is specified, then comments are scanned and any $symbol
18219 substitutions performed as in program text. This is particularly useful
18220 when structured comments are used (e.g., when writing programs in the
18221 SPARK dialect of Ada). Note that this switch is not available when
18222 doing integrated preprocessing (it would be useless in this context
18223 since comments are ignored by the compiler in any case).
18224
18225 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18226 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18227 Defines a new preprocessing symbol, associated with value. If no value is given
18228 on the command line, then symbol is considered to be @code{True}. This switch
18229 can be used in place of a definition file.
18230
18231 @ifset vms
18232 @item /REMOVE
18233 @cindex @option{/REMOVE} (@command{gnatprep})
18234 This is the default setting which causes lines deleted by preprocessing
18235 to be entirely removed from the output file.
18236 @end ifset
18237
18238 @item ^-r^/REFERENCE^
18239 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18240 Causes a @code{Source_Reference} pragma to be generated that
18241 references the original input file, so that error messages will use
18242 the file name of this original file. The use of this switch implies
18243 that preprocessor lines are not to be removed from the file, so its
18244 use will force @option{^-b^/BLANK_LINES^} mode if
18245 @option{^-c^/COMMENTS^}
18246 has not been specified explicitly.
18247
18248 Note that if the file to be preprocessed contains multiple units, then
18249 it will be necessary to @code{gnatchop} the output file from
18250 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18251 in the preprocessed file, it will be respected by
18252 @code{gnatchop ^-r^/REFERENCE^}
18253 so that the final chopped files will correctly refer to the original
18254 input source file for @code{gnatprep}.
18255
18256 @item ^-s^/SYMBOLS^
18257 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18258 Causes a sorted list of symbol names and values to be
18259 listed on the standard output file.
18260
18261 @item ^-u^/UNDEFINED^
18262 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18263 Causes undefined symbols to be treated as having the value FALSE in the context
18264 of a preprocessor test. In the absence of this option, an undefined symbol in
18265 a @code{#if} or @code{#elsif} test will be treated as an error.
18266
18267 @end table
18268
18269 @ifclear vms
18270 @noindent
18271 Note: if neither @option{-b} nor @option{-c} is present,
18272 then preprocessor lines and
18273 deleted lines are completely removed from the output, unless -r is
18274 specified, in which case -b is assumed.
18275 @end ifclear
18276
18277 @node Form of Definitions File
18278 @section Form of Definitions File
18279
18280 @noindent
18281 The definitions file contains lines of the form
18282
18283 @smallexample
18284 symbol := value
18285 @end smallexample
18286
18287 @noindent
18288 where symbol is a preprocessing symbol, and value is one of the following:
18289
18290 @itemize @bullet
18291 @item
18292 Empty, corresponding to a null substitution
18293 @item
18294 A string literal using normal Ada syntax
18295 @item
18296 Any sequence of characters from the set
18297 (letters, digits, period, underline).
18298 @end itemize
18299
18300 @noindent
18301 Comment lines may also appear in the definitions file, starting with
18302 the usual @code{--},
18303 and comments may be added to the definitions lines.
18304
18305 @node Form of Input Text for gnatprep
18306 @section Form of Input Text for @code{gnatprep}
18307
18308 @noindent
18309 The input text may contain preprocessor conditional inclusion lines,
18310 as well as general symbol substitution sequences.
18311
18312 The preprocessor conditional inclusion commands have the form
18313
18314 @smallexample
18315 @group
18316 @cartouche
18317 #if @i{expression} @r{[}then@r{]}
18318 lines
18319 #elsif @i{expression} @r{[}then@r{]}
18320 lines
18321 #elsif @i{expression} @r{[}then@r{]}
18322 lines
18323 @dots{}
18324 #else
18325 lines
18326 #end if;
18327 @end cartouche
18328 @end group
18329 @end smallexample
18330
18331 @noindent
18332 In this example, @i{expression} is defined by the following grammar:
18333 @smallexample
18334 @i{expression} ::= <symbol>
18335 @i{expression} ::= <symbol> = "<value>"
18336 @i{expression} ::= <symbol> = <symbol>
18337 @i{expression} ::= <symbol> 'Defined
18338 @i{expression} ::= not @i{expression}
18339 @i{expression} ::= @i{expression} and @i{expression}
18340 @i{expression} ::= @i{expression} or @i{expression}
18341 @i{expression} ::= @i{expression} and then @i{expression}
18342 @i{expression} ::= @i{expression} or else @i{expression}
18343 @i{expression} ::= ( @i{expression} )
18344 @end smallexample
18345
18346 The following restriction exists: it is not allowed to have "and" or "or"
18347 following "not" in the same expression without parentheses. For example, this
18348 is not allowed:
18349
18350 @smallexample
18351 not X or Y
18352 @end smallexample
18353
18354 This should be one of the following:
18355
18356 @smallexample
18357 (not X) or Y
18358 not (X or Y)
18359 @end smallexample
18360
18361 @noindent
18362 For the first test (@i{expression} ::= <symbol>) the symbol must have
18363 either the value true or false, that is to say the right-hand of the
18364 symbol definition must be one of the (case-insensitive) literals
18365 @code{True} or @code{False}. If the value is true, then the
18366 corresponding lines are included, and if the value is false, they are
18367 excluded.
18368
18369 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18370 the symbol has been defined in the definition file or by a @option{-D}
18371 switch on the command line. Otherwise, the test is false.
18372
18373 The equality tests are case insensitive, as are all the preprocessor lines.
18374
18375 If the symbol referenced is not defined in the symbol definitions file,
18376 then the effect depends on whether or not switch @option{-u}
18377 is specified. If so, then the symbol is treated as if it had the value
18378 false and the test fails. If this switch is not specified, then
18379 it is an error to reference an undefined symbol. It is also an error to
18380 reference a symbol that is defined with a value other than @code{True}
18381 or @code{False}.
18382
18383 The use of the @code{not} operator inverts the sense of this logical test.
18384 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18385 operators, without parentheses. For example, "if not X or Y then" is not
18386 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18387
18388 The @code{then} keyword is optional as shown
18389
18390 The @code{#} must be the first non-blank character on a line, but
18391 otherwise the format is free form. Spaces or tabs may appear between
18392 the @code{#} and the keyword. The keywords and the symbols are case
18393 insensitive as in normal Ada code. Comments may be used on a
18394 preprocessor line, but other than that, no other tokens may appear on a
18395 preprocessor line. Any number of @code{elsif} clauses can be present,
18396 including none at all. The @code{else} is optional, as in Ada.
18397
18398 The @code{#} marking the start of a preprocessor line must be the first
18399 non-blank character on the line, i.e., it must be preceded only by
18400 spaces or horizontal tabs.
18401
18402 Symbol substitution outside of preprocessor lines is obtained by using
18403 the sequence
18404
18405 @smallexample
18406 $symbol
18407 @end smallexample
18408
18409 @noindent
18410 anywhere within a source line, except in a comment or within a
18411 string literal. The identifier
18412 following the @code{$} must match one of the symbols defined in the symbol
18413 definition file, and the result is to substitute the value of the
18414 symbol in place of @code{$symbol} in the output file.
18415
18416 Note that although the substitution of strings within a string literal
18417 is not possible, it is possible to have a symbol whose defined value is
18418 a string literal. So instead of setting XYZ to @code{hello} and writing:
18419
18420 @smallexample
18421 Header : String := "$XYZ";
18422 @end smallexample
18423
18424 @noindent
18425 you should set XYZ to @code{"hello"} and write:
18426
18427 @smallexample
18428 Header : String := $XYZ;
18429 @end smallexample
18430
18431 @noindent
18432 and then the substitution will occur as desired.
18433
18434 @ifset vms
18435 @node The GNAT Run-Time Library Builder gnatlbr
18436 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18437 @findex gnatlbr
18438 @cindex Library builder
18439
18440 @noindent
18441 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18442 supplied configuration pragmas.
18443
18444 @menu
18445 * Running gnatlbr::
18446 * Switches for gnatlbr::
18447 * Examples of gnatlbr Usage::
18448 @end menu
18449
18450 @node Running gnatlbr
18451 @section Running @code{gnatlbr}
18452
18453 @noindent
18454 The @code{gnatlbr} command has the form
18455
18456 @smallexample
18457 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18458 @end smallexample
18459
18460 @node Switches for gnatlbr
18461 @section Switches for @code{gnatlbr}
18462
18463 @noindent
18464 @code{gnatlbr} recognizes the following switches:
18465
18466 @table @option
18467 @c !sort!
18468 @item /CREATE=directory
18469 @cindex @code{/CREATE} (@code{gnatlbr})
18470 Create the new run-time library in the specified directory.
18471
18472 @item /SET=directory
18473 @cindex @code{/SET} (@code{gnatlbr})
18474 Make the library in the specified directory the current run-time library.
18475
18476 @item /DELETE=directory
18477 @cindex @code{/DELETE} (@code{gnatlbr})
18478 Delete the run-time library in the specified directory.
18479
18480 @item /CONFIG=file
18481 @cindex @code{/CONFIG} (@code{gnatlbr})
18482 With /CREATE: Use the configuration pragmas in the specified file when
18483 building the library.
18484
18485 With /SET: Use the configuration pragmas in the specified file when
18486 compiling.
18487
18488 @end table
18489
18490 @node Examples of gnatlbr Usage
18491 @section Example of @code{gnatlbr} Usage
18492
18493 @smallexample
18494 Contents of VAXFLOAT.ADC:
18495 pragma Float_Representation (VAX_Float);
18496
18497 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18498
18499 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18500
18501 @end smallexample
18502 @end ifset
18503
18504 @node The GNAT Library Browser gnatls
18505 @chapter The GNAT Library Browser @code{gnatls}
18506 @findex gnatls
18507 @cindex Library browser
18508
18509 @noindent
18510 @code{gnatls} is a tool that outputs information about compiled
18511 units. It gives the relationship between objects, unit names and source
18512 files. It can also be used to check the source dependencies of a unit
18513 as well as various characteristics.
18514
18515 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18516 driver (see @ref{The GNAT Driver and Project Files}).
18517
18518 @menu
18519 * Running gnatls::
18520 * Switches for gnatls::
18521 * Examples of gnatls Usage::
18522 @end menu
18523
18524 @node Running gnatls
18525 @section Running @code{gnatls}
18526
18527 @noindent
18528 The @code{gnatls} command has the form
18529
18530 @smallexample
18531 $ gnatls switches @var{object_or_ali_file}
18532 @end smallexample
18533
18534 @noindent
18535 The main argument is the list of object or @file{ali} files
18536 (@pxref{The Ada Library Information Files})
18537 for which information is requested.
18538
18539 In normal mode, without additional option, @code{gnatls} produces a
18540 four-column listing. Each line represents information for a specific
18541 object. The first column gives the full path of the object, the second
18542 column gives the name of the principal unit in this object, the third
18543 column gives the status of the source and the fourth column gives the
18544 full path of the source representing this unit.
18545 Here is a simple example of use:
18546
18547 @smallexample
18548 $ gnatls *.o
18549 ^./^[]^demo1.o demo1 DIF demo1.adb
18550 ^./^[]^demo2.o demo2 OK demo2.adb
18551 ^./^[]^hello.o h1 OK hello.adb
18552 ^./^[]^instr-child.o instr.child MOK instr-child.adb
18553 ^./^[]^instr.o instr OK instr.adb
18554 ^./^[]^tef.o tef DIF tef.adb
18555 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
18556 ^./^[]^tgef.o tgef DIF tgef.adb
18557 @end smallexample
18558
18559 @noindent
18560 The first line can be interpreted as follows: the main unit which is
18561 contained in
18562 object file @file{demo1.o} is demo1, whose main source is in
18563 @file{demo1.adb}. Furthermore, the version of the source used for the
18564 compilation of demo1 has been modified (DIF). Each source file has a status
18565 qualifier which can be:
18566
18567 @table @code
18568 @item OK (unchanged)
18569 The version of the source file used for the compilation of the
18570 specified unit corresponds exactly to the actual source file.
18571
18572 @item MOK (slightly modified)
18573 The version of the source file used for the compilation of the
18574 specified unit differs from the actual source file but not enough to
18575 require recompilation. If you use gnatmake with the qualifier
18576 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18577 MOK will not be recompiled.
18578
18579 @item DIF (modified)
18580 No version of the source found on the path corresponds to the source
18581 used to build this object.
18582
18583 @item ??? (file not found)
18584 No source file was found for this unit.
18585
18586 @item HID (hidden, unchanged version not first on PATH)
18587 The version of the source that corresponds exactly to the source used
18588 for compilation has been found on the path but it is hidden by another
18589 version of the same source that has been modified.
18590
18591 @end table
18592
18593 @node Switches for gnatls
18594 @section Switches for @code{gnatls}
18595
18596 @noindent
18597 @code{gnatls} recognizes the following switches:
18598
18599 @table @option
18600 @c !sort!
18601 @cindex @option{--version} @command{gnatls}
18602 Display Copyright and version, then exit disregarding all other options.
18603
18604 @item --help
18605 @cindex @option{--help} @command{gnatls}
18606 If @option{--version} was not used, display usage, then exit disregarding
18607 all other options.
18608
18609 @item ^-a^/ALL_UNITS^
18610 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18611 Consider all units, including those of the predefined Ada library.
18612 Especially useful with @option{^-d^/DEPENDENCIES^}.
18613
18614 @item ^-d^/DEPENDENCIES^
18615 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18616 List sources from which specified units depend on.
18617
18618 @item ^-h^/OUTPUT=OPTIONS^
18619 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18620 Output the list of options.
18621
18622 @item ^-o^/OUTPUT=OBJECTS^
18623 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18624 Only output information about object files.
18625
18626 @item ^-s^/OUTPUT=SOURCES^
18627 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18628 Only output information about source files.
18629
18630 @item ^-u^/OUTPUT=UNITS^
18631 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18632 Only output information about compilation units.
18633
18634 @item ^-files^/FILES^=@var{file}
18635 @cindex @option{^-files^/FILES^} (@code{gnatls})
18636 Take as arguments the files listed in text file @var{file}.
18637 Text file @var{file} may contain empty lines that are ignored.
18638 Each nonempty line should contain the name of an existing file.
18639 Several such switches may be specified simultaneously.
18640
18641 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18642 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18643 @itemx ^-I^/SEARCH=^@var{dir}
18644 @itemx ^-I-^/NOCURRENT_DIRECTORY^
18645 @itemx -nostdinc
18646 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18647 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18648 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18649 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18650 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18651 flags (@pxref{Switches for gnatmake}).
18652
18653 @item --RTS=@var{rts-path}
18654 @cindex @option{--RTS} (@code{gnatls})
18655 Specifies the default location of the runtime library. Same meaning as the
18656 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18657
18658 @item ^-v^/OUTPUT=VERBOSE^
18659 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18660 Verbose mode. Output the complete source, object and project paths. Do not use
18661 the default column layout but instead use long format giving as much as
18662 information possible on each requested units, including special
18663 characteristics such as:
18664
18665 @table @code
18666 @item Preelaborable
18667 The unit is preelaborable in the Ada sense.
18668
18669 @item No_Elab_Code
18670 No elaboration code has been produced by the compiler for this unit.
18671
18672 @item Pure
18673 The unit is pure in the Ada sense.
18674
18675 @item Elaborate_Body
18676 The unit contains a pragma Elaborate_Body.
18677
18678 @item Remote_Types
18679 The unit contains a pragma Remote_Types.
18680
18681 @item Shared_Passive
18682 The unit contains a pragma Shared_Passive.
18683
18684 @item Predefined
18685 This unit is part of the predefined environment and cannot be modified
18686 by the user.
18687
18688 @item Remote_Call_Interface
18689 The unit contains a pragma Remote_Call_Interface.
18690
18691 @end table
18692
18693 @end table
18694
18695 @node Examples of gnatls Usage
18696 @section Example of @code{gnatls} Usage
18697 @ifclear vms
18698
18699 @noindent
18700 Example of using the verbose switch. Note how the source and
18701 object paths are affected by the -I switch.
18702
18703 @smallexample
18704 $ gnatls -v -I.. demo1.o
18705
18706 GNATLS 5.03w (20041123-34)
18707 Copyright 1997-2004 Free Software Foundation, Inc.
18708
18709 Source Search Path:
18710 <Current_Directory>
18711 ../
18712 /home/comar/local/adainclude/
18713
18714 Object Search Path:
18715 <Current_Directory>
18716 ../
18717 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18718
18719 Project Search Path:
18720 <Current_Directory>
18721 /home/comar/local/lib/gnat/
18722
18723 ./demo1.o
18724 Unit =>
18725 Name => demo1
18726 Kind => subprogram body
18727 Flags => No_Elab_Code
18728 Source => demo1.adb modified
18729 @end smallexample
18730
18731 @noindent
18732 The following is an example of use of the dependency list.
18733 Note the use of the -s switch
18734 which gives a straight list of source files. This can be useful for
18735 building specialized scripts.
18736
18737 @smallexample
18738 $ gnatls -d demo2.o
18739 ./demo2.o demo2 OK demo2.adb
18740 OK gen_list.ads
18741 OK gen_list.adb
18742 OK instr.ads
18743 OK instr-child.ads
18744
18745 $ gnatls -d -s -a demo1.o
18746 demo1.adb
18747 /home/comar/local/adainclude/ada.ads
18748 /home/comar/local/adainclude/a-finali.ads
18749 /home/comar/local/adainclude/a-filico.ads
18750 /home/comar/local/adainclude/a-stream.ads
18751 /home/comar/local/adainclude/a-tags.ads
18752 gen_list.ads
18753 gen_list.adb
18754 /home/comar/local/adainclude/gnat.ads
18755 /home/comar/local/adainclude/g-io.ads
18756 instr.ads
18757 /home/comar/local/adainclude/system.ads
18758 /home/comar/local/adainclude/s-exctab.ads
18759 /home/comar/local/adainclude/s-finimp.ads
18760 /home/comar/local/adainclude/s-finroo.ads
18761 /home/comar/local/adainclude/s-secsta.ads
18762 /home/comar/local/adainclude/s-stalib.ads
18763 /home/comar/local/adainclude/s-stoele.ads
18764 /home/comar/local/adainclude/s-stratt.ads
18765 /home/comar/local/adainclude/s-tasoli.ads
18766 /home/comar/local/adainclude/s-unstyp.ads
18767 /home/comar/local/adainclude/unchconv.ads
18768 @end smallexample
18769 @end ifclear
18770
18771 @ifset vms
18772 @smallexample
18773 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18774
18775 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18776 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18777 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18778 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18779 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18780 demo1.adb
18781 gen_list.ads
18782 gen_list.adb
18783 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18784 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18785 instr.ads
18786 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18787 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18788 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18789 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18790 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18791 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18792 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18793 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18794 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18795 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18796 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18797 @end smallexample
18798 @end ifset
18799
18800 @node Cleaning Up Using gnatclean
18801 @chapter Cleaning Up Using @code{gnatclean}
18802 @findex gnatclean
18803 @cindex Cleaning tool
18804
18805 @noindent
18806 @code{gnatclean} is a tool that allows the deletion of files produced by the
18807 compiler, binder and linker, including ALI files, object files, tree files,
18808 expanded source files, library files, interface copy source files, binder
18809 generated files and executable files.
18810
18811 @menu
18812 * Running gnatclean::
18813 * Switches for gnatclean::
18814 @c * Examples of gnatclean Usage::
18815 @end menu
18816
18817 @node Running gnatclean
18818 @section Running @code{gnatclean}
18819
18820 @noindent
18821 The @code{gnatclean} command has the form:
18822
18823 @smallexample
18824 $ gnatclean switches @var{names}
18825 @end smallexample
18826
18827 @noindent
18828 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18829 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18830 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18831
18832 @noindent
18833 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18834 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18835 the linker. In informative-only mode, specified by switch
18836 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18837 normal mode is listed, but no file is actually deleted.
18838
18839 @node Switches for gnatclean
18840 @section Switches for @code{gnatclean}
18841
18842 @noindent
18843 @code{gnatclean} recognizes the following switches:
18844
18845 @table @option
18846 @c !sort!
18847 @cindex @option{--version} @command{gnatclean}
18848 Display Copyright and version, then exit disregarding all other options.
18849
18850 @item --help
18851 @cindex @option{--help} @command{gnatclean}
18852 If @option{--version} was not used, display usage, then exit disregarding
18853 all other options.
18854
18855 @item ^-c^/COMPILER_FILES_ONLY^
18856 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18857 Only attempt to delete the files produced by the compiler, not those produced
18858 by the binder or the linker. The files that are not to be deleted are library
18859 files, interface copy files, binder generated files and executable files.
18860
18861 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18862 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18863 Indicate that ALI and object files should normally be found in directory
18864 @var{dir}.
18865
18866 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18867 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18868 When using project files, if some errors or warnings are detected during
18869 parsing and verbose mode is not in effect (no use of switch
18870 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18871 file, rather than its simple file name.
18872
18873 @item ^-h^/HELP^
18874 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18875 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18876
18877 @item ^-n^/NODELETE^
18878 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18879 Informative-only mode. Do not delete any files. Output the list of the files
18880 that would have been deleted if this switch was not specified.
18881
18882 @item ^-P^/PROJECT_FILE=^@var{project}
18883 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18884 Use project file @var{project}. Only one such switch can be used.
18885 When cleaning a project file, the files produced by the compilation of the
18886 immediate sources or inherited sources of the project files are to be
18887 deleted. This is not depending on the presence or not of executable names
18888 on the command line.
18889
18890 @item ^-q^/QUIET^
18891 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18892 Quiet output. If there are no errors, do not output anything, except in
18893 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18894 (switch ^-n^/NODELETE^).
18895
18896 @item ^-r^/RECURSIVE^
18897 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18898 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18899 clean all imported and extended project files, recursively. If this switch
18900 is not specified, only the files related to the main project file are to be
18901 deleted. This switch has no effect if no project file is specified.
18902
18903 @item ^-v^/VERBOSE^
18904 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18905 Verbose mode.
18906
18907 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18908 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18909 Indicates the verbosity of the parsing of GNAT project files.
18910 @xref{Switches Related to Project Files}.
18911
18912 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18913 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18914 Indicates that external variable @var{name} has the value @var{value}.
18915 The Project Manager will use this value for occurrences of
18916 @code{external(name)} when parsing the project file.
18917 @xref{Switches Related to Project Files}.
18918
18919 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18920 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18921 When searching for ALI and object files, look in directory
18922 @var{dir}.
18923
18924 @item ^-I^/SEARCH=^@var{dir}
18925 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18926 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18927
18928 @item ^-I-^/NOCURRENT_DIRECTORY^
18929 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18930 @cindex Source files, suppressing search
18931 Do not look for ALI or object files in the directory
18932 where @code{gnatclean} was invoked.
18933
18934 @end table
18935
18936 @c @node Examples of gnatclean Usage
18937 @c @section Examples of @code{gnatclean} Usage
18938
18939 @ifclear vms
18940 @node GNAT and Libraries
18941 @chapter GNAT and Libraries
18942 @cindex Library, building, installing, using
18943
18944 @noindent
18945 This chapter describes how to build and use libraries with GNAT, and also shows
18946 how to recompile the GNAT run-time library. You should be familiar with the
18947 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18948 chapter.
18949
18950 @menu
18951 * Introduction to Libraries in GNAT::
18952 * General Ada Libraries::
18953 * Stand-alone Ada Libraries::
18954 * Rebuilding the GNAT Run-Time Library::
18955 @end menu
18956
18957 @node Introduction to Libraries in GNAT
18958 @section Introduction to Libraries in GNAT
18959
18960 @noindent
18961 A library is, conceptually, a collection of objects which does not have its
18962 own main thread of execution, but rather provides certain services to the
18963 applications that use it. A library can be either statically linked with the
18964 application, in which case its code is directly included in the application,
18965 or, on platforms that support it, be dynamically linked, in which case
18966 its code is shared by all applications making use of this library.
18967
18968 GNAT supports both types of libraries.
18969 In the static case, the compiled code can be provided in different ways. The
18970 simplest approach is to provide directly the set of objects resulting from
18971 compilation of the library source files. Alternatively, you can group the
18972 objects into an archive using whatever commands are provided by the operating
18973 system. For the latter case, the objects are grouped into a shared library.
18974
18975 In the GNAT environment, a library has three types of components:
18976 @itemize @bullet
18977 @item
18978 Source files.
18979 @item
18980 @file{ALI} files.
18981 @xref{The Ada Library Information Files}.
18982 @item
18983 Object files, an archive or a shared library.
18984 @end itemize
18985
18986 @noindent
18987 A GNAT library may expose all its source files, which is useful for
18988 documentation purposes. Alternatively, it may expose only the units needed by
18989 an external user to make use of the library. That is to say, the specs
18990 reflecting the library services along with all the units needed to compile
18991 those specs, which can include generic bodies or any body implementing an
18992 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18993 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18994
18995 All compilation units comprising an application, including those in a library,
18996 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18997 computes the elaboration order from the @file{ALI} files and this is why they
18998 constitute a mandatory part of GNAT libraries.
18999 @emph{Stand-alone libraries} are the exception to this rule because a specific
19000 library elaboration routine is produced independently of the application(s)
19001 using the library.
19002
19003 @node General Ada Libraries
19004 @section General Ada Libraries
19005
19006 @menu
19007 * Building a library::
19008 * Installing a library::
19009 * Using a library::
19010 @end menu
19011
19012 @node Building a library
19013 @subsection Building a library
19014
19015 @noindent
19016 The easiest way to build a library is to use the Project Manager,
19017 which supports a special type of project called a @emph{Library Project}
19018 (@pxref{Library Projects}).
19019
19020 A project is considered a library project, when two project-level attributes
19021 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19022 control different aspects of library configuration, additional optional
19023 project-level attributes can be specified:
19024 @table @code
19025 @item Library_Kind
19026 This attribute controls whether the library is to be static or dynamic
19027
19028 @item Library_Version
19029 This attribute specifies the library version; this value is used
19030 during dynamic linking of shared libraries to determine if the currently
19031 installed versions of the binaries are compatible.
19032
19033 @item Library_Options
19034 @item Library_GCC
19035 These attributes specify additional low-level options to be used during
19036 library generation, and redefine the actual application used to generate
19037 library.
19038 @end table
19039
19040 @noindent
19041 The GNAT Project Manager takes full care of the library maintenance task,
19042 including recompilation of the source files for which objects do not exist
19043 or are not up to date, assembly of the library archive, and installation of
19044 the library (i.e., copying associated source, object and @file{ALI} files
19045 to the specified location).
19046
19047 Here is a simple library project file:
19048 @smallexample @c ada
19049 project My_Lib is
19050 for Source_Dirs use ("src1", "src2");
19051 for Object_Dir use "obj";
19052 for Library_Name use "mylib";
19053 for Library_Dir use "lib";
19054 for Library_Kind use "dynamic";
19055 end My_lib;
19056 @end smallexample
19057
19058 @noindent
19059 and the compilation command to build and install the library:
19060
19061 @smallexample @c ada
19062 $ gnatmake -Pmy_lib
19063 @end smallexample
19064
19065 @noindent
19066 It is not entirely trivial to perform manually all the steps required to
19067 produce a library. We recommend that you use the GNAT Project Manager
19068 for this task. In special cases where this is not desired, the necessary
19069 steps are discussed below.
19070
19071 There are various possibilities for compiling the units that make up the
19072 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19073 with a conventional script. For simple libraries, it is also possible to create
19074 a dummy main program which depends upon all the packages that comprise the
19075 interface of the library. This dummy main program can then be given to
19076 @command{gnatmake}, which will ensure that all necessary objects are built.
19077
19078 After this task is accomplished, you should follow the standard procedure
19079 of the underlying operating system to produce the static or shared library.
19080
19081 Here is an example of such a dummy program:
19082 @smallexample @c ada
19083 @group
19084 with My_Lib.Service1;
19085 with My_Lib.Service2;
19086 with My_Lib.Service3;
19087 procedure My_Lib_Dummy is
19088 begin
19089 null;
19090 end;
19091 @end group
19092 @end smallexample
19093
19094 @noindent
19095 Here are the generic commands that will build an archive or a shared library.
19096
19097 @smallexample
19098 # compiling the library
19099 $ gnatmake -c my_lib_dummy.adb
19100
19101 # we don't need the dummy object itself
19102 $ rm my_lib_dummy.o my_lib_dummy.ali
19103
19104 # create an archive with the remaining objects
19105 $ ar rc libmy_lib.a *.o
19106 # some systems may require "ranlib" to be run as well
19107
19108 # or create a shared library
19109 $ gcc -shared -o libmy_lib.so *.o
19110 # some systems may require the code to have been compiled with -fPIC
19111
19112 # remove the object files that are now in the library
19113 $ rm *.o
19114
19115 # Make the ALI files read-only so that gnatmake will not try to
19116 # regenerate the objects that are in the library
19117 $ chmod -w *.ali
19118 @end smallexample
19119
19120 @noindent
19121 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19122 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19123 be accessed by the directive @option{-l@var{xxx}} at link time.
19124
19125 @node Installing a library
19126 @subsection Installing a library
19127 @cindex @code{ADA_PROJECT_PATH}
19128 @cindex @code{GPR_PROJECT_PATH}
19129
19130 @noindent
19131 If you use project files, library installation is part of the library build
19132 process. Thus no further action is needed in order to make use of the
19133 libraries that are built as part of the general application build. A usable
19134 version of the library is installed in the directory specified by the
19135 @code{Library_Dir} attribute of the library project file.
19136
19137 You may want to install a library in a context different from where the library
19138 is built. This situation arises with third party suppliers, who may want
19139 to distribute a library in binary form where the user is not expected to be
19140 able to recompile the library. The simplest option in this case is to provide
19141 a project file slightly different from the one used to build the library, by
19142 using the @code{externally_built} attribute. For instance, the project
19143 file used to build the library in the previous section can be changed into the
19144 following one when the library is installed:
19145
19146 @smallexample @c projectfile
19147 project My_Lib is
19148 for Source_Dirs use ("src1", "src2");
19149 for Library_Name use "mylib";
19150 for Library_Dir use "lib";
19151 for Library_Kind use "dynamic";
19152 for Externally_Built use "true";
19153 end My_lib;
19154 @end smallexample
19155
19156 @noindent
19157 This project file assumes that the directories @file{src1},
19158 @file{src2}, and @file{lib} exist in
19159 the directory containing the project file. The @code{externally_built}
19160 attribute makes it clear to the GNAT builder that it should not attempt to
19161 recompile any of the units from this library. It allows the library provider to
19162 restrict the source set to the minimum necessary for clients to make use of the
19163 library as described in the first section of this chapter. It is the
19164 responsibility of the library provider to install the necessary sources, ALI
19165 files and libraries in the directories mentioned in the project file. For
19166 convenience, the user's library project file should be installed in a location
19167 that will be searched automatically by the GNAT
19168 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19169 environment variable (@pxref{Importing Projects}), and also the default GNAT
19170 library location that can be queried with @command{gnatls -v} and is usually of
19171 the form $gnat_install_root/lib/gnat.
19172
19173 When project files are not an option, it is also possible, but not recommended,
19174 to install the library so that the sources needed to use the library are on the
19175 Ada source path and the ALI files & libraries be on the Ada Object path (see
19176 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19177 administrator can place general-purpose libraries in the default compiler
19178 paths, by specifying the libraries' location in the configuration files
19179 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19180 must be located in the GNAT installation tree at the same place as the gcc spec
19181 file. The location of the gcc spec file can be determined as follows:
19182 @smallexample
19183 $ gcc -v
19184 @end smallexample
19185
19186 @noindent
19187 The configuration files mentioned above have a simple format: each line
19188 must contain one unique directory name.
19189 Those names are added to the corresponding path
19190 in their order of appearance in the file. The names can be either absolute
19191 or relative; in the latter case, they are relative to where theses files
19192 are located.
19193
19194 The files @file{ada_source_path} and @file{ada_object_path} might not be
19195 present in a
19196 GNAT installation, in which case, GNAT will look for its run-time library in
19197 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19198 objects and @file{ALI} files). When the files exist, the compiler does not
19199 look in @file{adainclude} and @file{adalib}, and thus the
19200 @file{ada_source_path} file
19201 must contain the location for the GNAT run-time sources (which can simply
19202 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19203 contain the location for the GNAT run-time objects (which can simply
19204 be @file{adalib}).
19205
19206 You can also specify a new default path to the run-time library at compilation
19207 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19208 the run-time library you want your program to be compiled with. This switch is
19209 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19210 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19211
19212 It is possible to install a library before or after the standard GNAT
19213 library, by reordering the lines in the configuration files. In general, a
19214 library must be installed before the GNAT library if it redefines
19215 any part of it.
19216
19217 @node Using a library
19218 @subsection Using a library
19219
19220 @noindent Once again, the project facility greatly simplifies the use of
19221 libraries. In this context, using a library is just a matter of adding a
19222 @code{with} clause in the user project. For instance, to make use of the
19223 library @code{My_Lib} shown in examples in earlier sections, you can
19224 write:
19225
19226 @smallexample @c projectfile
19227 with "my_lib";
19228 project My_Proj is
19229 @dots{}
19230 end My_Proj;
19231 @end smallexample
19232
19233 Even if you have a third-party, non-Ada library, you can still use GNAT's
19234 Project Manager facility to provide a wrapper for it. For example, the
19235 following project, when @code{with}ed by your main project, will link with the
19236 third-party library @file{liba.a}:
19237
19238 @smallexample @c projectfile
19239 @group
19240 project Liba is
19241 for Externally_Built use "true";
19242 for Source_Files use ();
19243 for Library_Dir use "lib";
19244 for Library_Name use "a";
19245 for Library_Kind use "static";
19246 end Liba;
19247 @end group
19248 @end smallexample
19249 This is an alternative to the use of @code{pragma Linker_Options}. It is
19250 especially interesting in the context of systems with several interdependent
19251 static libraries where finding a proper linker order is not easy and best be
19252 left to the tools having visibility over project dependence information.
19253
19254 @noindent
19255 In order to use an Ada library manually, you need to make sure that this
19256 library is on both your source and object path
19257 (see @ref{Search Paths and the Run-Time Library (RTL)}
19258 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19259 in an archive or a shared library, you need to specify the desired
19260 library at link time.
19261
19262 For example, you can use the library @file{mylib} installed in
19263 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19264
19265 @smallexample
19266 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19267 -largs -lmy_lib
19268 @end smallexample
19269
19270 @noindent
19271 This can be expressed more simply:
19272 @smallexample
19273 $ gnatmake my_appl
19274 @end smallexample
19275 @noindent
19276 when the following conditions are met:
19277 @itemize @bullet
19278 @item
19279 @file{/dir/my_lib_src} has been added by the user to the environment
19280 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19281 @file{ada_source_path}
19282 @item
19283 @file{/dir/my_lib_obj} has been added by the user to the environment
19284 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19285 @file{ada_object_path}
19286 @item
19287 a pragma @code{Linker_Options} has been added to one of the sources.
19288 For example:
19289
19290 @smallexample @c ada
19291 pragma Linker_Options ("-lmy_lib");
19292 @end smallexample
19293 @end itemize
19294
19295 @node Stand-alone Ada Libraries
19296 @section Stand-alone Ada Libraries
19297 @cindex Stand-alone library, building, using
19298
19299 @menu
19300 * Introduction to Stand-alone Libraries::
19301 * Building a Stand-alone Library::
19302 * Creating a Stand-alone Library to be used in a non-Ada context::
19303 * Restrictions in Stand-alone Libraries::
19304 @end menu
19305
19306 @node Introduction to Stand-alone Libraries
19307 @subsection Introduction to Stand-alone Libraries
19308
19309 @noindent
19310 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19311 necessary code to
19312 elaborate the Ada units that are included in the library. In contrast with
19313 an ordinary library, which consists of all sources, objects and @file{ALI}
19314 files of the
19315 library, a SAL may specify a restricted subset of compilation units
19316 to serve as a library interface. In this case, the fully
19317 self-sufficient set of files will normally consist of an objects
19318 archive, the sources of interface units' specs, and the @file{ALI}
19319 files of interface units.
19320 If an interface spec contains a generic unit or an inlined subprogram,
19321 the body's
19322 source must also be provided; if the units that must be provided in the source
19323 form depend on other units, the source and @file{ALI} files of those must
19324 also be provided.
19325
19326 The main purpose of a SAL is to minimize the recompilation overhead of client
19327 applications when a new version of the library is installed. Specifically,
19328 if the interface sources have not changed, client applications do not need to
19329 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19330 version, controlled by @code{Library_Version} attribute, is not changed,
19331 then the clients do not need to be relinked.
19332
19333 SALs also allow the library providers to minimize the amount of library source
19334 text exposed to the clients. Such ``information hiding'' might be useful or
19335 necessary for various reasons.
19336
19337 Stand-alone libraries are also well suited to be used in an executable whose
19338 main routine is not written in Ada.
19339
19340 @node Building a Stand-alone Library
19341 @subsection Building a Stand-alone Library
19342
19343 @noindent
19344 GNAT's Project facility provides a simple way of building and installing
19345 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19346 To be a Stand-alone Library Project, in addition to the two attributes
19347 that make a project a Library Project (@code{Library_Name} and
19348 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19349 @code{Library_Interface} must be defined. For example:
19350
19351 @smallexample @c projectfile
19352 @group
19353 for Library_Dir use "lib_dir";
19354 for Library_Name use "dummy";
19355 for Library_Interface use ("int1", "int1.child");
19356 @end group
19357 @end smallexample
19358
19359 @noindent
19360 Attribute @code{Library_Interface} has a non-empty string list value,
19361 each string in the list designating a unit contained in an immediate source
19362 of the project file.
19363
19364 When a Stand-alone Library is built, first the binder is invoked to build
19365 a package whose name depends on the library name
19366 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19367 This binder-generated package includes initialization and
19368 finalization procedures whose
19369 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19370 in the example
19371 above). The object corresponding to this package is included in the library.
19372
19373 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19374 calling of these procedures if a static SAL is built, or if a shared SAL
19375 is built
19376 with the project-level attribute @code{Library_Auto_Init} set to
19377 @code{"false"}.
19378
19379 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19380 (those that are listed in attribute @code{Library_Interface}) are copied to
19381 the Library Directory. As a consequence, only the Interface Units may be
19382 imported from Ada units outside of the library. If other units are imported,
19383 the binding phase will fail.
19384
19385 The attribute @code{Library_Src_Dir} may be specified for a
19386 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19387 single string value. Its value must be the path (absolute or relative to the
19388 project directory) of an existing directory. This directory cannot be the
19389 object directory or one of the source directories, but it can be the same as
19390 the library directory. The sources of the Interface
19391 Units of the library that are needed by an Ada client of the library will be
19392 copied to the designated directory, called the Interface Copy directory.
19393 These sources include the specs of the Interface Units, but they may also
19394 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19395 are used, or when there is a generic unit in the spec. Before the sources
19396 are copied to the Interface Copy directory, an attempt is made to delete all
19397 files in the Interface Copy directory.
19398
19399 Building stand-alone libraries by hand is somewhat tedious, but for those
19400 occasions when it is necessary here are the steps that you need to perform:
19401 @itemize @bullet
19402 @item
19403 Compile all library sources.
19404
19405 @item
19406 Invoke the binder with the switch @option{-n} (No Ada main program),
19407 with all the @file{ALI} files of the interfaces, and
19408 with the switch @option{-L} to give specific names to the @code{init}
19409 and @code{final} procedures. For example:
19410 @smallexample
19411 gnatbind -n int1.ali int2.ali -Lsal1
19412 @end smallexample
19413
19414 @item
19415 Compile the binder generated file:
19416 @smallexample
19417 gcc -c b~int2.adb
19418 @end smallexample
19419
19420 @item
19421 Link the dynamic library with all the necessary object files,
19422 indicating to the linker the names of the @code{init} (and possibly
19423 @code{final}) procedures for automatic initialization (and finalization).
19424 The built library should be placed in a directory different from
19425 the object directory.
19426
19427 @item
19428 Copy the @code{ALI} files of the interface to the library directory,
19429 add in this copy an indication that it is an interface to a SAL
19430 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19431 with letter ``P'') and make the modified copy of the @file{ALI} file
19432 read-only.
19433 @end itemize
19434
19435 @noindent
19436 Using SALs is not different from using other libraries
19437 (see @ref{Using a library}).
19438
19439 @node Creating a Stand-alone Library to be used in a non-Ada context
19440 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19441
19442 @noindent
19443 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19444 a non-Ada context.
19445
19446 The only extra step required is to ensure that library interface subprograms
19447 are compatible with the main program, by means of @code{pragma Export}
19448 or @code{pragma Convention}.
19449
19450 Here is an example of simple library interface for use with C main program:
19451
19452 @smallexample @c ada
19453 package My_Package is
19454
19455 procedure Do_Something;
19456 pragma Export (C, Do_Something, "do_something");
19457
19458 procedure Do_Something_Else;
19459 pragma Export (C, Do_Something_Else, "do_something_else");
19460
19461 end My_Package;
19462 @end smallexample
19463
19464 @noindent
19465 On the foreign language side, you must provide a ``foreign'' view of the
19466 library interface; remember that it should contain elaboration routines in
19467 addition to interface subprograms.
19468
19469 The example below shows the content of @code{mylib_interface.h} (note
19470 that there is no rule for the naming of this file, any name can be used)
19471 @smallexample
19472 /* the library elaboration procedure */
19473 extern void mylibinit (void);
19474
19475 /* the library finalization procedure */
19476 extern void mylibfinal (void);
19477
19478 /* the interface exported by the library */
19479 extern void do_something (void);
19480 extern void do_something_else (void);
19481 @end smallexample
19482
19483 @noindent
19484 Libraries built as explained above can be used from any program, provided
19485 that the elaboration procedures (named @code{mylibinit} in the previous
19486 example) are called before the library services are used. Any number of
19487 libraries can be used simultaneously, as long as the elaboration
19488 procedure of each library is called.
19489
19490 Below is an example of a C program that uses the @code{mylib} library.
19491
19492 @smallexample
19493 #include "mylib_interface.h"
19494
19495 int
19496 main (void)
19497 @{
19498 /* First, elaborate the library before using it */
19499 mylibinit ();
19500
19501 /* Main program, using the library exported entities */
19502 do_something ();
19503 do_something_else ();
19504
19505 /* Library finalization at the end of the program */
19506 mylibfinal ();
19507 return 0;
19508 @}
19509 @end smallexample
19510
19511 @noindent
19512 Note that invoking any library finalization procedure generated by
19513 @code{gnatbind} shuts down the Ada run-time environment.
19514 Consequently, the
19515 finalization of all Ada libraries must be performed at the end of the program.
19516 No call to these libraries or to the Ada run-time library should be made
19517 after the finalization phase.
19518
19519 @node Restrictions in Stand-alone Libraries
19520 @subsection Restrictions in Stand-alone Libraries
19521
19522 @noindent
19523 The pragmas listed below should be used with caution inside libraries,
19524 as they can create incompatibilities with other Ada libraries:
19525 @itemize @bullet
19526 @item pragma @code{Locking_Policy}
19527 @item pragma @code{Queuing_Policy}
19528 @item pragma @code{Task_Dispatching_Policy}
19529 @item pragma @code{Unreserve_All_Interrupts}
19530 @end itemize
19531
19532 @noindent
19533 When using a library that contains such pragmas, the user must make sure
19534 that all libraries use the same pragmas with the same values. Otherwise,
19535 @code{Program_Error} will
19536 be raised during the elaboration of the conflicting
19537 libraries. The usage of these pragmas and its consequences for the user
19538 should therefore be well documented.
19539
19540 Similarly, the traceback in the exception occurrence mechanism should be
19541 enabled or disabled in a consistent manner across all libraries.
19542 Otherwise, Program_Error will be raised during the elaboration of the
19543 conflicting libraries.
19544
19545 If the @code{Version} or @code{Body_Version}
19546 attributes are used inside a library, then you need to
19547 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19548 libraries, so that version identifiers can be properly computed.
19549 In practice these attributes are rarely used, so this is unlikely
19550 to be a consideration.
19551
19552 @node Rebuilding the GNAT Run-Time Library
19553 @section Rebuilding the GNAT Run-Time Library
19554 @cindex GNAT Run-Time Library, rebuilding
19555 @cindex Building the GNAT Run-Time Library
19556 @cindex Rebuilding the GNAT Run-Time Library
19557 @cindex Run-Time Library, rebuilding
19558
19559 @noindent
19560 It may be useful to recompile the GNAT library in various contexts, the
19561 most important one being the use of partition-wide configuration pragmas
19562 such as @code{Normalize_Scalars}. A special Makefile called
19563 @code{Makefile.adalib} is provided to that effect and can be found in
19564 the directory containing the GNAT library. The location of this
19565 directory depends on the way the GNAT environment has been installed and can
19566 be determined by means of the command:
19567
19568 @smallexample
19569 $ gnatls -v
19570 @end smallexample
19571
19572 @noindent
19573 The last entry in the object search path usually contains the
19574 gnat library. This Makefile contains its own documentation and in
19575 particular the set of instructions needed to rebuild a new library and
19576 to use it.
19577
19578 @node Using the GNU make Utility
19579 @chapter Using the GNU @code{make} Utility
19580 @findex make
19581
19582 @noindent
19583 This chapter offers some examples of makefiles that solve specific
19584 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19585 make, make, GNU @code{make}}), nor does it try to replace the
19586 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19587
19588 All the examples in this section are specific to the GNU version of
19589 make. Although @command{make} is a standard utility, and the basic language
19590 is the same, these examples use some advanced features found only in
19591 @code{GNU make}.
19592
19593 @menu
19594 * Using gnatmake in a Makefile::
19595 * Automatically Creating a List of Directories::
19596 * Generating the Command Line Switches::
19597 * Overcoming Command Line Length Limits::
19598 @end menu
19599
19600 @node Using gnatmake in a Makefile
19601 @section Using gnatmake in a Makefile
19602 @findex makefile
19603 @cindex GNU make
19604
19605 @noindent
19606 Complex project organizations can be handled in a very powerful way by
19607 using GNU make combined with gnatmake. For instance, here is a Makefile
19608 which allows you to build each subsystem of a big project into a separate
19609 shared library. Such a makefile allows you to significantly reduce the link
19610 time of very big applications while maintaining full coherence at
19611 each step of the build process.
19612
19613 The list of dependencies are handled automatically by
19614 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19615 the appropriate directories.
19616
19617 Note that you should also read the example on how to automatically
19618 create the list of directories
19619 (@pxref{Automatically Creating a List of Directories})
19620 which might help you in case your project has a lot of subdirectories.
19621
19622 @smallexample
19623 @iftex
19624 @leftskip=0cm
19625 @font@heightrm=cmr8
19626 @heightrm
19627 @end iftex
19628 ## This Makefile is intended to be used with the following directory
19629 ## configuration:
19630 ## - The sources are split into a series of csc (computer software components)
19631 ## Each of these csc is put in its own directory.
19632 ## Their name are referenced by the directory names.
19633 ## They will be compiled into shared library (although this would also work
19634 ## with static libraries
19635 ## - The main program (and possibly other packages that do not belong to any
19636 ## csc is put in the top level directory (where the Makefile is).
19637 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
19638 ## \_ second_csc (sources) __ lib (will contain the library)
19639 ## \_ @dots{}
19640 ## Although this Makefile is build for shared library, it is easy to modify
19641 ## to build partial link objects instead (modify the lines with -shared and
19642 ## gnatlink below)
19643 ##
19644 ## With this makefile, you can change any file in the system or add any new
19645 ## file, and everything will be recompiled correctly (only the relevant shared
19646 ## objects will be recompiled, and the main program will be re-linked).
19647
19648 # The list of computer software component for your project. This might be
19649 # generated automatically.
19650 CSC_LIST=aa bb cc
19651
19652 # Name of the main program (no extension)
19653 MAIN=main
19654
19655 # If we need to build objects with -fPIC, uncomment the following line
19656 #NEED_FPIC=-fPIC
19657
19658 # The following variable should give the directory containing libgnat.so
19659 # You can get this directory through 'gnatls -v'. This is usually the last
19660 # directory in the Object_Path.
19661 GLIB=@dots{}
19662
19663 # The directories for the libraries
19664 # (This macro expands the list of CSC to the list of shared libraries, you
19665 # could simply use the expanded form:
19666 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19667 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19668
19669 $@{MAIN@}: objects $@{LIB_DIR@}
19670 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19671 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19672
19673 objects::
19674 # recompile the sources
19675 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19676
19677 # Note: In a future version of GNAT, the following commands will be simplified
19678 # by a new tool, gnatmlib
19679 $@{LIB_DIR@}:
19680 mkdir -p $@{dir $@@ @}
19681 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19682 cd $@{dir $@@ @} && cp -f ../*.ali .
19683
19684 # The dependencies for the modules
19685 # Note that we have to force the expansion of *.o, since in some cases
19686 # make won't be able to do it itself.
19687 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19688 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19689 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19690
19691 # Make sure all of the shared libraries are in the path before starting the
19692 # program
19693 run::
19694 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19695
19696 clean::
19697 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19698 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19699 $@{RM@} $@{CSC_LIST:%=%/*.o@}
19700 $@{RM@} *.o *.ali $@{MAIN@}
19701 @end smallexample
19702
19703 @node Automatically Creating a List of Directories
19704 @section Automatically Creating a List of Directories
19705
19706 @noindent
19707 In most makefiles, you will have to specify a list of directories, and
19708 store it in a variable. For small projects, it is often easier to
19709 specify each of them by hand, since you then have full control over what
19710 is the proper order for these directories, which ones should be
19711 included.
19712
19713 However, in larger projects, which might involve hundreds of
19714 subdirectories, it might be more convenient to generate this list
19715 automatically.
19716
19717 The example below presents two methods. The first one, although less
19718 general, gives you more control over the list. It involves wildcard
19719 characters, that are automatically expanded by @command{make}. Its
19720 shortcoming is that you need to explicitly specify some of the
19721 organization of your project, such as for instance the directory tree
19722 depth, whether some directories are found in a separate tree, @enddots{}
19723
19724 The second method is the most general one. It requires an external
19725 program, called @command{find}, which is standard on all Unix systems. All
19726 the directories found under a given root directory will be added to the
19727 list.
19728
19729 @smallexample
19730 @iftex
19731 @leftskip=0cm
19732 @font@heightrm=cmr8
19733 @heightrm
19734 @end iftex
19735 # The examples below are based on the following directory hierarchy:
19736 # All the directories can contain any number of files
19737 # ROOT_DIRECTORY -> a -> aa -> aaa
19738 # -> ab
19739 # -> ac
19740 # -> b -> ba -> baa
19741 # -> bb
19742 # -> bc
19743 # This Makefile creates a variable called DIRS, that can be reused any time
19744 # you need this list (see the other examples in this section)
19745
19746 # The root of your project's directory hierarchy
19747 ROOT_DIRECTORY=.
19748
19749 ####
19750 # First method: specify explicitly the list of directories
19751 # This allows you to specify any subset of all the directories you need.
19752 ####
19753
19754 DIRS := a/aa/ a/ab/ b/ba/
19755
19756 ####
19757 # Second method: use wildcards
19758 # Note that the argument(s) to wildcard below should end with a '/'.
19759 # Since wildcards also return file names, we have to filter them out
19760 # to avoid duplicate directory names.
19761 # We thus use make's @code{dir} and @code{sort} functions.
19762 # It sets DIRs to the following value (note that the directories aaa and baa
19763 # are not given, unless you change the arguments to wildcard).
19764 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19765 ####
19766
19767 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19768 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19769
19770 ####
19771 # Third method: use an external program
19772 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19773 # This is the most complete command: it sets DIRs to the following value:
19774 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19775 ####
19776
19777 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19778
19779 @end smallexample
19780
19781 @node Generating the Command Line Switches
19782 @section Generating the Command Line Switches
19783
19784 @noindent
19785 Once you have created the list of directories as explained in the
19786 previous section (@pxref{Automatically Creating a List of Directories}),
19787 you can easily generate the command line arguments to pass to gnatmake.
19788
19789 For the sake of completeness, this example assumes that the source path
19790 is not the same as the object path, and that you have two separate lists
19791 of directories.
19792
19793 @smallexample
19794 # see "Automatically creating a list of directories" to create
19795 # these variables
19796 SOURCE_DIRS=
19797 OBJECT_DIRS=
19798
19799 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19800 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19801
19802 all:
19803 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19804 @end smallexample
19805
19806 @node Overcoming Command Line Length Limits
19807 @section Overcoming Command Line Length Limits
19808
19809 @noindent
19810 One problem that might be encountered on big projects is that many
19811 operating systems limit the length of the command line. It is thus hard to give
19812 gnatmake the list of source and object directories.
19813
19814 This example shows how you can set up environment variables, which will
19815 make @command{gnatmake} behave exactly as if the directories had been
19816 specified on the command line, but have a much higher length limit (or
19817 even none on most systems).
19818
19819 It assumes that you have created a list of directories in your Makefile,
19820 using one of the methods presented in
19821 @ref{Automatically Creating a List of Directories}.
19822 For the sake of completeness, we assume that the object
19823 path (where the ALI files are found) is different from the sources patch.
19824
19825 Note a small trick in the Makefile below: for efficiency reasons, we
19826 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19827 expanded immediately by @code{make}. This way we overcome the standard
19828 make behavior which is to expand the variables only when they are
19829 actually used.
19830
19831 On Windows, if you are using the standard Windows command shell, you must
19832 replace colons with semicolons in the assignments to these variables.
19833
19834 @smallexample
19835 @iftex
19836 @leftskip=0cm
19837 @font@heightrm=cmr8
19838 @heightrm
19839 @end iftex
19840 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19841 # This is the same thing as putting the -I arguments on the command line.
19842 # (the equivalent of using -aI on the command line would be to define
19843 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19844 # You can of course have different values for these variables.
19845 #
19846 # Note also that we need to keep the previous values of these variables, since
19847 # they might have been set before running 'make' to specify where the GNAT
19848 # library is installed.
19849
19850 # see "Automatically creating a list of directories" to create these
19851 # variables
19852 SOURCE_DIRS=
19853 OBJECT_DIRS=
19854
19855 empty:=
19856 space:=$@{empty@} $@{empty@}
19857 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19858 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19859 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19860 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19861 export ADA_INCLUDE_PATH
19862 export ADA_OBJECT_PATH
19863
19864 all:
19865 gnatmake main_unit
19866 @end smallexample
19867 @end ifclear
19868
19869 @node Memory Management Issues
19870 @chapter Memory Management Issues
19871
19872 @noindent
19873 This chapter describes some useful memory pools provided in the GNAT library
19874 and in particular the GNAT Debug Pool facility, which can be used to detect
19875 incorrect uses of access values (including ``dangling references'').
19876 @ifclear vms
19877 It also describes the @command{gnatmem} tool, which can be used to track down
19878 ``memory leaks''.
19879 @end ifclear
19880
19881 @menu
19882 * Some Useful Memory Pools::
19883 * The GNAT Debug Pool Facility::
19884 @ifclear vms
19885 * The gnatmem Tool::
19886 @end ifclear
19887 @end menu
19888
19889 @node Some Useful Memory Pools
19890 @section Some Useful Memory Pools
19891 @findex Memory Pool
19892 @cindex storage, pool
19893
19894 @noindent
19895 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19896 storage pool. Allocations use the standard system call @code{malloc} while
19897 deallocations use the standard system call @code{free}. No reclamation is
19898 performed when the pool goes out of scope. For performance reasons, the
19899 standard default Ada allocators/deallocators do not use any explicit storage
19900 pools but if they did, they could use this storage pool without any change in
19901 behavior. That is why this storage pool is used when the user
19902 manages to make the default implicit allocator explicit as in this example:
19903 @smallexample @c ada
19904 type T1 is access Something;
19905 -- no Storage pool is defined for T2
19906 type T2 is access Something_Else;
19907 for T2'Storage_Pool use T1'Storage_Pool;
19908 -- the above is equivalent to
19909 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19910 @end smallexample
19911
19912 @noindent
19913 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19914 pool. The allocation strategy is similar to @code{Pool_Local}'s
19915 except that the all
19916 storage allocated with this pool is reclaimed when the pool object goes out of
19917 scope. This pool provides a explicit mechanism similar to the implicit one
19918 provided by several Ada 83 compilers for allocations performed through a local
19919 access type and whose purpose was to reclaim memory when exiting the
19920 scope of a given local access. As an example, the following program does not
19921 leak memory even though it does not perform explicit deallocation:
19922
19923 @smallexample @c ada
19924 with System.Pool_Local;
19925 procedure Pooloc1 is
19926 procedure Internal is
19927 type A is access Integer;
19928 X : System.Pool_Local.Unbounded_Reclaim_Pool;
19929 for A'Storage_Pool use X;
19930 v : A;
19931 begin
19932 for I in 1 .. 50 loop
19933 v := new Integer;
19934 end loop;
19935 end Internal;
19936 begin
19937 for I in 1 .. 100 loop
19938 Internal;
19939 end loop;
19940 end Pooloc1;
19941 @end smallexample
19942
19943 @noindent
19944 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19945 @code{Storage_Size} is specified for an access type.
19946 The whole storage for the pool is
19947 allocated at once, usually on the stack at the point where the access type is
19948 elaborated. It is automatically reclaimed when exiting the scope where the
19949 access type is defined. This package is not intended to be used directly by the
19950 user and it is implicitly used for each such declaration:
19951
19952 @smallexample @c ada
19953 type T1 is access Something;
19954 for T1'Storage_Size use 10_000;
19955 @end smallexample
19956
19957 @node The GNAT Debug Pool Facility
19958 @section The GNAT Debug Pool Facility
19959 @findex Debug Pool
19960 @cindex storage, pool, memory corruption
19961
19962 @noindent
19963 The use of unchecked deallocation and unchecked conversion can easily
19964 lead to incorrect memory references. The problems generated by such
19965 references are usually difficult to tackle because the symptoms can be
19966 very remote from the origin of the problem. In such cases, it is
19967 very helpful to detect the problem as early as possible. This is the
19968 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19969
19970 In order to use the GNAT specific debugging pool, the user must
19971 associate a debug pool object with each of the access types that may be
19972 related to suspected memory problems. See Ada Reference Manual 13.11.
19973 @smallexample @c ada
19974 type Ptr is access Some_Type;
19975 Pool : GNAT.Debug_Pools.Debug_Pool;
19976 for Ptr'Storage_Pool use Pool;
19977 @end smallexample
19978
19979 @noindent
19980 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19981 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19982 allow the user to redefine allocation and deallocation strategies. They
19983 also provide a checkpoint for each dereference, through the use of
19984 the primitive operation @code{Dereference} which is implicitly called at
19985 each dereference of an access value.
19986
19987 Once an access type has been associated with a debug pool, operations on
19988 values of the type may raise four distinct exceptions,
19989 which correspond to four potential kinds of memory corruption:
19990 @itemize @bullet
19991 @item
19992 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19993 @item
19994 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19995 @item
19996 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19997 @item
19998 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19999 @end itemize
20000
20001 @noindent
20002 For types associated with a Debug_Pool, dynamic allocation is performed using
20003 the standard GNAT allocation routine. References to all allocated chunks of
20004 memory are kept in an internal dictionary. Several deallocation strategies are
20005 provided, whereupon the user can choose to release the memory to the system,
20006 keep it allocated for further invalid access checks, or fill it with an easily
20007 recognizable pattern for debug sessions. The memory pattern is the old IBM
20008 hexadecimal convention: @code{16#DEADBEEF#}.
20009
20010 See the documentation in the file g-debpoo.ads for more information on the
20011 various strategies.
20012
20013 Upon each dereference, a check is made that the access value denotes a
20014 properly allocated memory location. Here is a complete example of use of
20015 @code{Debug_Pools}, that includes typical instances of memory corruption:
20016 @smallexample @c ada
20017 @iftex
20018 @leftskip=0cm
20019 @end iftex
20020 with Gnat.Io; use Gnat.Io;
20021 with Unchecked_Deallocation;
20022 with Unchecked_Conversion;
20023 with GNAT.Debug_Pools;
20024 with System.Storage_Elements;
20025 with Ada.Exceptions; use Ada.Exceptions;
20026 procedure Debug_Pool_Test is
20027
20028 type T is access Integer;
20029 type U is access all T;
20030
20031 P : GNAT.Debug_Pools.Debug_Pool;
20032 for T'Storage_Pool use P;
20033
20034 procedure Free is new Unchecked_Deallocation (Integer, T);
20035 function UC is new Unchecked_Conversion (U, T);
20036 A, B : aliased T;
20037
20038 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20039
20040 begin
20041 Info (P);
20042 A := new Integer;
20043 B := new Integer;
20044 B := A;
20045 Info (P);
20046 Free (A);
20047 begin
20048 Put_Line (Integer'Image(B.all));
20049 exception
20050 when E : others => Put_Line ("raised: " & Exception_Name (E));
20051 end;
20052 begin
20053 Free (B);
20054 exception
20055 when E : others => Put_Line ("raised: " & Exception_Name (E));
20056 end;
20057 B := UC(A'Access);
20058 begin
20059 Put_Line (Integer'Image(B.all));
20060 exception
20061 when E : others => Put_Line ("raised: " & Exception_Name (E));
20062 end;
20063 begin
20064 Free (B);
20065 exception
20066 when E : others => Put_Line ("raised: " & Exception_Name (E));
20067 end;
20068 Info (P);
20069 end Debug_Pool_Test;
20070 @end smallexample
20071
20072 @noindent
20073 The debug pool mechanism provides the following precise diagnostics on the
20074 execution of this erroneous program:
20075 @smallexample
20076 Debug Pool info:
20077 Total allocated bytes : 0
20078 Total deallocated bytes : 0
20079 Current Water Mark: 0
20080 High Water Mark: 0
20081
20082 Debug Pool info:
20083 Total allocated bytes : 8
20084 Total deallocated bytes : 0
20085 Current Water Mark: 8
20086 High Water Mark: 8
20087
20088 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20089 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20090 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20091 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20092 Debug Pool info:
20093 Total allocated bytes : 8
20094 Total deallocated bytes : 4
20095 Current Water Mark: 4
20096 High Water Mark: 8
20097 @end smallexample
20098
20099 @ifclear vms
20100 @node The gnatmem Tool
20101 @section The @command{gnatmem} Tool
20102 @findex gnatmem
20103
20104 @noindent
20105 The @code{gnatmem} utility monitors dynamic allocation and
20106 deallocation activity in a program, and displays information about
20107 incorrect deallocations and possible sources of memory leaks.
20108 It is designed to work in association with a static runtime library
20109 only and in this context provides three types of information:
20110 @itemize @bullet
20111 @item
20112 General information concerning memory management, such as the total
20113 number of allocations and deallocations, the amount of allocated
20114 memory and the high water mark, i.e.@: the largest amount of allocated
20115 memory in the course of program execution.
20116
20117 @item
20118 Backtraces for all incorrect deallocations, that is to say deallocations
20119 which do not correspond to a valid allocation.
20120
20121 @item
20122 Information on each allocation that is potentially the origin of a memory
20123 leak.
20124 @end itemize
20125
20126 @menu
20127 * Running gnatmem::
20128 * Switches for gnatmem::
20129 * Example of gnatmem Usage::
20130 @end menu
20131
20132 @node Running gnatmem
20133 @subsection Running @code{gnatmem}
20134
20135 @noindent
20136 @code{gnatmem} makes use of the output created by the special version of
20137 allocation and deallocation routines that record call information. This
20138 allows to obtain accurate dynamic memory usage history at a minimal cost to
20139 the execution speed. Note however, that @code{gnatmem} is not supported on
20140 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20141 Solaris and Windows NT/2000/XP (x86).
20142
20143 @noindent
20144 The @code{gnatmem} command has the form
20145
20146 @smallexample
20147 $ gnatmem @ovar{switches} user_program
20148 @end smallexample
20149
20150 @noindent
20151 The program must have been linked with the instrumented version of the
20152 allocation and deallocation routines. This is done by linking with the
20153 @file{libgmem.a} library. For correct symbolic backtrace information,
20154 the user program should be compiled with debugging options
20155 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20156
20157 @smallexample
20158 $ gnatmake -g my_program -largs -lgmem
20159 @end smallexample
20160
20161 @noindent
20162 As library @file{libgmem.a} contains an alternate body for package
20163 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20164 when an executable is linked with library @file{libgmem.a}. It is then not
20165 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20166
20167 @noindent
20168 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20169 This file contains information about all allocations and deallocations
20170 performed by the program. It is produced by the instrumented allocations and
20171 deallocations routines and will be used by @code{gnatmem}.
20172
20173 In order to produce symbolic backtrace information for allocations and
20174 deallocations performed by the GNAT run-time library, you need to use a
20175 version of that library that has been compiled with the @option{-g} switch
20176 (see @ref{Rebuilding the GNAT Run-Time Library}).
20177
20178 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20179 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20180 @option{-i} switch, gnatmem will assume that this file can be found in the
20181 current directory. For example, after you have executed @file{my_program},
20182 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20183
20184 @smallexample
20185 $ gnatmem my_program
20186 @end smallexample
20187
20188 @noindent
20189 This will produce the output with the following format:
20190
20191 *************** debut cc
20192 @smallexample
20193 $ gnatmem my_program
20194
20195 Global information
20196 ------------------
20197 Total number of allocations : 45
20198 Total number of deallocations : 6
20199 Final Water Mark (non freed mem) : 11.29 Kilobytes
20200 High Water Mark : 11.40 Kilobytes
20201
20202 .
20203 .
20204 .
20205 Allocation Root # 2
20206 -------------------
20207 Number of non freed allocations : 11
20208 Final Water Mark (non freed mem) : 1.16 Kilobytes
20209 High Water Mark : 1.27 Kilobytes
20210 Backtrace :
20211 my_program.adb:23 my_program.alloc
20212 .
20213 .
20214 .
20215 @end smallexample
20216
20217 The first block of output gives general information. In this case, the
20218 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20219 Unchecked_Deallocation routine occurred.
20220
20221 @noindent
20222 Subsequent paragraphs display information on all allocation roots.
20223 An allocation root is a specific point in the execution of the program
20224 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20225 construct. This root is represented by an execution backtrace (or subprogram
20226 call stack). By default the backtrace depth for allocations roots is 1, so
20227 that a root corresponds exactly to a source location. The backtrace can
20228 be made deeper, to make the root more specific.
20229
20230 @node Switches for gnatmem
20231 @subsection Switches for @code{gnatmem}
20232
20233 @noindent
20234 @code{gnatmem} recognizes the following switches:
20235
20236 @table @option
20237
20238 @item -q
20239 @cindex @option{-q} (@code{gnatmem})
20240 Quiet. Gives the minimum output needed to identify the origin of the
20241 memory leaks. Omits statistical information.
20242
20243 @item @var{N}
20244 @cindex @var{N} (@code{gnatmem})
20245 N is an integer literal (usually between 1 and 10) which controls the
20246 depth of the backtraces defining allocation root. The default value for
20247 N is 1. The deeper the backtrace, the more precise the localization of
20248 the root. Note that the total number of roots can depend on this
20249 parameter. This parameter must be specified @emph{before} the name of the
20250 executable to be analyzed, to avoid ambiguity.
20251
20252 @item -b n
20253 @cindex @option{-b} (@code{gnatmem})
20254 This switch has the same effect as just depth parameter.
20255
20256 @item -i @var{file}
20257 @cindex @option{-i} (@code{gnatmem})
20258 Do the @code{gnatmem} processing starting from @file{file}, rather than
20259 @file{gmem.out} in the current directory.
20260
20261 @item -m n
20262 @cindex @option{-m} (@code{gnatmem})
20263 This switch causes @code{gnatmem} to mask the allocation roots that have less
20264 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20265 examine even the roots that didn't result in leaks.
20266
20267 @item -s order
20268 @cindex @option{-s} (@code{gnatmem})
20269 This switch causes @code{gnatmem} to sort the allocation roots according to the
20270 specified order of sort criteria, each identified by a single letter. The
20271 currently supported criteria are @code{n, h, w} standing respectively for
20272 number of unfreed allocations, high watermark, and final watermark
20273 corresponding to a specific root. The default order is @code{nwh}.
20274
20275 @end table
20276
20277 @node Example of gnatmem Usage
20278 @subsection Example of @code{gnatmem} Usage
20279
20280 @noindent
20281 The following example shows the use of @code{gnatmem}
20282 on a simple memory-leaking program.
20283 Suppose that we have the following Ada program:
20284
20285 @smallexample @c ada
20286 @group
20287 @cartouche
20288 with Unchecked_Deallocation;
20289 procedure Test_Gm is
20290
20291 type T is array (1..1000) of Integer;
20292 type Ptr is access T;
20293 procedure Free is new Unchecked_Deallocation (T, Ptr);
20294 A : Ptr;
20295
20296 procedure My_Alloc is
20297 begin
20298 A := new T;
20299 end My_Alloc;
20300
20301 procedure My_DeAlloc is
20302 B : Ptr := A;
20303 begin
20304 Free (B);
20305 end My_DeAlloc;
20306
20307 begin
20308 My_Alloc;
20309 for I in 1 .. 5 loop
20310 for J in I .. 5 loop
20311 My_Alloc;
20312 end loop;
20313 My_Dealloc;
20314 end loop;
20315 end;
20316 @end cartouche
20317 @end group
20318 @end smallexample
20319
20320 @noindent
20321 The program needs to be compiled with debugging option and linked with
20322 @code{gmem} library:
20323
20324 @smallexample
20325 $ gnatmake -g test_gm -largs -lgmem
20326 @end smallexample
20327
20328 @noindent
20329 Then we execute the program as usual:
20330
20331 @smallexample
20332 $ test_gm
20333 @end smallexample
20334
20335 @noindent
20336 Then @code{gnatmem} is invoked simply with
20337 @smallexample
20338 $ gnatmem test_gm
20339 @end smallexample
20340
20341 @noindent
20342 which produces the following output (result may vary on different platforms):
20343
20344 @smallexample
20345 Global information
20346 ------------------
20347 Total number of allocations : 18
20348 Total number of deallocations : 5
20349 Final Water Mark (non freed mem) : 53.00 Kilobytes
20350 High Water Mark : 56.90 Kilobytes
20351
20352 Allocation Root # 1
20353 -------------------
20354 Number of non freed allocations : 11
20355 Final Water Mark (non freed mem) : 42.97 Kilobytes
20356 High Water Mark : 46.88 Kilobytes
20357 Backtrace :
20358 test_gm.adb:11 test_gm.my_alloc
20359
20360 Allocation Root # 2
20361 -------------------
20362 Number of non freed allocations : 1
20363 Final Water Mark (non freed mem) : 10.02 Kilobytes
20364 High Water Mark : 10.02 Kilobytes
20365 Backtrace :
20366 s-secsta.adb:81 system.secondary_stack.ss_init
20367
20368 Allocation Root # 3
20369 -------------------
20370 Number of non freed allocations : 1
20371 Final Water Mark (non freed mem) : 12 Bytes
20372 High Water Mark : 12 Bytes
20373 Backtrace :
20374 s-secsta.adb:181 system.secondary_stack.ss_init
20375 @end smallexample
20376
20377 @noindent
20378 Note that the GNAT run time contains itself a certain number of
20379 allocations that have no corresponding deallocation,
20380 as shown here for root #2 and root
20381 #3. This is a normal behavior when the number of non-freed allocations
20382 is one, it allocates dynamic data structures that the run time needs for
20383 the complete lifetime of the program. Note also that there is only one
20384 allocation root in the user program with a single line back trace:
20385 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20386 program shows that 'My_Alloc' is called at 2 different points in the
20387 source (line 21 and line 24). If those two allocation roots need to be
20388 distinguished, the backtrace depth parameter can be used:
20389
20390 @smallexample
20391 $ gnatmem 3 test_gm
20392 @end smallexample
20393
20394 @noindent
20395 which will give the following output:
20396
20397 @smallexample
20398 Global information
20399 ------------------
20400 Total number of allocations : 18
20401 Total number of deallocations : 5
20402 Final Water Mark (non freed mem) : 53.00 Kilobytes
20403 High Water Mark : 56.90 Kilobytes
20404
20405 Allocation Root # 1
20406 -------------------
20407 Number of non freed allocations : 10
20408 Final Water Mark (non freed mem) : 39.06 Kilobytes
20409 High Water Mark : 42.97 Kilobytes
20410 Backtrace :
20411 test_gm.adb:11 test_gm.my_alloc
20412 test_gm.adb:24 test_gm
20413 b_test_gm.c:52 main
20414
20415 Allocation Root # 2
20416 -------------------
20417 Number of non freed allocations : 1
20418 Final Water Mark (non freed mem) : 10.02 Kilobytes
20419 High Water Mark : 10.02 Kilobytes
20420 Backtrace :
20421 s-secsta.adb:81 system.secondary_stack.ss_init
20422 s-secsta.adb:283 <system__secondary_stack___elabb>
20423 b_test_gm.c:33 adainit
20424
20425 Allocation Root # 3
20426 -------------------
20427 Number of non freed allocations : 1
20428 Final Water Mark (non freed mem) : 3.91 Kilobytes
20429 High Water Mark : 3.91 Kilobytes
20430 Backtrace :
20431 test_gm.adb:11 test_gm.my_alloc
20432 test_gm.adb:21 test_gm
20433 b_test_gm.c:52 main
20434
20435 Allocation Root # 4
20436 -------------------
20437 Number of non freed allocations : 1
20438 Final Water Mark (non freed mem) : 12 Bytes
20439 High Water Mark : 12 Bytes
20440 Backtrace :
20441 s-secsta.adb:181 system.secondary_stack.ss_init
20442 s-secsta.adb:283 <system__secondary_stack___elabb>
20443 b_test_gm.c:33 adainit
20444 @end smallexample
20445
20446 @noindent
20447 The allocation root #1 of the first example has been split in 2 roots #1
20448 and #3 thanks to the more precise associated backtrace.
20449
20450 @end ifclear
20451
20452 @node Stack Related Facilities
20453 @chapter Stack Related Facilities
20454
20455 @noindent
20456 This chapter describes some useful tools associated with stack
20457 checking and analysis. In
20458 particular, it deals with dynamic and static stack usage measurements.
20459
20460 @menu
20461 * Stack Overflow Checking::
20462 * Static Stack Usage Analysis::
20463 * Dynamic Stack Usage Analysis::
20464 @end menu
20465
20466 @node Stack Overflow Checking
20467 @section Stack Overflow Checking
20468 @cindex Stack Overflow Checking
20469 @cindex -fstack-check
20470
20471 @noindent
20472 For most operating systems, @command{gcc} does not perform stack overflow
20473 checking by default. This means that if the main environment task or
20474 some other task exceeds the available stack space, then unpredictable
20475 behavior will occur. Most native systems offer some level of protection by
20476 adding a guard page at the end of each task stack. This mechanism is usually
20477 not enough for dealing properly with stack overflow situations because
20478 a large local variable could ``jump'' above the guard page.
20479 Furthermore, when the
20480 guard page is hit, there may not be any space left on the stack for executing
20481 the exception propagation code. Enabling stack checking avoids
20482 such situations.
20483
20484 To activate stack checking, compile all units with the gcc option
20485 @option{-fstack-check}. For example:
20486
20487 @smallexample
20488 gcc -c -fstack-check package1.adb
20489 @end smallexample
20490
20491 @noindent
20492 Units compiled with this option will generate extra instructions to check
20493 that any use of the stack (for procedure calls or for declaring local
20494 variables in declare blocks) does not exceed the available stack space.
20495 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20496
20497 For declared tasks, the stack size is controlled by the size
20498 given in an applicable @code{Storage_Size} pragma or by the value specified
20499 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20500 the default size as defined in the GNAT runtime otherwise.
20501
20502 For the environment task, the stack size depends on
20503 system defaults and is unknown to the compiler. Stack checking
20504 may still work correctly if a fixed
20505 size stack is allocated, but this cannot be guaranteed.
20506 @ifclear vms
20507 To ensure that a clean exception is signalled for stack
20508 overflow, set the environment variable
20509 @env{GNAT_STACK_LIMIT} to indicate the maximum
20510 stack area that can be used, as in:
20511 @cindex GNAT_STACK_LIMIT
20512
20513 @smallexample
20514 SET GNAT_STACK_LIMIT 1600
20515 @end smallexample
20516
20517 @noindent
20518 The limit is given in kilobytes, so the above declaration would
20519 set the stack limit of the environment task to 1.6 megabytes.
20520 Note that the only purpose of this usage is to limit the amount
20521 of stack used by the environment task. If it is necessary to
20522 increase the amount of stack for the environment task, then this
20523 is an operating systems issue, and must be addressed with the
20524 appropriate operating systems commands.
20525 @end ifclear
20526 @ifset vms
20527 To have a fixed size stack in the environment task, the stack must be put
20528 in the P0 address space and its size specified. Use these switches to
20529 create a p0 image:
20530
20531 @smallexample
20532 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20533 @end smallexample
20534
20535 @noindent
20536 The quotes are required to keep case. The number after @samp{STACK=} is the
20537 size of the environmental task stack in pagelets (512 bytes). In this example
20538 the stack size is about 2 megabytes.
20539
20540 @noindent
20541 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20542 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
20543 more details about the @option{/p0image} qualifier and the @option{stack}
20544 option.
20545 @end ifset
20546
20547 @node Static Stack Usage Analysis
20548 @section Static Stack Usage Analysis
20549 @cindex Static Stack Usage Analysis
20550 @cindex -fstack-usage
20551
20552 @noindent
20553 A unit compiled with @option{-fstack-usage} will generate an extra file
20554 that specifies
20555 the maximum amount of stack used, on a per-function basis.
20556 The file has the same
20557 basename as the target object file with a @file{.su} extension.
20558 Each line of this file is made up of three fields:
20559
20560 @itemize
20561 @item
20562 The name of the function.
20563 @item
20564 A number of bytes.
20565 @item
20566 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20567 @end itemize
20568
20569 The second field corresponds to the size of the known part of the function
20570 frame.
20571
20572 The qualifier @code{static} means that the function frame size
20573 is purely static.
20574 It usually means that all local variables have a static size.
20575 In this case, the second field is a reliable measure of the function stack
20576 utilization.
20577
20578 The qualifier @code{dynamic} means that the function frame size is not static.
20579 It happens mainly when some local variables have a dynamic size. When this
20580 qualifier appears alone, the second field is not a reliable measure
20581 of the function stack analysis. When it is qualified with @code{bounded}, it
20582 means that the second field is a reliable maximum of the function stack
20583 utilization.
20584
20585 @node Dynamic Stack Usage Analysis
20586 @section Dynamic Stack Usage Analysis
20587
20588 @noindent
20589 It is possible to measure the maximum amount of stack used by a task, by
20590 adding a switch to @command{gnatbind}, as:
20591
20592 @smallexample
20593 $ gnatbind -u0 file
20594 @end smallexample
20595
20596 @noindent
20597 With this option, at each task termination, its stack usage is output on
20598 @file{stderr}.
20599 It is not always convenient to output the stack usage when the program
20600 is still running. Hence, it is possible to delay this output until program
20601 termination. for a given number of tasks specified as the argument of the
20602 @option{-u} option. For instance:
20603
20604 @smallexample
20605 $ gnatbind -u100 file
20606 @end smallexample
20607
20608 @noindent
20609 will buffer the stack usage information of the first 100 tasks to terminate and
20610 output this info at program termination. Results are displayed in four
20611 columns:
20612
20613 @noindent
20614 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20615
20616 @noindent
20617 where:
20618
20619 @table @emph
20620 @item Index
20621 is a number associated with each task.
20622
20623 @item Task Name
20624 is the name of the task analyzed.
20625
20626 @item Stack Size
20627 is the maximum size for the stack.
20628
20629 @item Stack Usage
20630 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20631 is not entirely analyzed, and it's not possible to know exactly how
20632 much has actually been used. The report thus contains the theoretical stack usage
20633 (Value) and the possible variation (Variation) around this value.
20634
20635 @end table
20636
20637 @noindent
20638 The environment task stack, e.g., the stack that contains the main unit, is
20639 only processed when the environment variable GNAT_STACK_LIMIT is set.
20640
20641
20642 @c *********************************
20643 @c * GNATCHECK *
20644 @c *********************************
20645 @node Verifying Properties Using gnatcheck
20646 @chapter Verifying Properties Using @command{gnatcheck}
20647 @findex gnatcheck
20648 @cindex @command{gnatcheck}
20649
20650 @noindent
20651 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20652 of Ada source files according to a given set of semantic rules.
20653 @cindex ASIS
20654
20655 In order to check compliance with a given rule, @command{gnatcheck} has to
20656 semantically analyze the Ada sources.
20657 Therefore, checks can only be performed on
20658 legal Ada units. Moreover, when a unit depends semantically upon units located
20659 outside the current directory, the source search path has to be provided when
20660 calling @command{gnatcheck}, either through a specified project file or
20661 through @command{gnatcheck} switches as described below.
20662
20663 A number of rules are predefined in @command{gnatcheck} and are described
20664 later in this chapter.
20665 You can also add new rules, by modifying the @command{gnatcheck} code and
20666 rebuilding the tool. In order to add a simple rule making some local checks,
20667 a small amount of straightforward ASIS-based programming is usually needed.
20668
20669 Project support for @command{gnatcheck} is provided by the GNAT
20670 driver (see @ref{The GNAT Driver and Project Files}).
20671
20672 Invoking @command{gnatcheck} on the command line has the form:
20673
20674 @smallexample
20675 $ gnatcheck @ovar{switches} @{@var{filename}@}
20676 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20677 @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20678 @end smallexample
20679
20680 @noindent
20681 where
20682 @itemize @bullet
20683 @item
20684 @var{switches} specify the general tool options
20685
20686 @item
20687 Each @var{filename} is the name (including the extension) of a source
20688 file to process. ``Wildcards'' are allowed, and
20689 the file name may contain path information.
20690
20691 @item
20692 Each @var{arg_list_filename} is the name (including the extension) of a text
20693 file containing the names of the source files to process, separated by spaces
20694 or line breaks.
20695
20696 @item
20697 @var{gcc_switches} is a list of switches for
20698 @command{gcc}. They will be passed on to all compiler invocations made by
20699 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20700 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20701 and use the @option{-gnatec} switch to set the configuration file.
20702
20703 @item
20704 @var{rule_options} is a list of options for controlling a set of
20705 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20706 @end itemize
20707
20708 @noindent
20709 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20710 supplied.
20711
20712 @menu
20713 * Format of the Report File::
20714 * General gnatcheck Switches::
20715 * gnatcheck Rule Options::
20716 * Adding the Results of Compiler Checks to gnatcheck Output::
20717 * Project-Wide Checks::
20718 * Rule exemption::
20719 * Predefined Rules::
20720 @end menu
20721
20722 @node Format of the Report File
20723 @section Format of the Report File
20724 @cindex Report file (for @code{gnatcheck})
20725
20726 @noindent
20727 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20728 rule violations.
20729 It also creates a text file that
20730 contains the complete report of the last gnatcheck run. By default this file
20731 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20732 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20733 name and/or location of the report file. This report contains:
20734 @itemize @bullet
20735 @item date and time of @command{gnatcheck} run, the version of
20736 the tool that has generated this report and the full parameters
20737 of the @command{gnatcheck} invocation;
20738 @item list of enabled rules;
20739 @item total number of detected violations;
20740 @item list of source files where rule violations have been detected;
20741 @item list of source files where no violations have been detected.
20742 @end itemize
20743
20744 @node General gnatcheck Switches
20745 @section General @command{gnatcheck} Switches
20746
20747 @noindent
20748 The following switches control the general @command{gnatcheck} behavior
20749
20750 @table @option
20751 @c !sort!
20752 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20753 @item ^-a^/ALL^
20754 Process all units including those with read-only ALI files such as
20755 those from the GNAT Run-Time library.
20756
20757 @ifclear vms
20758 @ignore
20759 @cindex @option{-d} (@command{gnatcheck})
20760 @item -d
20761 Debug mode
20762 @end ignore
20763
20764 @cindex @option{-dd} (@command{gnatcheck})
20765 @item -dd
20766 Progress indicator mode (for use in GPS).
20767 @end ifclear
20768
20769 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20770 @item ^-h^/HELP^
20771 List the predefined and user-defined rules. For more details see
20772 @ref{Predefined Rules}.
20773
20774 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20775 @item ^-l^/LOCS^
20776 Use full source locations references in the report file. For a construct from
20777 a generic instantiation a full source location is a chain from the location
20778 of this construct in the generic unit to the place where this unit is
20779 instantiated.
20780
20781 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20782 @item ^-log^/LOG^
20783 Duplicate all the output sent to @file{stderr} into a log file. The log file
20784 is named @file{gnatcheck.log} and is located in the current directory.
20785
20786 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20787 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20788 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20789 the range 0@dots{}1000;
20790 the default value is 500. Zero means that there is no limitation on
20791 the number of diagnostic messages to be output.
20792
20793 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20794 @item ^-q^/QUIET^
20795 Quiet mode. All the diagnostics about rule violations are placed in the
20796 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20797
20798 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20799 @item ^-s^/SHORT^
20800 Short format of the report file (no version information, no list of applied
20801 rules, no list of checked sources is included)
20802
20803 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20804 @item ^--include-file^/INCLUDE_FILE^
20805 Append the content of the specified text file to the report file
20806
20807 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20808 @item ^-t^/TIME^
20809 Print out execution time.
20810
20811 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20812 @item ^-v^/VERBOSE^
20813 Verbose mode; @command{gnatcheck} generates version information and then
20814 a trace of sources being processed.
20815
20816 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20817 @item ^-o ^/OUTPUT=^@var{report_file}
20818 Set name of report file file to @var{report_file} .
20819
20820 @end table
20821
20822 @noindent
20823 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20824 @option{^-s2^/BY_RULES^} or
20825 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20826 then the @command{gnatcheck} report file will only contain sections
20827 explicitly denoted by these options.
20828
20829 @node gnatcheck Rule Options
20830 @section @command{gnatcheck} Rule Options
20831
20832 @noindent
20833 The following options control the processing performed by
20834 @command{gnatcheck}.
20835
20836 @table @option
20837 @cindex @option{+ALL} (@command{gnatcheck})
20838 @item +ALL
20839 Turn all the rule checks ON.
20840
20841 @cindex @option{-ALL} (@command{gnatcheck})
20842 @item -ALL
20843 Turn all the rule checks OFF.
20844
20845 @cindex @option{+R} (@command{gnatcheck})
20846 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20847 Turn on the check for a specified rule with the specified parameter, if any.
20848 @var{rule_id} must be the identifier of one of the currently implemented rules
20849 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20850 are not case-sensitive. The @var{param} item must
20851 be a string representing a valid parameter(s) for the specified rule.
20852 If it contains any space characters then this string must be enclosed in
20853 quotation marks.
20854
20855 @cindex @option{-R} (@command{gnatcheck})
20856 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20857 Turn off the check for a specified rule with the specified parameter, if any.
20858
20859 @cindex @option{-from} (@command{gnatcheck})
20860 @item -from=@var{rule_option_filename}
20861 Read the rule options from the text file @var{rule_option_filename}, referred
20862 to as a ``coding standard file'' below.
20863
20864 @end table
20865
20866 @noindent
20867 The default behavior is that all the rule checks are disabled.
20868
20869 A coding standard file is a text file that contains a set of rule options
20870 described above.
20871 @cindex Coding standard file (for @code{gnatcheck})
20872 The file may contain empty lines and Ada-style comments (comment
20873 lines and end-of-line comments). There can be several rule options on a
20874 single line (separated by a space).
20875
20876 A coding standard file may reference other coding standard files by including
20877 more @option{-from=@var{rule_option_filename}}
20878 options, each such option being replaced with the content of the
20879 corresponding coding standard file during processing. In case a
20880 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20881 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20882 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20883 processing fails with an error message.
20884
20885
20886 @node Adding the Results of Compiler Checks to gnatcheck Output
20887 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20888
20889 @noindent
20890 The @command{gnatcheck} tool can include in the generated diagnostic messages
20891 and in
20892 the report file the results of the checks performed by the compiler. Though
20893 disabled by default, this effect may be obtained by using @option{+R} with
20894 the following rule identifiers and parameters:
20895
20896 @table @option
20897 @item Restrictions
20898 To record restrictions violations (which are performed by the compiler if the
20899 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20900 use the @code{Restrictions} rule
20901 with the same parameters as pragma
20902 @code{Restrictions} or @code{Restriction_Warnings}.
20903
20904 @item Style_Checks
20905 To record compiler style checks (@pxref{Style Checking}), use the
20906 @code{Style_Checks} rule.
20907 This rule takes a parameter in one of the following forms:
20908 @itemize
20909 @item
20910 @code{All_Checks},
20911 which enables the standard style checks corresponding to the @option{-gnatyy}
20912 GNAT style check option, or
20913
20914 @item
20915 a string with the same
20916 structure and semantics as the @code{string_LITERAL} parameter of the
20917 GNAT pragma @code{Style_Checks}
20918 (for further information about this pragma,
20919 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20920 @end itemize
20921
20922 @noindent
20923 For example, the
20924 @code{+RStyle_Checks:O} rule option activates
20925 the compiler style check that corresponds to
20926 @code{-gnatyO} style check option.
20927
20928 @item Warnings
20929 To record compiler warnings (@pxref{Warning Message Control}), use the
20930 @code{Warnings} rule with a parameter that is a valid
20931 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20932 (for further information about this pragma,
20933 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20934 Note that in case of gnatcheck
20935 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20936 all the specific warnings, but not suppresses the warning mode,
20937 and 'e' parameter, corresponding to @option{-gnatwe} that means
20938 "treat warnings as errors", does not have any effect.
20939
20940 @end table
20941
20942 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20943 option with the corresponding restriction name as a parameter. @code{-R} is
20944 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20945 warnings and style checks, use the corresponding warning and style options.
20946
20947 @node Project-Wide Checks
20948 @section Project-Wide Checks
20949 @cindex Project-wide checks (for @command{gnatcheck})
20950
20951 @noindent
20952 In order to perform checks on all units of a given project, you can use
20953 the GNAT driver along with the @option{-P} option:
20954 @smallexample
20955 gnat check -Pproj -rules -from=my_rules
20956 @end smallexample
20957
20958 @noindent
20959 If the project @code{proj} depends upon other projects, you can perform
20960 checks on the project closure using the @option{-U} option:
20961 @smallexample
20962 gnat check -Pproj -U -rules -from=my_rules
20963 @end smallexample
20964
20965 @noindent
20966 Finally, if not all the units are relevant to a particular main
20967 program in the project closure, you can perform checks for the set
20968 of units needed to create a given main program (unit closure) using
20969 the @option{-U} option followed by the name of the main unit:
20970 @smallexample
20971 gnat check -Pproj -U main -rules -from=my_rules
20972 @end smallexample
20973
20974
20975 @node Rule exemption
20976 @section Rule exemption
20977 @cindex Rule exemption (for @command{gnatcheck})
20978
20979 @noindent
20980 One of the most useful applications of @command{gnatcheck} is to
20981 automate the enforcement of project-specific coding standards,
20982 for example in safety-critical systems where particular features
20983 must be restricted in order to simplify the certification effort.
20984 However, it may sometimes be appropriate to violate a coding standard rule,
20985 and in such cases the rationale for the violation should be provided
20986 in the source program itself so that the individuals
20987 reviewing or maintaining the program can immediately understand the intent.
20988
20989 The @command{gnatcheck} tool supports this practice with the notion of
20990 a ``rule exemption'' covering a specific source code section. Normally
20991 rule violation messages are issued both on @file{stderr}
20992 and in a report file. In contrast, exempted violations are not listed on
20993 @file{stderr}; thus users invoking @command{gnatcheck} interactively
20994 (e.g. in its GPS interface) do not need to pay attention to known and
20995 justified violations. However, exempted violations along with their
20996 justification are documented in a special section of the report file that
20997 @command{gnatcheck} generates.
20998
20999 @menu
21000 * Using pragma Annotate to Control Rule Exemption::
21001 * gnatcheck Annotations Rules::
21002 @end menu
21003
21004 @node Using pragma Annotate to Control Rule Exemption
21005 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21006 @cindex Using pragma Annotate to control rule exemption
21007
21008 @noindent
21009 Rule exemption is controlled by pragma @code{Annotate} when its first
21010 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21011 exemption control annotations is as follows:
21012
21013 @smallexample @c ada
21014 @group
21015 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21016
21017 @i{exemption_control} ::= "Exempt_On" | "Exempt_Off"
21018
21019 @i{Rule_Name} ::= string_literal
21020
21021 @i{justification} ::= string_literal
21022 @end group
21023 @end smallexample
21024
21025 @noindent
21026 When a @command{gnatcheck} annotation has more then four arguments,
21027 @command{gnatcheck} issues a warning and ignores the additional arguments.
21028 If the additional arguments do not follow the syntax above,
21029 @command{gnatcheck} emits a warning and ignores the annotation.
21030
21031 The @i{@code{Rule_Name}} argument should be the name of some existing
21032 @command{gnatcheck} rule.
21033 Otherwise a warning message is generated and the pragma is
21034 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21035 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21036
21037 A source code section where an exemption is active for a given rule is
21038 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21039
21040 @smallexample @c ada
21041 pragma Annotate (gnatcheck, "Exempt_On", Rule_Name, "justification");
21042 -- source code section
21043 pragma Annotate (gnatcheck, "Exempt_Off", Rule_Name);
21044 @end smallexample
21045
21046
21047 @node gnatcheck Annotations Rules
21048 @subsection @command{gnatcheck} Annotations Rules
21049 @cindex @command{gnatcheck} annotations rules
21050
21051 @itemize @bullet
21052
21053 @item
21054 An ``Exempt_Off'' annotation can only appear after a corresponding
21055 ``Exempt_On'' annotation.
21056
21057 @item
21058 Exempted source code sections are only based on the source location of the
21059 annotations. Any source construct between the two
21060 annotations is part of the exempted source code section.
21061
21062 @item
21063 Exempted source code sections for different rules are independent. They can
21064 be nested or intersect with one another without limitation.
21065 Creating nested or intersecting source code sections for the same rule is
21066 not allowed.
21067
21068 @item
21069 Malformed exempted source code sections are reported by a warning, and
21070 the corresponding rule exemptions are ignored.
21071
21072 @item
21073 When an exempted source code section does not contain at least one violation
21074 of the exempted rule, a warning is emitted on @file{stderr}.
21075
21076 @item
21077 If an ``Exempt_On'' annotation pragma does not have a matching
21078 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21079 exemption for the given rule is ignored and a warning is issued.
21080 @end itemize
21081
21082
21083 @node Predefined Rules
21084 @section Predefined Rules
21085 @cindex Predefined rules (for @command{gnatcheck})
21086
21087 @ignore
21088 @c (Jan 2007) Since the global rules are still under development and are not
21089 @c documented, there is no point in explaining the difference between
21090 @c global and local rules
21091 @noindent
21092 A rule in @command{gnatcheck} is either local or global.
21093 A @emph{local rule} is a rule that applies to a well-defined section
21094 of a program and that can be checked by analyzing only this section.
21095 A @emph{global rule} requires analysis of some global properties of the
21096 whole program (mostly related to the program call graph).
21097 As of @value{NOW}, the implementation of global rules should be
21098 considered to be at a preliminary stage. You can use the
21099 @option{+GLOBAL} option to enable all the global rules, and the
21100 @option{-GLOBAL} rule option to disable all the global rules.
21101
21102 All the global rules in the list below are
21103 so indicated by marking them ``GLOBAL''.
21104 This +GLOBAL and -GLOBAL options are not
21105 included in the list of gnatcheck options above, because at the moment they
21106 are considered as a temporary debug options.
21107
21108 @command{gnatcheck} performs rule checks for generic
21109 instances only for global rules. This limitation may be relaxed in a later
21110 release.
21111 @end ignore
21112
21113 @noindent
21114 The following subsections document the rules implemented in
21115 @command{gnatcheck}.
21116 The subsection title is the same as the rule identifier, which may be
21117 used as a parameter of the @option{+R} or @option{-R} options.
21118
21119
21120 @menu
21121 * Abstract_Type_Declarations::
21122 * Anonymous_Arrays::
21123 * Anonymous_Subtypes::
21124 * Blocks::
21125 * Boolean_Relational_Operators::
21126 @ignore
21127 * Ceiling_Violations::
21128 @end ignore
21129 * Complex_Inlined_Subprograms::
21130 * Controlled_Type_Declarations::
21131 * Declarations_In_Blocks::
21132 * Deep_Inheritance_Hierarchies::
21133 * Deeply_Nested_Generics::
21134 * Deeply_Nested_Inlining::
21135 @ignore
21136 * Deeply_Nested_Local_Inlining::
21137 @end ignore
21138 * Default_Parameters::
21139 * Direct_Calls_To_Primitives::
21140 * Discriminated_Records::
21141 * Enumeration_Ranges_In_CASE_Statements::
21142 * Exceptions_As_Control_Flow::
21143 * Exits_From_Conditional_Loops::
21144 * EXIT_Statements_With_No_Loop_Name::
21145 * Expanded_Loop_Exit_Names::
21146 * Explicit_Full_Discrete_Ranges::
21147 * Float_Equality_Checks::
21148 * Forbidden_Attributes::
21149 * Forbidden_Pragmas::
21150 * Function_Style_Procedures::
21151 * Generics_In_Subprograms::
21152 * GOTO_Statements::
21153 * Implicit_IN_Mode_Parameters::
21154 * Implicit_SMALL_For_Fixed_Point_Types::
21155 * Improperly_Located_Instantiations::
21156 * Improper_Returns::
21157 * Library_Level_Subprograms::
21158 * Local_Packages::
21159 @ignore
21160 * Improperly_Called_Protected_Entries::
21161 @end ignore
21162 * Metrics::
21163 * Misnamed_Controlling_Parameters::
21164 * Misnamed_Identifiers::
21165 * Multiple_Entries_In_Protected_Definitions::
21166 * Name_Clashes::
21167 * Non_Qualified_Aggregates::
21168 * Non_Short_Circuit_Operators::
21169 * Non_SPARK_Attributes::
21170 * Non_Tagged_Derived_Types::
21171 * Non_Visible_Exceptions::
21172 * Numeric_Literals::
21173 * OTHERS_In_Aggregates::
21174 * OTHERS_In_CASE_Statements::
21175 * OTHERS_In_Exception_Handlers::
21176 * Outer_Loop_Exits::
21177 * Overloaded_Operators::
21178 * Overly_Nested_Control_Structures::
21179 * Parameters_Out_Of_Order::
21180 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21181 * Positional_Actuals_For_Defaulted_Parameters::
21182 * Positional_Components::
21183 * Positional_Generic_Parameters::
21184 * Positional_Parameters::
21185 * Predefined_Numeric_Types::
21186 * Raising_External_Exceptions::
21187 * Raising_Predefined_Exceptions::
21188 * Separate_Numeric_Error_Handlers::
21189 @ignore
21190 * Recursion::
21191 * Side_Effect_Functions::
21192 @end ignore
21193 * Slices::
21194 * Too_Many_Parents::
21195 * Unassigned_OUT_Parameters::
21196 * Uncommented_BEGIN_In_Package_Bodies::
21197 * Unconditional_Exits::
21198 * Unconstrained_Array_Returns::
21199 * Universal_Ranges::
21200 * Unnamed_Blocks_And_Loops::
21201 @ignore
21202 * Unused_Subprograms::
21203 @end ignore
21204 * USE_PACKAGE_Clauses::
21205 * Visible_Components::
21206 * Volatile_Objects_Without_Address_Clauses::
21207 @end menu
21208
21209
21210 @node Abstract_Type_Declarations
21211 @subsection @code{Abstract_Type_Declarations}
21212 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21213
21214 @noindent
21215 Flag all declarations of abstract types. For an abstract private
21216 type, both the private and full type declarations are flagged.
21217
21218 This rule has no parameters.
21219
21220
21221 @node Anonymous_Arrays
21222 @subsection @code{Anonymous_Arrays}
21223 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21224
21225 @noindent
21226 Flag all anonymous array type definitions (by Ada semantics these can only
21227 occur in object declarations).
21228
21229 This rule has no parameters.
21230
21231 @node Anonymous_Subtypes
21232 @subsection @code{Anonymous_Subtypes}
21233 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21234
21235 @noindent
21236 Flag all uses of anonymous subtypes (except cases when subtype indication
21237 is a part of a record component definition, and this subtype indication
21238 depends on a discriminant). A use of an anonymous subtype is
21239 any instance of a subtype indication with a constraint, other than one
21240 that occurs immediately within a subtype declaration. Any use of a range
21241 other than as a constraint used immediately within a subtype declaration
21242 is considered as an anonymous subtype.
21243
21244 An effect of this rule is that @code{for} loops such as the following are
21245 flagged (since @code{1..N} is formally a ``range''):
21246
21247 @smallexample @c ada
21248 for I in 1 .. N loop
21249 @dots{}
21250 end loop;
21251 @end smallexample
21252
21253 @noindent
21254 Declaring an explicit subtype solves the problem:
21255
21256 @smallexample @c ada
21257 subtype S is Integer range 1..N;
21258 @dots{}
21259 for I in S loop
21260 @dots{}
21261 end loop;
21262 @end smallexample
21263
21264 @noindent
21265 This rule has no parameters.
21266
21267 @node Blocks
21268 @subsection @code{Blocks}
21269 @cindex @code{Blocks} rule (for @command{gnatcheck})
21270
21271 @noindent
21272 Flag each block statement.
21273
21274 This rule has no parameters.
21275
21276 @node Boolean_Relational_Operators
21277 @subsection @code{Boolean_Relational_Operators}
21278 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21279
21280 @noindent
21281 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21282 ``>='', ``='' and ``/='') for the predefined Boolean type.
21283 (This rule is useful in enforcing the SPARK language restrictions.)
21284
21285 Calls to predefined relational operators of any type derived from
21286 @code{Standard.Boolean} are not detected. Calls to user-defined functions
21287 with these designators, and uses of operators that are renamings
21288 of the predefined relational operators for @code{Standard.Boolean},
21289 are likewise not detected.
21290
21291 This rule has no parameters.
21292
21293 @ignore
21294 @node Ceiling_Violations
21295 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21296 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21297
21298 @noindent
21299 Flag invocations of a protected operation by a task whose priority exceeds
21300 the protected object's ceiling.
21301
21302 As of @value{NOW}, this rule has the following limitations:
21303
21304 @itemize @bullet
21305
21306 @item
21307 We consider only pragmas Priority and Interrupt_Priority as means to define
21308 a task/protected operation priority. We do not consider the effect of using
21309 Ada.Dynamic_Priorities.Set_Priority procedure;
21310
21311 @item
21312 We consider only base task priorities, and no priority inheritance. That is,
21313 we do not make a difference between calls issued during task activation and
21314 execution of the sequence of statements from task body;
21315
21316 @item
21317 Any situation when the priority of protected operation caller is set by a
21318 dynamic expression (that is, the corresponding Priority or
21319 Interrupt_Priority pragma has a non-static expression as an argument) we
21320 treat as a priority inconsistency (and, therefore, detect this situation).
21321 @end itemize
21322
21323 @noindent
21324 At the moment the notion of the main subprogram is not implemented in
21325 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21326 if this subprogram can be a main subprogram of a partition) changes the
21327 priority of an environment task. So if we have more then one such pragma in
21328 the set of processed sources, the pragma that is processed last, defines the
21329 priority of an environment task.
21330
21331 This rule has no parameters.
21332 @end ignore
21333
21334 @node Controlled_Type_Declarations
21335 @subsection @code{Controlled_Type_Declarations}
21336 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21337
21338 @noindent
21339 Flag all declarations of controlled types. A declaration of a private type
21340 is flagged if its full declaration declares a controlled type. A declaration
21341 of a derived type is flagged if its ancestor type is controlled. Subtype
21342 declarations are not checked. A declaration of a type that itself is not a
21343 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21344 component is not checked.
21345
21346 This rule has no parameters.
21347
21348
21349 @node Complex_Inlined_Subprograms
21350 @subsection @code{Complex_Inlined_Subprograms}
21351 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21352
21353 @noindent
21354 Flags a subprogram (or generic subprogram) if
21355 pragma Inline is applied to the subprogram and at least one of the following
21356 conditions is met:
21357
21358 @itemize @bullet
21359 @item
21360 it contains at least one complex declaration such as a subprogram body,
21361 package, task, protected declaration, or a generic instantiation
21362 (except instantiation of @code{Ada.Unchecked_Conversion});
21363
21364 @item
21365 it contains at least one complex statement such as a loop, a case
21366 or a if statement, or a short circuit control form;
21367
21368 @item
21369 the number of statements exceeds
21370 a value specified by the @option{N} rule parameter;
21371 @end itemize
21372
21373 @noindent
21374 This rule has the following (mandatory) parameter for the @option{+R} option:
21375
21376 @table @emph
21377 @item N
21378 Positive integer specifying the maximum allowed total number of statements
21379 in the subprogram body.
21380 @end table
21381
21382
21383 @node Declarations_In_Blocks
21384 @subsection @code{Declarations_In_Blocks}
21385 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21386
21387 @noindent
21388 Flag all block statements containing local declarations. A @code{declare}
21389 block with an empty @i{declarative_part} or with a @i{declarative part}
21390 containing only pragmas and/or @code{use} clauses is not flagged.
21391
21392 This rule has no parameters.
21393
21394
21395 @node Deep_Inheritance_Hierarchies
21396 @subsection @code{Deep_Inheritance_Hierarchies}
21397 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21398
21399 @noindent
21400 Flags a tagged derived type declaration or an interface type declaration if
21401 its depth (in its inheritance
21402 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21403
21404 The inheritance depth of a tagged type or interface type is defined as 0 for
21405 a type with no parent and no progenitor, and otherwise as 1 + max of the
21406 depths of the immediate parent and immediate progenitors.
21407
21408 This rule does not flag private extension
21409 declarations. In the case of a private extension, the corresponding full
21410 declaration is checked.
21411
21412 This rule has the following (mandatory) parameter for the @option{+R} option:
21413
21414 @table @emph
21415 @item N
21416 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21417 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21418 of tagged and interface types.
21419 @end table
21420
21421
21422 @node Deeply_Nested_Generics
21423 @subsection @code{Deeply_Nested_Generics}
21424 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21425
21426 @noindent
21427 Flags a generic declaration nested in another generic declaration if
21428 the nesting level of the inner generic exceeds
21429 a value specified by the @option{N} rule parameter.
21430 The nesting level is the number of generic declaratons that enclose the given
21431 (generic) declaration. Formal packages are not flagged by this rule.
21432
21433 This rule has the following (mandatory) parameters for the @option{+R} option:
21434
21435 @table @emph
21436 @item N
21437 Positive integer specifying the maximal allowed nesting level
21438 for a generic declaration.
21439 @end table
21440
21441 @node Deeply_Nested_Inlining
21442 @subsection @code{Deeply_Nested_Inlining}
21443 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21444
21445 @noindent
21446 Flags a subprogram (or generic subprogram) if
21447 pragma Inline has been applied to the subprogram but the subprogram
21448 calls to another inlined subprogram that results in nested inlining
21449 with nesting depth exceeding the value specified by the
21450 @option{N} rule parameter.
21451
21452 This rule requires the global analysis of all the compilation units that
21453 are @command{gnatcheck} arguments; such analysis may affect the tool's
21454 performance.
21455
21456 This rule has the following (mandatory) parameter for the @option{+R} option:
21457
21458 @table @emph
21459 @item N
21460 Positive integer specifying the maximal allowed level of nested inlining.
21461 @end table
21462
21463
21464 @ignore
21465 @node Deeply_Nested_Local_Inlining
21466 @subsection @code{Deeply_Nested_Local_Inlining}
21467 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21468
21469 @noindent
21470 Flags a subprogram body if a pragma @code{Inline} is applied to the
21471 corresponding subprogram (or generic subprogram) and the body contains a call
21472 to another inlined subprogram that results in nested inlining with nesting
21473 depth more then a value specified by the @option{N} rule parameter.
21474 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21475 assumes that calls to subprograms in
21476 with'ed units are not inlided, so all the analysis of the depth of inlining is
21477 limited by the compilation unit where the subprogram body is located and the
21478 units it depends semantically upon. Such analysis may be usefull for the case
21479 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21480 the executable.
21481
21482 This rule has the following (mandatory) parameters for the @option{+R} option:
21483
21484 @table @emph
21485 @item N
21486 Positive integer specifying the maximal allowed level of nested inlining.
21487 @end table
21488
21489 @end ignore
21490
21491 @node Default_Parameters
21492 @subsection @code{Default_Parameters}
21493 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21494
21495 @noindent
21496 Flag all default expressions for subprogram parameters. Parameter
21497 declarations of formal and generic subprograms are also checked.
21498
21499 This rule has no parameters.
21500
21501
21502 @node Direct_Calls_To_Primitives
21503 @subsection @code{Direct_Calls_To_Primitives}
21504 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21505
21506 @noindent
21507 Flags any non-dispatching call to a dispatching primitive operation, except
21508 for the common idiom where a primitive subprogram for a tagged type
21509 directly calls the same primitive subprogram of the type's immediate ancestor.
21510
21511 This rule has no parameters.
21512
21513
21514 @node Discriminated_Records
21515 @subsection @code{Discriminated_Records}
21516 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21517
21518 @noindent
21519 Flag all declarations of record types with discriminants. Only the
21520 declarations of record and record extension types are checked. Incomplete,
21521 formal, private, derived and private extension type declarations are not
21522 checked. Task and protected type declarations also are not checked.
21523
21524 This rule has no parameters.
21525
21526
21527 @node Enumeration_Ranges_In_CASE_Statements
21528 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21529 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21530
21531 @noindent
21532 Flag each use of a range of enumeration literals as a choice in a
21533 @code{case} statement.
21534 All forms for specifying a range (explicit ranges
21535 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21536 An enumeration range is
21537 flagged even if contains exactly one enumeration value or no values at all. A
21538 type derived from an enumeration type is considered as an enumeration type.
21539
21540 This rule helps prevent maintenance problems arising from adding an
21541 enumeration value to a type and having it implicitly handled by an existing
21542 @code{case} statement with an enumeration range that includes the new literal.
21543
21544 This rule has no parameters.
21545
21546
21547 @node Exceptions_As_Control_Flow
21548 @subsection @code{Exceptions_As_Control_Flow}
21549 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21550
21551 @noindent
21552 Flag each place where an exception is explicitly raised and handled in the
21553 same subprogram body. A @code{raise} statement in an exception handler,
21554 package body, task body or entry body is not flagged.
21555
21556 The rule has no parameters.
21557
21558 @node Exits_From_Conditional_Loops
21559 @subsection @code{Exits_From_Conditional_Loops}
21560 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21561
21562 @noindent
21563 Flag any exit statement if it transfers the control out of a @code{for} loop
21564 or a @code{while} loop. This includes cases when the @code{exit} statement
21565 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21566 in some @code{for} or @code{while} loop, but transfers the control from some
21567 outer (inconditional) @code{loop} statement.
21568
21569 The rule has no parameters.
21570
21571
21572 @node EXIT_Statements_With_No_Loop_Name
21573 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21574 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21575
21576 @noindent
21577 Flag each @code{exit} statement that does not specify the name of the loop
21578 being exited.
21579
21580 The rule has no parameters.
21581
21582
21583 @node Expanded_Loop_Exit_Names
21584 @subsection @code{Expanded_Loop_Exit_Names}
21585 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21586
21587 @noindent
21588 Flag all expanded loop names in @code{exit} statements.
21589
21590 This rule has no parameters.
21591
21592 @node Explicit_Full_Discrete_Ranges
21593 @subsection @code{Explicit_Full_Discrete_Ranges}
21594 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21595
21596 @noindent
21597 Flag each discrete range that has the form @code{A'First .. A'Last}.
21598
21599 This rule has no parameters.
21600
21601 @node Float_Equality_Checks
21602 @subsection @code{Float_Equality_Checks}
21603 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21604
21605 @noindent
21606 Flag all calls to the predefined equality operations for floating-point types.
21607 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21608 User-defined equality operations are not flagged, nor are ``@code{=}''
21609 and ``@code{/=}'' operations for fixed-point types.
21610
21611 This rule has no parameters.
21612
21613
21614 @node Forbidden_Attributes
21615 @subsection @code{Forbidden_Attributes}
21616 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21617
21618 @noindent
21619 Flag each use of the specified attributes. The attributes to be detected are
21620 named in the rule's parameters.
21621
21622 This rule has the following parameters:
21623
21624 @itemize @bullet
21625 @item For the @option{+R} option
21626
21627 @table @asis
21628 @item @emph{Attribute_Designator}
21629 Adds the specified attribute to the set of attributes to be detected and sets
21630 the detection checks for all the specified attributes ON.
21631 If @emph{Attribute_Designator}
21632 does not denote any attribute defined in the Ada standard
21633 or in
21634 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21635 Manual}, it is treated as the name of unknown attribute.
21636
21637 @item @code{GNAT}
21638 All the GNAT-specific attributes are detected; this sets
21639 the detection checks for all the specified attributes ON.
21640
21641 @item @code{ALL}
21642 All attributes are detected; this sets the rule ON.
21643 @end table
21644
21645 @item For the @option{-R} option
21646 @table @asis
21647 @item @emph{Attribute_Designator}
21648 Removes the specified attribute from the set of attributes to be
21649 detected without affecting detection checks for
21650 other attributes. If @emph{Attribute_Designator} does not correspond to any
21651 attribute defined in the Ada standard or in
21652 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21653 this option is treated as turning OFF detection of all unknown attributes.
21654
21655 @item GNAT
21656 Turn OFF detection of all GNAT-specific attributes
21657
21658 @item ALL
21659 Clear the list of the attributes to be detected and
21660 turn the rule OFF.
21661 @end table
21662 @end itemize
21663
21664 @noindent
21665 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21666 have the syntax of an Ada identifier and therefore can not be considered as a
21667 (part of an) attribute designator, a diagnostic message is generated and the
21668 corresponding parameter is ignored. (If an attribute allows a static
21669 expression to be a part of the attribute designator, this expression is
21670 ignored by this rule.)
21671
21672 When more then one parameter is given in the same rule option, the parameters
21673 must be separated by commas.
21674
21675 If more then one option for this rule is specified for the gnatcheck call, a
21676 new option overrides the previous one(s).
21677
21678 The @option{+R} option with no parameters turns the rule ON, with the set of
21679 attributes to be detected defined by the previous rule options.
21680 (By default this set is empty, so if the only option specified for the rule is
21681 @option{+RForbidden_Attributes} (with
21682 no parameter), then the rule is enabled, but it does not detect anything).
21683 The @option{-R} option with no parameter turns the rule OFF, but it does not
21684 affect the set of attributes to be detected.
21685
21686
21687 @node Forbidden_Pragmas
21688 @subsection @code{Forbidden_Pragmas}
21689 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21690
21691 @noindent
21692 Flag each use of the specified pragmas. The pragmas to be detected
21693 are named in the rule's parameters.
21694
21695 This rule has the following parameters:
21696
21697 @itemize @bullet
21698 @item For the @option{+R} option
21699
21700 @table @asis
21701 @item @emph{Pragma_Name}
21702 Adds the specified pragma to the set of pragmas to be
21703 checked and sets the checks for all the specified pragmas
21704 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21705 does not correspond to any pragma name defined in the Ada
21706 standard or to the name of a GNAT-specific pragma defined
21707 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21708 Manual}, it is treated as the name of unknown pragma.
21709
21710 @item @code{GNAT}
21711 All the GNAT-specific pragmas are detected; this sets
21712 the checks for all the specified pragmas ON.
21713
21714 @item @code{ALL}
21715 All pragmas are detected; this sets the rule ON.
21716 @end table
21717
21718 @item For the @option{-R} option
21719 @table @asis
21720 @item @emph{Pragma_Name}
21721 Removes the specified pragma from the set of pragmas to be
21722 checked without affecting checks for
21723 other pragmas. @emph{Pragma_Name} is treated as a name
21724 of a pragma. If it does not correspond to any pragma
21725 defined in the Ada standard or to any name defined in
21726 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21727 this option is treated as turning OFF detection of all unknown pragmas.
21728
21729 @item GNAT
21730 Turn OFF detection of all GNAT-specific pragmas
21731
21732 @item ALL
21733 Clear the list of the pragmas to be detected and
21734 turn the rule OFF.
21735 @end table
21736 @end itemize
21737
21738 @noindent
21739 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21740 the syntax of an Ada identifier and therefore can not be considered
21741 as a pragma name, a diagnostic message is generated and the corresponding
21742 parameter is ignored.
21743
21744 When more then one parameter is given in the same rule option, the parameters
21745 must be separated by a comma.
21746
21747 If more then one option for this rule is specified for the @command{gnatcheck}
21748 call, a new option overrides the previous one(s).
21749
21750 The @option{+R} option with no parameters turns the rule ON with the set of
21751 pragmas to be detected defined by the previous rule options.
21752 (By default this set is empty, so if the only option specified for the rule is
21753 @option{+RForbidden_Pragmas} (with
21754 no parameter), then the rule is enabled, but it does not detect anything).
21755 The @option{-R} option with no parameter turns the rule OFF, but it does not
21756 affect the set of pragmas to be detected.
21757
21758
21759
21760
21761 @node Function_Style_Procedures
21762 @subsection @code{Function_Style_Procedures}
21763 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21764
21765 @noindent
21766 Flag each procedure that can be rewritten as a function. A procedure can be
21767 converted into a function if it has exactly one parameter of mode @code{out}
21768 and no parameters of mode @code{in out}. Procedure declarations,
21769 formal procedure declarations, and generic procedure declarations are always
21770 checked. Procedure
21771 bodies and body stubs are flagged only if they do not have corresponding
21772 separate declarations. Procedure renamings and procedure instantiations are
21773 not flagged.
21774
21775 If a procedure can be rewritten as a function, but its @code{out} parameter is
21776 of a limited type, it is not flagged.
21777
21778 Protected procedures are not flagged. Null procedures also are not flagged.
21779
21780 This rule has no parameters.
21781
21782
21783 @node Generics_In_Subprograms
21784 @subsection @code{Generics_In_Subprograms}
21785 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21786
21787 @noindent
21788 Flag each declaration of a generic unit in a subprogram. Generic
21789 declarations in the bodies of generic subprograms are also flagged.
21790 A generic unit nested in another generic unit is not flagged.
21791 If a generic unit is
21792 declared in a local package that is declared in a subprogram body, the
21793 generic unit is flagged.
21794
21795 This rule has no parameters.
21796
21797
21798 @node GOTO_Statements
21799 @subsection @code{GOTO_Statements}
21800 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21801
21802 @noindent
21803 Flag each occurrence of a @code{goto} statement.
21804
21805 This rule has no parameters.
21806
21807
21808 @node Implicit_IN_Mode_Parameters
21809 @subsection @code{Implicit_IN_Mode_Parameters}
21810 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21811
21812 @noindent
21813 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21814 Note that @code{access} parameters, although they technically behave
21815 like @code{in} parameters, are not flagged.
21816
21817 This rule has no parameters.
21818
21819
21820 @node Implicit_SMALL_For_Fixed_Point_Types
21821 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21822 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21823
21824 @noindent
21825 Flag each fixed point type declaration that lacks an explicit
21826 representation clause to define its @code{'Small} value.
21827 Since @code{'Small} can be defined only for ordinary fixed point types,
21828 decimal fixed point type declarations are not checked.
21829
21830 This rule has no parameters.
21831
21832
21833 @node Improperly_Located_Instantiations
21834 @subsection @code{Improperly_Located_Instantiations}
21835 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21836
21837 @noindent
21838 Flag all generic instantiations in library-level package specs
21839 (including library generic packages) and in all subprogram bodies.
21840
21841 Instantiations in task and entry bodies are not flagged. Instantiations in the
21842 bodies of protected subprograms are flagged.
21843
21844 This rule has no parameters.
21845
21846
21847
21848 @node Improper_Returns
21849 @subsection @code{Improper_Returns}
21850 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21851
21852 @noindent
21853 Flag each explicit @code{return} statement in procedures, and
21854 multiple @code{return} statements in functions.
21855 Diagnostic messages are generated for all @code{return} statements
21856 in a procedure (thus each procedure must be written so that it
21857 returns implicitly at the end of its statement part),
21858 and for all @code{return} statements in a function after the first one.
21859 This rule supports the stylistic convention that each subprogram
21860 should have no more than one point of normal return.
21861
21862 This rule has no parameters.
21863
21864
21865 @node Library_Level_Subprograms
21866 @subsection @code{Library_Level_Subprograms}
21867 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21868
21869 @noindent
21870 Flag all library-level subprograms (including generic subprogram instantiations).
21871
21872 This rule has no parameters.
21873
21874
21875 @node Local_Packages
21876 @subsection @code{Local_Packages}
21877 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21878
21879 @noindent
21880 Flag all local packages declared in package and generic package
21881 specs.
21882 Local packages in bodies are not flagged.
21883
21884 This rule has no parameters.
21885
21886 @ignore
21887 @node Improperly_Called_Protected_Entries
21888 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21889 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21890
21891 @noindent
21892 Flag each protected entry that can be called from more than one task.
21893
21894 This rule has no parameters.
21895 @end ignore
21896
21897 @node Metrics
21898 @subsection @code{Metrics}
21899 @cindex @code{Metrics} rule (for @command{gnatcheck})
21900
21901 @noindent
21902 There is a set of checks based on computing a metric value and comparing the
21903 result with the specified upper (or lower, depending on a specific metric)
21904 value specified for a given metric. A construct is flagged if a given metric
21905 is applicable (can be computed) for it and the computed value is greater
21906 then (lover then) the specified upper (lower) bound.
21907
21908 The name of any metric-based rule consists of the prefix @code{Metrics_}
21909 followed by the name of the corresponding metric (see the table below).
21910 For @option{+R} option, each metric-based rule has a numeric parameter
21911 specifying the bound (integer or real, depending on a metric), @option{-R}
21912 option for metric rules does not have a parameter.
21913
21914 The following table shows the metric names for that the corresponding
21915 metrics-based checks are supported by gnatcheck, including the
21916 constraint that must be satisfied by the bound that is specified for the check
21917 and what bound - upper (U) or lower (L) - should be specified.
21918
21919 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21920 @ifnothtml
21921 @headitem Check Name @tab Description @tab Bounds Value
21922 @end ifnothtml
21923 @ifhtml
21924 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21925 @end ifhtml
21926 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21927 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21928 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21929 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21930 @end multitable
21931
21932 @noindent
21933 The meaning and the computed values for all these metrics are exactly
21934 the same as for the corresponding metrics in @command{gnatmetric}.
21935
21936 @emph{Example:} the rule
21937 @smallexample
21938 +RMetrics_Cyclomatic_Complexity : 7
21939 @end smallexample
21940 @noindent
21941 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21942
21943 To turn OFF the check for cyclomatic complexity metric, use the following option:
21944 @smallexample
21945 -RMetrics_Cyclomatic_Complexity
21946 @end smallexample
21947
21948
21949 @node Misnamed_Controlling_Parameters
21950 @subsection @code{Misnamed_Controlling_Parameters}
21951 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21952
21953 @noindent
21954 Flags a declaration of a dispatching operation, if the first parameter is
21955 not a controlling one and its name is not @code{This} (the check for
21956 parameter name is not case-sensitive). Declarations of dispatching functions
21957 with controlling result and no controlling parameter are never flagged.
21958
21959 A subprogram body declaration, subprogram renaming declaration or subprogram
21960 body stub is flagged only if it is not a completion of a prior subprogram
21961 declaration.
21962
21963 This rule has no parameters.
21964
21965
21966
21967 @node Misnamed_Identifiers
21968 @subsection @code{Misnamed_Identifiers}
21969 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21970
21971 @noindent
21972 Flag the declaration of each identifier that does not have a suffix
21973 corresponding to the kind of entity being declared.
21974 The following declarations are checked:
21975
21976 @itemize @bullet
21977 @item
21978 type declarations
21979
21980 @item
21981 subtype declarations
21982
21983 @item
21984 constant declarations (but not number declarations)
21985
21986 @item
21987 package renaming declarations (but not generic package renaming
21988 declarations)
21989 @end itemize
21990
21991 @noindent
21992 This rule may have parameters. When used without parameters, the rule enforces
21993 the following checks:
21994
21995 @itemize @bullet
21996 @item
21997 type-defining names end with @code{_T}, unless the type is an access type,
21998 in which case the suffix must be @code{_A}
21999 @item
22000 constant names end with @code{_C}
22001 @item
22002 names defining package renamings end with @code{_R}
22003 @end itemize
22004
22005 @noindent
22006 Defining identifiers from incomplete type declarations are never flagged.
22007
22008 For a private type declaration (including private extensions), the defining
22009 identifier from the private type declaration is checked against the type
22010 suffix (even if the corresponding full declaration is an access type
22011 declaration), and the defining identifier from the corresponding full type
22012 declaration is not checked.
22013
22014 @noindent
22015 For a deferred constant, the defining name in the corresponding full constant
22016 declaration is not checked.
22017
22018 Defining names of formal types are not checked.
22019
22020 The rule may have the following parameters:
22021
22022 @itemize @bullet
22023 @item
22024 For the @option{+R} option:
22025 @table @code
22026 @item Default
22027 Sets the default listed above for all the names to be checked.
22028
22029 @item Type_Suffix=@emph{string}
22030 Specifies the suffix for a type name.
22031
22032 @item Access_Suffix=@emph{string}
22033 Specifies the suffix for an access type name. If
22034 this parameter is set, it overrides for access
22035 types the suffix set by the @code{Type_Suffix} parameter.
22036 For access types, @emph{string} may have the following format:
22037 @emph{suffix1(suffix2)}. That means that an access type name
22038 should have the @emph{suffix1} suffix except for the case when
22039 the designated type is also an access type, in this case the
22040 type name should have the @emph{suffix1 & suffix2} suffix.
22041
22042 @item Class_Access_Suffix=@emph{string}
22043 Specifies the suffix for the name of an access type that points to some class-wide
22044 type. If this parameter is set, it overrides for such access
22045 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22046 parameter.
22047
22048 @item Class_Subtype_Suffix=@emph{string}
22049 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22050
22051 @item Constant_Suffix=@emph{string}
22052 Specifies the suffix for a constant name.
22053
22054 @item Renaming_Suffix=@emph{string}
22055 Specifies the suffix for a package renaming name.
22056 @end table
22057
22058 @item
22059 For the @option{-R} option:
22060 @table @code
22061 @item All_Suffixes
22062 Remove all the suffixes specified for the
22063 identifier suffix checks, whether by default or
22064 as specified by other rule parameters. All the
22065 checks for this rule are disabled as a result.
22066
22067 @item Type_Suffix
22068 Removes the suffix specified for types. This
22069 disables checks for types but does not disable
22070 any other checks for this rule (including the
22071 check for access type names if @code{Access_Suffix} is
22072 set).
22073
22074 @item Access_Suffix
22075 Removes the suffix specified for access types.
22076 This disables checks for access type names but
22077 does not disable any other checks for this rule.
22078 If @code{Type_Suffix} is set, access type names are
22079 checked as ordinary type names.
22080
22081 @item Class_Access_Suffix
22082 Removes the suffix specified for access types pointing to class-wide
22083 type. This disables specific checks for names of access types pointing to
22084 class-wide types but does not disable any other checks for this rule.
22085 If @code{Type_Suffix} is set, access type names are
22086 checked as ordinary type names. If @code{Access_Suffix} is set, these
22087 access types are checked as any other access type name.
22088
22089 @item Class_Subtype_Suffix=@emph{string}
22090 Removes the suffix specified for subtype names.
22091 This disables checks for subtype names but
22092 does not disable any other checks for this rule.
22093
22094 @item Constant_Suffix
22095 Removes the suffix specified for constants. This
22096 disables checks for constant names but does not
22097 disable any other checks for this rule.
22098
22099 @item Renaming_Suffix
22100 Removes the suffix specified for package
22101 renamings. This disables checks for package
22102 renamings but does not disable any other checks
22103 for this rule.
22104 @end table
22105 @end itemize
22106
22107 @noindent
22108 If more than one parameter is used, parameters must be separated by commas.
22109
22110 If more than one option is specified for the @command{gnatcheck} invocation,
22111 a new option overrides the previous one(s).
22112
22113 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22114 checks for all the
22115 name suffixes specified by previous options used for this rule.
22116
22117 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22118 all the checks but keeps
22119 all the suffixes specified by previous options used for this rule.
22120
22121 The @emph{string} value must be a valid suffix for an Ada identifier (after
22122 trimming all the leading and trailing space characters, if any).
22123 Parameters are not case sensitive, except the @emph{string} part.
22124
22125 If any error is detected in a rule parameter, the parameter is ignored.
22126 In such a case the options that are set for the rule are not
22127 specified.
22128
22129
22130
22131 @node Multiple_Entries_In_Protected_Definitions
22132 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22133 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22134
22135 @noindent
22136 Flag each protected definition (i.e., each protected object/type declaration)
22137 that defines more than one entry.
22138 Diagnostic messages are generated for all the entry declarations
22139 except the first one. An entry family is counted as one entry. Entries from
22140 the private part of the protected definition are also checked.
22141
22142 This rule has no parameters.
22143
22144 @node Name_Clashes
22145 @subsection @code{Name_Clashes}
22146 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22147
22148 @noindent
22149 Check that certain names are not used as defining identifiers. To activate
22150 this rule, you need to supply a reference to the dictionary file(s) as a rule
22151 parameter(s) (more then one dictionary file can be specified). If no
22152 dictionary file is set, this rule will not cause anything to be flagged.
22153 Only defining occurrences, not references, are checked.
22154 The check is not case-sensitive.
22155
22156 This rule is enabled by default, but without setting any corresponding
22157 dictionary file(s); thus the default effect is to do no checks.
22158
22159 A dictionary file is a plain text file. The maximum line length for this file
22160 is 1024 characters. If the line is longer then this limit, extra characters
22161 are ignored.
22162
22163 Each line can be either an empty line, a comment line, or a line containing
22164 a list of identifiers separated by space or HT characters.
22165 A comment is an Ada-style comment (from @code{--} to end-of-line).
22166 Identifiers must follow the Ada syntax for identifiers.
22167 A line containing one or more identifiers may end with a comment.
22168
22169 @node Non_Qualified_Aggregates
22170 @subsection @code{Non_Qualified_Aggregates}
22171 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22172
22173 @noindent
22174 Flag each non-qualified aggregate.
22175 A non-qualified aggregate is an
22176 aggregate that is not the expression of a qualified expression. A
22177 string literal is not considered an aggregate, but an array
22178 aggregate of a string type is considered as a normal aggregate.
22179 Aggregates of anonymous array types are not flagged.
22180
22181 This rule has no parameters.
22182
22183
22184 @node Non_Short_Circuit_Operators
22185 @subsection @code{Non_Short_Circuit_Operators}
22186 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22187
22188 @noindent
22189 Flag all calls to predefined @code{and} and @code{or} operators for
22190 any boolean type. Calls to
22191 user-defined @code{and} and @code{or} and to operators defined by renaming
22192 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22193 operators for modular types or boolean array types are not flagged.
22194
22195 This rule has no parameters.
22196
22197
22198
22199 @node Non_SPARK_Attributes
22200 @subsection @code{Non_SPARK_Attributes}
22201 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22202
22203 @noindent
22204 The SPARK language defines the following subset of Ada 95 attribute
22205 designators as those that can be used in SPARK programs. The use of
22206 any other attribute is flagged.
22207
22208 @itemize @bullet
22209 @item @code{'Adjacent}
22210 @item @code{'Aft}
22211 @item @code{'Base}
22212 @item @code{'Ceiling}
22213 @item @code{'Component_Size}
22214 @item @code{'Compose}
22215 @item @code{'Copy_Sign}
22216 @item @code{'Delta}
22217 @item @code{'Denorm}
22218 @item @code{'Digits}
22219 @item @code{'Exponent}
22220 @item @code{'First}
22221 @item @code{'Floor}
22222 @item @code{'Fore}
22223 @item @code{'Fraction}
22224 @item @code{'Last}
22225 @item @code{'Leading_Part}
22226 @item @code{'Length}
22227 @item @code{'Machine}
22228 @item @code{'Machine_Emax}
22229 @item @code{'Machine_Emin}
22230 @item @code{'Machine_Mantissa}
22231 @item @code{'Machine_Overflows}
22232 @item @code{'Machine_Radix}
22233 @item @code{'Machine_Rounds}
22234 @item @code{'Max}
22235 @item @code{'Min}
22236 @item @code{'Model}
22237 @item @code{'Model_Emin}
22238 @item @code{'Model_Epsilon}
22239 @item @code{'Model_Mantissa}
22240 @item @code{'Model_Small}
22241 @item @code{'Modulus}
22242 @item @code{'Pos}
22243 @item @code{'Pred}
22244 @item @code{'Range}
22245 @item @code{'Remainder}
22246 @item @code{'Rounding}
22247 @item @code{'Safe_First}
22248 @item @code{'Safe_Last}
22249 @item @code{'Scaling}
22250 @item @code{'Signed_Zeros}
22251 @item @code{'Size}
22252 @item @code{'Small}
22253 @item @code{'Succ}
22254 @item @code{'Truncation}
22255 @item @code{'Unbiased_Rounding}
22256 @item @code{'Val}
22257 @item @code{'Valid}
22258 @end itemize
22259
22260 @noindent
22261 This rule has no parameters.
22262
22263
22264 @node Non_Tagged_Derived_Types
22265 @subsection @code{Non_Tagged_Derived_Types}
22266 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22267
22268 @noindent
22269 Flag all derived type declarations that do not have a record extension part.
22270
22271 This rule has no parameters.
22272
22273
22274
22275 @node Non_Visible_Exceptions
22276 @subsection @code{Non_Visible_Exceptions}
22277 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22278
22279 @noindent
22280 Flag constructs leading to the possibility of propagating an exception
22281 out of the scope in which the exception is declared.
22282 Two cases are detected:
22283
22284 @itemize @bullet
22285 @item
22286 An exception declaration in a subprogram body, task body or block
22287 statement is flagged if the body or statement does not contain a handler for
22288 that exception or a handler with an @code{others} choice.
22289
22290 @item
22291 A @code{raise} statement in an exception handler of a subprogram body,
22292 task body or block statement is flagged if it (re)raises a locally
22293 declared exception. This may occur under the following circumstances:
22294 @itemize @minus
22295 @item
22296 it explicitly raises a locally declared exception, or
22297 @item
22298 it does not specify an exception name (i.e., it is simply @code{raise;})
22299 and the enclosing handler contains a locally declared exception in its
22300 exception choices.
22301 @end itemize
22302 @end itemize
22303
22304 @noindent
22305 Renamings of local exceptions are not flagged.
22306
22307 This rule has no parameters.
22308
22309
22310 @node Numeric_Literals
22311 @subsection @code{Numeric_Literals}
22312 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22313
22314 @noindent
22315 Flag each use of a numeric literal in an index expression, and in any
22316 circumstance except for the following:
22317
22318 @itemize @bullet
22319 @item
22320 a literal occurring in the initialization expression for a constant
22321 declaration or a named number declaration, or
22322
22323 @item
22324 an integer literal that is less than or equal to a value
22325 specified by the @option{N} rule parameter.
22326 @end itemize
22327
22328 @noindent
22329 This rule may have the following parameters for the @option{+R} option:
22330
22331 @table @asis
22332 @item @emph{N}
22333 @emph{N} is an integer literal used as the maximal value that is not flagged
22334 (i.e., integer literals not exceeding this value are allowed)
22335
22336 @item @code{ALL}
22337 All integer literals are flagged
22338 @end table
22339
22340 @noindent
22341 If no parameters are set, the maximum unflagged value is 1.
22342
22343 The last specified check limit (or the fact that there is no limit at
22344 all) is used when multiple @option{+R} options appear.
22345
22346 The @option{-R} option for this rule has no parameters.
22347 It disables the rule but retains the last specified maximum unflagged value.
22348 If the @option{+R} option subsequently appears, this value is used as the
22349 threshold for the check.
22350
22351
22352 @node OTHERS_In_Aggregates
22353 @subsection @code{OTHERS_In_Aggregates}
22354 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22355
22356 @noindent
22357 Flag each use of an @code{others} choice in extension aggregates.
22358 In record and array aggregates, an @code{others} choice is flagged unless
22359 it is used to refer to all components, or to all but one component.
22360
22361 If, in case of a named array aggregate, there are two associations, one
22362 with an @code{others} choice and another with a discrete range, the
22363 @code{others} choice is flagged even if the discrete range specifies
22364 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22365
22366 This rule has no parameters.
22367
22368 @node OTHERS_In_CASE_Statements
22369 @subsection @code{OTHERS_In_CASE_Statements}
22370 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22371
22372 @noindent
22373 Flag any use of an @code{others} choice in a @code{case} statement.
22374
22375 This rule has no parameters.
22376
22377 @node OTHERS_In_Exception_Handlers
22378 @subsection @code{OTHERS_In_Exception_Handlers}
22379 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22380
22381 @noindent
22382 Flag any use of an @code{others} choice in an exception handler.
22383
22384 This rule has no parameters.
22385
22386
22387 @node Outer_Loop_Exits
22388 @subsection @code{Outer_Loop_Exits}
22389 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22390
22391 @noindent
22392 Flag each @code{exit} statement containing a loop name that is not the name
22393 of the immediately enclosing @code{loop} statement.
22394
22395 This rule has no parameters.
22396
22397
22398 @node Overloaded_Operators
22399 @subsection @code{Overloaded_Operators}
22400 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22401
22402 @noindent
22403 Flag each function declaration that overloads an operator symbol.
22404 A function body is checked only if the body does not have a
22405 separate spec. Formal functions are also checked. For a
22406 renaming declaration, only renaming-as-declaration is checked
22407
22408 This rule has no parameters.
22409
22410
22411 @node Overly_Nested_Control_Structures
22412 @subsection @code{Overly_Nested_Control_Structures}
22413 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22414
22415 @noindent
22416 Flag each control structure whose nesting level exceeds the value provided
22417 in the rule parameter.
22418
22419 The control structures checked are the following:
22420
22421 @itemize @bullet
22422 @item @code{if} statement
22423 @item @code{case} statement
22424 @item @code{loop} statement
22425 @item Selective accept statement
22426 @item Timed entry call statement
22427 @item Conditional entry call
22428 @item Asynchronous select statement
22429 @end itemize
22430
22431 @noindent
22432 The rule has the following parameter for the @option{+R} option:
22433
22434 @table @emph
22435 @item N
22436 Positive integer specifying the maximal control structure nesting
22437 level that is not flagged
22438 @end table
22439
22440 @noindent
22441 If the parameter for the @option{+R} option is not specified or
22442 if it is not a positive integer, @option{+R} option is ignored.
22443
22444 If more then one option is specified for the gnatcheck call, the later option and
22445 new parameter override the previous one(s).
22446
22447
22448 @node Parameters_Out_Of_Order
22449 @subsection @code{Parameters_Out_Of_Order}
22450 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22451
22452 @noindent
22453 Flag each subprogram and entry declaration whose formal parameters are not
22454 ordered according to the following scheme:
22455
22456 @itemize @bullet
22457
22458 @item @code{in} and @code{access} parameters first,
22459 then @code{in out} parameters,
22460 and then @code{out} parameters;
22461
22462 @item for @code{in} mode, parameters with default initialization expressions
22463 occur last
22464 @end itemize
22465
22466 @noindent
22467 Only the first violation of the described order is flagged.
22468
22469 The following constructs are checked:
22470
22471 @itemize @bullet
22472 @item subprogram declarations (including null procedures);
22473 @item generic subprogram declarations;
22474 @item formal subprogram declarations;
22475 @item entry declarations;
22476 @item subprogram bodies and subprogram body stubs that do not
22477 have separate specifications
22478 @end itemize
22479
22480 @noindent
22481 Subprogram renamings are not checked.
22482
22483 This rule has no parameters.
22484
22485
22486 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22487 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22488 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22489
22490 @noindent
22491 Flag each generic actual parameter corresponding to a generic formal
22492 parameter with a default initialization, if positional notation is used.
22493
22494 This rule has no parameters.
22495
22496 @node Positional_Actuals_For_Defaulted_Parameters
22497 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22498 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22499
22500 @noindent
22501 Flag each actual parameter to a subprogram or entry call where the
22502 corresponding formal parameter has a default expression, if positional
22503 notation is used.
22504
22505 This rule has no parameters.
22506
22507 @node Positional_Components
22508 @subsection @code{Positional_Components}
22509 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22510
22511 @noindent
22512 Flag each array, record and extension aggregate that includes positional
22513 notation.
22514
22515 This rule has no parameters.
22516
22517
22518 @node Positional_Generic_Parameters
22519 @subsection @code{Positional_Generic_Parameters}
22520 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22521
22522 @noindent
22523 Flag each positional actual generic parameter except for the case when
22524 the generic unit being iinstantiated has exactly one generic formal
22525 parameter.
22526
22527 This rule has no parameters.
22528
22529
22530 @node Positional_Parameters
22531 @subsection @code{Positional_Parameters}
22532 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22533
22534 @noindent
22535 Flag each positional parameter notation in a subprogram or entry call,
22536 except for the following:
22537
22538 @itemize @bullet
22539 @item
22540 Parameters of calls to of prefix or infix operators are not flagged
22541 @item
22542 If the called subprogram or entry has only one formal parameter,
22543 the parameter of the call is not flagged;
22544 @item
22545 If a subprogram call uses the @emph{Object.Operation} notation, then
22546 @itemize @minus
22547 @item
22548 the first parameter (that is, @emph{Object}) is not flagged;
22549 @item
22550 if the called subprogram has only two parameters, the second parameter
22551 of the call is not flagged;
22552 @end itemize
22553 @end itemize
22554
22555 @noindent
22556 This rule has no parameters.
22557
22558
22559
22560
22561 @node Predefined_Numeric_Types
22562 @subsection @code{Predefined_Numeric_Types}
22563 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22564
22565 @noindent
22566 Flag each explicit use of the name of any numeric type or subtype defined
22567 in package @code{Standard}.
22568
22569 The rationale for this rule is to detect when the
22570 program may depend on platform-specific characteristics of the implementation
22571 of the predefined numeric types. Note that this rule is over-pessimistic;
22572 for example, a program that uses @code{String} indexing
22573 likely needs a variable of type @code{Integer}.
22574 Another example is the flagging of predefined numeric types with explicit
22575 constraints:
22576
22577 @smallexample @c ada
22578 subtype My_Integer is Integer range Left .. Right;
22579 Vy_Var : My_Integer;
22580 @end smallexample
22581
22582 @noindent
22583 This rule detects only numeric types and subtypes defined in
22584 @code{Standard}. The use of numeric types and subtypes defined in other
22585 predefined packages (such as @code{System.Any_Priority} or
22586 @code{Ada.Text_IO.Count}) is not flagged
22587
22588 This rule has no parameters.
22589
22590
22591
22592 @node Raising_External_Exceptions
22593 @subsection @code{Raising_External_Exceptions}
22594 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22595
22596 @noindent
22597 Flag any @code{raise} statement, in a program unit declared in a library
22598 package or in a generic library package, for an exception that is
22599 neither a predefined exception nor an exception that is also declared (or
22600 renamed) in the visible part of the package.
22601
22602 This rule has no parameters.
22603
22604
22605
22606 @node Raising_Predefined_Exceptions
22607 @subsection @code{Raising_Predefined_Exceptions}
22608 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22609
22610 @noindent
22611 Flag each @code{raise} statement that raises a predefined exception
22612 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22613 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22614
22615 This rule has no parameters.
22616
22617 @node Separate_Numeric_Error_Handlers
22618 @subsection @code{Separate_Numeric_Error_Handlers}
22619 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22620
22621 @noindent
22622 Flags each exception handler that contains a choice for
22623 the predefined @code{Constraint_Error} exception, but does not contain
22624 the choice for the predefined @code{Numeric_Error} exception, or
22625 that contains the choice for @code{Numeric_Error}, but does not contain the
22626 choice for @code{Constraint_Error}.
22627
22628 This rule has no parameters.
22629
22630 @ignore
22631 @node Recursion
22632 @subsection @code{Recursion} (under construction, GLOBAL)
22633 @cindex @code{Recursion} rule (for @command{gnatcheck})
22634
22635 @noindent
22636 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22637 calls, of recursive subprograms are detected.
22638
22639 This rule has no parameters.
22640 @end ignore
22641
22642 @ignore
22643 @node Side_Effect_Functions
22644 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22645 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22646
22647 @noindent
22648 Flag functions with side effects.
22649
22650 We define a side effect as changing any data object that is not local for the
22651 body of this function.
22652
22653 At the moment, we do NOT consider a side effect any input-output operations
22654 (changing a state or a content of any file).
22655
22656 We do not consider protected functions for this rule (???)
22657
22658 There are the following sources of side effect:
22659
22660 @enumerate
22661 @item Explicit (or direct) side-effect:
22662
22663 @itemize @bullet
22664 @item
22665 direct assignment to a non-local variable;
22666
22667 @item
22668 direct call to an entity that is known to change some data object that is
22669 not local for the body of this function (Note, that if F1 calls F2 and F2
22670 does have a side effect, this does not automatically mean that F1 also
22671 have a side effect, because it may be the case that F2 is declared in
22672 F1's body and it changes some data object that is global for F2, but
22673 local for F1);
22674 @end itemize
22675
22676 @item Indirect side-effect:
22677 @itemize @bullet
22678 @item
22679 Subprogram calls implicitly issued by:
22680 @itemize @bullet
22681 @item
22682 computing initialization expressions from type declarations as a part
22683 of object elaboration or allocator evaluation;
22684 @item
22685 computing implicit parameters of subprogram or entry calls or generic
22686 instantiations;
22687 @end itemize
22688
22689 @item
22690 activation of a task that change some non-local data object (directly or
22691 indirectly);
22692
22693 @item
22694 elaboration code of a package that is a result of a package instantiation;
22695
22696 @item
22697 controlled objects;
22698 @end itemize
22699
22700 @item Situations when we can suspect a side-effect, but the full static check
22701 is either impossible or too hard:
22702 @itemize @bullet
22703 @item
22704 assignment to access variables or to the objects pointed by access
22705 variables;
22706
22707 @item
22708 call to a subprogram pointed by access-to-subprogram value
22709
22710 @item
22711 dispatching calls;
22712 @end itemize
22713 @end enumerate
22714
22715 @noindent
22716 This rule has no parameters.
22717 @end ignore
22718
22719 @node Slices
22720 @subsection @code{Slices}
22721 @cindex @code{Slices} rule (for @command{gnatcheck})
22722
22723 @noindent
22724 Flag all uses of array slicing
22725
22726 This rule has no parameters.
22727
22728
22729 @node Too_Many_Parents
22730 @subsection @code{Too_Many_Parents}
22731 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22732
22733 @noindent
22734 Flags any type declaration, single task declaration or single protected
22735 declaration that has more then @option{N} parents, @option{N} is a parameter
22736 of the rule.
22737 A parent here is either a (sub)type denoted by the subtype mark from the
22738 parent_subtype_indication (in case of a derived type declaration), or
22739 any of the progenitors from the interface list, if any.
22740
22741 This rule has the following (mandatory) parameters for the @option{+R} option:
22742
22743 @table @emph
22744 @item N
22745 Positive integer specifying the maximal allowed number of parents.
22746 @end table
22747
22748
22749 @node Unassigned_OUT_Parameters
22750 @subsection @code{Unassigned_OUT_Parameters}
22751 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22752
22753 @noindent
22754 Flags procedures' @code{out} parameters that are not assigned, and
22755 identifies the contexts in which the assignments are missing.
22756
22757 An @code{out} parameter is flagged in the statements in the procedure
22758 body's handled sequence of statements (before the procedure body's
22759 @code{exception} part, if any) if this sequence of statements contains
22760 no assignments to the parameter.
22761
22762 An @code{out} parameter is flagged in an exception handler in the exception
22763 part of the procedure body's handled sequence of statements if the handler
22764 contains no assignment to the parameter.
22765
22766 Bodies of generic procedures are also considered.
22767
22768 The following are treated as assignments to an @code{out} parameter:
22769
22770 @itemize @bullet
22771 @item
22772 an assignment statement, with the parameter or some component as the target;
22773
22774 @item
22775 passing the parameter (or one of its components) as an @code{out} or
22776 @code{in out} parameter.
22777 @end itemize
22778
22779 @noindent
22780 This rule does not have any parameters.
22781
22782
22783
22784 @node Uncommented_BEGIN_In_Package_Bodies
22785 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22786 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22787
22788 @noindent
22789 Flags each package body with declarations and a statement part that does not
22790 include a trailing comment on the line containing the @code{begin} keyword;
22791 this trailing comment needs to specify the package name and nothing else.
22792 The @code{begin} is not flagged if the package body does not
22793 contain any declarations.
22794
22795 If the @code{begin} keyword is placed on the
22796 same line as the last declaration or the first statement, it is flagged
22797 independently of whether the line contains a trailing comment. The
22798 diagnostic message is attached to the line containing the first statement.
22799
22800 This rule has no parameters.
22801
22802 @node Unconditional_Exits
22803 @subsection @code{Unconditional_Exits}
22804 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22805
22806 @noindent
22807 Flag unconditional @code{exit} statements.
22808
22809 This rule has no parameters.
22810
22811 @node Unconstrained_Array_Returns
22812 @subsection @code{Unconstrained_Array_Returns}
22813 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22814
22815 @noindent
22816 Flag each function returning an unconstrained array. Function declarations,
22817 function bodies (and body stubs) having no separate specifications,
22818 and generic function instantiations are checked.
22819 Function calls and function renamings are
22820 not checked.
22821
22822 Generic function declarations, and function declarations in generic
22823 packages are not checked, instead this rule checks the results of
22824 generic instantiations (that is, expanded specification and expanded
22825 body corresponding to an instantiation).
22826
22827 This rule has no parameters.
22828
22829 @node Universal_Ranges
22830 @subsection @code{Universal_Ranges}
22831 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22832
22833 @noindent
22834 Flag discrete ranges that are a part of an index constraint, constrained
22835 array definition, or @code{for}-loop parameter specification, and whose bounds
22836 are both of type @i{universal_integer}. Ranges that have at least one
22837 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22838 or an expression of non-universal type) are not flagged.
22839
22840 This rule has no parameters.
22841
22842
22843 @node Unnamed_Blocks_And_Loops
22844 @subsection @code{Unnamed_Blocks_And_Loops}
22845 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22846
22847 @noindent
22848 Flag each unnamed block statement and loop statement.
22849
22850 The rule has no parameters.
22851
22852
22853
22854 @ignore
22855 @node Unused_Subprograms
22856 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22857 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22858
22859 @noindent
22860 Flag all unused subprograms.
22861
22862 This rule has no parameters.
22863 @end ignore
22864
22865
22866
22867
22868 @node USE_PACKAGE_Clauses
22869 @subsection @code{USE_PACKAGE_Clauses}
22870 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22871
22872 @noindent
22873 Flag all @code{use} clauses for packages; @code{use type} clauses are
22874 not flagged.
22875
22876 This rule has no parameters.
22877
22878
22879 @node Visible_Components
22880 @subsection @code{Visible_Components}
22881 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22882
22883 @noindent
22884 Flags all the type declarations located in the visible part of a library
22885 package or a library generic package that can declare a visible component. A
22886 type is considered as declaring a visible component if it contains a record
22887 definition by its own or as a part of a record extension. Type declaration is
22888 flagged even if it contains a record definition that defines no components.
22889
22890 Declarations located in private parts of local (generic) packages are not
22891 flagged. Declarations in private packages are not flagged.
22892
22893 This rule has no parameters.
22894
22895
22896 @node Volatile_Objects_Without_Address_Clauses
22897 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22898 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22899
22900 @noindent
22901 Flag each volatile object that does not have an address clause.
22902
22903 The following check is made: if the pragma @code{Volatile} is applied to a
22904 data object or to its type, then an address clause must
22905 be supplied for this object.
22906
22907 This rule does not check the components of data objects,
22908 array components that are volatile as a result of the pragma
22909 @code{Volatile_Components}, or objects that are volatile because
22910 they are atomic as a result of pragmas @code{Atomic} or
22911 @code{Atomic_Components}.
22912
22913 Only variable declarations, and not constant declarations, are checked.
22914
22915 This rule has no parameters.
22916
22917
22918 @c *********************************
22919 @node Creating Sample Bodies Using gnatstub
22920 @chapter Creating Sample Bodies Using @command{gnatstub}
22921 @findex gnatstub
22922
22923 @noindent
22924 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22925 for library unit declarations.
22926
22927 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22928 driver (see @ref{The GNAT Driver and Project Files}).
22929
22930 To create a body stub, @command{gnatstub} has to compile the library
22931 unit declaration. Therefore, bodies can be created only for legal
22932 library units. Moreover, if a library unit depends semantically upon
22933 units located outside the current directory, you have to provide
22934 the source search path when calling @command{gnatstub}, see the description
22935 of @command{gnatstub} switches below.
22936
22937 By default, all the program unit body stubs generated by @code{gnatstub}
22938 raise the predefined @code{Program_Error} exception, which will catch
22939 accidental calls of generated stubs. This behavior can be changed with
22940 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22941
22942 @menu
22943 * Running gnatstub::
22944 * Switches for gnatstub::
22945 @end menu
22946
22947 @node Running gnatstub
22948 @section Running @command{gnatstub}
22949
22950 @noindent
22951 @command{gnatstub} has the command-line interface of the form
22952
22953 @smallexample
22954 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22955 @end smallexample
22956
22957 @noindent
22958 where
22959 @table @var
22960 @item filename
22961 is the name of the source file that contains a library unit declaration
22962 for which a body must be created. The file name may contain the path
22963 information.
22964 The file name does not have to follow the GNAT file name conventions. If the
22965 name
22966 does not follow GNAT file naming conventions, the name of the body file must
22967 be provided
22968 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22969 If the file name follows the GNAT file naming
22970 conventions and the name of the body file is not provided,
22971 @command{gnatstub}
22972 creates the name
22973 of the body file from the argument file name by replacing the @file{.ads}
22974 suffix
22975 with the @file{.adb} suffix.
22976
22977 @item directory
22978 indicates the directory in which the body stub is to be placed (the default
22979 is the
22980 current directory)
22981
22982 @item switches
22983 is an optional sequence of switches as described in the next section
22984 @end table
22985
22986 @node Switches for gnatstub
22987 @section Switches for @command{gnatstub}
22988
22989 @table @option
22990 @c !sort!
22991
22992 @item ^-f^/FULL^
22993 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22994 If the destination directory already contains a file with the name of the
22995 body file
22996 for the argument spec file, replace it with the generated body stub.
22997
22998 @item ^-hs^/HEADER=SPEC^
22999 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23000 Put the comment header (i.e., all the comments preceding the
23001 compilation unit) from the source of the library unit declaration
23002 into the body stub.
23003
23004 @item ^-hg^/HEADER=GENERAL^
23005 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23006 Put a sample comment header into the body stub.
23007
23008 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23009 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23010 Use the content of the file as the comment header for a generated body stub.
23011
23012 @ifclear vms
23013 @item -IDIR
23014 @cindex @option{-IDIR} (@command{gnatstub})
23015 @itemx -I-
23016 @cindex @option{-I-} (@command{gnatstub})
23017 @end ifclear
23018 @ifset vms
23019 @item /NOCURRENT_DIRECTORY
23020 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23021 @end ifset
23022 ^These switches have ^This switch has^ the same meaning as in calls to
23023 @command{gcc}.
23024 ^They define ^It defines ^ the source search path in the call to
23025 @command{gcc} issued
23026 by @command{gnatstub} to compile an argument source file.
23027
23028 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23029 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23030 This switch has the same meaning as in calls to @command{gcc}.
23031 It defines the additional configuration file to be passed to the call to
23032 @command{gcc} issued
23033 by @command{gnatstub} to compile an argument source file.
23034
23035 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23036 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23037 (@var{n} is a non-negative integer). Set the maximum line length in the
23038 body stub to @var{n}; the default is 79. The maximum value that can be
23039 specified is 32767. Note that in the special case of configuration
23040 pragma files, the maximum is always 32767 regardless of whether or
23041 not this switch appears.
23042
23043 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23044 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23045 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23046 the generated body sample to @var{n}.
23047 The default indentation is 3.
23048
23049 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23050 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23051 Order local bodies alphabetically. (By default local bodies are ordered
23052 in the same way as the corresponding local specs in the argument spec file.)
23053
23054 @item ^-i^/INDENTATION=^@var{n}
23055 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23056 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23057
23058 @item ^-k^/TREE_FILE=SAVE^
23059 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23060 Do not remove the tree file (i.e., the snapshot of the compiler internal
23061 structures used by @command{gnatstub}) after creating the body stub.
23062
23063 @item ^-l^/LINE_LENGTH=^@var{n}
23064 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23065 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23066
23067 @item ^--no-exception^/NO_EXCEPTION^
23068 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23069 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23070 This is not always possible for function stubs.
23071
23072 @item ^--no-local-header^/NO_LOCAL_HEADER^
23073 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23074 Do not place local comment header with unit name before body stub for a
23075 unit.
23076
23077 @item ^-o ^/BODY=^@var{body-name}
23078 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23079 Body file name. This should be set if the argument file name does not
23080 follow
23081 the GNAT file naming
23082 conventions. If this switch is omitted the default name for the body will be
23083 obtained
23084 from the argument file name according to the GNAT file naming conventions.
23085
23086 @item ^-q^/QUIET^
23087 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23088 Quiet mode: do not generate a confirmation when a body is
23089 successfully created, and do not generate a message when a body is not
23090 required for an
23091 argument unit.
23092
23093 @item ^-r^/TREE_FILE=REUSE^
23094 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23095 Reuse the tree file (if it exists) instead of creating it. Instead of
23096 creating the tree file for the library unit declaration, @command{gnatstub}
23097 tries to find it in the current directory and use it for creating
23098 a body. If the tree file is not found, no body is created. This option
23099 also implies @option{^-k^/SAVE^}, whether or not
23100 the latter is set explicitly.
23101
23102 @item ^-t^/TREE_FILE=OVERWRITE^
23103 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23104 Overwrite the existing tree file. If the current directory already
23105 contains the file which, according to the GNAT file naming rules should
23106 be considered as a tree file for the argument source file,
23107 @command{gnatstub}
23108 will refuse to create the tree file needed to create a sample body
23109 unless this option is set.
23110
23111 @item ^-v^/VERBOSE^
23112 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23113 Verbose mode: generate version information.
23114
23115 @end table
23116
23117 @c *********************************
23118 @node Generating Ada Bindings for C and C++ headers
23119 @chapter Generating Ada Bindings for C and C++ headers
23120 @findex binding
23121
23122 @noindent
23123 GNAT now comes with a new experimental binding generator for C and C++
23124 headers which is intended to do 95% of the tedious work of generating
23125 Ada specs from C or C++ header files. Note that this still is a work in
23126 progress, not designed to generate 100% correct Ada specs.
23127
23128 The code generated is using the Ada 2005 syntax, which makes it
23129 easier to interface with other languages than previous versions of Ada.
23130
23131 @menu
23132 * Running the binding generator::
23133 * Generating bindings for C++ headers::
23134 * Switches::
23135 @end menu
23136
23137 @node Running the binding generator
23138 @section Running the binding generator
23139
23140 @noindent
23141 The binding generator is part of the @command{gcc} compiler and can be
23142 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23143 spec files for the header files specified on the command line, and all
23144 header files needed by these files transitivitely. For example:
23145
23146 @smallexample
23147 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23148 $ gcc -c -gnat05 *.ads
23149 @end smallexample
23150
23151 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23152 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23153 correspond to the files @file{/usr/include/time.h},
23154 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23155 mode these Ada specs.
23156
23157 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23158 and will attempt to generate corresponding Ada comments.
23159
23160 If you want to generate a single Ada file and not the transitive closure, you
23161 can use instead the @option{-fdump-ada-spec-slim} switch.
23162
23163 Note that we recommend when possible to use the @command{g++} driver to
23164 generate bindings, even for most C headers, since this will in general
23165 generate better Ada specs. For generating bindings for C++ headers, it is
23166 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23167 is equivalent in this case. If @command{g++} cannot work on your C headers
23168 because of incompatibilities between C and C++, then you can fallback to
23169 @command{gcc} instead.
23170
23171 For an example of better bindings generated from the C++ front-end,
23172 the name of the parameters (when available) are actually ignored by the C
23173 front-end. Consider the following C header:
23174
23175 @smallexample
23176 extern void foo (int variable);
23177 @end smallexample
23178
23179 with the C front-end, @code{variable} is ignored, and the above is handled as:
23180
23181 @smallexample
23182 extern void foo (int);
23183 @end smallexample
23184
23185 generating a generic:
23186
23187 @smallexample
23188 procedure foo (param1 : int);
23189 @end smallexample
23190
23191 with the C++ front-end, the name is available, and we generate:
23192
23193 @smallexample
23194 procedure foo (variable : int);
23195 @end smallexample
23196
23197 In some cases, the generated bindings will be more complete or more meaningful
23198 when defining some macros, which you can do via the @option{-D} switch. This
23199 is for example the case with @file{Xlib.h} under GNU/Linux:
23200
23201 @smallexample
23202 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23203 @end smallexample
23204
23205 The above will generate more complete bindings than a straight call without
23206 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23207
23208 In other cases, it is not possible to parse a header file in a stand alone
23209 manner, because other include files need to be included first. In this
23210 case, the solution is to create a small header file including the needed
23211 @code{#include} and possible @code{#define} directives. For example, to
23212 generate Ada bindings for @file{readline/readline.h}, you need to first
23213 include @file{stdio.h}, so you can create a file with the following two
23214 lines in e.g. @file{readline1.h}:
23215
23216 @smallexample
23217 #include <stdio.h>
23218 #include <readline/readline.h>
23219 @end smallexample
23220
23221 and then generate Ada bindings from this file:
23222
23223 @smallexample
23224 $ g++ -c -fdump-ada-spec readline1.h
23225 @end smallexample
23226
23227 @node Generating bindings for C++ headers
23228 @section Generating bindings for C++ headers
23229
23230 @noindent
23231 Generating bindings for C++ headers is done using the same options, always
23232 with the @command{g++} compiler.
23233
23234 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23235 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23236 multiple inheritance of abstract classes will be mapped to Ada interfaces
23237 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23238 information on interfacing to C++).
23239
23240 For example, given the following C++ header file:
23241
23242 @smallexample
23243 @group
23244 @cartouche
23245 class Carnivore @{
23246 public:
23247 virtual int Number_Of_Teeth () = 0;
23248 @};
23249
23250 class Domestic @{
23251 public:
23252 virtual void Set_Owner (char* Name) = 0;
23253 @};
23254
23255 class Animal @{
23256 public:
23257 int Age_Count;
23258 virtual void Set_Age (int New_Age);
23259 @};
23260
23261 class Dog : Animal, Carnivore, Domestic @{
23262 public:
23263 int Tooth_Count;
23264 char *Owner;
23265
23266 virtual int Number_Of_Teeth ();
23267 virtual void Set_Owner (char* Name);
23268
23269 Dog();
23270 @};
23271 @end cartouche
23272 @end group
23273 @end smallexample
23274
23275 The corresponding Ada code is generated:
23276
23277 @smallexample @c ada
23278 @group
23279 @cartouche
23280 package Class_Carnivore is
23281 type Carnivore is limited interface;
23282 pragma Import (CPP, Carnivore);
23283
23284 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23285 end;
23286 use Class_Carnivore;
23287
23288 package Class_Domestic is
23289 type Domestic is limited interface;
23290 pragma Import (CPP, Domestic);
23291
23292 procedure Set_Owner
23293 (this : access Domestic;
23294 Name : Interfaces.C.Strings.chars_ptr) is abstract;
23295 end;
23296 use Class_Domestic;
23297
23298 package Class_Animal is
23299 type Animal is tagged limited record
23300 Age_Count : aliased int;
23301 end record;
23302 pragma Import (CPP, Animal);
23303
23304 procedure Set_Age (this : access Animal; New_Age : int);
23305 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23306 end;
23307 use Class_Animal;
23308
23309 package Class_Dog is
23310 type Dog is new Animal and Carnivore and Domestic with record
23311 Tooth_Count : aliased int;
23312 Owner : Interfaces.C.Strings.chars_ptr;
23313 end record;
23314 pragma Import (CPP, Dog);
23315
23316 function Number_Of_Teeth (this : access Dog) return int;
23317 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23318
23319 procedure Set_Owner
23320 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23321 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23322
23323 function New_Dog return Dog;
23324 pragma CPP_Constructor (New_Dog);
23325 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23326 end;
23327 use Class_Dog;
23328 @end cartouche
23329 @end group
23330 @end smallexample
23331
23332 @node Switches
23333 @section Switches
23334
23335 @table @option
23336 @item -fdump-ada-spec
23337 @cindex @option{-fdump-ada-spec} (@command{gcc})
23338 Generate Ada spec files for the given header files transitively (including
23339 all header files that these headers depend upon).
23340
23341 @item -fdump-ada-spec-slim
23342 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23343 Generate Ada spec files for the header files specified on the command line
23344 only.
23345
23346 @item -C
23347 @cindex @option{-C} (@command{gcc})
23348 Extract comments from headers and generate Ada comments in the Ada spec files.
23349 @end table
23350
23351 @node Other Utility Programs
23352 @chapter Other Utility Programs
23353
23354 @noindent
23355 This chapter discusses some other utility programs available in the Ada
23356 environment.
23357
23358 @menu
23359 * Using Other Utility Programs with GNAT::
23360 * The External Symbol Naming Scheme of GNAT::
23361 * Converting Ada Files to html with gnathtml::
23362 * Installing gnathtml::
23363 @ifset vms
23364 * LSE::
23365 * Profiling::
23366 @end ifset
23367 @end menu
23368
23369 @node Using Other Utility Programs with GNAT
23370 @section Using Other Utility Programs with GNAT
23371
23372 @noindent
23373 The object files generated by GNAT are in standard system format and in
23374 particular the debugging information uses this format. This means
23375 programs generated by GNAT can be used with existing utilities that
23376 depend on these formats.
23377
23378 @ifclear vms
23379 In general, any utility program that works with C will also often work with
23380 Ada programs generated by GNAT. This includes software utilities such as
23381 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23382 as Purify.
23383 @end ifclear
23384
23385 @node The External Symbol Naming Scheme of GNAT
23386 @section The External Symbol Naming Scheme of GNAT
23387
23388 @noindent
23389 In order to interpret the output from GNAT, when using tools that are
23390 originally intended for use with other languages, it is useful to
23391 understand the conventions used to generate link names from the Ada
23392 entity names.
23393
23394 All link names are in all lowercase letters. With the exception of library
23395 procedure names, the mechanism used is simply to use the full expanded
23396 Ada name with dots replaced by double underscores. For example, suppose
23397 we have the following package spec:
23398
23399 @smallexample @c ada
23400 @group
23401 @cartouche
23402 package QRS is
23403 MN : Integer;
23404 end QRS;
23405 @end cartouche
23406 @end group
23407 @end smallexample
23408
23409 @noindent
23410 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23411 the corresponding link name is @code{qrs__mn}.
23412 @findex Export
23413 Of course if a @code{pragma Export} is used this may be overridden:
23414
23415 @smallexample @c ada
23416 @group
23417 @cartouche
23418 package Exports is
23419 Var1 : Integer;
23420 pragma Export (Var1, C, External_Name => "var1_name");
23421 Var2 : Integer;
23422 pragma Export (Var2, C, Link_Name => "var2_link_name");
23423 end Exports;
23424 @end cartouche
23425 @end group
23426 @end smallexample
23427
23428 @noindent
23429 In this case, the link name for @var{Var1} is whatever link name the
23430 C compiler would assign for the C function @var{var1_name}. This typically
23431 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23432 system conventions, but other possibilities exist. The link name for
23433 @var{Var2} is @var{var2_link_name}, and this is not operating system
23434 dependent.
23435
23436 @findex _main
23437 One exception occurs for library level procedures. A potential ambiguity
23438 arises between the required name @code{_main} for the C main program,
23439 and the name we would otherwise assign to an Ada library level procedure
23440 called @code{Main} (which might well not be the main program).
23441
23442 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23443 names. So if we have a library level procedure such as
23444
23445 @smallexample @c ada
23446 @group
23447 @cartouche
23448 procedure Hello (S : String);
23449 @end cartouche
23450 @end group
23451 @end smallexample
23452
23453 @noindent
23454 the external name of this procedure will be @var{_ada_hello}.
23455
23456
23457 @node Converting Ada Files to html with gnathtml
23458 @section Converting Ada Files to HTML with @code{gnathtml}
23459
23460 @noindent
23461 This @code{Perl} script allows Ada source files to be browsed using
23462 standard Web browsers. For installation procedure, see the section
23463 @xref{Installing gnathtml}.
23464
23465 Ada reserved keywords are highlighted in a bold font and Ada comments in
23466 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23467 switch to suppress the generation of cross-referencing information, user
23468 defined variables and types will appear in a different color; you will
23469 be able to click on any identifier and go to its declaration.
23470
23471 The command line is as follow:
23472 @smallexample
23473 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23474 @end smallexample
23475
23476 @noindent
23477 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23478 an html file for every ada file, and a global file called @file{index.htm}.
23479 This file is an index of every identifier defined in the files.
23480
23481 The available ^switches^options^ are the following ones:
23482
23483 @table @option
23484 @item -83
23485 @cindex @option{-83} (@code{gnathtml})
23486 Only the Ada 83 subset of keywords will be highlighted.
23487
23488 @item -cc @var{color}
23489 @cindex @option{-cc} (@code{gnathtml})
23490 This option allows you to change the color used for comments. The default
23491 value is green. The color argument can be any name accepted by html.
23492
23493 @item -d
23494 @cindex @option{-d} (@code{gnathtml})
23495 If the Ada files depend on some other files (for instance through
23496 @code{with} clauses, the latter files will also be converted to html.
23497 Only the files in the user project will be converted to html, not the files
23498 in the run-time library itself.
23499
23500 @item -D
23501 @cindex @option{-D} (@code{gnathtml})
23502 This command is the same as @option{-d} above, but @command{gnathtml} will
23503 also look for files in the run-time library, and generate html files for them.
23504
23505 @item -ext @var{extension}
23506 @cindex @option{-ext} (@code{gnathtml})
23507 This option allows you to change the extension of the generated HTML files.
23508 If you do not specify an extension, it will default to @file{htm}.
23509
23510 @item -f
23511 @cindex @option{-f} (@code{gnathtml})
23512 By default, gnathtml will generate html links only for global entities
23513 ('with'ed units, global variables and types,@dots{}). If you specify
23514 @option{-f} on the command line, then links will be generated for local
23515 entities too.
23516
23517 @item -l @var{number}
23518 @cindex @option{-l} (@code{gnathtml})
23519 If this ^switch^option^ is provided and @var{number} is not 0, then
23520 @code{gnathtml} will number the html files every @var{number} line.
23521
23522 @item -I @var{dir}
23523 @cindex @option{-I} (@code{gnathtml})
23524 Specify a directory to search for library files (@file{.ALI} files) and
23525 source files. You can provide several -I switches on the command line,
23526 and the directories will be parsed in the order of the command line.
23527
23528 @item -o @var{dir}
23529 @cindex @option{-o} (@code{gnathtml})
23530 Specify the output directory for html files. By default, gnathtml will
23531 saved the generated html files in a subdirectory named @file{html/}.
23532
23533 @item -p @var{file}
23534 @cindex @option{-p} (@code{gnathtml})
23535 If you are using Emacs and the most recent Emacs Ada mode, which provides
23536 a full Integrated Development Environment for compiling, checking,
23537 running and debugging applications, you may use @file{.gpr} files
23538 to give the directories where Emacs can find sources and object files.
23539
23540 Using this ^switch^option^, you can tell gnathtml to use these files.
23541 This allows you to get an html version of your application, even if it
23542 is spread over multiple directories.
23543
23544 @item -sc @var{color}
23545 @cindex @option{-sc} (@code{gnathtml})
23546 This ^switch^option^ allows you to change the color used for symbol
23547 definitions.
23548 The default value is red. The color argument can be any name accepted by html.
23549
23550 @item -t @var{file}
23551 @cindex @option{-t} (@code{gnathtml})
23552 This ^switch^option^ provides the name of a file. This file contains a list of
23553 file names to be converted, and the effect is exactly as though they had
23554 appeared explicitly on the command line. This
23555 is the recommended way to work around the command line length limit on some
23556 systems.
23557
23558 @end table
23559
23560 @node Installing gnathtml
23561 @section Installing @code{gnathtml}
23562
23563 @noindent
23564 @code{Perl} needs to be installed on your machine to run this script.
23565 @code{Perl} is freely available for almost every architecture and
23566 Operating System via the Internet.
23567
23568 On Unix systems, you may want to modify the first line of the script
23569 @code{gnathtml}, to explicitly tell the Operating system where Perl
23570 is. The syntax of this line is:
23571 @smallexample
23572 #!full_path_name_to_perl
23573 @end smallexample
23574
23575 @noindent
23576 Alternatively, you may run the script using the following command line:
23577
23578 @smallexample
23579 $ perl gnathtml.pl @ovar{switches} @var{files}
23580 @end smallexample
23581
23582 @ifset vms
23583 @node LSE
23584 @section LSE
23585 @findex LSE
23586
23587 @noindent
23588 The GNAT distribution provides an Ada 95 template for the HP Language
23589 Sensitive Editor (LSE), a component of DECset. In order to
23590 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23591
23592 @node Profiling
23593 @section Profiling
23594 @findex PCA
23595
23596 @noindent
23597 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23598 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23599 the collection phase with the /DEBUG qualifier.
23600
23601 @smallexample
23602 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23603 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23604 $ RUN/DEBUG <PROGRAM_NAME>
23605 @end smallexample
23606 @noindent
23607 @end ifset
23608
23609 @ifclear vms
23610 @c ******************************
23611 @node Code Coverage and Profiling
23612 @chapter Code Coverage and Profiling
23613 @cindex Code Coverage
23614 @cindex Profiling
23615
23616 @noindent
23617 This chapter describes how to use @code{gcov} - coverage testing tool - and
23618 @code{gprof} - profiler tool - on your Ada programs.
23619
23620 @menu
23621 * Code Coverage of Ada Programs using gcov::
23622 * Profiling an Ada Program using gprof::
23623 @end menu
23624
23625 @node Code Coverage of Ada Programs using gcov
23626 @section Code Coverage of Ada Programs using gcov
23627 @cindex gcov
23628 @cindex -fprofile-arcs
23629 @cindex -ftest-coverage
23630 @cindex -coverage
23631 @cindex Code Coverage
23632
23633 @noindent
23634 @code{gcov} is a test coverage program: it analyzes the execution of a given
23635 program on selected tests, to help you determine the portions of the program
23636 that are still untested.
23637
23638 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23639 User's Guide. You can refer to this documentation for a more complete
23640 description.
23641
23642 This chapter provides a quick startup guide, and
23643 details some Gnat-specific features.
23644
23645 @menu
23646 * Quick startup guide::
23647 * Gnat specifics::
23648 @end menu
23649
23650 @node Quick startup guide
23651 @subsection Quick startup guide
23652
23653 In order to perform coverage analysis of a program using @code{gcov}, 3
23654 steps are needed:
23655
23656 @itemize @bullet
23657 @item
23658 Code instrumentation during the compilation process
23659 @item
23660 Execution of the instrumented program
23661 @item
23662 Execution of the @code{gcov} tool to generate the result.
23663 @end itemize
23664
23665 The code instrumentation needed by gcov is created at the object level:
23666 The source code is not modified in any way, because the instrumentation code is
23667 inserted by gcc during the compilation process. To compile your code with code
23668 coverage activated, you need to recompile your whole project using the
23669 switches
23670 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23671 @code{-fprofile-arcs}.
23672
23673 @smallexample
23674 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23675 -largs -fprofile-arcs
23676 @end smallexample
23677
23678 This compilation process will create @file{.gcno} files together with
23679 the usual object files.
23680
23681 Once the program is compiled with coverage instrumentation, you can
23682 run it as many times as needed - on portions of a test suite for
23683 example. The first execution will produce @file{.gcda} files at the
23684 same location as the @file{.gcno} files. The following executions
23685 will update those files, so that a cumulative result of the covered
23686 portions of the program is generated.
23687
23688 Finally, you need to call the @code{gcov} tool. The different options of
23689 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23690
23691 This will create annotated source files with a @file{.gcov} extension:
23692 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23693
23694 @node Gnat specifics
23695 @subsection Gnat specifics
23696
23697 Because Ada semantics, portions of the source code may be shared among
23698 several object files. This is the case for example when generics are
23699 involved, when inlining is active or when declarations generate initialisation
23700 calls. In order to take
23701 into account this shared code, you need to call @code{gcov} on all
23702 source files of the tested program at once.
23703
23704 The list of source files might exceed the system's maximum command line
23705 length. In order to bypass this limitation, a new mechanism has been
23706 implemented in @code{gcov}: you can now list all your project's files into a
23707 text file, and provide this file to gcov as a parameter, preceded by a @@
23708 (e.g. @samp{gcov @@mysrclist.txt}).
23709
23710 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23711 not supported as there can be unresolved symbols during the final link.
23712
23713 @node Profiling an Ada Program using gprof
23714 @section Profiling an Ada Program using gprof
23715 @cindex gprof
23716 @cindex -pg
23717 @cindex Profiling
23718
23719 @noindent
23720 This section is not meant to be an exhaustive documentation of @code{gprof}.
23721 Full documentation for it can be found in the GNU Profiler User's Guide
23722 documentation that is part of this GNAT distribution.
23723
23724 Profiling a program helps determine the parts of a program that are executed
23725 most often, and are therefore the most time-consuming.
23726
23727 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23728 better handle Ada programs and multitasking.
23729 It is currently supported on the following platforms
23730 @itemize @bullet
23731 @item
23732 linux x86/x86_64
23733 @item
23734 solaris sparc/sparc64/x86
23735 @item
23736 windows x86
23737 @end itemize
23738
23739 @noindent
23740 In order to profile a program using @code{gprof}, 3 steps are needed:
23741
23742 @itemize @bullet
23743 @item
23744 Code instrumentation, requiring a full recompilation of the project with the
23745 proper switches.
23746 @item
23747 Execution of the program under the analysis conditions, i.e. with the desired
23748 input.
23749 @item
23750 Analysis of the results using the @code{gprof} tool.
23751 @end itemize
23752
23753 @noindent
23754 The following sections detail the different steps, and indicate how
23755 to interpret the results:
23756 @menu
23757 * Compilation for profiling::
23758 * Program execution::
23759 * Running gprof::
23760 * Interpretation of profiling results::
23761 @end menu
23762
23763 @node Compilation for profiling
23764 @subsection Compilation for profiling
23765 @cindex -pg
23766 @cindex Profiling
23767
23768 In order to profile a program the first step is to tell the compiler
23769 to generate the necessary profiling information. The compiler switch to be used
23770 is @code{-pg}, which must be added to other compilation switches. This
23771 switch needs to be specified both during compilation and link stages, and can
23772 be specified once when using gnatmake:
23773
23774 @smallexample
23775 gnatmake -f -pg -P my_project
23776 @end smallexample
23777
23778 @noindent
23779 Note that only the objects that were compiled with the @samp{-pg} switch will be
23780 profiled; if you need to profile your whole project, use the
23781 @samp{-f} gnatmake switch to force full recompilation.
23782
23783 @node Program execution
23784 @subsection Program execution
23785
23786 @noindent
23787 Once the program has been compiled for profiling, you can run it as usual.
23788
23789 The only constraint imposed by profiling is that the program must terminate
23790 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23791 properly analyzed.
23792
23793 Once the program completes execution, a data file called @file{gmon.out} is
23794 generated in the directory where the program was launched from. If this file
23795 already exists, it will be overwritten.
23796
23797 @node Running gprof
23798 @subsection Running gprof
23799
23800 @noindent
23801 The @code{gprof} tool is called as follow:
23802
23803 @smallexample
23804 gprof my_prog gmon.out
23805 @end smallexample
23806
23807 @noindent
23808 or simpler:
23809
23810 @smallexample
23811 gprof my_prog
23812 @end smallexample
23813
23814 @noindent
23815 The complete form of the gprof command line is the following:
23816
23817 @smallexample
23818 gprof [^switches^options^] [executable [data-file]]
23819 @end smallexample
23820
23821 @noindent
23822 @code{gprof} supports numerous ^switch^options^. The order of these
23823 ^switch^options^ does not matter. The full list of options can be found in
23824 the GNU Profiler User's Guide documentation that comes with this documentation.
23825
23826 The following is the subset of those switches that is most relevant:
23827
23828 @table @option
23829
23830 @item --demangle[=@var{style}]
23831 @itemx --no-demangle
23832 @cindex @option{--demangle} (@code{gprof})
23833 These options control whether symbol names should be demangled when
23834 printing output. The default is to demangle C++ symbols. The
23835 @code{--no-demangle} option may be used to turn off demangling. Different
23836 compilers have different mangling styles. The optional demangling style
23837 argument can be used to choose an appropriate demangling style for your
23838 compiler, in particular Ada symbols generated by GNAT can be demangled using
23839 @code{--demangle=gnat}.
23840
23841 @item -e @var{function_name}
23842 @cindex @option{-e} (@code{gprof})
23843 The @samp{-e @var{function}} option tells @code{gprof} not to print
23844 information about the function @var{function_name} (and its
23845 children@dots{}) in the call graph. The function will still be listed
23846 as a child of any functions that call it, but its index number will be
23847 shown as @samp{[not printed]}. More than one @samp{-e} option may be
23848 given; only one @var{function_name} may be indicated with each @samp{-e}
23849 option.
23850
23851 @item -E @var{function_name}
23852 @cindex @option{-E} (@code{gprof})
23853 The @code{-E @var{function}} option works like the @code{-e} option, but
23854 execution time spent in the function (and children who were not called from
23855 anywhere else), will not be used to compute the percentages-of-time for
23856 the call graph. More than one @samp{-E} option may be given; only one
23857 @var{function_name} may be indicated with each @samp{-E} option.
23858
23859 @item -f @var{function_name}
23860 @cindex @option{-f} (@code{gprof})
23861 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23862 call graph to the function @var{function_name} and its children (and
23863 their children@dots{}). More than one @samp{-f} option may be given;
23864 only one @var{function_name} may be indicated with each @samp{-f}
23865 option.
23866
23867 @item -F @var{function_name}
23868 @cindex @option{-F} (@code{gprof})
23869 The @samp{-F @var{function}} option works like the @code{-f} option, but
23870 only time spent in the function and its children (and their
23871 children@dots{}) will be used to determine total-time and
23872 percentages-of-time for the call graph. More than one @samp{-F} option
23873 may be given; only one @var{function_name} may be indicated with each
23874 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
23875
23876 @end table
23877
23878 @node Interpretation of profiling results
23879 @subsection Interpretation of profiling results
23880
23881 @noindent
23882
23883 The results of the profiling analysis are represented by two arrays: the
23884 'flat profile' and the 'call graph'. Full documentation of those outputs
23885 can be found in the GNU Profiler User's Guide.
23886
23887 The flat profile shows the time spent in each function of the program, and how
23888 many time it has been called. This allows you to locate easily the most
23889 time-consuming functions.
23890
23891 The call graph shows, for each subprogram, the subprograms that call it,
23892 and the subprograms that it calls. It also provides an estimate of the time
23893 spent in each of those callers/called subprograms.
23894 @end ifclear
23895
23896 @c ******************************
23897 @node Running and Debugging Ada Programs
23898 @chapter Running and Debugging Ada Programs
23899 @cindex Debugging
23900
23901 @noindent
23902 This chapter discusses how to debug Ada programs.
23903 @ifset vms
23904 It applies to GNAT on the Alpha OpenVMS platform;
23905 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23906 since HP has implemented Ada support in the OpenVMS debugger on I64.
23907 @end ifset
23908
23909 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23910
23911 @enumerate
23912 @item
23913 The illegality may be a violation of the static semantics of Ada. In
23914 that case GNAT diagnoses the constructs in the program that are illegal.
23915 It is then a straightforward matter for the user to modify those parts of
23916 the program.
23917
23918 @item
23919 The illegality may be a violation of the dynamic semantics of Ada. In
23920 that case the program compiles and executes, but may generate incorrect
23921 results, or may terminate abnormally with some exception.
23922
23923 @item
23924 When presented with a program that contains convoluted errors, GNAT
23925 itself may terminate abnormally without providing full diagnostics on
23926 the incorrect user program.
23927 @end enumerate
23928
23929 @menu
23930 * The GNAT Debugger GDB::
23931 * Running GDB::
23932 * Introduction to GDB Commands::
23933 * Using Ada Expressions::
23934 * Calling User-Defined Subprograms::
23935 * Using the Next Command in a Function::
23936 * Ada Exceptions::
23937 * Ada Tasks::
23938 * Debugging Generic Units::
23939 * GNAT Abnormal Termination or Failure to Terminate::
23940 * Naming Conventions for GNAT Source Files::
23941 * Getting Internal Debugging Information::
23942 * Stack Traceback::
23943 @end menu
23944
23945 @cindex Debugger
23946 @findex gdb
23947
23948 @node The GNAT Debugger GDB
23949 @section The GNAT Debugger GDB
23950
23951 @noindent
23952 @code{GDB} is a general purpose, platform-independent debugger that
23953 can be used to debug mixed-language programs compiled with @command{gcc},
23954 and in particular is capable of debugging Ada programs compiled with
23955 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23956 complex Ada data structures.
23957
23958 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23959 @ifset vms
23960 located in the GNU:[DOCS] directory,
23961 @end ifset
23962 for full details on the usage of @code{GDB}, including a section on
23963 its usage on programs. This manual should be consulted for full
23964 details. The section that follows is a brief introduction to the
23965 philosophy and use of @code{GDB}.
23966
23967 When GNAT programs are compiled, the compiler optionally writes debugging
23968 information into the generated object file, including information on
23969 line numbers, and on declared types and variables. This information is
23970 separate from the generated code. It makes the object files considerably
23971 larger, but it does not add to the size of the actual executable that
23972 will be loaded into memory, and has no impact on run-time performance. The
23973 generation of debug information is triggered by the use of the
23974 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23975 used to carry out the compilations. It is important to emphasize that
23976 the use of these options does not change the generated code.
23977
23978 The debugging information is written in standard system formats that
23979 are used by many tools, including debuggers and profilers. The format
23980 of the information is typically designed to describe C types and
23981 semantics, but GNAT implements a translation scheme which allows full
23982 details about Ada types and variables to be encoded into these
23983 standard C formats. Details of this encoding scheme may be found in
23984 the file exp_dbug.ads in the GNAT source distribution. However, the
23985 details of this encoding are, in general, of no interest to a user,
23986 since @code{GDB} automatically performs the necessary decoding.
23987
23988 When a program is bound and linked, the debugging information is
23989 collected from the object files, and stored in the executable image of
23990 the program. Again, this process significantly increases the size of
23991 the generated executable file, but it does not increase the size of
23992 the executable program itself. Furthermore, if this program is run in
23993 the normal manner, it runs exactly as if the debug information were
23994 not present, and takes no more actual memory.
23995
23996 However, if the program is run under control of @code{GDB}, the
23997 debugger is activated. The image of the program is loaded, at which
23998 point it is ready to run. If a run command is given, then the program
23999 will run exactly as it would have if @code{GDB} were not present. This
24000 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
24001 entirely non-intrusive until a breakpoint is encountered. If no
24002 breakpoint is ever hit, the program will run exactly as it would if no
24003 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24004 the debugging information and can respond to user commands to inspect
24005 variables, and more generally to report on the state of execution.
24006
24007 @c **************
24008 @node Running GDB
24009 @section Running GDB
24010
24011 @noindent
24012 This section describes how to initiate the debugger.
24013 @c The above sentence is really just filler, but it was otherwise
24014 @c clumsy to get the first paragraph nonindented given the conditional
24015 @c nature of the description
24016
24017 @ifclear vms
24018 The debugger can be launched from a @code{GPS} menu or
24019 directly from the command line. The description below covers the latter use.
24020 All the commands shown can be used in the @code{GPS} debug console window,
24021 but there are usually more GUI-based ways to achieve the same effect.
24022 @end ifclear
24023
24024 The command to run @code{GDB} is
24025
24026 @smallexample
24027 $ ^gdb program^GDB PROGRAM^
24028 @end smallexample
24029
24030 @noindent
24031 where @code{^program^PROGRAM^} is the name of the executable file. This
24032 activates the debugger and results in a prompt for debugger commands.
24033 The simplest command is simply @code{run}, which causes the program to run
24034 exactly as if the debugger were not present. The following section
24035 describes some of the additional commands that can be given to @code{GDB}.
24036
24037 @c *******************************
24038 @node Introduction to GDB Commands
24039 @section Introduction to GDB Commands
24040
24041 @noindent
24042 @code{GDB} contains a large repertoire of commands. @xref{Top,,
24043 Debugging with GDB, gdb, Debugging with GDB},
24044 @ifset vms
24045 located in the GNU:[DOCS] directory,
24046 @end ifset
24047 for extensive documentation on the use
24048 of these commands, together with examples of their use. Furthermore,
24049 the command @command{help} invoked from within GDB activates a simple help
24050 facility which summarizes the available commands and their options.
24051 In this section we summarize a few of the most commonly
24052 used commands to give an idea of what @code{GDB} is about. You should create
24053 a simple program with debugging information and experiment with the use of
24054 these @code{GDB} commands on the program as you read through the
24055 following section.
24056
24057 @table @code
24058 @item set args @var{arguments}
24059 The @var{arguments} list above is a list of arguments to be passed to
24060 the program on a subsequent run command, just as though the arguments
24061 had been entered on a normal invocation of the program. The @code{set args}
24062 command is not needed if the program does not require arguments.
24063
24064 @item run
24065 The @code{run} command causes execution of the program to start from
24066 the beginning. If the program is already running, that is to say if
24067 you are currently positioned at a breakpoint, then a prompt will ask
24068 for confirmation that you want to abandon the current execution and
24069 restart.
24070
24071 @item breakpoint @var{location}
24072 The breakpoint command sets a breakpoint, that is to say a point at which
24073 execution will halt and @code{GDB} will await further
24074 commands. @var{location} is
24075 either a line number within a file, given in the format @code{file:linenumber},
24076 or it is the name of a subprogram. If you request that a breakpoint be set on
24077 a subprogram that is overloaded, a prompt will ask you to specify on which of
24078 those subprograms you want to breakpoint. You can also
24079 specify that all of them should be breakpointed. If the program is run
24080 and execution encounters the breakpoint, then the program
24081 stops and @code{GDB} signals that the breakpoint was encountered by
24082 printing the line of code before which the program is halted.
24083
24084 @item breakpoint exception @var{name}
24085 A special form of the breakpoint command which breakpoints whenever
24086 exception @var{name} is raised.
24087 If @var{name} is omitted,
24088 then a breakpoint will occur when any exception is raised.
24089
24090 @item print @var{expression}
24091 This will print the value of the given expression. Most simple
24092 Ada expression formats are properly handled by @code{GDB}, so the expression
24093 can contain function calls, variables, operators, and attribute references.
24094
24095 @item continue
24096 Continues execution following a breakpoint, until the next breakpoint or the
24097 termination of the program.
24098
24099 @item step
24100 Executes a single line after a breakpoint. If the next statement
24101 is a subprogram call, execution continues into (the first statement of)
24102 the called subprogram.
24103
24104 @item next
24105 Executes a single line. If this line is a subprogram call, executes and
24106 returns from the call.
24107
24108 @item list
24109 Lists a few lines around the current source location. In practice, it
24110 is usually more convenient to have a separate edit window open with the
24111 relevant source file displayed. Successive applications of this command
24112 print subsequent lines. The command can be given an argument which is a
24113 line number, in which case it displays a few lines around the specified one.
24114
24115 @item backtrace
24116 Displays a backtrace of the call chain. This command is typically
24117 used after a breakpoint has occurred, to examine the sequence of calls that
24118 leads to the current breakpoint. The display includes one line for each
24119 activation record (frame) corresponding to an active subprogram.
24120
24121 @item up
24122 At a breakpoint, @code{GDB} can display the values of variables local
24123 to the current frame. The command @code{up} can be used to
24124 examine the contents of other active frames, by moving the focus up
24125 the stack, that is to say from callee to caller, one frame at a time.
24126
24127 @item down
24128 Moves the focus of @code{GDB} down from the frame currently being
24129 examined to the frame of its callee (the reverse of the previous command),
24130
24131 @item frame @var{n}
24132 Inspect the frame with the given number. The value 0 denotes the frame
24133 of the current breakpoint, that is to say the top of the call stack.
24134
24135 @end table
24136
24137 @noindent
24138 The above list is a very short introduction to the commands that
24139 @code{GDB} provides. Important additional capabilities, including conditional
24140 breakpoints, the ability to execute command sequences on a breakpoint,
24141 the ability to debug at the machine instruction level and many other
24142 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24143 Debugging with GDB}. Note that most commands can be abbreviated
24144 (for example, c for continue, bt for backtrace).
24145
24146 @node Using Ada Expressions
24147 @section Using Ada Expressions
24148 @cindex Ada expressions
24149
24150 @noindent
24151 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24152 extensions. The philosophy behind the design of this subset is
24153
24154 @itemize @bullet
24155 @item
24156 That @code{GDB} should provide basic literals and access to operations for
24157 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24158 leaving more sophisticated computations to subprograms written into the
24159 program (which therefore may be called from @code{GDB}).
24160
24161 @item
24162 That type safety and strict adherence to Ada language restrictions
24163 are not particularly important to the @code{GDB} user.
24164
24165 @item
24166 That brevity is important to the @code{GDB} user.
24167 @end itemize
24168
24169 @noindent
24170 Thus, for brevity, the debugger acts as if there were
24171 implicit @code{with} and @code{use} clauses in effect for all user-written
24172 packages, thus making it unnecessary to fully qualify most names with
24173 their packages, regardless of context. Where this causes ambiguity,
24174 @code{GDB} asks the user's intent.
24175
24176 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24177 GDB, gdb, Debugging with GDB}.
24178
24179 @node Calling User-Defined Subprograms
24180 @section Calling User-Defined Subprograms
24181
24182 @noindent
24183 An important capability of @code{GDB} is the ability to call user-defined
24184 subprograms while debugging. This is achieved simply by entering
24185 a subprogram call statement in the form:
24186
24187 @smallexample
24188 call subprogram-name (parameters)
24189 @end smallexample
24190
24191 @noindent
24192 The keyword @code{call} can be omitted in the normal case where the
24193 @code{subprogram-name} does not coincide with any of the predefined
24194 @code{GDB} commands.
24195
24196 The effect is to invoke the given subprogram, passing it the
24197 list of parameters that is supplied. The parameters can be expressions and
24198 can include variables from the program being debugged. The
24199 subprogram must be defined
24200 at the library level within your program, and @code{GDB} will call the
24201 subprogram within the environment of your program execution (which
24202 means that the subprogram is free to access or even modify variables
24203 within your program).
24204
24205 The most important use of this facility is in allowing the inclusion of
24206 debugging routines that are tailored to particular data structures
24207 in your program. Such debugging routines can be written to provide a suitably
24208 high-level description of an abstract type, rather than a low-level dump
24209 of its physical layout. After all, the standard
24210 @code{GDB print} command only knows the physical layout of your
24211 types, not their abstract meaning. Debugging routines can provide information
24212 at the desired semantic level and are thus enormously useful.
24213
24214 For example, when debugging GNAT itself, it is crucial to have access to
24215 the contents of the tree nodes used to represent the program internally.
24216 But tree nodes are represented simply by an integer value (which in turn
24217 is an index into a table of nodes).
24218 Using the @code{print} command on a tree node would simply print this integer
24219 value, which is not very useful. But the PN routine (defined in file
24220 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24221 a useful high level representation of the tree node, which includes the
24222 syntactic category of the node, its position in the source, the integers
24223 that denote descendant nodes and parent node, as well as varied
24224 semantic information. To study this example in more detail, you might want to
24225 look at the body of the PN procedure in the stated file.
24226
24227 @node Using the Next Command in a Function
24228 @section Using the Next Command in a Function
24229
24230 @noindent
24231 When you use the @code{next} command in a function, the current source
24232 location will advance to the next statement as usual. A special case
24233 arises in the case of a @code{return} statement.
24234
24235 Part of the code for a return statement is the ``epilog'' of the function.
24236 This is the code that returns to the caller. There is only one copy of
24237 this epilog code, and it is typically associated with the last return
24238 statement in the function if there is more than one return. In some
24239 implementations, this epilog is associated with the first statement
24240 of the function.
24241
24242 The result is that if you use the @code{next} command from a return
24243 statement that is not the last return statement of the function you
24244 may see a strange apparent jump to the last return statement or to
24245 the start of the function. You should simply ignore this odd jump.
24246 The value returned is always that from the first return statement
24247 that was stepped through.
24248
24249 @node Ada Exceptions
24250 @section Breaking on Ada Exceptions
24251 @cindex Exceptions
24252
24253 @noindent
24254 You can set breakpoints that trip when your program raises
24255 selected exceptions.
24256
24257 @table @code
24258 @item break exception
24259 Set a breakpoint that trips whenever (any task in the) program raises
24260 any exception.
24261
24262 @item break exception @var{name}
24263 Set a breakpoint that trips whenever (any task in the) program raises
24264 the exception @var{name}.
24265
24266 @item break exception unhandled
24267 Set a breakpoint that trips whenever (any task in the) program raises an
24268 exception for which there is no handler.
24269
24270 @item info exceptions
24271 @itemx info exceptions @var{regexp}
24272 The @code{info exceptions} command permits the user to examine all defined
24273 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24274 argument, prints out only those exceptions whose name matches @var{regexp}.
24275 @end table
24276
24277 @node Ada Tasks
24278 @section Ada Tasks
24279 @cindex Tasks
24280
24281 @noindent
24282 @code{GDB} allows the following task-related commands:
24283
24284 @table @code
24285 @item info tasks
24286 This command shows a list of current Ada tasks, as in the following example:
24287
24288 @smallexample
24289 @iftex
24290 @leftskip=0cm
24291 @end iftex
24292 (gdb) info tasks
24293 ID TID P-ID Thread Pri State Name
24294 1 8088000 0 807e000 15 Child Activation Wait main_task
24295 2 80a4000 1 80ae000 15 Accept/Select Wait b
24296 3 809a800 1 80a4800 15 Child Activation Wait a
24297 * 4 80ae800 3 80b8000 15 Running c
24298 @end smallexample
24299
24300 @noindent
24301 In this listing, the asterisk before the first task indicates it to be the
24302 currently running task. The first column lists the task ID that is used
24303 to refer to tasks in the following commands.
24304
24305 @item break @var{linespec} task @var{taskid}
24306 @itemx break @var{linespec} task @var{taskid} if @dots{}
24307 @cindex Breakpoints and tasks
24308 These commands are like the @code{break @dots{} thread @dots{}}.
24309 @var{linespec} specifies source lines.
24310
24311 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24312 to specify that you only want @code{GDB} to stop the program when a
24313 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24314 numeric task identifiers assigned by @code{GDB}, shown in the first
24315 column of the @samp{info tasks} display.
24316
24317 If you do not specify @samp{task @var{taskid}} when you set a
24318 breakpoint, the breakpoint applies to @emph{all} tasks of your
24319 program.
24320
24321 You can use the @code{task} qualifier on conditional breakpoints as
24322 well; in this case, place @samp{task @var{taskid}} before the
24323 breakpoint condition (before the @code{if}).
24324
24325 @item task @var{taskno}
24326 @cindex Task switching
24327
24328 This command allows to switch to the task referred by @var{taskno}. In
24329 particular, This allows to browse the backtrace of the specified
24330 task. It is advised to switch back to the original task before
24331 continuing execution otherwise the scheduling of the program may be
24332 perturbed.
24333 @end table
24334
24335 @noindent
24336 For more detailed information on the tasking support,
24337 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24338
24339 @node Debugging Generic Units
24340 @section Debugging Generic Units
24341 @cindex Debugging Generic Units
24342 @cindex Generics
24343
24344 @noindent
24345 GNAT always uses code expansion for generic instantiation. This means that
24346 each time an instantiation occurs, a complete copy of the original code is
24347 made, with appropriate substitutions of formals by actuals.
24348
24349 It is not possible to refer to the original generic entities in
24350 @code{GDB}, but it is always possible to debug a particular instance of
24351 a generic, by using the appropriate expanded names. For example, if we have
24352
24353 @smallexample @c ada
24354 @group
24355 @cartouche
24356 procedure g is
24357
24358 generic package k is
24359 procedure kp (v1 : in out integer);
24360 end k;
24361
24362 package body k is
24363 procedure kp (v1 : in out integer) is
24364 begin
24365 v1 := v1 + 1;
24366 end kp;
24367 end k;
24368
24369 package k1 is new k;
24370 package k2 is new k;
24371
24372 var : integer := 1;
24373
24374 begin
24375 k1.kp (var);
24376 k2.kp (var);
24377 k1.kp (var);
24378 k2.kp (var);
24379 end;
24380 @end cartouche
24381 @end group
24382 @end smallexample
24383
24384 @noindent
24385 Then to break on a call to procedure kp in the k2 instance, simply
24386 use the command:
24387
24388 @smallexample
24389 (gdb) break g.k2.kp
24390 @end smallexample
24391
24392 @noindent
24393 When the breakpoint occurs, you can step through the code of the
24394 instance in the normal manner and examine the values of local variables, as for
24395 other units.
24396
24397 @node GNAT Abnormal Termination or Failure to Terminate
24398 @section GNAT Abnormal Termination or Failure to Terminate
24399 @cindex GNAT Abnormal Termination or Failure to Terminate
24400
24401 @noindent
24402 When presented with programs that contain serious errors in syntax
24403 or semantics,
24404 GNAT may on rare occasions experience problems in operation, such
24405 as aborting with a
24406 segmentation fault or illegal memory access, raising an internal
24407 exception, terminating abnormally, or failing to terminate at all.
24408 In such cases, you can activate
24409 various features of GNAT that can help you pinpoint the construct in your
24410 program that is the likely source of the problem.
24411
24412 The following strategies are presented in increasing order of
24413 difficulty, corresponding to your experience in using GNAT and your
24414 familiarity with compiler internals.
24415
24416 @enumerate
24417 @item
24418 Run @command{gcc} with the @option{-gnatf}. This first
24419 switch causes all errors on a given line to be reported. In its absence,
24420 only the first error on a line is displayed.
24421
24422 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24423 are encountered, rather than after compilation is terminated. If GNAT
24424 terminates prematurely or goes into an infinite loop, the last error
24425 message displayed may help to pinpoint the culprit.
24426
24427 @item
24428 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24429 mode, @command{gcc} produces ongoing information about the progress of the
24430 compilation and provides the name of each procedure as code is
24431 generated. This switch allows you to find which Ada procedure was being
24432 compiled when it encountered a code generation problem.
24433
24434 @item
24435 @cindex @option{-gnatdc} switch
24436 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24437 switch that does for the front-end what @option{^-v^VERBOSE^} does
24438 for the back end. The system prints the name of each unit,
24439 either a compilation unit or nested unit, as it is being analyzed.
24440 @item
24441 Finally, you can start
24442 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24443 front-end of GNAT, and can be run independently (normally it is just
24444 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24445 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24446 @code{where} command is the first line of attack; the variable
24447 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24448 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24449 which the execution stopped, and @code{input_file name} indicates the name of
24450 the source file.
24451 @end enumerate
24452
24453 @node Naming Conventions for GNAT Source Files
24454 @section Naming Conventions for GNAT Source Files
24455
24456 @noindent
24457 In order to examine the workings of the GNAT system, the following
24458 brief description of its organization may be helpful:
24459
24460 @itemize @bullet
24461 @item
24462 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24463
24464 @item
24465 All files prefixed with @file{^par^PAR^} are components of the parser. The
24466 numbers correspond to chapters of the Ada Reference Manual. For example,
24467 parsing of select statements can be found in @file{par-ch9.adb}.
24468
24469 @item
24470 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24471 numbers correspond to chapters of the Ada standard. For example, all
24472 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24473 addition, some features of the language require sufficient special processing
24474 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24475 dynamic dispatching, etc.
24476
24477 @item
24478 All files prefixed with @file{^exp^EXP^} perform normalization and
24479 expansion of the intermediate representation (abstract syntax tree, or AST).
24480 these files use the same numbering scheme as the parser and semantics files.
24481 For example, the construction of record initialization procedures is done in
24482 @file{exp_ch3.adb}.
24483
24484 @item
24485 The files prefixed with @file{^bind^BIND^} implement the binder, which
24486 verifies the consistency of the compilation, determines an order of
24487 elaboration, and generates the bind file.
24488
24489 @item
24490 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24491 data structures used by the front-end.
24492
24493 @item
24494 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24495 the abstract syntax tree as produced by the parser.
24496
24497 @item
24498 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24499 all entities, computed during semantic analysis.
24500
24501 @item
24502 Library management issues are dealt with in files with prefix
24503 @file{^lib^LIB^}.
24504
24505 @item
24506 @findex Ada
24507 @cindex Annex A
24508 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24509 defined in Annex A.
24510
24511 @item
24512 @findex Interfaces
24513 @cindex Annex B
24514 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24515 defined in Annex B.
24516
24517 @item
24518 @findex System
24519 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24520 both language-defined children and GNAT run-time routines.
24521
24522 @item
24523 @findex GNAT
24524 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24525 general-purpose packages, fully documented in their specs. All
24526 the other @file{.c} files are modifications of common @command{gcc} files.
24527 @end itemize
24528
24529 @node Getting Internal Debugging Information
24530 @section Getting Internal Debugging Information
24531
24532 @noindent
24533 Most compilers have internal debugging switches and modes. GNAT
24534 does also, except GNAT internal debugging switches and modes are not
24535 secret. A summary and full description of all the compiler and binder
24536 debug flags are in the file @file{debug.adb}. You must obtain the
24537 sources of the compiler to see the full detailed effects of these flags.
24538
24539 The switches that print the source of the program (reconstructed from
24540 the internal tree) are of general interest for user programs, as are the
24541 options to print
24542 the full internal tree, and the entity table (the symbol table
24543 information). The reconstructed source provides a readable version of the
24544 program after the front-end has completed analysis and expansion,
24545 and is useful when studying the performance of specific constructs.
24546 For example, constraint checks are indicated, complex aggregates
24547 are replaced with loops and assignments, and tasking primitives
24548 are replaced with run-time calls.
24549
24550 @node Stack Traceback
24551 @section Stack Traceback
24552 @cindex traceback
24553 @cindex stack traceback
24554 @cindex stack unwinding
24555
24556 @noindent
24557 Traceback is a mechanism to display the sequence of subprogram calls that
24558 leads to a specified execution point in a program. Often (but not always)
24559 the execution point is an instruction at which an exception has been raised.
24560 This mechanism is also known as @i{stack unwinding} because it obtains
24561 its information by scanning the run-time stack and recovering the activation
24562 records of all active subprograms. Stack unwinding is one of the most
24563 important tools for program debugging.
24564
24565 The first entry stored in traceback corresponds to the deepest calling level,
24566 that is to say the subprogram currently executing the instruction
24567 from which we want to obtain the traceback.
24568
24569 Note that there is no runtime performance penalty when stack traceback
24570 is enabled, and no exception is raised during program execution.
24571
24572 @menu
24573 * Non-Symbolic Traceback::
24574 * Symbolic Traceback::
24575 @end menu
24576
24577 @node Non-Symbolic Traceback
24578 @subsection Non-Symbolic Traceback
24579 @cindex traceback, non-symbolic
24580
24581 @noindent
24582 Note: this feature is not supported on all platforms. See
24583 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24584 platforms.
24585
24586 @menu
24587 * Tracebacks From an Unhandled Exception::
24588 * Tracebacks From Exception Occurrences (non-symbolic)::
24589 * Tracebacks From Anywhere in a Program (non-symbolic)::
24590 @end menu
24591
24592 @node Tracebacks From an Unhandled Exception
24593 @subsubsection Tracebacks From an Unhandled Exception
24594
24595 @noindent
24596 A runtime non-symbolic traceback is a list of addresses of call instructions.
24597 To enable this feature you must use the @option{-E}
24598 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24599 of exception information. You can retrieve this information using the
24600 @code{addr2line} tool.
24601
24602 Here is a simple example:
24603
24604 @smallexample @c ada
24605 @cartouche
24606 procedure STB is
24607
24608 procedure P1 is
24609 begin
24610 raise Constraint_Error;
24611 end P1;
24612
24613 procedure P2 is
24614 begin
24615 P1;
24616 end P2;
24617
24618 begin
24619 P2;
24620 end STB;
24621 @end cartouche
24622 @end smallexample
24623
24624 @smallexample
24625 $ gnatmake stb -bargs -E
24626 $ stb
24627
24628 Execution terminated by unhandled exception
24629 Exception name: CONSTRAINT_ERROR
24630 Message: stb.adb:5
24631 Call stack traceback locations:
24632 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24633 @end smallexample
24634
24635 @noindent
24636 As we see the traceback lists a sequence of addresses for the unhandled
24637 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24638 guess that this exception come from procedure P1. To translate these
24639 addresses into the source lines where the calls appear, the
24640 @code{addr2line} tool, described below, is invaluable. The use of this tool
24641 requires the program to be compiled with debug information.
24642
24643 @smallexample
24644 $ gnatmake -g stb -bargs -E
24645 $ stb
24646
24647 Execution terminated by unhandled exception
24648 Exception name: CONSTRAINT_ERROR
24649 Message: stb.adb:5
24650 Call stack traceback locations:
24651 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24652
24653 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24654 0x4011f1 0x77e892a4
24655
24656 00401373 at d:/stb/stb.adb:5
24657 0040138B at d:/stb/stb.adb:10
24658 0040139C at d:/stb/stb.adb:14
24659 00401335 at d:/stb/b~stb.adb:104
24660 004011C4 at /build/@dots{}/crt1.c:200
24661 004011F1 at /build/@dots{}/crt1.c:222
24662 77E892A4 in ?? at ??:0
24663 @end smallexample
24664
24665 @noindent
24666 The @code{addr2line} tool has several other useful options:
24667
24668 @table @code
24669 @item --functions
24670 to get the function name corresponding to any location
24671
24672 @item --demangle=gnat
24673 to use the gnat decoding mode for the function names. Note that
24674 for binutils version 2.9.x the option is simply @option{--demangle}.
24675 @end table
24676
24677 @smallexample
24678 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24679 0x40139c 0x401335 0x4011c4 0x4011f1
24680
24681 00401373 in stb.p1 at d:/stb/stb.adb:5
24682 0040138B in stb.p2 at d:/stb/stb.adb:10
24683 0040139C in stb at d:/stb/stb.adb:14
24684 00401335 in main at d:/stb/b~stb.adb:104
24685 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24686 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24687 @end smallexample
24688
24689 @noindent
24690 From this traceback we can see that the exception was raised in
24691 @file{stb.adb} at line 5, which was reached from a procedure call in
24692 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24693 which contains the call to the main program.
24694 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24695 and the output will vary from platform to platform.
24696
24697 It is also possible to use @code{GDB} with these traceback addresses to debug
24698 the program. For example, we can break at a given code location, as reported
24699 in the stack traceback:
24700
24701 @smallexample
24702 $ gdb -nw stb
24703 @ifclear vms
24704 @noindent
24705 Furthermore, this feature is not implemented inside Windows DLL. Only
24706 the non-symbolic traceback is reported in this case.
24707 @end ifclear
24708
24709 (gdb) break *0x401373
24710 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24711 @end smallexample
24712
24713 @noindent
24714 It is important to note that the stack traceback addresses
24715 do not change when debug information is included. This is particularly useful
24716 because it makes it possible to release software without debug information (to
24717 minimize object size), get a field report that includes a stack traceback
24718 whenever an internal bug occurs, and then be able to retrieve the sequence
24719 of calls with the same program compiled with debug information.
24720
24721 @node Tracebacks From Exception Occurrences (non-symbolic)
24722 @subsubsection Tracebacks From Exception Occurrences
24723
24724 @noindent
24725 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24726 The stack traceback is attached to the exception information string, and can
24727 be retrieved in an exception handler within the Ada program, by means of the
24728 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24729
24730 @smallexample @c ada
24731 with Ada.Text_IO;
24732 with Ada.Exceptions;
24733
24734 procedure STB is
24735
24736 use Ada;
24737 use Ada.Exceptions;
24738
24739 procedure P1 is
24740 K : Positive := 1;
24741 begin
24742 K := K - 1;
24743 exception
24744 when E : others =>
24745 Text_IO.Put_Line (Exception_Information (E));
24746 end P1;
24747
24748 procedure P2 is
24749 begin
24750 P1;
24751 end P2;
24752
24753 begin
24754 P2;
24755 end STB;
24756 @end smallexample
24757
24758 @noindent
24759 This program will output:
24760
24761 @smallexample
24762 $ stb
24763
24764 Exception name: CONSTRAINT_ERROR
24765 Message: stb.adb:12
24766 Call stack traceback locations:
24767 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24768 @end smallexample
24769
24770 @node Tracebacks From Anywhere in a Program (non-symbolic)
24771 @subsubsection Tracebacks From Anywhere in a Program
24772
24773 @noindent
24774 It is also possible to retrieve a stack traceback from anywhere in a
24775 program. For this you need to
24776 use the @code{GNAT.Traceback} API. This package includes a procedure called
24777 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24778 display procedures described below. It is not necessary to use the
24779 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24780 is invoked explicitly.
24781
24782 @noindent
24783 In the following example we compute a traceback at a specific location in
24784 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24785 convert addresses to strings:
24786
24787 @smallexample @c ada
24788 with Ada.Text_IO;
24789 with GNAT.Traceback;
24790 with GNAT.Debug_Utilities;
24791
24792 procedure STB is
24793
24794 use Ada;
24795 use GNAT;
24796 use GNAT.Traceback;
24797
24798 procedure P1 is
24799 TB : Tracebacks_Array (1 .. 10);
24800 -- We are asking for a maximum of 10 stack frames.
24801 Len : Natural;
24802 -- Len will receive the actual number of stack frames returned.
24803 begin
24804 Call_Chain (TB, Len);
24805
24806 Text_IO.Put ("In STB.P1 : ");
24807
24808 for K in 1 .. Len loop
24809 Text_IO.Put (Debug_Utilities.Image (TB (K)));
24810 Text_IO.Put (' ');
24811 end loop;
24812
24813 Text_IO.New_Line;
24814 end P1;
24815
24816 procedure P2 is
24817 begin
24818 P1;
24819 end P2;
24820
24821 begin
24822 P2;
24823 end STB;
24824 @end smallexample
24825
24826 @smallexample
24827 $ gnatmake -g stb
24828 $ stb
24829
24830 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24831 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24832 @end smallexample
24833
24834 @noindent
24835 You can then get further information by invoking the @code{addr2line}
24836 tool as described earlier (note that the hexadecimal addresses
24837 need to be specified in C format, with a leading ``0x'').
24838
24839 @node Symbolic Traceback
24840 @subsection Symbolic Traceback
24841 @cindex traceback, symbolic
24842
24843 @noindent
24844 A symbolic traceback is a stack traceback in which procedure names are
24845 associated with each code location.
24846
24847 @noindent
24848 Note that this feature is not supported on all platforms. See
24849 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24850 list of currently supported platforms.
24851
24852 @noindent
24853 Note that the symbolic traceback requires that the program be compiled
24854 with debug information. If it is not compiled with debug information
24855 only the non-symbolic information will be valid.
24856
24857 @menu
24858 * Tracebacks From Exception Occurrences (symbolic)::
24859 * Tracebacks From Anywhere in a Program (symbolic)::
24860 @end menu
24861
24862 @node Tracebacks From Exception Occurrences (symbolic)
24863 @subsubsection Tracebacks From Exception Occurrences
24864
24865 @smallexample @c ada
24866 with Ada.Text_IO;
24867 with GNAT.Traceback.Symbolic;
24868
24869 procedure STB is
24870
24871 procedure P1 is
24872 begin
24873 raise Constraint_Error;
24874 end P1;
24875
24876 procedure P2 is
24877 begin
24878 P1;
24879 end P2;
24880
24881 procedure P3 is
24882 begin
24883 P2;
24884 end P3;
24885
24886 begin
24887 P3;
24888 exception
24889 when E : others =>
24890 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24891 end STB;
24892 @end smallexample
24893
24894 @smallexample
24895 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24896 $ stb
24897
24898 0040149F in stb.p1 at stb.adb:8
24899 004014B7 in stb.p2 at stb.adb:13
24900 004014CF in stb.p3 at stb.adb:18
24901 004015DD in ada.stb at stb.adb:22
24902 00401461 in main at b~stb.adb:168
24903 004011C4 in __mingw_CRTStartup at crt1.c:200
24904 004011F1 in mainCRTStartup at crt1.c:222
24905 77E892A4 in ?? at ??:0
24906 @end smallexample
24907
24908 @noindent
24909 In the above example the ``.\'' syntax in the @command{gnatmake} command
24910 is currently required by @command{addr2line} for files that are in
24911 the current working directory.
24912 Moreover, the exact sequence of linker options may vary from platform
24913 to platform.
24914 The above @option{-largs} section is for Windows platforms. By contrast,
24915 under Unix there is no need for the @option{-largs} section.
24916 Differences across platforms are due to details of linker implementation.
24917
24918 @node Tracebacks From Anywhere in a Program (symbolic)
24919 @subsubsection Tracebacks From Anywhere in a Program
24920
24921 @noindent
24922 It is possible to get a symbolic stack traceback
24923 from anywhere in a program, just as for non-symbolic tracebacks.
24924 The first step is to obtain a non-symbolic
24925 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24926 information. Here is an example:
24927
24928 @smallexample @c ada
24929 with Ada.Text_IO;
24930 with GNAT.Traceback;
24931 with GNAT.Traceback.Symbolic;
24932
24933 procedure STB is
24934
24935 use Ada;
24936 use GNAT.Traceback;
24937 use GNAT.Traceback.Symbolic;
24938
24939 procedure P1 is
24940 TB : Tracebacks_Array (1 .. 10);
24941 -- We are asking for a maximum of 10 stack frames.
24942 Len : Natural;
24943 -- Len will receive the actual number of stack frames returned.
24944 begin
24945 Call_Chain (TB, Len);
24946 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24947 end P1;
24948
24949 procedure P2 is
24950 begin
24951 P1;
24952 end P2;
24953
24954 begin
24955 P2;
24956 end STB;
24957 @end smallexample
24958
24959 @c ******************************
24960 @ifset vms
24961 @node Compatibility with HP Ada
24962 @chapter Compatibility with HP Ada
24963 @cindex Compatibility
24964
24965 @noindent
24966 @cindex DEC Ada
24967 @cindex HP Ada
24968 @cindex Compatibility between GNAT and HP Ada
24969 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24970 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24971 GNAT is highly compatible
24972 with HP Ada, and it should generally be straightforward to port code
24973 from the HP Ada environment to GNAT. However, there are a few language
24974 and implementation differences of which the user must be aware. These
24975 differences are discussed in this chapter. In
24976 addition, the operating environment and command structure for the
24977 compiler are different, and these differences are also discussed.
24978
24979 For further details on these and other compatibility issues,
24980 see Appendix E of the HP publication
24981 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24982
24983 Except where otherwise indicated, the description of GNAT for OpenVMS
24984 applies to both the Alpha and I64 platforms.
24985
24986 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24987 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24988
24989 The discussion in this chapter addresses specifically the implementation
24990 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24991 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24992 GNAT always follows the Alpha implementation.
24993
24994 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24995 attributes are recognized, although only a subset of them can sensibly
24996 be implemented. The description of pragmas in
24997 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
24998 indicates whether or not they are applicable to non-VMS systems.
24999
25000 @menu
25001 * Ada Language Compatibility::
25002 * Differences in the Definition of Package System::
25003 * Language-Related Features::
25004 * The Package STANDARD::
25005 * The Package SYSTEM::
25006 * Tasking and Task-Related Features::
25007 * Pragmas and Pragma-Related Features::
25008 * Library of Predefined Units::
25009 * Bindings::
25010 * Main Program Definition::
25011 * Implementation-Defined Attributes::
25012 * Compiler and Run-Time Interfacing::
25013 * Program Compilation and Library Management::
25014 * Input-Output::
25015 * Implementation Limits::
25016 * Tools and Utilities::
25017 @end menu
25018
25019 @node Ada Language Compatibility
25020 @section Ada Language Compatibility
25021
25022 @noindent
25023 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25024 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25025 with Ada 83, and therefore Ada 83 programs will compile
25026 and run under GNAT with
25027 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25028 provides details on specific incompatibilities.
25029
25030 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25031 as well as the pragma @code{ADA_83}, to force the compiler to
25032 operate in Ada 83 mode. This mode does not guarantee complete
25033 conformance to Ada 83, but in practice is sufficient to
25034 eliminate most sources of incompatibilities.
25035 In particular, it eliminates the recognition of the
25036 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25037 in Ada 83 programs is legal, and handles the cases of packages
25038 with optional bodies, and generics that instantiate unconstrained
25039 types without the use of @code{(<>)}.
25040
25041 @node Differences in the Definition of Package System
25042 @section Differences in the Definition of Package @code{System}
25043
25044 @noindent
25045 An Ada compiler is allowed to add
25046 implementation-dependent declarations to package @code{System}.
25047 In normal mode,
25048 GNAT does not take advantage of this permission, and the version of
25049 @code{System} provided by GNAT exactly matches that defined in the Ada
25050 Reference Manual.
25051
25052 However, HP Ada adds an extensive set of declarations to package
25053 @code{System},
25054 as fully documented in the HP Ada manuals. To minimize changes required
25055 for programs that make use of these extensions, GNAT provides the pragma
25056 @code{Extend_System} for extending the definition of package System. By using:
25057 @cindex pragma @code{Extend_System}
25058 @cindex @code{Extend_System} pragma
25059
25060 @smallexample @c ada
25061 @group
25062 @cartouche
25063 pragma Extend_System (Aux_DEC);
25064 @end cartouche
25065 @end group
25066 @end smallexample
25067
25068 @noindent
25069 the set of definitions in @code{System} is extended to include those in
25070 package @code{System.Aux_DEC}.
25071 @cindex @code{System.Aux_DEC} package
25072 @cindex @code{Aux_DEC} package (child of @code{System})
25073 These definitions are incorporated directly into package @code{System},
25074 as though they had been declared there. For a
25075 list of the declarations added, see the spec of this package,
25076 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25077 @cindex @file{s-auxdec.ads} file
25078 The pragma @code{Extend_System} is a configuration pragma, which means that
25079 it can be placed in the file @file{gnat.adc}, so that it will automatically
25080 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25081 for further details.
25082
25083 An alternative approach that avoids the use of the non-standard
25084 @code{Extend_System} pragma is to add a context clause to the unit that
25085 references these facilities:
25086
25087 @smallexample @c ada
25088 @cartouche
25089 with System.Aux_DEC;
25090 use System.Aux_DEC;
25091 @end cartouche
25092 @end smallexample
25093
25094 @noindent
25095 The effect is not quite semantically identical to incorporating
25096 the declarations directly into package @code{System},
25097 but most programs will not notice a difference
25098 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25099 to reference the entities directly in package @code{System}.
25100 For units containing such references,
25101 the prefixes must either be removed, or the pragma @code{Extend_System}
25102 must be used.
25103
25104 @node Language-Related Features
25105 @section Language-Related Features
25106
25107 @noindent
25108 The following sections highlight differences in types,
25109 representations of types, operations, alignment, and
25110 related topics.
25111
25112 @menu
25113 * Integer Types and Representations::
25114 * Floating-Point Types and Representations::
25115 * Pragmas Float_Representation and Long_Float::
25116 * Fixed-Point Types and Representations::
25117 * Record and Array Component Alignment::
25118 * Address Clauses::
25119 * Other Representation Clauses::
25120 @end menu
25121
25122 @node Integer Types and Representations
25123 @subsection Integer Types and Representations
25124
25125 @noindent
25126 The set of predefined integer types is identical in HP Ada and GNAT.
25127 Furthermore the representation of these integer types is also identical,
25128 including the capability of size clauses forcing biased representation.
25129
25130 In addition,
25131 HP Ada for OpenVMS Alpha systems has defined the
25132 following additional integer types in package @code{System}:
25133
25134 @itemize @bullet
25135
25136 @item
25137 @code{INTEGER_8}
25138
25139 @item
25140 @code{INTEGER_16}
25141
25142 @item
25143 @code{INTEGER_32}
25144
25145 @item
25146 @code{INTEGER_64}
25147
25148 @item
25149 @code{LARGEST_INTEGER}
25150 @end itemize
25151
25152 @noindent
25153 In GNAT, the first four of these types may be obtained from the
25154 standard Ada package @code{Interfaces}.
25155 Alternatively, by use of the pragma @code{Extend_System}, identical
25156 declarations can be referenced directly in package @code{System}.
25157 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25158
25159 @node Floating-Point Types and Representations
25160 @subsection Floating-Point Types and Representations
25161 @cindex Floating-Point types
25162
25163 @noindent
25164 The set of predefined floating-point types is identical in HP Ada and GNAT.
25165 Furthermore the representation of these floating-point
25166 types is also identical. One important difference is that the default
25167 representation for HP Ada is @code{VAX_Float}, but the default representation
25168 for GNAT is IEEE.
25169
25170 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25171 pragma @code{Float_Representation} as described in the HP Ada
25172 documentation.
25173 For example, the declarations:
25174
25175 @smallexample @c ada
25176 @cartouche
25177 type F_Float is digits 6;
25178 pragma Float_Representation (VAX_Float, F_Float);
25179 @end cartouche
25180 @end smallexample
25181
25182 @noindent
25183 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25184 format.
25185 This set of declarations actually appears in @code{System.Aux_DEC},
25186 which contains
25187 the full set of additional floating-point declarations provided in
25188 the HP Ada version of package @code{System}.
25189 This and similar declarations may be accessed in a user program
25190 by using pragma @code{Extend_System}. The use of this
25191 pragma, and the related pragma @code{Long_Float} is described in further
25192 detail in the following section.
25193
25194 @node Pragmas Float_Representation and Long_Float
25195 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25196
25197 @noindent
25198 HP Ada provides the pragma @code{Float_Representation}, which
25199 acts as a program library switch to allow control over
25200 the internal representation chosen for the predefined
25201 floating-point types declared in the package @code{Standard}.
25202 The format of this pragma is as follows:
25203
25204 @smallexample @c ada
25205 @cartouche
25206 pragma Float_Representation(VAX_Float | IEEE_Float);
25207 @end cartouche
25208 @end smallexample
25209
25210 @noindent
25211 This pragma controls the representation of floating-point
25212 types as follows:
25213
25214 @itemize @bullet
25215 @item
25216 @code{VAX_Float} specifies that floating-point
25217 types are represented by default with the VAX system hardware types
25218 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25219 Note that the @code{H-floating}
25220 type was available only on VAX systems, and is not available
25221 in either HP Ada or GNAT.
25222
25223 @item
25224 @code{IEEE_Float} specifies that floating-point
25225 types are represented by default with the IEEE single and
25226 double floating-point types.
25227 @end itemize
25228
25229 @noindent
25230 GNAT provides an identical implementation of the pragma
25231 @code{Float_Representation}, except that it functions as a
25232 configuration pragma. Note that the
25233 notion of configuration pragma corresponds closely to the
25234 HP Ada notion of a program library switch.
25235
25236 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25237 which is different
25238 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25239 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25240 advisable to change the format of numbers passed to standard library
25241 routines, and if necessary explicit type conversions may be needed.
25242
25243 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25244 efficient, and (given that it conforms to an international standard)
25245 potentially more portable.
25246 The situation in which @code{VAX_Float} may be useful is in interfacing
25247 to existing code and data that expect the use of @code{VAX_Float}.
25248 In such a situation use the predefined @code{VAX_Float}
25249 types in package @code{System}, as extended by
25250 @code{Extend_System}. For example, use @code{System.F_Float}
25251 to specify the 32-bit @code{F-Float} format.
25252
25253 @noindent
25254 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25255 to allow control over the internal representation chosen
25256 for the predefined type @code{Long_Float} and for floating-point
25257 type declarations with digits specified in the range 7 .. 15.
25258 The format of this pragma is as follows:
25259
25260 @smallexample @c ada
25261 @cartouche
25262 pragma Long_Float (D_FLOAT | G_FLOAT);
25263 @end cartouche
25264 @end smallexample
25265
25266 @node Fixed-Point Types and Representations
25267 @subsection Fixed-Point Types and Representations
25268
25269 @noindent
25270 On HP Ada for OpenVMS Alpha systems, rounding is
25271 away from zero for both positive and negative numbers.
25272 Therefore, @code{+0.5} rounds to @code{1},
25273 and @code{-0.5} rounds to @code{-1}.
25274
25275 On GNAT the results of operations
25276 on fixed-point types are in accordance with the Ada
25277 rules. In particular, results of operations on decimal
25278 fixed-point types are truncated.
25279
25280 @node Record and Array Component Alignment
25281 @subsection Record and Array Component Alignment
25282
25283 @noindent
25284 On HP Ada for OpenVMS Alpha, all non-composite components
25285 are aligned on natural boundaries. For example, 1-byte
25286 components are aligned on byte boundaries, 2-byte
25287 components on 2-byte boundaries, 4-byte components on 4-byte
25288 byte boundaries, and so on. The OpenVMS Alpha hardware
25289 runs more efficiently with naturally aligned data.
25290
25291 On GNAT, alignment rules are compatible
25292 with HP Ada for OpenVMS Alpha.
25293
25294 @node Address Clauses
25295 @subsection Address Clauses
25296
25297 @noindent
25298 In HP Ada and GNAT, address clauses are supported for
25299 objects and imported subprograms.
25300 The predefined type @code{System.Address} is a private type
25301 in both compilers on Alpha OpenVMS, with the same representation
25302 (it is simply a machine pointer). Addition, subtraction, and comparison
25303 operations are available in the standard Ada package
25304 @code{System.Storage_Elements}, or in package @code{System}
25305 if it is extended to include @code{System.Aux_DEC} using a
25306 pragma @code{Extend_System} as previously described.
25307
25308 Note that code that @code{with}'s both this extended package @code{System}
25309 and the package @code{System.Storage_Elements} should not @code{use}
25310 both packages, or ambiguities will result. In general it is better
25311 not to mix these two sets of facilities. The Ada package was
25312 designed specifically to provide the kind of features that HP Ada
25313 adds directly to package @code{System}.
25314
25315 The type @code{System.Address} is a 64-bit integer type in GNAT for
25316 I64 OpenVMS. For more information,
25317 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25318
25319 GNAT is compatible with HP Ada in its handling of address
25320 clauses, except for some limitations in
25321 the form of address clauses for composite objects with
25322 initialization. Such address clauses are easily replaced
25323 by the use of an explicitly-defined constant as described
25324 in the Ada Reference Manual (13.1(22)). For example, the sequence
25325 of declarations:
25326
25327 @smallexample @c ada
25328 @cartouche
25329 X, Y : Integer := Init_Func;
25330 Q : String (X .. Y) := "abc";
25331 @dots{}
25332 for Q'Address use Compute_Address;
25333 @end cartouche
25334 @end smallexample
25335
25336 @noindent
25337 will be rejected by GNAT, since the address cannot be computed at the time
25338 that @code{Q} is declared. To achieve the intended effect, write instead:
25339
25340 @smallexample @c ada
25341 @group
25342 @cartouche
25343 X, Y : Integer := Init_Func;
25344 Q_Address : constant Address := Compute_Address;
25345 Q : String (X .. Y) := "abc";
25346 @dots{}
25347 for Q'Address use Q_Address;
25348 @end cartouche
25349 @end group
25350 @end smallexample
25351
25352 @noindent
25353 which will be accepted by GNAT (and other Ada compilers), and is also
25354 compatible with Ada 83. A fuller description of the restrictions
25355 on address specifications is found in @ref{Top, GNAT Reference Manual,
25356 About This Guide, gnat_rm, GNAT Reference Manual}.
25357
25358 @node Other Representation Clauses
25359 @subsection Other Representation Clauses
25360
25361 @noindent
25362 GNAT implements in a compatible manner all the representation
25363 clauses supported by HP Ada. In addition, GNAT
25364 implements the representation clause forms that were introduced in Ada 95,
25365 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25366
25367 @node The Package STANDARD
25368 @section The Package @code{STANDARD}
25369
25370 @noindent
25371 The package @code{STANDARD}, as implemented by HP Ada, is fully
25372 described in the @cite{Ada Reference Manual} and in the
25373 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25374 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25375
25376 In addition, HP Ada supports the Latin-1 character set in
25377 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25378 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25379 the type @code{WIDE_CHARACTER}.
25380
25381 The floating-point types supported by GNAT are those
25382 supported by HP Ada, but the defaults are different, and are controlled by
25383 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25384
25385 @node The Package SYSTEM
25386 @section The Package @code{SYSTEM}
25387
25388 @noindent
25389 HP Ada provides a specific version of the package
25390 @code{SYSTEM} for each platform on which the language is implemented.
25391 For the complete spec of the package @code{SYSTEM}, see
25392 Appendix F of the @cite{HP Ada Language Reference Manual}.
25393
25394 On HP Ada, the package @code{SYSTEM} includes the following conversion
25395 functions:
25396 @itemize @bullet
25397 @item @code{TO_ADDRESS(INTEGER)}
25398
25399 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25400
25401 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25402
25403 @item @code{TO_INTEGER(ADDRESS)}
25404
25405 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25406
25407 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25408 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25409 @end itemize
25410
25411 @noindent
25412 By default, GNAT supplies a version of @code{SYSTEM} that matches
25413 the definition given in the @cite{Ada Reference Manual}.
25414 This
25415 is a subset of the HP system definitions, which is as
25416 close as possible to the original definitions. The only difference
25417 is that the definition of @code{SYSTEM_NAME} is different:
25418
25419 @smallexample @c ada
25420 @cartouche
25421 type Name is (SYSTEM_NAME_GNAT);
25422 System_Name : constant Name := SYSTEM_NAME_GNAT;
25423 @end cartouche
25424 @end smallexample
25425
25426 @noindent
25427 Also, GNAT adds the Ada declarations for
25428 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25429
25430 However, the use of the following pragma causes GNAT
25431 to extend the definition of package @code{SYSTEM} so that it
25432 encompasses the full set of HP-specific extensions,
25433 including the functions listed above:
25434
25435 @smallexample @c ada
25436 @cartouche
25437 pragma Extend_System (Aux_DEC);
25438 @end cartouche
25439 @end smallexample
25440
25441 @noindent
25442 The pragma @code{Extend_System} is a configuration pragma that
25443 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25444 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25445
25446 HP Ada does not allow the recompilation of the package
25447 @code{SYSTEM}. Instead HP Ada provides several pragmas
25448 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25449 to modify values in the package @code{SYSTEM}.
25450 On OpenVMS Alpha systems, the pragma
25451 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25452 its single argument.
25453
25454 GNAT does permit the recompilation of package @code{SYSTEM} using
25455 the special switch @option{-gnatg}, and this switch can be used if
25456 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25457 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25458 or @code{MEMORY_SIZE} by any other means.
25459
25460 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25461 enumeration literal @code{SYSTEM_NAME_GNAT}.
25462
25463 The definitions provided by the use of
25464
25465 @smallexample @c ada
25466 pragma Extend_System (AUX_Dec);
25467 @end smallexample
25468
25469 @noindent
25470 are virtually identical to those provided by the HP Ada 83 package
25471 @code{SYSTEM}. One important difference is that the name of the
25472 @code{TO_ADDRESS}
25473 function for type @code{UNSIGNED_LONGWORD} is changed to
25474 @code{TO_ADDRESS_LONG}.
25475 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25476 discussion of why this change was necessary.
25477
25478 @noindent
25479 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25480 is in fact
25481 an extension to Ada 83 not strictly compatible with the reference manual.
25482 GNAT, in order to be exactly compatible with the standard,
25483 does not provide this capability. In HP Ada 83, the
25484 point of this definition is to deal with a call like:
25485
25486 @smallexample @c ada
25487 TO_ADDRESS (16#12777#);
25488 @end smallexample
25489
25490 @noindent
25491 Normally, according to Ada 83 semantics, one would expect this to be
25492 ambiguous, since it matches both the @code{INTEGER} and
25493 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25494 However, in HP Ada 83, there is no ambiguity, since the
25495 definition using @i{universal_integer} takes precedence.
25496
25497 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25498 it is
25499 not possible to be 100% compatible. Since there are many programs using
25500 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25501 GNAT was
25502 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25503 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25504
25505 @smallexample @c ada
25506 function To_Address (X : Integer) return Address;
25507 pragma Pure_Function (To_Address);
25508
25509 function To_Address_Long (X : Unsigned_Longword) return Address;
25510 pragma Pure_Function (To_Address_Long);
25511 @end smallexample
25512
25513 @noindent
25514 This means that programs using @code{TO_ADDRESS} for
25515 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25516
25517 @node Tasking and Task-Related Features
25518 @section Tasking and Task-Related Features
25519
25520 @noindent
25521 This section compares the treatment of tasking in GNAT
25522 and in HP Ada for OpenVMS Alpha.
25523 The GNAT description applies to both Alpha and I64 OpenVMS.
25524 For detailed information on tasking in
25525 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25526 relevant run-time reference manual.
25527
25528 @menu
25529 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25530 * Assigning Task IDs::
25531 * Task IDs and Delays::
25532 * Task-Related Pragmas::
25533 * Scheduling and Task Priority::
25534 * The Task Stack::
25535 * External Interrupts::
25536 @end menu
25537
25538 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25539 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25540
25541 @noindent
25542 On OpenVMS Alpha systems, each Ada task (except a passive
25543 task) is implemented as a single stream of execution
25544 that is created and managed by the kernel. On these
25545 systems, HP Ada tasking support is based on DECthreads,
25546 an implementation of the POSIX standard for threads.
25547
25548 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25549 code that calls DECthreads routines can be used together.
25550 The interaction between Ada tasks and DECthreads routines
25551 can have some benefits. For example when on OpenVMS Alpha,
25552 HP Ada can call C code that is already threaded.
25553
25554 GNAT uses the facilities of DECthreads,
25555 and Ada tasks are mapped to threads.
25556
25557 @node Assigning Task IDs
25558 @subsection Assigning Task IDs
25559
25560 @noindent
25561 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25562 the environment task that executes the main program. On
25563 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25564 that have been created but are not yet activated.
25565
25566 On OpenVMS Alpha systems, task IDs are assigned at
25567 activation. On GNAT systems, task IDs are also assigned at
25568 task creation but do not have the same form or values as
25569 task ID values in HP Ada. There is no null task, and the
25570 environment task does not have a specific task ID value.
25571
25572 @node Task IDs and Delays
25573 @subsection Task IDs and Delays
25574
25575 @noindent
25576 On OpenVMS Alpha systems, tasking delays are implemented
25577 using Timer System Services. The Task ID is used for the
25578 identification of the timer request (the @code{REQIDT} parameter).
25579 If Timers are used in the application take care not to use
25580 @code{0} for the identification, because cancelling such a timer
25581 will cancel all timers and may lead to unpredictable results.
25582
25583 @node Task-Related Pragmas
25584 @subsection Task-Related Pragmas
25585
25586 @noindent
25587 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25588 specification of the size of the guard area for a task
25589 stack. (The guard area forms an area of memory that has no
25590 read or write access and thus helps in the detection of
25591 stack overflow.) On OpenVMS Alpha systems, if the pragma
25592 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25593 area is created. In the absence of a pragma @code{TASK_STORAGE},
25594 a default guard area is created.
25595
25596 GNAT supplies the following task-related pragmas:
25597
25598 @itemize @bullet
25599 @item @code{TASK_INFO}
25600
25601 This pragma appears within a task definition and
25602 applies to the task in which it appears. The argument
25603 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25604
25605 @item @code{TASK_STORAGE}
25606
25607 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25608 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25609 @code{SUPPRESS}, and @code{VOLATILE}.
25610 @end itemize
25611 @node Scheduling and Task Priority
25612 @subsection Scheduling and Task Priority
25613
25614 @noindent
25615 HP Ada implements the Ada language requirement that
25616 when two tasks are eligible for execution and they have
25617 different priorities, the lower priority task does not
25618 execute while the higher priority task is waiting. The HP
25619 Ada Run-Time Library keeps a task running until either the
25620 task is suspended or a higher priority task becomes ready.
25621
25622 On OpenVMS Alpha systems, the default strategy is round-
25623 robin with preemption. Tasks of equal priority take turns
25624 at the processor. A task is run for a certain period of
25625 time and then placed at the tail of the ready queue for
25626 its priority level.
25627
25628 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25629 which can be used to enable or disable round-robin
25630 scheduling of tasks with the same priority.
25631 See the relevant HP Ada run-time reference manual for
25632 information on using the pragmas to control HP Ada task
25633 scheduling.
25634
25635 GNAT follows the scheduling rules of Annex D (Real-Time
25636 Annex) of the @cite{Ada Reference Manual}. In general, this
25637 scheduling strategy is fully compatible with HP Ada
25638 although it provides some additional constraints (as
25639 fully documented in Annex D).
25640 GNAT implements time slicing control in a manner compatible with
25641 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25642 are identical to the HP Ada 83 pragma of the same name.
25643 Note that it is not possible to mix GNAT tasking and
25644 HP Ada 83 tasking in the same program, since the two run-time
25645 libraries are not compatible.
25646
25647 @node The Task Stack
25648 @subsection The Task Stack
25649
25650 @noindent
25651 In HP Ada, a task stack is allocated each time a
25652 non-passive task is activated. As soon as the task is
25653 terminated, the storage for the task stack is deallocated.
25654 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25655 a default stack size is used. Also, regardless of the size
25656 specified, some additional space is allocated for task
25657 management purposes. On OpenVMS Alpha systems, at least
25658 one page is allocated.
25659
25660 GNAT handles task stacks in a similar manner. In accordance with
25661 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25662 an alternative method for controlling the task stack size.
25663 The specification of the attribute @code{T'STORAGE_SIZE} is also
25664 supported in a manner compatible with HP Ada.
25665
25666 @node External Interrupts
25667 @subsection External Interrupts
25668
25669 @noindent
25670 On HP Ada, external interrupts can be associated with task entries.
25671 GNAT is compatible with HP Ada in its handling of external interrupts.
25672
25673 @node Pragmas and Pragma-Related Features
25674 @section Pragmas and Pragma-Related Features
25675
25676 @noindent
25677 Both HP Ada and GNAT supply all language-defined pragmas
25678 as specified by the Ada 83 standard. GNAT also supplies all
25679 language-defined pragmas introduced by Ada 95 and Ada 2005.
25680 In addition, GNAT implements the implementation-defined pragmas
25681 from HP Ada 83.
25682
25683 @itemize @bullet
25684 @item @code{AST_ENTRY}
25685
25686 @item @code{COMMON_OBJECT}
25687
25688 @item @code{COMPONENT_ALIGNMENT}
25689
25690 @item @code{EXPORT_EXCEPTION}
25691
25692 @item @code{EXPORT_FUNCTION}
25693
25694 @item @code{EXPORT_OBJECT}
25695
25696 @item @code{EXPORT_PROCEDURE}
25697
25698 @item @code{EXPORT_VALUED_PROCEDURE}
25699
25700 @item @code{FLOAT_REPRESENTATION}
25701
25702 @item @code{IDENT}
25703
25704 @item @code{IMPORT_EXCEPTION}
25705
25706 @item @code{IMPORT_FUNCTION}
25707
25708 @item @code{IMPORT_OBJECT}
25709
25710 @item @code{IMPORT_PROCEDURE}
25711
25712 @item @code{IMPORT_VALUED_PROCEDURE}
25713
25714 @item @code{INLINE_GENERIC}
25715
25716 @item @code{INTERFACE_NAME}
25717
25718 @item @code{LONG_FLOAT}
25719
25720 @item @code{MAIN_STORAGE}
25721
25722 @item @code{PASSIVE}
25723
25724 @item @code{PSECT_OBJECT}
25725
25726 @item @code{SHARE_GENERIC}
25727
25728 @item @code{SUPPRESS_ALL}
25729
25730 @item @code{TASK_STORAGE}
25731
25732 @item @code{TIME_SLICE}
25733
25734 @item @code{TITLE}
25735 @end itemize
25736
25737 @noindent
25738 These pragmas are all fully implemented, with the exception of @code{TITLE},
25739 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25740 recognized, but which have no
25741 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25742 use of Ada protected objects. In GNAT, all generics are inlined.
25743
25744 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25745 a separate subprogram specification which must appear before the
25746 subprogram body.
25747
25748 GNAT also supplies a number of implementation-defined pragmas as follows:
25749 @itemize @bullet
25750 @item @code{ABORT_DEFER}
25751
25752 @item @code{ADA_83}
25753
25754 @item @code{ADA_95}
25755
25756 @item @code{ADA_05}
25757
25758 @item @code{ANNOTATE}
25759
25760 @item @code{ASSERT}
25761
25762 @item @code{C_PASS_BY_COPY}
25763
25764 @item @code{CPP_CLASS}
25765
25766 @item @code{CPP_CONSTRUCTOR}
25767
25768 @item @code{CPP_DESTRUCTOR}
25769
25770 @item @code{DEBUG}
25771
25772 @item @code{EXTEND_SYSTEM}
25773
25774 @item @code{LINKER_ALIAS}
25775
25776 @item @code{LINKER_SECTION}
25777
25778 @item @code{MACHINE_ATTRIBUTE}
25779
25780 @item @code{NO_RETURN}
25781
25782 @item @code{PURE_FUNCTION}
25783
25784 @item @code{SOURCE_FILE_NAME}
25785
25786 @item @code{SOURCE_REFERENCE}
25787
25788 @item @code{TASK_INFO}
25789
25790 @item @code{UNCHECKED_UNION}
25791
25792 @item @code{UNIMPLEMENTED_UNIT}
25793
25794 @item @code{UNIVERSAL_DATA}
25795
25796 @item @code{UNSUPPRESS}
25797
25798 @item @code{WARNINGS}
25799
25800 @item @code{WEAK_EXTERNAL}
25801 @end itemize
25802
25803 @noindent
25804 For full details on these GNAT implementation-defined pragmas,
25805 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25806 Manual}.
25807
25808 @menu
25809 * Restrictions on the Pragma INLINE::
25810 * Restrictions on the Pragma INTERFACE::
25811 * Restrictions on the Pragma SYSTEM_NAME::
25812 @end menu
25813
25814 @node Restrictions on the Pragma INLINE
25815 @subsection Restrictions on Pragma @code{INLINE}
25816
25817 @noindent
25818 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25819 @itemize @bullet
25820 @item Parameters cannot have a task type.
25821
25822 @item Function results cannot be task types, unconstrained
25823 array types, or unconstrained types with discriminants.
25824
25825 @item Bodies cannot declare the following:
25826 @itemize @bullet
25827 @item Subprogram body or stub (imported subprogram is allowed)
25828
25829 @item Tasks
25830
25831 @item Generic declarations
25832
25833 @item Instantiations
25834
25835 @item Exceptions
25836
25837 @item Access types (types derived from access types allowed)
25838
25839 @item Array or record types
25840
25841 @item Dependent tasks
25842
25843 @item Direct recursive calls of subprogram or containing
25844 subprogram, directly or via a renaming
25845
25846 @end itemize
25847 @end itemize
25848
25849 @noindent
25850 In GNAT, the only restriction on pragma @code{INLINE} is that the
25851 body must occur before the call if both are in the same
25852 unit, and the size must be appropriately small. There are
25853 no other specific restrictions which cause subprograms to
25854 be incapable of being inlined.
25855
25856 @node Restrictions on the Pragma INTERFACE
25857 @subsection Restrictions on Pragma @code{INTERFACE}
25858
25859 @noindent
25860 The following restrictions on pragma @code{INTERFACE}
25861 are enforced by both HP Ada and GNAT:
25862 @itemize @bullet
25863 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
25864 Default is the default on OpenVMS Alpha systems.
25865
25866 @item Parameter passing: Language specifies default
25867 mechanisms but can be overridden with an @code{EXPORT} pragma.
25868
25869 @itemize @bullet
25870 @item Ada: Use internal Ada rules.
25871
25872 @item Bliss, C: Parameters must be mode @code{in}; cannot be
25873 record or task type. Result cannot be a string, an
25874 array, or a record.
25875
25876 @item Fortran: Parameters cannot have a task type. Result cannot
25877 be a string, an array, or a record.
25878 @end itemize
25879 @end itemize
25880
25881 @noindent
25882 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25883 record parameters for all languages.
25884
25885 @node Restrictions on the Pragma SYSTEM_NAME
25886 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
25887
25888 @noindent
25889 For HP Ada for OpenVMS Alpha, the enumeration literal
25890 for the type @code{NAME} is @code{OPENVMS_AXP}.
25891 In GNAT, the enumeration
25892 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25893
25894 @node Library of Predefined Units
25895 @section Library of Predefined Units
25896
25897 @noindent
25898 A library of predefined units is provided as part of the
25899 HP Ada and GNAT implementations. HP Ada does not provide
25900 the package @code{MACHINE_CODE} but instead recommends importing
25901 assembler code.
25902
25903 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25904 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25905 version.
25906 The HP Ada Predefined Library units are modified to remove post-Ada 83
25907 incompatibilities and to make them interoperable with GNAT
25908 (@pxref{Changes to DECLIB}, for details).
25909 The units are located in the @file{DECLIB} directory.
25910
25911 The GNAT RTL is contained in
25912 the @file{ADALIB} directory, and
25913 the default search path is set up to find @code{DECLIB} units in preference
25914 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25915 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25916
25917 @menu
25918 * Changes to DECLIB::
25919 @end menu
25920
25921 @node Changes to DECLIB
25922 @subsection Changes to @code{DECLIB}
25923
25924 @noindent
25925 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25926 compatibility are minor and include the following:
25927
25928 @itemize @bullet
25929 @item Adjusting the location of pragmas and record representation
25930 clauses to obey Ada 95 (and thus Ada 2005) rules
25931
25932 @item Adding the proper notation to generic formal parameters
25933 that take unconstrained types in instantiation
25934
25935 @item Adding pragma @code{ELABORATE_BODY} to package specs
25936 that have package bodies not otherwise allowed
25937
25938 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25939 ``@code{PROTECTD}''.
25940 Currently these are found only in the @code{STARLET} package spec.
25941
25942 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25943 where the address size is constrained to 32 bits.
25944 @end itemize
25945
25946 @noindent
25947 None of the above changes is visible to users.
25948
25949 @node Bindings
25950 @section Bindings
25951
25952 @noindent
25953 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25954 @itemize @bullet
25955
25956 @item Command Language Interpreter (CLI interface)
25957
25958 @item DECtalk Run-Time Library (DTK interface)
25959
25960 @item Librarian utility routines (LBR interface)
25961
25962 @item General Purpose Run-Time Library (LIB interface)
25963
25964 @item Math Run-Time Library (MTH interface)
25965
25966 @item National Character Set Run-Time Library (NCS interface)
25967
25968 @item Compiled Code Support Run-Time Library (OTS interface)
25969
25970 @item Parallel Processing Run-Time Library (PPL interface)
25971
25972 @item Screen Management Run-Time Library (SMG interface)
25973
25974 @item Sort Run-Time Library (SOR interface)
25975
25976 @item String Run-Time Library (STR interface)
25977
25978 @item STARLET System Library
25979 @findex Starlet
25980
25981 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
25982
25983 @item X Windows Toolkit (XT interface)
25984
25985 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
25986 @end itemize
25987
25988 @noindent
25989 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25990 directory, on both the Alpha and I64 OpenVMS platforms.
25991
25992 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25993 in the
25994 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25995 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25996 @code{Xt}, and @code{X_Lib}
25997 causing the default X/Motif sharable image libraries to be linked in. This
25998 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25999 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26000
26001 It may be necessary to edit these options files to update or correct the
26002 library names if, for example, the newer X/Motif bindings from
26003 @file{ADA$EXAMPLES}
26004 had been (previous to installing GNAT) copied and renamed to supersede the
26005 default @file{ADA$PREDEFINED} versions.
26006
26007 @menu
26008 * Shared Libraries and Options Files::
26009 * Interfaces to C::
26010 @end menu
26011
26012 @node Shared Libraries and Options Files
26013 @subsection Shared Libraries and Options Files
26014
26015 @noindent
26016 When using the HP Ada
26017 predefined X and Motif bindings, the linking with their sharable images is
26018 done automatically by @command{GNAT LINK}.
26019 When using other X and Motif bindings, you need
26020 to add the corresponding sharable images to the command line for
26021 @code{GNAT LINK}. When linking with shared libraries, or with
26022 @file{.OPT} files, you must
26023 also add them to the command line for @command{GNAT LINK}.
26024
26025 A shared library to be used with GNAT is built in the same way as other
26026 libraries under VMS. The VMS Link command can be used in standard fashion.
26027
26028 @node Interfaces to C
26029 @subsection Interfaces to C
26030
26031 @noindent
26032 HP Ada
26033 provides the following Ada types and operations:
26034
26035 @itemize @bullet
26036 @item C types package (@code{C_TYPES})
26037
26038 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26039
26040 @item Other_types (@code{SHORT_INT})
26041 @end itemize
26042
26043 @noindent
26044 Interfacing to C with GNAT, you can use the above approach
26045 described for HP Ada or the facilities of Annex B of
26046 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26047 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26048 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26049
26050 The @option{-gnatF} qualifier forces default and explicit
26051 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26052 to be uppercased for compatibility with the default behavior
26053 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26054
26055 @node Main Program Definition
26056 @section Main Program Definition
26057
26058 @noindent
26059 The following section discusses differences in the
26060 definition of main programs on HP Ada and GNAT.
26061 On HP Ada, main programs are defined to meet the
26062 following conditions:
26063 @itemize @bullet
26064 @item Procedure with no formal parameters (returns @code{0} upon
26065 normal completion)
26066
26067 @item Procedure with no formal parameters (returns @code{42} when
26068 an unhandled exception is raised)
26069
26070 @item Function with no formal parameters whose returned value
26071 is of a discrete type
26072
26073 @item Procedure with one @code{out} formal of a discrete type for
26074 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26075
26076 @end itemize
26077
26078 @noindent
26079 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26080 a main function or main procedure returns a discrete
26081 value whose size is less than 64 bits (32 on VAX systems),
26082 the value is zero- or sign-extended as appropriate.
26083 On GNAT, main programs are defined as follows:
26084 @itemize @bullet
26085 @item Must be a non-generic, parameterless subprogram that
26086 is either a procedure or function returning an Ada
26087 @code{STANDARD.INTEGER} (the predefined type)
26088
26089 @item Cannot be a generic subprogram or an instantiation of a
26090 generic subprogram
26091 @end itemize
26092
26093 @node Implementation-Defined Attributes
26094 @section Implementation-Defined Attributes
26095
26096 @noindent
26097 GNAT provides all HP Ada implementation-defined
26098 attributes.
26099
26100 @node Compiler and Run-Time Interfacing
26101 @section Compiler and Run-Time Interfacing
26102
26103 @noindent
26104 HP Ada provides the following qualifiers to pass options to the linker
26105 (ACS LINK):
26106 @itemize @bullet
26107 @item @option{/WAIT} and @option{/SUBMIT}
26108
26109 @item @option{/COMMAND}
26110
26111 @item @option{/@r{[}NO@r{]}MAP}
26112
26113 @item @option{/OUTPUT=@var{file-spec}}
26114
26115 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26116 @end itemize
26117
26118 @noindent
26119 To pass options to the linker, GNAT provides the following
26120 switches:
26121
26122 @itemize @bullet
26123 @item @option{/EXECUTABLE=@var{exec-name}}
26124
26125 @item @option{/VERBOSE}
26126
26127 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26128 @end itemize
26129
26130 @noindent
26131 For more information on these switches, see
26132 @ref{Switches for gnatlink}.
26133 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26134 to control optimization. HP Ada also supplies the
26135 following pragmas:
26136 @itemize @bullet
26137 @item @code{OPTIMIZE}
26138
26139 @item @code{INLINE}
26140
26141 @item @code{INLINE_GENERIC}
26142
26143 @item @code{SUPPRESS_ALL}
26144
26145 @item @code{PASSIVE}
26146 @end itemize
26147
26148 @noindent
26149 In GNAT, optimization is controlled strictly by command
26150 line parameters, as described in the corresponding section of this guide.
26151 The HP pragmas for control of optimization are
26152 recognized but ignored.
26153
26154 Note that in GNAT, the default is optimization off, whereas in HP Ada
26155 the default is that optimization is turned on.
26156
26157 @node Program Compilation and Library Management
26158 @section Program Compilation and Library Management
26159
26160 @noindent
26161 HP Ada and GNAT provide a comparable set of commands to
26162 build programs. HP Ada also provides a program library,
26163 which is a concept that does not exist on GNAT. Instead,
26164 GNAT provides directories of sources that are compiled as
26165 needed.
26166
26167 The following table summarizes
26168 the HP Ada commands and provides
26169 equivalent GNAT commands. In this table, some GNAT
26170 equivalents reflect the fact that GNAT does not use the
26171 concept of a program library. Instead, it uses a model
26172 in which collections of source and object files are used
26173 in a manner consistent with other languages like C and
26174 Fortran. Therefore, standard system file commands are used
26175 to manipulate these elements. Those GNAT commands are marked with
26176 an asterisk.
26177 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26178
26179 @need 1500
26180 @multitable @columnfractions .35 .65
26181
26182 @item @emph{HP Ada Command}
26183 @tab @emph{GNAT Equivalent / Description}
26184
26185 @item @command{ADA}
26186 @tab @command{GNAT COMPILE}@*
26187 Invokes the compiler to compile one or more Ada source files.
26188
26189 @item @command{ACS ATTACH}@*
26190 @tab [No equivalent]@*
26191 Switches control of terminal from current process running the program
26192 library manager.
26193
26194 @item @command{ACS CHECK}
26195 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26196 Forms the execution closure of one
26197 or more compiled units and checks completeness and currency.
26198
26199 @item @command{ACS COMPILE}
26200 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26201 Forms the execution closure of one or
26202 more specified units, checks completeness and currency,
26203 identifies units that have revised source files, compiles same,
26204 and recompiles units that are or will become obsolete.
26205 Also completes incomplete generic instantiations.
26206
26207 @item @command{ACS COPY FOREIGN}
26208 @tab Copy (*)@*
26209 Copies a foreign object file into the program library as a
26210 library unit body.
26211
26212 @item @command{ACS COPY UNIT}
26213 @tab Copy (*)@*
26214 Copies a compiled unit from one program library to another.
26215
26216 @item @command{ACS CREATE LIBRARY}
26217 @tab Create /directory (*)@*
26218 Creates a program library.
26219
26220 @item @command{ACS CREATE SUBLIBRARY}
26221 @tab Create /directory (*)@*
26222 Creates a program sublibrary.
26223
26224 @item @command{ACS DELETE LIBRARY}
26225 @tab @*
26226 Deletes a program library and its contents.
26227
26228 @item @command{ACS DELETE SUBLIBRARY}
26229 @tab @*
26230 Deletes a program sublibrary and its contents.
26231
26232 @item @command{ACS DELETE UNIT}
26233 @tab Delete file (*)@*
26234 On OpenVMS systems, deletes one or more compiled units from
26235 the current program library.
26236
26237 @item @command{ACS DIRECTORY}
26238 @tab Directory (*)@*
26239 On OpenVMS systems, lists units contained in the current
26240 program library.
26241
26242 @item @command{ACS ENTER FOREIGN}
26243 @tab Copy (*)@*
26244 Allows the import of a foreign body as an Ada library
26245 spec and enters a reference to a pointer.
26246
26247 @item @command{ACS ENTER UNIT}
26248 @tab Copy (*)@*
26249 Enters a reference (pointer) from the current program library to
26250 a unit compiled into another program library.
26251
26252 @item @command{ACS EXIT}
26253 @tab [No equivalent]@*
26254 Exits from the program library manager.
26255
26256 @item @command{ACS EXPORT}
26257 @tab Copy (*)@*
26258 Creates an object file that contains system-specific object code
26259 for one or more units. With GNAT, object files can simply be copied
26260 into the desired directory.
26261
26262 @item @command{ACS EXTRACT SOURCE}
26263 @tab Copy (*)@*
26264 Allows access to the copied source file for each Ada compilation unit
26265
26266 @item @command{ACS HELP}
26267 @tab @command{HELP GNAT}@*
26268 Provides online help.
26269
26270 @item @command{ACS LINK}
26271 @tab @command{GNAT LINK}@*
26272 Links an object file containing Ada units into an executable file.
26273
26274 @item @command{ACS LOAD}
26275 @tab Copy (*)@*
26276 Loads (partially compiles) Ada units into the program library.
26277 Allows loading a program from a collection of files into a library
26278 without knowing the relationship among units.
26279
26280 @item @command{ACS MERGE}
26281 @tab Copy (*)@*
26282 Merges into the current program library, one or more units from
26283 another library where they were modified.
26284
26285 @item @command{ACS RECOMPILE}
26286 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26287 Recompiles from external or copied source files any obsolete
26288 unit in the closure. Also, completes any incomplete generic
26289 instantiations.
26290
26291 @item @command{ACS REENTER}
26292 @tab @command{GNAT MAKE}@*
26293 Reenters current references to units compiled after last entered
26294 with the @command{ACS ENTER UNIT} command.
26295
26296 @item @command{ACS SET LIBRARY}
26297 @tab Set default (*)@*
26298 Defines a program library to be the compilation context as well
26299 as the target library for compiler output and commands in general.
26300
26301 @item @command{ACS SET PRAGMA}
26302 @tab Edit @file{gnat.adc} (*)@*
26303 Redefines specified values of the library characteristics
26304 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26305 and @code{Float_Representation}.
26306
26307 @item @command{ACS SET SOURCE}
26308 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26309 Defines the source file search list for the @command{ACS COMPILE} command.
26310
26311 @item @command{ACS SHOW LIBRARY}
26312 @tab Directory (*)@*
26313 Lists information about one or more program libraries.
26314
26315 @item @command{ACS SHOW PROGRAM}
26316 @tab [No equivalent]@*
26317 Lists information about the execution closure of one or
26318 more units in the program library.
26319
26320 @item @command{ACS SHOW SOURCE}
26321 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26322 Shows the source file search used when compiling units.
26323
26324 @item @command{ACS SHOW VERSION}
26325 @tab Compile with @option{VERBOSE} option
26326 Displays the version number of the compiler and program library
26327 manager used.
26328
26329 @item @command{ACS SPAWN}
26330 @tab [No equivalent]@*
26331 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26332 command).
26333
26334 @item @command{ACS VERIFY}
26335 @tab [No equivalent]@*
26336 Performs a series of consistency checks on a program library to
26337 determine whether the library structure and library files are in
26338 valid form.
26339 @end multitable
26340
26341 @noindent
26342
26343 @node Input-Output
26344 @section Input-Output
26345
26346 @noindent
26347 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26348 Management Services (RMS) to perform operations on
26349 external files.
26350
26351 @noindent
26352 HP Ada and GNAT predefine an identical set of input-
26353 output packages. To make the use of the
26354 generic @code{TEXT_IO} operations more convenient, HP Ada
26355 provides predefined library packages that instantiate the
26356 integer and floating-point operations for the predefined
26357 integer and floating-point types as shown in the following table.
26358
26359 @multitable @columnfractions .45 .55
26360 @item @emph{Package Name} @tab Instantiation
26361
26362 @item @code{INTEGER_TEXT_IO}
26363 @tab @code{INTEGER_IO(INTEGER)}
26364
26365 @item @code{SHORT_INTEGER_TEXT_IO}
26366 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26367
26368 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26369 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26370
26371 @item @code{FLOAT_TEXT_IO}
26372 @tab @code{FLOAT_IO(FLOAT)}
26373
26374 @item @code{LONG_FLOAT_TEXT_IO}
26375 @tab @code{FLOAT_IO(LONG_FLOAT)}
26376 @end multitable
26377
26378 @noindent
26379 The HP Ada predefined packages and their operations
26380 are implemented using OpenVMS Alpha files and input-output
26381 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26382 Familiarity with the following is recommended:
26383 @itemize @bullet
26384 @item RMS file organizations and access methods
26385
26386 @item OpenVMS file specifications and directories
26387
26388 @item OpenVMS File Definition Language (FDL)
26389 @end itemize
26390
26391 @noindent
26392 GNAT provides I/O facilities that are completely
26393 compatible with HP Ada. The distribution includes the
26394 standard HP Ada versions of all I/O packages, operating
26395 in a manner compatible with HP Ada. In particular, the
26396 following packages are by default the HP Ada (Ada 83)
26397 versions of these packages rather than the renamings
26398 suggested in Annex J of the Ada Reference Manual:
26399 @itemize @bullet
26400 @item @code{TEXT_IO}
26401
26402 @item @code{SEQUENTIAL_IO}
26403
26404 @item @code{DIRECT_IO}
26405 @end itemize
26406
26407 @noindent
26408 The use of the standard child package syntax (for
26409 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26410 packages.
26411 GNAT provides HP-compatible predefined instantiations
26412 of the @code{TEXT_IO} packages, and also
26413 provides the standard predefined instantiations required
26414 by the @cite{Ada Reference Manual}.
26415
26416 For further information on how GNAT interfaces to the file
26417 system or how I/O is implemented in programs written in
26418 mixed languages, see @ref{Implementation of the Standard I/O,,,
26419 gnat_rm, GNAT Reference Manual}.
26420 This chapter covers the following:
26421 @itemize @bullet
26422 @item Standard I/O packages
26423
26424 @item @code{FORM} strings
26425
26426 @item @code{ADA.DIRECT_IO}
26427
26428 @item @code{ADA.SEQUENTIAL_IO}
26429
26430 @item @code{ADA.TEXT_IO}
26431
26432 @item Stream pointer positioning
26433
26434 @item Reading and writing non-regular files
26435
26436 @item @code{GET_IMMEDIATE}
26437
26438 @item Treating @code{TEXT_IO} files as streams
26439
26440 @item Shared files
26441
26442 @item Open modes
26443 @end itemize
26444
26445 @node Implementation Limits
26446 @section Implementation Limits
26447
26448 @noindent
26449 The following table lists implementation limits for HP Ada
26450 and GNAT systems.
26451 @multitable @columnfractions .60 .20 .20
26452 @sp 1
26453 @item @emph{Compilation Parameter}
26454 @tab @emph{HP Ada}
26455 @tab @emph{GNAT}
26456 @sp 1
26457
26458 @item In a subprogram or entry declaration, maximum number of
26459 formal parameters that are of an unconstrained record type
26460 @tab 32
26461 @tab No set limit
26462 @sp 1
26463
26464 @item Maximum identifier length (number of characters)
26465 @tab 255
26466 @tab 32766
26467 @sp 1
26468
26469 @item Maximum number of characters in a source line
26470 @tab 255
26471 @tab 32766
26472 @sp 1
26473
26474 @item Maximum collection size (number of bytes)
26475 @tab 2**31-1
26476 @tab 2**31-1
26477 @sp 1
26478
26479 @item Maximum number of discriminants for a record type
26480 @tab 245
26481 @tab No set limit
26482 @sp 1
26483
26484 @item Maximum number of formal parameters in an entry or
26485 subprogram declaration
26486 @tab 246
26487 @tab No set limit
26488 @sp 1
26489
26490 @item Maximum number of dimensions in an array type
26491 @tab 255
26492 @tab No set limit
26493 @sp 1
26494
26495 @item Maximum number of library units and subunits in a compilation.
26496 @tab 4095
26497 @tab No set limit
26498 @sp 1
26499
26500 @item Maximum number of library units and subunits in an execution.
26501 @tab 16383
26502 @tab No set limit
26503 @sp 1
26504
26505 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26506 or @code{PSECT_OBJECT}
26507 @tab 32757
26508 @tab No set limit
26509 @sp 1
26510
26511 @item Maximum number of enumeration literals in an enumeration type
26512 definition
26513 @tab 65535
26514 @tab No set limit
26515 @sp 1
26516
26517 @item Maximum number of lines in a source file
26518 @tab 65534
26519 @tab No set limit
26520 @sp 1
26521
26522 @item Maximum number of bits in any object
26523 @tab 2**31-1
26524 @tab 2**31-1
26525 @sp 1
26526
26527 @item Maximum size of the static portion of a stack frame (approximate)
26528 @tab 2**31-1
26529 @tab 2**31-1
26530 @end multitable
26531
26532 @node Tools and Utilities
26533 @section Tools and Utilities
26534
26535 @noindent
26536 The following table lists some of the OpenVMS development tools
26537 available for HP Ada, and the corresponding tools for
26538 use with @value{EDITION} on Alpha and I64 platforms.
26539 Aside from the debugger, all the OpenVMS tools identified are part
26540 of the DECset package.
26541
26542 @iftex
26543 @c Specify table in TeX since Texinfo does a poor job
26544 @tex
26545 \smallskip
26546 \smallskip
26547 \settabs\+Language-Sensitive Editor\quad
26548 &Product with HP Ada\quad
26549 &\cr
26550 \+\it Tool
26551 &\it Product with HP Ada
26552 & \it Product with GNAT Pro\cr
26553 \smallskip
26554 \+Code Management System
26555 &HP CMS
26556 & HP CMS\cr
26557 \smallskip
26558 \+Language-Sensitive Editor
26559 &HP LSE
26560 & emacs or HP LSE (Alpha)\cr
26561 \+
26562 &
26563 & HP LSE (I64)\cr
26564 \smallskip
26565 \+Debugger
26566 &OpenVMS Debug
26567 & gdb (Alpha),\cr
26568 \+
26569 &
26570 & OpenVMS Debug (I64)\cr
26571 \smallskip
26572 \+Source Code Analyzer /
26573 &HP SCA
26574 & GNAT XREF\cr
26575 \+Cross Referencer
26576 &
26577 &\cr
26578 \smallskip
26579 \+Test Manager
26580 &HP Digital Test
26581 & HP DTM\cr
26582 \+
26583 &Manager (DTM)
26584 &\cr
26585 \smallskip
26586 \+Performance and
26587 & HP PCA
26588 & HP PCA\cr
26589 \+Coverage Analyzer
26590 &
26591 &\cr
26592 \smallskip
26593 \+Module Management
26594 & HP MMS
26595 & Not applicable\cr
26596 \+ System
26597 &
26598 &\cr
26599 \smallskip
26600 \smallskip
26601 @end tex
26602 @end iftex
26603
26604 @ifnottex
26605 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
26606 @c the TeX version above for the printed version
26607 @flushleft
26608 @c @multitable @columnfractions .3 .4 .4
26609 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26610 @item @i{Tool}
26611 @tab @i{Tool with HP Ada}
26612 @tab @i{Tool with @value{EDITION}}
26613 @item Code Management@*System
26614 @tab HP CMS
26615 @tab HP CMS
26616 @item Language-Sensitive@*Editor
26617 @tab HP LSE
26618 @tab emacs or HP LSE (Alpha)
26619 @item
26620 @tab
26621 @tab HP LSE (I64)
26622 @item Debugger
26623 @tab OpenVMS Debug
26624 @tab gdb (Alpha),
26625 @item
26626 @tab
26627 @tab OpenVMS Debug (I64)
26628 @item Source Code Analyzer /@*Cross Referencer
26629 @tab HP SCA
26630 @tab GNAT XREF
26631 @item Test Manager
26632 @tab HP Digital Test@*Manager (DTM)
26633 @tab HP DTM
26634 @item Performance and@*Coverage Analyzer
26635 @tab HP PCA
26636 @tab HP PCA
26637 @item Module Management@*System
26638 @tab HP MMS
26639 @tab Not applicable
26640 @end multitable
26641 @end flushleft
26642 @end ifnottex
26643
26644 @end ifset
26645
26646 @c **************************************
26647 @node Platform-Specific Information for the Run-Time Libraries
26648 @appendix Platform-Specific Information for the Run-Time Libraries
26649 @cindex Tasking and threads libraries
26650 @cindex Threads libraries and tasking
26651 @cindex Run-time libraries (platform-specific information)
26652
26653 @noindent
26654 The GNAT run-time implementation may vary with respect to both the
26655 underlying threads library and the exception handling scheme.
26656 For threads support, one or more of the following are supplied:
26657 @itemize @bullet
26658 @item @b{native threads library}, a binding to the thread package from
26659 the underlying operating system
26660
26661 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26662 POSIX thread package
26663 @end itemize
26664
26665 @noindent
26666 For exception handling, either or both of two models are supplied:
26667 @itemize @bullet
26668 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26669 Most programs should experience a substantial speed improvement by
26670 being compiled with a ZCX run-time.
26671 This is especially true for
26672 tasking applications or applications with many exception handlers.}
26673 @cindex Zero-Cost Exceptions
26674 @cindex ZCX (Zero-Cost Exceptions)
26675 which uses binder-generated tables that
26676 are interrogated at run time to locate a handler
26677
26678 @item @b{setjmp / longjmp} (``SJLJ''),
26679 @cindex setjmp/longjmp Exception Model
26680 @cindex SJLJ (setjmp/longjmp Exception Model)
26681 which uses dynamically-set data to establish
26682 the set of handlers
26683 @end itemize
26684
26685 @noindent
26686 This appendix summarizes which combinations of threads and exception support
26687 are supplied on various GNAT platforms.
26688 It then shows how to select a particular library either
26689 permanently or temporarily,
26690 explains the properties of (and tradeoffs among) the various threads
26691 libraries, and provides some additional
26692 information about several specific platforms.
26693
26694 @menu
26695 * Summary of Run-Time Configurations::
26696 * Specifying a Run-Time Library::
26697 * Choosing the Scheduling Policy::
26698 * Solaris-Specific Considerations::
26699 * Linux-Specific Considerations::
26700 * AIX-Specific Considerations::
26701 * Irix-Specific Considerations::
26702 * RTX-Specific Considerations::
26703 @end menu
26704
26705 @node Summary of Run-Time Configurations
26706 @section Summary of Run-Time Configurations
26707
26708 @multitable @columnfractions .30 .70
26709 @item @b{alpha-openvms}
26710 @item @code{@ @ }@i{rts-native (default)}
26711 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26712 @item @code{@ @ @ @ }Exceptions @tab ZCX
26713 @*
26714 @item @b{alpha-tru64}
26715 @item @code{@ @ }@i{rts-native (default)}
26716 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26717 @item @code{@ @ @ @ }Exceptions @tab ZCX
26718 @*
26719 @item @code{@ @ }@i{rts-sjlj}
26720 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26721 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26722 @*
26723 @item @b{ia64-hp_linux}
26724 @item @code{@ @ }@i{rts-native (default)}
26725 @item @code{@ @ @ @ }Tasking @tab pthread library
26726 @item @code{@ @ @ @ }Exceptions @tab ZCX
26727 @*
26728 @item @b{ia64-hpux}
26729 @item @code{@ @ }@i{rts-native (default)}
26730 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26731 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26732 @*
26733 @item @b{ia64-openvms}
26734 @item @code{@ @ }@i{rts-native (default)}
26735 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26736 @item @code{@ @ @ @ }Exceptions @tab ZCX
26737 @*
26738 @item @b{ia64-sgi_linux}
26739 @item @code{@ @ }@i{rts-native (default)}
26740 @item @code{@ @ @ @ }Tasking @tab pthread library
26741 @item @code{@ @ @ @ }Exceptions @tab ZCX
26742 @*
26743 @item @b{mips-irix}
26744 @item @code{@ @ }@i{rts-native (default)}
26745 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
26746 @item @code{@ @ @ @ }Exceptions @tab ZCX
26747 @*
26748 @item @b{pa-hpux}
26749 @item @code{@ @ }@i{rts-native (default)}
26750 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26751 @item @code{@ @ @ @ }Exceptions @tab ZCX
26752 @*
26753 @item @code{@ @ }@i{rts-sjlj}
26754 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26755 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26756 @*
26757 @item @b{ppc-aix}
26758 @item @code{@ @ }@i{rts-native (default)}
26759 @item @code{@ @ @ @ }Tasking @tab native AIX threads
26760 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26761 @*
26762 @item @b{ppc-darwin}
26763 @item @code{@ @ }@i{rts-native (default)}
26764 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
26765 @item @code{@ @ @ @ }Exceptions @tab ZCX
26766 @*
26767 @item @b{sparc-solaris} @tab
26768 @item @code{@ @ }@i{rts-native (default)}
26769 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26770 @item @code{@ @ @ @ }Exceptions @tab ZCX
26771 @*
26772 @item @code{@ @ }@i{rts-pthread}
26773 @item @code{@ @ @ @ }Tasking @tab pthread library
26774 @item @code{@ @ @ @ }Exceptions @tab ZCX
26775 @*
26776 @item @code{@ @ }@i{rts-sjlj}
26777 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26778 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26779 @*
26780 @item @b{sparc64-solaris} @tab
26781 @item @code{@ @ }@i{rts-native (default)}
26782 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26783 @item @code{@ @ @ @ }Exceptions @tab ZCX
26784 @*
26785 @item @b{x86-linux}
26786 @item @code{@ @ }@i{rts-native (default)}
26787 @item @code{@ @ @ @ }Tasking @tab pthread library
26788 @item @code{@ @ @ @ }Exceptions @tab ZCX
26789 @*
26790 @item @code{@ @ }@i{rts-sjlj}
26791 @item @code{@ @ @ @ }Tasking @tab pthread library
26792 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26793 @*
26794 @item @b{x86-lynx}
26795 @item @code{@ @ }@i{rts-native (default)}
26796 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
26797 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26798 @*
26799 @item @b{x86-solaris}
26800 @item @code{@ @ }@i{rts-native (default)}
26801 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
26802 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26803 @*
26804 @item @b{x86-windows}
26805 @item @code{@ @ }@i{rts-native (default)}
26806 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26807 @item @code{@ @ @ @ }Exceptions @tab ZCX
26808 @*
26809 @item @code{@ @ }@i{rts-sjlj (default)}
26810 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26811 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26812 @*
26813 @item @b{x86-windows-rtx}
26814 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26815 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
26816 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26817 @*
26818 @item @code{@ @ }@i{rts-rtx-w32}
26819 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
26820 @item @code{@ @ @ @ }Exceptions @tab ZCX
26821 @*
26822 @item @b{x86_64-linux}
26823 @item @code{@ @ }@i{rts-native (default)}
26824 @item @code{@ @ @ @ }Tasking @tab pthread library
26825 @item @code{@ @ @ @ }Exceptions @tab ZCX
26826 @*
26827 @item @code{@ @ }@i{rts-sjlj}
26828 @item @code{@ @ @ @ }Tasking @tab pthread library
26829 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26830 @*
26831 @end multitable
26832
26833 @node Specifying a Run-Time Library
26834 @section Specifying a Run-Time Library
26835
26836 @noindent
26837 The @file{adainclude} subdirectory containing the sources of the GNAT
26838 run-time library, and the @file{adalib} subdirectory containing the
26839 @file{ALI} files and the static and/or shared GNAT library, are located
26840 in the gcc target-dependent area:
26841
26842 @smallexample
26843 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26844 @end smallexample
26845
26846 @noindent
26847 As indicated above, on some platforms several run-time libraries are supplied.
26848 These libraries are installed in the target dependent area and
26849 contain a complete source and binary subdirectory. The detailed description
26850 below explains the differences between the different libraries in terms of
26851 their thread support.
26852
26853 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26854 This default run time is selected by the means of soft links.
26855 For example on x86-linux:
26856
26857 @smallexample
26858 @group
26859 $(target-dir)
26860 |
26861 +--- adainclude----------+
26862 | |
26863 +--- adalib-----------+ |
26864 | | |
26865 +--- rts-native | |
26866 | | | |
26867 | +--- adainclude <---+
26868 | | |
26869 | +--- adalib <----+
26870 |
26871 +--- rts-sjlj
26872 |
26873 +--- adainclude
26874 |
26875 +--- adalib
26876 @end group
26877 @end smallexample
26878
26879 @noindent
26880 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26881 these soft links can be modified with the following commands:
26882
26883 @smallexample
26884 $ cd $target
26885 $ rm -f adainclude adalib
26886 $ ln -s rts-sjlj/adainclude adainclude
26887 $ ln -s rts-sjlj/adalib adalib
26888 @end smallexample
26889
26890 @noindent
26891 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26892 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26893 @file{$target/ada_object_path}.
26894
26895 Selecting another run-time library temporarily can be
26896 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26897 @cindex @option{--RTS} option
26898
26899 @node Choosing the Scheduling Policy
26900 @section Choosing the Scheduling Policy
26901
26902 @noindent
26903 When using a POSIX threads implementation, you have a choice of several
26904 scheduling policies: @code{SCHED_FIFO},
26905 @cindex @code{SCHED_FIFO} scheduling policy
26906 @code{SCHED_RR}
26907 @cindex @code{SCHED_RR} scheduling policy
26908 and @code{SCHED_OTHER}.
26909 @cindex @code{SCHED_OTHER} scheduling policy
26910 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26911 or @code{SCHED_RR} requires special (e.g., root) privileges.
26912
26913 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26914 @code{SCHED_FIFO},
26915 @cindex @code{SCHED_FIFO} scheduling policy
26916 you can use one of the following:
26917
26918 @itemize @bullet
26919 @item
26920 @code{pragma Time_Slice (0.0)}
26921 @cindex pragma Time_Slice
26922 @item
26923 the corresponding binder option @option{-T0}
26924 @cindex @option{-T0} option
26925 @item
26926 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26927 @cindex pragma Task_Dispatching_Policy
26928 @end itemize
26929
26930 @noindent
26931 To specify @code{SCHED_RR},
26932 @cindex @code{SCHED_RR} scheduling policy
26933 you should use @code{pragma Time_Slice} with a
26934 value greater than @code{0.0}, or else use the corresponding @option{-T}
26935 binder option.
26936
26937 @node Solaris-Specific Considerations
26938 @section Solaris-Specific Considerations
26939 @cindex Solaris Sparc threads libraries
26940
26941 @noindent
26942 This section addresses some topics related to the various threads libraries
26943 on Sparc Solaris.
26944
26945 @menu
26946 * Solaris Threads Issues::
26947 @end menu
26948
26949 @node Solaris Threads Issues
26950 @subsection Solaris Threads Issues
26951
26952 @noindent
26953 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26954 library based on POSIX threads --- @emph{rts-pthread}.
26955 @cindex rts-pthread threads library
26956 This run-time library has the advantage of being mostly shared across all
26957 POSIX-compliant thread implementations, and it also provides under
26958 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26959 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26960 and @code{PTHREAD_PRIO_PROTECT}
26961 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26962 semantics that can be selected using the predefined pragma
26963 @code{Locking_Policy}
26964 @cindex pragma Locking_Policy (under rts-pthread)
26965 with respectively
26966 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26967 @cindex @code{Inheritance_Locking} (under rts-pthread)
26968 @cindex @code{Ceiling_Locking} (under rts-pthread)
26969
26970 As explained above, the native run-time library is based on the Solaris thread
26971 library (@code{libthread}) and is the default library.
26972
26973 When the Solaris threads library is used (this is the default), programs
26974 compiled with GNAT can automatically take advantage of
26975 and can thus execute on multiple processors.
26976 The user can alternatively specify a processor on which the program should run
26977 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26978 is made by
26979 setting the environment variable @env{GNAT_PROCESSOR}
26980 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26981 to one of the following:
26982
26983 @table @code
26984 @item -2
26985 Use the default configuration (run the program on all
26986 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26987 unset
26988
26989 @item -1
26990 Let the run-time implementation choose one processor and run the program on
26991 that processor
26992
26993 @item 0 .. Last_Proc
26994 Run the program on the specified processor.
26995 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26996 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26997 @end table
26998
26999 @node Linux-Specific Considerations
27000 @section Linux-Specific Considerations
27001 @cindex Linux threads libraries
27002
27003 @noindent
27004 On GNU/Linux without NPTL support (usually system with GNU C Library
27005 older than 2.3), the signal model is not POSIX compliant, which means
27006 that to send a signal to the process, you need to send the signal to all
27007 threads, e.g.@: by using @code{killpg()}.
27008
27009 @node AIX-Specific Considerations
27010 @section AIX-Specific Considerations
27011 @cindex AIX resolver library
27012
27013 @noindent
27014 On AIX, the resolver library initializes some internal structure on
27015 the first call to @code{get*by*} functions, which are used to implement
27016 @code{GNAT.Sockets.Get_Host_By_Name} and
27017 @code{GNAT.Sockets.Get_Host_By_Address}.
27018 If such initialization occurs within an Ada task, and the stack size for
27019 the task is the default size, a stack overflow may occur.
27020
27021 To avoid this overflow, the user should either ensure that the first call
27022 to @code{GNAT.Sockets.Get_Host_By_Name} or
27023 @code{GNAT.Sockets.Get_Host_By_Addrss}
27024 occurs in the environment task, or use @code{pragma Storage_Size} to
27025 specify a sufficiently large size for the stack of the task that contains
27026 this call.
27027
27028 @node Irix-Specific Considerations
27029 @section Irix-Specific Considerations
27030 @cindex Irix libraries
27031
27032 @noindent
27033 The GCC support libraries coming with the Irix compiler have moved to
27034 their canonical place with respect to the general Irix ABI related
27035 conventions. Running applications built with the default shared GNAT
27036 run-time now requires the LD_LIBRARY_PATH environment variable to
27037 include this location. A possible way to achieve this is to issue the
27038 following command line on a bash prompt:
27039
27040 @smallexample
27041 @group
27042 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27043 @end group
27044 @end smallexample
27045
27046 @node RTX-Specific Considerations
27047 @section RTX-Specific Considerations
27048 @cindex RTX libraries
27049
27050 @noindent
27051 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27052 API. Applications can be built to work in two different modes:
27053
27054 @itemize @bullet
27055 @item
27056 Windows executables that run in Ring 3 to utilize memory protection
27057 (@emph{rts-rtx-w32}).
27058
27059 @item
27060 Real-time subsystem (RTSS) executables that run in Ring 0, where
27061 performance can be optimized with RTSS applications taking precedent
27062 over all Windows applications (@emph{rts-rtx-rtss}).
27063
27064 @end itemize
27065
27066 @c *******************************
27067 @node Example of Binder Output File
27068 @appendix Example of Binder Output File
27069
27070 @noindent
27071 This Appendix displays the source code for @command{gnatbind}'s output
27072 file generated for a simple ``Hello World'' program.
27073 Comments have been added for clarification purposes.
27074
27075 @smallexample @c adanocomment
27076 @iftex
27077 @leftskip=0cm
27078 @end iftex
27079 -- The package is called Ada_Main unless this name is actually used
27080 -- as a unit name in the partition, in which case some other unique
27081 -- name is used.
27082
27083 with System;
27084 package ada_main is
27085
27086 Elab_Final_Code : Integer;
27087 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27088
27089 -- The main program saves the parameters (argument count,
27090 -- argument values, environment pointer) in global variables
27091 -- for later access by other units including
27092 -- Ada.Command_Line.
27093
27094 gnat_argc : Integer;
27095 gnat_argv : System.Address;
27096 gnat_envp : System.Address;
27097
27098 -- The actual variables are stored in a library routine. This
27099 -- is useful for some shared library situations, where there
27100 -- are problems if variables are not in the library.
27101
27102 pragma Import (C, gnat_argc);
27103 pragma Import (C, gnat_argv);
27104 pragma Import (C, gnat_envp);
27105
27106 -- The exit status is similarly an external location
27107
27108 gnat_exit_status : Integer;
27109 pragma Import (C, gnat_exit_status);
27110
27111 GNAT_Version : constant String :=
27112 "GNAT Version: 6.0.0w (20061115)";
27113 pragma Export (C, GNAT_Version, "__gnat_version");
27114
27115 -- This is the generated adafinal routine that performs
27116 -- finalization at the end of execution. In the case where
27117 -- Ada is the main program, this main program makes a call
27118 -- to adafinal at program termination.
27119
27120 procedure adafinal;
27121 pragma Export (C, adafinal, "adafinal");
27122
27123 -- This is the generated adainit routine that performs
27124 -- initialization at the start of execution. In the case
27125 -- where Ada is the main program, this main program makes
27126 -- a call to adainit at program startup.
27127
27128 procedure adainit;
27129 pragma Export (C, adainit, "adainit");
27130
27131 -- This routine is called at the start of execution. It is
27132 -- a dummy routine that is used by the debugger to breakpoint
27133 -- at the start of execution.
27134
27135 procedure Break_Start;
27136 pragma Import (C, Break_Start, "__gnat_break_start");
27137
27138 -- This is the actual generated main program (it would be
27139 -- suppressed if the no main program switch were used). As
27140 -- required by standard system conventions, this program has
27141 -- the external name main.
27142
27143 function main
27144 (argc : Integer;
27145 argv : System.Address;
27146 envp : System.Address)
27147 return Integer;
27148 pragma Export (C, main, "main");
27149
27150 -- The following set of constants give the version
27151 -- identification values for every unit in the bound
27152 -- partition. This identification is computed from all
27153 -- dependent semantic units, and corresponds to the
27154 -- string that would be returned by use of the
27155 -- Body_Version or Version attributes.
27156
27157 type Version_32 is mod 2 ** 32;
27158 u00001 : constant Version_32 := 16#7880BEB3#;
27159 u00002 : constant Version_32 := 16#0D24CBD0#;
27160 u00003 : constant Version_32 := 16#3283DBEB#;
27161 u00004 : constant Version_32 := 16#2359F9ED#;
27162 u00005 : constant Version_32 := 16#664FB847#;
27163 u00006 : constant Version_32 := 16#68E803DF#;
27164 u00007 : constant Version_32 := 16#5572E604#;
27165 u00008 : constant Version_32 := 16#46B173D8#;
27166 u00009 : constant Version_32 := 16#156A40CF#;
27167 u00010 : constant Version_32 := 16#033DABE0#;
27168 u00011 : constant Version_32 := 16#6AB38FEA#;
27169 u00012 : constant Version_32 := 16#22B6217D#;
27170 u00013 : constant Version_32 := 16#68A22947#;
27171 u00014 : constant Version_32 := 16#18CC4A56#;
27172 u00015 : constant Version_32 := 16#08258E1B#;
27173 u00016 : constant Version_32 := 16#367D5222#;
27174 u00017 : constant Version_32 := 16#20C9ECA4#;
27175 u00018 : constant Version_32 := 16#50D32CB6#;
27176 u00019 : constant Version_32 := 16#39A8BB77#;
27177 u00020 : constant Version_32 := 16#5CF8FA2B#;
27178 u00021 : constant Version_32 := 16#2F1EB794#;
27179 u00022 : constant Version_32 := 16#31AB6444#;
27180 u00023 : constant Version_32 := 16#1574B6E9#;
27181 u00024 : constant Version_32 := 16#5109C189#;
27182 u00025 : constant Version_32 := 16#56D770CD#;
27183 u00026 : constant Version_32 := 16#02F9DE3D#;
27184 u00027 : constant Version_32 := 16#08AB6B2C#;
27185 u00028 : constant Version_32 := 16#3FA37670#;
27186 u00029 : constant Version_32 := 16#476457A0#;
27187 u00030 : constant Version_32 := 16#731E1B6E#;
27188 u00031 : constant Version_32 := 16#23C2E789#;
27189 u00032 : constant Version_32 := 16#0F1BD6A1#;
27190 u00033 : constant Version_32 := 16#7C25DE96#;
27191 u00034 : constant Version_32 := 16#39ADFFA2#;
27192 u00035 : constant Version_32 := 16#571DE3E7#;
27193 u00036 : constant Version_32 := 16#5EB646AB#;
27194 u00037 : constant Version_32 := 16#4249379B#;
27195 u00038 : constant Version_32 := 16#0357E00A#;
27196 u00039 : constant Version_32 := 16#3784FB72#;
27197 u00040 : constant Version_32 := 16#2E723019#;
27198 u00041 : constant Version_32 := 16#623358EA#;
27199 u00042 : constant Version_32 := 16#107F9465#;
27200 u00043 : constant Version_32 := 16#6843F68A#;
27201 u00044 : constant Version_32 := 16#63305874#;
27202 u00045 : constant Version_32 := 16#31E56CE1#;
27203 u00046 : constant Version_32 := 16#02917970#;
27204 u00047 : constant Version_32 := 16#6CCBA70E#;
27205 u00048 : constant Version_32 := 16#41CD4204#;
27206 u00049 : constant Version_32 := 16#572E3F58#;
27207 u00050 : constant Version_32 := 16#20729FF5#;
27208 u00051 : constant Version_32 := 16#1D4F93E8#;
27209 u00052 : constant Version_32 := 16#30B2EC3D#;
27210 u00053 : constant Version_32 := 16#34054F96#;
27211 u00054 : constant Version_32 := 16#5A199860#;
27212 u00055 : constant Version_32 := 16#0E7F912B#;
27213 u00056 : constant Version_32 := 16#5760634A#;
27214 u00057 : constant Version_32 := 16#5D851835#;
27215
27216 -- The following Export pragmas export the version numbers
27217 -- with symbolic names ending in B (for body) or S
27218 -- (for spec) so that they can be located in a link. The
27219 -- information provided here is sufficient to track down
27220 -- the exact versions of units used in a given build.
27221
27222 pragma Export (C, u00001, "helloB");
27223 pragma Export (C, u00002, "system__standard_libraryB");
27224 pragma Export (C, u00003, "system__standard_libraryS");
27225 pragma Export (C, u00004, "adaS");
27226 pragma Export (C, u00005, "ada__text_ioB");
27227 pragma Export (C, u00006, "ada__text_ioS");
27228 pragma Export (C, u00007, "ada__exceptionsB");
27229 pragma Export (C, u00008, "ada__exceptionsS");
27230 pragma Export (C, u00009, "gnatS");
27231 pragma Export (C, u00010, "gnat__heap_sort_aB");
27232 pragma Export (C, u00011, "gnat__heap_sort_aS");
27233 pragma Export (C, u00012, "systemS");
27234 pragma Export (C, u00013, "system__exception_tableB");
27235 pragma Export (C, u00014, "system__exception_tableS");
27236 pragma Export (C, u00015, "gnat__htableB");
27237 pragma Export (C, u00016, "gnat__htableS");
27238 pragma Export (C, u00017, "system__exceptionsS");
27239 pragma Export (C, u00018, "system__machine_state_operationsB");
27240 pragma Export (C, u00019, "system__machine_state_operationsS");
27241 pragma Export (C, u00020, "system__machine_codeS");
27242 pragma Export (C, u00021, "system__storage_elementsB");
27243 pragma Export (C, u00022, "system__storage_elementsS");
27244 pragma Export (C, u00023, "system__secondary_stackB");
27245 pragma Export (C, u00024, "system__secondary_stackS");
27246 pragma Export (C, u00025, "system__parametersB");
27247 pragma Export (C, u00026, "system__parametersS");
27248 pragma Export (C, u00027, "system__soft_linksB");
27249 pragma Export (C, u00028, "system__soft_linksS");
27250 pragma Export (C, u00029, "system__stack_checkingB");
27251 pragma Export (C, u00030, "system__stack_checkingS");
27252 pragma Export (C, u00031, "system__tracebackB");
27253 pragma Export (C, u00032, "system__tracebackS");
27254 pragma Export (C, u00033, "ada__streamsS");
27255 pragma Export (C, u00034, "ada__tagsB");
27256 pragma Export (C, u00035, "ada__tagsS");
27257 pragma Export (C, u00036, "system__string_opsB");
27258 pragma Export (C, u00037, "system__string_opsS");
27259 pragma Export (C, u00038, "interfacesS");
27260 pragma Export (C, u00039, "interfaces__c_streamsB");
27261 pragma Export (C, u00040, "interfaces__c_streamsS");
27262 pragma Export (C, u00041, "system__file_ioB");
27263 pragma Export (C, u00042, "system__file_ioS");
27264 pragma Export (C, u00043, "ada__finalizationB");
27265 pragma Export (C, u00044, "ada__finalizationS");
27266 pragma Export (C, u00045, "system__finalization_rootB");
27267 pragma Export (C, u00046, "system__finalization_rootS");
27268 pragma Export (C, u00047, "system__finalization_implementationB");
27269 pragma Export (C, u00048, "system__finalization_implementationS");
27270 pragma Export (C, u00049, "system__string_ops_concat_3B");
27271 pragma Export (C, u00050, "system__string_ops_concat_3S");
27272 pragma Export (C, u00051, "system__stream_attributesB");
27273 pragma Export (C, u00052, "system__stream_attributesS");
27274 pragma Export (C, u00053, "ada__io_exceptionsS");
27275 pragma Export (C, u00054, "system__unsigned_typesS");
27276 pragma Export (C, u00055, "system__file_control_blockS");
27277 pragma Export (C, u00056, "ada__finalization__list_controllerB");
27278 pragma Export (C, u00057, "ada__finalization__list_controllerS");
27279
27280 -- BEGIN ELABORATION ORDER
27281 -- ada (spec)
27282 -- gnat (spec)
27283 -- gnat.heap_sort_a (spec)
27284 -- gnat.heap_sort_a (body)
27285 -- gnat.htable (spec)
27286 -- gnat.htable (body)
27287 -- interfaces (spec)
27288 -- system (spec)
27289 -- system.machine_code (spec)
27290 -- system.parameters (spec)
27291 -- system.parameters (body)
27292 -- interfaces.c_streams (spec)
27293 -- interfaces.c_streams (body)
27294 -- system.standard_library (spec)
27295 -- ada.exceptions (spec)
27296 -- system.exception_table (spec)
27297 -- system.exception_table (body)
27298 -- ada.io_exceptions (spec)
27299 -- system.exceptions (spec)
27300 -- system.storage_elements (spec)
27301 -- system.storage_elements (body)
27302 -- system.machine_state_operations (spec)
27303 -- system.machine_state_operations (body)
27304 -- system.secondary_stack (spec)
27305 -- system.stack_checking (spec)
27306 -- system.soft_links (spec)
27307 -- system.soft_links (body)
27308 -- system.stack_checking (body)
27309 -- system.secondary_stack (body)
27310 -- system.standard_library (body)
27311 -- system.string_ops (spec)
27312 -- system.string_ops (body)
27313 -- ada.tags (spec)
27314 -- ada.tags (body)
27315 -- ada.streams (spec)
27316 -- system.finalization_root (spec)
27317 -- system.finalization_root (body)
27318 -- system.string_ops_concat_3 (spec)
27319 -- system.string_ops_concat_3 (body)
27320 -- system.traceback (spec)
27321 -- system.traceback (body)
27322 -- ada.exceptions (body)
27323 -- system.unsigned_types (spec)
27324 -- system.stream_attributes (spec)
27325 -- system.stream_attributes (body)
27326 -- system.finalization_implementation (spec)
27327 -- system.finalization_implementation (body)
27328 -- ada.finalization (spec)
27329 -- ada.finalization (body)
27330 -- ada.finalization.list_controller (spec)
27331 -- ada.finalization.list_controller (body)
27332 -- system.file_control_block (spec)
27333 -- system.file_io (spec)
27334 -- system.file_io (body)
27335 -- ada.text_io (spec)
27336 -- ada.text_io (body)
27337 -- hello (body)
27338 -- END ELABORATION ORDER
27339
27340 end ada_main;
27341
27342 -- The following source file name pragmas allow the generated file
27343 -- names to be unique for different main programs. They are needed
27344 -- since the package name will always be Ada_Main.
27345
27346 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27347 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27348
27349 -- Generated package body for Ada_Main starts here
27350
27351 package body ada_main is
27352
27353 -- The actual finalization is performed by calling the
27354 -- library routine in System.Standard_Library.Adafinal
27355
27356 procedure Do_Finalize;
27357 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27358
27359 -------------
27360 -- adainit --
27361 -------------
27362
27363 @findex adainit
27364 procedure adainit is
27365
27366 -- These booleans are set to True once the associated unit has
27367 -- been elaborated. It is also used to avoid elaborating the
27368 -- same unit twice.
27369
27370 E040 : Boolean;
27371 pragma Import (Ada, E040, "interfaces__c_streams_E");
27372
27373 E008 : Boolean;
27374 pragma Import (Ada, E008, "ada__exceptions_E");
27375
27376 E014 : Boolean;
27377 pragma Import (Ada, E014, "system__exception_table_E");
27378
27379 E053 : Boolean;
27380 pragma Import (Ada, E053, "ada__io_exceptions_E");
27381
27382 E017 : Boolean;
27383 pragma Import (Ada, E017, "system__exceptions_E");
27384
27385 E024 : Boolean;
27386 pragma Import (Ada, E024, "system__secondary_stack_E");
27387
27388 E030 : Boolean;
27389 pragma Import (Ada, E030, "system__stack_checking_E");
27390
27391 E028 : Boolean;
27392 pragma Import (Ada, E028, "system__soft_links_E");
27393
27394 E035 : Boolean;
27395 pragma Import (Ada, E035, "ada__tags_E");
27396
27397 E033 : Boolean;
27398 pragma Import (Ada, E033, "ada__streams_E");
27399
27400 E046 : Boolean;
27401 pragma Import (Ada, E046, "system__finalization_root_E");
27402
27403 E048 : Boolean;
27404 pragma Import (Ada, E048, "system__finalization_implementation_E");
27405
27406 E044 : Boolean;
27407 pragma Import (Ada, E044, "ada__finalization_E");
27408
27409 E057 : Boolean;
27410 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27411
27412 E055 : Boolean;
27413 pragma Import (Ada, E055, "system__file_control_block_E");
27414
27415 E042 : Boolean;
27416 pragma Import (Ada, E042, "system__file_io_E");
27417
27418 E006 : Boolean;
27419 pragma Import (Ada, E006, "ada__text_io_E");
27420
27421 -- Set_Globals is a library routine that stores away the
27422 -- value of the indicated set of global values in global
27423 -- variables within the library.
27424
27425 procedure Set_Globals
27426 (Main_Priority : Integer;
27427 Time_Slice_Value : Integer;
27428 WC_Encoding : Character;
27429 Locking_Policy : Character;
27430 Queuing_Policy : Character;
27431 Task_Dispatching_Policy : Character;
27432 Adafinal : System.Address;
27433 Unreserve_All_Interrupts : Integer;
27434 Exception_Tracebacks : Integer);
27435 @findex __gnat_set_globals
27436 pragma Import (C, Set_Globals, "__gnat_set_globals");
27437
27438 -- SDP_Table_Build is a library routine used to build the
27439 -- exception tables. See unit Ada.Exceptions in files
27440 -- a-except.ads/adb for full details of how zero cost
27441 -- exception handling works. This procedure, the call to
27442 -- it, and the two following tables are all omitted if the
27443 -- build is in longjmp/setjmp exception mode.
27444
27445 @findex SDP_Table_Build
27446 @findex Zero Cost Exceptions
27447 procedure SDP_Table_Build
27448 (SDP_Addresses : System.Address;
27449 SDP_Count : Natural;
27450 Elab_Addresses : System.Address;
27451 Elab_Addr_Count : Natural);
27452 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27453
27454 -- Table of Unit_Exception_Table addresses. Used for zero
27455 -- cost exception handling to build the top level table.
27456
27457 ST : aliased constant array (1 .. 23) of System.Address := (
27458 Hello'UET_Address,
27459 Ada.Text_Io'UET_Address,
27460 Ada.Exceptions'UET_Address,
27461 Gnat.Heap_Sort_A'UET_Address,
27462 System.Exception_Table'UET_Address,
27463 System.Machine_State_Operations'UET_Address,
27464 System.Secondary_Stack'UET_Address,
27465 System.Parameters'UET_Address,
27466 System.Soft_Links'UET_Address,
27467 System.Stack_Checking'UET_Address,
27468 System.Traceback'UET_Address,
27469 Ada.Streams'UET_Address,
27470 Ada.Tags'UET_Address,
27471 System.String_Ops'UET_Address,
27472 Interfaces.C_Streams'UET_Address,
27473 System.File_Io'UET_Address,
27474 Ada.Finalization'UET_Address,
27475 System.Finalization_Root'UET_Address,
27476 System.Finalization_Implementation'UET_Address,
27477 System.String_Ops_Concat_3'UET_Address,
27478 System.Stream_Attributes'UET_Address,
27479 System.File_Control_Block'UET_Address,
27480 Ada.Finalization.List_Controller'UET_Address);
27481
27482 -- Table of addresses of elaboration routines. Used for
27483 -- zero cost exception handling to make sure these
27484 -- addresses are included in the top level procedure
27485 -- address table.
27486
27487 EA : aliased constant array (1 .. 23) of System.Address := (
27488 adainit'Code_Address,
27489 Do_Finalize'Code_Address,
27490 Ada.Exceptions'Elab_Spec'Address,
27491 System.Exceptions'Elab_Spec'Address,
27492 Interfaces.C_Streams'Elab_Spec'Address,
27493 System.Exception_Table'Elab_Body'Address,
27494 Ada.Io_Exceptions'Elab_Spec'Address,
27495 System.Stack_Checking'Elab_Spec'Address,
27496 System.Soft_Links'Elab_Body'Address,
27497 System.Secondary_Stack'Elab_Body'Address,
27498 Ada.Tags'Elab_Spec'Address,
27499 Ada.Tags'Elab_Body'Address,
27500 Ada.Streams'Elab_Spec'Address,
27501 System.Finalization_Root'Elab_Spec'Address,
27502 Ada.Exceptions'Elab_Body'Address,
27503 System.Finalization_Implementation'Elab_Spec'Address,
27504 System.Finalization_Implementation'Elab_Body'Address,
27505 Ada.Finalization'Elab_Spec'Address,
27506 Ada.Finalization.List_Controller'Elab_Spec'Address,
27507 System.File_Control_Block'Elab_Spec'Address,
27508 System.File_Io'Elab_Body'Address,
27509 Ada.Text_Io'Elab_Spec'Address,
27510 Ada.Text_Io'Elab_Body'Address);
27511
27512 -- Start of processing for adainit
27513
27514 begin
27515
27516 -- Call SDP_Table_Build to build the top level procedure
27517 -- table for zero cost exception handling (omitted in
27518 -- longjmp/setjmp mode).
27519
27520 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27521
27522 -- Call Set_Globals to record various information for
27523 -- this partition. The values are derived by the binder
27524 -- from information stored in the ali files by the compiler.
27525
27526 @findex __gnat_set_globals
27527 Set_Globals
27528 (Main_Priority => -1,
27529 -- Priority of main program, -1 if no pragma Priority used
27530
27531 Time_Slice_Value => -1,
27532 -- Time slice from Time_Slice pragma, -1 if none used
27533
27534 WC_Encoding => 'b',
27535 -- Wide_Character encoding used, default is brackets
27536
27537 Locking_Policy => ' ',
27538 -- Locking_Policy used, default of space means not
27539 -- specified, otherwise it is the first character of
27540 -- the policy name.
27541
27542 Queuing_Policy => ' ',
27543 -- Queuing_Policy used, default of space means not
27544 -- specified, otherwise it is the first character of
27545 -- the policy name.
27546
27547 Task_Dispatching_Policy => ' ',
27548 -- Task_Dispatching_Policy used, default of space means
27549 -- not specified, otherwise first character of the
27550 -- policy name.
27551
27552 Adafinal => System.Null_Address,
27553 -- Address of Adafinal routine, not used anymore
27554
27555 Unreserve_All_Interrupts => 0,
27556 -- Set true if pragma Unreserve_All_Interrupts was used
27557
27558 Exception_Tracebacks => 0);
27559 -- Indicates if exception tracebacks are enabled
27560
27561 Elab_Final_Code := 1;
27562
27563 -- Now we have the elaboration calls for all units in the partition.
27564 -- The Elab_Spec and Elab_Body attributes generate references to the
27565 -- implicit elaboration procedures generated by the compiler for
27566 -- each unit that requires elaboration.
27567
27568 if not E040 then
27569 Interfaces.C_Streams'Elab_Spec;
27570 end if;
27571 E040 := True;
27572 if not E008 then
27573 Ada.Exceptions'Elab_Spec;
27574 end if;
27575 if not E014 then
27576 System.Exception_Table'Elab_Body;
27577 E014 := True;
27578 end if;
27579 if not E053 then
27580 Ada.Io_Exceptions'Elab_Spec;
27581 E053 := True;
27582 end if;
27583 if not E017 then
27584 System.Exceptions'Elab_Spec;
27585 E017 := True;
27586 end if;
27587 if not E030 then
27588 System.Stack_Checking'Elab_Spec;
27589 end if;
27590 if not E028 then
27591 System.Soft_Links'Elab_Body;
27592 E028 := True;
27593 end if;
27594 E030 := True;
27595 if not E024 then
27596 System.Secondary_Stack'Elab_Body;
27597 E024 := True;
27598 end if;
27599 if not E035 then
27600 Ada.Tags'Elab_Spec;
27601 end if;
27602 if not E035 then
27603 Ada.Tags'Elab_Body;
27604 E035 := True;
27605 end if;
27606 if not E033 then
27607 Ada.Streams'Elab_Spec;
27608 E033 := True;
27609 end if;
27610 if not E046 then
27611 System.Finalization_Root'Elab_Spec;
27612 end if;
27613 E046 := True;
27614 if not E008 then
27615 Ada.Exceptions'Elab_Body;
27616 E008 := True;
27617 end if;
27618 if not E048 then
27619 System.Finalization_Implementation'Elab_Spec;
27620 end if;
27621 if not E048 then
27622 System.Finalization_Implementation'Elab_Body;
27623 E048 := True;
27624 end if;
27625 if not E044 then
27626 Ada.Finalization'Elab_Spec;
27627 end if;
27628 E044 := True;
27629 if not E057 then
27630 Ada.Finalization.List_Controller'Elab_Spec;
27631 end if;
27632 E057 := True;
27633 if not E055 then
27634 System.File_Control_Block'Elab_Spec;
27635 E055 := True;
27636 end if;
27637 if not E042 then
27638 System.File_Io'Elab_Body;
27639 E042 := True;
27640 end if;
27641 if not E006 then
27642 Ada.Text_Io'Elab_Spec;
27643 end if;
27644 if not E006 then
27645 Ada.Text_Io'Elab_Body;
27646 E006 := True;
27647 end if;
27648
27649 Elab_Final_Code := 0;
27650 end adainit;
27651
27652 --------------
27653 -- adafinal --
27654 --------------
27655
27656 @findex adafinal
27657 procedure adafinal is
27658 begin
27659 Do_Finalize;
27660 end adafinal;
27661
27662 ----------
27663 -- main --
27664 ----------
27665
27666 -- main is actually a function, as in the ANSI C standard,
27667 -- defined to return the exit status. The three parameters
27668 -- are the argument count, argument values and environment
27669 -- pointer.
27670
27671 @findex Main Program
27672 function main
27673 (argc : Integer;
27674 argv : System.Address;
27675 envp : System.Address)
27676 return Integer
27677 is
27678 -- The initialize routine performs low level system
27679 -- initialization using a standard library routine which
27680 -- sets up signal handling and performs any other
27681 -- required setup. The routine can be found in file
27682 -- a-init.c.
27683
27684 @findex __gnat_initialize
27685 procedure initialize;
27686 pragma Import (C, initialize, "__gnat_initialize");
27687
27688 -- The finalize routine performs low level system
27689 -- finalization using a standard library routine. The
27690 -- routine is found in file a-final.c and in the standard
27691 -- distribution is a dummy routine that does nothing, so
27692 -- really this is a hook for special user finalization.
27693
27694 @findex __gnat_finalize
27695 procedure finalize;
27696 pragma Import (C, finalize, "__gnat_finalize");
27697
27698 -- We get to the main program of the partition by using
27699 -- pragma Import because if we try to with the unit and
27700 -- call it Ada style, then not only do we waste time
27701 -- recompiling it, but also, we don't really know the right
27702 -- switches (e.g.@: identifier character set) to be used
27703 -- to compile it.
27704
27705 procedure Ada_Main_Program;
27706 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27707
27708 -- Start of processing for main
27709
27710 begin
27711 -- Save global variables
27712
27713 gnat_argc := argc;
27714 gnat_argv := argv;
27715 gnat_envp := envp;
27716
27717 -- Call low level system initialization
27718
27719 Initialize;
27720
27721 -- Call our generated Ada initialization routine
27722
27723 adainit;
27724
27725 -- This is the point at which we want the debugger to get
27726 -- control
27727
27728 Break_Start;
27729
27730 -- Now we call the main program of the partition
27731
27732 Ada_Main_Program;
27733
27734 -- Perform Ada finalization
27735
27736 adafinal;
27737
27738 -- Perform low level system finalization
27739
27740 Finalize;
27741
27742 -- Return the proper exit status
27743 return (gnat_exit_status);
27744 end;
27745
27746 -- This section is entirely comments, so it has no effect on the
27747 -- compilation of the Ada_Main package. It provides the list of
27748 -- object files and linker options, as well as some standard
27749 -- libraries needed for the link. The gnatlink utility parses
27750 -- this b~hello.adb file to read these comment lines to generate
27751 -- the appropriate command line arguments for the call to the
27752 -- system linker. The BEGIN/END lines are used for sentinels for
27753 -- this parsing operation.
27754
27755 -- The exact file names will of course depend on the environment,
27756 -- host/target and location of files on the host system.
27757
27758 @findex Object file list
27759 -- BEGIN Object file/option list
27760 -- ./hello.o
27761 -- -L./
27762 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27763 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27764 -- END Object file/option list
27765
27766 end ada_main;
27767 @end smallexample
27768
27769 @noindent
27770 The Ada code in the above example is exactly what is generated by the
27771 binder. We have added comments to more clearly indicate the function
27772 of each part of the generated @code{Ada_Main} package.
27773
27774 The code is standard Ada in all respects, and can be processed by any
27775 tools that handle Ada. In particular, it is possible to use the debugger
27776 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27777 suppose that for reasons that you do not understand, your program is crashing
27778 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27779 you can place a breakpoint on the call:
27780
27781 @smallexample @c ada
27782 Ada.Text_Io'Elab_Body;
27783 @end smallexample
27784
27785 @noindent
27786 and trace the elaboration routine for this package to find out where
27787 the problem might be (more usually of course you would be debugging
27788 elaboration code in your own application).
27789
27790 @node Elaboration Order Handling in GNAT
27791 @appendix Elaboration Order Handling in GNAT
27792 @cindex Order of elaboration
27793 @cindex Elaboration control
27794
27795 @menu
27796 * Elaboration Code::
27797 * Checking the Elaboration Order::
27798 * Controlling the Elaboration Order::
27799 * Controlling Elaboration in GNAT - Internal Calls::
27800 * Controlling Elaboration in GNAT - External Calls::
27801 * Default Behavior in GNAT - Ensuring Safety::
27802 * Treatment of Pragma Elaborate::
27803 * Elaboration Issues for Library Tasks::
27804 * Mixing Elaboration Models::
27805 * What to Do If the Default Elaboration Behavior Fails::
27806 * Elaboration for Access-to-Subprogram Values::
27807 * Summary of Procedures for Elaboration Control::
27808 * Other Elaboration Order Considerations::
27809 @end menu
27810
27811 @noindent
27812 This chapter describes the handling of elaboration code in Ada and
27813 in GNAT, and discusses how the order of elaboration of program units can
27814 be controlled in GNAT, either automatically or with explicit programming
27815 features.
27816
27817 @node Elaboration Code
27818 @section Elaboration Code
27819
27820 @noindent
27821 Ada provides rather general mechanisms for executing code at elaboration
27822 time, that is to say before the main program starts executing. Such code arises
27823 in three contexts:
27824
27825 @table @asis
27826 @item Initializers for variables.
27827 Variables declared at the library level, in package specs or bodies, can
27828 require initialization that is performed at elaboration time, as in:
27829 @smallexample @c ada
27830 @cartouche
27831 Sqrt_Half : Float := Sqrt (0.5);
27832 @end cartouche
27833 @end smallexample
27834
27835 @item Package initialization code
27836 Code in a @code{BEGIN-END} section at the outer level of a package body is
27837 executed as part of the package body elaboration code.
27838
27839 @item Library level task allocators
27840 Tasks that are declared using task allocators at the library level
27841 start executing immediately and hence can execute at elaboration time.
27842 @end table
27843
27844 @noindent
27845 Subprogram calls are possible in any of these contexts, which means that
27846 any arbitrary part of the program may be executed as part of the elaboration
27847 code. It is even possible to write a program which does all its work at
27848 elaboration time, with a null main program, although stylistically this
27849 would usually be considered an inappropriate way to structure
27850 a program.
27851
27852 An important concern arises in the context of elaboration code:
27853 we have to be sure that it is executed in an appropriate order. What we
27854 have is a series of elaboration code sections, potentially one section
27855 for each unit in the program. It is important that these execute
27856 in the correct order. Correctness here means that, taking the above
27857 example of the declaration of @code{Sqrt_Half},
27858 if some other piece of
27859 elaboration code references @code{Sqrt_Half},
27860 then it must run after the
27861 section of elaboration code that contains the declaration of
27862 @code{Sqrt_Half}.
27863
27864 There would never be any order of elaboration problem if we made a rule
27865 that whenever you @code{with} a unit, you must elaborate both the spec and body
27866 of that unit before elaborating the unit doing the @code{with}'ing:
27867
27868 @smallexample @c ada
27869 @group
27870 @cartouche
27871 with Unit_1;
27872 package Unit_2 is @dots{}
27873 @end cartouche
27874 @end group
27875 @end smallexample
27876
27877 @noindent
27878 would require that both the body and spec of @code{Unit_1} be elaborated
27879 before the spec of @code{Unit_2}. However, a rule like that would be far too
27880 restrictive. In particular, it would make it impossible to have routines
27881 in separate packages that were mutually recursive.
27882
27883 You might think that a clever enough compiler could look at the actual
27884 elaboration code and determine an appropriate correct order of elaboration,
27885 but in the general case, this is not possible. Consider the following
27886 example.
27887
27888 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27889 that references
27890 the variable @code{Sqrt_1}, which is declared in the elaboration code
27891 of the body of @code{Unit_1}:
27892
27893 @smallexample @c ada
27894 @cartouche
27895 Sqrt_1 : Float := Sqrt (0.1);
27896 @end cartouche
27897 @end smallexample
27898
27899 @noindent
27900 The elaboration code of the body of @code{Unit_1} also contains:
27901
27902 @smallexample @c ada
27903 @group
27904 @cartouche
27905 if expression_1 = 1 then
27906 Q := Unit_2.Func_2;
27907 end if;
27908 @end cartouche
27909 @end group
27910 @end smallexample
27911
27912 @noindent
27913 @code{Unit_2} is exactly parallel,
27914 it has a procedure @code{Func_2} that references
27915 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27916 the body @code{Unit_2}:
27917
27918 @smallexample @c ada
27919 @cartouche
27920 Sqrt_2 : Float := Sqrt (0.1);
27921 @end cartouche
27922 @end smallexample
27923
27924 @noindent
27925 The elaboration code of the body of @code{Unit_2} also contains:
27926
27927 @smallexample @c ada
27928 @group
27929 @cartouche
27930 if expression_2 = 2 then
27931 Q := Unit_1.Func_1;
27932 end if;
27933 @end cartouche
27934 @end group
27935 @end smallexample
27936
27937 @noindent
27938 Now the question is, which of the following orders of elaboration is
27939 acceptable:
27940
27941 @smallexample
27942 @group
27943 Spec of Unit_1
27944 Spec of Unit_2
27945 Body of Unit_1
27946 Body of Unit_2
27947 @end group
27948 @end smallexample
27949
27950 @noindent
27951 or
27952
27953 @smallexample
27954 @group
27955 Spec of Unit_2
27956 Spec of Unit_1
27957 Body of Unit_2
27958 Body of Unit_1
27959 @end group
27960 @end smallexample
27961
27962 @noindent
27963 If you carefully analyze the flow here, you will see that you cannot tell
27964 at compile time the answer to this question.
27965 If @code{expression_1} is not equal to 1,
27966 and @code{expression_2} is not equal to 2,
27967 then either order is acceptable, because neither of the function calls is
27968 executed. If both tests evaluate to true, then neither order is acceptable
27969 and in fact there is no correct order.
27970
27971 If one of the two expressions is true, and the other is false, then one
27972 of the above orders is correct, and the other is incorrect. For example,
27973 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27974 then the call to @code{Func_1}
27975 will occur, but not the call to @code{Func_2.}
27976 This means that it is essential
27977 to elaborate the body of @code{Unit_1} before
27978 the body of @code{Unit_2}, so the first
27979 order of elaboration is correct and the second is wrong.
27980
27981 By making @code{expression_1} and @code{expression_2}
27982 depend on input data, or perhaps
27983 the time of day, we can make it impossible for the compiler or binder
27984 to figure out which of these expressions will be true, and hence it
27985 is impossible to guarantee a safe order of elaboration at run time.
27986
27987 @node Checking the Elaboration Order
27988 @section Checking the Elaboration Order
27989
27990 @noindent
27991 In some languages that involve the same kind of elaboration problems,
27992 e.g.@: Java and C++, the programmer is expected to worry about these
27993 ordering problems himself, and it is common to
27994 write a program in which an incorrect elaboration order gives
27995 surprising results, because it references variables before they
27996 are initialized.
27997 Ada is designed to be a safe language, and a programmer-beware approach is
27998 clearly not sufficient. Consequently, the language provides three lines
27999 of defense:
28000
28001 @table @asis
28002 @item Standard rules
28003 Some standard rules restrict the possible choice of elaboration
28004 order. In particular, if you @code{with} a unit, then its spec is always
28005 elaborated before the unit doing the @code{with}. Similarly, a parent
28006 spec is always elaborated before the child spec, and finally
28007 a spec is always elaborated before its corresponding body.
28008
28009 @item Dynamic elaboration checks
28010 @cindex Elaboration checks
28011 @cindex Checks, elaboration
28012 Dynamic checks are made at run time, so that if some entity is accessed
28013 before it is elaborated (typically by means of a subprogram call)
28014 then the exception (@code{Program_Error}) is raised.
28015
28016 @item Elaboration control
28017 Facilities are provided for the programmer to specify the desired order
28018 of elaboration.
28019 @end table
28020
28021 Let's look at these facilities in more detail. First, the rules for
28022 dynamic checking. One possible rule would be simply to say that the
28023 exception is raised if you access a variable which has not yet been
28024 elaborated. The trouble with this approach is that it could require
28025 expensive checks on every variable reference. Instead Ada has two
28026 rules which are a little more restrictive, but easier to check, and
28027 easier to state:
28028
28029 @table @asis
28030 @item Restrictions on calls
28031 A subprogram can only be called at elaboration time if its body
28032 has been elaborated. The rules for elaboration given above guarantee
28033 that the spec of the subprogram has been elaborated before the
28034 call, but not the body. If this rule is violated, then the
28035 exception @code{Program_Error} is raised.
28036
28037 @item Restrictions on instantiations
28038 A generic unit can only be instantiated if the body of the generic
28039 unit has been elaborated. Again, the rules for elaboration given above
28040 guarantee that the spec of the generic unit has been elaborated
28041 before the instantiation, but not the body. If this rule is
28042 violated, then the exception @code{Program_Error} is raised.
28043 @end table
28044
28045 @noindent
28046 The idea is that if the body has been elaborated, then any variables
28047 it references must have been elaborated; by checking for the body being
28048 elaborated we guarantee that none of its references causes any
28049 trouble. As we noted above, this is a little too restrictive, because a
28050 subprogram that has no non-local references in its body may in fact be safe
28051 to call. However, it really would be unsafe to rely on this, because
28052 it would mean that the caller was aware of details of the implementation
28053 in the body. This goes against the basic tenets of Ada.
28054
28055 A plausible implementation can be described as follows.
28056 A Boolean variable is associated with each subprogram
28057 and each generic unit. This variable is initialized to False, and is set to
28058 True at the point body is elaborated. Every call or instantiation checks the
28059 variable, and raises @code{Program_Error} if the variable is False.
28060
28061 Note that one might think that it would be good enough to have one Boolean
28062 variable for each package, but that would not deal with cases of trying
28063 to call a body in the same package as the call
28064 that has not been elaborated yet.
28065 Of course a compiler may be able to do enough analysis to optimize away
28066 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28067 does such optimizations, but still the easiest conceptual model is to
28068 think of there being one variable per subprogram.
28069
28070 @node Controlling the Elaboration Order
28071 @section Controlling the Elaboration Order
28072
28073 @noindent
28074 In the previous section we discussed the rules in Ada which ensure
28075 that @code{Program_Error} is raised if an incorrect elaboration order is
28076 chosen. This prevents erroneous executions, but we need mechanisms to
28077 specify a correct execution and avoid the exception altogether.
28078 To achieve this, Ada provides a number of features for controlling
28079 the order of elaboration. We discuss these features in this section.
28080
28081 First, there are several ways of indicating to the compiler that a given
28082 unit has no elaboration problems:
28083
28084 @table @asis
28085 @item packages that do not require a body
28086 A library package that does not require a body does not permit
28087 a body (this rule was introduced in Ada 95).
28088 Thus if we have a such a package, as in:
28089
28090 @smallexample @c ada
28091 @group
28092 @cartouche
28093 package Definitions is
28094 generic
28095 type m is new integer;
28096 package Subp is
28097 type a is array (1 .. 10) of m;
28098 type b is array (1 .. 20) of m;
28099 end Subp;
28100 end Definitions;
28101 @end cartouche
28102 @end group
28103 @end smallexample
28104
28105 @noindent
28106 A package that @code{with}'s @code{Definitions} may safely instantiate
28107 @code{Definitions.Subp} because the compiler can determine that there
28108 definitely is no package body to worry about in this case
28109
28110 @item pragma Pure
28111 @cindex pragma Pure
28112 @findex Pure
28113 Places sufficient restrictions on a unit to guarantee that
28114 no call to any subprogram in the unit can result in an
28115 elaboration problem. This means that the compiler does not need
28116 to worry about the point of elaboration of such units, and in
28117 particular, does not need to check any calls to any subprograms
28118 in this unit.
28119
28120 @item pragma Preelaborate
28121 @findex Preelaborate
28122 @cindex pragma Preelaborate
28123 This pragma places slightly less stringent restrictions on a unit than
28124 does pragma Pure,
28125 but these restrictions are still sufficient to ensure that there
28126 are no elaboration problems with any calls to the unit.
28127
28128 @item pragma Elaborate_Body
28129 @findex Elaborate_Body
28130 @cindex pragma Elaborate_Body
28131 This pragma requires that the body of a unit be elaborated immediately
28132 after its spec. Suppose a unit @code{A} has such a pragma,
28133 and unit @code{B} does
28134 a @code{with} of unit @code{A}. Recall that the standard rules require
28135 the spec of unit @code{A}
28136 to be elaborated before the @code{with}'ing unit; given the pragma in
28137 @code{A}, we also know that the body of @code{A}
28138 will be elaborated before @code{B}, so
28139 that calls to @code{A} are safe and do not need a check.
28140 @end table
28141
28142 @noindent
28143 Note that,
28144 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28145 the use of
28146 @code{Elaborate_Body} does not guarantee that the program is
28147 free of elaboration problems, because it may not be possible
28148 to satisfy the requested elaboration order.
28149 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28150 If a programmer
28151 marks @code{Unit_1} as @code{Elaborate_Body},
28152 and not @code{Unit_2,} then the order of
28153 elaboration will be:
28154
28155 @smallexample
28156 @group
28157 Spec of Unit_2
28158 Spec of Unit_1
28159 Body of Unit_1
28160 Body of Unit_2
28161 @end group
28162 @end smallexample
28163
28164 @noindent
28165 Now that means that the call to @code{Func_1} in @code{Unit_2}
28166 need not be checked,
28167 it must be safe. But the call to @code{Func_2} in
28168 @code{Unit_1} may still fail if
28169 @code{Expression_1} is equal to 1,
28170 and the programmer must still take
28171 responsibility for this not being the case.
28172
28173 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28174 eliminated, except for calls entirely within a body, which are
28175 in any case fully under programmer control. However, using the pragma
28176 everywhere is not always possible.
28177 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28178 we marked both of them as having pragma @code{Elaborate_Body}, then
28179 clearly there would be no possible elaboration order.
28180
28181 The above pragmas allow a server to guarantee safe use by clients, and
28182 clearly this is the preferable approach. Consequently a good rule
28183 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28184 and if this is not possible,
28185 mark them as @code{Elaborate_Body} if possible.
28186 As we have seen, there are situations where neither of these
28187 three pragmas can be used.
28188 So we also provide methods for clients to control the
28189 order of elaboration of the servers on which they depend:
28190
28191 @table @asis
28192 @item pragma Elaborate (unit)
28193 @findex Elaborate
28194 @cindex pragma Elaborate
28195 This pragma is placed in the context clause, after a @code{with} clause,
28196 and it requires that the body of the named unit be elaborated before
28197 the unit in which the pragma occurs. The idea is to use this pragma
28198 if the current unit calls at elaboration time, directly or indirectly,
28199 some subprogram in the named unit.
28200
28201 @item pragma Elaborate_All (unit)
28202 @findex Elaborate_All
28203 @cindex pragma Elaborate_All
28204 This is a stronger version of the Elaborate pragma. Consider the
28205 following example:
28206
28207 @smallexample
28208 Unit A @code{with}'s unit B and calls B.Func in elab code
28209 Unit B @code{with}'s unit C, and B.Func calls C.Func
28210 @end smallexample
28211
28212 @noindent
28213 Now if we put a pragma @code{Elaborate (B)}
28214 in unit @code{A}, this ensures that the
28215 body of @code{B} is elaborated before the call, but not the
28216 body of @code{C}, so
28217 the call to @code{C.Func} could still cause @code{Program_Error} to
28218 be raised.
28219
28220 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28221 not only that the body of the named unit be elaborated before the
28222 unit doing the @code{with}, but also the bodies of all units that the
28223 named unit uses, following @code{with} links transitively. For example,
28224 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28225 then it requires
28226 not only that the body of @code{B} be elaborated before @code{A},
28227 but also the
28228 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28229 @end table
28230
28231 @noindent
28232 We are now in a position to give a usage rule in Ada for avoiding
28233 elaboration problems, at least if dynamic dispatching and access to
28234 subprogram values are not used. We will handle these cases separately
28235 later.
28236
28237 The rule is simple. If a unit has elaboration code that can directly or
28238 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28239 a generic package in a @code{with}'ed unit,
28240 then if the @code{with}'ed unit does not have
28241 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28242 a pragma @code{Elaborate_All}
28243 for the @code{with}'ed unit. By following this rule a client is
28244 assured that calls can be made without risk of an exception.
28245
28246 For generic subprogram instantiations, the rule can be relaxed to
28247 require only a pragma @code{Elaborate} since elaborating the body
28248 of a subprogram cannot cause any transitive elaboration (we are
28249 not calling the subprogram in this case, just elaborating its
28250 declaration).
28251
28252 If this rule is not followed, then a program may be in one of four
28253 states:
28254
28255 @table @asis
28256 @item No order exists
28257 No order of elaboration exists which follows the rules, taking into
28258 account any @code{Elaborate}, @code{Elaborate_All},
28259 or @code{Elaborate_Body} pragmas. In
28260 this case, an Ada compiler must diagnose the situation at bind
28261 time, and refuse to build an executable program.
28262
28263 @item One or more orders exist, all incorrect
28264 One or more acceptable elaboration orders exist, and all of them
28265 generate an elaboration order problem. In this case, the binder
28266 can build an executable program, but @code{Program_Error} will be raised
28267 when the program is run.
28268
28269 @item Several orders exist, some right, some incorrect
28270 One or more acceptable elaboration orders exists, and some of them
28271 work, and some do not. The programmer has not controlled
28272 the order of elaboration, so the binder may or may not pick one of
28273 the correct orders, and the program may or may not raise an
28274 exception when it is run. This is the worst case, because it means
28275 that the program may fail when moved to another compiler, or even
28276 another version of the same compiler.
28277
28278 @item One or more orders exists, all correct
28279 One ore more acceptable elaboration orders exist, and all of them
28280 work. In this case the program runs successfully. This state of
28281 affairs can be guaranteed by following the rule we gave above, but
28282 may be true even if the rule is not followed.
28283 @end table
28284
28285 @noindent
28286 Note that one additional advantage of following our rules on the use
28287 of @code{Elaborate} and @code{Elaborate_All}
28288 is that the program continues to stay in the ideal (all orders OK) state
28289 even if maintenance
28290 changes some bodies of some units. Conversely, if a program that does
28291 not follow this rule happens to be safe at some point, this state of affairs
28292 may deteriorate silently as a result of maintenance changes.
28293
28294 You may have noticed that the above discussion did not mention
28295 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28296 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28297 code in the body makes calls to some other unit, so it is still necessary
28298 to use @code{Elaborate_All} on such units.
28299
28300 @node Controlling Elaboration in GNAT - Internal Calls
28301 @section Controlling Elaboration in GNAT - Internal Calls
28302
28303 @noindent
28304 In the case of internal calls, i.e., calls within a single package, the
28305 programmer has full control over the order of elaboration, and it is up
28306 to the programmer to elaborate declarations in an appropriate order. For
28307 example writing:
28308
28309 @smallexample @c ada
28310 @group
28311 @cartouche
28312 function One return Float;
28313
28314 Q : Float := One;
28315
28316 function One return Float is
28317 begin
28318 return 1.0;
28319 end One;
28320 @end cartouche
28321 @end group
28322 @end smallexample
28323
28324 @noindent
28325 will obviously raise @code{Program_Error} at run time, because function
28326 One will be called before its body is elaborated. In this case GNAT will
28327 generate a warning that the call will raise @code{Program_Error}:
28328
28329 @smallexample
28330 @group
28331 @cartouche
28332 1. procedure y is
28333 2. function One return Float;
28334 3.
28335 4. Q : Float := One;
28336 |
28337 >>> warning: cannot call "One" before body is elaborated
28338 >>> warning: Program_Error will be raised at run time
28339
28340 5.
28341 6. function One return Float is
28342 7. begin
28343 8. return 1.0;
28344 9. end One;
28345 10.
28346 11. begin
28347 12. null;
28348 13. end;
28349 @end cartouche
28350 @end group
28351 @end smallexample
28352
28353 @noindent
28354 Note that in this particular case, it is likely that the call is safe, because
28355 the function @code{One} does not access any global variables.
28356 Nevertheless in Ada, we do not want the validity of the check to depend on
28357 the contents of the body (think about the separate compilation case), so this
28358 is still wrong, as we discussed in the previous sections.
28359
28360 The error is easily corrected by rearranging the declarations so that the
28361 body of @code{One} appears before the declaration containing the call
28362 (note that in Ada 95 and Ada 2005,
28363 declarations can appear in any order, so there is no restriction that
28364 would prevent this reordering, and if we write:
28365
28366 @smallexample @c ada
28367 @group
28368 @cartouche
28369 function One return Float;
28370
28371 function One return Float is
28372 begin
28373 return 1.0;
28374 end One;
28375
28376 Q : Float := One;
28377 @end cartouche
28378 @end group
28379 @end smallexample
28380
28381 @noindent
28382 then all is well, no warning is generated, and no
28383 @code{Program_Error} exception
28384 will be raised.
28385 Things are more complicated when a chain of subprograms is executed:
28386
28387 @smallexample @c ada
28388 @group
28389 @cartouche
28390 function A return Integer;
28391 function B return Integer;
28392 function C return Integer;
28393
28394 function B return Integer is begin return A; end;
28395 function C return Integer is begin return B; end;
28396
28397 X : Integer := C;
28398
28399 function A return Integer is begin return 1; end;
28400 @end cartouche
28401 @end group
28402 @end smallexample
28403
28404 @noindent
28405 Now the call to @code{C}
28406 at elaboration time in the declaration of @code{X} is correct, because
28407 the body of @code{C} is already elaborated,
28408 and the call to @code{B} within the body of
28409 @code{C} is correct, but the call
28410 to @code{A} within the body of @code{B} is incorrect, because the body
28411 of @code{A} has not been elaborated, so @code{Program_Error}
28412 will be raised on the call to @code{A}.
28413 In this case GNAT will generate a
28414 warning that @code{Program_Error} may be
28415 raised at the point of the call. Let's look at the warning:
28416
28417 @smallexample
28418 @group
28419 @cartouche
28420 1. procedure x is
28421 2. function A return Integer;
28422 3. function B return Integer;
28423 4. function C return Integer;
28424 5.
28425 6. function B return Integer is begin return A; end;
28426 |
28427 >>> warning: call to "A" before body is elaborated may
28428 raise Program_Error
28429 >>> warning: "B" called at line 7
28430 >>> warning: "C" called at line 9
28431
28432 7. function C return Integer is begin return B; end;
28433 8.
28434 9. X : Integer := C;
28435 10.
28436 11. function A return Integer is begin return 1; end;
28437 12.
28438 13. begin
28439 14. null;
28440 15. end;
28441 @end cartouche
28442 @end group
28443 @end smallexample
28444
28445 @noindent
28446 Note that the message here says ``may raise'', instead of the direct case,
28447 where the message says ``will be raised''. That's because whether
28448 @code{A} is
28449 actually called depends in general on run-time flow of control.
28450 For example, if the body of @code{B} said
28451
28452 @smallexample @c ada
28453 @group
28454 @cartouche
28455 function B return Integer is
28456 begin
28457 if some-condition-depending-on-input-data then
28458 return A;
28459 else
28460 return 1;
28461 end if;
28462 end B;
28463 @end cartouche
28464 @end group
28465 @end smallexample
28466
28467 @noindent
28468 then we could not know until run time whether the incorrect call to A would
28469 actually occur, so @code{Program_Error} might
28470 or might not be raised. It is possible for a compiler to
28471 do a better job of analyzing bodies, to
28472 determine whether or not @code{Program_Error}
28473 might be raised, but it certainly
28474 couldn't do a perfect job (that would require solving the halting problem
28475 and is provably impossible), and because this is a warning anyway, it does
28476 not seem worth the effort to do the analysis. Cases in which it
28477 would be relevant are rare.
28478
28479 In practice, warnings of either of the forms given
28480 above will usually correspond to
28481 real errors, and should be examined carefully and eliminated.
28482 In the rare case where a warning is bogus, it can be suppressed by any of
28483 the following methods:
28484
28485 @itemize @bullet
28486 @item
28487 Compile with the @option{-gnatws} switch set
28488
28489 @item
28490 Suppress @code{Elaboration_Check} for the called subprogram
28491
28492 @item
28493 Use pragma @code{Warnings_Off} to turn warnings off for the call
28494 @end itemize
28495
28496 @noindent
28497 For the internal elaboration check case,
28498 GNAT by default generates the
28499 necessary run-time checks to ensure
28500 that @code{Program_Error} is raised if any
28501 call fails an elaboration check. Of course this can only happen if a
28502 warning has been issued as described above. The use of pragma
28503 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28504 some of these checks, meaning that it may be possible (but is not
28505 guaranteed) for a program to be able to call a subprogram whose body
28506 is not yet elaborated, without raising a @code{Program_Error} exception.
28507
28508 @node Controlling Elaboration in GNAT - External Calls
28509 @section Controlling Elaboration in GNAT - External Calls
28510
28511 @noindent
28512 The previous section discussed the case in which the execution of a
28513 particular thread of elaboration code occurred entirely within a
28514 single unit. This is the easy case to handle, because a programmer
28515 has direct and total control over the order of elaboration, and
28516 furthermore, checks need only be generated in cases which are rare
28517 and which the compiler can easily detect.
28518 The situation is more complex when separate compilation is taken into account.
28519 Consider the following:
28520
28521 @smallexample @c ada
28522 @cartouche
28523 @group
28524 package Math is
28525 function Sqrt (Arg : Float) return Float;
28526 end Math;
28527
28528 package body Math is
28529 function Sqrt (Arg : Float) return Float is
28530 begin
28531 @dots{}
28532 end Sqrt;
28533 end Math;
28534 @end group
28535 @group
28536 with Math;
28537 package Stuff is
28538 X : Float := Math.Sqrt (0.5);
28539 end Stuff;
28540
28541 with Stuff;
28542 procedure Main is
28543 begin
28544 @dots{}
28545 end Main;
28546 @end group
28547 @end cartouche
28548 @end smallexample
28549
28550 @noindent
28551 where @code{Main} is the main program. When this program is executed, the
28552 elaboration code must first be executed, and one of the jobs of the
28553 binder is to determine the order in which the units of a program are
28554 to be elaborated. In this case we have four units: the spec and body
28555 of @code{Math},
28556 the spec of @code{Stuff} and the body of @code{Main}).
28557 In what order should the four separate sections of elaboration code
28558 be executed?
28559
28560 There are some restrictions in the order of elaboration that the binder
28561 can choose. In particular, if unit U has a @code{with}
28562 for a package @code{X}, then you
28563 are assured that the spec of @code{X}
28564 is elaborated before U , but you are
28565 not assured that the body of @code{X}
28566 is elaborated before U.
28567 This means that in the above case, the binder is allowed to choose the
28568 order:
28569
28570 @smallexample
28571 spec of Math
28572 spec of Stuff
28573 body of Math
28574 body of Main
28575 @end smallexample
28576
28577 @noindent
28578 but that's not good, because now the call to @code{Math.Sqrt}
28579 that happens during
28580 the elaboration of the @code{Stuff}
28581 spec happens before the body of @code{Math.Sqrt} is
28582 elaborated, and hence causes @code{Program_Error} exception to be raised.
28583 At first glance, one might say that the binder is misbehaving, because
28584 obviously you want to elaborate the body of something you @code{with}
28585 first, but
28586 that is not a general rule that can be followed in all cases. Consider
28587
28588 @smallexample @c ada
28589 @group
28590 @cartouche
28591 package X is @dots{}
28592
28593 package Y is @dots{}
28594
28595 with X;
28596 package body Y is @dots{}
28597
28598 with Y;
28599 package body X is @dots{}
28600 @end cartouche
28601 @end group
28602 @end smallexample
28603
28604 @noindent
28605 This is a common arrangement, and, apart from the order of elaboration
28606 problems that might arise in connection with elaboration code, this works fine.
28607 A rule that says that you must first elaborate the body of anything you
28608 @code{with} cannot work in this case:
28609 the body of @code{X} @code{with}'s @code{Y},
28610 which means you would have to
28611 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28612 which means
28613 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28614 loop that cannot be broken.
28615
28616 It is true that the binder can in many cases guess an order of elaboration
28617 that is unlikely to cause a @code{Program_Error}
28618 exception to be raised, and it tries to do so (in the
28619 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28620 by default
28621 elaborate the body of @code{Math} right after its spec, so all will be well).
28622
28623 However, a program that blindly relies on the binder to be helpful can
28624 get into trouble, as we discussed in the previous sections, so
28625 GNAT
28626 provides a number of facilities for assisting the programmer in
28627 developing programs that are robust with respect to elaboration order.
28628
28629 @node Default Behavior in GNAT - Ensuring Safety
28630 @section Default Behavior in GNAT - Ensuring Safety
28631
28632 @noindent
28633 The default behavior in GNAT ensures elaboration safety. In its
28634 default mode GNAT implements the
28635 rule we previously described as the right approach. Let's restate it:
28636
28637 @itemize
28638 @item
28639 @emph{If a unit has elaboration code that can directly or indirectly make a
28640 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28641 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28642 does not have pragma @code{Pure} or
28643 @code{Preelaborate}, then the client should have an
28644 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28645
28646 @emph{In the case of instantiating a generic subprogram, it is always
28647 sufficient to have only an @code{Elaborate} pragma for the
28648 @code{with}'ed unit.}
28649 @end itemize
28650
28651 @noindent
28652 By following this rule a client is assured that calls and instantiations
28653 can be made without risk of an exception.
28654
28655 In this mode GNAT traces all calls that are potentially made from
28656 elaboration code, and puts in any missing implicit @code{Elaborate}
28657 and @code{Elaborate_All} pragmas.
28658 The advantage of this approach is that no elaboration problems
28659 are possible if the binder can find an elaboration order that is
28660 consistent with these implicit @code{Elaborate} and
28661 @code{Elaborate_All} pragmas. The
28662 disadvantage of this approach is that no such order may exist.
28663
28664 If the binder does not generate any diagnostics, then it means that it has
28665 found an elaboration order that is guaranteed to be safe. However, the binder
28666 may still be relying on implicitly generated @code{Elaborate} and
28667 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28668 guaranteed.
28669
28670 If it is important to guarantee portability, then the compilations should
28671 use the
28672 @option{-gnatwl}
28673 (warn on elaboration problems) switch. This will cause warning messages
28674 to be generated indicating the missing @code{Elaborate} and
28675 @code{Elaborate_All} pragmas.
28676 Consider the following source program:
28677
28678 @smallexample @c ada
28679 @group
28680 @cartouche
28681 with k;
28682 package j is
28683 m : integer := k.r;
28684 end;
28685 @end cartouche
28686 @end group
28687 @end smallexample
28688
28689 @noindent
28690 where it is clear that there
28691 should be a pragma @code{Elaborate_All}
28692 for unit @code{k}. An implicit pragma will be generated, and it is
28693 likely that the binder will be able to honor it. However, if you want
28694 to port this program to some other Ada compiler than GNAT.
28695 it is safer to include the pragma explicitly in the source. If this
28696 unit is compiled with the
28697 @option{-gnatwl}
28698 switch, then the compiler outputs a warning:
28699
28700 @smallexample
28701 @group
28702 @cartouche
28703 1. with k;
28704 2. package j is
28705 3. m : integer := k.r;
28706 |
28707 >>> warning: call to "r" may raise Program_Error
28708 >>> warning: missing pragma Elaborate_All for "k"
28709
28710 4. end;
28711 @end cartouche
28712 @end group
28713 @end smallexample
28714
28715 @noindent
28716 and these warnings can be used as a guide for supplying manually
28717 the missing pragmas. It is usually a bad idea to use this warning
28718 option during development. That's because it will warn you when
28719 you need to put in a pragma, but cannot warn you when it is time
28720 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28721 unnecessary dependencies and even false circularities.
28722
28723 This default mode is more restrictive than the Ada Reference
28724 Manual, and it is possible to construct programs which will compile
28725 using the dynamic model described there, but will run into a
28726 circularity using the safer static model we have described.
28727
28728 Of course any Ada compiler must be able to operate in a mode
28729 consistent with the requirements of the Ada Reference Manual,
28730 and in particular must have the capability of implementing the
28731 standard dynamic model of elaboration with run-time checks.
28732
28733 In GNAT, this standard mode can be achieved either by the use of
28734 the @option{-gnatE} switch on the compiler (@command{gcc} or
28735 @command{gnatmake}) command, or by the use of the configuration pragma:
28736
28737 @smallexample @c ada
28738 pragma Elaboration_Checks (DYNAMIC);
28739 @end smallexample
28740
28741 @noindent
28742 Either approach will cause the unit affected to be compiled using the
28743 standard dynamic run-time elaboration checks described in the Ada
28744 Reference Manual. The static model is generally preferable, since it
28745 is clearly safer to rely on compile and link time checks rather than
28746 run-time checks. However, in the case of legacy code, it may be
28747 difficult to meet the requirements of the static model. This
28748 issue is further discussed in
28749 @ref{What to Do If the Default Elaboration Behavior Fails}.
28750
28751 Note that the static model provides a strict subset of the allowed
28752 behavior and programs of the Ada Reference Manual, so if you do
28753 adhere to the static model and no circularities exist,
28754 then you are assured that your program will
28755 work using the dynamic model, providing that you remove any
28756 pragma Elaborate statements from the source.
28757
28758 @node Treatment of Pragma Elaborate
28759 @section Treatment of Pragma Elaborate
28760 @cindex Pragma Elaborate
28761
28762 @noindent
28763 The use of @code{pragma Elaborate}
28764 should generally be avoided in Ada 95 and Ada 2005 programs,
28765 since there is no guarantee that transitive calls
28766 will be properly handled. Indeed at one point, this pragma was placed
28767 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28768
28769 Now that's a bit restrictive. In practice, the case in which
28770 @code{pragma Elaborate} is useful is when the caller knows that there
28771 are no transitive calls, or that the called unit contains all necessary
28772 transitive @code{pragma Elaborate} statements, and legacy code often
28773 contains such uses.
28774
28775 Strictly speaking the static mode in GNAT should ignore such pragmas,
28776 since there is no assurance at compile time that the necessary safety
28777 conditions are met. In practice, this would cause GNAT to be incompatible
28778 with correctly written Ada 83 code that had all necessary
28779 @code{pragma Elaborate} statements in place. Consequently, we made the
28780 decision that GNAT in its default mode will believe that if it encounters
28781 a @code{pragma Elaborate} then the programmer knows what they are doing,
28782 and it will trust that no elaboration errors can occur.
28783
28784 The result of this decision is two-fold. First to be safe using the
28785 static mode, you should remove all @code{pragma Elaborate} statements.
28786 Second, when fixing circularities in existing code, you can selectively
28787 use @code{pragma Elaborate} statements to convince the static mode of
28788 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28789 statement.
28790
28791 When using the static mode with @option{-gnatwl}, any use of
28792 @code{pragma Elaborate} will generate a warning about possible
28793 problems.
28794
28795 @node Elaboration Issues for Library Tasks
28796 @section Elaboration Issues for Library Tasks
28797 @cindex Library tasks, elaboration issues
28798 @cindex Elaboration of library tasks
28799
28800 @noindent
28801 In this section we examine special elaboration issues that arise for
28802 programs that declare library level tasks.
28803
28804 Generally the model of execution of an Ada program is that all units are
28805 elaborated, and then execution of the program starts. However, the
28806 declaration of library tasks definitely does not fit this model. The
28807 reason for this is that library tasks start as soon as they are declared
28808 (more precisely, as soon as the statement part of the enclosing package
28809 body is reached), that is to say before elaboration
28810 of the program is complete. This means that if such a task calls a
28811 subprogram, or an entry in another task, the callee may or may not be
28812 elaborated yet, and in the standard
28813 Reference Manual model of dynamic elaboration checks, you can even
28814 get timing dependent Program_Error exceptions, since there can be
28815 a race between the elaboration code and the task code.
28816
28817 The static model of elaboration in GNAT seeks to avoid all such
28818 dynamic behavior, by being conservative, and the conservative
28819 approach in this particular case is to assume that all the code
28820 in a task body is potentially executed at elaboration time if
28821 a task is declared at the library level.
28822
28823 This can definitely result in unexpected circularities. Consider
28824 the following example
28825
28826 @smallexample @c ada
28827 package Decls is
28828 task Lib_Task is
28829 entry Start;
28830 end Lib_Task;
28831
28832 type My_Int is new Integer;
28833
28834 function Ident (M : My_Int) return My_Int;
28835 end Decls;
28836
28837 with Utils;
28838 package body Decls is
28839 task body Lib_Task is
28840 begin
28841 accept Start;
28842 Utils.Put_Val (2);
28843 end Lib_Task;
28844
28845 function Ident (M : My_Int) return My_Int is
28846 begin
28847 return M;
28848 end Ident;
28849 end Decls;
28850
28851 with Decls;
28852 package Utils is
28853 procedure Put_Val (Arg : Decls.My_Int);
28854 end Utils;
28855
28856 with Text_IO;
28857 package body Utils is
28858 procedure Put_Val (Arg : Decls.My_Int) is
28859 begin
28860 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28861 end Put_Val;
28862 end Utils;
28863
28864 with Decls;
28865 procedure Main is
28866 begin
28867 Decls.Lib_Task.Start;
28868 end;
28869 @end smallexample
28870
28871 @noindent
28872 If the above example is compiled in the default static elaboration
28873 mode, then a circularity occurs. The circularity comes from the call
28874 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28875 this call occurs in elaboration code, we need an implicit pragma
28876 @code{Elaborate_All} for @code{Utils}. This means that not only must
28877 the spec and body of @code{Utils} be elaborated before the body
28878 of @code{Decls}, but also the spec and body of any unit that is
28879 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28880 the body of @code{Decls}. This is the transitive implication of
28881 pragma @code{Elaborate_All} and it makes sense, because in general
28882 the body of @code{Put_Val} might have a call to something in a
28883 @code{with'ed} unit.
28884
28885 In this case, the body of Utils (actually its spec) @code{with's}
28886 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28887 must be elaborated before itself, in case there is a call from the
28888 body of @code{Utils}.
28889
28890 Here is the exact chain of events we are worrying about:
28891
28892 @enumerate
28893 @item
28894 In the body of @code{Decls} a call is made from within the body of a library
28895 task to a subprogram in the package @code{Utils}. Since this call may
28896 occur at elaboration time (given that the task is activated at elaboration
28897 time), we have to assume the worst, i.e., that the
28898 call does happen at elaboration time.
28899
28900 @item
28901 This means that the body and spec of @code{Util} must be elaborated before
28902 the body of @code{Decls} so that this call does not cause an access before
28903 elaboration.
28904
28905 @item
28906 Within the body of @code{Util}, specifically within the body of
28907 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28908 by this package.
28909
28910 @item
28911 One such @code{with}'ed package is package @code{Decls}, so there
28912 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28913 In fact there is such a call in this example, but we would have to
28914 assume that there was such a call even if it were not there, since
28915 we are not supposed to write the body of @code{Decls} knowing what
28916 is in the body of @code{Utils}; certainly in the case of the
28917 static elaboration model, the compiler does not know what is in
28918 other bodies and must assume the worst.
28919
28920 @item
28921 This means that the spec and body of @code{Decls} must also be
28922 elaborated before we elaborate the unit containing the call, but
28923 that unit is @code{Decls}! This means that the body of @code{Decls}
28924 must be elaborated before itself, and that's a circularity.
28925 @end enumerate
28926
28927 @noindent
28928 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28929 the body of @code{Decls} you will get a true Ada Reference Manual
28930 circularity that makes the program illegal.
28931
28932 In practice, we have found that problems with the static model of
28933 elaboration in existing code often arise from library tasks, so
28934 we must address this particular situation.
28935
28936 Note that if we compile and run the program above, using the dynamic model of
28937 elaboration (that is to say use the @option{-gnatE} switch),
28938 then it compiles, binds,
28939 links, and runs, printing the expected result of 2. Therefore in some sense
28940 the circularity here is only apparent, and we need to capture
28941 the properties of this program that distinguish it from other library-level
28942 tasks that have real elaboration problems.
28943
28944 We have four possible answers to this question:
28945
28946 @itemize @bullet
28947
28948 @item
28949 Use the dynamic model of elaboration.
28950
28951 If we use the @option{-gnatE} switch, then as noted above, the program works.
28952 Why is this? If we examine the task body, it is apparent that the task cannot
28953 proceed past the
28954 @code{accept} statement until after elaboration has been completed, because
28955 the corresponding entry call comes from the main program, not earlier.
28956 This is why the dynamic model works here. But that's really giving
28957 up on a precise analysis, and we prefer to take this approach only if we cannot
28958 solve the
28959 problem in any other manner. So let us examine two ways to reorganize
28960 the program to avoid the potential elaboration problem.
28961
28962 @item
28963 Split library tasks into separate packages.
28964
28965 Write separate packages, so that library tasks are isolated from
28966 other declarations as much as possible. Let us look at a variation on
28967 the above program.
28968
28969 @smallexample @c ada
28970 package Decls1 is
28971 task Lib_Task is
28972 entry Start;
28973 end Lib_Task;
28974 end Decls1;
28975
28976 with Utils;
28977 package body Decls1 is
28978 task body Lib_Task is
28979 begin
28980 accept Start;
28981 Utils.Put_Val (2);
28982 end Lib_Task;
28983 end Decls1;
28984
28985 package Decls2 is
28986 type My_Int is new Integer;
28987 function Ident (M : My_Int) return My_Int;
28988 end Decls2;
28989
28990 with Utils;
28991 package body Decls2 is
28992 function Ident (M : My_Int) return My_Int is
28993 begin
28994 return M;
28995 end Ident;
28996 end Decls2;
28997
28998 with Decls2;
28999 package Utils is
29000 procedure Put_Val (Arg : Decls2.My_Int);
29001 end Utils;
29002
29003 with Text_IO;
29004 package body Utils is
29005 procedure Put_Val (Arg : Decls2.My_Int) is
29006 begin
29007 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29008 end Put_Val;
29009 end Utils;
29010
29011 with Decls1;
29012 procedure Main is
29013 begin
29014 Decls1.Lib_Task.Start;
29015 end;
29016 @end smallexample
29017
29018 @noindent
29019 All we have done is to split @code{Decls} into two packages, one
29020 containing the library task, and one containing everything else. Now
29021 there is no cycle, and the program compiles, binds, links and executes
29022 using the default static model of elaboration.
29023
29024 @item
29025 Declare separate task types.
29026
29027 A significant part of the problem arises because of the use of the
29028 single task declaration form. This means that the elaboration of
29029 the task type, and the elaboration of the task itself (i.e.@: the
29030 creation of the task) happen at the same time. A good rule
29031 of style in Ada is to always create explicit task types. By
29032 following the additional step of placing task objects in separate
29033 packages from the task type declaration, many elaboration problems
29034 are avoided. Here is another modified example of the example program:
29035
29036 @smallexample @c ada
29037 package Decls is
29038 task type Lib_Task_Type is
29039 entry Start;
29040 end Lib_Task_Type;
29041
29042 type My_Int is new Integer;
29043
29044 function Ident (M : My_Int) return My_Int;
29045 end Decls;
29046
29047 with Utils;
29048 package body Decls is
29049 task body Lib_Task_Type is
29050 begin
29051 accept Start;
29052 Utils.Put_Val (2);
29053 end Lib_Task_Type;
29054
29055 function Ident (M : My_Int) return My_Int is
29056 begin
29057 return M;
29058 end Ident;
29059 end Decls;
29060
29061 with Decls;
29062 package Utils is
29063 procedure Put_Val (Arg : Decls.My_Int);
29064 end Utils;
29065
29066 with Text_IO;
29067 package body Utils is
29068 procedure Put_Val (Arg : Decls.My_Int) is
29069 begin
29070 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29071 end Put_Val;
29072 end Utils;
29073
29074 with Decls;
29075 package Declst is
29076 Lib_Task : Decls.Lib_Task_Type;
29077 end Declst;
29078
29079 with Declst;
29080 procedure Main is
29081 begin
29082 Declst.Lib_Task.Start;
29083 end;
29084 @end smallexample
29085
29086 @noindent
29087 What we have done here is to replace the @code{task} declaration in
29088 package @code{Decls} with a @code{task type} declaration. Then we
29089 introduce a separate package @code{Declst} to contain the actual
29090 task object. This separates the elaboration issues for
29091 the @code{task type}
29092 declaration, which causes no trouble, from the elaboration issues
29093 of the task object, which is also unproblematic, since it is now independent
29094 of the elaboration of @code{Utils}.
29095 This separation of concerns also corresponds to
29096 a generally sound engineering principle of separating declarations
29097 from instances. This version of the program also compiles, binds, links,
29098 and executes, generating the expected output.
29099
29100 @item
29101 Use No_Entry_Calls_In_Elaboration_Code restriction.
29102 @cindex No_Entry_Calls_In_Elaboration_Code
29103
29104 The previous two approaches described how a program can be restructured
29105 to avoid the special problems caused by library task bodies. in practice,
29106 however, such restructuring may be difficult to apply to existing legacy code,
29107 so we must consider solutions that do not require massive rewriting.
29108
29109 Let us consider more carefully why our original sample program works
29110 under the dynamic model of elaboration. The reason is that the code
29111 in the task body blocks immediately on the @code{accept}
29112 statement. Now of course there is nothing to prohibit elaboration
29113 code from making entry calls (for example from another library level task),
29114 so we cannot tell in isolation that
29115 the task will not execute the accept statement during elaboration.
29116
29117 However, in practice it is very unusual to see elaboration code
29118 make any entry calls, and the pattern of tasks starting
29119 at elaboration time and then immediately blocking on @code{accept} or
29120 @code{select} statements is very common. What this means is that
29121 the compiler is being too pessimistic when it analyzes the
29122 whole package body as though it might be executed at elaboration
29123 time.
29124
29125 If we know that the elaboration code contains no entry calls, (a very safe
29126 assumption most of the time, that could almost be made the default
29127 behavior), then we can compile all units of the program under control
29128 of the following configuration pragma:
29129
29130 @smallexample
29131 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29132 @end smallexample
29133
29134 @noindent
29135 This pragma can be placed in the @file{gnat.adc} file in the usual
29136 manner. If we take our original unmodified program and compile it
29137 in the presence of a @file{gnat.adc} containing the above pragma,
29138 then once again, we can compile, bind, link, and execute, obtaining
29139 the expected result. In the presence of this pragma, the compiler does
29140 not trace calls in a task body, that appear after the first @code{accept}
29141 or @code{select} statement, and therefore does not report a potential
29142 circularity in the original program.
29143
29144 The compiler will check to the extent it can that the above
29145 restriction is not violated, but it is not always possible to do a
29146 complete check at compile time, so it is important to use this
29147 pragma only if the stated restriction is in fact met, that is to say
29148 no task receives an entry call before elaboration of all units is completed.
29149
29150 @end itemize
29151
29152 @node Mixing Elaboration Models
29153 @section Mixing Elaboration Models
29154 @noindent
29155 So far, we have assumed that the entire program is either compiled
29156 using the dynamic model or static model, ensuring consistency. It
29157 is possible to mix the two models, but rules have to be followed
29158 if this mixing is done to ensure that elaboration checks are not
29159 omitted.
29160
29161 The basic rule is that @emph{a unit compiled with the static model cannot
29162 be @code{with'ed} by a unit compiled with the dynamic model}. The
29163 reason for this is that in the static model, a unit assumes that
29164 its clients guarantee to use (the equivalent of) pragma
29165 @code{Elaborate_All} so that no elaboration checks are required
29166 in inner subprograms, and this assumption is violated if the
29167 client is compiled with dynamic checks.
29168
29169 The precise rule is as follows. A unit that is compiled with dynamic
29170 checks can only @code{with} a unit that meets at least one of the
29171 following criteria:
29172
29173 @itemize @bullet
29174
29175 @item
29176 The @code{with'ed} unit is itself compiled with dynamic elaboration
29177 checks (that is with the @option{-gnatE} switch.
29178
29179 @item
29180 The @code{with'ed} unit is an internal GNAT implementation unit from
29181 the System, Interfaces, Ada, or GNAT hierarchies.
29182
29183 @item
29184 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29185
29186 @item
29187 The @code{with'ing} unit (that is the client) has an explicit pragma
29188 @code{Elaborate_All} for the @code{with'ed} unit.
29189
29190 @end itemize
29191
29192 @noindent
29193 If this rule is violated, that is if a unit with dynamic elaboration
29194 checks @code{with's} a unit that does not meet one of the above four
29195 criteria, then the binder (@code{gnatbind}) will issue a warning
29196 similar to that in the following example:
29197
29198 @smallexample
29199 warning: "x.ads" has dynamic elaboration checks and with's
29200 warning: "y.ads" which has static elaboration checks
29201 @end smallexample
29202
29203 @noindent
29204 These warnings indicate that the rule has been violated, and that as a result
29205 elaboration checks may be missed in the resulting executable file.
29206 This warning may be suppressed using the @option{-ws} binder switch
29207 in the usual manner.
29208
29209 One useful application of this mixing rule is in the case of a subsystem
29210 which does not itself @code{with} units from the remainder of the
29211 application. In this case, the entire subsystem can be compiled with
29212 dynamic checks to resolve a circularity in the subsystem, while
29213 allowing the main application that uses this subsystem to be compiled
29214 using the more reliable default static model.
29215
29216 @node What to Do If the Default Elaboration Behavior Fails
29217 @section What to Do If the Default Elaboration Behavior Fails
29218
29219 @noindent
29220 If the binder cannot find an acceptable order, it outputs detailed
29221 diagnostics. For example:
29222 @smallexample
29223 @group
29224 @iftex
29225 @leftskip=0cm
29226 @end iftex
29227 error: elaboration circularity detected
29228 info: "proc (body)" must be elaborated before "pack (body)"
29229 info: reason: Elaborate_All probably needed in unit "pack (body)"
29230 info: recompile "pack (body)" with -gnatwl
29231 info: for full details
29232 info: "proc (body)"
29233 info: is needed by its spec:
29234 info: "proc (spec)"
29235 info: which is withed by:
29236 info: "pack (body)"
29237 info: "pack (body)" must be elaborated before "proc (body)"
29238 info: reason: pragma Elaborate in unit "proc (body)"
29239 @end group
29240
29241 @end smallexample
29242
29243 @noindent
29244 In this case we have a cycle that the binder cannot break. On the one
29245 hand, there is an explicit pragma Elaborate in @code{proc} for
29246 @code{pack}. This means that the body of @code{pack} must be elaborated
29247 before the body of @code{proc}. On the other hand, there is elaboration
29248 code in @code{pack} that calls a subprogram in @code{proc}. This means
29249 that for maximum safety, there should really be a pragma
29250 Elaborate_All in @code{pack} for @code{proc} which would require that
29251 the body of @code{proc} be elaborated before the body of
29252 @code{pack}. Clearly both requirements cannot be satisfied.
29253 Faced with a circularity of this kind, you have three different options.
29254
29255 @table @asis
29256 @item Fix the program
29257 The most desirable option from the point of view of long-term maintenance
29258 is to rearrange the program so that the elaboration problems are avoided.
29259 One useful technique is to place the elaboration code into separate
29260 child packages. Another is to move some of the initialization code to
29261 explicitly called subprograms, where the program controls the order
29262 of initialization explicitly. Although this is the most desirable option,
29263 it may be impractical and involve too much modification, especially in
29264 the case of complex legacy code.
29265
29266 @item Perform dynamic checks
29267 If the compilations are done using the
29268 @option{-gnatE}
29269 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29270 manner. Dynamic checks are generated for all calls that could possibly result
29271 in raising an exception. With this switch, the compiler does not generate
29272 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29273 exactly as specified in the @cite{Ada Reference Manual}.
29274 The binder will generate
29275 an executable program that may or may not raise @code{Program_Error}, and then
29276 it is the programmer's job to ensure that it does not raise an exception. Note
29277 that it is important to compile all units with the switch, it cannot be used
29278 selectively.
29279
29280 @item Suppress checks
29281 The drawback of dynamic checks is that they generate a
29282 significant overhead at run time, both in space and time. If you
29283 are absolutely sure that your program cannot raise any elaboration
29284 exceptions, and you still want to use the dynamic elaboration model,
29285 then you can use the configuration pragma
29286 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29287 example this pragma could be placed in the @file{gnat.adc} file.
29288
29289 @item Suppress checks selectively
29290 When you know that certain calls or instantiations in elaboration code cannot
29291 possibly lead to an elaboration error, and the binder nevertheless complains
29292 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29293 elaboration circularities, it is possible to remove those warnings locally and
29294 obtain a program that will bind. Clearly this can be unsafe, and it is the
29295 responsibility of the programmer to make sure that the resulting program has no
29296 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29297 used with different granularity to suppress warnings and break elaboration
29298 circularities:
29299
29300 @itemize @bullet
29301 @item
29302 Place the pragma that names the called subprogram in the declarative part
29303 that contains the call.
29304
29305 @item
29306 Place the pragma in the declarative part, without naming an entity. This
29307 disables warnings on all calls in the corresponding declarative region.
29308
29309 @item
29310 Place the pragma in the package spec that declares the called subprogram,
29311 and name the subprogram. This disables warnings on all elaboration calls to
29312 that subprogram.
29313
29314 @item
29315 Place the pragma in the package spec that declares the called subprogram,
29316 without naming any entity. This disables warnings on all elaboration calls to
29317 all subprograms declared in this spec.
29318
29319 @item Use Pragma Elaborate
29320 As previously described in section @xref{Treatment of Pragma Elaborate},
29321 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29322 that no elaboration checks are required on calls to the designated unit.
29323 There may be cases in which the caller knows that no transitive calls
29324 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29325 case where @code{pragma Elaborate_All} would cause a circularity.
29326 @end itemize
29327
29328 @noindent
29329 These five cases are listed in order of decreasing safety, and therefore
29330 require increasing programmer care in their application. Consider the
29331 following program:
29332
29333 @smallexample @c adanocomment
29334 package Pack1 is
29335 function F1 return Integer;
29336 X1 : Integer;
29337 end Pack1;
29338
29339 package Pack2 is
29340 function F2 return Integer;
29341 function Pure (x : integer) return integer;
29342 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
29343 -- pragma Suppress (Elaboration_Check); -- (4)
29344 end Pack2;
29345
29346 with Pack2;
29347 package body Pack1 is
29348 function F1 return Integer is
29349 begin
29350 return 100;
29351 end F1;
29352 Val : integer := Pack2.Pure (11); -- Elab. call (1)
29353 begin
29354 declare
29355 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
29356 -- pragma Suppress(Elaboration_Check); -- (2)
29357 begin
29358 X1 := Pack2.F2 + 1; -- Elab. call (2)
29359 end;
29360 end Pack1;
29361
29362 with Pack1;
29363 package body Pack2 is
29364 function F2 return Integer is
29365 begin
29366 return Pack1.F1;
29367 end F2;
29368 function Pure (x : integer) return integer is
29369 begin
29370 return x ** 3 - 3 * x;
29371 end;
29372 end Pack2;
29373
29374 with Pack1, Ada.Text_IO;
29375 procedure Proc3 is
29376 begin
29377 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29378 end Proc3;
29379 @end smallexample
29380 In the absence of any pragmas, an attempt to bind this program produces
29381 the following diagnostics:
29382 @smallexample
29383 @group
29384 @iftex
29385 @leftskip=.5cm
29386 @end iftex
29387 error: elaboration circularity detected
29388 info: "pack1 (body)" must be elaborated before "pack1 (body)"
29389 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
29390 info: recompile "pack1 (body)" with -gnatwl for full details
29391 info: "pack1 (body)"
29392 info: must be elaborated along with its spec:
29393 info: "pack1 (spec)"
29394 info: which is withed by:
29395 info: "pack2 (body)"
29396 info: which must be elaborated along with its spec:
29397 info: "pack2 (spec)"
29398 info: which is withed by:
29399 info: "pack1 (body)"
29400 @end group
29401 @end smallexample
29402 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29403 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29404 F2 is safe, even though F2 calls F1, because the call appears after the
29405 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29406 remove the warning on the call. It is also possible to use pragma (2)
29407 because there are no other potentially unsafe calls in the block.
29408
29409 @noindent
29410 The call to @code{Pure} is safe because this function does not depend on the
29411 state of @code{Pack2}. Therefore any call to this function is safe, and it
29412 is correct to place pragma (3) in the corresponding package spec.
29413
29414 @noindent
29415 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29416 warnings on all calls to functions declared therein. Note that this is not
29417 necessarily safe, and requires more detailed examination of the subprogram
29418 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29419 be already elaborated.
29420 @end table
29421
29422 @noindent
29423 It is hard to generalize on which of these four approaches should be
29424 taken. Obviously if it is possible to fix the program so that the default
29425 treatment works, this is preferable, but this may not always be practical.
29426 It is certainly simple enough to use
29427 @option{-gnatE}
29428 but the danger in this case is that, even if the GNAT binder
29429 finds a correct elaboration order, it may not always do so,
29430 and certainly a binder from another Ada compiler might not. A
29431 combination of testing and analysis (for which the warnings generated
29432 with the
29433 @option{-gnatwl}
29434 switch can be useful) must be used to ensure that the program is free
29435 of errors. One switch that is useful in this testing is the
29436 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29437 switch for
29438 @code{gnatbind}.
29439 Normally the binder tries to find an order that has the best chance
29440 of avoiding elaboration problems. However, if this switch is used, the binder
29441 plays a devil's advocate role, and tries to choose the order that
29442 has the best chance of failing. If your program works even with this
29443 switch, then it has a better chance of being error free, but this is still
29444 not a guarantee.
29445
29446 For an example of this approach in action, consider the C-tests (executable
29447 tests) from the ACVC suite. If these are compiled and run with the default
29448 treatment, then all but one of them succeed without generating any error
29449 diagnostics from the binder. However, there is one test that fails, and
29450 this is not surprising, because the whole point of this test is to ensure
29451 that the compiler can handle cases where it is impossible to determine
29452 a correct order statically, and it checks that an exception is indeed
29453 raised at run time.
29454
29455 This one test must be compiled and run using the
29456 @option{-gnatE}
29457 switch, and then it passes. Alternatively, the entire suite can
29458 be run using this switch. It is never wrong to run with the dynamic
29459 elaboration switch if your code is correct, and we assume that the
29460 C-tests are indeed correct (it is less efficient, but efficiency is
29461 not a factor in running the ACVC tests.)
29462
29463 @node Elaboration for Access-to-Subprogram Values
29464 @section Elaboration for Access-to-Subprogram Values
29465 @cindex Access-to-subprogram
29466
29467 @noindent
29468 Access-to-subprogram types (introduced in Ada 95) complicate
29469 the handling of elaboration. The trouble is that it becomes
29470 impossible to tell at compile time which procedure
29471 is being called. This means that it is not possible for the binder
29472 to analyze the elaboration requirements in this case.
29473
29474 If at the point at which the access value is created
29475 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29476 the body of the subprogram is
29477 known to have been elaborated, then the access value is safe, and its use
29478 does not require a check. This may be achieved by appropriate arrangement
29479 of the order of declarations if the subprogram is in the current unit,
29480 or, if the subprogram is in another unit, by using pragma
29481 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29482 on the referenced unit.
29483
29484 If the referenced body is not known to have been elaborated at the point
29485 the access value is created, then any use of the access value must do a
29486 dynamic check, and this dynamic check will fail and raise a
29487 @code{Program_Error} exception if the body has not been elaborated yet.
29488 GNAT will generate the necessary checks, and in addition, if the
29489 @option{-gnatwl}
29490 switch is set, will generate warnings that such checks are required.
29491
29492 The use of dynamic dispatching for tagged types similarly generates
29493 a requirement for dynamic checks, and premature calls to any primitive
29494 operation of a tagged type before the body of the operation has been
29495 elaborated, will result in the raising of @code{Program_Error}.
29496
29497 @node Summary of Procedures for Elaboration Control
29498 @section Summary of Procedures for Elaboration Control
29499 @cindex Elaboration control
29500
29501 @noindent
29502 First, compile your program with the default options, using none of
29503 the special elaboration control switches. If the binder successfully
29504 binds your program, then you can be confident that, apart from issues
29505 raised by the use of access-to-subprogram types and dynamic dispatching,
29506 the program is free of elaboration errors. If it is important that the
29507 program be portable, then use the
29508 @option{-gnatwl}
29509 switch to generate warnings about missing @code{Elaborate} or
29510 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29511
29512 If the program fails to bind using the default static elaboration
29513 handling, then you can fix the program to eliminate the binder
29514 message, or recompile the entire program with the
29515 @option{-gnatE} switch to generate dynamic elaboration checks,
29516 and, if you are sure there really are no elaboration problems,
29517 use a global pragma @code{Suppress (Elaboration_Check)}.
29518
29519 @node Other Elaboration Order Considerations
29520 @section Other Elaboration Order Considerations
29521 @noindent
29522 This section has been entirely concerned with the issue of finding a valid
29523 elaboration order, as defined by the Ada Reference Manual. In a case
29524 where several elaboration orders are valid, the task is to find one
29525 of the possible valid elaboration orders (and the static model in GNAT
29526 will ensure that this is achieved).
29527
29528 The purpose of the elaboration rules in the Ada Reference Manual is to
29529 make sure that no entity is accessed before it has been elaborated. For
29530 a subprogram, this means that the spec and body must have been elaborated
29531 before the subprogram is called. For an object, this means that the object
29532 must have been elaborated before its value is read or written. A violation
29533 of either of these two requirements is an access before elaboration order,
29534 and this section has been all about avoiding such errors.
29535
29536 In the case where more than one order of elaboration is possible, in the
29537 sense that access before elaboration errors are avoided, then any one of
29538 the orders is ``correct'' in the sense that it meets the requirements of
29539 the Ada Reference Manual, and no such error occurs.
29540
29541 However, it may be the case for a given program, that there are
29542 constraints on the order of elaboration that come not from consideration
29543 of avoiding elaboration errors, but rather from extra-lingual logic
29544 requirements. Consider this example:
29545
29546 @smallexample @c ada
29547 with Init_Constants;
29548 package Constants is
29549 X : Integer := 0;
29550 Y : Integer := 0;
29551 end Constants;
29552
29553 package Init_Constants is
29554 procedure P; -- require a body
29555 end Init_Constants;
29556
29557 with Constants;
29558 package body Init_Constants is
29559 procedure P is begin null; end;
29560 begin
29561 Constants.X := 3;
29562 Constants.Y := 4;
29563 end Init_Constants;
29564
29565 with Constants;
29566 package Calc is
29567 Z : Integer := Constants.X + Constants.Y;
29568 end Calc;
29569
29570 with Calc;
29571 with Text_IO; use Text_IO;
29572 procedure Main is
29573 begin
29574 Put_Line (Calc.Z'Img);
29575 end Main;
29576 @end smallexample
29577
29578 @noindent
29579 In this example, there is more than one valid order of elaboration. For
29580 example both the following are correct orders:
29581
29582 @smallexample
29583 Init_Constants spec
29584 Constants spec
29585 Calc spec
29586 Init_Constants body
29587 Main body
29588
29589 and
29590
29591 Init_Constants spec
29592 Init_Constants body
29593 Constants spec
29594 Calc spec
29595 Main body
29596 @end smallexample
29597
29598 @noindent
29599 There is no language rule to prefer one or the other, both are correct
29600 from an order of elaboration point of view. But the programmatic effects
29601 of the two orders are very different. In the first, the elaboration routine
29602 of @code{Calc} initializes @code{Z} to zero, and then the main program
29603 runs with this value of zero. But in the second order, the elaboration
29604 routine of @code{Calc} runs after the body of Init_Constants has set
29605 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29606 runs.
29607
29608 One could perhaps by applying pretty clever non-artificial intelligence
29609 to the situation guess that it is more likely that the second order of
29610 elaboration is the one desired, but there is no formal linguistic reason
29611 to prefer one over the other. In fact in this particular case, GNAT will
29612 prefer the second order, because of the rule that bodies are elaborated
29613 as soon as possible, but it's just luck that this is what was wanted
29614 (if indeed the second order was preferred).
29615
29616 If the program cares about the order of elaboration routines in a case like
29617 this, it is important to specify the order required. In this particular
29618 case, that could have been achieved by adding to the spec of Calc:
29619
29620 @smallexample @c ada
29621 pragma Elaborate_All (Constants);
29622 @end smallexample
29623
29624 @noindent
29625 which requires that the body (if any) and spec of @code{Constants},
29626 as well as the body and spec of any unit @code{with}'ed by
29627 @code{Constants} be elaborated before @code{Calc} is elaborated.
29628
29629 Clearly no automatic method can always guess which alternative you require,
29630 and if you are working with legacy code that had constraints of this kind
29631 which were not properly specified by adding @code{Elaborate} or
29632 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29633 compilers can choose different orders.
29634
29635 However, GNAT does attempt to diagnose the common situation where there
29636 are uninitialized variables in the visible part of a package spec, and the
29637 corresponding package body has an elaboration block that directly or
29638 indirectly initialized one or more of these variables. This is the situation
29639 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29640 a warning that suggests this addition if it detects this situation.
29641
29642 The @code{gnatbind}
29643 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29644 out problems. This switch causes bodies to be elaborated as late as possible
29645 instead of as early as possible. In the example above, it would have forced
29646 the choice of the first elaboration order. If you get different results
29647 when using this switch, and particularly if one set of results is right,
29648 and one is wrong as far as you are concerned, it shows that you have some
29649 missing @code{Elaborate} pragmas. For the example above, we have the
29650 following output:
29651
29652 @smallexample
29653 gnatmake -f -q main
29654 main
29655 7
29656 gnatmake -f -q main -bargs -p
29657 main
29658 0
29659 @end smallexample
29660
29661 @noindent
29662 It is of course quite unlikely that both these results are correct, so
29663 it is up to you in a case like this to investigate the source of the
29664 difference, by looking at the two elaboration orders that are chosen,
29665 and figuring out which is correct, and then adding the necessary
29666 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29667
29668
29669
29670 @c *******************************
29671 @node Conditional Compilation
29672 @appendix Conditional Compilation
29673 @c *******************************
29674 @cindex Conditional compilation
29675
29676 @noindent
29677 It is often necessary to arrange for a single source program
29678 to serve multiple purposes, where it is compiled in different
29679 ways to achieve these different goals. Some examples of the
29680 need for this feature are
29681
29682 @itemize @bullet
29683 @item Adapting a program to a different hardware environment
29684 @item Adapting a program to a different target architecture
29685 @item Turning debugging features on and off
29686 @item Arranging for a program to compile with different compilers
29687 @end itemize
29688
29689 @noindent
29690 In C, or C++, the typical approach would be to use the preprocessor
29691 that is defined as part of the language. The Ada language does not
29692 contain such a feature. This is not an oversight, but rather a very
29693 deliberate design decision, based on the experience that overuse of
29694 the preprocessing features in C and C++ can result in programs that
29695 are extremely difficult to maintain. For example, if we have ten
29696 switches that can be on or off, this means that there are a thousand
29697 separate programs, any one of which might not even be syntactically
29698 correct, and even if syntactically correct, the resulting program
29699 might not work correctly. Testing all combinations can quickly become
29700 impossible.
29701
29702 Nevertheless, the need to tailor programs certainly exists, and in
29703 this Appendix we will discuss how this can
29704 be achieved using Ada in general, and GNAT in particular.
29705
29706 @menu
29707 * Use of Boolean Constants::
29708 * Debugging - A Special Case::
29709 * Conditionalizing Declarations::
29710 * Use of Alternative Implementations::
29711 * Preprocessing::
29712 @end menu
29713
29714 @node Use of Boolean Constants
29715 @section Use of Boolean Constants
29716
29717 @noindent
29718 In the case where the difference is simply which code
29719 sequence is executed, the cleanest solution is to use Boolean
29720 constants to control which code is executed.
29721
29722 @smallexample @c ada
29723 @group
29724 FP_Initialize_Required : constant Boolean := True;
29725 @dots{}
29726 if FP_Initialize_Required then
29727 @dots{}
29728 end if;
29729 @end group
29730 @end smallexample
29731
29732 @noindent
29733 Not only will the code inside the @code{if} statement not be executed if
29734 the constant Boolean is @code{False}, but it will also be completely
29735 deleted from the program.
29736 However, the code is only deleted after the @code{if} statement
29737 has been checked for syntactic and semantic correctness.
29738 (In contrast, with preprocessors the code is deleted before the
29739 compiler ever gets to see it, so it is not checked until the switch
29740 is turned on.)
29741 @cindex Preprocessors (contrasted with conditional compilation)
29742
29743 Typically the Boolean constants will be in a separate package,
29744 something like:
29745
29746 @smallexample @c ada
29747 @group
29748 package Config is
29749 FP_Initialize_Required : constant Boolean := True;
29750 Reset_Available : constant Boolean := False;
29751 @dots{}
29752 end Config;
29753 @end group
29754 @end smallexample
29755
29756 @noindent
29757 The @code{Config} package exists in multiple forms for the various targets,
29758 with an appropriate script selecting the version of @code{Config} needed.
29759 Then any other unit requiring conditional compilation can do a @code{with}
29760 of @code{Config} to make the constants visible.
29761
29762
29763 @node Debugging - A Special Case
29764 @section Debugging - A Special Case
29765
29766 @noindent
29767 A common use of conditional code is to execute statements (for example
29768 dynamic checks, or output of intermediate results) under control of a
29769 debug switch, so that the debugging behavior can be turned on and off.
29770 This can be done using a Boolean constant to control whether the code
29771 is active:
29772
29773 @smallexample @c ada
29774 @group
29775 if Debugging then
29776 Put_Line ("got to the first stage!");
29777 end if;
29778 @end group
29779 @end smallexample
29780
29781 @noindent
29782 or
29783
29784 @smallexample @c ada
29785 @group
29786 if Debugging and then Temperature > 999.0 then
29787 raise Temperature_Crazy;
29788 end if;
29789 @end group
29790 @end smallexample
29791
29792 @noindent
29793 Since this is a common case, there are special features to deal with
29794 this in a convenient manner. For the case of tests, Ada 2005 has added
29795 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29796 @cindex pragma @code{Assert}
29797 on the @code{Assert} pragma that has always been available in GNAT, so this
29798 feature may be used with GNAT even if you are not using Ada 2005 features.
29799 The use of pragma @code{Assert} is described in
29800 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29801 example, the last test could be written:
29802
29803 @smallexample @c ada
29804 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29805 @end smallexample
29806
29807 @noindent
29808 or simply
29809
29810 @smallexample @c ada
29811 pragma Assert (Temperature <= 999.0);
29812 @end smallexample
29813
29814 @noindent
29815 In both cases, if assertions are active and the temperature is excessive,
29816 the exception @code{Assert_Failure} will be raised, with the given string in
29817 the first case or a string indicating the location of the pragma in the second
29818 case used as the exception message.
29819
29820 You can turn assertions on and off by using the @code{Assertion_Policy}
29821 pragma.
29822 @cindex pragma @code{Assertion_Policy}
29823 This is an Ada 2005 pragma which is implemented in all modes by
29824 GNAT, but only in the latest versions of GNAT which include Ada 2005
29825 capability. Alternatively, you can use the @option{-gnata} switch
29826 @cindex @option{-gnata} switch
29827 to enable assertions from the command line (this is recognized by all versions
29828 of GNAT).
29829
29830 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29831 @code{Debug} can be used:
29832 @cindex pragma @code{Debug}
29833
29834 @smallexample @c ada
29835 pragma Debug (Put_Line ("got to the first stage!"));
29836 @end smallexample
29837
29838 @noindent
29839 If debug pragmas are enabled, the argument, which must be of the form of
29840 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29841 Only one call can be present, but of course a special debugging procedure
29842 containing any code you like can be included in the program and then
29843 called in a pragma @code{Debug} argument as needed.
29844
29845 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29846 construct is that pragma @code{Debug} can appear in declarative contexts,
29847 such as at the very beginning of a procedure, before local declarations have
29848 been elaborated.
29849
29850 Debug pragmas are enabled using either the @option{-gnata} switch that also
29851 controls assertions, or with a separate Debug_Policy pragma.
29852 @cindex pragma @code{Debug_Policy}
29853 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29854 in Ada 95 and Ada 83 programs as well), and is analogous to
29855 pragma @code{Assertion_Policy} to control assertions.
29856
29857 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29858 and thus they can appear in @file{gnat.adc} if you are not using a
29859 project file, or in the file designated to contain configuration pragmas
29860 in a project file.
29861 They then apply to all subsequent compilations. In practice the use of
29862 the @option{-gnata} switch is often the most convenient method of controlling
29863 the status of these pragmas.
29864
29865 Note that a pragma is not a statement, so in contexts where a statement
29866 sequence is required, you can't just write a pragma on its own. You have
29867 to add a @code{null} statement.
29868
29869 @smallexample @c ada
29870 @group
29871 if @dots{} then
29872 @dots{} -- some statements
29873 else
29874 pragma Assert (Num_Cases < 10);
29875 null;
29876 end if;
29877 @end group
29878 @end smallexample
29879
29880
29881 @node Conditionalizing Declarations
29882 @section Conditionalizing Declarations
29883
29884 @noindent
29885 In some cases, it may be necessary to conditionalize declarations to meet
29886 different requirements. For example we might want a bit string whose length
29887 is set to meet some hardware message requirement.
29888
29889 In some cases, it may be possible to do this using declare blocks controlled
29890 by conditional constants:
29891
29892 @smallexample @c ada
29893 @group
29894 if Small_Machine then
29895 declare
29896 X : Bit_String (1 .. 10);
29897 begin
29898 @dots{}
29899 end;
29900 else
29901 declare
29902 X : Large_Bit_String (1 .. 1000);
29903 begin
29904 @dots{}
29905 end;
29906 end if;
29907 @end group
29908 @end smallexample
29909
29910 @noindent
29911 Note that in this approach, both declarations are analyzed by the
29912 compiler so this can only be used where both declarations are legal,
29913 even though one of them will not be used.
29914
29915 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29916 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29917 that are parameterized by these constants. For example
29918
29919 @smallexample @c ada
29920 @group
29921 for Rec use
29922 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29923 end record;
29924 @end group
29925 @end smallexample
29926
29927 @noindent
29928 If @code{Bits_Per_Word} is set to 32, this generates either
29929
29930 @smallexample @c ada
29931 @group
29932 for Rec use
29933 Field1 at 0 range 0 .. 32;
29934 end record;
29935 @end group
29936 @end smallexample
29937
29938 @noindent
29939 for the big endian case, or
29940
29941 @smallexample @c ada
29942 @group
29943 for Rec use record
29944 Field1 at 0 range 10 .. 32;
29945 end record;
29946 @end group
29947 @end smallexample
29948
29949 @noindent
29950 for the little endian case. Since a powerful subset of Ada expression
29951 notation is usable for creating static constants, clever use of this
29952 feature can often solve quite difficult problems in conditionalizing
29953 compilation (note incidentally that in Ada 95, the little endian
29954 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29955 need to define this one yourself).
29956
29957
29958 @node Use of Alternative Implementations
29959 @section Use of Alternative Implementations
29960
29961 @noindent
29962 In some cases, none of the approaches described above are adequate. This
29963 can occur for example if the set of declarations required is radically
29964 different for two different configurations.
29965
29966 In this situation, the official Ada way of dealing with conditionalizing
29967 such code is to write separate units for the different cases. As long as
29968 this does not result in excessive duplication of code, this can be done
29969 without creating maintenance problems. The approach is to share common
29970 code as far as possible, and then isolate the code and declarations
29971 that are different. Subunits are often a convenient method for breaking
29972 out a piece of a unit that is to be conditionalized, with separate files
29973 for different versions of the subunit for different targets, where the
29974 build script selects the right one to give to the compiler.
29975 @cindex Subunits (and conditional compilation)
29976
29977 As an example, consider a situation where a new feature in Ada 2005
29978 allows something to be done in a really nice way. But your code must be able
29979 to compile with an Ada 95 compiler. Conceptually you want to say:
29980
29981 @smallexample @c ada
29982 @group
29983 if Ada_2005 then
29984 @dots{} neat Ada 2005 code
29985 else
29986 @dots{} not quite as neat Ada 95 code
29987 end if;
29988 @end group
29989 @end smallexample
29990
29991 @noindent
29992 where @code{Ada_2005} is a Boolean constant.
29993
29994 But this won't work when @code{Ada_2005} is set to @code{False},
29995 since the @code{then} clause will be illegal for an Ada 95 compiler.
29996 (Recall that although such unreachable code would eventually be deleted
29997 by the compiler, it still needs to be legal. If it uses features
29998 introduced in Ada 2005, it will be illegal in Ada 95.)
29999
30000 So instead we write
30001
30002 @smallexample @c ada
30003 procedure Insert is separate;
30004 @end smallexample
30005
30006 @noindent
30007 Then we have two files for the subunit @code{Insert}, with the two sets of
30008 code.
30009 If the package containing this is called @code{File_Queries}, then we might
30010 have two files
30011
30012 @itemize @bullet
30013 @item @file{file_queries-insert-2005.adb}
30014 @item @file{file_queries-insert-95.adb}
30015 @end itemize
30016
30017 @noindent
30018 and the build script renames the appropriate file to
30019
30020 @smallexample
30021 file_queries-insert.adb
30022 @end smallexample
30023
30024 @noindent
30025 and then carries out the compilation.
30026
30027 This can also be done with project files' naming schemes. For example:
30028
30029 @smallexample @c project
30030 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30031 @end smallexample
30032
30033 @noindent
30034 Note also that with project files it is desirable to use a different extension
30035 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30036 conflict may arise through another commonly used feature: to declare as part
30037 of the project a set of directories containing all the sources obeying the
30038 default naming scheme.
30039
30040 The use of alternative units is certainly feasible in all situations,
30041 and for example the Ada part of the GNAT run-time is conditionalized
30042 based on the target architecture using this approach. As a specific example,
30043 consider the implementation of the AST feature in VMS. There is one
30044 spec:
30045
30046 @smallexample
30047 s-asthan.ads
30048 @end smallexample
30049
30050 @noindent
30051 which is the same for all architectures, and three bodies:
30052
30053 @table @file
30054 @item s-asthan.adb
30055 used for all non-VMS operating systems
30056 @item s-asthan-vms-alpha.adb
30057 used for VMS on the Alpha
30058 @item s-asthan-vms-ia64.adb
30059 used for VMS on the ia64
30060 @end table
30061
30062 @noindent
30063 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30064 this operating system feature is not available, and the two remaining
30065 versions interface with the corresponding versions of VMS to provide
30066 VMS-compatible AST handling. The GNAT build script knows the architecture
30067 and operating system, and automatically selects the right version,
30068 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30069
30070 Another style for arranging alternative implementations is through Ada's
30071 access-to-subprogram facility.
30072 In case some functionality is to be conditionally included,
30073 you can declare an access-to-procedure variable @code{Ref} that is initialized
30074 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30075 when appropriate.
30076 In some library package, set @code{Ref} to @code{Proc'Access} for some
30077 procedure @code{Proc} that performs the relevant processing.
30078 The initialization only occurs if the library package is included in the
30079 program.
30080 The same idea can also be implemented using tagged types and dispatching
30081 calls.
30082
30083
30084 @node Preprocessing
30085 @section Preprocessing
30086 @cindex Preprocessing
30087
30088 @noindent
30089 Although it is quite possible to conditionalize code without the use of
30090 C-style preprocessing, as described earlier in this section, it is
30091 nevertheless convenient in some cases to use the C approach. Moreover,
30092 older Ada compilers have often provided some preprocessing capability,
30093 so legacy code may depend on this approach, even though it is not
30094 standard.
30095
30096 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30097 extent on the various preprocessors that have been used
30098 with legacy code on other compilers, to enable easier transition).
30099
30100 The preprocessor may be used in two separate modes. It can be used quite
30101 separately from the compiler, to generate a separate output source file
30102 that is then fed to the compiler as a separate step. This is the
30103 @code{gnatprep} utility, whose use is fully described in
30104 @ref{Preprocessing Using gnatprep}.
30105 @cindex @code{gnatprep}
30106
30107 The preprocessing language allows such constructs as
30108
30109 @smallexample
30110 @group
30111 #if DEBUG or PRIORITY > 4 then
30112 bunch of declarations
30113 #else
30114 completely different bunch of declarations
30115 #end if;
30116 @end group
30117 @end smallexample
30118
30119 @noindent
30120 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30121 defined either on the command line or in a separate file.
30122
30123 The other way of running the preprocessor is even closer to the C style and
30124 often more convenient. In this approach the preprocessing is integrated into
30125 the compilation process. The compiler is fed the preprocessor input which
30126 includes @code{#if} lines etc, and then the compiler carries out the
30127 preprocessing internally and processes the resulting output.
30128 For more details on this approach, see @ref{Integrated Preprocessing}.
30129
30130
30131 @c *******************************
30132 @node Inline Assembler
30133 @appendix Inline Assembler
30134 @c *******************************
30135
30136 @noindent
30137 If you need to write low-level software that interacts directly
30138 with the hardware, Ada provides two ways to incorporate assembly
30139 language code into your program. First, you can import and invoke
30140 external routines written in assembly language, an Ada feature fully
30141 supported by GNAT@. However, for small sections of code it may be simpler
30142 or more efficient to include assembly language statements directly
30143 in your Ada source program, using the facilities of the implementation-defined
30144 package @code{System.Machine_Code}, which incorporates the gcc
30145 Inline Assembler. The Inline Assembler approach offers a number of advantages,
30146 including the following:
30147
30148 @itemize @bullet
30149 @item No need to use non-Ada tools
30150 @item Consistent interface over different targets
30151 @item Automatic usage of the proper calling conventions
30152 @item Access to Ada constants and variables
30153 @item Definition of intrinsic routines
30154 @item Possibility of inlining a subprogram comprising assembler code
30155 @item Code optimizer can take Inline Assembler code into account
30156 @end itemize
30157
30158 This chapter presents a series of examples to show you how to use
30159 the Inline Assembler. Although it focuses on the Intel x86,
30160 the general approach applies also to other processors.
30161 It is assumed that you are familiar with Ada
30162 and with assembly language programming.
30163
30164 @menu
30165 * Basic Assembler Syntax::
30166 * A Simple Example of Inline Assembler::
30167 * Output Variables in Inline Assembler::
30168 * Input Variables in Inline Assembler::
30169 * Inlining Inline Assembler Code::
30170 * Other Asm Functionality::
30171 @end menu
30172
30173 @c ---------------------------------------------------------------------------
30174 @node Basic Assembler Syntax
30175 @section Basic Assembler Syntax
30176
30177 @noindent
30178 The assembler used by GNAT and gcc is based not on the Intel assembly
30179 language, but rather on a language that descends from the AT&T Unix
30180 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30181 The following table summarizes the main features of @emph{as} syntax
30182 and points out the differences from the Intel conventions.
30183 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30184 pre-processor) documentation for further information.
30185
30186 @table @asis
30187 @item Register names
30188 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30189 @*
30190 Intel: No extra punctuation; for example @code{eax}
30191
30192 @item Immediate operand
30193 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30194 @*
30195 Intel: No extra punctuation; for example @code{4}
30196
30197 @item Address
30198 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30199 @*
30200 Intel: No extra punctuation; for example @code{loc}
30201
30202 @item Memory contents
30203 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30204 @*
30205 Intel: Square brackets; for example @code{[loc]}
30206
30207 @item Register contents
30208 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30209 @*
30210 Intel: Square brackets; for example @code{[eax]}
30211
30212 @item Hexadecimal numbers
30213 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30214 @*
30215 Intel: Trailing ``h''; for example @code{A0h}
30216
30217 @item Operand size
30218 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30219 a 16-bit word
30220 @*
30221 Intel: Implicit, deduced by assembler; for example @code{mov}
30222
30223 @item Instruction repetition
30224 gcc / @emph{as}: Split into two lines; for example
30225 @*
30226 @code{rep}
30227 @*
30228 @code{stosl}
30229 @*
30230 Intel: Keep on one line; for example @code{rep stosl}
30231
30232 @item Order of operands
30233 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30234 @*
30235 Intel: Destination first; for example @code{mov eax, 4}
30236 @end table
30237
30238 @c ---------------------------------------------------------------------------
30239 @node A Simple Example of Inline Assembler
30240 @section A Simple Example of Inline Assembler
30241
30242 @noindent
30243 The following example will generate a single assembly language statement,
30244 @code{nop}, which does nothing. Despite its lack of run-time effect,
30245 the example will be useful in illustrating the basics of
30246 the Inline Assembler facility.
30247
30248 @smallexample @c ada
30249 @group
30250 with System.Machine_Code; use System.Machine_Code;
30251 procedure Nothing is
30252 begin
30253 Asm ("nop");
30254 end Nothing;
30255 @end group
30256 @end smallexample
30257
30258 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30259 here it takes one parameter, a @emph{template string} that must be a static
30260 expression and that will form the generated instruction.
30261 @code{Asm} may be regarded as a compile-time procedure that parses
30262 the template string and additional parameters (none here),
30263 from which it generates a sequence of assembly language instructions.
30264
30265 The examples in this chapter will illustrate several of the forms
30266 for invoking @code{Asm}; a complete specification of the syntax
30267 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30268 Manual}.
30269
30270 Under the standard GNAT conventions, the @code{Nothing} procedure
30271 should be in a file named @file{nothing.adb}.
30272 You can build the executable in the usual way:
30273 @smallexample
30274 gnatmake nothing
30275 @end smallexample
30276 However, the interesting aspect of this example is not its run-time behavior
30277 but rather the generated assembly code.
30278 To see this output, invoke the compiler as follows:
30279 @smallexample
30280 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30281 @end smallexample
30282 where the options are:
30283
30284 @table @code
30285 @item -c
30286 compile only (no bind or link)
30287 @item -S
30288 generate assembler listing
30289 @item -fomit-frame-pointer
30290 do not set up separate stack frames
30291 @item -gnatp
30292 do not add runtime checks
30293 @end table
30294
30295 This gives a human-readable assembler version of the code. The resulting
30296 file will have the same name as the Ada source file, but with a @code{.s}
30297 extension. In our example, the file @file{nothing.s} has the following
30298 contents:
30299
30300 @smallexample
30301 @group
30302 .file "nothing.adb"
30303 gcc2_compiled.:
30304 ___gnu_compiled_ada:
30305 .text
30306 .align 4
30307 .globl __ada_nothing
30308 __ada_nothing:
30309 #APP
30310 nop
30311 #NO_APP
30312 jmp L1
30313 .align 2,0x90
30314 L1:
30315 ret
30316 @end group
30317 @end smallexample
30318
30319 The assembly code you included is clearly indicated by
30320 the compiler, between the @code{#APP} and @code{#NO_APP}
30321 delimiters. The character before the 'APP' and 'NOAPP'
30322 can differ on different targets. For example, GNU/Linux uses '#APP' while
30323 on NT you will see '/APP'.
30324
30325 If you make a mistake in your assembler code (such as using the
30326 wrong size modifier, or using a wrong operand for the instruction) GNAT
30327 will report this error in a temporary file, which will be deleted when
30328 the compilation is finished. Generating an assembler file will help
30329 in such cases, since you can assemble this file separately using the
30330 @emph{as} assembler that comes with gcc.
30331
30332 Assembling the file using the command
30333
30334 @smallexample
30335 as @file{nothing.s}
30336 @end smallexample
30337 @noindent
30338 will give you error messages whose lines correspond to the assembler
30339 input file, so you can easily find and correct any mistakes you made.
30340 If there are no errors, @emph{as} will generate an object file
30341 @file{nothing.out}.
30342
30343 @c ---------------------------------------------------------------------------
30344 @node Output Variables in Inline Assembler
30345 @section Output Variables in Inline Assembler
30346
30347 @noindent
30348 The examples in this section, showing how to access the processor flags,
30349 illustrate how to specify the destination operands for assembly language
30350 statements.
30351
30352 @smallexample @c ada
30353 @group
30354 with Interfaces; use Interfaces;
30355 with Ada.Text_IO; use Ada.Text_IO;
30356 with System.Machine_Code; use System.Machine_Code;
30357 procedure Get_Flags is
30358 Flags : Unsigned_32;
30359 use ASCII;
30360 begin
30361 Asm ("pushfl" & LF & HT & -- push flags on stack
30362 "popl %%eax" & LF & HT & -- load eax with flags
30363 "movl %%eax, %0", -- store flags in variable
30364 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30365 Put_Line ("Flags register:" & Flags'Img);
30366 end Get_Flags;
30367 @end group
30368 @end smallexample
30369
30370 In order to have a nicely aligned assembly listing, we have separated
30371 multiple assembler statements in the Asm template string with linefeed
30372 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30373 The resulting section of the assembly output file is:
30374
30375 @smallexample
30376 @group
30377 #APP
30378 pushfl
30379 popl %eax
30380 movl %eax, -40(%ebp)
30381 #NO_APP
30382 @end group
30383 @end smallexample
30384
30385 It would have been legal to write the Asm invocation as:
30386
30387 @smallexample
30388 Asm ("pushfl popl %%eax movl %%eax, %0")
30389 @end smallexample
30390
30391 but in the generated assembler file, this would come out as:
30392
30393 @smallexample
30394 #APP
30395 pushfl popl %eax movl %eax, -40(%ebp)
30396 #NO_APP
30397 @end smallexample
30398
30399 which is not so convenient for the human reader.
30400
30401 We use Ada comments
30402 at the end of each line to explain what the assembler instructions
30403 actually do. This is a useful convention.
30404
30405 When writing Inline Assembler instructions, you need to precede each register
30406 and variable name with a percent sign. Since the assembler already requires
30407 a percent sign at the beginning of a register name, you need two consecutive
30408 percent signs for such names in the Asm template string, thus @code{%%eax}.
30409 In the generated assembly code, one of the percent signs will be stripped off.
30410
30411 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30412 variables: operands you later define using @code{Input} or @code{Output}
30413 parameters to @code{Asm}.
30414 An output variable is illustrated in
30415 the third statement in the Asm template string:
30416 @smallexample
30417 movl %%eax, %0
30418 @end smallexample
30419 The intent is to store the contents of the eax register in a variable that can
30420 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
30421 necessarily work, since the compiler might optimize by using a register
30422 to hold Flags, and the expansion of the @code{movl} instruction would not be
30423 aware of this optimization. The solution is not to store the result directly
30424 but rather to advise the compiler to choose the correct operand form;
30425 that is the purpose of the @code{%0} output variable.
30426
30427 Information about the output variable is supplied in the @code{Outputs}
30428 parameter to @code{Asm}:
30429 @smallexample
30430 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30431 @end smallexample
30432
30433 The output is defined by the @code{Asm_Output} attribute of the target type;
30434 the general format is
30435 @smallexample
30436 Type'Asm_Output (constraint_string, variable_name)
30437 @end smallexample
30438
30439 The constraint string directs the compiler how
30440 to store/access the associated variable. In the example
30441 @smallexample
30442 Unsigned_32'Asm_Output ("=m", Flags);
30443 @end smallexample
30444 the @code{"m"} (memory) constraint tells the compiler that the variable
30445 @code{Flags} should be stored in a memory variable, thus preventing
30446 the optimizer from keeping it in a register. In contrast,
30447 @smallexample
30448 Unsigned_32'Asm_Output ("=r", Flags);
30449 @end smallexample
30450 uses the @code{"r"} (register) constraint, telling the compiler to
30451 store the variable in a register.
30452
30453 If the constraint is preceded by the equal character (@strong{=}), it tells
30454 the compiler that the variable will be used to store data into it.
30455
30456 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30457 allowing the optimizer to choose whatever it deems best.
30458
30459 There are a fairly large number of constraints, but the ones that are
30460 most useful (for the Intel x86 processor) are the following:
30461
30462 @table @code
30463 @item =
30464 output constraint
30465 @item g
30466 global (i.e.@: can be stored anywhere)
30467 @item m
30468 in memory
30469 @item I
30470 a constant
30471 @item a
30472 use eax
30473 @item b
30474 use ebx
30475 @item c
30476 use ecx
30477 @item d
30478 use edx
30479 @item S
30480 use esi
30481 @item D
30482 use edi
30483 @item r
30484 use one of eax, ebx, ecx or edx
30485 @item q
30486 use one of eax, ebx, ecx, edx, esi or edi
30487 @end table
30488
30489 The full set of constraints is described in the gcc and @emph{as}
30490 documentation; note that it is possible to combine certain constraints
30491 in one constraint string.
30492
30493 You specify the association of an output variable with an assembler operand
30494 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30495 integer. Thus in
30496 @smallexample @c ada
30497 @group
30498 Asm ("pushfl" & LF & HT & -- push flags on stack
30499 "popl %%eax" & LF & HT & -- load eax with flags
30500 "movl %%eax, %0", -- store flags in variable
30501 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30502 @end group
30503 @end smallexample
30504 @noindent
30505 @code{%0} will be replaced in the expanded code by the appropriate operand,
30506 whatever
30507 the compiler decided for the @code{Flags} variable.
30508
30509 In general, you may have any number of output variables:
30510 @itemize @bullet
30511 @item
30512 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30513 @item
30514 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30515 of @code{Asm_Output} attributes
30516 @end itemize
30517
30518 For example:
30519 @smallexample @c ada
30520 @group
30521 Asm ("movl %%eax, %0" & LF & HT &
30522 "movl %%ebx, %1" & LF & HT &
30523 "movl %%ecx, %2",
30524 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
30525 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
30526 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
30527 @end group
30528 @end smallexample
30529 @noindent
30530 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30531 in the Ada program.
30532
30533 As a variation on the @code{Get_Flags} example, we can use the constraints
30534 string to direct the compiler to store the eax register into the @code{Flags}
30535 variable, instead of including the store instruction explicitly in the
30536 @code{Asm} template string:
30537
30538 @smallexample @c ada
30539 @group
30540 with Interfaces; use Interfaces;
30541 with Ada.Text_IO; use Ada.Text_IO;
30542 with System.Machine_Code; use System.Machine_Code;
30543 procedure Get_Flags_2 is
30544 Flags : Unsigned_32;
30545 use ASCII;
30546 begin
30547 Asm ("pushfl" & LF & HT & -- push flags on stack
30548 "popl %%eax", -- save flags in eax
30549 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30550 Put_Line ("Flags register:" & Flags'Img);
30551 end Get_Flags_2;
30552 @end group
30553 @end smallexample
30554
30555 @noindent
30556 The @code{"a"} constraint tells the compiler that the @code{Flags}
30557 variable will come from the eax register. Here is the resulting code:
30558
30559 @smallexample
30560 @group
30561 #APP
30562 pushfl
30563 popl %eax
30564 #NO_APP
30565 movl %eax,-40(%ebp)
30566 @end group
30567 @end smallexample
30568
30569 @noindent
30570 The compiler generated the store of eax into Flags after
30571 expanding the assembler code.
30572
30573 Actually, there was no need to pop the flags into the eax register;
30574 more simply, we could just pop the flags directly into the program variable:
30575
30576 @smallexample @c ada
30577 @group
30578 with Interfaces; use Interfaces;
30579 with Ada.Text_IO; use Ada.Text_IO;
30580 with System.Machine_Code; use System.Machine_Code;
30581 procedure Get_Flags_3 is
30582 Flags : Unsigned_32;
30583 use ASCII;
30584 begin
30585 Asm ("pushfl" & LF & HT & -- push flags on stack
30586 "pop %0", -- save flags in Flags
30587 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30588 Put_Line ("Flags register:" & Flags'Img);
30589 end Get_Flags_3;
30590 @end group
30591 @end smallexample
30592
30593 @c ---------------------------------------------------------------------------
30594 @node Input Variables in Inline Assembler
30595 @section Input Variables in Inline Assembler
30596
30597 @noindent
30598 The example in this section illustrates how to specify the source operands
30599 for assembly language statements.
30600 The program simply increments its input value by 1:
30601
30602 @smallexample @c ada
30603 @group
30604 with Interfaces; use Interfaces;
30605 with Ada.Text_IO; use Ada.Text_IO;
30606 with System.Machine_Code; use System.Machine_Code;
30607 procedure Increment is
30608
30609 function Incr (Value : Unsigned_32) return Unsigned_32 is
30610 Result : Unsigned_32;
30611 begin
30612 Asm ("incl %0",
30613 Inputs => Unsigned_32'Asm_Input ("a", Value),
30614 Outputs => Unsigned_32'Asm_Output ("=a", Result));
30615 return Result;
30616 end Incr;
30617
30618 Value : Unsigned_32;
30619
30620 begin
30621 Value := 5;
30622 Put_Line ("Value before is" & Value'Img);
30623 Value := Incr (Value);
30624 Put_Line ("Value after is" & Value'Img);
30625 end Increment;
30626 @end group
30627 @end smallexample
30628
30629 The @code{Outputs} parameter to @code{Asm} specifies
30630 that the result will be in the eax register and that it is to be stored
30631 in the @code{Result} variable.
30632
30633 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30634 but with an @code{Asm_Input} attribute.
30635 The @code{"="} constraint, indicating an output value, is not present.
30636
30637 You can have multiple input variables, in the same way that you can have more
30638 than one output variable.
30639
30640 The parameter count (%0, %1) etc, now starts at the first input
30641 statement, and continues with the output statements.
30642 When both parameters use the same variable, the
30643 compiler will treat them as the same %n operand, which is the case here.
30644
30645 Just as the @code{Outputs} parameter causes the register to be stored into the
30646 target variable after execution of the assembler statements, so does the
30647 @code{Inputs} parameter cause its variable to be loaded into the register
30648 before execution of the assembler statements.
30649
30650 Thus the effect of the @code{Asm} invocation is:
30651 @enumerate
30652 @item load the 32-bit value of @code{Value} into eax
30653 @item execute the @code{incl %eax} instruction
30654 @item store the contents of eax into the @code{Result} variable
30655 @end enumerate
30656
30657 The resulting assembler file (with @option{-O2} optimization) contains:
30658 @smallexample
30659 @group
30660 _increment__incr.1:
30661 subl $4,%esp
30662 movl 8(%esp),%eax
30663 #APP
30664 incl %eax
30665 #NO_APP
30666 movl %eax,%edx
30667 movl %ecx,(%esp)
30668 addl $4,%esp
30669 ret
30670 @end group
30671 @end smallexample
30672
30673 @c ---------------------------------------------------------------------------
30674 @node Inlining Inline Assembler Code
30675 @section Inlining Inline Assembler Code
30676
30677 @noindent
30678 For a short subprogram such as the @code{Incr} function in the previous
30679 section, the overhead of the call and return (creating / deleting the stack
30680 frame) can be significant, compared to the amount of code in the subprogram
30681 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30682 which directs the compiler to expand invocations of the subprogram at the
30683 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30684 Here is the resulting program:
30685
30686 @smallexample @c ada
30687 @group
30688 with Interfaces; use Interfaces;
30689 with Ada.Text_IO; use Ada.Text_IO;
30690 with System.Machine_Code; use System.Machine_Code;
30691 procedure Increment_2 is
30692
30693 function Incr (Value : Unsigned_32) return Unsigned_32 is
30694 Result : Unsigned_32;
30695 begin
30696 Asm ("incl %0",
30697 Inputs => Unsigned_32'Asm_Input ("a", Value),
30698 Outputs => Unsigned_32'Asm_Output ("=a", Result));
30699 return Result;
30700 end Incr;
30701 pragma Inline (Increment);
30702
30703 Value : Unsigned_32;
30704
30705 begin
30706 Value := 5;
30707 Put_Line ("Value before is" & Value'Img);
30708 Value := Increment (Value);
30709 Put_Line ("Value after is" & Value'Img);
30710 end Increment_2;
30711 @end group
30712 @end smallexample
30713
30714 Compile the program with both optimization (@option{-O2}) and inlining
30715 (@option{-gnatn}) enabled.
30716
30717 The @code{Incr} function is still compiled as usual, but at the
30718 point in @code{Increment} where our function used to be called:
30719
30720 @smallexample
30721 @group
30722 pushl %edi
30723 call _increment__incr.1
30724 @end group
30725 @end smallexample
30726
30727 @noindent
30728 the code for the function body directly appears:
30729
30730 @smallexample
30731 @group
30732 movl %esi,%eax
30733 #APP
30734 incl %eax
30735 #NO_APP
30736 movl %eax,%edx
30737 @end group
30738 @end smallexample
30739
30740 @noindent
30741 thus saving the overhead of stack frame setup and an out-of-line call.
30742
30743 @c ---------------------------------------------------------------------------
30744 @node Other Asm Functionality
30745 @section Other @code{Asm} Functionality
30746
30747 @noindent
30748 This section describes two important parameters to the @code{Asm}
30749 procedure: @code{Clobber}, which identifies register usage;
30750 and @code{Volatile}, which inhibits unwanted optimizations.
30751
30752 @menu
30753 * The Clobber Parameter::
30754 * The Volatile Parameter::
30755 @end menu
30756
30757 @c ---------------------------------------------------------------------------
30758 @node The Clobber Parameter
30759 @subsection The @code{Clobber} Parameter
30760
30761 @noindent
30762 One of the dangers of intermixing assembly language and a compiled language
30763 such as Ada is that the compiler needs to be aware of which registers are
30764 being used by the assembly code. In some cases, such as the earlier examples,
30765 the constraint string is sufficient to indicate register usage (e.g.,
30766 @code{"a"} for
30767 the eax register). But more generally, the compiler needs an explicit
30768 identification of the registers that are used by the Inline Assembly
30769 statements.
30770
30771 Using a register that the compiler doesn't know about
30772 could be a side effect of an instruction (like @code{mull}
30773 storing its result in both eax and edx).
30774 It can also arise from explicit register usage in your
30775 assembly code; for example:
30776 @smallexample
30777 @group
30778 Asm ("movl %0, %%ebx" & LF & HT &
30779 "movl %%ebx, %1",
30780 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30781 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30782 @end group
30783 @end smallexample
30784 @noindent
30785 where the compiler (since it does not analyze the @code{Asm} template string)
30786 does not know you are using the ebx register.
30787
30788 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30789 to identify the registers that will be used by your assembly code:
30790
30791 @smallexample
30792 @group
30793 Asm ("movl %0, %%ebx" & LF & HT &
30794 "movl %%ebx, %1",
30795 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30796 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30797 Clobber => "ebx");
30798 @end group
30799 @end smallexample
30800
30801 The Clobber parameter is a static string expression specifying the
30802 register(s) you are using. Note that register names are @emph{not} prefixed
30803 by a percent sign. Also, if more than one register is used then their names
30804 are separated by commas; e.g., @code{"eax, ebx"}
30805
30806 The @code{Clobber} parameter has several additional uses:
30807 @enumerate
30808 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30809 @item Use ``register'' name @code{memory} if you changed a memory location
30810 @end enumerate
30811
30812 @c ---------------------------------------------------------------------------
30813 @node The Volatile Parameter
30814 @subsection The @code{Volatile} Parameter
30815 @cindex Volatile parameter
30816
30817 @noindent
30818 Compiler optimizations in the presence of Inline Assembler may sometimes have
30819 unwanted effects. For example, when an @code{Asm} invocation with an input
30820 variable is inside a loop, the compiler might move the loading of the input
30821 variable outside the loop, regarding it as a one-time initialization.
30822
30823 If this effect is not desired, you can disable such optimizations by setting
30824 the @code{Volatile} parameter to @code{True}; for example:
30825
30826 @smallexample @c ada
30827 @group
30828 Asm ("movl %0, %%ebx" & LF & HT &
30829 "movl %%ebx, %1",
30830 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30831 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30832 Clobber => "ebx",
30833 Volatile => True);
30834 @end group
30835 @end smallexample
30836
30837 By default, @code{Volatile} is set to @code{False} unless there is no
30838 @code{Outputs} parameter.
30839
30840 Although setting @code{Volatile} to @code{True} prevents unwanted
30841 optimizations, it will also disable other optimizations that might be
30842 important for efficiency. In general, you should set @code{Volatile}
30843 to @code{True} only if the compiler's optimizations have created
30844 problems.
30845 @c END OF INLINE ASSEMBLER CHAPTER
30846 @c ===============================
30847
30848 @c ***********************************
30849 @c * Compatibility and Porting Guide *
30850 @c ***********************************
30851 @node Compatibility and Porting Guide
30852 @appendix Compatibility and Porting Guide
30853
30854 @noindent
30855 This chapter describes the compatibility issues that may arise between
30856 GNAT and other Ada compilation systems (including those for Ada 83),
30857 and shows how GNAT can expedite porting
30858 applications developed in other Ada environments.
30859
30860 @menu
30861 * Compatibility with Ada 83::
30862 * Compatibility between Ada 95 and Ada 2005::
30863 * Implementation-dependent characteristics::
30864 * Compatibility with Other Ada Systems::
30865 * Representation Clauses::
30866 @ifclear vms
30867 @c Brief section is only in non-VMS version
30868 @c Full chapter is in VMS version
30869 * Compatibility with HP Ada 83::
30870 @end ifclear
30871 @ifset vms
30872 * Transitioning to 64-Bit GNAT for OpenVMS::
30873 @end ifset
30874 @end menu
30875
30876 @node Compatibility with Ada 83
30877 @section Compatibility with Ada 83
30878 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30879
30880 @noindent
30881 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
30882 particular, the design intention was that the difficulties associated
30883 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30884 that occur when moving from one Ada 83 system to another.
30885
30886 However, there are a number of points at which there are minor
30887 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
30888 full details of these issues,
30889 and should be consulted for a complete treatment.
30890 In practice the
30891 following subsections treat the most likely issues to be encountered.
30892
30893 @menu
30894 * Legal Ada 83 programs that are illegal in Ada 95::
30895 * More deterministic semantics::
30896 * Changed semantics::
30897 * Other language compatibility issues::
30898 @end menu
30899
30900 @node Legal Ada 83 programs that are illegal in Ada 95
30901 @subsection Legal Ada 83 programs that are illegal in Ada 95
30902
30903 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30904 Ada 95 and thus also in Ada 2005:
30905
30906 @table @emph
30907 @item Character literals
30908 Some uses of character literals are ambiguous. Since Ada 95 has introduced
30909 @code{Wide_Character} as a new predefined character type, some uses of
30910 character literals that were legal in Ada 83 are illegal in Ada 95.
30911 For example:
30912 @smallexample @c ada
30913 for Char in 'A' .. 'Z' loop @dots{} end loop;
30914 @end smallexample
30915
30916 @noindent
30917 The problem is that @code{'A'} and @code{'Z'} could be from either
30918 @code{Character} or @code{Wide_Character}. The simplest correction
30919 is to make the type explicit; e.g.:
30920 @smallexample @c ada
30921 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30922 @end smallexample
30923
30924 @item New reserved words
30925 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30926 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30927 Existing Ada 83 code using any of these identifiers must be edited to
30928 use some alternative name.
30929
30930 @item Freezing rules
30931 The rules in Ada 95 are slightly different with regard to the point at
30932 which entities are frozen, and representation pragmas and clauses are
30933 not permitted past the freeze point. This shows up most typically in
30934 the form of an error message complaining that a representation item
30935 appears too late, and the appropriate corrective action is to move
30936 the item nearer to the declaration of the entity to which it refers.
30937
30938 A particular case is that representation pragmas
30939 @ifset vms
30940 (including the
30941 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30942 @end ifset
30943 cannot be applied to a subprogram body. If necessary, a separate subprogram
30944 declaration must be introduced to which the pragma can be applied.
30945
30946 @item Optional bodies for library packages
30947 In Ada 83, a package that did not require a package body was nevertheless
30948 allowed to have one. This lead to certain surprises in compiling large
30949 systems (situations in which the body could be unexpectedly ignored by the
30950 binder). In Ada 95, if a package does not require a body then it is not
30951 permitted to have a body. To fix this problem, simply remove a redundant
30952 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30953 into the spec that makes the body required. One approach is to add a private
30954 part to the package declaration (if necessary), and define a parameterless
30955 procedure called @code{Requires_Body}, which must then be given a dummy
30956 procedure body in the package body, which then becomes required.
30957 Another approach (assuming that this does not introduce elaboration
30958 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30959 since one effect of this pragma is to require the presence of a package body.
30960
30961 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30962 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30963 @code{Constraint_Error}.
30964 This means that it is illegal to have separate exception handlers for
30965 the two exceptions. The fix is simply to remove the handler for the
30966 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30967 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30968
30969 @item Indefinite subtypes in generics
30970 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30971 as the actual for a generic formal private type, but then the instantiation
30972 would be illegal if there were any instances of declarations of variables
30973 of this type in the generic body. In Ada 95, to avoid this clear violation
30974 of the methodological principle known as the ``contract model'',
30975 the generic declaration explicitly indicates whether
30976 or not such instantiations are permitted. If a generic formal parameter
30977 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30978 type name, then it can be instantiated with indefinite types, but no
30979 stand-alone variables can be declared of this type. Any attempt to declare
30980 such a variable will result in an illegality at the time the generic is
30981 declared. If the @code{(<>)} notation is not used, then it is illegal
30982 to instantiate the generic with an indefinite type.
30983 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30984 It will show up as a compile time error, and
30985 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30986 @end table
30987
30988 @node More deterministic semantics
30989 @subsection More deterministic semantics
30990
30991 @table @emph
30992 @item Conversions
30993 Conversions from real types to integer types round away from 0. In Ada 83
30994 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
30995 implementation freedom was intended to support unbiased rounding in
30996 statistical applications, but in practice it interfered with portability.
30997 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30998 is required. Numeric code may be affected by this change in semantics.
30999 Note, though, that this issue is no worse than already existed in Ada 83
31000 when porting code from one vendor to another.
31001
31002 @item Tasking
31003 The Real-Time Annex introduces a set of policies that define the behavior of
31004 features that were implementation dependent in Ada 83, such as the order in
31005 which open select branches are executed.
31006 @end table
31007
31008 @node Changed semantics
31009 @subsection Changed semantics
31010
31011 @noindent
31012 The worst kind of incompatibility is one where a program that is legal in
31013 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31014 possible in Ada 83. Fortunately this is extremely rare, but the one
31015 situation that you should be alert to is the change in the predefined type
31016 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31017
31018 @table @emph
31019 @item Range of type @code{Character}
31020 The range of @code{Standard.Character} is now the full 256 characters
31021 of Latin-1, whereas in most Ada 83 implementations it was restricted
31022 to 128 characters. Although some of the effects of
31023 this change will be manifest in compile-time rejection of legal
31024 Ada 83 programs it is possible for a working Ada 83 program to have
31025 a different effect in Ada 95, one that was not permitted in Ada 83.
31026 As an example, the expression
31027 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31028 delivers @code{255} as its value.
31029 In general, you should look at the logic of any
31030 character-processing Ada 83 program and see whether it needs to be adapted
31031 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
31032 character handling package that may be relevant if code needs to be adapted
31033 to account for the additional Latin-1 elements.
31034 The desirable fix is to
31035 modify the program to accommodate the full character set, but in some cases
31036 it may be convenient to define a subtype or derived type of Character that
31037 covers only the restricted range.
31038 @cindex Latin-1
31039 @end table
31040
31041 @node Other language compatibility issues
31042 @subsection Other language compatibility issues
31043
31044 @table @emph
31045 @item @option{-gnat83} switch
31046 All implementations of GNAT provide a switch that causes GNAT to operate
31047 in Ada 83 mode. In this mode, some but not all compatibility problems
31048 of the type described above are handled automatically. For example, the
31049 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31050 as identifiers as in Ada 83.
31051 However,
31052 in practice, it is usually advisable to make the necessary modifications
31053 to the program to remove the need for using this switch.
31054 See @ref{Compiling Different Versions of Ada}.
31055
31056 @item Support for removed Ada 83 pragmas and attributes
31057 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31058 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
31059 compilers are allowed, but not required, to implement these missing
31060 elements. In contrast with some other compilers, GNAT implements all
31061 such pragmas and attributes, eliminating this compatibility concern. These
31062 include @code{pragma Interface} and the floating point type attributes
31063 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31064 @end table
31065
31066
31067 @node Compatibility between Ada 95 and Ada 2005
31068 @section Compatibility between Ada 95 and Ada 2005
31069 @cindex Compatibility between Ada 95 and Ada 2005
31070
31071 @noindent
31072 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31073 a number of incompatibilities. Several are enumerated below;
31074 for a complete description please see the
31075 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31076 @cite{Rationale for Ada 2005}.
31077
31078 @table @emph
31079 @item New reserved words.
31080 The words @code{interface}, @code{overriding} and @code{synchronized} are
31081 reserved in Ada 2005.
31082 A pre-Ada 2005 program that uses any of these as an identifier will be
31083 illegal.
31084
31085 @item New declarations in predefined packages.
31086 A number of packages in the predefined environment contain new declarations:
31087 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31088 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31089 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31090 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31091 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31092 If an Ada 95 program does a @code{with} and @code{use} of any of these
31093 packages, the new declarations may cause name clashes.
31094
31095 @item Access parameters.
31096 A nondispatching subprogram with an access parameter cannot be renamed
31097 as a dispatching operation. This was permitted in Ada 95.
31098
31099 @item Access types, discriminants, and constraints.
31100 Rule changes in this area have led to some incompatibilities; for example,
31101 constrained subtypes of some access types are not permitted in Ada 2005.
31102
31103 @item Aggregates for limited types.
31104 The allowance of aggregates for limited types in Ada 2005 raises the
31105 possibility of ambiguities in legal Ada 95 programs, since additional types
31106 now need to be considered in expression resolution.
31107
31108 @item Fixed-point multiplication and division.
31109 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31110 were legal in Ada 95 and invoked the predefined versions of these operations,
31111 are now ambiguous.
31112 The ambiguity may be resolved either by applying a type conversion to the
31113 expression, or by explicitly invoking the operation from package
31114 @code{Standard}.
31115
31116 @item Return-by-reference types.
31117 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
31118 can declare a function returning a value from an anonymous access type.
31119 @end table
31120
31121
31122 @node Implementation-dependent characteristics
31123 @section Implementation-dependent characteristics
31124 @noindent
31125 Although the Ada language defines the semantics of each construct as
31126 precisely as practical, in some situations (for example for reasons of
31127 efficiency, or where the effect is heavily dependent on the host or target
31128 platform) the implementation is allowed some freedom. In porting Ada 83
31129 code to GNAT, you need to be aware of whether / how the existing code
31130 exercised such implementation dependencies. Such characteristics fall into
31131 several categories, and GNAT offers specific support in assisting the
31132 transition from certain Ada 83 compilers.
31133
31134 @menu
31135 * Implementation-defined pragmas::
31136 * Implementation-defined attributes::
31137 * Libraries::
31138 * Elaboration order::
31139 * Target-specific aspects::
31140 @end menu
31141
31142 @node Implementation-defined pragmas
31143 @subsection Implementation-defined pragmas
31144
31145 @noindent
31146 Ada compilers are allowed to supplement the language-defined pragmas, and
31147 these are a potential source of non-portability. All GNAT-defined pragmas
31148 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31149 Reference Manual}, and these include several that are specifically
31150 intended to correspond to other vendors' Ada 83 pragmas.
31151 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31152 For compatibility with HP Ada 83, GNAT supplies the pragmas
31153 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31154 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31155 and @code{Volatile}.
31156 Other relevant pragmas include @code{External} and @code{Link_With}.
31157 Some vendor-specific
31158 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31159 recognized, thus
31160 avoiding compiler rejection of units that contain such pragmas; they are not
31161 relevant in a GNAT context and hence are not otherwise implemented.
31162
31163 @node Implementation-defined attributes
31164 @subsection Implementation-defined attributes
31165
31166 Analogous to pragmas, the set of attributes may be extended by an
31167 implementation. All GNAT-defined attributes are described in
31168 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31169 Manual}, and these include several that are specifically intended
31170 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
31171 the attribute @code{VADS_Size} may be useful. For compatibility with HP
31172 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31173 @code{Type_Class}.
31174
31175 @node Libraries
31176 @subsection Libraries
31177 @noindent
31178 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
31179 code uses vendor-specific libraries then there are several ways to manage
31180 this in Ada 95 or Ada 2005:
31181 @enumerate
31182 @item
31183 If the source code for the libraries (specs and bodies) are
31184 available, then the libraries can be migrated in the same way as the
31185 application.
31186 @item
31187 If the source code for the specs but not the bodies are
31188 available, then you can reimplement the bodies.
31189 @item
31190 Some features introduced by Ada 95 obviate the need for library support. For
31191 example most Ada 83 vendors supplied a package for unsigned integers. The
31192 Ada 95 modular type feature is the preferred way to handle this need, so
31193 instead of migrating or reimplementing the unsigned integer package it may
31194 be preferable to retrofit the application using modular types.
31195 @end enumerate
31196
31197 @node Elaboration order
31198 @subsection Elaboration order
31199 @noindent
31200 The implementation can choose any elaboration order consistent with the unit
31201 dependency relationship. This freedom means that some orders can result in
31202 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31203 to invoke a subprogram its body has been elaborated, or to instantiate a
31204 generic before the generic body has been elaborated. By default GNAT
31205 attempts to choose a safe order (one that will not encounter access before
31206 elaboration problems) by implicitly inserting @code{Elaborate} or
31207 @code{Elaborate_All} pragmas where
31208 needed. However, this can lead to the creation of elaboration circularities
31209 and a resulting rejection of the program by gnatbind. This issue is
31210 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31211 In brief, there are several
31212 ways to deal with this situation:
31213
31214 @itemize @bullet
31215 @item
31216 Modify the program to eliminate the circularities, e.g.@: by moving
31217 elaboration-time code into explicitly-invoked procedures
31218 @item
31219 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31220 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31221 @code{Elaborate_All}
31222 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31223 (by selectively suppressing elaboration checks via pragma
31224 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31225 @end itemize
31226
31227 @node Target-specific aspects
31228 @subsection Target-specific aspects
31229 @noindent
31230 Low-level applications need to deal with machine addresses, data
31231 representations, interfacing with assembler code, and similar issues. If
31232 such an Ada 83 application is being ported to different target hardware (for
31233 example where the byte endianness has changed) then you will need to
31234 carefully examine the program logic; the porting effort will heavily depend
31235 on the robustness of the original design. Moreover, Ada 95 (and thus
31236 Ada 2005) are sometimes
31237 incompatible with typical Ada 83 compiler practices regarding implicit
31238 packing, the meaning of the Size attribute, and the size of access values.
31239 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31240
31241 @node Compatibility with Other Ada Systems
31242 @section Compatibility with Other Ada Systems
31243
31244 @noindent
31245 If programs avoid the use of implementation dependent and
31246 implementation defined features, as documented in the @cite{Ada
31247 Reference Manual}, there should be a high degree of portability between
31248 GNAT and other Ada systems. The following are specific items which
31249 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31250 compilers, but do not affect porting code to GNAT@.
31251 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31252 the following issues may or may not arise for Ada 2005 programs
31253 when other compilers appear.)
31254
31255 @table @emph
31256 @item Ada 83 Pragmas and Attributes
31257 Ada 95 compilers are allowed, but not required, to implement the missing
31258 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31259 GNAT implements all such pragmas and attributes, eliminating this as
31260 a compatibility concern, but some other Ada 95 compilers reject these
31261 pragmas and attributes.
31262
31263 @item Specialized Needs Annexes
31264 GNAT implements the full set of special needs annexes. At the
31265 current time, it is the only Ada 95 compiler to do so. This means that
31266 programs making use of these features may not be portable to other Ada
31267 95 compilation systems.
31268
31269 @item Representation Clauses
31270 Some other Ada 95 compilers implement only the minimal set of
31271 representation clauses required by the Ada 95 reference manual. GNAT goes
31272 far beyond this minimal set, as described in the next section.
31273 @end table
31274
31275 @node Representation Clauses
31276 @section Representation Clauses
31277
31278 @noindent
31279 The Ada 83 reference manual was quite vague in describing both the minimal
31280 required implementation of representation clauses, and also their precise
31281 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
31282 minimal set of capabilities required is still quite limited.
31283
31284 GNAT implements the full required set of capabilities in
31285 Ada 95 and Ada 2005, but also goes much further, and in particular
31286 an effort has been made to be compatible with existing Ada 83 usage to the
31287 greatest extent possible.
31288
31289 A few cases exist in which Ada 83 compiler behavior is incompatible with
31290 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
31291 intentional or accidental dependence on specific implementation dependent
31292 characteristics of these Ada 83 compilers. The following is a list of
31293 the cases most likely to arise in existing Ada 83 code.
31294
31295 @table @emph
31296 @item Implicit Packing
31297 Some Ada 83 compilers allowed a Size specification to cause implicit
31298 packing of an array or record. This could cause expensive implicit
31299 conversions for change of representation in the presence of derived
31300 types, and the Ada design intends to avoid this possibility.
31301 Subsequent AI's were issued to make it clear that such implicit
31302 change of representation in response to a Size clause is inadvisable,
31303 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31304 Reference Manuals as implementation advice that is followed by GNAT@.
31305 The problem will show up as an error
31306 message rejecting the size clause. The fix is simply to provide
31307 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31308 a Component_Size clause.
31309
31310 @item Meaning of Size Attribute
31311 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31312 the minimal number of bits required to hold values of the type. For example,
31313 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31314 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
31315 some 32 in this situation. This problem will usually show up as a compile
31316 time error, but not always. It is a good idea to check all uses of the
31317 'Size attribute when porting Ada 83 code. The GNAT specific attribute
31318 Object_Size can provide a useful way of duplicating the behavior of
31319 some Ada 83 compiler systems.
31320
31321 @item Size of Access Types
31322 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31323 and that therefore it will be the same size as a System.Address value. This
31324 assumption is true for GNAT in most cases with one exception. For the case of
31325 a pointer to an unconstrained array type (where the bounds may vary from one
31326 value of the access type to another), the default is to use a ``fat pointer'',
31327 which is represented as two separate pointers, one to the bounds, and one to
31328 the array. This representation has a number of advantages, including improved
31329 efficiency. However, it may cause some difficulties in porting existing Ada 83
31330 code which makes the assumption that, for example, pointers fit in 32 bits on
31331 a machine with 32-bit addressing.
31332
31333 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31334 access types in this case (where the designated type is an unconstrained array
31335 type). These thin pointers are indeed the same size as a System.Address value.
31336 To specify a thin pointer, use a size clause for the type, for example:
31337
31338 @smallexample @c ada
31339 type X is access all String;
31340 for X'Size use Standard'Address_Size;
31341 @end smallexample
31342
31343 @noindent
31344 which will cause the type X to be represented using a single pointer.
31345 When using this representation, the bounds are right behind the array.
31346 This representation is slightly less efficient, and does not allow quite
31347 such flexibility in the use of foreign pointers or in using the
31348 Unrestricted_Access attribute to create pointers to non-aliased objects.
31349 But for any standard portable use of the access type it will work in
31350 a functionally correct manner and allow porting of existing code.
31351 Note that another way of forcing a thin pointer representation
31352 is to use a component size clause for the element size in an array,
31353 or a record representation clause for an access field in a record.
31354 @end table
31355
31356 @ifclear vms
31357 @c This brief section is only in the non-VMS version
31358 @c The complete chapter on HP Ada is in the VMS version
31359 @node Compatibility with HP Ada 83
31360 @section Compatibility with HP Ada 83
31361
31362 @noindent
31363 The VMS version of GNAT fully implements all the pragmas and attributes
31364 provided by HP Ada 83, as well as providing the standard HP Ada 83
31365 libraries, including Starlet. In addition, data layouts and parameter
31366 passing conventions are highly compatible. This means that porting
31367 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31368 most other porting efforts. The following are some of the most
31369 significant differences between GNAT and HP Ada 83.
31370
31371 @table @emph
31372 @item Default floating-point representation
31373 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31374 it is VMS format. GNAT does implement the necessary pragmas
31375 (Long_Float, Float_Representation) for changing this default.
31376
31377 @item System
31378 The package System in GNAT exactly corresponds to the definition in the
31379 Ada 95 reference manual, which means that it excludes many of the
31380 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
31381 that contains the additional definitions, and a special pragma,
31382 Extend_System allows this package to be treated transparently as an
31383 extension of package System.
31384
31385 @item To_Address
31386 The definitions provided by Aux_DEC are exactly compatible with those
31387 in the HP Ada 83 version of System, with one exception.
31388 HP Ada provides the following declarations:
31389
31390 @smallexample @c ada
31391 TO_ADDRESS (INTEGER)
31392 TO_ADDRESS (UNSIGNED_LONGWORD)
31393 TO_ADDRESS (@i{universal_integer})
31394 @end smallexample
31395
31396 @noindent
31397 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31398 an extension to Ada 83 not strictly compatible with the reference manual.
31399 In GNAT, we are constrained to be exactly compatible with the standard,
31400 and this means we cannot provide this capability. In HP Ada 83, the
31401 point of this definition is to deal with a call like:
31402
31403 @smallexample @c ada
31404 TO_ADDRESS (16#12777#);
31405 @end smallexample
31406
31407 @noindent
31408 Normally, according to the Ada 83 standard, one would expect this to be
31409 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31410 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
31411 definition using @i{universal_integer} takes precedence.
31412
31413 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31414 is not possible to be 100% compatible. Since there are many programs using
31415 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31416 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31417 declarations provided in the GNAT version of AUX_Dec are:
31418
31419 @smallexample @c ada
31420 function To_Address (X : Integer) return Address;
31421 pragma Pure_Function (To_Address);
31422
31423 function To_Address_Long (X : Unsigned_Longword)
31424 return Address;
31425 pragma Pure_Function (To_Address_Long);
31426 @end smallexample
31427
31428 @noindent
31429 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31430 change the name to TO_ADDRESS_LONG@.
31431
31432 @item Task_Id values
31433 The Task_Id values assigned will be different in the two systems, and GNAT
31434 does not provide a specified value for the Task_Id of the environment task,
31435 which in GNAT is treated like any other declared task.
31436 @end table
31437
31438 @noindent
31439 For full details on these and other less significant compatibility issues,
31440 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31441 Overview and Comparison on HP Platforms}.
31442
31443 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31444 attributes are recognized, although only a subset of them can sensibly
31445 be implemented. The description of pragmas in @ref{Implementation
31446 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31447 indicates whether or not they are applicable to non-VMS systems.
31448 @end ifclear
31449
31450 @ifset vms
31451 @node Transitioning to 64-Bit GNAT for OpenVMS
31452 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31453
31454 @noindent
31455 This section is meant to assist users of pre-2006 @value{EDITION}
31456 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31457 the version of the GNAT technology supplied in 2006 and later for
31458 OpenVMS on both Alpha and I64.
31459
31460 @menu
31461 * Introduction to transitioning::
31462 * Migration of 32 bit code::
31463 * Taking advantage of 64 bit addressing::
31464 * Technical details::
31465 @end menu
31466
31467 @node Introduction to transitioning
31468 @subsection Introduction
31469
31470 @noindent
31471 64-bit @value{EDITION} for Open VMS has been designed to meet
31472 three main goals:
31473
31474 @enumerate
31475 @item
31476 Providing a full conforming implementation of Ada 95 and Ada 2005
31477
31478 @item
31479 Allowing maximum backward compatibility, thus easing migration of existing
31480 Ada source code
31481
31482 @item
31483 Supplying a path for exploiting the full 64-bit address range
31484 @end enumerate
31485
31486 @noindent
31487 Ada's strong typing semantics has made it
31488 impractical to have different 32-bit and 64-bit modes. As soon as
31489 one object could possibly be outside the 32-bit address space, this
31490 would make it necessary for the @code{System.Address} type to be 64 bits.
31491 In particular, this would cause inconsistencies if 32-bit code is
31492 called from 64-bit code that raises an exception.
31493
31494 This issue has been resolved by always using 64-bit addressing
31495 at the system level, but allowing for automatic conversions between
31496 32-bit and 64-bit addresses where required. Thus users who
31497 do not currently require 64-bit addressing capabilities, can
31498 recompile their code with only minimal changes (and indeed
31499 if the code is written in portable Ada, with no assumptions about
31500 the size of the @code{Address} type, then no changes at all are necessary).
31501 At the same time,
31502 this approach provides a simple, gradual upgrade path to future
31503 use of larger memories than available for 32-bit systems.
31504 Also, newly written applications or libraries will by default
31505 be fully compatible with future systems exploiting 64-bit
31506 addressing capabilities.
31507
31508 @ref{Migration of 32 bit code}, will focus on porting applications
31509 that do not require more than 2 GB of
31510 addressable memory. This code will be referred to as
31511 @emph{32-bit code}.
31512 For applications intending to exploit the full 64-bit address space,
31513 @ref{Taking advantage of 64 bit addressing},
31514 will consider further changes that may be required.
31515 Such code will be referred to below as @emph{64-bit code}.
31516
31517 @node Migration of 32 bit code
31518 @subsection Migration of 32-bit code
31519
31520 @menu
31521 * Address types::
31522 * Access types::
31523 * Unchecked conversions::
31524 * Predefined constants::
31525 * Interfacing with C::
31526 * Experience with source compatibility::
31527 @end menu
31528
31529 @node Address types
31530 @subsubsection Address types
31531
31532 @noindent
31533 To solve the problem of mixing 64-bit and 32-bit addressing,
31534 while maintaining maximum backward compatibility, the following
31535 approach has been taken:
31536
31537 @itemize @bullet
31538 @item
31539 @code{System.Address} always has a size of 64 bits
31540
31541 @item
31542 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31543 @end itemize
31544
31545 @noindent
31546 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31547 a @code{Short_Address}
31548 may be used where an @code{Address} is required, and vice versa, without
31549 needing explicit type conversions.
31550 By virtue of the Open VMS parameter passing conventions,
31551 even imported
31552 and exported subprograms that have 32-bit address parameters are
31553 compatible with those that have 64-bit address parameters.
31554 (See @ref{Making code 64 bit clean} for details.)
31555
31556 The areas that may need attention are those where record types have
31557 been defined that contain components of the type @code{System.Address}, and
31558 where objects of this type are passed to code expecting a record layout with
31559 32-bit addresses.
31560
31561 Different compilers on different platforms cannot be
31562 expected to represent the same type in the same way,
31563 since alignment constraints
31564 and other system-dependent properties affect the compiler's decision.
31565 For that reason, Ada code
31566 generally uses representation clauses to specify the expected
31567 layout where required.
31568
31569 If such a representation clause uses 32 bits for a component having
31570 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31571 will detect that error and produce a specific diagnostic message.
31572 The developer should then determine whether the representation
31573 should be 64 bits or not and make either of two changes:
31574 change the size to 64 bits and leave the type as @code{System.Address}, or
31575 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31576 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31577 required in any code setting or accessing the field; the compiler will
31578 automatically perform any needed conversions between address
31579 formats.
31580
31581 @node Access types
31582 @subsubsection Access types
31583
31584 @noindent
31585 By default, objects designated by access values are always
31586 allocated in the 32-bit
31587 address space. Thus legacy code will never contain
31588 any objects that are not addressable with 32-bit addresses, and
31589 the compiler will never raise exceptions as result of mixing
31590 32-bit and 64-bit addresses.
31591
31592 However, the access values themselves are represented in 64 bits, for optimum
31593 performance and future compatibility with 64-bit code. As was
31594 the case with @code{System.Address}, the compiler will give an error message
31595 if an object or record component has a representation clause that
31596 requires the access value to fit in 32 bits. In such a situation,
31597 an explicit size clause for the access type, specifying 32 bits,
31598 will have the desired effect.
31599
31600 General access types (declared with @code{access all}) can never be
31601 32 bits, as values of such types must be able to refer to any object
31602 of the designated type,
31603 including objects residing outside the 32-bit address range.
31604 Existing Ada 83 code will not contain such type definitions,
31605 however, since general access types were introduced in Ada 95.
31606
31607 @node Unchecked conversions
31608 @subsubsection Unchecked conversions
31609
31610 @noindent
31611 In the case of an @code{Unchecked_Conversion} where the source type is a
31612 64-bit access type or the type @code{System.Address}, and the target
31613 type is a 32-bit type, the compiler will generate a warning.
31614 Even though the generated code will still perform the required
31615 conversions, it is highly recommended in these cases to use
31616 respectively a 32-bit access type or @code{System.Short_Address}
31617 as the source type.
31618
31619 @node Predefined constants
31620 @subsubsection Predefined constants
31621
31622 @noindent
31623 The following table shows the correspondence between pre-2006 versions of
31624 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31625 (``New''):
31626
31627 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31628 @item @b{Constant} @tab @b{Old} @tab @b{New}
31629 @item @code{System.Word_Size} @tab 32 @tab 64
31630 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
31631 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
31632 @item @code{System.Address_Size} @tab 32 @tab 64
31633 @end multitable
31634
31635 @noindent
31636 If you need to refer to the specific
31637 memory size of a 32-bit implementation, instead of the
31638 actual memory size, use @code{System.Short_Memory_Size}
31639 rather than @code{System.Memory_Size}.
31640 Similarly, references to @code{System.Address_Size} may need
31641 to be replaced by @code{System.Short_Address'Size}.
31642 The program @command{gnatfind} may be useful for locating
31643 references to the above constants, so that you can verify that they
31644 are still correct.
31645
31646 @node Interfacing with C
31647 @subsubsection Interfacing with C
31648
31649 @noindent
31650 In order to minimize the impact of the transition to 64-bit addresses on
31651 legacy programs, some fundamental types in the @code{Interfaces.C}
31652 package hierarchy continue to be represented in 32 bits.
31653 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31654 This eases integration with the default HP C layout choices, for example
31655 as found in the system routines in @code{DECC$SHR.EXE}.
31656 Because of this implementation choice, the type fully compatible with
31657 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31658 Depending on the context the compiler will issue a
31659 warning or an error when type @code{Address} is used, alerting the user to a
31660 potential problem. Otherwise 32-bit programs that use
31661 @code{Interfaces.C} should normally not require code modifications
31662
31663 The other issue arising with C interfacing concerns pragma @code{Convention}.
31664 For VMS 64-bit systems, there is an issue of the appropriate default size
31665 of C convention pointers in the absence of an explicit size clause. The HP
31666 C compiler can choose either 32 or 64 bits depending on compiler options.
31667 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31668 clause is given. This proves a better choice for porting 32-bit legacy
31669 applications. In order to have a 64-bit representation, it is necessary to
31670 specify a size representation clause. For example:
31671
31672 @smallexample @c ada
31673 type int_star is access Interfaces.C.int;
31674 pragma Convention(C, int_star);
31675 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
31676 @end smallexample
31677
31678 @node Experience with source compatibility
31679 @subsubsection Experience with source compatibility
31680
31681 @noindent
31682 The Security Server and STARLET on I64 provide an interesting ``test case''
31683 for source compatibility issues, since it is in such system code
31684 where assumptions about @code{Address} size might be expected to occur.
31685 Indeed, there were a small number of occasions in the Security Server
31686 file @file{jibdef.ads}
31687 where a representation clause for a record type specified
31688 32 bits for a component of type @code{Address}.
31689 All of these errors were detected by the compiler.
31690 The repair was obvious and immediate; to simply replace @code{Address} by
31691 @code{Short_Address}.
31692
31693 In the case of STARLET, there were several record types that should
31694 have had representation clauses but did not. In these record types
31695 there was an implicit assumption that an @code{Address} value occupied
31696 32 bits.
31697 These compiled without error, but their usage resulted in run-time error
31698 returns from STARLET system calls.
31699 Future GNAT technology enhancements may include a tool that detects and flags
31700 these sorts of potential source code porting problems.
31701
31702 @c ****************************************
31703 @node Taking advantage of 64 bit addressing
31704 @subsection Taking advantage of 64-bit addressing
31705
31706 @menu
31707 * Making code 64 bit clean::
31708 * Allocating memory from the 64 bit storage pool::
31709 * Restrictions on use of 64 bit objects::
31710 * Using 64 bit storage pools by default::
31711 * General access types::
31712 * STARLET and other predefined libraries::
31713 @end menu
31714
31715 @node Making code 64 bit clean
31716 @subsubsection Making code 64-bit clean
31717
31718 @noindent
31719 In order to prevent problems that may occur when (parts of) a
31720 system start using memory outside the 32-bit address range,
31721 we recommend some additional guidelines:
31722
31723 @itemize @bullet
31724 @item
31725 For imported subprograms that take parameters of the
31726 type @code{System.Address}, ensure that these subprograms can
31727 indeed handle 64-bit addresses. If not, or when in doubt,
31728 change the subprogram declaration to specify
31729 @code{System.Short_Address} instead.
31730
31731 @item
31732 Resolve all warnings related to size mismatches in
31733 unchecked conversions. Failing to do so causes
31734 erroneous execution if the source object is outside
31735 the 32-bit address space.
31736
31737 @item
31738 (optional) Explicitly use the 32-bit storage pool
31739 for access types used in a 32-bit context, or use
31740 generic access types where possible
31741 (@pxref{Restrictions on use of 64 bit objects}).
31742 @end itemize
31743
31744 @noindent
31745 If these rules are followed, the compiler will automatically insert
31746 any necessary checks to ensure that no addresses or access values
31747 passed to 32-bit code ever refer to objects outside the 32-bit
31748 address range.
31749 Any attempt to do this will raise @code{Constraint_Error}.
31750
31751 @node Allocating memory from the 64 bit storage pool
31752 @subsubsection Allocating memory from the 64-bit storage pool
31753
31754 @noindent
31755 For any access type @code{T} that potentially requires memory allocations
31756 beyond the 32-bit address space,
31757 use the following representation clause:
31758
31759 @smallexample @c ada
31760 for T'Storage_Pool use System.Pool_64;
31761 @end smallexample
31762
31763 @node Restrictions on use of 64 bit objects
31764 @subsubsection Restrictions on use of 64-bit objects
31765
31766 @noindent
31767 Taking the address of an object allocated from a 64-bit storage pool,
31768 and then passing this address to a subprogram expecting
31769 @code{System.Short_Address},
31770 or assigning it to a variable of type @code{Short_Address}, will cause
31771 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31772 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31773 no exception is raised and execution
31774 will become erroneous.
31775
31776 @node Using 64 bit storage pools by default
31777 @subsubsection Using 64-bit storage pools by default
31778
31779 @noindent
31780 In some cases it may be desirable to have the compiler allocate
31781 from 64-bit storage pools by default. This may be the case for
31782 libraries that are 64-bit clean, but may be used in both 32-bit
31783 and 64-bit contexts. For these cases the following configuration
31784 pragma may be specified:
31785
31786 @smallexample @c ada
31787 pragma Pool_64_Default;
31788 @end smallexample
31789
31790 @noindent
31791 Any code compiled in the context of this pragma will by default
31792 use the @code{System.Pool_64} storage pool. This default may be overridden
31793 for a specific access type @code{T} by the representation clause:
31794
31795 @smallexample @c ada
31796 for T'Storage_Pool use System.Pool_32;
31797 @end smallexample
31798
31799 @noindent
31800 Any object whose address may be passed to a subprogram with a
31801 @code{Short_Address} argument, or assigned to a variable of type
31802 @code{Short_Address}, needs to be allocated from this pool.
31803
31804 @node General access types
31805 @subsubsection General access types
31806
31807 @noindent
31808 Objects designated by access values from a
31809 general access type (declared with @code{access all}) are never allocated
31810 from a 64-bit storage pool. Code that uses general access types will
31811 accept objects allocated in either 32-bit or 64-bit address spaces,
31812 but never allocate objects outside the 32-bit address space.
31813 Using general access types ensures maximum compatibility with both
31814 32-bit and 64-bit code.
31815
31816 @node STARLET and other predefined libraries
31817 @subsubsection STARLET and other predefined libraries
31818
31819 @noindent
31820 All code that comes as part of GNAT is 64-bit clean, but the
31821 restrictions given in @ref{Restrictions on use of 64 bit objects},
31822 still apply. Look at the package
31823 specs to see in which contexts objects allocated
31824 in 64-bit address space are acceptable.
31825
31826 @node Technical details
31827 @subsection Technical details
31828
31829 @noindent
31830 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31831 Ada standard with respect to the type of @code{System.Address}. Previous
31832 versions of GNAT Pro have defined this type as private and implemented it as a
31833 modular type.
31834
31835 In order to allow defining @code{System.Short_Address} as a proper subtype,
31836 and to match the implicit sign extension in parameter passing,
31837 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31838 visible (i.e., non-private) integer type.
31839 Standard operations on the type, such as the binary operators ``+'', ``-'',
31840 etc., that take @code{Address} operands and return an @code{Address} result,
31841 have been hidden by declaring these
31842 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31843 ambiguities that would otherwise result from overloading.
31844 (Note that, although @code{Address} is a visible integer type,
31845 good programming practice dictates against exploiting the type's
31846 integer properties such as literals, since this will compromise
31847 code portability.)
31848
31849 Defining @code{Address} as a visible integer type helps achieve
31850 maximum compatibility for existing Ada code,
31851 without sacrificing the capabilities of the 64-bit architecture.
31852 @end ifset
31853
31854 @c ************************************************
31855 @ifset unw
31856 @node Microsoft Windows Topics
31857 @appendix Microsoft Windows Topics
31858 @cindex Windows NT
31859 @cindex Windows 95
31860 @cindex Windows 98
31861
31862 @noindent
31863 This chapter describes topics that are specific to the Microsoft Windows
31864 platforms (NT, 2000, and XP Professional).
31865
31866 @menu
31867 * Using GNAT on Windows::
31868 * Using a network installation of GNAT::
31869 * CONSOLE and WINDOWS subsystems::
31870 * Temporary Files::
31871 * Mixed-Language Programming on Windows::
31872 * Windows Calling Conventions::
31873 * Introduction to Dynamic Link Libraries (DLLs)::
31874 * Using DLLs with GNAT::
31875 * Building DLLs with GNAT::
31876 * Building DLLs with GNAT Project files::
31877 * Building DLLs with gnatdll::
31878 * GNAT and Windows Resources::
31879 * Debugging a DLL::
31880 * Setting Stack Size from gnatlink::
31881 * Setting Heap Size from gnatlink::
31882 @end menu
31883
31884 @node Using GNAT on Windows
31885 @section Using GNAT on Windows
31886
31887 @noindent
31888 One of the strengths of the GNAT technology is that its tool set
31889 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31890 @code{gdb} debugger, etc.) is used in the same way regardless of the
31891 platform.
31892
31893 On Windows this tool set is complemented by a number of Microsoft-specific
31894 tools that have been provided to facilitate interoperability with Windows
31895 when this is required. With these tools:
31896
31897 @itemize @bullet
31898
31899 @item
31900 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31901 subsystems.
31902
31903 @item
31904 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31905 relocatable and non-relocatable DLLs are supported).
31906
31907 @item
31908 You can build Ada DLLs for use in other applications. These applications
31909 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31910 relocatable and non-relocatable Ada DLLs are supported.
31911
31912 @item
31913 You can include Windows resources in your Ada application.
31914
31915 @item
31916 You can use or create COM/DCOM objects.
31917 @end itemize
31918
31919 @noindent
31920 Immediately below are listed all known general GNAT-for-Windows restrictions.
31921 Other restrictions about specific features like Windows Resources and DLLs
31922 are listed in separate sections below.
31923
31924 @itemize @bullet
31925
31926 @item
31927 It is not possible to use @code{GetLastError} and @code{SetLastError}
31928 when tasking, protected records, or exceptions are used. In these
31929 cases, in order to implement Ada semantics, the GNAT run-time system
31930 calls certain Win32 routines that set the last error variable to 0 upon
31931 success. It should be possible to use @code{GetLastError} and
31932 @code{SetLastError} when tasking, protected record, and exception
31933 features are not used, but it is not guaranteed to work.
31934
31935 @item
31936 It is not possible to link against Microsoft libraries except for
31937 import libraries. The library must be built to be compatible with
31938 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31939 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31940 not be compatible with the GNAT runtime. Even if the library is
31941 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31942
31943 @item
31944 When the compilation environment is located on FAT32 drives, users may
31945 experience recompilations of the source files that have not changed if
31946 Daylight Saving Time (DST) state has changed since the last time files
31947 were compiled. NTFS drives do not have this problem.
31948
31949 @item
31950 No components of the GNAT toolset use any entries in the Windows
31951 registry. The only entries that can be created are file associations and
31952 PATH settings, provided the user has chosen to create them at installation
31953 time, as well as some minimal book-keeping information needed to correctly
31954 uninstall or integrate different GNAT products.
31955 @end itemize
31956
31957 @node Using a network installation of GNAT
31958 @section Using a network installation of GNAT
31959
31960 @noindent
31961 Make sure the system on which GNAT is installed is accessible from the
31962 current machine, i.e., the install location is shared over the network.
31963 Shared resources are accessed on Windows by means of UNC paths, which
31964 have the format @code{\\server\sharename\path}
31965
31966 In order to use such a network installation, simply add the UNC path of the
31967 @file{bin} directory of your GNAT installation in front of your PATH. For
31968 example, if GNAT is installed in @file{\GNAT} directory of a share location
31969 called @file{c-drive} on a machine @file{LOKI}, the following command will
31970 make it available:
31971
31972 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31973
31974 Be aware that every compilation using the network installation results in the
31975 transfer of large amounts of data across the network and will likely cause
31976 serious performance penalty.
31977
31978 @node CONSOLE and WINDOWS subsystems
31979 @section CONSOLE and WINDOWS subsystems
31980 @cindex CONSOLE Subsystem
31981 @cindex WINDOWS Subsystem
31982 @cindex -mwindows
31983
31984 @noindent
31985 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31986 (which is the default subsystem) will always create a console when
31987 launching the application. This is not something desirable when the
31988 application has a Windows GUI. To get rid of this console the
31989 application must be using the @code{WINDOWS} subsystem. To do so
31990 the @option{-mwindows} linker option must be specified.
31991
31992 @smallexample
31993 $ gnatmake winprog -largs -mwindows
31994 @end smallexample
31995
31996 @node Temporary Files
31997 @section Temporary Files
31998 @cindex Temporary files
31999
32000 @noindent
32001 It is possible to control where temporary files gets created by setting
32002 the @env{TMP} environment variable. The file will be created:
32003
32004 @itemize
32005 @item Under the directory pointed to by the @env{TMP} environment variable if
32006 this directory exists.
32007
32008 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32009 set (or not pointing to a directory) and if this directory exists.
32010
32011 @item Under the current working directory otherwise.
32012 @end itemize
32013
32014 @noindent
32015 This allows you to determine exactly where the temporary
32016 file will be created. This is particularly useful in networked
32017 environments where you may not have write access to some
32018 directories.
32019
32020 @node Mixed-Language Programming on Windows
32021 @section Mixed-Language Programming on Windows
32022
32023 @noindent
32024 Developing pure Ada applications on Windows is no different than on
32025 other GNAT-supported platforms. However, when developing or porting an
32026 application that contains a mix of Ada and C/C++, the choice of your
32027 Windows C/C++ development environment conditions your overall
32028 interoperability strategy.
32029
32030 If you use @command{gcc} to compile the non-Ada part of your application,
32031 there are no Windows-specific restrictions that affect the overall
32032 interoperability with your Ada code. If you plan to use
32033 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32034 the following limitations:
32035
32036 @itemize @bullet
32037 @item
32038 You cannot link your Ada code with an object or library generated with
32039 Microsoft tools if these use the @code{.tls} section (Thread Local
32040 Storage section) since the GNAT linker does not yet support this section.
32041
32042 @item
32043 You cannot link your Ada code with an object or library generated with
32044 Microsoft tools if these use I/O routines other than those provided in
32045 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32046 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32047 libraries can cause a conflict with @code{msvcrt.dll} services. For
32048 instance Visual C++ I/O stream routines conflict with those in
32049 @code{msvcrt.dll}.
32050 @end itemize
32051
32052 @noindent
32053 If you do want to use the Microsoft tools for your non-Ada code and hit one
32054 of the above limitations, you have two choices:
32055
32056 @enumerate
32057 @item
32058 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32059 application. In this case, use the Microsoft or whatever environment to
32060 build the DLL and use GNAT to build your executable
32061 (@pxref{Using DLLs with GNAT}).
32062
32063 @item
32064 Or you can encapsulate your Ada code in a DLL to be linked with the
32065 other part of your application. In this case, use GNAT to build the DLL
32066 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32067 environment to build your executable.
32068 @end enumerate
32069
32070 @node Windows Calling Conventions
32071 @section Windows Calling Conventions
32072 @findex Stdcall
32073 @findex APIENTRY
32074
32075 @menu
32076 * C Calling Convention::
32077 * Stdcall Calling Convention::
32078 * Win32 Calling Convention::
32079 * DLL Calling Convention::
32080 @end menu
32081
32082 @noindent
32083 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32084 (callee), there are several ways to push @code{G}'s parameters on the
32085 stack and there are several possible scenarios to clean up the stack
32086 upon @code{G}'s return. A calling convention is an agreed upon software
32087 protocol whereby the responsibilities between the caller (@code{F}) and
32088 the callee (@code{G}) are clearly defined. Several calling conventions
32089 are available for Windows:
32090
32091 @itemize @bullet
32092 @item
32093 @code{C} (Microsoft defined)
32094
32095 @item
32096 @code{Stdcall} (Microsoft defined)
32097
32098 @item
32099 @code{Win32} (GNAT specific)
32100
32101 @item
32102 @code{DLL} (GNAT specific)
32103 @end itemize
32104
32105 @node C Calling Convention
32106 @subsection @code{C} Calling Convention
32107
32108 @noindent
32109 This is the default calling convention used when interfacing to C/C++
32110 routines compiled with either @command{gcc} or Microsoft Visual C++.
32111
32112 In the @code{C} calling convention subprogram parameters are pushed on the
32113 stack by the caller from right to left. The caller itself is in charge of
32114 cleaning up the stack after the call. In addition, the name of a routine
32115 with @code{C} calling convention is mangled by adding a leading underscore.
32116
32117 The name to use on the Ada side when importing (or exporting) a routine
32118 with @code{C} calling convention is the name of the routine. For
32119 instance the C function:
32120
32121 @smallexample
32122 int get_val (long);
32123 @end smallexample
32124
32125 @noindent
32126 should be imported from Ada as follows:
32127
32128 @smallexample @c ada
32129 @group
32130 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32131 pragma Import (C, Get_Val, External_Name => "get_val");
32132 @end group
32133 @end smallexample
32134
32135 @noindent
32136 Note that in this particular case the @code{External_Name} parameter could
32137 have been omitted since, when missing, this parameter is taken to be the
32138 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32139 is missing, as in the above example, this parameter is set to be the
32140 @code{External_Name} with a leading underscore.
32141
32142 When importing a variable defined in C, you should always use the @code{C}
32143 calling convention unless the object containing the variable is part of a
32144 DLL (in which case you should use the @code{Stdcall} calling
32145 convention, @pxref{Stdcall Calling Convention}).
32146
32147 @node Stdcall Calling Convention
32148 @subsection @code{Stdcall} Calling Convention
32149
32150 @noindent
32151 This convention, which was the calling convention used for Pascal
32152 programs, is used by Microsoft for all the routines in the Win32 API for
32153 efficiency reasons. It must be used to import any routine for which this
32154 convention was specified.
32155
32156 In the @code{Stdcall} calling convention subprogram parameters are pushed
32157 on the stack by the caller from right to left. The callee (and not the
32158 caller) is in charge of cleaning the stack on routine exit. In addition,
32159 the name of a routine with @code{Stdcall} calling convention is mangled by
32160 adding a leading underscore (as for the @code{C} calling convention) and a
32161 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32162 bytes) of the parameters passed to the routine.
32163
32164 The name to use on the Ada side when importing a C routine with a
32165 @code{Stdcall} calling convention is the name of the C routine. The leading
32166 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32167 the compiler. For instance the Win32 function:
32168
32169 @smallexample
32170 @b{APIENTRY} int get_val (long);
32171 @end smallexample
32172
32173 @noindent
32174 should be imported from Ada as follows:
32175
32176 @smallexample @c ada
32177 @group
32178 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32179 pragma Import (Stdcall, Get_Val);
32180 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32181 @end group
32182 @end smallexample
32183
32184 @noindent
32185 As for the @code{C} calling convention, when the @code{External_Name}
32186 parameter is missing, it is taken to be the name of the Ada entity in lower
32187 case. If instead of writing the above import pragma you write:
32188
32189 @smallexample @c ada
32190 @group
32191 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32192 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32193 @end group
32194 @end smallexample
32195
32196 @noindent
32197 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32198 of specifying the @code{External_Name} parameter you specify the
32199 @code{Link_Name} as in the following example:
32200
32201 @smallexample @c ada
32202 @group
32203 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32204 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32205 @end group
32206 @end smallexample
32207
32208 @noindent
32209 then the imported routine is @code{retrieve_val}, that is, there is no
32210 decoration at all. No leading underscore and no Stdcall suffix
32211 @code{@@}@code{@var{nn}}.
32212
32213 @noindent
32214 This is especially important as in some special cases a DLL's entry
32215 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32216 name generated for a call has it.
32217
32218 @noindent
32219 It is also possible to import variables defined in a DLL by using an
32220 import pragma for a variable. As an example, if a DLL contains a
32221 variable defined as:
32222
32223 @smallexample
32224 int my_var;
32225 @end smallexample
32226
32227 @noindent
32228 then, to access this variable from Ada you should write:
32229
32230 @smallexample @c ada
32231 @group
32232 My_Var : Interfaces.C.int;
32233 pragma Import (Stdcall, My_Var);
32234 @end group
32235 @end smallexample
32236
32237 @noindent
32238 Note that to ease building cross-platform bindings this convention
32239 will be handled as a @code{C} calling convention on non-Windows platforms.
32240
32241 @node Win32 Calling Convention
32242 @subsection @code{Win32} Calling Convention
32243
32244 @noindent
32245 This convention, which is GNAT-specific is fully equivalent to the
32246 @code{Stdcall} calling convention described above.
32247
32248 @node DLL Calling Convention
32249 @subsection @code{DLL} Calling Convention
32250
32251 @noindent
32252 This convention, which is GNAT-specific is fully equivalent to the
32253 @code{Stdcall} calling convention described above.
32254
32255 @node Introduction to Dynamic Link Libraries (DLLs)
32256 @section Introduction to Dynamic Link Libraries (DLLs)
32257 @findex DLL
32258
32259 @noindent
32260 A Dynamically Linked Library (DLL) is a library that can be shared by
32261 several applications running under Windows. A DLL can contain any number of
32262 routines and variables.
32263
32264 One advantage of DLLs is that you can change and enhance them without
32265 forcing all the applications that depend on them to be relinked or
32266 recompiled. However, you should be aware than all calls to DLL routines are
32267 slower since, as you will understand below, such calls are indirect.
32268
32269 To illustrate the remainder of this section, suppose that an application
32270 wants to use the services of a DLL @file{API.dll}. To use the services
32271 provided by @file{API.dll} you must statically link against the DLL or
32272 an import library which contains a jump table with an entry for each
32273 routine and variable exported by the DLL. In the Microsoft world this
32274 import library is called @file{API.lib}. When using GNAT this import
32275 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32276 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32277
32278 After you have linked your application with the DLL or the import library
32279 and you run your application, here is what happens:
32280
32281 @enumerate
32282 @item
32283 Your application is loaded into memory.
32284
32285 @item
32286 The DLL @file{API.dll} is mapped into the address space of your
32287 application. This means that:
32288
32289 @itemize @bullet
32290 @item
32291 The DLL will use the stack of the calling thread.
32292
32293 @item
32294 The DLL will use the virtual address space of the calling process.
32295
32296 @item
32297 The DLL will allocate memory from the virtual address space of the calling
32298 process.
32299
32300 @item
32301 Handles (pointers) can be safely exchanged between routines in the DLL
32302 routines and routines in the application using the DLL.
32303 @end itemize
32304
32305 @item
32306 The entries in the jump table (from the import library @file{libAPI.dll.a}
32307 or @file{API.lib} or automatically created when linking against a DLL)
32308 which is part of your application are initialized with the addresses
32309 of the routines and variables in @file{API.dll}.
32310
32311 @item
32312 If present in @file{API.dll}, routines @code{DllMain} or
32313 @code{DllMainCRTStartup} are invoked. These routines typically contain
32314 the initialization code needed for the well-being of the routines and
32315 variables exported by the DLL.
32316 @end enumerate
32317
32318 @noindent
32319 There is an additional point which is worth mentioning. In the Windows
32320 world there are two kind of DLLs: relocatable and non-relocatable
32321 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32322 in the target application address space. If the addresses of two
32323 non-relocatable DLLs overlap and these happen to be used by the same
32324 application, a conflict will occur and the application will run
32325 incorrectly. Hence, when possible, it is always preferable to use and
32326 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32327 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32328 User's Guide) removes the debugging symbols from the DLL but the DLL can
32329 still be relocated.
32330
32331 As a side note, an interesting difference between Microsoft DLLs and
32332 Unix shared libraries, is the fact that on most Unix systems all public
32333 routines are exported by default in a Unix shared library, while under
32334 Windows it is possible (but not required) to list exported routines in
32335 a definition file (@pxref{The Definition File}).
32336
32337 @node Using DLLs with GNAT
32338 @section Using DLLs with GNAT
32339
32340 @menu
32341 * Creating an Ada Spec for the DLL Services::
32342 * Creating an Import Library::
32343 @end menu
32344
32345 @noindent
32346 To use the services of a DLL, say @file{API.dll}, in your Ada application
32347 you must have:
32348
32349 @enumerate
32350 @item
32351 The Ada spec for the routines and/or variables you want to access in
32352 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32353 header files provided with the DLL.
32354
32355 @item
32356 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32357 mentioned an import library is a statically linked library containing the
32358 import table which will be filled at load time to point to the actual
32359 @file{API.dll} routines. Sometimes you don't have an import library for the
32360 DLL you want to use. The following sections will explain how to build
32361 one. Note that this is optional.
32362
32363 @item
32364 The actual DLL, @file{API.dll}.
32365 @end enumerate
32366
32367 @noindent
32368 Once you have all the above, to compile an Ada application that uses the
32369 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32370 you simply issue the command
32371
32372 @smallexample
32373 $ gnatmake my_ada_app -largs -lAPI
32374 @end smallexample
32375
32376 @noindent
32377 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32378 tells the GNAT linker to look first for a library named @file{API.lib}
32379 (Microsoft-style name) and if not found for a libraries named
32380 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32381 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32382 contains the following pragma
32383
32384 @smallexample @c ada
32385 pragma Linker_Options ("-lAPI");
32386 @end smallexample
32387
32388 @noindent
32389 you do not have to add @option{-largs -lAPI} at the end of the
32390 @command{gnatmake} command.
32391
32392 If any one of the items above is missing you will have to create it
32393 yourself. The following sections explain how to do so using as an
32394 example a fictitious DLL called @file{API.dll}.
32395
32396 @node Creating an Ada Spec for the DLL Services
32397 @subsection Creating an Ada Spec for the DLL Services
32398
32399 @noindent
32400 A DLL typically comes with a C/C++ header file which provides the
32401 definitions of the routines and variables exported by the DLL. The Ada
32402 equivalent of this header file is a package spec that contains definitions
32403 for the imported entities. If the DLL you intend to use does not come with
32404 an Ada spec you have to generate one such spec yourself. For example if
32405 the header file of @file{API.dll} is a file @file{api.h} containing the
32406 following two definitions:
32407
32408 @smallexample
32409 @group
32410 @cartouche
32411 int some_var;
32412 int get (char *);
32413 @end cartouche
32414 @end group
32415 @end smallexample
32416
32417 @noindent
32418 then the equivalent Ada spec could be:
32419
32420 @smallexample @c ada
32421 @group
32422 @cartouche
32423 with Interfaces.C.Strings;
32424 package API is
32425 use Interfaces;
32426
32427 Some_Var : C.int;
32428 function Get (Str : C.Strings.Chars_Ptr) return C.int;
32429
32430 private
32431 pragma Import (C, Get);
32432 pragma Import (DLL, Some_Var);
32433 end API;
32434 @end cartouche
32435 @end group
32436 @end smallexample
32437
32438 @noindent
32439 Note that a variable is
32440 @strong{always imported with a Stdcall convention}. A function
32441 can have @code{C} or @code{Stdcall} convention.
32442 (@pxref{Windows Calling Conventions}).
32443
32444 @node Creating an Import Library
32445 @subsection Creating an Import Library
32446 @cindex Import library
32447
32448 @menu
32449 * The Definition File::
32450 * GNAT-Style Import Library::
32451 * Microsoft-Style Import Library::
32452 @end menu
32453
32454 @noindent
32455 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32456 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32457 with @file{API.dll} you can skip this section. You can also skip this
32458 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32459 as in this case it is possible to link directly against the
32460 DLL. Otherwise read on.
32461
32462 @node The Definition File
32463 @subsubsection The Definition File
32464 @cindex Definition file
32465 @findex .def
32466
32467 @noindent
32468 As previously mentioned, and unlike Unix systems, the list of symbols
32469 that are exported from a DLL must be provided explicitly in Windows.
32470 The main goal of a definition file is precisely that: list the symbols
32471 exported by a DLL. A definition file (usually a file with a @code{.def}
32472 suffix) has the following structure:
32473
32474 @smallexample
32475 @group
32476 @cartouche
32477 @r{[}LIBRARY @var{name}@r{]}
32478 @r{[}DESCRIPTION @var{string}@r{]}
32479 EXPORTS
32480 @var{symbol1}
32481 @var{symbol2}
32482 @dots{}
32483 @end cartouche
32484 @end group
32485 @end smallexample
32486
32487 @table @code
32488 @item LIBRARY @var{name}
32489 This section, which is optional, gives the name of the DLL.
32490
32491 @item DESCRIPTION @var{string}
32492 This section, which is optional, gives a description string that will be
32493 embedded in the import library.
32494
32495 @item EXPORTS
32496 This section gives the list of exported symbols (procedures, functions or
32497 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32498 section of @file{API.def} looks like:
32499
32500 @smallexample
32501 @group
32502 @cartouche
32503 EXPORTS
32504 some_var
32505 get
32506 @end cartouche
32507 @end group
32508 @end smallexample
32509 @end table
32510
32511 @noindent
32512 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32513 (@pxref{Windows Calling Conventions}) for a Stdcall
32514 calling convention function in the exported symbols list.
32515
32516 @noindent
32517 There can actually be other sections in a definition file, but these
32518 sections are not relevant to the discussion at hand.
32519
32520 @node GNAT-Style Import Library
32521 @subsubsection GNAT-Style Import Library
32522
32523 @noindent
32524 To create a static import library from @file{API.dll} with the GNAT tools
32525 you should proceed as follows:
32526
32527 @enumerate
32528 @item
32529 Create the definition file @file{API.def} (@pxref{The Definition File}).
32530 For that use the @code{dll2def} tool as follows:
32531
32532 @smallexample
32533 $ dll2def API.dll > API.def
32534 @end smallexample
32535
32536 @noindent
32537 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32538 to standard output the list of entry points in the DLL. Note that if
32539 some routines in the DLL have the @code{Stdcall} convention
32540 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32541 suffix then you'll have to edit @file{api.def} to add it, and specify
32542 @option{-k} to @command{gnatdll} when creating the import library.
32543
32544 @noindent
32545 Here are some hints to find the right @code{@@}@var{nn} suffix.
32546
32547 @enumerate
32548 @item
32549 If you have the Microsoft import library (.lib), it is possible to get
32550 the right symbols by using Microsoft @code{dumpbin} tool (see the
32551 corresponding Microsoft documentation for further details).
32552
32553 @smallexample
32554 $ dumpbin /exports api.lib
32555 @end smallexample
32556
32557 @item
32558 If you have a message about a missing symbol at link time the compiler
32559 tells you what symbol is expected. You just have to go back to the
32560 definition file and add the right suffix.
32561 @end enumerate
32562
32563 @item
32564 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32565 (@pxref{Using gnatdll}) as follows:
32566
32567 @smallexample
32568 $ gnatdll -e API.def -d API.dll
32569 @end smallexample
32570
32571 @noindent
32572 @code{gnatdll} takes as input a definition file @file{API.def} and the
32573 name of the DLL containing the services listed in the definition file
32574 @file{API.dll}. The name of the static import library generated is
32575 computed from the name of the definition file as follows: if the
32576 definition file name is @var{xyz}@code{.def}, the import library name will
32577 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32578 @option{-e} could have been removed because the name of the definition
32579 file (before the ``@code{.def}'' suffix) is the same as the name of the
32580 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32581 @end enumerate
32582
32583 @node Microsoft-Style Import Library
32584 @subsubsection Microsoft-Style Import Library
32585
32586 @noindent
32587 With GNAT you can either use a GNAT-style or Microsoft-style import
32588 library. A Microsoft import library is needed only if you plan to make an
32589 Ada DLL available to applications developed with Microsoft
32590 tools (@pxref{Mixed-Language Programming on Windows}).
32591
32592 To create a Microsoft-style import library for @file{API.dll} you
32593 should proceed as follows:
32594
32595 @enumerate
32596 @item
32597 Create the definition file @file{API.def} from the DLL. For this use either
32598 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32599 tool (see the corresponding Microsoft documentation for further details).
32600
32601 @item
32602 Build the actual import library using Microsoft's @code{lib} utility:
32603
32604 @smallexample
32605 $ lib -machine:IX86 -def:API.def -out:API.lib
32606 @end smallexample
32607
32608 @noindent
32609 If you use the above command the definition file @file{API.def} must
32610 contain a line giving the name of the DLL:
32611
32612 @smallexample
32613 LIBRARY "API"
32614 @end smallexample
32615
32616 @noindent
32617 See the Microsoft documentation for further details about the usage of
32618 @code{lib}.
32619 @end enumerate
32620
32621 @node Building DLLs with GNAT
32622 @section Building DLLs with GNAT
32623 @cindex DLLs, building
32624
32625 @noindent
32626 This section explain how to build DLLs using the GNAT built-in DLL
32627 support. With the following procedure it is straight forward to build
32628 and use DLLs with GNAT.
32629
32630 @enumerate
32631
32632 @item building object files
32633
32634 The first step is to build all objects files that are to be included
32635 into the DLL. This is done by using the standard @command{gnatmake} tool.
32636
32637 @item building the DLL
32638
32639 To build the DLL you must use @command{gcc}'s @option{-shared}
32640 option. It is quite simple to use this method:
32641
32642 @smallexample
32643 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32644 @end smallexample
32645
32646 It is important to note that in this case all symbols found in the
32647 object files are automatically exported. It is possible to restrict
32648 the set of symbols to export by passing to @command{gcc} a definition
32649 file, @pxref{The Definition File}. For example:
32650
32651 @smallexample
32652 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32653 @end smallexample
32654
32655 If you use a definition file you must export the elaboration procedures
32656 for every package that required one. Elaboration procedures are named
32657 using the package name followed by "_E".
32658
32659 @item preparing DLL to be used
32660
32661 For the DLL to be used by client programs the bodies must be hidden
32662 from it and the .ali set with read-only attribute. This is very important
32663 otherwise GNAT will recompile all packages and will not actually use
32664 the code in the DLL. For example:
32665
32666 @smallexample
32667 $ mkdir apilib
32668 $ copy *.ads *.ali api.dll apilib
32669 $ attrib +R apilib\*.ali
32670 @end smallexample
32671
32672 @end enumerate
32673
32674 At this point it is possible to use the DLL by directly linking
32675 against it. Note that you must use the GNAT shared runtime when using
32676 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32677 option.
32678
32679 @smallexample
32680 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32681 @end smallexample
32682
32683 @node Building DLLs with GNAT Project files
32684 @section Building DLLs with GNAT Project files
32685 @cindex DLLs, building
32686
32687 @noindent
32688 There is nothing specific to Windows in the build process.
32689 @pxref{Library Projects}.
32690
32691 @noindent
32692 Due to a system limitation, it is not possible under Windows to create threads
32693 when inside the @code{DllMain} routine which is used for auto-initialization
32694 of shared libraries, so it is not possible to have library level tasks in SALs.
32695
32696 @node Building DLLs with gnatdll
32697 @section Building DLLs with gnatdll
32698 @cindex DLLs, building
32699
32700 @menu
32701 * Limitations When Using Ada DLLs from Ada::
32702 * Exporting Ada Entities::
32703 * Ada DLLs and Elaboration::
32704 * Ada DLLs and Finalization::
32705 * Creating a Spec for Ada DLLs::
32706 * Creating the Definition File::
32707 * Using gnatdll::
32708 @end menu
32709
32710 @noindent
32711 Note that it is preferred to use the built-in GNAT DLL support
32712 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32713 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32714
32715 This section explains how to build DLLs containing Ada code using
32716 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32717 remainder of this section.
32718
32719 The steps required to build an Ada DLL that is to be used by Ada as well as
32720 non-Ada applications are as follows:
32721
32722 @enumerate
32723 @item
32724 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32725 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32726 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32727 skip this step if you plan to use the Ada DLL only from Ada applications.
32728
32729 @item
32730 Your Ada code must export an initialization routine which calls the routine
32731 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32732 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32733 routine exported by the Ada DLL must be invoked by the clients of the DLL
32734 to initialize the DLL.
32735
32736 @item
32737 When useful, the DLL should also export a finalization routine which calls
32738 routine @code{adafinal} generated by @command{gnatbind} to perform the
32739 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32740 The finalization routine exported by the Ada DLL must be invoked by the
32741 clients of the DLL when the DLL services are no further needed.
32742
32743 @item
32744 You must provide a spec for the services exported by the Ada DLL in each
32745 of the programming languages to which you plan to make the DLL available.
32746
32747 @item
32748 You must provide a definition file listing the exported entities
32749 (@pxref{The Definition File}).
32750
32751 @item
32752 Finally you must use @code{gnatdll} to produce the DLL and the import
32753 library (@pxref{Using gnatdll}).
32754 @end enumerate
32755
32756 @noindent
32757 Note that a relocatable DLL stripped using the @code{strip}
32758 binutils tool will not be relocatable anymore. To build a DLL without
32759 debug information pass @code{-largs -s} to @code{gnatdll}. This
32760 restriction does not apply to a DLL built using a Library Project.
32761 @pxref{Library Projects}.
32762
32763 @node Limitations When Using Ada DLLs from Ada
32764 @subsection Limitations When Using Ada DLLs from Ada
32765
32766 @noindent
32767 When using Ada DLLs from Ada applications there is a limitation users
32768 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32769 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32770 each Ada DLL includes the services of the GNAT run time that are necessary
32771 to the Ada code inside the DLL. As a result, when an Ada program uses an
32772 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32773 one in the main program.
32774
32775 It is therefore not possible to exchange GNAT run-time objects between the
32776 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32777 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32778 types, etc.
32779
32780 It is completely safe to exchange plain elementary, array or record types,
32781 Windows object handles, etc.
32782
32783 @node Exporting Ada Entities
32784 @subsection Exporting Ada Entities
32785 @cindex Export table
32786
32787 @noindent
32788 Building a DLL is a way to encapsulate a set of services usable from any
32789 application. As a result, the Ada entities exported by a DLL should be
32790 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32791 any Ada name mangling. As an example here is an Ada package
32792 @code{API}, spec and body, exporting two procedures, a function, and a
32793 variable:
32794
32795 @smallexample @c ada
32796 @group
32797 @cartouche
32798 with Interfaces.C; use Interfaces;
32799 package API is
32800 Count : C.int := 0;
32801 function Factorial (Val : C.int) return C.int;
32802
32803 procedure Initialize_API;
32804 procedure Finalize_API;
32805 -- Initialization & Finalization routines. More in the next section.
32806 private
32807 pragma Export (C, Initialize_API);
32808 pragma Export (C, Finalize_API);
32809 pragma Export (C, Count);
32810 pragma Export (C, Factorial);
32811 end API;
32812 @end cartouche
32813 @end group
32814 @end smallexample
32815
32816 @smallexample @c ada
32817 @group
32818 @cartouche
32819 package body API is
32820 function Factorial (Val : C.int) return C.int is
32821 Fact : C.int := 1;
32822 begin
32823 Count := Count + 1;
32824 for K in 1 .. Val loop
32825 Fact := Fact * K;
32826 end loop;
32827 return Fact;
32828 end Factorial;
32829
32830 procedure Initialize_API is
32831 procedure Adainit;
32832 pragma Import (C, Adainit);
32833 begin
32834 Adainit;
32835 end Initialize_API;
32836
32837 procedure Finalize_API is
32838 procedure Adafinal;
32839 pragma Import (C, Adafinal);
32840 begin
32841 Adafinal;
32842 end Finalize_API;
32843 end API;
32844 @end cartouche
32845 @end group
32846 @end smallexample
32847
32848 @noindent
32849 If the Ada DLL you are building will only be used by Ada applications
32850 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32851 convention. As an example, the previous package could be written as
32852 follows:
32853
32854 @smallexample @c ada
32855 @group
32856 @cartouche
32857 package API is
32858 Count : Integer := 0;
32859 function Factorial (Val : Integer) return Integer;
32860
32861 procedure Initialize_API;
32862 procedure Finalize_API;
32863 -- Initialization and Finalization routines.
32864 end API;
32865 @end cartouche
32866 @end group
32867 @end smallexample
32868
32869 @smallexample @c ada
32870 @group
32871 @cartouche
32872 package body API is
32873 function Factorial (Val : Integer) return Integer is
32874 Fact : Integer := 1;
32875 begin
32876 Count := Count + 1;
32877 for K in 1 .. Val loop
32878 Fact := Fact * K;
32879 end loop;
32880 return Fact;
32881 end Factorial;
32882
32883 @dots{}
32884 -- The remainder of this package body is unchanged.
32885 end API;
32886 @end cartouche
32887 @end group
32888 @end smallexample
32889
32890 @noindent
32891 Note that if you do not export the Ada entities with a @code{C} or
32892 @code{Stdcall} convention you will have to provide the mangled Ada names
32893 in the definition file of the Ada DLL
32894 (@pxref{Creating the Definition File}).
32895
32896 @node Ada DLLs and Elaboration
32897 @subsection Ada DLLs and Elaboration
32898 @cindex DLLs and elaboration
32899
32900 @noindent
32901 The DLL that you are building contains your Ada code as well as all the
32902 routines in the Ada library that are needed by it. The first thing a
32903 user of your DLL must do is elaborate the Ada code
32904 (@pxref{Elaboration Order Handling in GNAT}).
32905
32906 To achieve this you must export an initialization routine
32907 (@code{Initialize_API} in the previous example), which must be invoked
32908 before using any of the DLL services. This elaboration routine must call
32909 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32910 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32911 @code{Initialize_Api} for an example. Note that the GNAT binder is
32912 automatically invoked during the DLL build process by the @code{gnatdll}
32913 tool (@pxref{Using gnatdll}).
32914
32915 When a DLL is loaded, Windows systematically invokes a routine called
32916 @code{DllMain}. It would therefore be possible to call @code{adainit}
32917 directly from @code{DllMain} without having to provide an explicit
32918 initialization routine. Unfortunately, it is not possible to call
32919 @code{adainit} from the @code{DllMain} if your program has library level
32920 tasks because access to the @code{DllMain} entry point is serialized by
32921 the system (that is, only a single thread can execute ``through'' it at a
32922 time), which means that the GNAT run time will deadlock waiting for the
32923 newly created task to complete its initialization.
32924
32925 @node Ada DLLs and Finalization
32926 @subsection Ada DLLs and Finalization
32927 @cindex DLLs and finalization
32928
32929 @noindent
32930 When the services of an Ada DLL are no longer needed, the client code should
32931 invoke the DLL finalization routine, if available. The DLL finalization
32932 routine is in charge of releasing all resources acquired by the DLL. In the
32933 case of the Ada code contained in the DLL, this is achieved by calling
32934 routine @code{adafinal} generated by the GNAT binder
32935 (@pxref{Binding with Non-Ada Main Programs}).
32936 See the body of @code{Finalize_Api} for an
32937 example. As already pointed out the GNAT binder is automatically invoked
32938 during the DLL build process by the @code{gnatdll} tool
32939 (@pxref{Using gnatdll}).
32940
32941 @node Creating a Spec for Ada DLLs
32942 @subsection Creating a Spec for Ada DLLs
32943
32944 @noindent
32945 To use the services exported by the Ada DLL from another programming
32946 language (e.g.@: C), you have to translate the specs of the exported Ada
32947 entities in that language. For instance in the case of @code{API.dll},
32948 the corresponding C header file could look like:
32949
32950 @smallexample
32951 @group
32952 @cartouche
32953 extern int *_imp__count;
32954 #define count (*_imp__count)
32955 int factorial (int);
32956 @end cartouche
32957 @end group
32958 @end smallexample
32959
32960 @noindent
32961 It is important to understand that when building an Ada DLL to be used by
32962 other Ada applications, you need two different specs for the packages
32963 contained in the DLL: one for building the DLL and the other for using
32964 the DLL. This is because the @code{DLL} calling convention is needed to
32965 use a variable defined in a DLL, but when building the DLL, the variable
32966 must have either the @code{Ada} or @code{C} calling convention. As an
32967 example consider a DLL comprising the following package @code{API}:
32968
32969 @smallexample @c ada
32970 @group
32971 @cartouche
32972 package API is
32973 Count : Integer := 0;
32974 @dots{}
32975 -- Remainder of the package omitted.
32976 end API;
32977 @end cartouche
32978 @end group
32979 @end smallexample
32980
32981 @noindent
32982 After producing a DLL containing package @code{API}, the spec that
32983 must be used to import @code{API.Count} from Ada code outside of the
32984 DLL is:
32985
32986 @smallexample @c ada
32987 @group
32988 @cartouche
32989 package API is
32990 Count : Integer;
32991 pragma Import (DLL, Count);
32992 end API;
32993 @end cartouche
32994 @end group
32995 @end smallexample
32996
32997 @node Creating the Definition File
32998 @subsection Creating the Definition File
32999
33000 @noindent
33001 The definition file is the last file needed to build the DLL. It lists
33002 the exported symbols. As an example, the definition file for a DLL
33003 containing only package @code{API} (where all the entities are exported
33004 with a @code{C} calling convention) is:
33005
33006 @smallexample
33007 @group
33008 @cartouche
33009 EXPORTS
33010 count
33011 factorial
33012 finalize_api
33013 initialize_api
33014 @end cartouche
33015 @end group
33016 @end smallexample
33017
33018 @noindent
33019 If the @code{C} calling convention is missing from package @code{API},
33020 then the definition file contains the mangled Ada names of the above
33021 entities, which in this case are:
33022
33023 @smallexample
33024 @group
33025 @cartouche
33026 EXPORTS
33027 api__count
33028 api__factorial
33029 api__finalize_api
33030 api__initialize_api
33031 @end cartouche
33032 @end group
33033 @end smallexample
33034
33035 @node Using gnatdll
33036 @subsection Using @code{gnatdll}
33037 @findex gnatdll
33038
33039 @menu
33040 * gnatdll Example::
33041 * gnatdll behind the Scenes::
33042 * Using dlltool::
33043 @end menu
33044
33045 @noindent
33046 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33047 and non-Ada sources that make up your DLL have been compiled.
33048 @code{gnatdll} is actually in charge of two distinct tasks: build the
33049 static import library for the DLL and the actual DLL. The form of the
33050 @code{gnatdll} command is
33051
33052 @smallexample
33053 @cartouche
33054 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33055 @end cartouche
33056 @end smallexample
33057
33058 @noindent
33059 where @var{list-of-files} is a list of ALI and object files. The object
33060 file list must be the exact list of objects corresponding to the non-Ada
33061 sources whose services are to be included in the DLL. The ALI file list
33062 must be the exact list of ALI files for the corresponding Ada sources
33063 whose services are to be included in the DLL. If @var{list-of-files} is
33064 missing, only the static import library is generated.
33065
33066 @noindent
33067 You may specify any of the following switches to @code{gnatdll}:
33068
33069 @table @code
33070 @item -a@ovar{address}
33071 @cindex @option{-a} (@code{gnatdll})
33072 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33073 specified the default address @var{0x11000000} will be used. By default,
33074 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33075 advise the reader to build relocatable DLL.
33076
33077 @item -b @var{address}
33078 @cindex @option{-b} (@code{gnatdll})
33079 Set the relocatable DLL base address. By default the address is
33080 @code{0x11000000}.
33081
33082 @item -bargs @var{opts}
33083 @cindex @option{-bargs} (@code{gnatdll})
33084 Binder options. Pass @var{opts} to the binder.
33085
33086 @item -d @var{dllfile}
33087 @cindex @option{-d} (@code{gnatdll})
33088 @var{dllfile} is the name of the DLL. This switch must be present for
33089 @code{gnatdll} to do anything. The name of the generated import library is
33090 obtained algorithmically from @var{dllfile} as shown in the following
33091 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33092 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33093 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33094 as shown in the following example:
33095 if @var{dllfile} is @code{xyz.dll}, the definition
33096 file used is @code{xyz.def}.
33097
33098 @item -e @var{deffile}
33099 @cindex @option{-e} (@code{gnatdll})
33100 @var{deffile} is the name of the definition file.
33101
33102 @item -g
33103 @cindex @option{-g} (@code{gnatdll})
33104 Generate debugging information. This information is stored in the object
33105 file and copied from there to the final DLL file by the linker,
33106 where it can be read by the debugger. You must use the
33107 @option{-g} switch if you plan on using the debugger or the symbolic
33108 stack traceback.
33109
33110 @item -h
33111 @cindex @option{-h} (@code{gnatdll})
33112 Help mode. Displays @code{gnatdll} switch usage information.
33113
33114 @item -Idir
33115 @cindex @option{-I} (@code{gnatdll})
33116 Direct @code{gnatdll} to search the @var{dir} directory for source and
33117 object files needed to build the DLL.
33118 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33119
33120 @item -k
33121 @cindex @option{-k} (@code{gnatdll})
33122 Removes the @code{@@}@var{nn} suffix from the import library's exported
33123 names, but keeps them for the link names. You must specify this
33124 option if you want to use a @code{Stdcall} function in a DLL for which
33125 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33126 of the Windows NT DLL for example. This option has no effect when
33127 @option{-n} option is specified.
33128
33129 @item -l @var{file}
33130 @cindex @option{-l} (@code{gnatdll})
33131 The list of ALI and object files used to build the DLL are listed in
33132 @var{file}, instead of being given in the command line. Each line in
33133 @var{file} contains the name of an ALI or object file.
33134
33135 @item -n
33136 @cindex @option{-n} (@code{gnatdll})
33137 No Import. Do not create the import library.
33138
33139 @item -q
33140 @cindex @option{-q} (@code{gnatdll})
33141 Quiet mode. Do not display unnecessary messages.
33142
33143 @item -v
33144 @cindex @option{-v} (@code{gnatdll})
33145 Verbose mode. Display extra information.
33146
33147 @item -largs @var{opts}
33148 @cindex @option{-largs} (@code{gnatdll})
33149 Linker options. Pass @var{opts} to the linker.
33150 @end table
33151
33152 @node gnatdll Example
33153 @subsubsection @code{gnatdll} Example
33154
33155 @noindent
33156 As an example the command to build a relocatable DLL from @file{api.adb}
33157 once @file{api.adb} has been compiled and @file{api.def} created is
33158
33159 @smallexample
33160 $ gnatdll -d api.dll api.ali
33161 @end smallexample
33162
33163 @noindent
33164 The above command creates two files: @file{libapi.dll.a} (the import
33165 library) and @file{api.dll} (the actual DLL). If you want to create
33166 only the DLL, just type:
33167
33168 @smallexample
33169 $ gnatdll -d api.dll -n api.ali
33170 @end smallexample
33171
33172 @noindent
33173 Alternatively if you want to create just the import library, type:
33174
33175 @smallexample
33176 $ gnatdll -d api.dll
33177 @end smallexample
33178
33179 @node gnatdll behind the Scenes
33180 @subsubsection @code{gnatdll} behind the Scenes
33181
33182 @noindent
33183 This section details the steps involved in creating a DLL. @code{gnatdll}
33184 does these steps for you. Unless you are interested in understanding what
33185 goes on behind the scenes, you should skip this section.
33186
33187 We use the previous example of a DLL containing the Ada package @code{API},
33188 to illustrate the steps necessary to build a DLL. The starting point is a
33189 set of objects that will make up the DLL and the corresponding ALI
33190 files. In the case of this example this means that @file{api.o} and
33191 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33192 the following:
33193
33194 @enumerate
33195 @item
33196 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33197 the information necessary to generate relocation information for the
33198 DLL.
33199
33200 @smallexample
33201 @group
33202 $ gnatbind -n api
33203 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33204 @end group
33205 @end smallexample
33206
33207 @noindent
33208 In addition to the base file, the @command{gnatlink} command generates an
33209 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33210 asks @command{gnatlink} to generate the routines @code{DllMain} and
33211 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33212 is loaded into memory.
33213
33214 @item
33215 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33216 export table (@file{api.exp}). The export table contains the relocation
33217 information in a form which can be used during the final link to ensure
33218 that the Windows loader is able to place the DLL anywhere in memory.
33219
33220 @smallexample
33221 @group
33222 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33223 --output-exp api.exp
33224 @end group
33225 @end smallexample
33226
33227 @item
33228 @code{gnatdll} builds the base file using the new export table. Note that
33229 @command{gnatbind} must be called once again since the binder generated file
33230 has been deleted during the previous call to @command{gnatlink}.
33231
33232 @smallexample
33233 @group
33234 $ gnatbind -n api
33235 $ gnatlink api -o api.jnk api.exp -mdll
33236 -Wl,--base-file,api.base
33237 @end group
33238 @end smallexample
33239
33240 @item
33241 @code{gnatdll} builds the new export table using the new base file and
33242 generates the DLL import library @file{libAPI.dll.a}.
33243
33244 @smallexample
33245 @group
33246 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33247 --output-exp api.exp --output-lib libAPI.a
33248 @end group
33249 @end smallexample
33250
33251 @item
33252 Finally @code{gnatdll} builds the relocatable DLL using the final export
33253 table.
33254
33255 @smallexample
33256 @group
33257 $ gnatbind -n api
33258 $ gnatlink api api.exp -o api.dll -mdll
33259 @end group
33260 @end smallexample
33261 @end enumerate
33262
33263 @node Using dlltool
33264 @subsubsection Using @code{dlltool}
33265
33266 @noindent
33267 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33268 DLLs and static import libraries. This section summarizes the most
33269 common @code{dlltool} switches. The form of the @code{dlltool} command
33270 is
33271
33272 @smallexample
33273 $ dlltool @ovar{switches}
33274 @end smallexample
33275
33276 @noindent
33277 @code{dlltool} switches include:
33278
33279 @table @option
33280 @item --base-file @var{basefile}
33281 @cindex @option{--base-file} (@command{dlltool})
33282 Read the base file @var{basefile} generated by the linker. This switch
33283 is used to create a relocatable DLL.
33284
33285 @item --def @var{deffile}
33286 @cindex @option{--def} (@command{dlltool})
33287 Read the definition file.
33288
33289 @item --dllname @var{name}
33290 @cindex @option{--dllname} (@command{dlltool})
33291 Gives the name of the DLL. This switch is used to embed the name of the
33292 DLL in the static import library generated by @code{dlltool} with switch
33293 @option{--output-lib}.
33294
33295 @item -k
33296 @cindex @option{-k} (@command{dlltool})
33297 Kill @code{@@}@var{nn} from exported names
33298 (@pxref{Windows Calling Conventions}
33299 for a discussion about @code{Stdcall}-style symbols.
33300
33301 @item --help
33302 @cindex @option{--help} (@command{dlltool})
33303 Prints the @code{dlltool} switches with a concise description.
33304
33305 @item --output-exp @var{exportfile}
33306 @cindex @option{--output-exp} (@command{dlltool})
33307 Generate an export file @var{exportfile}. The export file contains the
33308 export table (list of symbols in the DLL) and is used to create the DLL.
33309
33310 @item --output-lib @var{libfile}
33311 @cindex @option{--output-lib} (@command{dlltool})
33312 Generate a static import library @var{libfile}.
33313
33314 @item -v
33315 @cindex @option{-v} (@command{dlltool})
33316 Verbose mode.
33317
33318 @item --as @var{assembler-name}
33319 @cindex @option{--as} (@command{dlltool})
33320 Use @var{assembler-name} as the assembler. The default is @code{as}.
33321 @end table
33322
33323 @node GNAT and Windows Resources
33324 @section GNAT and Windows Resources
33325 @cindex Resources, windows
33326
33327 @menu
33328 * Building Resources::
33329 * Compiling Resources::
33330 * Using Resources::
33331 @end menu
33332
33333 @noindent
33334 Resources are an easy way to add Windows specific objects to your
33335 application. The objects that can be added as resources include:
33336
33337 @itemize @bullet
33338 @item
33339 menus
33340
33341 @item
33342 accelerators
33343
33344 @item
33345 dialog boxes
33346
33347 @item
33348 string tables
33349
33350 @item
33351 bitmaps
33352
33353 @item
33354 cursors
33355
33356 @item
33357 icons
33358
33359 @item
33360 fonts
33361 @end itemize
33362
33363 @noindent
33364 This section explains how to build, compile and use resources.
33365
33366 @node Building Resources
33367 @subsection Building Resources
33368 @cindex Resources, building
33369
33370 @noindent
33371 A resource file is an ASCII file. By convention resource files have an
33372 @file{.rc} extension.
33373 The easiest way to build a resource file is to use Microsoft tools
33374 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33375 @code{dlgedit.exe} to build dialogs.
33376 It is always possible to build an @file{.rc} file yourself by writing a
33377 resource script.
33378
33379 It is not our objective to explain how to write a resource file. A
33380 complete description of the resource script language can be found in the
33381 Microsoft documentation.
33382
33383 @node Compiling Resources
33384 @subsection Compiling Resources
33385 @findex rc
33386 @findex windres
33387 @cindex Resources, compiling
33388
33389 @noindent
33390 This section describes how to build a GNAT-compatible (COFF) object file
33391 containing the resources. This is done using the Resource Compiler
33392 @code{windres} as follows:
33393
33394 @smallexample
33395 $ windres -i myres.rc -o myres.o
33396 @end smallexample
33397
33398 @noindent
33399 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33400 file. You can specify an alternate preprocessor (usually named
33401 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33402 parameter. A list of all possible options may be obtained by entering
33403 the command @code{windres} @option{--help}.
33404
33405 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33406 to produce a @file{.res} file (binary resource file). See the
33407 corresponding Microsoft documentation for further details. In this case
33408 you need to use @code{windres} to translate the @file{.res} file to a
33409 GNAT-compatible object file as follows:
33410
33411 @smallexample
33412 $ windres -i myres.res -o myres.o
33413 @end smallexample
33414
33415 @node Using Resources
33416 @subsection Using Resources
33417 @cindex Resources, using
33418
33419 @noindent
33420 To include the resource file in your program just add the
33421 GNAT-compatible object file for the resource(s) to the linker
33422 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33423 option:
33424
33425 @smallexample
33426 $ gnatmake myprog -largs myres.o
33427 @end smallexample
33428
33429 @node Debugging a DLL
33430 @section Debugging a DLL
33431 @cindex DLL debugging
33432
33433 @menu
33434 * Program and DLL Both Built with GCC/GNAT::
33435 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33436 @end menu
33437
33438 @noindent
33439 Debugging a DLL is similar to debugging a standard program. But
33440 we have to deal with two different executable parts: the DLL and the
33441 program that uses it. We have the following four possibilities:
33442
33443 @enumerate 1
33444 @item
33445 The program and the DLL are built with @code{GCC/GNAT}.
33446 @item
33447 The program is built with foreign tools and the DLL is built with
33448 @code{GCC/GNAT}.
33449 @item
33450 The program is built with @code{GCC/GNAT} and the DLL is built with
33451 foreign tools.
33452 @item
33453 @end enumerate
33454
33455 @noindent
33456 In this section we address only cases one and two above.
33457 There is no point in trying to debug
33458 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33459 information in it. To do so you must use a debugger compatible with the
33460 tools suite used to build the DLL.
33461
33462 @node Program and DLL Both Built with GCC/GNAT
33463 @subsection Program and DLL Both Built with GCC/GNAT
33464
33465 @noindent
33466 This is the simplest case. Both the DLL and the program have @code{GDB}
33467 compatible debugging information. It is then possible to break anywhere in
33468 the process. Let's suppose here that the main procedure is named
33469 @code{ada_main} and that in the DLL there is an entry point named
33470 @code{ada_dll}.
33471
33472 @noindent
33473 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33474 program must have been built with the debugging information (see GNAT -g
33475 switch). Here are the step-by-step instructions for debugging it:
33476
33477 @enumerate 1
33478 @item Launch @code{GDB} on the main program.
33479
33480 @smallexample
33481 $ gdb -nw ada_main
33482 @end smallexample
33483
33484 @item Start the program and stop at the beginning of the main procedure
33485
33486 @smallexample
33487 (gdb) start
33488 @end smallexample
33489
33490 @noindent
33491 This step is required to be able to set a breakpoint inside the DLL. As long
33492 as the program is not run, the DLL is not loaded. This has the
33493 consequence that the DLL debugging information is also not loaded, so it is not
33494 possible to set a breakpoint in the DLL.
33495
33496 @item Set a breakpoint inside the DLL
33497
33498 @smallexample
33499 (gdb) break ada_dll
33500 (gdb) cont
33501 @end smallexample
33502
33503 @end enumerate
33504
33505 @noindent
33506 At this stage a breakpoint is set inside the DLL. From there on
33507 you can use the standard approach to debug the whole program
33508 (@pxref{Running and Debugging Ada Programs}).
33509
33510 @ignore
33511 @c This used to work, probably because the DLLs were non-relocatable
33512 @c keep this section around until the problem is sorted out.
33513
33514 To break on the @code{DllMain} routine it is not possible to follow
33515 the procedure above. At the time the program stop on @code{ada_main}
33516 the @code{DllMain} routine as already been called. Either you can use
33517 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33518
33519 @enumerate 1
33520 @item Launch @code{GDB} on the main program.
33521
33522 @smallexample
33523 $ gdb ada_main
33524 @end smallexample
33525
33526 @item Load DLL symbols
33527
33528 @smallexample
33529 (gdb) add-sym api.dll
33530 @end smallexample
33531
33532 @item Set a breakpoint inside the DLL
33533
33534 @smallexample
33535 (gdb) break ada_dll.adb:45
33536 @end smallexample
33537
33538 Note that at this point it is not possible to break using the routine symbol
33539 directly as the program is not yet running. The solution is to break
33540 on the proper line (break in @file{ada_dll.adb} line 45).
33541
33542 @item Start the program
33543
33544 @smallexample
33545 (gdb) run
33546 @end smallexample
33547
33548 @end enumerate
33549 @end ignore
33550
33551 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33552 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33553
33554 @menu
33555 * Debugging the DLL Directly::
33556 * Attaching to a Running Process::
33557 @end menu
33558
33559 @noindent
33560 In this case things are slightly more complex because it is not possible to
33561 start the main program and then break at the beginning to load the DLL and the
33562 associated DLL debugging information. It is not possible to break at the
33563 beginning of the program because there is no @code{GDB} debugging information,
33564 and therefore there is no direct way of getting initial control. This
33565 section addresses this issue by describing some methods that can be used
33566 to break somewhere in the DLL to debug it.
33567
33568 @noindent
33569 First suppose that the main procedure is named @code{main} (this is for
33570 example some C code built with Microsoft Visual C) and that there is a
33571 DLL named @code{test.dll} containing an Ada entry point named
33572 @code{ada_dll}.
33573
33574 @noindent
33575 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33576 been built with debugging information (see GNAT -g option).
33577
33578 @node Debugging the DLL Directly
33579 @subsubsection Debugging the DLL Directly
33580
33581 @enumerate 1
33582 @item
33583 Find out the executable starting address
33584
33585 @smallexample
33586 $ objdump --file-header main.exe
33587 @end smallexample
33588
33589 The starting address is reported on the last line. For example:
33590
33591 @smallexample
33592 main.exe: file format pei-i386
33593 architecture: i386, flags 0x0000010a:
33594 EXEC_P, HAS_DEBUG, D_PAGED
33595 start address 0x00401010
33596 @end smallexample
33597
33598 @item
33599 Launch the debugger on the executable.
33600
33601 @smallexample
33602 $ gdb main.exe
33603 @end smallexample
33604
33605 @item
33606 Set a breakpoint at the starting address, and launch the program.
33607
33608 @smallexample
33609 $ (gdb) break *0x00401010
33610 $ (gdb) run
33611 @end smallexample
33612
33613 The program will stop at the given address.
33614
33615 @item
33616 Set a breakpoint on a DLL subroutine.
33617
33618 @smallexample
33619 (gdb) break ada_dll.adb:45
33620 @end smallexample
33621
33622 Or if you want to break using a symbol on the DLL, you need first to
33623 select the Ada language (language used by the DLL).
33624
33625 @smallexample
33626 (gdb) set language ada
33627 (gdb) break ada_dll
33628 @end smallexample
33629
33630 @item
33631 Continue the program.
33632
33633 @smallexample
33634 (gdb) cont
33635 @end smallexample
33636
33637 @noindent
33638 This will run the program until it reaches the breakpoint that has been
33639 set. From that point you can use the standard way to debug a program
33640 as described in (@pxref{Running and Debugging Ada Programs}).
33641
33642 @end enumerate
33643
33644 @noindent
33645 It is also possible to debug the DLL by attaching to a running process.
33646
33647 @node Attaching to a Running Process
33648 @subsubsection Attaching to a Running Process
33649 @cindex DLL debugging, attach to process
33650
33651 @noindent
33652 With @code{GDB} it is always possible to debug a running process by
33653 attaching to it. It is possible to debug a DLL this way. The limitation
33654 of this approach is that the DLL must run long enough to perform the
33655 attach operation. It may be useful for instance to insert a time wasting
33656 loop in the code of the DLL to meet this criterion.
33657
33658 @enumerate 1
33659
33660 @item Launch the main program @file{main.exe}.
33661
33662 @smallexample
33663 $ main
33664 @end smallexample
33665
33666 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33667 that the process PID for @file{main.exe} is 208.
33668
33669 @item Launch gdb.
33670
33671 @smallexample
33672 $ gdb
33673 @end smallexample
33674
33675 @item Attach to the running process to be debugged.
33676
33677 @smallexample
33678 (gdb) attach 208
33679 @end smallexample
33680
33681 @item Load the process debugging information.
33682
33683 @smallexample
33684 (gdb) symbol-file main.exe
33685 @end smallexample
33686
33687 @item Break somewhere in the DLL.
33688
33689 @smallexample
33690 (gdb) break ada_dll
33691 @end smallexample
33692
33693 @item Continue process execution.
33694
33695 @smallexample
33696 (gdb) cont
33697 @end smallexample
33698
33699 @end enumerate
33700
33701 @noindent
33702 This last step will resume the process execution, and stop at
33703 the breakpoint we have set. From there you can use the standard
33704 approach to debug a program as described in
33705 (@pxref{Running and Debugging Ada Programs}).
33706
33707 @node Setting Stack Size from gnatlink
33708 @section Setting Stack Size from @command{gnatlink}
33709
33710 @noindent
33711 It is possible to specify the program stack size at link time. On modern
33712 versions of Windows, starting with XP, this is mostly useful to set the size of
33713 the main stack (environment task). The other task stacks are set with pragma
33714 Storage_Size or with the @command{gnatbind -d} command.
33715
33716 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33717 reserve size of individual tasks, the link-time stack size applies to all
33718 tasks, and pragma Storage_Size has no effect.
33719 In particular, Stack Overflow checks are made against this
33720 link-time specified size.
33721
33722 This setting can be done with
33723 @command{gnatlink} using either:
33724
33725 @itemize @bullet
33726
33727 @item using @option{-Xlinker} linker option
33728
33729 @smallexample
33730 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33731 @end smallexample
33732
33733 This sets the stack reserve size to 0x10000 bytes and the stack commit
33734 size to 0x1000 bytes.
33735
33736 @item using @option{-Wl} linker option
33737
33738 @smallexample
33739 $ gnatlink hello -Wl,--stack=0x1000000
33740 @end smallexample
33741
33742 This sets the stack reserve size to 0x1000000 bytes. Note that with
33743 @option{-Wl} option it is not possible to set the stack commit size
33744 because the coma is a separator for this option.
33745
33746 @end itemize
33747
33748 @node Setting Heap Size from gnatlink
33749 @section Setting Heap Size from @command{gnatlink}
33750
33751 @noindent
33752 Under Windows systems, it is possible to specify the program heap size from
33753 @command{gnatlink} using either:
33754
33755 @itemize @bullet
33756
33757 @item using @option{-Xlinker} linker option
33758
33759 @smallexample
33760 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33761 @end smallexample
33762
33763 This sets the heap reserve size to 0x10000 bytes and the heap commit
33764 size to 0x1000 bytes.
33765
33766 @item using @option{-Wl} linker option
33767
33768 @smallexample
33769 $ gnatlink hello -Wl,--heap=0x1000000
33770 @end smallexample
33771
33772 This sets the heap reserve size to 0x1000000 bytes. Note that with
33773 @option{-Wl} option it is not possible to set the heap commit size
33774 because the coma is a separator for this option.
33775
33776 @end itemize
33777
33778 @end ifset
33779
33780 @c **********************************
33781 @c * GNU Free Documentation License *
33782 @c **********************************
33783 @include fdl.texi
33784 @c GNU Free Documentation License
33785
33786 @node Index,,GNU Free Documentation License, Top
33787 @unnumbered Index
33788
33789 @printindex cp
33790
33791 @contents
33792 @c Put table of contents at end, otherwise it precedes the "title page" in
33793 @c the .txt version
33794 @c Edit the pdf file to move the contents to the beginning, after the title
33795 @c page
33796
33797 @bye