]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/ada/gnat_ugn.texi
[multiple changes]
[thirdparty/gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c o
6 @c GNAT DOCUMENTATION o
7 @c o
8 @c G N A T _ U G N o
9 @c o
10 @c 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 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103 Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213 procedure Hello;
1214 procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219 procedure Hello is
1220 begin
1221 Put_Line ("Hello WORLD!");
1222 end Hello;
1223
1224 procedure Goodbye is
1225 begin
1226 Put_Line ("Goodbye WORLD!");
1227 end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235 Greetings.Hello;
1236 Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs. This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear. In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}. This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503 Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568 Line : String (1..80);
1569 N : Natural;
1570 begin
1571 Put_Line("Type a line of text at each prompt; an empty line to exit");
1572 loop
1573 Put(": ");
1574 Get_Line (Line, N);
1575 Put_Line (Line (1..N) );
1576 exit when N=0;
1577 end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}. When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091 Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093 Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151 Spec_File_Name => FILE_NAME_PATTERN
2152 @r{[},Casing => CASING_SPEC@r{]}
2153 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156 Body_File_Name => FILE_NAME_PATTERN
2157 @r{[},Casing => CASING_SPEC@r{]}
2158 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161 Subunit_File_Name => FILE_NAME_PATTERN
2162 @r{[},Casing => CASING_SPEC@r{]}
2163 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231 (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233 (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259 (Spec_File_Name => "*_.ADA",
2260 Dot_Replacement => "__",
2261 Casing = Uppercase);
2262 pragma Source_File_Name
2263 (Body_File_Name => "*.ADA",
2264 Dot_Replacement => "__",
2265 Casing = Uppercase);
2266 pragma Source_File_Name
2267 (Subunit_File_Name => "*.SEP",
2268 Dot_Replacement => "__",
2269 Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada. Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555 printf ("num is %d.\n", num);
2556 return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566 return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 -- my_main.adb
2572 procedure My_Main is
2573
2574 -- Declare then export an Integer entity called num_from_Ada
2575 My_Num : Integer := 10;
2576 pragma Export (C, My_Num, "num_from_Ada");
2577
2578 -- Declare an Ada function spec for Get_Num, then use
2579 -- C function get_num for the implementation.
2580 function Get_Num return Integer;
2581 pragma Import (C, Get_Num, "get_num");
2582
2583 -- Declare an Ada procedure spec for Print_Num, then use
2584 -- C function print_num for the implementation.
2585 procedure Print_Num (Num : Integer);
2586 pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589 Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources. To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652 int a = 21, b = 7;
2653
2654 adainit();
2655
2656 /* Should print "21 + 7 = 28" */
2657 printf ("%d + %d = %d\n", a, b, add (a, b));
2658 /* Should print "21 - 7 = 14" */
2659 printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661 adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 -- unit1.ads
2667 package Unit1 is
2668 function Add (A, B : Integer) return Integer;
2669 pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 -- unit1.adb
2673 package body Unit1 is
2674 function Add (A, B : Integer) return Integer is
2675 begin
2676 return A + B;
2677 end Add;
2678 end Unit1;
2679
2680 -- unit2.ads
2681 package Unit2 is
2682 function Sub (A, B : Integer) return Integer;
2683 pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 -- unit2.adb
2687 package body Unit2 is
2688 function Sub (A, B : Integer) return Integer is
2689 begin
2690 return A - B;
2691 end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's. First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file. Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886 return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903 function builtin_sqrt (F : Float) return Float;
2904 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge. This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ constructors::
2980 * Interfacing with C++ at the Class Level::
2981 @end menu
2982
2983 @node Interfacing to C++
2984 @subsection Interfacing to C++
2985
2986 @noindent
2987 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2988 generating code that is compatible with the G++ Application Binary
2989 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2990
2991 @noindent
2992 Interfacing can be done at 3 levels: simple data, subprograms, and
2993 classes. In the first two cases, GNAT offers a specific @code{Convention
2994 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2995 Usually, C++ mangles the names of subprograms. To generate proper mangled
2996 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2997 This problem can also be addressed manually in two ways:
2998
2999 @itemize @bullet
3000 @item
3001 by modifying the C++ code in order to force a C convention using
3002 the @code{extern "C"} syntax.
3003
3004 @item
3005 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3006 Link_Name argument of the pragma import.
3007 @end itemize
3008
3009 @noindent
3010 Interfacing at the class level can be achieved by using the GNAT specific
3011 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3012 gnat_rm, GNAT Reference Manual}, for additional information.
3013
3014 @node Linking a Mixed C++ & Ada Program
3015 @subsection Linking a Mixed C++ & Ada Program
3016
3017 @noindent
3018 Usually the linker of the C++ development system must be used to link
3019 mixed applications because most C++ systems will resolve elaboration
3020 issues (such as calling constructors on global class instances)
3021 transparently during the link phase. GNAT has been adapted to ease the
3022 use of a foreign linker for the last phase. Three cases can be
3023 considered:
3024 @enumerate
3025
3026 @item
3027 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3028 The C++ linker can simply be called by using the C++ specific driver
3029 called @code{g++}.
3030
3031 Note that if the C++ code uses inline functions, you will need to
3032 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3033 order to provide an existing function implementation that the Ada code can
3034 link with.
3035
3036 @smallexample
3037 $ g++ -c -fkeep-inline-functions file1.C
3038 $ g++ -c -fkeep-inline-functions file2.C
3039 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3040 @end smallexample
3041
3042 @item
3043 Using GNAT and G++ from two different GCC installations: If both
3044 compilers are on the @env{PATH}, the previous method may be used. It is
3045 important to note that environment variables such as
3046 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3047 @env{GCC_ROOT} will affect both compilers
3048 at the same time and may make one of the two compilers operate
3049 improperly if set during invocation of the wrong compiler. It is also
3050 very important that the linker uses the proper @file{libgcc.a} GCC
3051 library -- that is, the one from the C++ compiler installation. The
3052 implicit link command as suggested in the @command{gnatmake} command
3053 from the former example can be replaced by an explicit link command with
3054 the full-verbosity option in order to verify which library is used:
3055 @smallexample
3056 $ gnatbind ada_unit
3057 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3058 @end smallexample
3059 If there is a problem due to interfering environment variables, it can
3060 be worked around by using an intermediate script. The following example
3061 shows the proper script to use when GNAT has not been installed at its
3062 default location and g++ has been installed at its default location:
3063
3064 @smallexample
3065 $ cat ./my_script
3066 #!/bin/sh
3067 unset BINUTILS_ROOT
3068 unset GCC_ROOT
3069 c++ $*
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3071 @end smallexample
3072
3073 @item
3074 Using a non-GNU C++ compiler: The commands previously described can be
3075 used to insure that the C++ linker is used. Nonetheless, you need to add
3076 a few more parameters to the link command line, depending on the exception
3077 mechanism used.
3078
3079 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3080 to the libgcc libraries are required:
3081
3082 @smallexample
3083 $ cat ./my_script
3084 #!/bin/sh
3085 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3086 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3087 @end smallexample
3088
3089 Where CC is the name of the non-GNU C++ compiler.
3090
3091 If the @code{zero cost} exception mechanism is used, and the platform
3092 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3093 paths to more objects are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC `gcc -print-file-name=crtbegin.o` $* \
3099 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3100 `gcc -print-file-name=crtend.o`
3101 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3102 @end smallexample
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3106 Tru64 or AIX), the simple approach described above will not work and
3107 a pre-linking phase using GNAT will be necessary.
3108
3109 @end enumerate
3110
3111 Another alternative is to use the @command{gprbuild} multi-language builder
3112 which has a large knowledge base and knows how to link Ada and C++ code
3113 together automatically in most cases.
3114
3115 @node A Simple Example
3116 @subsection A Simple Example
3117 @noindent
3118 The following example, provided as part of the GNAT examples, shows how
3119 to achieve procedural interfacing between Ada and C++ in both
3120 directions. The C++ class A has two methods. The first method is exported
3121 to Ada by the means of an extern C wrapper function. The second method
3122 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3123 a limited record with a layout comparable to the C++ class. The Ada
3124 subprogram, in turn, calls the C++ method. So, starting from the C++
3125 main program, the process passes back and forth between the two
3126 languages.
3127
3128 @noindent
3129 Here are the compilation commands:
3130 @smallexample
3131 $ gnatmake -c simple_cpp_interface
3132 $ g++ -c cpp_main.C
3133 $ g++ -c ex7.C
3134 $ gnatbind -n simple_cpp_interface
3135 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3136 -lstdc++ ex7.o cpp_main.o
3137 @end smallexample
3138
3139 @noindent
3140 Here are the corresponding sources:
3141 @smallexample
3142
3143 //cpp_main.C
3144
3145 #include "ex7.h"
3146
3147 extern "C" @{
3148 void adainit (void);
3149 void adafinal (void);
3150 void method1 (A *t);
3151 @}
3152
3153 void method1 (A *t)
3154 @{
3155 t->method1 ();
3156 @}
3157
3158 int main ()
3159 @{
3160 A obj;
3161 adainit ();
3162 obj.method2 (3030);
3163 adafinal ();
3164 @}
3165
3166 //ex7.h
3167
3168 class Origin @{
3169 public:
3170 int o_value;
3171 @};
3172 class A : public Origin @{
3173 public:
3174 void method1 (void);
3175 void method2 (int v);
3176 A();
3177 int a_value;
3178 @};
3179
3180 //ex7.C
3181
3182 #include "ex7.h"
3183 #include <stdio.h>
3184
3185 extern "C" @{ void ada_method2 (A *t, int v);@}
3186
3187 void A::method1 (void)
3188 @{
3189 a_value = 2020;
3190 printf ("in A::method1, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 void A::method2 (int v)
3195 @{
3196 ada_method2 (this, v);
3197 printf ("in A::method2, a_value = %d \n",a_value);
3198
3199 @}
3200
3201 A::A(void)
3202 @{
3203 a_value = 1010;
3204 printf ("in A::A, a_value = %d \n",a_value);
3205 @}
3206 @end smallexample
3207
3208 @smallexample @c ada
3209 -- Ada sources
3210 package body Simple_Cpp_Interface is
3211
3212 procedure Ada_Method2 (This : in out A; V : Integer) is
3213 begin
3214 Method1 (This);
3215 This.A_Value := V;
3216 end Ada_Method2;
3217
3218 end Simple_Cpp_Interface;
3219
3220 with System;
3221 package Simple_Cpp_Interface is
3222 type A is limited
3223 record
3224 Vptr : System.Address;
3225 O_Value : Integer;
3226 A_Value : Integer;
3227 end record;
3228 pragma Convention (C, A);
3229
3230 procedure Method1 (This : in out A);
3231 pragma Import (C, Method1);
3232
3233 procedure Ada_Method2 (This : in out A; V : Integer);
3234 pragma Export (C, Ada_Method2);
3235
3236 end Simple_Cpp_Interface;
3237 @end smallexample
3238
3239 @node Interfacing with C++ constructors
3240 @subsection Interfacing with C++ constructors
3241 @noindent
3242
3243 In order to interface with C++ constructors GNAT provides the
3244 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3245 gnat_rm, GNAT Reference Manual}, for additional information).
3246 In this section we present some common uses of C++ constructors
3247 in mixed-languages programs in GNAT.
3248
3249 Let us assume that we need to interface with the following
3250 C++ class:
3251
3252 @smallexample
3253 @b{class} Root @{
3254 @b{public}:
3255 int a_value;
3256 int b_value;
3257 @b{virtual} int Get_Value ();
3258 Root(); // Default constructor
3259 Root(int v); // 1st non-default constructor
3260 Root(int v, int w); // 2nd non-default constructor
3261 @};
3262 @end smallexample
3263
3264 For this purpose we can write the following package spec (further
3265 information on how to build this spec is available in
3266 @ref{Interfacing with C++ at the Class Level} and
3267 @ref{Generating Ada Bindings for C and C++ headers}).
3268
3269 @smallexample @c ada
3270 with Interfaces.C; use Interfaces.C;
3271 package Pkg_Root is
3272 type Root is tagged limited record
3273 A_Value : int;
3274 B_Value : int;
3275 end record;
3276 pragma Import (CPP, Root);
3277
3278 function Get_Value (Obj : Root) return int;
3279 pragma Import (CPP, Get_Value);
3280
3281 function Constructor return Root'Class;
3282 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284 function Constructor (v : Integer) return Root'Class;
3285 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287 function Constructor (v, w : Integer) return Root'Class;
3288 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3289 end Pkg_Root;
3290 @end smallexample
3291
3292 On the Ada side the constructor is represented by a function (whose
3293 name is arbitrary) that returns the classwide type corresponding to
3294 the imported C++ class. Although the constructor is described as a
3295 function, it is typically a procedure with an extra implicit argument
3296 (the object being initialized) at the implementation level. GNAT
3297 issues the appropriate call, whatever it is, to get the object
3298 properly initialized.
3299
3300 Constructors can only appear in the following contexts:
3301
3302 @itemize @bullet
3303 @item
3304 On the right side of an initialization of an object of type @var{T}.
3305 @item
3306 On the right side of an initialization of a record component of type @var{T}.
3307 @item
3308 In an Ada 2005 limited aggregate.
3309 @item
3310 In an Ada 2005 nested limited aggregate.
3311 @item
3312 In an Ada 2005 limited aggregate that initializes an object built in
3313 place by an extended return statement.
3314 @end itemize
3315
3316 @noindent
3317 In a declaration of an object whose type is a class imported from C++,
3318 either the default C++ constructor is implicitly called by GNAT, or
3319 else the required C++ constructor must be explicitly called in the
3320 expression that initializes the object. For example:
3321
3322 @smallexample @c ada
3323 Obj1 : Root;
3324 Obj2 : Root := Constructor;
3325 Obj3 : Root := Constructor (v => 10);
3326 Obj4 : Root := Constructor (30, 40);
3327 @end smallexample
3328
3329 The first two declarations are equivalent: in both cases the default C++
3330 constructor is invoked (in the former case the call to the constructor is
3331 implicit, and in the latter case the call is explicit in the object
3332 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3333 that takes an integer argument, and @code{Obj4} is initialized by the
3334 non-default C++ constructor that takes two integers.
3335
3336 Let us derive the imported C++ class in the Ada side. For example:
3337
3338 @smallexample @c ada
3339 type DT is new Root with record
3340 C_Value : Natural := 2009;
3341 end record;
3342 @end smallexample
3343
3344 In this case the components DT inherited from the C++ side must be
3345 initialized by a C++ constructor, and the additional Ada components
3346 of type DT are initialized by GNAT. The initialization of such an
3347 object is done either by default, or by means of a function returning
3348 an aggregate of type DT, or by means of an extension aggregate.
3349
3350 @smallexample @c ada
3351 Obj5 : DT;
3352 Obj6 : DT := Function_Returning_DT (50);
3353 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3354 @end smallexample
3355
3356 The declaration of @code{Obj5} invokes the default constructors: the
3357 C++ default constructor of the parent type takes care of the initialization
3358 of the components inherited from Root, and GNAT takes care of the default
3359 initialization of the additional Ada components of type DT (that is,
3360 @code{C_Value} is initialized to value 2009). The order of invocation of
3361 the constructors is consistent with the order of elaboration required by
3362 Ada and C++. That is, the constructor of the parent type is always called
3363 before the constructor of the derived type.
3364
3365 Let us now consider a record that has components whose type is imported
3366 from C++. For example:
3367
3368 @smallexample @c ada
3369 type Rec1 is limited record
3370 Data1 : Root := Constructor (10);
3371 Value : Natural := 1000;
3372 end record;
3373
3374 type Rec2 (D : Integer := 20) is limited record
3375 Rec : Rec1;
3376 Data2 : Root := Constructor (D, 30);
3377 end record;
3378 @end smallexample
3379
3380 The initialization of an object of type @code{Rec2} will call the
3381 non-default C++ constructors specified for the imported components.
3382 For example:
3383
3384 @smallexample @c ada
3385 Obj8 : Rec2 (40);
3386 @end smallexample
3387
3388 Using Ada 2005 we can use limited aggregates to initialize an object
3389 invoking C++ constructors that differ from those specified in the type
3390 declarations. For example:
3391
3392 @smallexample @c ada
3393 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3394 others => <>),
3395 others => <>);
3396 @end smallexample
3397
3398 The above declaration uses an Ada 2005 limited aggregate to
3399 initialize @code{Obj9}, and the C++ constructor that has two integer
3400 arguments is invoked to initialize the @code{Data1} component instead
3401 of the constructor specified in the declaration of type @code{Rec1}. In
3402 Ada 2005 the box in the aggregate indicates that unspecified components
3403 are initialized using the expression (if any) available in the component
3404 declaration. That is, in this case discriminant @code{D} is initialized
3405 to value @code{20}, @code{Value} is initialized to value 1000, and the
3406 non-default C++ constructor that handles two integers takes care of
3407 initializing component @code{Data2} with values @code{20,30}.
3408
3409 In Ada 2005 we can use the extended return statement to build the Ada
3410 equivalent to C++ non-default constructors. For example:
3411
3412 @smallexample @c ada
3413 function Constructor (V : Integer) return Rec2 is
3414 begin
3415 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3416 others => <>),
3417 others => <>) do
3418 -- Further actions required for construction of
3419 -- objects of type Rec2
3420 ...
3421 end record;
3422 end Constructor;
3423 @end smallexample
3424
3425 In this example the extended return statement construct is used to
3426 build in place the returned object whose components are initialized
3427 by means of a limited aggregate. Any further action associated with
3428 the constructor can be placed inside the construct.
3429
3430 @node Interfacing with C++ at the Class Level
3431 @subsection Interfacing with C++ at the Class Level
3432 @noindent
3433 In this section we demonstrate the GNAT features for interfacing with
3434 C++ by means of an example making use of Ada 2005 abstract interface
3435 types. This example consists of a classification of animals; classes
3436 have been used to model our main classification of animals, and
3437 interfaces provide support for the management of secondary
3438 classifications. We first demonstrate a case in which the types and
3439 constructors are defined on the C++ side and imported from the Ada
3440 side, and latter the reverse case.
3441
3442 The root of our derivation will be the @code{Animal} class, with a
3443 single private attribute (the @code{Age} of the animal) and two public
3444 primitives to set and get the value of this attribute.
3445
3446 @smallexample
3447 @b{class} Animal @{
3448 @b{public}:
3449 @b{virtual} void Set_Age (int New_Age);
3450 @b{virtual} int Age ();
3451 @b{private}:
3452 int Age_Count;
3453 @};
3454 @end smallexample
3455
3456 Abstract interface types are defined in C++ by means of classes with pure
3457 virtual functions and no data members. In our example we will use two
3458 interfaces that provide support for the common management of @code{Carnivore}
3459 and @code{Domestic} animals:
3460
3461 @smallexample
3462 @b{class} Carnivore @{
3463 @b{public}:
3464 @b{virtual} int Number_Of_Teeth () = 0;
3465 @};
3466
3467 @b{class} Domestic @{
3468 @b{public}:
3469 @b{virtual void} Set_Owner (char* Name) = 0;
3470 @};
3471 @end smallexample
3472
3473 Using these declarations, we can now say that a @code{Dog} is an animal that is
3474 both Carnivore and Domestic, that is:
3475
3476 @smallexample
3477 @b{class} Dog : Animal, Carnivore, Domestic @{
3478 @b{public}:
3479 @b{virtual} int Number_Of_Teeth ();
3480 @b{virtual} void Set_Owner (char* Name);
3481
3482 Dog(); // Constructor
3483 @b{private}:
3484 int Tooth_Count;
3485 char *Owner;
3486 @};
3487 @end smallexample
3488
3489 In the following examples we will assume that the previous declarations are
3490 located in a file named @code{animals.h}. The following package demonstrates
3491 how to import these C++ declarations from the Ada side:
3492
3493 @smallexample @c ada
3494 with Interfaces.C.Strings; use Interfaces.C.Strings;
3495 package Animals is
3496 type Carnivore is interface;
3497 pragma Convention (C_Plus_Plus, Carnivore);
3498 function Number_Of_Teeth (X : Carnivore)
3499 return Natural is abstract;
3500
3501 type Domestic is interface;
3502 pragma Convention (C_Plus_Plus, Set_Owner);
3503 procedure Set_Owner
3504 (X : in out Domestic;
3505 Name : Chars_Ptr) is abstract;
3506
3507 type Animal is tagged record
3508 Age : Natural := 0;
3509 end record;
3510 pragma Import (C_Plus_Plus, Animal);
3511
3512 procedure Set_Age (X : in out Animal; Age : Integer);
3513 pragma Import (C_Plus_Plus, Set_Age);
3514
3515 function Age (X : Animal) return Integer;
3516 pragma Import (C_Plus_Plus, Age);
3517
3518 type Dog is new Animal and Carnivore and Domestic with record
3519 Tooth_Count : Natural;
3520 Owner : String (1 .. 30);
3521 end record;
3522 pragma Import (C_Plus_Plus, Dog);
3523
3524 function Number_Of_Teeth (A : Dog) return Integer;
3525 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3526
3527 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3528 pragma Import (C_Plus_Plus, Set_Owner);
3529
3530 function New_Dog return Dog'Class;
3531 pragma CPP_Constructor (New_Dog);
3532 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3533 end Animals;
3534 @end smallexample
3535
3536 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3537 interfacing with these C++ classes is easy. The only requirement is that all
3538 the primitives and components must be declared exactly in the same order in
3539 the two languages.
3540
3541 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3542 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3543 the arguments to the called primitives will be the same as for C++. For the
3544 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3545 to indicate that they have been defined on the C++ side; this is required
3546 because the dispatch table associated with these tagged types will be built
3547 in the C++ side and therefore will not contain the predefined Ada primitives
3548 which Ada would otherwise expect.
3549
3550 As the reader can see there is no need to indicate the C++ mangled names
3551 associated with each subprogram because it is assumed that all the calls to
3552 these primitives will be dispatching calls. The only exception is the
3553 constructor, which must be registered with the compiler by means of
3554 @code{pragma CPP_Constructor} and needs to provide its associated C++
3555 mangled name because the Ada compiler generates direct calls to it.
3556
3557 With the above packages we can now declare objects of type Dog on the Ada side
3558 and dispatch calls to the corresponding subprograms on the C++ side. We can
3559 also extend the tagged type Dog with further fields and primitives, and
3560 override some of its C++ primitives on the Ada side. For example, here we have
3561 a type derivation defined on the Ada side that inherits all the dispatching
3562 primitives of the ancestor from the C++ side.
3563
3564 @smallexample
3565 @b{with} Animals; @b{use} Animals;
3566 @b{package} Vaccinated_Animals @b{is}
3567 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3568 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3569 @b{end} Vaccinated_Animals;
3570 @end smallexample
3571
3572 It is important to note that, because of the ABI compatibility, the programmer
3573 does not need to add any further information to indicate either the object
3574 layout or the dispatch table entry associated with each dispatching operation.
3575
3576 Now let us define all the types and constructors on the Ada side and export
3577 them to C++, using the same hierarchy of our previous example:
3578
3579 @smallexample @c ada
3580 with Interfaces.C.Strings;
3581 use Interfaces.C.Strings;
3582 package Animals is
3583 type Carnivore is interface;
3584 pragma Convention (C_Plus_Plus, Carnivore);
3585 function Number_Of_Teeth (X : Carnivore)
3586 return Natural is abstract;
3587
3588 type Domestic is interface;
3589 pragma Convention (C_Plus_Plus, Set_Owner);
3590 procedure Set_Owner
3591 (X : in out Domestic;
3592 Name : Chars_Ptr) is abstract;
3593
3594 type Animal is tagged record
3595 Age : Natural := 0;
3596 end record;
3597 pragma Convention (C_Plus_Plus, Animal);
3598
3599 procedure Set_Age (X : in out Animal; Age : Integer);
3600 pragma Export (C_Plus_Plus, Set_Age);
3601
3602 function Age (X : Animal) return Integer;
3603 pragma Export (C_Plus_Plus, Age);
3604
3605 type Dog is new Animal and Carnivore and Domestic with record
3606 Tooth_Count : Natural;
3607 Owner : String (1 .. 30);
3608 end record;
3609 pragma Convention (C_Plus_Plus, Dog);
3610
3611 function Number_Of_Teeth (A : Dog) return Integer;
3612 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3613
3614 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3615 pragma Export (C_Plus_Plus, Set_Owner);
3616
3617 function New_Dog return Dog'Class;
3618 pragma Export (C_Plus_Plus, New_Dog);
3619 end Animals;
3620 @end smallexample
3621
3622 Compared with our previous example the only difference is the use of
3623 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3624 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3625 nothing else to be done; as explained above, the only requirement is that all
3626 the primitives and components are declared in exactly the same order.
3627
3628 For completeness, let us see a brief C++ main program that uses the
3629 declarations available in @code{animals.h} (presented in our first example) to
3630 import and use the declarations from the Ada side, properly initializing and
3631 finalizing the Ada run-time system along the way:
3632
3633 @smallexample
3634 @b{#include} "animals.h"
3635 @b{#include} <iostream>
3636 @b{using namespace} std;
3637
3638 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3639 void Check_Domestic (Domestic *obj) @{@dots{}@}
3640 void Check_Animal (Animal *obj) @{@dots{}@}
3641 void Check_Dog (Dog *obj) @{@dots{}@}
3642
3643 @b{extern} "C" @{
3644 void adainit (void);
3645 void adafinal (void);
3646 Dog* new_dog ();
3647 @}
3648
3649 void test ()
3650 @{
3651 Dog *obj = new_dog(); // Ada constructor
3652 Check_Carnivore (obj); // Check secondary DT
3653 Check_Domestic (obj); // Check secondary DT
3654 Check_Animal (obj); // Check primary DT
3655 Check_Dog (obj); // Check primary DT
3656 @}
3657
3658 int main ()
3659 @{
3660 adainit (); test(); adafinal ();
3661 return 0;
3662 @}
3663 @end smallexample
3664
3665 @node Comparison between GNAT and C/C++ Compilation Models
3666 @section Comparison between GNAT and C/C++ Compilation Models
3667
3668 @noindent
3669 The GNAT model of compilation is close to the C and C++ models. You can
3670 think of Ada specs as corresponding to header files in C. As in C, you
3671 don't need to compile specs; they are compiled when they are used. The
3672 Ada @code{with} is similar in effect to the @code{#include} of a C
3673 header.
3674
3675 One notable difference is that, in Ada, you may compile specs separately
3676 to check them for semantic and syntactic accuracy. This is not always
3677 possible with C headers because they are fragments of programs that have
3678 less specific syntactic or semantic rules.
3679
3680 The other major difference is the requirement for running the binder,
3681 which performs two important functions. First, it checks for
3682 consistency. In C or C++, the only defense against assembling
3683 inconsistent programs lies outside the compiler, in a makefile, for
3684 example. The binder satisfies the Ada requirement that it be impossible
3685 to construct an inconsistent program when the compiler is used in normal
3686 mode.
3687
3688 @cindex Elaboration order control
3689 The other important function of the binder is to deal with elaboration
3690 issues. There are also elaboration issues in C++ that are handled
3691 automatically. This automatic handling has the advantage of being
3692 simpler to use, but the C++ programmer has no control over elaboration.
3693 Where @code{gnatbind} might complain there was no valid order of
3694 elaboration, a C++ compiler would simply construct a program that
3695 malfunctioned at run time.
3696 @end ifclear
3697
3698 @node Comparison between GNAT and Conventional Ada Library Models
3699 @section Comparison between GNAT and Conventional Ada Library Models
3700
3701 @noindent
3702 This section is intended for Ada programmers who have
3703 used an Ada compiler implementing the traditional Ada library
3704 model, as described in the Ada Reference Manual.
3705
3706 @cindex GNAT library
3707 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3708 source files themselves acts as the library. Compiling Ada programs does
3709 not generate any centralized information, but rather an object file and
3710 a ALI file, which are of interest only to the binder and linker.
3711 In a traditional system, the compiler reads information not only from
3712 the source file being compiled, but also from the centralized library.
3713 This means that the effect of a compilation depends on what has been
3714 previously compiled. In particular:
3715
3716 @itemize @bullet
3717 @item
3718 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3719 to the version of the unit most recently compiled into the library.
3720
3721 @item
3722 Inlining is effective only if the necessary body has already been
3723 compiled into the library.
3724
3725 @item
3726 Compiling a unit may obsolete other units in the library.
3727 @end itemize
3728
3729 @noindent
3730 In GNAT, compiling one unit never affects the compilation of any other
3731 units because the compiler reads only source files. Only changes to source
3732 files can affect the results of a compilation. In particular:
3733
3734 @itemize @bullet
3735 @item
3736 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3737 to the source version of the unit that is currently accessible to the
3738 compiler.
3739
3740 @item
3741 @cindex Inlining
3742 Inlining requires the appropriate source files for the package or
3743 subprogram bodies to be available to the compiler. Inlining is always
3744 effective, independent of the order in which units are complied.
3745
3746 @item
3747 Compiling a unit never affects any other compilations. The editing of
3748 sources may cause previous compilations to be out of date if they
3749 depended on the source file being modified.
3750 @end itemize
3751
3752 @noindent
3753 The most important result of these differences is that order of compilation
3754 is never significant in GNAT. There is no situation in which one is
3755 required to do one compilation before another. What shows up as order of
3756 compilation requirements in the traditional Ada library becomes, in
3757 GNAT, simple source dependencies; in other words, there is only a set
3758 of rules saying what source files must be present when a file is
3759 compiled.
3760
3761 @ifset vms
3762 @node Placement of temporary files
3763 @section Placement of temporary files
3764 @cindex Temporary files (user control over placement)
3765
3766 @noindent
3767 GNAT creates temporary files in the directory designated by the environment
3768 variable @env{TMPDIR}.
3769 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3770 for detailed information on how environment variables are resolved.
3771 For most users the easiest way to make use of this feature is to simply
3772 define @env{TMPDIR} as a job level logical name).
3773 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3774 for compiler temporary files, then you can include something like the
3775 following command in your @file{LOGIN.COM} file:
3776
3777 @smallexample
3778 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3779 @end smallexample
3780
3781 @noindent
3782 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3783 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3784 designated by @env{TEMP}.
3785 If none of these environment variables are defined then GNAT uses the
3786 directory designated by the logical name @code{SYS$SCRATCH:}
3787 (by default the user's home directory). If all else fails
3788 GNAT uses the current directory for temporary files.
3789 @end ifset
3790
3791 @c *************************
3792 @node Compiling Using gcc
3793 @chapter Compiling Using @command{gcc}
3794
3795 @noindent
3796 This chapter discusses how to compile Ada programs using the @command{gcc}
3797 command. It also describes the set of switches
3798 that can be used to control the behavior of the compiler.
3799 @menu
3800 * Compiling Programs::
3801 * Switches for gcc::
3802 * Search Paths and the Run-Time Library (RTL)::
3803 * Order of Compilation Issues::
3804 * Examples::
3805 @end menu
3806
3807 @node Compiling Programs
3808 @section Compiling Programs
3809
3810 @noindent
3811 The first step in creating an executable program is to compile the units
3812 of the program using the @command{gcc} command. You must compile the
3813 following files:
3814
3815 @itemize @bullet
3816 @item
3817 the body file (@file{.adb}) for a library level subprogram or generic
3818 subprogram
3819
3820 @item
3821 the spec file (@file{.ads}) for a library level package or generic
3822 package that has no body
3823
3824 @item
3825 the body file (@file{.adb}) for a library level package
3826 or generic package that has a body
3827
3828 @end itemize
3829
3830 @noindent
3831 You need @emph{not} compile the following files
3832
3833 @itemize @bullet
3834
3835 @item
3836 the spec of a library unit which has a body
3837
3838 @item
3839 subunits
3840 @end itemize
3841
3842 @noindent
3843 because they are compiled as part of compiling related units. GNAT
3844 package specs
3845 when the corresponding body is compiled, and subunits when the parent is
3846 compiled.
3847
3848 @cindex cannot generate code
3849 If you attempt to compile any of these files, you will get one of the
3850 following error messages (where @var{fff} is the name of the file you compiled):
3851
3852 @smallexample
3853 cannot generate code for file @var{fff} (package spec)
3854 to check package spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (missing subunits)
3857 to check parent unit, use -gnatc
3858
3859 cannot generate code for file @var{fff} (subprogram spec)
3860 to check subprogram spec, use -gnatc
3861
3862 cannot generate code for file @var{fff} (subunit)
3863 to check subunit, use -gnatc
3864 @end smallexample
3865
3866 @noindent
3867 As indicated by the above error messages, if you want to submit
3868 one of these files to the compiler to check for correct semantics
3869 without generating code, then use the @option{-gnatc} switch.
3870
3871 The basic command for compiling a file containing an Ada unit is
3872
3873 @smallexample
3874 $ gcc -c @ovar{switches} @file{file name}
3875 @end smallexample
3876
3877 @noindent
3878 where @var{file name} is the name of the Ada file (usually
3879 having an extension
3880 @file{.ads} for a spec or @file{.adb} for a body).
3881 @ifclear vms
3882 You specify the
3883 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3884 @end ifclear
3885 The result of a successful compilation is an object file, which has the
3886 same name as the source file but an extension of @file{.o} and an Ada
3887 Library Information (ALI) file, which also has the same name as the
3888 source file, but with @file{.ali} as the extension. GNAT creates these
3889 two output files in the current directory, but you may specify a source
3890 file in any directory using an absolute or relative path specification
3891 containing the directory information.
3892
3893 @findex gnat1
3894 @command{gcc} is actually a driver program that looks at the extensions of
3895 the file arguments and loads the appropriate compiler. For example, the
3896 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3897 These programs are in directories known to the driver program (in some
3898 configurations via environment variables you set), but need not be in
3899 your path. The @command{gcc} driver also calls the assembler and any other
3900 utilities needed to complete the generation of the required object
3901 files.
3902
3903 It is possible to supply several file names on the same @command{gcc}
3904 command. This causes @command{gcc} to call the appropriate compiler for
3905 each file. For example, the following command lists three separate
3906 files to be compiled:
3907
3908 @smallexample
3909 $ gcc -c x.adb y.adb z.c
3910 @end smallexample
3911
3912 @noindent
3913 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3914 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3915 The compiler generates three object files @file{x.o}, @file{y.o} and
3916 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3917 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3918 @ifclear vms
3919 except for
3920 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3921 @end ifclear
3922
3923 @node Switches for gcc
3924 @section Switches for @command{gcc}
3925
3926 @noindent
3927 The @command{gcc} command accepts switches that control the
3928 compilation process. These switches are fully described in this section.
3929 First we briefly list all the switches, in alphabetical order, then we
3930 describe the switches in more detail in functionally grouped sections.
3931
3932 More switches exist for GCC than those documented here, especially
3933 for specific targets. However, their use is not recommended as
3934 they may change code generation in ways that are incompatible with
3935 the Ada run-time library, or can cause inconsistencies between
3936 compilation units.
3937
3938 @menu
3939 * Output and Error Message Control::
3940 * Warning Message Control::
3941 * Debugging and Assertion Control::
3942 * Validity Checking::
3943 * Style Checking::
3944 * Run-Time Checks::
3945 * Using gcc for Syntax Checking::
3946 * Using gcc for Semantic Checking::
3947 * Compiling Different Versions of Ada::
3948 * Character Set Control::
3949 * File Naming Control::
3950 * Subprogram Inlining Control::
3951 * Auxiliary Output Control::
3952 * Debugging Control::
3953 * Exception Handling Control::
3954 * Units to Sources Mapping Files::
3955 * Integrated Preprocessing::
3956 * Code Generation Control::
3957 @ifset vms
3958 * Return Codes::
3959 @end ifset
3960 @end menu
3961
3962 @table @option
3963 @c !sort!
3964 @ifclear vms
3965 @cindex @option{-b} (@command{gcc})
3966 @item -b @var{target}
3967 Compile your program to run on @var{target}, which is the name of a
3968 system configuration. You must have a GNAT cross-compiler built if
3969 @var{target} is not the same as your host system.
3970
3971 @item -B@var{dir}
3972 @cindex @option{-B} (@command{gcc})
3973 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3974 from @var{dir} instead of the default location. Only use this switch
3975 when multiple versions of the GNAT compiler are available.
3976 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3977 GNU Compiler Collection (GCC)}, for further details. You would normally
3978 use the @option{-b} or @option{-V} switch instead.
3979
3980 @item -c
3981 @cindex @option{-c} (@command{gcc})
3982 Compile. Always use this switch when compiling Ada programs.
3983
3984 Note: for some other languages when using @command{gcc}, notably in
3985 the case of C and C++, it is possible to use
3986 use @command{gcc} without a @option{-c} switch to
3987 compile and link in one step. In the case of GNAT, you
3988 cannot use this approach, because the binder must be run
3989 and @command{gcc} cannot be used to run the GNAT binder.
3990 @end ifclear
3991
3992 @item -fno-inline
3993 @cindex @option{-fno-inline} (@command{gcc})
3994 Suppresses all back-end inlining, even if other optimization or inlining
3995 switches are set.
3996 This includes suppression of inlining that results
3997 from the use of the pragma @code{Inline_Always}.
3998 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3999 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4000 effect if this switch is present.
4001
4002 @item -fno-inline-functions
4003 @cindex @option{-fno-inline-functions} (@command{gcc})
4004 Suppresses automatic inlining of simple subprograms, which is enabled
4005 if @option{-O3} is used.
4006
4007 @item -fno-inline-small-functions
4008 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4009 Suppresses automatic inlining of small subprograms, which is enabled
4010 if @option{-O2} is used.
4011
4012 @item -fno-inline-functions-called-once
4013 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4014 Suppresses inlining of subprograms local to the unit and called once
4015 from within it, which is enabled if @option{-O1} is used.
4016
4017 @item -fno-ivopts
4018 @cindex @option{-fno-ivopts} (@command{gcc})
4019 Suppresses high-level loop induction variable optimizations, which are
4020 enabled if @option{-O1} is used. These optimizations are generally
4021 profitable but, for some specific cases of loops with numerous uses
4022 of the iteration variable that follow a common pattern, they may end
4023 up destroying the regularity that could be exploited at a lower level
4024 and thus producing inferior code.
4025
4026 @item -fno-strict-aliasing
4027 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4028 Causes the compiler to avoid assumptions regarding non-aliasing
4029 of objects of different types. See
4030 @ref{Optimization and Strict Aliasing} for details.
4031
4032 @item -fstack-check
4033 @cindex @option{-fstack-check} (@command{gcc})
4034 Activates stack checking.
4035 See @ref{Stack Overflow Checking} for details.
4036
4037 @item -fstack-usage
4038 @cindex @option{-fstack-usage} (@command{gcc})
4039 Makes the compiler output stack usage information for the program, on a
4040 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4041
4042 @item -fcallgraph-info@r{[}=su@r{]}
4043 @cindex @option{-fcallgraph-info} (@command{gcc})
4044 Makes the compiler output callgraph information for the program, on a
4045 per-file basis. The information is generated in the VCG format. It can
4046 be decorated with stack-usage per-node information.
4047
4048 @item ^-g^/DEBUG^
4049 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4050 Generate debugging information. This information is stored in the object
4051 file and copied from there to the final executable file by the linker,
4052 where it can be read by the debugger. You must use the
4053 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4054
4055 @item -gnat83
4056 @cindex @option{-gnat83} (@command{gcc})
4057 Enforce Ada 83 restrictions.
4058
4059 @item -gnat95
4060 @cindex @option{-gnat95} (@command{gcc})
4061 Enforce Ada 95 restrictions.
4062
4063 @item -gnat05
4064 @cindex @option{-gnat05} (@command{gcc})
4065 Allow full Ada 2005 features.
4066
4067 @item -gnata
4068 @cindex @option{-gnata} (@command{gcc})
4069 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4070 activated. Note that these pragmas can also be controlled using the
4071 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4072 It also activates pragmas @code{Check}, @code{Precondition}, and
4073 @code{Postcondition}. Note that these pragmas can also be controlled
4074 using the configuration pragma @code{Check_Policy}.
4075
4076 @item -gnatA
4077 @cindex @option{-gnatA} (@command{gcc})
4078 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4079 it will be ignored.
4080
4081 @item -gnatb
4082 @cindex @option{-gnatb} (@command{gcc})
4083 Generate brief messages to @file{stderr} even if verbose mode set.
4084
4085 @item -gnatB
4086 @cindex @option{-gnatB} (@command{gcc})
4087 Assume no invalid (bad) values except for 'Valid attribute use.
4088
4089 @item -gnatc
4090 @cindex @option{-gnatc} (@command{gcc})
4091 Check syntax and semantics only (no code generation attempted).
4092
4093 @item -gnatd
4094 @cindex @option{-gnatd} (@command{gcc})
4095 Specify debug options for the compiler. The string of characters after
4096 the @option{-gnatd} specify the specific debug options. The possible
4097 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4098 compiler source file @file{debug.adb} for details of the implemented
4099 debug options. Certain debug options are relevant to applications
4100 programmers, and these are documented at appropriate points in this
4101 users guide.
4102
4103 @ifclear vms
4104 @item -gnatD
4105 @cindex @option{-gnatD[nn]} (@command{gcc})
4106 @end ifclear
4107 @ifset vms
4108 @item /XDEBUG /LXDEBUG=nnn
4109 @end ifset
4110 Create expanded source files for source level debugging. This switch
4111 also suppress generation of cross-reference information
4112 (see @option{-gnatx}).
4113
4114 @item -gnatec=@var{path}
4115 @cindex @option{-gnatec} (@command{gcc})
4116 Specify a configuration pragma file
4117 @ifclear vms
4118 (the equal sign is optional)
4119 @end ifclear
4120 (@pxref{The Configuration Pragmas Files}).
4121
4122 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4123 @cindex @option{-gnateD} (@command{gcc})
4124 Defines a symbol, associated with @var{value}, for preprocessing.
4125 (@pxref{Integrated Preprocessing}).
4126
4127 @item -gnatef
4128 @cindex @option{-gnatef} (@command{gcc})
4129 Display full source path name in brief error messages.
4130
4131 @item -gnateG
4132 @cindex @option{-gnateG} (@command{gcc})
4133 Save result of preprocessing in a text file.
4134
4135 @item -gnatem=@var{path}
4136 @cindex @option{-gnatem} (@command{gcc})
4137 Specify a mapping file
4138 @ifclear vms
4139 (the equal sign is optional)
4140 @end ifclear
4141 (@pxref{Units to Sources Mapping Files}).
4142
4143 @item -gnatep=@var{file}
4144 @cindex @option{-gnatep} (@command{gcc})
4145 Specify a preprocessing data file
4146 @ifclear vms
4147 (the equal sign is optional)
4148 @end ifclear
4149 (@pxref{Integrated Preprocessing}).
4150
4151 @item -gnatE
4152 @cindex @option{-gnatE} (@command{gcc})
4153 Full dynamic elaboration checks.
4154
4155 @item -gnatf
4156 @cindex @option{-gnatf} (@command{gcc})
4157 Full errors. Multiple errors per line, all undefined references, do not
4158 attempt to suppress cascaded errors.
4159
4160 @item -gnatF
4161 @cindex @option{-gnatF} (@command{gcc})
4162 Externals names are folded to all uppercase.
4163
4164 @item ^-gnatg^/GNAT_INTERNAL^
4165 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4166 Internal GNAT implementation mode. This should not be used for
4167 applications programs, it is intended only for use by the compiler
4168 and its run-time library. For documentation, see the GNAT sources.
4169 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4170 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4171 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4172 so that all standard warnings and all standard style options are turned on.
4173 All warnings and style error messages are treated as errors.
4174
4175 @ifclear vms
4176 @item -gnatG=nn
4177 @cindex @option{-gnatG[nn]} (@command{gcc})
4178 @end ifclear
4179 @ifset vms
4180 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4181 @end ifset
4182 List generated expanded code in source form.
4183
4184 @item ^-gnath^/HELP^
4185 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4186 Output usage information. The output is written to @file{stdout}.
4187
4188 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4189 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4190 Identifier character set
4191 @ifclear vms
4192 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4193 @end ifclear
4194 For details of the possible selections for @var{c},
4195 see @ref{Character Set Control}.
4196
4197 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4198 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4199 Ignore representation clauses. When this switch is used,
4200 representation clauses are treated as comments. This is useful
4201 when initially porting code where you want to ignore rep clause
4202 problems, and also for compiling foreign code (particularly
4203 for use with ASIS). The representation clauses that are ignored
4204 are: enumeration_representation_clause, record_representation_clause,
4205 and attribute_definition_clause for the following attributes:
4206 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4207 Object_Size, Size, Small, Stream_Size, and Value_Size.
4208 Note that this option should be used only for compiling -- the
4209 code is likely to malfunction at run time.
4210
4211 @item -gnatjnn
4212 @cindex @option{-gnatjnn} (@command{gcc})
4213 Reformat error messages to fit on nn character lines
4214
4215 @item -gnatk=@var{n}
4216 @cindex @option{-gnatk} (@command{gcc})
4217 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4218
4219 @item -gnatl
4220 @cindex @option{-gnatl} (@command{gcc})
4221 Output full source listing with embedded error messages.
4222
4223 @item -gnatL
4224 @cindex @option{-gnatL} (@command{gcc})
4225 Used in conjunction with -gnatG or -gnatD to intersperse original
4226 source lines (as comment lines with line numbers) in the expanded
4227 source output.
4228
4229 @item -gnatm=@var{n}
4230 @cindex @option{-gnatm} (@command{gcc})
4231 Limit number of detected error or warning messages to @var{n}
4232 where @var{n} is in the range 1..999999. The default setting if
4233 no switch is given is 9999. If the number of warnings reaches this
4234 limit, then a message is output and further warnings are suppressed,
4235 but the compilation is continued. If the number of error messages
4236 reaches this limit, then a message is output and the compilation
4237 is abandoned. The equal sign here is optional. A value of zero
4238 means that no limit applies.
4239
4240 @item -gnatn
4241 @cindex @option{-gnatn} (@command{gcc})
4242 Activate inlining for subprograms for which
4243 pragma @code{inline} is specified. This inlining is performed
4244 by the GCC back-end.
4245
4246 @item -gnatN
4247 @cindex @option{-gnatN} (@command{gcc})
4248 Activate front end inlining for subprograms for which
4249 pragma @code{Inline} is specified. This inlining is performed
4250 by the front end and will be visible in the
4251 @option{-gnatG} output.
4252
4253 When using a gcc-based back end (in practice this means using any version
4254 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4255 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4256 Historically front end inlining was more extensive than the gcc back end
4257 inlining, but that is no longer the case.
4258
4259 @item -gnato
4260 @cindex @option{-gnato} (@command{gcc})
4261 Enable numeric overflow checking (which is not normally enabled by
4262 default). Note that division by zero is a separate check that is not
4263 controlled by this switch (division by zero checking is on by default).
4264
4265 @item -gnatp
4266 @cindex @option{-gnatp} (@command{gcc})
4267 Suppress all checks. See @ref{Run-Time Checks} for details.
4268
4269 @item -gnatP
4270 @cindex @option{-gnatP} (@command{gcc})
4271 Enable polling. This is required on some systems (notably Windows NT) to
4272 obtain asynchronous abort and asynchronous transfer of control capability.
4273 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4274 details.
4275
4276 @item -gnatq
4277 @cindex @option{-gnatq} (@command{gcc})
4278 Don't quit. Try semantics, even if parse errors.
4279
4280 @item -gnatQ
4281 @cindex @option{-gnatQ} (@command{gcc})
4282 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4283
4284 @item -gnatr
4285 @cindex @option{-gnatr} (@command{gcc})
4286 Treat pragma Restrictions as Restriction_Warnings.
4287
4288 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4289 @cindex @option{-gnatR} (@command{gcc})
4290 Output representation information for declared types and objects.
4291
4292 @item -gnats
4293 @cindex @option{-gnats} (@command{gcc})
4294 Syntax check only.
4295
4296 @item -gnatS
4297 @cindex @option{-gnatS} (@command{gcc})
4298 Print package Standard.
4299
4300 @item -gnatt
4301 @cindex @option{-gnatt} (@command{gcc})
4302 Generate tree output file.
4303
4304 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4305 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4306 All compiler tables start at @var{nnn} times usual starting size.
4307
4308 @item -gnatu
4309 @cindex @option{-gnatu} (@command{gcc})
4310 List units for this compilation.
4311
4312 @item -gnatU
4313 @cindex @option{-gnatU} (@command{gcc})
4314 Tag all error messages with the unique string ``error:''
4315
4316 @item -gnatv
4317 @cindex @option{-gnatv} (@command{gcc})
4318 Verbose mode. Full error output with source lines to @file{stdout}.
4319
4320 @item -gnatV
4321 @cindex @option{-gnatV} (@command{gcc})
4322 Control level of validity checking. See separate section describing
4323 this feature.
4324
4325 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4326 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4327 Warning mode where
4328 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4329 the exact warnings that
4330 are enabled or disabled (@pxref{Warning Message Control}).
4331
4332 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4333 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4334 Wide character encoding method
4335 @ifclear vms
4336 (@var{e}=n/h/u/s/e/8).
4337 @end ifclear
4338 @ifset vms
4339 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4340 @end ifset
4341
4342 @item -gnatx
4343 @cindex @option{-gnatx} (@command{gcc})
4344 Suppress generation of cross-reference information.
4345
4346 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4347 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4348 Enable built-in style checks (@pxref{Style Checking}).
4349
4350 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4351 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4352 Distribution stub generation and compilation
4353 @ifclear vms
4354 (@var{m}=r/c for receiver/caller stubs).
4355 @end ifclear
4356 @ifset vms
4357 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4358 to be generated and compiled).
4359 @end ifset
4360
4361 @item ^-I^/SEARCH=^@var{dir}
4362 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4363 @cindex RTL
4364 Direct GNAT to search the @var{dir} directory for source files needed by
4365 the current compilation
4366 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4367
4368 @item ^-I-^/NOCURRENT_DIRECTORY^
4369 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4370 @cindex RTL
4371 Except for the source file named in the command line, do not look for source
4372 files in the directory containing the source file named in the command line
4373 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4374
4375 @ifclear vms
4376 @item -mbig-switch
4377 @cindex @option{-mbig-switch} (@command{gcc})
4378 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4379 This standard gcc switch causes the compiler to use larger offsets in its
4380 jump table representation for @code{case} statements.
4381 This may result in less efficient code, but is sometimes necessary
4382 (for example on HP-UX targets)
4383 @cindex HP-UX and @option{-mbig-switch} option
4384 in order to compile large and/or nested @code{case} statements.
4385
4386 @item -o @var{file}
4387 @cindex @option{-o} (@command{gcc})
4388 This switch is used in @command{gcc} to redirect the generated object file
4389 and its associated ALI file. Beware of this switch with GNAT, because it may
4390 cause the object file and ALI file to have different names which in turn
4391 may confuse the binder and the linker.
4392 @end ifclear
4393
4394 @item -nostdinc
4395 @cindex @option{-nostdinc} (@command{gcc})
4396 Inhibit the search of the default location for the GNAT Run Time
4397 Library (RTL) source files.
4398
4399 @item -nostdlib
4400 @cindex @option{-nostdlib} (@command{gcc})
4401 Inhibit the search of the default location for the GNAT Run Time
4402 Library (RTL) ALI files.
4403
4404 @ifclear vms
4405 @item -O@ovar{n}
4406 @cindex @option{-O} (@command{gcc})
4407 @var{n} controls the optimization level.
4408
4409 @table @asis
4410 @item n = 0
4411 No optimization, the default setting if no @option{-O} appears
4412
4413 @item n = 1
4414 Normal optimization, the default if you specify @option{-O} without
4415 an operand. A good compromise between code quality and compilation
4416 time.
4417
4418 @item n = 2
4419 Extensive optimization, may improve execution time, possibly at the cost of
4420 substantially increased compilation time.
4421
4422 @item n = 3
4423 Same as @option{-O2}, and also includes inline expansion for small subprograms
4424 in the same unit.
4425
4426 @item n = s
4427 Optimize space usage
4428 @end table
4429
4430 @noindent
4431 See also @ref{Optimization Levels}.
4432 @end ifclear
4433
4434 @ifset vms
4435 @item /NOOPTIMIZE
4436 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4437 Equivalent to @option{/OPTIMIZE=NONE}.
4438 This is the default behavior in the absence of an @option{/OPTIMIZE}
4439 qualifier.
4440
4441 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4442 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4443 Selects the level of optimization for your program. The supported
4444 keywords are as follows:
4445 @table @code
4446 @item ALL
4447 Perform most optimizations, including those that
4448 are expensive.
4449 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4450 without keyword options.
4451
4452 @item NONE
4453 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4454
4455 @item SOME
4456 Perform some optimizations, but omit ones that are costly.
4457
4458 @item DEVELOPMENT
4459 Same as @code{SOME}.
4460
4461 @item INLINING
4462 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4463 automatic inlining of small subprograms within a unit
4464
4465 @item UNROLL_LOOPS
4466 Try to unroll loops. This keyword may be specified together with
4467 any keyword above other than @code{NONE}. Loop unrolling
4468 usually, but not always, improves the performance of programs.
4469
4470 @item SPACE
4471 Optimize space usage
4472 @end table
4473
4474 @noindent
4475 See also @ref{Optimization Levels}.
4476 @end ifset
4477
4478 @ifclear vms
4479 @item -pass-exit-codes
4480 @cindex @option{-pass-exit-codes} (@command{gcc})
4481 Catch exit codes from the compiler and use the most meaningful as
4482 exit status.
4483 @end ifclear
4484
4485 @item --RTS=@var{rts-path}
4486 @cindex @option{--RTS} (@command{gcc})
4487 Specifies the default location of the runtime library. Same meaning as the
4488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4489
4490 @item ^-S^/ASM^
4491 @cindex @option{^-S^/ASM^} (@command{gcc})
4492 ^Used in place of @option{-c} to^Used to^
4493 cause the assembler source file to be
4494 generated, using @file{^.s^.S^} as the extension,
4495 instead of the object file.
4496 This may be useful if you need to examine the generated assembly code.
4497
4498 @item ^-fverbose-asm^/VERBOSE_ASM^
4499 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4500 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4501 to cause the generated assembly code file to be annotated with variable
4502 names, making it significantly easier to follow.
4503
4504 @item ^-v^/VERBOSE^
4505 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4506 Show commands generated by the @command{gcc} driver. Normally used only for
4507 debugging purposes or if you need to be sure what version of the
4508 compiler you are executing.
4509
4510 @ifclear vms
4511 @item -V @var{ver}
4512 @cindex @option{-V} (@command{gcc})
4513 Execute @var{ver} version of the compiler. This is the @command{gcc}
4514 version, not the GNAT version.
4515 @end ifclear
4516
4517 @item ^-w^/NO_BACK_END_WARNINGS^
4518 @cindex @option{-w} (@command{gcc})
4519 Turn off warnings generated by the back end of the compiler. Use of
4520 this switch also causes the default for front end warnings to be set
4521 to suppress (as though @option{-gnatws} had appeared at the start of
4522 the options).
4523
4524 @end table
4525
4526 @ifclear vms
4527 @c Combining qualifiers does not work on VMS
4528 You may combine a sequence of GNAT switches into a single switch. For
4529 example, the combined switch
4530
4531 @cindex Combining GNAT switches
4532 @smallexample
4533 -gnatofi3
4534 @end smallexample
4535
4536 @noindent
4537 is equivalent to specifying the following sequence of switches:
4538
4539 @smallexample
4540 -gnato -gnatf -gnati3
4541 @end smallexample
4542 @end ifclear
4543
4544 @noindent
4545 The following restrictions apply to the combination of switches
4546 in this manner:
4547
4548 @itemize @bullet
4549 @item
4550 The switch @option{-gnatc} if combined with other switches must come
4551 first in the string.
4552
4553 @item
4554 The switch @option{-gnats} if combined with other switches must come
4555 first in the string.
4556
4557 @item
4558 The switches
4559 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4560 may not be combined with any other switches.
4561
4562 @ifclear vms
4563 @item
4564 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4565 switch), then all further characters in the switch are interpreted
4566 as style modifiers (see description of @option{-gnaty}).
4567
4568 @item
4569 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4570 switch), then all further characters in the switch are interpreted
4571 as debug flags (see description of @option{-gnatd}).
4572
4573 @item
4574 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4575 switch), then all further characters in the switch are interpreted
4576 as warning mode modifiers (see description of @option{-gnatw}).
4577
4578 @item
4579 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4580 switch), then all further characters in the switch are interpreted
4581 as validity checking options (see description of @option{-gnatV}).
4582 @end ifclear
4583 @end itemize
4584
4585 @node Output and Error Message Control
4586 @subsection Output and Error Message Control
4587 @findex stderr
4588
4589 @noindent
4590 The standard default format for error messages is called ``brief format''.
4591 Brief format messages are written to @file{stderr} (the standard error
4592 file) and have the following form:
4593
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:4:20: ";" should be "is"
4597 @end smallexample
4598
4599 @noindent
4600 The first integer after the file name is the line number in the file,
4601 and the second integer is the column number within the line.
4602 @ifclear vms
4603 @code{GPS} can parse the error messages
4604 and point to the referenced character.
4605 @end ifclear
4606 The following switches provide control over the error message
4607 format:
4608
4609 @table @option
4610 @c !sort!
4611 @item -gnatv
4612 @cindex @option{-gnatv} (@command{gcc})
4613 @findex stdout
4614 @ifclear vms
4615 The v stands for verbose.
4616 @end ifclear
4617 The effect of this setting is to write long-format error
4618 messages to @file{stdout} (the standard output file.
4619 The same program compiled with the
4620 @option{-gnatv} switch would generate:
4621
4622 @smallexample
4623 @cartouche
4624 3. funcion X (Q : Integer)
4625 |
4626 >>> Incorrect spelling of keyword "function"
4627 4. return Integer;
4628 |
4629 >>> ";" should be "is"
4630 @end cartouche
4631 @end smallexample
4632
4633 @noindent
4634 The vertical bar indicates the location of the error, and the @samp{>>>}
4635 prefix can be used to search for error messages. When this switch is
4636 used the only source lines output are those with errors.
4637
4638 @item -gnatl
4639 @cindex @option{-gnatl} (@command{gcc})
4640 @ifclear vms
4641 The @code{l} stands for list.
4642 @end ifclear
4643 This switch causes a full listing of
4644 the file to be generated. In the case where a body is
4645 compiled, the corresponding spec is also listed, along
4646 with any subunits. Typical output from compiling a package
4647 body @file{p.adb} might look like:
4648
4649 @smallexample @c ada
4650 @cartouche
4651 Compiling: p.adb
4652
4653 1. package body p is
4654 2. procedure a;
4655 3. procedure a is separate;
4656 4. begin
4657 5. null
4658 |
4659 >>> missing ";"
4660
4661 6. end;
4662
4663 Compiling: p.ads
4664
4665 1. package p is
4666 2. pragma Elaborate_Body
4667 |
4668 >>> missing ";"
4669
4670 3. end p;
4671
4672 Compiling: p-a.adb
4673
4674 1. separate p
4675 |
4676 >>> missing "("
4677
4678 2. procedure a is
4679 3. begin
4680 4. null
4681 |
4682 >>> missing ";"
4683
4684 5. end;
4685 @end cartouche
4686 @end smallexample
4687
4688 @noindent
4689 @findex stderr
4690 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4691 standard output is redirected, a brief summary is written to
4692 @file{stderr} (standard error) giving the number of error messages and
4693 warning messages generated.
4694
4695 @item -^gnatl^OUTPUT_FILE^=file
4696 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4697 This has the same effect as @option{-gnatl} except that the output is
4698 written to a file instead of to standard output. If the given name
4699 @file{fname} does not start with a period, then it is the full name
4700 of the file to be written. If @file{fname} is an extension, it is
4701 appended to the name of the file being compiled. For example, if
4702 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4703 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4704
4705 @item -gnatU
4706 @cindex @option{-gnatU} (@command{gcc})
4707 This switch forces all error messages to be preceded by the unique
4708 string ``error:''. This means that error messages take a few more
4709 characters in space, but allows easy searching for and identification
4710 of error messages.
4711
4712 @item -gnatb
4713 @cindex @option{-gnatb} (@command{gcc})
4714 @ifclear vms
4715 The @code{b} stands for brief.
4716 @end ifclear
4717 This switch causes GNAT to generate the
4718 brief format error messages to @file{stderr} (the standard error
4719 file) as well as the verbose
4720 format message or full listing (which as usual is written to
4721 @file{stdout} (the standard output file).
4722
4723 @item -gnatm=@var{n}
4724 @cindex @option{-gnatm} (@command{gcc})
4725 @ifclear vms
4726 The @code{m} stands for maximum.
4727 @end ifclear
4728 @var{n} is a decimal integer in the
4729 range of 1 to 999999 and limits the number of error or warning
4730 messages to be generated. For example, using
4731 @option{-gnatm2} might yield
4732
4733 @smallexample
4734 e.adb:3:04: Incorrect spelling of keyword "function"
4735 e.adb:5:35: missing ".."
4736 fatal error: maximum number of errors detected
4737 compilation abandoned
4738 @end smallexample
4739
4740 @noindent
4741 The default setting if
4742 no switch is given is 9999. If the number of warnings reaches this
4743 limit, then a message is output and further warnings are suppressed,
4744 but the compilation is continued. If the number of error messages
4745 reaches this limit, then a message is output and the compilation
4746 is abandoned. A value of zero means that no limit applies.
4747
4748 @noindent
4749 Note that the equal sign is optional, so the switches
4750 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4751
4752 @item -gnatf
4753 @cindex @option{-gnatf} (@command{gcc})
4754 @cindex Error messages, suppressing
4755 @ifclear vms
4756 The @code{f} stands for full.
4757 @end ifclear
4758 Normally, the compiler suppresses error messages that are likely to be
4759 redundant. This switch causes all error
4760 messages to be generated. In particular, in the case of
4761 references to undefined variables. If a given variable is referenced
4762 several times, the normal format of messages is
4763 @smallexample
4764 e.adb:7:07: "V" is undefined (more references follow)
4765 @end smallexample
4766
4767 @noindent
4768 where the parenthetical comment warns that there are additional
4769 references to the variable @code{V}. Compiling the same program with the
4770 @option{-gnatf} switch yields
4771
4772 @smallexample
4773 e.adb:7:07: "V" is undefined
4774 e.adb:8:07: "V" is undefined
4775 e.adb:8:12: "V" is undefined
4776 e.adb:8:16: "V" is undefined
4777 e.adb:9:07: "V" is undefined
4778 e.adb:9:12: "V" is undefined
4779 @end smallexample
4780
4781 @noindent
4782 The @option{-gnatf} switch also generates additional information for
4783 some error messages. Some examples are:
4784
4785 @itemize @bullet
4786 @item
4787 Full details on entities not available in high integrity mode
4788 @item
4789 Details on possibly non-portable unchecked conversion
4790 @item
4791 List possible interpretations for ambiguous calls
4792 @item
4793 Additional details on incorrect parameters
4794 @end itemize
4795
4796 @item -gnatjnn
4797 @cindex @option{-gnatjnn} (@command{gcc})
4798 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4799 with continuation lines are treated as though the continuation lines were
4800 separate messages (and so a warning with two continuation lines counts as
4801 three warnings, and is listed as three separate messages).
4802
4803 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4804 messages are output in a different manner. A message and all its continuation
4805 lines are treated as a unit, and count as only one warning or message in the
4806 statistics totals. Furthermore, the message is reformatted so that no line
4807 is longer than nn characters.
4808
4809 @item -gnatq
4810 @cindex @option{-gnatq} (@command{gcc})
4811 @ifclear vms
4812 The @code{q} stands for quit (really ``don't quit'').
4813 @end ifclear
4814 In normal operation mode, the compiler first parses the program and
4815 determines if there are any syntax errors. If there are, appropriate
4816 error messages are generated and compilation is immediately terminated.
4817 This switch tells
4818 GNAT to continue with semantic analysis even if syntax errors have been
4819 found. This may enable the detection of more errors in a single run. On
4820 the other hand, the semantic analyzer is more likely to encounter some
4821 internal fatal error when given a syntactically invalid tree.
4822
4823 @item -gnatQ
4824 @cindex @option{-gnatQ} (@command{gcc})
4825 In normal operation mode, the @file{ALI} file is not generated if any
4826 illegalities are detected in the program. The use of @option{-gnatQ} forces
4827 generation of the @file{ALI} file. This file is marked as being in
4828 error, so it cannot be used for binding purposes, but it does contain
4829 reasonably complete cross-reference information, and thus may be useful
4830 for use by tools (e.g., semantic browsing tools or integrated development
4831 environments) that are driven from the @file{ALI} file. This switch
4832 implies @option{-gnatq}, since the semantic phase must be run to get a
4833 meaningful ALI file.
4834
4835 In addition, if @option{-gnatt} is also specified, then the tree file is
4836 generated even if there are illegalities. It may be useful in this case
4837 to also specify @option{-gnatq} to ensure that full semantic processing
4838 occurs. The resulting tree file can be processed by ASIS, for the purpose
4839 of providing partial information about illegal units, but if the error
4840 causes the tree to be badly malformed, then ASIS may crash during the
4841 analysis.
4842
4843 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4844 being in error, @command{gnatmake} will attempt to recompile the source when it
4845 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4846
4847 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4848 since ALI files are never generated if @option{-gnats} is set.
4849
4850 @end table
4851
4852 @node Warning Message Control
4853 @subsection Warning Message Control
4854 @cindex Warning messages
4855 @noindent
4856 In addition to error messages, which correspond to illegalities as defined
4857 in the Ada Reference Manual, the compiler detects two kinds of warning
4858 situations.
4859
4860 First, the compiler considers some constructs suspicious and generates a
4861 warning message to alert you to a possible error. Second, if the
4862 compiler detects a situation that is sure to raise an exception at
4863 run time, it generates a warning message. The following shows an example
4864 of warning messages:
4865 @smallexample
4866 e.adb:4:24: warning: creation of object may raise Storage_Error
4867 e.adb:10:17: warning: static value out of range
4868 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4869 @end smallexample
4870
4871 @noindent
4872 GNAT considers a large number of situations as appropriate
4873 for the generation of warning messages. As always, warnings are not
4874 definite indications of errors. For example, if you do an out-of-range
4875 assignment with the deliberate intention of raising a
4876 @code{Constraint_Error} exception, then the warning that may be
4877 issued does not indicate an error. Some of the situations for which GNAT
4878 issues warnings (at least some of the time) are given in the following
4879 list. This list is not complete, and new warnings are often added to
4880 subsequent versions of GNAT. The list is intended to give a general idea
4881 of the kinds of warnings that are generated.
4882
4883 @itemize @bullet
4884 @item
4885 Possible infinitely recursive calls
4886
4887 @item
4888 Out-of-range values being assigned
4889
4890 @item
4891 Possible order of elaboration problems
4892
4893 @item
4894 Assertions (pragma Assert) that are sure to fail
4895
4896 @item
4897 Unreachable code
4898
4899 @item
4900 Address clauses with possibly unaligned values, or where an attempt is
4901 made to overlay a smaller variable with a larger one.
4902
4903 @item
4904 Fixed-point type declarations with a null range
4905
4906 @item
4907 Direct_IO or Sequential_IO instantiated with a type that has access values
4908
4909 @item
4910 Variables that are never assigned a value
4911
4912 @item
4913 Variables that are referenced before being initialized
4914
4915 @item
4916 Task entries with no corresponding @code{accept} statement
4917
4918 @item
4919 Duplicate accepts for the same task entry in a @code{select}
4920
4921 @item
4922 Objects that take too much storage
4923
4924 @item
4925 Unchecked conversion between types of differing sizes
4926
4927 @item
4928 Missing @code{return} statement along some execution path in a function
4929
4930 @item
4931 Incorrect (unrecognized) pragmas
4932
4933 @item
4934 Incorrect external names
4935
4936 @item
4937 Allocation from empty storage pool
4938
4939 @item
4940 Potentially blocking operation in protected type
4941
4942 @item
4943 Suspicious parenthesization of expressions
4944
4945 @item
4946 Mismatching bounds in an aggregate
4947
4948 @item
4949 Attempt to return local value by reference
4950
4951 @item
4952 Premature instantiation of a generic body
4953
4954 @item
4955 Attempt to pack aliased components
4956
4957 @item
4958 Out of bounds array subscripts
4959
4960 @item
4961 Wrong length on string assignment
4962
4963 @item
4964 Violations of style rules if style checking is enabled
4965
4966 @item
4967 Unused @code{with} clauses
4968
4969 @item
4970 @code{Bit_Order} usage that does not have any effect
4971
4972 @item
4973 @code{Standard.Duration} used to resolve universal fixed expression
4974
4975 @item
4976 Dereference of possibly null value
4977
4978 @item
4979 Declaration that is likely to cause storage error
4980
4981 @item
4982 Internal GNAT unit @code{with}'ed by application unit
4983
4984 @item
4985 Values known to be out of range at compile time
4986
4987 @item
4988 Unreferenced labels and variables
4989
4990 @item
4991 Address overlays that could clobber memory
4992
4993 @item
4994 Unexpected initialization when address clause present
4995
4996 @item
4997 Bad alignment for address clause
4998
4999 @item
5000 Useless type conversions
5001
5002 @item
5003 Redundant assignment statements and other redundant constructs
5004
5005 @item
5006 Useless exception handlers
5007
5008 @item
5009 Accidental hiding of name by child unit
5010
5011 @item
5012 Access before elaboration detected at compile time
5013
5014 @item
5015 A range in a @code{for} loop that is known to be null or might be null
5016
5017 @end itemize
5018
5019 @noindent
5020 The following section lists compiler switches that are available
5021 to control the handling of warning messages. It is also possible
5022 to exercise much finer control over what warnings are issued and
5023 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5024 gnat_rm, GNAT Reference manual}.
5025
5026 @table @option
5027 @c !sort!
5028 @item -gnatwa
5029 @emph{Activate all optional errors.}
5030 @cindex @option{-gnatwa} (@command{gcc})
5031 This switch activates most optional warning messages, see remaining list
5032 in this section for details on optional warning messages that can be
5033 individually controlled. The warnings that are not turned on by this
5034 switch are
5035 @option{-gnatwd} (implicit dereferencing),
5036 @option{-gnatwh} (hiding),
5037 @option{-gnatwl} (elaboration warnings),
5038 @option{-gnatw.o} (warn on values set by out parameters ignored)
5039 and @option{-gnatwt} (tracking of deleted conditional code).
5040 All other optional warnings are turned on.
5041
5042 @item -gnatwA
5043 @emph{Suppress all optional errors.}
5044 @cindex @option{-gnatwA} (@command{gcc})
5045 This switch suppresses all optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled.
5048
5049 @item -gnatw.a
5050 @emph{Activate warnings on failing assertions.}
5051 @cindex @option{-gnatw.a} (@command{gcc})
5052 @cindex Assert failures
5053 This switch activates warnings for assertions where the compiler can tell at
5054 compile time that the assertion will fail. Note that this warning is given
5055 even if assertions are disabled. The default is that such warnings are
5056 generated.
5057
5058 @item -gnatw.A
5059 @emph{Suppress warnings on failing assertions.}
5060 @cindex @option{-gnatw.A} (@command{gcc})
5061 @cindex Assert failures
5062 This switch suppresses warnings for assertions where the compiler can tell at
5063 compile time that the assertion will fail.
5064
5065 @item -gnatwb
5066 @emph{Activate warnings on bad fixed values.}
5067 @cindex @option{-gnatwb} (@command{gcc})
5068 @cindex Bad fixed values
5069 @cindex Fixed-point Small value
5070 @cindex Small value
5071 This switch activates warnings for static fixed-point expressions whose
5072 value is not an exact multiple of Small. Such values are implementation
5073 dependent, since an implementation is free to choose either of the multiples
5074 that surround the value. GNAT always chooses the closer one, but this is not
5075 required behavior, and it is better to specify a value that is an exact
5076 multiple, ensuring predictable execution. The default is that such warnings
5077 are not generated.
5078
5079 @item -gnatwB
5080 @emph{Suppress warnings on bad fixed values.}
5081 @cindex @option{-gnatwB} (@command{gcc})
5082 This switch suppresses warnings for static fixed-point expressions whose
5083 value is not an exact multiple of Small.
5084
5085 @item -gnatw.b
5086 @emph{Activate warnings on biased representation.}
5087 @cindex @option{-gnatw.b} (@command{gcc})
5088 @cindex Biased representation
5089 This switch activates warnings when a size clause, value size clause, component
5090 clause, or component size clause forces the use of biased representation for an
5091 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5092 to represent 10/11). The default is that such warnings are generated.
5093
5094 @item -gnatw.B
5095 @emph{Suppress warnings on biased representation.}
5096 @cindex @option{-gnatwB} (@command{gcc})
5097 This switch suppresses warnings for representation clauses that force the use
5098 of biased representation.
5099
5100 @item -gnatwc
5101 @emph{Activate warnings on conditionals.}
5102 @cindex @option{-gnatwc} (@command{gcc})
5103 @cindex Conditionals, constant
5104 This switch activates warnings for conditional expressions used in
5105 tests that are known to be True or False at compile time. The default
5106 is that such warnings are not generated.
5107 Note that this warning does
5108 not get issued for the use of boolean variables or constants whose
5109 values are known at compile time, since this is a standard technique
5110 for conditional compilation in Ada, and this would generate too many
5111 false positive warnings.
5112
5113 This warning option also activates a special test for comparisons using
5114 the operators ``>='' and`` <=''.
5115 If the compiler can tell that only the equality condition is possible,
5116 then it will warn that the ``>'' or ``<'' part of the test
5117 is useless and that the operator could be replaced by ``=''.
5118 An example would be comparing a @code{Natural} variable <= 0.
5119
5120 This warning option also generates warnings if
5121 one or both tests is optimized away in a membership test for integer
5122 values if the result can be determined at compile time. Range tests on
5123 enumeration types are not included, since it is common for such tests
5124 to include an end point.
5125
5126 This warning can also be turned on using @option{-gnatwa}.
5127
5128 @item -gnatwC
5129 @emph{Suppress warnings on conditionals.}
5130 @cindex @option{-gnatwC} (@command{gcc})
5131 This switch suppresses warnings for conditional expressions used in
5132 tests that are known to be True or False at compile time.
5133
5134 @item -gnatw.c
5135 @emph{Activate warnings on missing component clauses.}
5136 @cindex @option{-gnatw.c} (@command{gcc})
5137 @cindex Component clause, missing
5138 This switch activates warnings for record components where a record
5139 representation clause is present and has component clauses for the
5140 majority, but not all, of the components. A warning is given for each
5141 component for which no component clause is present.
5142
5143 This warning can also be turned on using @option{-gnatwa}.
5144
5145 @item -gnatw.C
5146 @emph{Suppress warnings on missing component clauses.}
5147 @cindex @option{-gnatwC} (@command{gcc})
5148 This switch suppresses warnings for record components that are
5149 missing a component clause in the situation described above.
5150
5151 @item -gnatwd
5152 @emph{Activate warnings on implicit dereferencing.}
5153 @cindex @option{-gnatwd} (@command{gcc})
5154 If this switch is set, then the use of a prefix of an access type
5155 in an indexed component, slice, or selected component without an
5156 explicit @code{.all} will generate a warning. With this warning
5157 enabled, access checks occur only at points where an explicit
5158 @code{.all} appears in the source code (assuming no warnings are
5159 generated as a result of this switch). The default is that such
5160 warnings are not generated.
5161 Note that @option{-gnatwa} does not affect the setting of
5162 this warning option.
5163
5164 @item -gnatwD
5165 @emph{Suppress warnings on implicit dereferencing.}
5166 @cindex @option{-gnatwD} (@command{gcc})
5167 @cindex Implicit dereferencing
5168 @cindex Dereferencing, implicit
5169 This switch suppresses warnings for implicit dereferences in
5170 indexed components, slices, and selected components.
5171
5172 @item -gnatwe
5173 @emph{Treat warnings as errors.}
5174 @cindex @option{-gnatwe} (@command{gcc})
5175 @cindex Warnings, treat as error
5176 This switch causes warning messages to be treated as errors.
5177 The warning string still appears, but the warning messages are counted
5178 as errors, and prevent the generation of an object file.
5179
5180 @item -gnatw.e
5181 @emph{Activate every optional warning}
5182 @cindex @option{-gnatw.e} (@command{gcc})
5183 @cindex Warnings, activate every optional warning
5184 This switch activates all optional warnings, including those which
5185 are not activated by @code{-gnatwa}.
5186
5187 @item -gnatwf
5188 @emph{Activate warnings on unreferenced formals.}
5189 @cindex @option{-gnatwf} (@command{gcc})
5190 @cindex Formals, unreferenced
5191 This switch causes a warning to be generated if a formal parameter
5192 is not referenced in the body of the subprogram. This warning can
5193 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5194 default is that these warnings are not generated.
5195
5196 @item -gnatwF
5197 @emph{Suppress warnings on unreferenced formals.}
5198 @cindex @option{-gnatwF} (@command{gcc})
5199 This switch suppresses warnings for unreferenced formal
5200 parameters. Note that the
5201 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5202 effect of warning on unreferenced entities other than subprogram
5203 formals.
5204
5205 @item -gnatwg
5206 @emph{Activate warnings on unrecognized pragmas.}
5207 @cindex @option{-gnatwg} (@command{gcc})
5208 @cindex Pragmas, unrecognized
5209 This switch causes a warning to be generated if an unrecognized
5210 pragma is encountered. Apart from issuing this warning, the
5211 pragma is ignored and has no effect. This warning can
5212 also be turned on using @option{-gnatwa}. The default
5213 is that such warnings are issued (satisfying the Ada Reference
5214 Manual requirement that such warnings appear).
5215
5216 @item -gnatwG
5217 @emph{Suppress warnings on unrecognized pragmas.}
5218 @cindex @option{-gnatwG} (@command{gcc})
5219 This switch suppresses warnings for unrecognized pragmas.
5220
5221 @item -gnatwh
5222 @emph{Activate warnings on hiding.}
5223 @cindex @option{-gnatwh} (@command{gcc})
5224 @cindex Hiding of Declarations
5225 This switch activates warnings on hiding declarations.
5226 A declaration is considered hiding
5227 if it is for a non-overloadable entity, and it declares an entity with the
5228 same name as some other entity that is directly or use-visible. The default
5229 is that such warnings are not generated.
5230 Note that @option{-gnatwa} does not affect the setting of this warning option.
5231
5232 @item -gnatwH
5233 @emph{Suppress warnings on hiding.}
5234 @cindex @option{-gnatwH} (@command{gcc})
5235 This switch suppresses warnings on hiding declarations.
5236
5237 @item -gnatwi
5238 @emph{Activate warnings on implementation units.}
5239 @cindex @option{-gnatwi} (@command{gcc})
5240 This switch activates warnings for a @code{with} of an internal GNAT
5241 implementation unit, defined as any unit from the @code{Ada},
5242 @code{Interfaces}, @code{GNAT},
5243 ^^@code{DEC},^ or @code{System}
5244 hierarchies that is not
5245 documented in either the Ada Reference Manual or the GNAT
5246 Programmer's Reference Manual. Such units are intended only
5247 for internal implementation purposes and should not be @code{with}'ed
5248 by user programs. The default is that such warnings are generated
5249 This warning can also be turned on using @option{-gnatwa}.
5250
5251 @item -gnatwI
5252 @emph{Disable warnings on implementation units.}
5253 @cindex @option{-gnatwI} (@command{gcc})
5254 This switch disables warnings for a @code{with} of an internal GNAT
5255 implementation unit.
5256
5257 @item -gnatwj
5258 @emph{Activate warnings on obsolescent features (Annex J).}
5259 @cindex @option{-gnatwj} (@command{gcc})
5260 @cindex Features, obsolescent
5261 @cindex Obsolescent features
5262 If this warning option is activated, then warnings are generated for
5263 calls to subprograms marked with @code{pragma Obsolescent} and
5264 for use of features in Annex J of the Ada Reference Manual. In the
5265 case of Annex J, not all features are flagged. In particular use
5266 of the renamed packages (like @code{Text_IO}) and use of package
5267 @code{ASCII} are not flagged, since these are very common and
5268 would generate many annoying positive warnings. The default is that
5269 such warnings are not generated. This warning is also turned on by
5270 the use of @option{-gnatwa}.
5271
5272 In addition to the above cases, warnings are also generated for
5273 GNAT features that have been provided in past versions but which
5274 have been superseded (typically by features in the new Ada standard).
5275 For example, @code{pragma Ravenscar} will be flagged since its
5276 function is replaced by @code{pragma Profile(Ravenscar)}.
5277
5278 Note that this warning option functions differently from the
5279 restriction @code{No_Obsolescent_Features} in two respects.
5280 First, the restriction applies only to annex J features.
5281 Second, the restriction does flag uses of package @code{ASCII}.
5282
5283 @item -gnatwJ
5284 @emph{Suppress warnings on obsolescent features (Annex J).}
5285 @cindex @option{-gnatwJ} (@command{gcc})
5286 This switch disables warnings on use of obsolescent features.
5287
5288 @item -gnatwk
5289 @emph{Activate warnings on variables that could be constants.}
5290 @cindex @option{-gnatwk} (@command{gcc})
5291 This switch activates warnings for variables that are initialized but
5292 never modified, and then could be declared constants. The default is that
5293 such warnings are not given.
5294 This warning can also be turned on using @option{-gnatwa}.
5295
5296 @item -gnatwK
5297 @emph{Suppress warnings on variables that could be constants.}
5298 @cindex @option{-gnatwK} (@command{gcc})
5299 This switch disables warnings on variables that could be declared constants.
5300
5301 @item -gnatwl
5302 @emph{Activate warnings for elaboration pragmas.}
5303 @cindex @option{-gnatwl} (@command{gcc})
5304 @cindex Elaboration, warnings
5305 This switch activates warnings on missing
5306 @code{Elaborate_All} and @code{Elaborate} pragmas.
5307 See the section in this guide on elaboration checking for details on
5308 when such pragmas should be used. In dynamic elaboration mode, this switch
5309 generations warnings about the need to add elaboration pragmas. Note however,
5310 that if you blindly follow these warnings, and add @code{Elaborate_All}
5311 warnings wherever they are recommended, you basically end up with the
5312 equivalent of the static elaboration model, which may not be what you want for
5313 legacy code for which the static model does not work.
5314
5315 For the static model, the messages generated are labeled "info:" (for
5316 information messages). They are not warnings to add elaboration pragmas,
5317 merely informational messages showing what implicit elaboration pragmas
5318 have been added, for use in analyzing elaboration circularity problems.
5319
5320 Warnings are also generated if you
5321 are using the static mode of elaboration, and a @code{pragma Elaborate}
5322 is encountered. The default is that such warnings
5323 are not generated.
5324 This warning is not automatically turned on by the use of @option{-gnatwa}.
5325
5326 @item -gnatwL
5327 @emph{Suppress warnings for elaboration pragmas.}
5328 @cindex @option{-gnatwL} (@command{gcc})
5329 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5330 See the section in this guide on elaboration checking for details on
5331 when such pragmas should be used.
5332
5333 @item -gnatwm
5334 @emph{Activate warnings on modified but unreferenced variables.}
5335 @cindex @option{-gnatwm} (@command{gcc})
5336 This switch activates warnings for variables that are assigned (using
5337 an initialization value or with one or more assignment statements) but
5338 whose value is never read. The warning is suppressed for volatile
5339 variables and also for variables that are renamings of other variables
5340 or for which an address clause is given.
5341 This warning can also be turned on using @option{-gnatwa}.
5342 The default is that these warnings are not given.
5343
5344 @item -gnatwM
5345 @emph{Disable warnings on modified but unreferenced variables.}
5346 @cindex @option{-gnatwM} (@command{gcc})
5347 This switch disables warnings for variables that are assigned or
5348 initialized, but never read.
5349
5350 @item -gnatwn
5351 @emph{Set normal warnings mode.}
5352 @cindex @option{-gnatwn} (@command{gcc})
5353 This switch sets normal warning mode, in which enabled warnings are
5354 issued and treated as warnings rather than errors. This is the default
5355 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5356 an explicit @option{-gnatws} or
5357 @option{-gnatwe}. It also cancels the effect of the
5358 implicit @option{-gnatwe} that is activated by the
5359 use of @option{-gnatg}.
5360
5361 @item -gnatwo
5362 @emph{Activate warnings on address clause overlays.}
5363 @cindex @option{-gnatwo} (@command{gcc})
5364 @cindex Address Clauses, warnings
5365 This switch activates warnings for possibly unintended initialization
5366 effects of defining address clauses that cause one variable to overlap
5367 another. The default is that such warnings are generated.
5368 This warning can also be turned on using @option{-gnatwa}.
5369
5370 @item -gnatwO
5371 @emph{Suppress warnings on address clause overlays.}
5372 @cindex @option{-gnatwO} (@command{gcc})
5373 This switch suppresses warnings on possibly unintended initialization
5374 effects of defining address clauses that cause one variable to overlap
5375 another.
5376
5377 @item -gnatw.o
5378 @emph{Activate warnings on modified but unreferenced out parameters.}
5379 @cindex @option{-gnatw.o} (@command{gcc})
5380 This switch activates warnings for variables that are modified by using
5381 them as actuals for a call to a procedure with an out mode formal, where
5382 the resulting assigned value is never read. It is applicable in the case
5383 where there is more than one out mode formal. If there is only one out
5384 mode formal, the warning is issued by default (controlled by -gnatwu).
5385 The warning is suppressed for volatile
5386 variables and also for variables that are renamings of other variables
5387 or for which an address clause is given.
5388 The default is that these warnings are not given. Note that this warning
5389 is not included in -gnatwa, it must be activated explicitly.
5390
5391 @item -gnatw.O
5392 @emph{Disable warnings on modified but unreferenced out parameters.}
5393 @cindex @option{-gnatw.O} (@command{gcc})
5394 This switch suppresses warnings for variables that are modified by using
5395 them as actuals for a call to a procedure with an out mode formal, where
5396 the resulting assigned value is never read.
5397
5398 @item -gnatwp
5399 @emph{Activate warnings on ineffective pragma Inlines.}
5400 @cindex @option{-gnatwp} (@command{gcc})
5401 @cindex Inlining, warnings
5402 This switch activates warnings for failure of front end inlining
5403 (activated by @option{-gnatN}) to inline a particular call. There are
5404 many reasons for not being able to inline a call, including most
5405 commonly that the call is too complex to inline. The default is
5406 that such warnings are not given.
5407 This warning can also be turned on using @option{-gnatwa}.
5408 Warnings on ineffective inlining by the gcc back-end can be activated
5409 separately, using the gcc switch -Winline.
5410
5411 @item -gnatwP
5412 @emph{Suppress warnings on ineffective pragma Inlines.}
5413 @cindex @option{-gnatwP} (@command{gcc})
5414 This switch suppresses warnings on ineffective pragma Inlines. If the
5415 inlining mechanism cannot inline a call, it will simply ignore the
5416 request silently.
5417
5418 @item -gnatw.p
5419 @emph{Activate warnings on parameter ordering.}
5420 @cindex @option{-gnatw.p} (@command{gcc})
5421 @cindex Parameter order, warnings
5422 This switch activates warnings for cases of suspicious parameter
5423 ordering when the list of arguments are all simple identifiers that
5424 match the names of the formals, but are in a different order. The
5425 warning is suppressed if any use of named parameter notation is used,
5426 so this is the appropriate way to suppress a false positive (and
5427 serves to emphasize that the "misordering" is deliberate). The
5428 default is
5429 that such warnings are not given.
5430 This warning can also be turned on using @option{-gnatwa}.
5431
5432 @item -gnatw.P
5433 @emph{Suppress warnings on parameter ordering.}
5434 @cindex @option{-gnatw.P} (@command{gcc})
5435 This switch suppresses warnings on cases of suspicious parameter
5436 ordering.
5437
5438 @item -gnatwq
5439 @emph{Activate warnings on questionable missing parentheses.}
5440 @cindex @option{-gnatwq} (@command{gcc})
5441 @cindex Parentheses, warnings
5442 This switch activates warnings for cases where parentheses are not used and
5443 the result is potential ambiguity from a readers point of view. For example
5444 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5445 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5446 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5447 follow the rule of always parenthesizing to make the association clear, and
5448 this warning switch warns if such parentheses are not present. The default
5449 is that these warnings are given.
5450 This warning can also be turned on using @option{-gnatwa}.
5451
5452 @item -gnatwQ
5453 @emph{Suppress warnings on questionable missing parentheses.}
5454 @cindex @option{-gnatwQ} (@command{gcc})
5455 This switch suppresses warnings for cases where the association is not
5456 clear and the use of parentheses is preferred.
5457
5458 @item -gnatwr
5459 @emph{Activate warnings on redundant constructs.}
5460 @cindex @option{-gnatwr} (@command{gcc})
5461 This switch activates warnings for redundant constructs. The following
5462 is the current list of constructs regarded as redundant:
5463
5464 @itemize @bullet
5465 @item
5466 Assignment of an item to itself.
5467 @item
5468 Type conversion that converts an expression to its own type.
5469 @item
5470 Use of the attribute @code{Base} where @code{typ'Base} is the same
5471 as @code{typ}.
5472 @item
5473 Use of pragma @code{Pack} when all components are placed by a record
5474 representation clause.
5475 @item
5476 Exception handler containing only a reraise statement (raise with no
5477 operand) which has no effect.
5478 @item
5479 Use of the operator abs on an operand that is known at compile time
5480 to be non-negative
5481 @item
5482 Comparison of boolean expressions to an explicit True value.
5483 @end itemize
5484
5485 This warning can also be turned on using @option{-gnatwa}.
5486 The default is that warnings for redundant constructs are not given.
5487
5488 @item -gnatwR
5489 @emph{Suppress warnings on redundant constructs.}
5490 @cindex @option{-gnatwR} (@command{gcc})
5491 This switch suppresses warnings for redundant constructs.
5492
5493 @item -gnatw.r
5494 @emph{Activate warnings for object renaming function.}
5495 @cindex @option{-gnatw.r} (@command{gcc})
5496 This switch activates warnings for an object renaming that renames a
5497 function call, which is equivalent to a constant declaration (as
5498 opposed to renaming the function itself). The default is that these
5499 warnings are given. This warning can also be turned on using
5500 @option{-gnatwa}.
5501
5502 @item -gnatw.R
5503 @emph{Suppress warnings for object renaming function.}
5504 @cindex @option{-gnatwT} (@command{gcc})
5505 This switch suppresses warnings for object renaming function.
5506
5507 @item -gnatws
5508 @emph{Suppress all warnings.}
5509 @cindex @option{-gnatws} (@command{gcc})
5510 This switch completely suppresses the
5511 output of all warning messages from the GNAT front end.
5512 Note that it does not suppress warnings from the @command{gcc} back end.
5513 To suppress these back end warnings as well, use the switch @option{-w}
5514 in addition to @option{-gnatws}.
5515
5516 @item -gnatwt
5517 @emph{Activate warnings for tracking of deleted conditional code.}
5518 @cindex @option{-gnatwt} (@command{gcc})
5519 @cindex Deactivated code, warnings
5520 @cindex Deleted code, warnings
5521 This switch activates warnings for tracking of code in conditionals (IF and
5522 CASE statements) that is detected to be dead code which cannot be executed, and
5523 which is removed by the front end. This warning is off by default, and is not
5524 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5525 useful for detecting deactivated code in certified applications.
5526
5527 @item -gnatwT
5528 @emph{Suppress warnings for tracking of deleted conditional code.}
5529 @cindex @option{-gnatwT} (@command{gcc})
5530 This switch suppresses warnings for tracking of deleted conditional code.
5531
5532 @item -gnatwu
5533 @emph{Activate warnings on unused entities.}
5534 @cindex @option{-gnatwu} (@command{gcc})
5535 This switch activates warnings to be generated for entities that
5536 are declared but not referenced, and for units that are @code{with}'ed
5537 and not
5538 referenced. In the case of packages, a warning is also generated if
5539 no entities in the package are referenced. This means that if the package
5540 is referenced but the only references are in @code{use}
5541 clauses or @code{renames}
5542 declarations, a warning is still generated. A warning is also generated
5543 for a generic package that is @code{with}'ed but never instantiated.
5544 In the case where a package or subprogram body is compiled, and there
5545 is a @code{with} on the corresponding spec
5546 that is only referenced in the body,
5547 a warning is also generated, noting that the
5548 @code{with} can be moved to the body. The default is that
5549 such warnings are not generated.
5550 This switch also activates warnings on unreferenced formals
5551 (it includes the effect of @option{-gnatwf}).
5552 This warning can also be turned on using @option{-gnatwa}.
5553
5554 @item -gnatwU
5555 @emph{Suppress warnings on unused entities.}
5556 @cindex @option{-gnatwU} (@command{gcc})
5557 This switch suppresses warnings for unused entities and packages.
5558 It also turns off warnings on unreferenced formals (and thus includes
5559 the effect of @option{-gnatwF}).
5560
5561 @item -gnatwv
5562 @emph{Activate warnings on unassigned variables.}
5563 @cindex @option{-gnatwv} (@command{gcc})
5564 @cindex Unassigned variable warnings
5565 This switch activates warnings for access to variables which
5566 may not be properly initialized. The default is that
5567 such warnings are generated.
5568 This warning can also be turned on using @option{-gnatwa}.
5569
5570 @item -gnatwV
5571 @emph{Suppress warnings on unassigned variables.}
5572 @cindex @option{-gnatwV} (@command{gcc})
5573 This switch suppresses warnings for access to variables which
5574 may not be properly initialized.
5575 For variables of a composite type, the warning can also be suppressed in
5576 Ada 2005 by using a default initialization with a box. For example, if
5577 Table is an array of records whose components are only partially uninitialized,
5578 then the following code:
5579
5580 @smallexample @c ada
5581 Tab : Table := (others => <>);
5582 @end smallexample
5583
5584 will suppress warnings on subsequent statements that access components
5585 of variable Tab.
5586
5587 @item -gnatww
5588 @emph{Activate warnings on wrong low bound assumption.}
5589 @cindex @option{-gnatww} (@command{gcc})
5590 @cindex String indexing warnings
5591 This switch activates warnings for indexing an unconstrained string parameter
5592 with a literal or S'Length. This is a case where the code is assuming that the
5593 low bound is one, which is in general not true (for example when a slice is
5594 passed). The default is that such warnings are generated.
5595 This warning can also be turned on using @option{-gnatwa}.
5596
5597 @item -gnatwW
5598 @emph{Suppress warnings on wrong low bound assumption.}
5599 @cindex @option{-gnatwW} (@command{gcc})
5600 This switch suppresses warnings for indexing an unconstrained string parameter
5601 with a literal or S'Length. Note that this warning can also be suppressed
5602 in a particular case by adding an
5603 assertion that the lower bound is 1,
5604 as shown in the following example.
5605
5606 @smallexample @c ada
5607 procedure K (S : String) is
5608 pragma Assert (S'First = 1);
5609 @dots{}
5610 @end smallexample
5611
5612 @item -gnatw.w
5613 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5614 @cindex @option{-gnatw.w} (@command{gcc})
5615 @cindex Warnings Off control
5616 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5617 where either the pragma is entirely useless (because it suppresses no
5618 warnings), or it could be replaced by @code{pragma Unreferenced} or
5619 @code{pragma Unmodified}.The default is that these warnings are not given.
5620 Note that this warning is not included in -gnatwa, it must be
5621 activated explicitly.
5622
5623 @item -gnatw.W
5624 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5625 @cindex @option{-gnatw.W} (@command{gcc})
5626 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5627
5628 @item -gnatwx
5629 @emph{Activate warnings on Export/Import pragmas.}
5630 @cindex @option{-gnatwx} (@command{gcc})
5631 @cindex Export/Import pragma warnings
5632 This switch activates warnings on Export/Import pragmas when
5633 the compiler detects a possible conflict between the Ada and
5634 foreign language calling sequences. For example, the use of
5635 default parameters in a convention C procedure is dubious
5636 because the C compiler cannot supply the proper default, so
5637 a warning is issued. The default is that such warnings are
5638 generated.
5639 This warning can also be turned on using @option{-gnatwa}.
5640
5641 @item -gnatwX
5642 @emph{Suppress warnings on Export/Import pragmas.}
5643 @cindex @option{-gnatwX} (@command{gcc})
5644 This switch suppresses warnings on Export/Import pragmas.
5645 The sense of this is that you are telling the compiler that
5646 you know what you are doing in writing the pragma, and it
5647 should not complain at you.
5648
5649 @item -gnatw.x
5650 @emph{Activate warnings for No_Exception_Propagation mode.}
5651 @cindex @option{-gnatwm} (@command{gcc})
5652 This switch activates warnings for exception usage when pragma Restrictions
5653 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5654 explicit exception raises which are not covered by a local handler, and for
5655 exception handlers which do not cover a local raise. The default is that these
5656 warnings are not given.
5657
5658 @item -gnatw.X
5659 @emph{Disable warnings for No_Exception_Propagation mode.}
5660 This switch disables warnings for exception usage when pragma Restrictions
5661 (No_Exception_Propagation) is in effect.
5662
5663 @item -gnatwy
5664 @emph{Activate warnings for Ada 2005 compatibility issues.}
5665 @cindex @option{-gnatwy} (@command{gcc})
5666 @cindex Ada 2005 compatibility issues warnings
5667 For the most part Ada 2005 is upwards compatible with Ada 95,
5668 but there are some exceptions (for example the fact that
5669 @code{interface} is now a reserved word in Ada 2005). This
5670 switch activates several warnings to help in identifying
5671 and correcting such incompatibilities. The default is that
5672 these warnings are generated. Note that at one point Ada 2005
5673 was called Ada 0Y, hence the choice of character.
5674 This warning can also be turned on using @option{-gnatwa}.
5675
5676 @item -gnatwY
5677 @emph{Disable warnings for Ada 2005 compatibility issues.}
5678 @cindex @option{-gnatwY} (@command{gcc})
5679 @cindex Ada 2005 compatibility issues warnings
5680 This switch suppresses several warnings intended to help in identifying
5681 incompatibilities between Ada 95 and Ada 2005.
5682
5683 @item -gnatwz
5684 @emph{Activate warnings on unchecked conversions.}
5685 @cindex @option{-gnatwz} (@command{gcc})
5686 @cindex Unchecked_Conversion warnings
5687 This switch activates warnings for unchecked conversions
5688 where the types are known at compile time to have different
5689 sizes. The default
5690 is that such warnings are generated. Warnings are also
5691 generated for subprogram pointers with different conventions,
5692 and, on VMS only, for data pointers with different conventions.
5693 This warning can also be turned on using @option{-gnatwa}.
5694
5695 @item -gnatwZ
5696 @emph{Suppress warnings on unchecked conversions.}
5697 @cindex @option{-gnatwZ} (@command{gcc})
5698 This switch suppresses warnings for unchecked conversions
5699 where the types are known at compile time to have different
5700 sizes or conventions.
5701
5702 @item ^-Wunused^WARNINGS=UNUSED^
5703 @cindex @option{-Wunused}
5704 The warnings controlled by the @option{-gnatw} switch are generated by
5705 the front end of the compiler. The @option{GCC} back end can provide
5706 additional warnings and they are controlled by the @option{-W} switch.
5707 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5708 warnings for entities that are declared but not referenced.
5709
5710 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5711 @cindex @option{-Wuninitialized}
5712 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5713 the back end warning for uninitialized variables. This switch must be
5714 used in conjunction with an optimization level greater than zero.
5715
5716 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5717 @cindex @option{-Wall}
5718 This switch enables all the above warnings from the @option{GCC} back end.
5719 The code generator detects a number of warning situations that are missed
5720 by the @option{GNAT} front end, and this switch can be used to activate them.
5721 The use of this switch also sets the default front end warning mode to
5722 @option{-gnatwa}, that is, most front end warnings activated as well.
5723
5724 @item ^-w^/NO_BACK_END_WARNINGS^
5725 @cindex @option{-w}
5726 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5727 The use of this switch also sets the default front end warning mode to
5728 @option{-gnatws}, that is, front end warnings suppressed as well.
5729
5730 @end table
5731
5732 @noindent
5733 @ifclear vms
5734 A string of warning parameters can be used in the same parameter. For example:
5735
5736 @smallexample
5737 -gnatwaLe
5738 @end smallexample
5739
5740 @noindent
5741 will turn on all optional warnings except for elaboration pragma warnings,
5742 and also specify that warnings should be treated as errors.
5743 @end ifclear
5744 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5745
5746 @table @option
5747 @c !sort!
5748 @item -gnatwC
5749 @item -gnatwD
5750 @item -gnatwF
5751 @item -gnatwg
5752 @item -gnatwH
5753 @item -gnatwi
5754 @item -gnatwJ
5755 @item -gnatwK
5756 @item -gnatwL
5757 @item -gnatwM
5758 @item -gnatwn
5759 @item -gnatwo
5760 @item -gnatwP
5761 @item -gnatwR
5762 @item -gnatwU
5763 @item -gnatwv
5764 @item -gnatwz
5765 @item -gnatwx
5766
5767 @end table
5768
5769 @node Debugging and Assertion Control
5770 @subsection Debugging and Assertion Control
5771
5772 @table @option
5773 @item -gnata
5774 @cindex @option{-gnata} (@command{gcc})
5775 @findex Assert
5776 @findex Debug
5777 @cindex Assertions
5778
5779 @noindent
5780 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5781 are ignored. This switch, where @samp{a} stands for assert, causes
5782 @code{Assert} and @code{Debug} pragmas to be activated.
5783
5784 The pragmas have the form:
5785
5786 @smallexample
5787 @cartouche
5788 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5789 @var{static-string-expression}@r{]})
5790 @b{pragma} Debug (@var{procedure call})
5791 @end cartouche
5792 @end smallexample
5793
5794 @noindent
5795 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5796 If the result is @code{True}, the pragma has no effect (other than
5797 possible side effects from evaluating the expression). If the result is
5798 @code{False}, the exception @code{Assert_Failure} declared in the package
5799 @code{System.Assertions} is
5800 raised (passing @var{static-string-expression}, if present, as the
5801 message associated with the exception). If no string expression is
5802 given the default is a string giving the file name and line number
5803 of the pragma.
5804
5805 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5806 @code{pragma Debug} may appear within a declaration sequence, allowing
5807 debugging procedures to be called between declarations.
5808
5809 @ifset vms
5810 @item /DEBUG@r{[}=debug-level@r{]}
5811 @itemx /NODEBUG
5812 Specifies how much debugging information is to be included in
5813 the resulting object file where 'debug-level' is one of the following:
5814 @table @code
5815 @item TRACEBACK
5816 Include both debugger symbol records and traceback
5817 the object file.
5818 This is the default setting.
5819 @item ALL
5820 Include both debugger symbol records and traceback in
5821 object file.
5822 @item NONE
5823 Excludes both debugger symbol records and traceback
5824 the object file. Same as /NODEBUG.
5825 @item SYMBOLS
5826 Includes only debugger symbol records in the object
5827 file. Note that this doesn't include traceback information.
5828 @end table
5829 @end ifset
5830 @end table
5831
5832 @node Validity Checking
5833 @subsection Validity Checking
5834 @findex Validity Checking
5835
5836 @noindent
5837 The Ada Reference Manual has specific requirements for checking
5838 for invalid values. In particular, RM 13.9.1 requires that the
5839 evaluation of invalid values (for example from unchecked conversions),
5840 not result in erroneous execution. In GNAT, the result of such an
5841 evaluation in normal default mode is to either use the value
5842 unmodified, or to raise Constraint_Error in those cases where use
5843 of the unmodified value would cause erroneous execution. The cases
5844 where unmodified values might lead to erroneous execution are case
5845 statements (where a wild jump might result from an invalid value),
5846 and subscripts on the left hand side (where memory corruption could
5847 occur as a result of an invalid value).
5848
5849 The @option{-gnatB} switch tells the compiler to assume that all
5850 values are valid (that is, within their declared subtype range)
5851 except in the context of a use of the Valid attribute. This means
5852 the compiler can generate more efficient code, since the range
5853 of values is better known at compile time.
5854
5855 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5856 checking mode.
5857 @ifclear vms
5858 The @code{x} argument is a string of letters that
5859 indicate validity checks that are performed or not performed in addition
5860 to the default checks described above.
5861 @end ifclear
5862 @ifset vms
5863 The options allowed for this qualifier
5864 indicate validity checks that are performed or not performed in addition
5865 to the default checks described above.
5866 @end ifset
5867
5868 @table @option
5869 @c !sort!
5870 @item -gnatVa
5871 @emph{All validity checks.}
5872 @cindex @option{-gnatVa} (@command{gcc})
5873 All validity checks are turned on.
5874 @ifclear vms
5875 That is, @option{-gnatVa} is
5876 equivalent to @option{gnatVcdfimorst}.
5877 @end ifclear
5878
5879 @item -gnatVc
5880 @emph{Validity checks for copies.}
5881 @cindex @option{-gnatVc} (@command{gcc})
5882 The right hand side of assignments, and the initializing values of
5883 object declarations are validity checked.
5884
5885 @item -gnatVd
5886 @emph{Default (RM) validity checks.}
5887 @cindex @option{-gnatVd} (@command{gcc})
5888 Some validity checks are done by default following normal Ada semantics
5889 (RM 13.9.1 (9-11)).
5890 A check is done in case statements that the expression is within the range
5891 of the subtype. If it is not, Constraint_Error is raised.
5892 For assignments to array components, a check is done that the expression used
5893 as index is within the range. If it is not, Constraint_Error is raised.
5894 Both these validity checks may be turned off using switch @option{-gnatVD}.
5895 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5896 switch @option{-gnatVd} will leave the checks turned on.
5897 Switch @option{-gnatVD} should be used only if you are sure that all such
5898 expressions have valid values. If you use this switch and invalid values
5899 are present, then the program is erroneous, and wild jumps or memory
5900 overwriting may occur.
5901
5902 @item -gnatVe
5903 @emph{Validity checks for elementary components.}
5904 @cindex @option{-gnatVe} (@command{gcc})
5905 In the absence of this switch, assignments to record or array components are
5906 not validity checked, even if validity checks for assignments generally
5907 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5908 require valid data, but assignment of individual components does. So for
5909 example, there is a difference between copying the elements of an array with a
5910 slice assignment, compared to assigning element by element in a loop. This
5911 switch allows you to turn off validity checking for components, even when they
5912 are assigned component by component.
5913
5914 @item -gnatVf
5915 @emph{Validity checks for floating-point values.}
5916 @cindex @option{-gnatVf} (@command{gcc})
5917 In the absence of this switch, validity checking occurs only for discrete
5918 values. If @option{-gnatVf} is specified, then validity checking also applies
5919 for floating-point values, and NaNs and infinities are considered invalid,
5920 as well as out of range values for constrained types. Note that this means
5921 that standard IEEE infinity mode is not allowed. The exact contexts
5922 in which floating-point values are checked depends on the setting of other
5923 options. For example,
5924 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5925 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5926 (the order does not matter) specifies that floating-point parameters of mode
5927 @code{in} should be validity checked.
5928
5929 @item -gnatVi
5930 @emph{Validity checks for @code{in} mode parameters}
5931 @cindex @option{-gnatVi} (@command{gcc})
5932 Arguments for parameters of mode @code{in} are validity checked in function
5933 and procedure calls at the point of call.
5934
5935 @item -gnatVm
5936 @emph{Validity checks for @code{in out} mode parameters.}
5937 @cindex @option{-gnatVm} (@command{gcc})
5938 Arguments for parameters of mode @code{in out} are validity checked in
5939 procedure calls at the point of call. The @code{'m'} here stands for
5940 modify, since this concerns parameters that can be modified by the call.
5941 Note that there is no specific option to test @code{out} parameters,
5942 but any reference within the subprogram will be tested in the usual
5943 manner, and if an invalid value is copied back, any reference to it
5944 will be subject to validity checking.
5945
5946 @item -gnatVn
5947 @emph{No validity checks.}
5948 @cindex @option{-gnatVn} (@command{gcc})
5949 This switch turns off all validity checking, including the default checking
5950 for case statements and left hand side subscripts. Note that the use of
5951 the switch @option{-gnatp} suppresses all run-time checks, including
5952 validity checks, and thus implies @option{-gnatVn}. When this switch
5953 is used, it cancels any other @option{-gnatV} previously issued.
5954
5955 @item -gnatVo
5956 @emph{Validity checks for operator and attribute operands.}
5957 @cindex @option{-gnatVo} (@command{gcc})
5958 Arguments for predefined operators and attributes are validity checked.
5959 This includes all operators in package @code{Standard},
5960 the shift operators defined as intrinsic in package @code{Interfaces}
5961 and operands for attributes such as @code{Pos}. Checks are also made
5962 on individual component values for composite comparisons, and on the
5963 expressions in type conversions and qualified expressions. Checks are
5964 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5965
5966 @item -gnatVp
5967 @emph{Validity checks for parameters.}
5968 @cindex @option{-gnatVp} (@command{gcc})
5969 This controls the treatment of parameters within a subprogram (as opposed
5970 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5971 of parameters on a call. If either of these call options is used, then
5972 normally an assumption is made within a subprogram that the input arguments
5973 have been validity checking at the point of call, and do not need checking
5974 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5975 is not made, and parameters are not assumed to be valid, so their validity
5976 will be checked (or rechecked) within the subprogram.
5977
5978 @item -gnatVr
5979 @emph{Validity checks for function returns.}
5980 @cindex @option{-gnatVr} (@command{gcc})
5981 The expression in @code{return} statements in functions is validity
5982 checked.
5983
5984 @item -gnatVs
5985 @emph{Validity checks for subscripts.}
5986 @cindex @option{-gnatVs} (@command{gcc})
5987 All subscripts expressions are checked for validity, whether they appear
5988 on the right side or left side (in default mode only left side subscripts
5989 are validity checked).
5990
5991 @item -gnatVt
5992 @emph{Validity checks for tests.}
5993 @cindex @option{-gnatVt} (@command{gcc})
5994 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5995 statements are checked, as well as guard expressions in entry calls.
5996
5997 @end table
5998
5999 @noindent
6000 The @option{-gnatV} switch may be followed by
6001 ^a string of letters^a list of options^
6002 to turn on a series of validity checking options.
6003 For example,
6004 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6005 specifies that in addition to the default validity checking, copies and
6006 function return expressions are to be validity checked.
6007 In order to make it easier
6008 to specify the desired combination of effects,
6009 @ifclear vms
6010 the upper case letters @code{CDFIMORST} may
6011 be used to turn off the corresponding lower case option.
6012 @end ifclear
6013 @ifset vms
6014 the prefix @code{NO} on an option turns off the corresponding validity
6015 checking:
6016 @itemize @bullet
6017 @item @code{NOCOPIES}
6018 @item @code{NODEFAULT}
6019 @item @code{NOFLOATS}
6020 @item @code{NOIN_PARAMS}
6021 @item @code{NOMOD_PARAMS}
6022 @item @code{NOOPERANDS}
6023 @item @code{NORETURNS}
6024 @item @code{NOSUBSCRIPTS}
6025 @item @code{NOTESTS}
6026 @end itemize
6027 @end ifset
6028 Thus
6029 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6030 turns on all validity checking options except for
6031 checking of @code{@b{in out}} procedure arguments.
6032
6033 The specification of additional validity checking generates extra code (and
6034 in the case of @option{-gnatVa} the code expansion can be substantial).
6035 However, these additional checks can be very useful in detecting
6036 uninitialized variables, incorrect use of unchecked conversion, and other
6037 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6038 is useful in conjunction with the extra validity checking, since this
6039 ensures that wherever possible uninitialized variables have invalid values.
6040
6041 See also the pragma @code{Validity_Checks} which allows modification of
6042 the validity checking mode at the program source level, and also allows for
6043 temporary disabling of validity checks.
6044
6045 @node Style Checking
6046 @subsection Style Checking
6047 @findex Style checking
6048
6049 @noindent
6050 The @option{-gnaty^x^(option,option,@dots{})^} switch
6051 @cindex @option{-gnaty} (@command{gcc})
6052 causes the compiler to
6053 enforce specified style rules. A limited set of style rules has been used
6054 in writing the GNAT sources themselves. This switch allows user programs
6055 to activate all or some of these checks. If the source program fails a
6056 specified style check, an appropriate warning message is given, preceded by
6057 the character sequence ``(style)''.
6058 @ifset vms
6059 @code{(option,option,@dots{})} is a sequence of keywords
6060 @end ifset
6061 @ifclear vms
6062 The string @var{x} is a sequence of letters or digits
6063 @end ifclear
6064 indicating the particular style
6065 checks to be performed. The following checks are defined:
6066
6067 @table @option
6068 @c !sort!
6069 @item 0-9
6070 @emph{Specify indentation level.}
6071 If a digit from 1-9 appears
6072 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6073 then proper indentation is checked, with the digit indicating the
6074 indentation level required. A value of zero turns off this style check.
6075 The general style of required indentation is as specified by
6076 the examples in the Ada Reference Manual. Full line comments must be
6077 aligned with the @code{--} starting on a column that is a multiple of
6078 the alignment level, or they may be aligned the same way as the following
6079 non-blank line (this is useful when full line comments appear in the middle
6080 of a statement.
6081
6082 @item ^a^ATTRIBUTE^
6083 @emph{Check attribute casing.}
6084 Attribute names, including the case of keywords such as @code{digits}
6085 used as attributes names, must be written in mixed case, that is, the
6086 initial letter and any letter following an underscore must be uppercase.
6087 All other letters must be lowercase.
6088
6089 @item ^A^ARRAY_INDEXES^
6090 @emph{Use of array index numbers in array attributes.}
6091 When using the array attributes First, Last, Range,
6092 or Length, the index number must be omitted for one-dimensional arrays
6093 and is required for multi-dimensional arrays.
6094
6095 @item ^b^BLANKS^
6096 @emph{Blanks not allowed at statement end.}
6097 Trailing blanks are not allowed at the end of statements. The purpose of this
6098 rule, together with h (no horizontal tabs), is to enforce a canonical format
6099 for the use of blanks to separate source tokens.
6100
6101 @item ^c^COMMENTS^
6102 @emph{Check comments.}
6103 Comments must meet the following set of rules:
6104
6105 @itemize @bullet
6106
6107 @item
6108 The ``@code{--}'' that starts the column must either start in column one,
6109 or else at least one blank must precede this sequence.
6110
6111 @item
6112 Comments that follow other tokens on a line must have at least one blank
6113 following the ``@code{--}'' at the start of the comment.
6114
6115 @item
6116 Full line comments must have two blanks following the ``@code{--}'' that
6117 starts the comment, with the following exceptions.
6118
6119 @item
6120 A line consisting only of the ``@code{--}'' characters, possibly preceded
6121 by blanks is permitted.
6122
6123 @item
6124 A comment starting with ``@code{--x}'' where @code{x} is a special character
6125 is permitted.
6126 This allows proper processing of the output generated by specialized tools
6127 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6128 annotation
6129 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6130 special character is defined as being in one of the ASCII ranges
6131 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6132 Note that this usage is not permitted
6133 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6134
6135 @item
6136 A line consisting entirely of minus signs, possibly preceded by blanks, is
6137 permitted. This allows the construction of box comments where lines of minus
6138 signs are used to form the top and bottom of the box.
6139
6140 @item
6141 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6142 least one blank follows the initial ``@code{--}''. Together with the preceding
6143 rule, this allows the construction of box comments, as shown in the following
6144 example:
6145 @smallexample
6146 ---------------------------
6147 -- This is a box comment --
6148 -- with two text lines. --
6149 ---------------------------
6150 @end smallexample
6151 @end itemize
6152
6153 @item ^d^DOS_LINE_ENDINGS^
6154 @emph{Check no DOS line terminators present.}
6155 All lines must be terminated by a single ASCII.LF
6156 character (in particular the DOS line terminator sequence CR/LF is not
6157 allowed).
6158
6159 @item ^e^END^
6160 @emph{Check end/exit labels.}
6161 Optional labels on @code{end} statements ending subprograms and on
6162 @code{exit} statements exiting named loops, are required to be present.
6163
6164 @item ^f^VTABS^
6165 @emph{No form feeds or vertical tabs.}
6166 Neither form feeds nor vertical tab characters are permitted
6167 in the source text.
6168
6169 @item ^g^GNAT^
6170 @emph{GNAT style mode}
6171 The set of style check switches is set to match that used by the GNAT sources.
6172 This may be useful when developing code that is eventually intended to be
6173 incorporated into GNAT. For further details, see GNAT sources.
6174
6175 @item ^h^HTABS^
6176 @emph{No horizontal tabs.}
6177 Horizontal tab characters are not permitted in the source text.
6178 Together with the b (no blanks at end of line) check, this
6179 enforces a canonical form for the use of blanks to separate
6180 source tokens.
6181
6182 @item ^i^IF_THEN^
6183 @emph{Check if-then layout.}
6184 The keyword @code{then} must appear either on the same
6185 line as corresponding @code{if}, or on a line on its own, lined
6186 up under the @code{if} with at least one non-blank line in between
6187 containing all or part of the condition to be tested.
6188
6189 @item ^I^IN_MODE^
6190 @emph{check mode IN keywords}
6191 Mode @code{in} (the default mode) is not
6192 allowed to be given explicitly. @code{in out} is fine,
6193 but not @code{in} on its own.
6194
6195 @item ^k^KEYWORD^
6196 @emph{Check keyword casing.}
6197 All keywords must be in lower case (with the exception of keywords
6198 such as @code{digits} used as attribute names to which this check
6199 does not apply).
6200
6201 @item ^l^LAYOUT^
6202 @emph{Check layout.}
6203 Layout of statement and declaration constructs must follow the
6204 recommendations in the Ada Reference Manual, as indicated by the
6205 form of the syntax rules. For example an @code{else} keyword must
6206 be lined up with the corresponding @code{if} keyword.
6207
6208 There are two respects in which the style rule enforced by this check
6209 option are more liberal than those in the Ada Reference Manual. First
6210 in the case of record declarations, it is permissible to put the
6211 @code{record} keyword on the same line as the @code{type} keyword, and
6212 then the @code{end} in @code{end record} must line up under @code{type}.
6213 This is also permitted when the type declaration is split on two lines.
6214 For example, any of the following three layouts is acceptable:
6215
6216 @smallexample @c ada
6217 @cartouche
6218 type q is record
6219 a : integer;
6220 b : integer;
6221 end record;
6222
6223 type q is
6224 record
6225 a : integer;
6226 b : integer;
6227 end record;
6228
6229 type q is
6230 record
6231 a : integer;
6232 b : integer;
6233 end record;
6234
6235 @end cartouche
6236 @end smallexample
6237
6238 @noindent
6239 Second, in the case of a block statement, a permitted alternative
6240 is to put the block label on the same line as the @code{declare} or
6241 @code{begin} keyword, and then line the @code{end} keyword up under
6242 the block label. For example both the following are permitted:
6243
6244 @smallexample @c ada
6245 @cartouche
6246 Block : declare
6247 A : Integer := 3;
6248 begin
6249 Proc (A, A);
6250 end Block;
6251
6252 Block :
6253 declare
6254 A : Integer := 3;
6255 begin
6256 Proc (A, A);
6257 end Block;
6258 @end cartouche
6259 @end smallexample
6260
6261 @noindent
6262 The same alternative format is allowed for loops. For example, both of
6263 the following are permitted:
6264
6265 @smallexample @c ada
6266 @cartouche
6267 Clear : while J < 10 loop
6268 A (J) := 0;
6269 end loop Clear;
6270
6271 Clear :
6272 while J < 10 loop
6273 A (J) := 0;
6274 end loop Clear;
6275 @end cartouche
6276 @end smallexample
6277
6278 @item ^Lnnn^MAX_NESTING=nnn^
6279 @emph{Set maximum nesting level}
6280 The maximum level of nesting of constructs (including subprograms, loops,
6281 blocks, packages, and conditionals) may not exceed the given value
6282 @option{nnn}. A value of zero disconnects this style check.
6283
6284 @item ^m^LINE_LENGTH^
6285 @emph{Check maximum line length.}
6286 The length of source lines must not exceed 79 characters, including
6287 any trailing blanks. The value of 79 allows convenient display on an
6288 80 character wide device or window, allowing for possible special
6289 treatment of 80 character lines. Note that this count is of
6290 characters in the source text. This means that a tab character counts
6291 as one character in this count but a wide character sequence counts as
6292 a single character (however many bytes are needed in the encoding).
6293
6294 @item ^Mnnn^MAX_LENGTH=nnn^
6295 @emph{Set maximum line length.}
6296 The length of lines must not exceed the
6297 given value @option{nnn}. The maximum value that can be specified is 32767.
6298
6299 @item ^n^STANDARD_CASING^
6300 @emph{Check casing of entities in Standard.}
6301 Any identifier from Standard must be cased
6302 to match the presentation in the Ada Reference Manual (for example,
6303 @code{Integer} and @code{ASCII.NUL}).
6304
6305 @item ^N^NONE^
6306 @emph{Turn off all style checks}
6307 All style check options are turned off.
6308
6309 @item ^o^ORDERED_SUBPROGRAMS^
6310 @emph{Check order of subprogram bodies.}
6311 All subprogram bodies in a given scope
6312 (e.g.@: a package body) must be in alphabetical order. The ordering
6313 rule uses normal Ada rules for comparing strings, ignoring casing
6314 of letters, except that if there is a trailing numeric suffix, then
6315 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6316 before Junk10).
6317
6318 @item ^O^OVERRIDING_INDICATORS^
6319 @emph{Check that overriding subprograms are explicitly marked as such.}
6320 The declaration of a primitive operation of a type extension that overrides
6321 an inherited operation must carry an overriding indicator.
6322
6323 @item ^p^PRAGMA^
6324 @emph{Check pragma casing.}
6325 Pragma names must be written in mixed case, that is, the
6326 initial letter and any letter following an underscore must be uppercase.
6327 All other letters must be lowercase.
6328
6329 @item ^r^REFERENCES^
6330 @emph{Check references.}
6331 All identifier references must be cased in the same way as the
6332 corresponding declaration. No specific casing style is imposed on
6333 identifiers. The only requirement is for consistency of references
6334 with declarations.
6335
6336 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6337 @emph{Check no statements after THEN/ELSE.}
6338 No statements are allowed
6339 on the same line as a THEN or ELSE keyword following the
6340 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6341 and a special exception allows a pragma to appear after ELSE.
6342
6343 @item ^s^SPECS^
6344 @emph{Check separate specs.}
6345 Separate declarations (``specs'') are required for subprograms (a
6346 body is not allowed to serve as its own declaration). The only
6347 exception is that parameterless library level procedures are
6348 not required to have a separate declaration. This exception covers
6349 the most frequent form of main program procedures.
6350
6351 @item ^t^TOKEN^
6352 @emph{Check token spacing.}
6353 The following token spacing rules are enforced:
6354
6355 @itemize @bullet
6356
6357 @item
6358 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6359
6360 @item
6361 The token @code{=>} must be surrounded by spaces.
6362
6363 @item
6364 The token @code{<>} must be preceded by a space or a left parenthesis.
6365
6366 @item
6367 Binary operators other than @code{**} must be surrounded by spaces.
6368 There is no restriction on the layout of the @code{**} binary operator.
6369
6370 @item
6371 Colon must be surrounded by spaces.
6372
6373 @item
6374 Colon-equal (assignment, initialization) must be surrounded by spaces.
6375
6376 @item
6377 Comma must be the first non-blank character on the line, or be
6378 immediately preceded by a non-blank character, and must be followed
6379 by a space.
6380
6381 @item
6382 If the token preceding a left parenthesis ends with a letter or digit, then
6383 a space must separate the two tokens.
6384
6385 @item
6386 A right parenthesis must either be the first non-blank character on
6387 a line, or it must be preceded by a non-blank character.
6388
6389 @item
6390 A semicolon must not be preceded by a space, and must not be followed by
6391 a non-blank character.
6392
6393 @item
6394 A unary plus or minus may not be followed by a space.
6395
6396 @item
6397 A vertical bar must be surrounded by spaces.
6398 @end itemize
6399
6400 @item ^u^UNNECESSARY_BLANK_LINES^
6401 @emph{Check unnecessary blank lines.}
6402 Unnecessary blank lines are not allowed. A blank line is considered
6403 unnecessary if it appears at the end of the file, or if more than
6404 one blank line occurs in sequence.
6405
6406 @item ^x^XTRA_PARENS^
6407 @emph{Check extra parentheses.}
6408 Unnecessary extra level of parentheses (C-style) are not allowed
6409 around conditions in @code{if} statements, @code{while} statements and
6410 @code{exit} statements.
6411
6412 @item ^y^ALL_BUILTIN^
6413 @emph{Set all standard style check options}
6414 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6415 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6416 @option{-gnatyS}, @option{-gnatyLnnn},
6417 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6418
6419 @ifclear vms
6420 @item -
6421 @emph{Remove style check options}
6422 This causes any subsequent options in the string to act as canceling the
6423 corresponding style check option. To cancel maximum nesting level control,
6424 use @option{L} parameter witout any integer value after that, because any
6425 digit following @option{-} in the parameter string of the @option{-gnaty}
6426 option will be threated as canceling indentation check. The same is true
6427 for @option{M} parameter. @option{y} and @option{N} parameters are not
6428 allowed after @option{-}.
6429
6430 @item +
6431 This causes any subsequent options in the string to enable the corresponding
6432 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6433 if any.
6434 @end ifclear
6435
6436 @ifset vms
6437 @item NOxxx
6438 @emph{Removing style check options}
6439 If the name of a style check is preceded by @option{NO} then the corresponding
6440 style check is turned off. For example @option{NOCOMMENTS} turns off style
6441 checking for comments.
6442 @end ifset
6443 @end table
6444
6445 @noindent
6446 In the above rules, appearing in column one is always permitted, that is,
6447 counts as meeting either a requirement for a required preceding space,
6448 or as meeting a requirement for no preceding space.
6449
6450 Appearing at the end of a line is also always permitted, that is, counts
6451 as meeting either a requirement for a following space, or as meeting
6452 a requirement for no following space.
6453
6454 @noindent
6455 If any of these style rules is violated, a message is generated giving
6456 details on the violation. The initial characters of such messages are
6457 always ``@code{(style)}''. Note that these messages are treated as warning
6458 messages, so they normally do not prevent the generation of an object
6459 file. The @option{-gnatwe} switch can be used to treat warning messages,
6460 including style messages, as fatal errors.
6461
6462 The switch
6463 @ifclear vms
6464 @option{-gnaty} on its own (that is not
6465 followed by any letters or digits), then the effect is equivalent
6466 to the use of @option{-gnatyy}, as described above, that is all
6467 built-in standard style check options are enabled.
6468
6469 @end ifclear
6470 @ifset vms
6471 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6472 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6473 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6474 @end ifset
6475
6476
6477
6478 The switch
6479 @ifclear vms
6480 @option{-gnatyN}
6481 @end ifclear
6482 @ifset vms
6483 /STYLE_CHECKS=NONE
6484 @end ifset
6485 clears any previously set style checks.
6486
6487 @node Run-Time Checks
6488 @subsection Run-Time Checks
6489 @cindex Division by zero
6490 @cindex Access before elaboration
6491 @cindex Checks, division by zero
6492 @cindex Checks, access before elaboration
6493 @cindex Checks, stack overflow checking
6494
6495 @noindent
6496 By default, the following checks are suppressed: integer overflow
6497 checks, stack overflow checks, and checks for access before
6498 elaboration on subprogram calls. All other checks, including range
6499 checks and array bounds checks, are turned on by default. The
6500 following @command{gcc} switches refine this default behavior.
6501
6502 @table @option
6503 @c !sort!
6504 @item -gnatp
6505 @cindex @option{-gnatp} (@command{gcc})
6506 @cindex Suppressing checks
6507 @cindex Checks, suppressing
6508 @findex Suppress
6509 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6510 had been present in the source. Validity checks are also suppressed (in
6511 other words @option{-gnatp} also implies @option{-gnatVn}.
6512 Use this switch to improve the performance
6513 of the code at the expense of safety in the presence of invalid data or
6514 program bugs.
6515
6516 Note that when checks are suppressed, the compiler is allowed, but not
6517 required, to omit the checking code. If the run-time cost of the
6518 checking code is zero or near-zero, the compiler will generate it even
6519 if checks are suppressed. In particular, if the compiler can prove
6520 that a certain check will necessarily fail, it will generate code to
6521 do an unconditional ``raise'', even if checks are suppressed. The
6522 compiler warns in this case.
6523
6524 Of course, run-time checks are omitted whenever the compiler can prove
6525 that they will not fail, whether or not checks are suppressed.
6526
6527 Note that if you suppress a check that would have failed, program
6528 execution is erroneous, which means the behavior is totally
6529 unpredictable. The program might crash, or print wrong answers, or
6530 do anything else. It might even do exactly what you wanted it to do
6531 (and then it might start failing mysteriously next week or next
6532 year). The compiler will generate code based on the assumption that
6533 the condition being checked is true, which can result in disaster if
6534 that assumption is wrong.
6535
6536 @item -gnato
6537 @cindex @option{-gnato} (@command{gcc})
6538 @cindex Overflow checks
6539 @cindex Check, overflow
6540 Enables overflow checking for integer operations.
6541 This causes GNAT to generate slower and larger executable
6542 programs by adding code to check for overflow (resulting in raising
6543 @code{Constraint_Error} as required by standard Ada
6544 semantics). These overflow checks correspond to situations in which
6545 the true value of the result of an operation may be outside the base
6546 range of the result type. The following example shows the distinction:
6547
6548 @smallexample @c ada
6549 X1 : Integer := "Integer'Last";
6550 X2 : Integer range 1 .. 5 := "5";
6551 X3 : Integer := "Integer'Last";
6552 X4 : Integer range 1 .. 5 := "5";
6553 F : Float := "2.0E+20";
6554 @dots{}
6555 X1 := X1 + 1;
6556 X2 := X2 + 1;
6557 X3 := Integer (F);
6558 X4 := Integer (F);
6559 @end smallexample
6560
6561 @noindent
6562 Note that if explicit values are assigned at compile time, the
6563 compiler may be able to detect overflow at compile time, in which case
6564 no actual run-time checking code is required, and Constraint_Error
6565 will be raised unconditionally, with or without
6566 @option{-gnato}. That's why the assigned values in the above fragment
6567 are in quotes, the meaning is "assign a value not known to the
6568 compiler that happens to be equal to ...". The remaining discussion
6569 assumes that the compiler cannot detect the values at compile time.
6570
6571 Here the first addition results in a value that is outside the base range
6572 of Integer, and hence requires an overflow check for detection of the
6573 constraint error. Thus the first assignment to @code{X1} raises a
6574 @code{Constraint_Error} exception only if @option{-gnato} is set.
6575
6576 The second increment operation results in a violation of the explicit
6577 range constraint; such range checks are performed by default, and are
6578 unaffected by @option{-gnato}.
6579
6580 The two conversions of @code{F} both result in values that are outside
6581 the base range of type @code{Integer} and thus will raise
6582 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6583 The fact that the result of the second conversion is assigned to
6584 variable @code{X4} with a restricted range is irrelevant, since the problem
6585 is in the conversion, not the assignment.
6586
6587 Basically the rule is that in the default mode (@option{-gnato} not
6588 used), the generated code assures that all integer variables stay
6589 within their declared ranges, or within the base range if there is
6590 no declared range. This prevents any serious problems like indexes
6591 out of range for array operations.
6592
6593 What is not checked in default mode is an overflow that results in
6594 an in-range, but incorrect value. In the above example, the assignments
6595 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6596 range of the target variable, but the result is wrong in the sense that
6597 it is too large to be represented correctly. Typically the assignment
6598 to @code{X1} will result in wrap around to the largest negative number.
6599 The conversions of @code{F} will result in some @code{Integer} value
6600 and if that integer value is out of the @code{X4} range then the
6601 subsequent assignment would generate an exception.
6602
6603 @findex Machine_Overflows
6604 Note that the @option{-gnato} switch does not affect the code generated
6605 for any floating-point operations; it applies only to integer
6606 semantics).
6607 For floating-point, GNAT has the @code{Machine_Overflows}
6608 attribute set to @code{False} and the normal mode of operation is to
6609 generate IEEE NaN and infinite values on overflow or invalid operations
6610 (such as dividing 0.0 by 0.0).
6611
6612 The reason that we distinguish overflow checking from other kinds of
6613 range constraint checking is that a failure of an overflow check, unlike
6614 for example the failure of a range check, can result in an incorrect
6615 value, but cannot cause random memory destruction (like an out of range
6616 subscript), or a wild jump (from an out of range case value). Overflow
6617 checking is also quite expensive in time and space, since in general it
6618 requires the use of double length arithmetic.
6619
6620 Note again that @option{-gnato} is off by default, so overflow checking is
6621 not performed in default mode. This means that out of the box, with the
6622 default settings, GNAT does not do all the checks expected from the
6623 language description in the Ada Reference Manual. If you want all constraint
6624 checks to be performed, as described in this Manual, then you must
6625 explicitly use the -gnato switch either on the @command{gnatmake} or
6626 @command{gcc} command.
6627
6628 @item -gnatE
6629 @cindex @option{-gnatE} (@command{gcc})
6630 @cindex Elaboration checks
6631 @cindex Check, elaboration
6632 Enables dynamic checks for access-before-elaboration
6633 on subprogram calls and generic instantiations.
6634 Note that @option{-gnatE} is not necessary for safety, because in the
6635 default mode, GNAT ensures statically that the checks would not fail.
6636 For full details of the effect and use of this switch,
6637 @xref{Compiling Using gcc}.
6638
6639 @item -fstack-check
6640 @cindex @option{-fstack-check} (@command{gcc})
6641 @cindex Stack Overflow Checking
6642 @cindex Checks, stack overflow checking
6643 Activates stack overflow checking. For full details of the effect and use of
6644 this switch see @ref{Stack Overflow Checking}.
6645 @end table
6646
6647 @findex Unsuppress
6648 @noindent
6649 The setting of these switches only controls the default setting of the
6650 checks. You may modify them using either @code{Suppress} (to remove
6651 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6652 the program source.
6653
6654 @node Using gcc for Syntax Checking
6655 @subsection Using @command{gcc} for Syntax Checking
6656 @table @option
6657 @item -gnats
6658 @cindex @option{-gnats} (@command{gcc})
6659 @ifclear vms
6660
6661 @noindent
6662 The @code{s} stands for ``syntax''.
6663 @end ifclear
6664
6665 Run GNAT in syntax checking only mode. For
6666 example, the command
6667
6668 @smallexample
6669 $ gcc -c -gnats x.adb
6670 @end smallexample
6671
6672 @noindent
6673 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6674 series of files in a single command
6675 @ifclear vms
6676 , and can use wild cards to specify such a group of files.
6677 Note that you must specify the @option{-c} (compile
6678 only) flag in addition to the @option{-gnats} flag.
6679 @end ifclear
6680 .
6681 You may use other switches in conjunction with @option{-gnats}. In
6682 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6683 format of any generated error messages.
6684
6685 When the source file is empty or contains only empty lines and/or comments,
6686 the output is a warning:
6687
6688 @smallexample
6689 $ gcc -c -gnats -x ada toto.txt
6690 toto.txt:1:01: warning: empty file, contains no compilation units
6691 $
6692 @end smallexample
6693
6694 Otherwise, the output is simply the error messages, if any. No object file or
6695 ALI file is generated by a syntax-only compilation. Also, no units other
6696 than the one specified are accessed. For example, if a unit @code{X}
6697 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6698 check only mode does not access the source file containing unit
6699 @code{Y}.
6700
6701 @cindex Multiple units, syntax checking
6702 Normally, GNAT allows only a single unit in a source file. However, this
6703 restriction does not apply in syntax-check-only mode, and it is possible
6704 to check a file containing multiple compilation units concatenated
6705 together. This is primarily used by the @code{gnatchop} utility
6706 (@pxref{Renaming Files Using gnatchop}).
6707 @end table
6708
6709 @node Using gcc for Semantic Checking
6710 @subsection Using @command{gcc} for Semantic Checking
6711 @table @option
6712 @item -gnatc
6713 @cindex @option{-gnatc} (@command{gcc})
6714
6715 @ifclear vms
6716 @noindent
6717 The @code{c} stands for ``check''.
6718 @end ifclear
6719 Causes the compiler to operate in semantic check mode,
6720 with full checking for all illegalities specified in the
6721 Ada Reference Manual, but without generation of any object code
6722 (no object file is generated).
6723
6724 Because dependent files must be accessed, you must follow the GNAT
6725 semantic restrictions on file structuring to operate in this mode:
6726
6727 @itemize @bullet
6728 @item
6729 The needed source files must be accessible
6730 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6731
6732 @item
6733 Each file must contain only one compilation unit.
6734
6735 @item
6736 The file name and unit name must match (@pxref{File Naming Rules}).
6737 @end itemize
6738
6739 The output consists of error messages as appropriate. No object file is
6740 generated. An @file{ALI} file is generated for use in the context of
6741 cross-reference tools, but this file is marked as not being suitable
6742 for binding (since no object file is generated).
6743 The checking corresponds exactly to the notion of
6744 legality in the Ada Reference Manual.
6745
6746 Any unit can be compiled in semantics-checking-only mode, including
6747 units that would not normally be compiled (subunits,
6748 and specifications where a separate body is present).
6749 @end table
6750
6751 @node Compiling Different Versions of Ada
6752 @subsection Compiling Different Versions of Ada
6753
6754 @noindent
6755 The switches described in this section allow you to explicitly specify
6756 the version of the Ada language that your programs are written in.
6757 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6758 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6759 indicate Ada 83 compatibility mode.
6760
6761 @table @option
6762 @cindex Compatibility with Ada 83
6763
6764 @item -gnat83 (Ada 83 Compatibility Mode)
6765 @cindex @option{-gnat83} (@command{gcc})
6766 @cindex ACVC, Ada 83 tests
6767 @cindex Ada 83 mode
6768
6769 @noindent
6770 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6771 specifies that the program is to be compiled in Ada 83 mode. With
6772 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6773 semantics where this can be done easily.
6774 It is not possible to guarantee this switch does a perfect
6775 job; some subtle tests, such as are
6776 found in earlier ACVC tests (and that have been removed from the ACATS suite
6777 for Ada 95), might not compile correctly.
6778 Nevertheless, this switch may be useful in some circumstances, for example
6779 where, due to contractual reasons, existing code needs to be maintained
6780 using only Ada 83 features.
6781
6782 With few exceptions (most notably the need to use @code{<>} on
6783 @cindex Generic formal parameters
6784 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6785 reserved words, and the use of packages
6786 with optional bodies), it is not necessary to specify the
6787 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6788 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6789 a correct Ada 83 program is usually also a correct program
6790 in these later versions of the language standard.
6791 For further information, please refer to @ref{Compatibility and Porting Guide}.
6792
6793 @item -gnat95 (Ada 95 mode)
6794 @cindex @option{-gnat95} (@command{gcc})
6795 @cindex Ada 95 mode
6796
6797 @noindent
6798 This switch directs the compiler to implement the Ada 95 version of the
6799 language.
6800 Since Ada 95 is almost completely upwards
6801 compatible with Ada 83, Ada 83 programs may generally be compiled using
6802 this switch (see the description of the @option{-gnat83} switch for further
6803 information about Ada 83 mode).
6804 If an Ada 2005 program is compiled in Ada 95 mode,
6805 uses of the new Ada 2005 features will cause error
6806 messages or warnings.
6807
6808 This switch also can be used to cancel the effect of a previous
6809 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6810
6811 @item -gnat05 (Ada 2005 mode)
6812 @cindex @option{-gnat05} (@command{gcc})
6813 @cindex Ada 2005 mode
6814
6815 @noindent
6816 This switch directs the compiler to implement the Ada 2005 version of the
6817 language.
6818 Since Ada 2005 is almost completely upwards
6819 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6820 may generally be compiled using this switch (see the description of the
6821 @option{-gnat83} and @option{-gnat95} switches for further
6822 information).
6823
6824 For information about the approved ``Ada Issues'' that have been incorporated
6825 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6826 Included with GNAT releases is a file @file{features-ada0y} that describes
6827 the set of implemented Ada 2005 features.
6828 @end table
6829
6830
6831 @node Character Set Control
6832 @subsection Character Set Control
6833 @table @option
6834 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6835 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6836
6837 @noindent
6838 Normally GNAT recognizes the Latin-1 character set in source program
6839 identifiers, as described in the Ada Reference Manual.
6840 This switch causes
6841 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6842 single character ^^or word^ indicating the character set, as follows:
6843
6844 @table @code
6845 @item 1
6846 ISO 8859-1 (Latin-1) identifiers
6847
6848 @item 2
6849 ISO 8859-2 (Latin-2) letters allowed in identifiers
6850
6851 @item 3
6852 ISO 8859-3 (Latin-3) letters allowed in identifiers
6853
6854 @item 4
6855 ISO 8859-4 (Latin-4) letters allowed in identifiers
6856
6857 @item 5
6858 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6859
6860 @item 9
6861 ISO 8859-15 (Latin-9) letters allowed in identifiers
6862
6863 @item ^p^PC^
6864 IBM PC letters (code page 437) allowed in identifiers
6865
6866 @item ^8^PC850^
6867 IBM PC letters (code page 850) allowed in identifiers
6868
6869 @item ^f^FULL_UPPER^
6870 Full upper-half codes allowed in identifiers
6871
6872 @item ^n^NO_UPPER^
6873 No upper-half codes allowed in identifiers
6874
6875 @item ^w^WIDE^
6876 Wide-character codes (that is, codes greater than 255)
6877 allowed in identifiers
6878 @end table
6879
6880 @xref{Foreign Language Representation}, for full details on the
6881 implementation of these character sets.
6882
6883 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6884 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6885 Specify the method of encoding for wide characters.
6886 @var{e} is one of the following:
6887
6888 @table @code
6889
6890 @item ^h^HEX^
6891 Hex encoding (brackets coding also recognized)
6892
6893 @item ^u^UPPER^
6894 Upper half encoding (brackets encoding also recognized)
6895
6896 @item ^s^SHIFT_JIS^
6897 Shift/JIS encoding (brackets encoding also recognized)
6898
6899 @item ^e^EUC^
6900 EUC encoding (brackets encoding also recognized)
6901
6902 @item ^8^UTF8^
6903 UTF-8 encoding (brackets encoding also recognized)
6904
6905 @item ^b^BRACKETS^
6906 Brackets encoding only (default value)
6907 @end table
6908 For full details on these encoding
6909 methods see @ref{Wide Character Encodings}.
6910 Note that brackets coding is always accepted, even if one of the other
6911 options is specified, so for example @option{-gnatW8} specifies that both
6912 brackets and UTF-8 encodings will be recognized. The units that are
6913 with'ed directly or indirectly will be scanned using the specified
6914 representation scheme, and so if one of the non-brackets scheme is
6915 used, it must be used consistently throughout the program. However,
6916 since brackets encoding is always recognized, it may be conveniently
6917 used in standard libraries, allowing these libraries to be used with
6918 any of the available coding schemes.
6919 scheme.
6920
6921 If no @option{-gnatW?} parameter is present, then the default
6922 representation is normally Brackets encoding only. However, if the
6923 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6924 byte order mark or BOM for UTF-8), then these three characters are
6925 skipped and the default representation for the file is set to UTF-8.
6926
6927 Note that the wide character representation that is specified (explicitly
6928 or by default) for the main program also acts as the default encoding used
6929 for Wide_Text_IO files if not specifically overridden by a WCEM form
6930 parameter.
6931
6932 @end table
6933 @node File Naming Control
6934 @subsection File Naming Control
6935
6936 @table @option
6937 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6938 @cindex @option{-gnatk} (@command{gcc})
6939 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6940 1-999, indicates the maximum allowable length of a file name (not
6941 including the @file{.ads} or @file{.adb} extension). The default is not
6942 to enable file name krunching.
6943
6944 For the source file naming rules, @xref{File Naming Rules}.
6945 @end table
6946
6947 @node Subprogram Inlining Control
6948 @subsection Subprogram Inlining Control
6949
6950 @table @option
6951 @c !sort!
6952 @item -gnatn
6953 @cindex @option{-gnatn} (@command{gcc})
6954 @ifclear vms
6955 The @code{n} here is intended to suggest the first syllable of the
6956 word ``inline''.
6957 @end ifclear
6958 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6959 inlining to actually occur, optimization must be enabled. To enable
6960 inlining of subprograms specified by pragma @code{Inline},
6961 you must also specify this switch.
6962 In the absence of this switch, GNAT does not attempt
6963 inlining and does not need to access the bodies of
6964 subprograms for which @code{pragma Inline} is specified if they are not
6965 in the current unit.
6966
6967 If you specify this switch the compiler will access these bodies,
6968 creating an extra source dependency for the resulting object file, and
6969 where possible, the call will be inlined.
6970 For further details on when inlining is possible
6971 see @ref{Inlining of Subprograms}.
6972
6973 @item -gnatN
6974 @cindex @option{-gnatN} (@command{gcc})
6975 This switch activates front-end inlining which also
6976 generates additional dependencies.
6977
6978 When using a gcc-based back end (in practice this means using any version
6979 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6980 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6981 Historically front end inlining was more extensive than the gcc back end
6982 inlining, but that is no longer the case.
6983 @end table
6984
6985 @node Auxiliary Output Control
6986 @subsection Auxiliary Output Control
6987
6988 @table @option
6989 @item -gnatt
6990 @cindex @option{-gnatt} (@command{gcc})
6991 @cindex Writing internal trees
6992 @cindex Internal trees, writing to file
6993 Causes GNAT to write the internal tree for a unit to a file (with the
6994 extension @file{.adt}.
6995 This not normally required, but is used by separate analysis tools.
6996 Typically
6997 these tools do the necessary compilations automatically, so you should
6998 not have to specify this switch in normal operation.
6999
7000 @item -gnatu
7001 @cindex @option{-gnatu} (@command{gcc})
7002 Print a list of units required by this compilation on @file{stdout}.
7003 The listing includes all units on which the unit being compiled depends
7004 either directly or indirectly.
7005
7006 @ifclear vms
7007 @item -pass-exit-codes
7008 @cindex @option{-pass-exit-codes} (@command{gcc})
7009 If this switch is not used, the exit code returned by @command{gcc} when
7010 compiling multiple files indicates whether all source files have
7011 been successfully used to generate object files or not.
7012
7013 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7014 exit status and allows an integrated development environment to better
7015 react to a compilation failure. Those exit status are:
7016
7017 @table @asis
7018 @item 5
7019 There was an error in at least one source file.
7020 @item 3
7021 At least one source file did not generate an object file.
7022 @item 2
7023 The compiler died unexpectedly (internal error for example).
7024 @item 0
7025 An object file has been generated for every source file.
7026 @end table
7027 @end ifclear
7028 @end table
7029
7030 @node Debugging Control
7031 @subsection Debugging Control
7032
7033 @table @option
7034 @c !sort!
7035 @cindex Debugging options
7036 @ifclear vms
7037 @item -gnatd@var{x}
7038 @cindex @option{-gnatd} (@command{gcc})
7039 Activate internal debugging switches. @var{x} is a letter or digit, or
7040 string of letters or digits, which specifies the type of debugging
7041 outputs desired. Normally these are used only for internal development
7042 or system debugging purposes. You can find full documentation for these
7043 switches in the body of the @code{Debug} unit in the compiler source
7044 file @file{debug.adb}.
7045 @end ifclear
7046
7047 @item -gnatG[=nn]
7048 @cindex @option{-gnatG} (@command{gcc})
7049 This switch causes the compiler to generate auxiliary output containing
7050 a pseudo-source listing of the generated expanded code. Like most Ada
7051 compilers, GNAT works by first transforming the high level Ada code into
7052 lower level constructs. For example, tasking operations are transformed
7053 into calls to the tasking run-time routines. A unique capability of GNAT
7054 is to list this expanded code in a form very close to normal Ada source.
7055 This is very useful in understanding the implications of various Ada
7056 usage on the efficiency of the generated code. There are many cases in
7057 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7058 generate a lot of run-time code. By using @option{-gnatG} you can identify
7059 these cases, and consider whether it may be desirable to modify the coding
7060 approach to improve efficiency.
7061
7062 The optional parameter @code{nn} if present after -gnatG specifies an
7063 alternative maximum line length that overrides the normal default of 72.
7064 This value is in the range 40-999999, values less than 40 being silently
7065 reset to 40. The equal sign is optional.
7066
7067 The format of the output is very similar to standard Ada source, and is
7068 easily understood by an Ada programmer. The following special syntactic
7069 additions correspond to low level features used in the generated code that
7070 do not have any exact analogies in pure Ada source form. The following
7071 is a partial list of these special constructions. See the spec
7072 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7073
7074 If the switch @option{-gnatL} is used in conjunction with
7075 @cindex @option{-gnatL} (@command{gcc})
7076 @option{-gnatG}, then the original source lines are interspersed
7077 in the expanded source (as comment lines with the original line number).
7078
7079 @table @code
7080 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7081 Shows the storage pool being used for an allocator.
7082
7083 @item at end @var{procedure-name};
7084 Shows the finalization (cleanup) procedure for a scope.
7085
7086 @item (if @var{expr} then @var{expr} else @var{expr})
7087 Conditional expression equivalent to the @code{x?y:z} construction in C.
7088
7089 @item @var{target}^^^(@var{source})
7090 A conversion with floating-point truncation instead of rounding.
7091
7092 @item @var{target}?(@var{source})
7093 A conversion that bypasses normal Ada semantic checking. In particular
7094 enumeration types and fixed-point types are treated simply as integers.
7095
7096 @item @var{target}?^^^(@var{source})
7097 Combines the above two cases.
7098
7099 @item @var{x} #/ @var{y}
7100 @itemx @var{x} #mod @var{y}
7101 @itemx @var{x} #* @var{y}
7102 @itemx @var{x} #rem @var{y}
7103 A division or multiplication of fixed-point values which are treated as
7104 integers without any kind of scaling.
7105
7106 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7107 Shows the storage pool associated with a @code{free} statement.
7108
7109 @item [subtype or type declaration]
7110 Used to list an equivalent declaration for an internally generated
7111 type that is referenced elsewhere in the listing.
7112
7113 @item freeze @var{type-name} @ovar{actions}
7114 Shows the point at which @var{type-name} is frozen, with possible
7115 associated actions to be performed at the freeze point.
7116
7117 @item reference @var{itype}
7118 Reference (and hence definition) to internal type @var{itype}.
7119
7120 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7121 Intrinsic function call.
7122
7123 @item @var{label-name} : label
7124 Declaration of label @var{labelname}.
7125
7126 @item #$ @var{subprogram-name}
7127 An implicit call to a run-time support routine
7128 (to meet the requirement of H.3.1(9) in a
7129 convenient manner).
7130
7131 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7132 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7133 @var{expr}, but handled more efficiently).
7134
7135 @item [constraint_error]
7136 Raise the @code{Constraint_Error} exception.
7137
7138 @item @var{expression}'reference
7139 A pointer to the result of evaluating @var{expression}.
7140
7141 @item @var{target-type}!(@var{source-expression})
7142 An unchecked conversion of @var{source-expression} to @var{target-type}.
7143
7144 @item [@var{numerator}/@var{denominator}]
7145 Used to represent internal real literals (that) have no exact
7146 representation in base 2-16 (for example, the result of compile time
7147 evaluation of the expression 1.0/27.0).
7148 @end table
7149
7150 @item -gnatD[=nn]
7151 @cindex @option{-gnatD} (@command{gcc})
7152 When used in conjunction with @option{-gnatG}, this switch causes
7153 the expanded source, as described above for
7154 @option{-gnatG} to be written to files with names
7155 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7156 instead of to the standard output file. For
7157 example, if the source file name is @file{hello.adb}, then a file
7158 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7159 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7160 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7161 you to do source level debugging using the generated code which is
7162 sometimes useful for complex code, for example to find out exactly
7163 which part of a complex construction raised an exception. This switch
7164 also suppress generation of cross-reference information (see
7165 @option{-gnatx}) since otherwise the cross-reference information
7166 would refer to the @file{^.dg^.DG^} file, which would cause
7167 confusion since this is not the original source file.
7168
7169 Note that @option{-gnatD} actually implies @option{-gnatG}
7170 automatically, so it is not necessary to give both options.
7171 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7172
7173 If the switch @option{-gnatL} is used in conjunction with
7174 @cindex @option{-gnatL} (@command{gcc})
7175 @option{-gnatDG}, then the original source lines are interspersed
7176 in the expanded source (as comment lines with the original line number).
7177
7178 The optional parameter @code{nn} if present after -gnatD specifies an
7179 alternative maximum line length that overrides the normal default of 72.
7180 This value is in the range 40-999999, values less than 40 being silently
7181 reset to 40. The equal sign is optional.
7182
7183 @item -gnatr
7184 @cindex @option{-gnatr} (@command{gcc})
7185 @cindex pragma Restrictions
7186 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7187 so that violation of restrictions causes warnings rather than illegalities.
7188 This is useful during the development process when new restrictions are added
7189 or investigated. The switch also causes pragma Profile to be treated as
7190 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7191 restriction warnings rather than restrictions.
7192
7193 @ifclear vms
7194 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7195 @cindex @option{-gnatR} (@command{gcc})
7196 This switch controls output from the compiler of a listing showing
7197 representation information for declared types and objects. For
7198 @option{-gnatR0}, no information is output (equivalent to omitting
7199 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7200 so @option{-gnatR} with no parameter has the same effect), size and alignment
7201 information is listed for declared array and record types. For
7202 @option{-gnatR2}, size and alignment information is listed for all
7203 declared types and objects. Finally @option{-gnatR3} includes symbolic
7204 expressions for values that are computed at run time for
7205 variant records. These symbolic expressions have a mostly obvious
7206 format with #n being used to represent the value of the n'th
7207 discriminant. See source files @file{repinfo.ads/adb} in the
7208 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7209 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7210 the output is to a file with the name @file{^file.rep^file_REP^} where
7211 file is the name of the corresponding source file.
7212 @end ifclear
7213 @ifset vms
7214 @item /REPRESENTATION_INFO
7215 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7216 This qualifier controls output from the compiler of a listing showing
7217 representation information for declared types and objects. For
7218 @option{/REPRESENTATION_INFO=NONE}, no information is output
7219 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7220 @option{/REPRESENTATION_INFO} without option is equivalent to
7221 @option{/REPRESENTATION_INFO=ARRAYS}.
7222 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7223 information is listed for declared array and record types. For
7224 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7225 is listed for all expression information for values that are computed
7226 at run time for variant records. These symbolic expressions have a mostly
7227 obvious format with #n being used to represent the value of the n'th
7228 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7229 @code{GNAT} sources for full details on the format of
7230 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7231 If _FILE is added at the end of an option
7232 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7233 then the output is to a file with the name @file{file_REP} where
7234 file is the name of the corresponding source file.
7235 @end ifset
7236 Note that it is possible for record components to have zero size. In
7237 this case, the component clause uses an obvious extension of permitted
7238 Ada syntax, for example @code{at 0 range 0 .. -1}.
7239
7240 Representation information requires that code be generated (since it is the
7241 code generator that lays out complex data structures). If an attempt is made
7242 to output representation information when no code is generated, for example
7243 when a subunit is compiled on its own, then no information can be generated
7244 and the compiler outputs a message to this effect.
7245
7246 @item -gnatS
7247 @cindex @option{-gnatS} (@command{gcc})
7248 The use of the switch @option{-gnatS} for an
7249 Ada compilation will cause the compiler to output a
7250 representation of package Standard in a form very
7251 close to standard Ada. It is not quite possible to
7252 do this entirely in standard Ada (since new
7253 numeric base types cannot be created in standard
7254 Ada), but the output is easily
7255 readable to any Ada programmer, and is useful to
7256 determine the characteristics of target dependent
7257 types in package Standard.
7258
7259 @item -gnatx
7260 @cindex @option{-gnatx} (@command{gcc})
7261 Normally the compiler generates full cross-referencing information in
7262 the @file{ALI} file. This information is used by a number of tools,
7263 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7264 suppresses this information. This saves some space and may slightly
7265 speed up compilation, but means that these tools cannot be used.
7266 @end table
7267
7268 @node Exception Handling Control
7269 @subsection Exception Handling Control
7270
7271 @noindent
7272 GNAT uses two methods for handling exceptions at run-time. The
7273 @code{setjmp/longjmp} method saves the context when entering
7274 a frame with an exception handler. Then when an exception is
7275 raised, the context can be restored immediately, without the
7276 need for tracing stack frames. This method provides very fast
7277 exception propagation, but introduces significant overhead for
7278 the use of exception handlers, even if no exception is raised.
7279
7280 The other approach is called ``zero cost'' exception handling.
7281 With this method, the compiler builds static tables to describe
7282 the exception ranges. No dynamic code is required when entering
7283 a frame containing an exception handler. When an exception is
7284 raised, the tables are used to control a back trace of the
7285 subprogram invocation stack to locate the required exception
7286 handler. This method has considerably poorer performance for
7287 the propagation of exceptions, but there is no overhead for
7288 exception handlers if no exception is raised. Note that in this
7289 mode and in the context of mixed Ada and C/C++ programming,
7290 to propagate an exception through a C/C++ code, the C/C++ code
7291 must be compiled with the @option{-funwind-tables} GCC's
7292 option.
7293
7294 The following switches may be used to control which of the
7295 two exception handling methods is used.
7296
7297 @table @option
7298 @c !sort!
7299
7300 @item --RTS=sjlj
7301 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7302 This switch causes the setjmp/longjmp run-time (when available) to be used
7303 for exception handling. If the default
7304 mechanism for the target is zero cost exceptions, then
7305 this switch can be used to modify this default, and must be
7306 used for all units in the partition.
7307 This option is rarely used. One case in which it may be
7308 advantageous is if you have an application where exception
7309 raising is common and the overall performance of the
7310 application is improved by favoring exception propagation.
7311
7312 @item --RTS=zcx
7313 @cindex @option{--RTS=zcx} (@command{gnatmake})
7314 @cindex Zero Cost Exceptions
7315 This switch causes the zero cost approach to be used
7316 for exception handling. If this is the default mechanism for the
7317 target (see below), then this switch is unneeded. If the default
7318 mechanism for the target is setjmp/longjmp exceptions, then
7319 this switch can be used to modify this default, and must be
7320 used for all units in the partition.
7321 This option can only be used if the zero cost approach
7322 is available for the target in use, otherwise it will generate an error.
7323 @end table
7324
7325 @noindent
7326 The same option @option{--RTS} must be used both for @command{gcc}
7327 and @command{gnatbind}. Passing this option to @command{gnatmake}
7328 (@pxref{Switches for gnatmake}) will ensure the required consistency
7329 through the compilation and binding steps.
7330
7331 @node Units to Sources Mapping Files
7332 @subsection Units to Sources Mapping Files
7333
7334 @table @option
7335
7336 @item -gnatem^^=^@var{path}
7337 @cindex @option{-gnatem} (@command{gcc})
7338 A mapping file is a way to communicate to the compiler two mappings:
7339 from unit names to file names (without any directory information) and from
7340 file names to path names (with full directory information). These mappings
7341 are used by the compiler to short-circuit the path search.
7342
7343 The use of mapping files is not required for correct operation of the
7344 compiler, but mapping files can improve efficiency, particularly when
7345 sources are read over a slow network connection. In normal operation,
7346 you need not be concerned with the format or use of mapping files,
7347 and the @option{-gnatem} switch is not a switch that you would use
7348 explicitly. it is intended only for use by automatic tools such as
7349 @command{gnatmake} running under the project file facility. The
7350 description here of the format of mapping files is provided
7351 for completeness and for possible use by other tools.
7352
7353 A mapping file is a sequence of sets of three lines. In each set,
7354 the first line is the unit name, in lower case, with ``@code{%s}''
7355 appended for
7356 specs and ``@code{%b}'' appended for bodies; the second line is the
7357 file name; and the third line is the path name.
7358
7359 Example:
7360 @smallexample
7361 main%b
7362 main.2.ada
7363 /gnat/project1/sources/main.2.ada
7364 @end smallexample
7365
7366 When the switch @option{-gnatem} is specified, the compiler will create
7367 in memory the two mappings from the specified file. If there is any problem
7368 (nonexistent file, truncated file or duplicate entries), no mapping will
7369 be created.
7370
7371 Several @option{-gnatem} switches may be specified; however, only the last
7372 one on the command line will be taken into account.
7373
7374 When using a project file, @command{gnatmake} create a temporary mapping file
7375 and communicates it to the compiler using this switch.
7376
7377 @end table
7378
7379 @node Integrated Preprocessing
7380 @subsection Integrated Preprocessing
7381
7382 @noindent
7383 GNAT sources may be preprocessed immediately before compilation.
7384 In this case, the actual
7385 text of the source is not the text of the source file, but is derived from it
7386 through a process called preprocessing. Integrated preprocessing is specified
7387 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7388 indicates, through a text file, the preprocessing data to be used.
7389 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7390
7391 @noindent
7392 Note that when integrated preprocessing is used, the output from the
7393 preprocessor is not written to any external file. Instead it is passed
7394 internally to the compiler. If you need to preserve the result of
7395 preprocessing in a file, then you should use @command{gnatprep}
7396 to perform the desired preprocessing in stand-alone mode.
7397
7398 @noindent
7399 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7400 used when Integrated Preprocessing is used. The reason is that preprocessing
7401 with another Preprocessing Data file without changing the sources will
7402 not trigger recompilation without this switch.
7403
7404 @noindent
7405 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7406 always trigger recompilation for sources that are preprocessed,
7407 because @command{gnatmake} cannot compute the checksum of the source after
7408 preprocessing.
7409
7410 @noindent
7411 The actual preprocessing function is described in details in section
7412 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7413 preprocessing is triggered and parameterized.
7414
7415 @table @code
7416
7417 @item -gnatep=@var{file}
7418 @cindex @option{-gnatep} (@command{gcc})
7419 This switch indicates to the compiler the file name (without directory
7420 information) of the preprocessor data file to use. The preprocessor data file
7421 should be found in the source directories.
7422
7423 @noindent
7424 A preprocessing data file is a text file with significant lines indicating
7425 how should be preprocessed either a specific source or all sources not
7426 mentioned in other lines. A significant line is a nonempty, non-comment line.
7427 Comments are similar to Ada comments.
7428
7429 @noindent
7430 Each significant line starts with either a literal string or the character '*'.
7431 A literal string is the file name (without directory information) of the source
7432 to preprocess. A character '*' indicates the preprocessing for all the sources
7433 that are not specified explicitly on other lines (order of the lines is not
7434 significant). It is an error to have two lines with the same file name or two
7435 lines starting with the character '*'.
7436
7437 @noindent
7438 After the file name or the character '*', another optional literal string
7439 indicating the file name of the definition file to be used for preprocessing
7440 (@pxref{Form of Definitions File}). The definition files are found by the
7441 compiler in one of the source directories. In some cases, when compiling
7442 a source in a directory other than the current directory, if the definition
7443 file is in the current directory, it may be necessary to add the current
7444 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7445 the compiler would not find the definition file.
7446
7447 @noindent
7448 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7449 be found. Those ^switches^switches^ are:
7450
7451 @table @code
7452
7453 @item -b
7454 Causes both preprocessor lines and the lines deleted by
7455 preprocessing to be replaced by blank lines, preserving the line number.
7456 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7457 it cancels the effect of @option{-c}.
7458
7459 @item -c
7460 Causes both preprocessor lines and the lines deleted
7461 by preprocessing to be retained as comments marked
7462 with the special string ``@code{--! }''.
7463
7464 @item -Dsymbol=value
7465 Define or redefine a symbol, associated with value. A symbol is an Ada
7466 identifier, or an Ada reserved word, with the exception of @code{if},
7467 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7468 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7469 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7470 same name defined in a definition file.
7471
7472 @item -s
7473 Causes a sorted list of symbol names and values to be
7474 listed on the standard output file.
7475
7476 @item -u
7477 Causes undefined symbols to be treated as having the value @code{FALSE}
7478 in the context
7479 of a preprocessor test. In the absence of this option, an undefined symbol in
7480 a @code{#if} or @code{#elsif} test will be treated as an error.
7481
7482 @end table
7483
7484 @noindent
7485 Examples of valid lines in a preprocessor data file:
7486
7487 @smallexample
7488 "toto.adb" "prep.def" -u
7489 -- preprocess "toto.adb", using definition file "prep.def",
7490 -- undefined symbol are False.
7491
7492 * -c -DVERSION=V101
7493 -- preprocess all other sources without a definition file;
7494 -- suppressed lined are commented; symbol VERSION has the value V101.
7495
7496 "titi.adb" "prep2.def" -s
7497 -- preprocess "titi.adb", using definition file "prep2.def";
7498 -- list all symbols with their values.
7499 @end smallexample
7500
7501 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7502 @cindex @option{-gnateD} (@command{gcc})
7503 Define or redefine a preprocessing symbol, associated with value. If no value
7504 is given on the command line, then the value of the symbol is @code{True}.
7505 A symbol is an identifier, following normal Ada (case-insensitive)
7506 rules for its syntax, and value is any sequence (including an empty sequence)
7507 of characters from the set (letters, digits, period, underline).
7508 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7509 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7510
7511 @noindent
7512 A symbol declared with this ^switch^switch^ on the command line replaces a
7513 symbol with the same name either in a definition file or specified with a
7514 ^switch^switch^ -D in the preprocessor data file.
7515
7516 @noindent
7517 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7518
7519 @item -gnateG
7520 When integrated preprocessing is performed and the preprocessor modifies
7521 the source text, write the result of this preprocessing into a file
7522 <source>^.prep^_prep^.
7523
7524 @end table
7525
7526 @node Code Generation Control
7527 @subsection Code Generation Control
7528
7529 @noindent
7530
7531 The GCC technology provides a wide range of target dependent
7532 @option{-m} switches for controlling
7533 details of code generation with respect to different versions of
7534 architectures. This includes variations in instruction sets (e.g.@:
7535 different members of the power pc family), and different requirements
7536 for optimal arrangement of instructions (e.g.@: different members of
7537 the x86 family). The list of available @option{-m} switches may be
7538 found in the GCC documentation.
7539
7540 Use of these @option{-m} switches may in some cases result in improved
7541 code performance.
7542
7543 The GNAT Pro technology is tested and qualified without any
7544 @option{-m} switches,
7545 so generally the most reliable approach is to avoid the use of these
7546 switches. However, we generally expect most of these switches to work
7547 successfully with GNAT Pro, and many customers have reported successful
7548 use of these options.
7549
7550 Our general advice is to avoid the use of @option{-m} switches unless
7551 special needs lead to requirements in this area. In particular,
7552 there is no point in using @option{-m} switches to improve performance
7553 unless you actually see a performance improvement.
7554
7555 @ifset vms
7556 @node Return Codes
7557 @subsection Return Codes
7558 @cindex Return Codes
7559 @cindex @option{/RETURN_CODES=VMS}
7560
7561 @noindent
7562 On VMS, GNAT compiled programs return POSIX-style codes by default,
7563 e.g.@: @option{/RETURN_CODES=POSIX}.
7564
7565 To enable VMS style return codes, use GNAT BIND and LINK with the option
7566 @option{/RETURN_CODES=VMS}. For example:
7567
7568 @smallexample
7569 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7570 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7571 @end smallexample
7572
7573 @noindent
7574 Programs built with /RETURN_CODES=VMS are suitable to be called in
7575 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7576 are suitable for spawning with appropriate GNAT RTL routines.
7577
7578 @end ifset
7579
7580 @node Search Paths and the Run-Time Library (RTL)
7581 @section Search Paths and the Run-Time Library (RTL)
7582
7583 @noindent
7584 With the GNAT source-based library system, the compiler must be able to
7585 find source files for units that are needed by the unit being compiled.
7586 Search paths are used to guide this process.
7587
7588 The compiler compiles one source file whose name must be given
7589 explicitly on the command line. In other words, no searching is done
7590 for this file. To find all other source files that are needed (the most
7591 common being the specs of units), the compiler examines the following
7592 directories, in the following order:
7593
7594 @enumerate
7595 @item
7596 The directory containing the source file of the main unit being compiled
7597 (the file name on the command line).
7598
7599 @item
7600 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7601 @command{gcc} command line, in the order given.
7602
7603 @item
7604 @findex ADA_PRJ_INCLUDE_FILE
7605 Each of the directories listed in the text file whose name is given
7606 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7607
7608 @noindent
7609 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7610 driver when project files are used. It should not normally be set
7611 by other means.
7612
7613 @item
7614 @findex ADA_INCLUDE_PATH
7615 Each of the directories listed in the value of the
7616 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7617 @ifclear vms
7618 Construct this value
7619 exactly as the @env{PATH} environment variable: a list of directory
7620 names separated by colons (semicolons when working with the NT version).
7621 @end ifclear
7622 @ifset vms
7623 Normally, define this value as a logical name containing a comma separated
7624 list of directory names.
7625
7626 This variable can also be defined by means of an environment string
7627 (an argument to the HP C exec* set of functions).
7628
7629 Logical Name:
7630 @smallexample
7631 DEFINE ANOTHER_PATH FOO:[BAG]
7632 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7633 @end smallexample
7634
7635 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7636 first, followed by the standard Ada
7637 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7638 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7639 (Text_IO, Sequential_IO, etc)
7640 instead of the standard Ada packages. Thus, in order to get the standard Ada
7641 packages by default, ADA_INCLUDE_PATH must be redefined.
7642 @end ifset
7643
7644 @item
7645 The content of the @file{ada_source_path} file which is part of the GNAT
7646 installation tree and is used to store standard libraries such as the
7647 GNAT Run Time Library (RTL) source files.
7648 @ifclear vms
7649 @ref{Installing a library}
7650 @end ifclear
7651 @end enumerate
7652
7653 @noindent
7654 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7655 inhibits the use of the directory
7656 containing the source file named in the command line. You can still
7657 have this directory on your search path, but in this case it must be
7658 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7659
7660 Specifying the switch @option{-nostdinc}
7661 inhibits the search of the default location for the GNAT Run Time
7662 Library (RTL) source files.
7663
7664 The compiler outputs its object files and ALI files in the current
7665 working directory.
7666 @ifclear vms
7667 Caution: The object file can be redirected with the @option{-o} switch;
7668 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7669 so the @file{ALI} file will not go to the right place. Therefore, you should
7670 avoid using the @option{-o} switch.
7671 @end ifclear
7672
7673 @findex System.IO
7674 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7675 children make up the GNAT RTL, together with the simple @code{System.IO}
7676 package used in the @code{"Hello World"} example. The sources for these units
7677 are needed by the compiler and are kept together in one directory. Not
7678 all of the bodies are needed, but all of the sources are kept together
7679 anyway. In a normal installation, you need not specify these directory
7680 names when compiling or binding. Either the environment variables or
7681 the built-in defaults cause these files to be found.
7682
7683 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7684 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7685 consisting of child units of @code{GNAT}. This is a collection of generally
7686 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7687 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7688
7689 Besides simplifying access to the RTL, a major use of search paths is
7690 in compiling sources from multiple directories. This can make
7691 development environments much more flexible.
7692
7693 @node Order of Compilation Issues
7694 @section Order of Compilation Issues
7695
7696 @noindent
7697 If, in our earlier example, there was a spec for the @code{hello}
7698 procedure, it would be contained in the file @file{hello.ads}; yet this
7699 file would not have to be explicitly compiled. This is the result of the
7700 model we chose to implement library management. Some of the consequences
7701 of this model are as follows:
7702
7703 @itemize @bullet
7704 @item
7705 There is no point in compiling specs (except for package
7706 specs with no bodies) because these are compiled as needed by clients. If
7707 you attempt a useless compilation, you will receive an error message.
7708 It is also useless to compile subunits because they are compiled as needed
7709 by the parent.
7710
7711 @item
7712 There are no order of compilation requirements: performing a
7713 compilation never obsoletes anything. The only way you can obsolete
7714 something and require recompilations is to modify one of the
7715 source files on which it depends.
7716
7717 @item
7718 There is no library as such, apart from the ALI files
7719 (@pxref{The Ada Library Information Files}, for information on the format
7720 of these files). For now we find it convenient to create separate ALI files,
7721 but eventually the information therein may be incorporated into the object
7722 file directly.
7723
7724 @item
7725 When you compile a unit, the source files for the specs of all units
7726 that it @code{with}'s, all its subunits, and the bodies of any generics it
7727 instantiates must be available (reachable by the search-paths mechanism
7728 described above), or you will receive a fatal error message.
7729 @end itemize
7730
7731 @node Examples
7732 @section Examples
7733
7734 @noindent
7735 The following are some typical Ada compilation command line examples:
7736
7737 @table @code
7738 @item $ gcc -c xyz.adb
7739 Compile body in file @file{xyz.adb} with all default options.
7740
7741 @ifclear vms
7742 @item $ gcc -c -O2 -gnata xyz-def.adb
7743 @end ifclear
7744 @ifset vms
7745 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7746 @end ifset
7747
7748 Compile the child unit package in file @file{xyz-def.adb} with extensive
7749 optimizations, and pragma @code{Assert}/@code{Debug} statements
7750 enabled.
7751
7752 @item $ gcc -c -gnatc abc-def.adb
7753 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7754 mode.
7755 @end table
7756
7757 @node Binding Using gnatbind
7758 @chapter Binding Using @code{gnatbind}
7759 @findex gnatbind
7760
7761 @menu
7762 * Running gnatbind::
7763 * Switches for gnatbind::
7764 * Command-Line Access::
7765 * Search Paths for gnatbind::
7766 * Examples of gnatbind Usage::
7767 @end menu
7768
7769 @noindent
7770 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7771 to bind compiled GNAT objects.
7772
7773 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7774 driver (see @ref{The GNAT Driver and Project Files}).
7775
7776 The @code{gnatbind} program performs four separate functions:
7777
7778 @enumerate
7779 @item
7780 Checks that a program is consistent, in accordance with the rules in
7781 Chapter 10 of the Ada Reference Manual. In particular, error
7782 messages are generated if a program uses inconsistent versions of a
7783 given unit.
7784
7785 @item
7786 Checks that an acceptable order of elaboration exists for the program
7787 and issues an error message if it cannot find an order of elaboration
7788 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7789
7790 @item
7791 Generates a main program incorporating the given elaboration order.
7792 This program is a small Ada package (body and spec) that
7793 must be subsequently compiled
7794 using the GNAT compiler. The necessary compilation step is usually
7795 performed automatically by @command{gnatlink}. The two most important
7796 functions of this program
7797 are to call the elaboration routines of units in an appropriate order
7798 and to call the main program.
7799
7800 @item
7801 Determines the set of object files required by the given main program.
7802 This information is output in the forms of comments in the generated program,
7803 to be read by the @command{gnatlink} utility used to link the Ada application.
7804 @end enumerate
7805
7806 @node Running gnatbind
7807 @section Running @code{gnatbind}
7808
7809 @noindent
7810 The form of the @code{gnatbind} command is
7811
7812 @smallexample
7813 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7814 @end smallexample
7815
7816 @noindent
7817 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7818 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7819 package in two files whose names are
7820 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7821 For example, if given the
7822 parameter @file{hello.ali}, for a main program contained in file
7823 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7824 and @file{b~hello.adb}.
7825
7826 When doing consistency checking, the binder takes into consideration
7827 any source files it can locate. For example, if the binder determines
7828 that the given main program requires the package @code{Pack}, whose
7829 @file{.ALI}
7830 file is @file{pack.ali} and whose corresponding source spec file is
7831 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7832 (using the same search path conventions as previously described for the
7833 @command{gcc} command). If it can locate this source file, it checks that
7834 the time stamps
7835 or source checksums of the source and its references to in @file{ALI} files
7836 match. In other words, any @file{ALI} files that mentions this spec must have
7837 resulted from compiling this version of the source file (or in the case
7838 where the source checksums match, a version close enough that the
7839 difference does not matter).
7840
7841 @cindex Source files, use by binder
7842 The effect of this consistency checking, which includes source files, is
7843 that the binder ensures that the program is consistent with the latest
7844 version of the source files that can be located at bind time. Editing a
7845 source file without compiling files that depend on the source file cause
7846 error messages to be generated by the binder.
7847
7848 For example, suppose you have a main program @file{hello.adb} and a
7849 package @code{P}, from file @file{p.ads} and you perform the following
7850 steps:
7851
7852 @enumerate
7853 @item
7854 Enter @code{gcc -c hello.adb} to compile the main program.
7855
7856 @item
7857 Enter @code{gcc -c p.ads} to compile package @code{P}.
7858
7859 @item
7860 Edit file @file{p.ads}.
7861
7862 @item
7863 Enter @code{gnatbind hello}.
7864 @end enumerate
7865
7866 @noindent
7867 At this point, the file @file{p.ali} contains an out-of-date time stamp
7868 because the file @file{p.ads} has been edited. The attempt at binding
7869 fails, and the binder generates the following error messages:
7870
7871 @smallexample
7872 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7873 error: "p.ads" has been modified and must be recompiled
7874 @end smallexample
7875
7876 @noindent
7877 Now both files must be recompiled as indicated, and then the bind can
7878 succeed, generating a main program. You need not normally be concerned
7879 with the contents of this file, but for reference purposes a sample
7880 binder output file is given in @ref{Example of Binder Output File}.
7881
7882 In most normal usage, the default mode of @command{gnatbind} which is to
7883 generate the main package in Ada, as described in the previous section.
7884 In particular, this means that any Ada programmer can read and understand
7885 the generated main program. It can also be debugged just like any other
7886 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7887 @command{gnatbind} and @command{gnatlink}.
7888
7889 However for some purposes it may be convenient to generate the main
7890 program in C rather than Ada. This may for example be helpful when you
7891 are generating a mixed language program with the main program in C. The
7892 GNAT compiler itself is an example.
7893 The use of the @option{^-C^/BIND_FILE=C^} switch
7894 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7895 be generated in C (and compiled using the gnu C compiler).
7896
7897 @node Switches for gnatbind
7898 @section Switches for @command{gnatbind}
7899
7900 @noindent
7901 The following switches are available with @code{gnatbind}; details will
7902 be presented in subsequent sections.
7903
7904 @menu
7905 * Consistency-Checking Modes::
7906 * Binder Error Message Control::
7907 * Elaboration Control::
7908 * Output Control::
7909 * Binding with Non-Ada Main Programs::
7910 * Binding Programs with No Main Subprogram::
7911 @end menu
7912
7913 @table @option
7914 @c !sort!
7915
7916 @item --version
7917 @cindex @option{--version} @command{gnatbind}
7918 Display Copyright and version, then exit disregarding all other options.
7919
7920 @item --help
7921 @cindex @option{--help} @command{gnatbind}
7922 If @option{--version} was not used, display usage, then exit disregarding
7923 all other options.
7924
7925 @item -a
7926 @cindex @option{-a} @command{gnatbind}
7927 Indicates that, if supported by the platform, the adainit procedure should
7928 be treated as an initialisation routine by the linker (a constructor). This
7929 is intended to be used by the Project Manager to automatically initialize
7930 shared Stand-Alone Libraries.
7931
7932 @item ^-aO^/OBJECT_SEARCH^
7933 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7934 Specify directory to be searched for ALI files.
7935
7936 @item ^-aI^/SOURCE_SEARCH^
7937 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7938 Specify directory to be searched for source file.
7939
7940 @item ^-A^/BIND_FILE=ADA^
7941 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7942 Generate binder program in Ada (default)
7943
7944 @item ^-b^/REPORT_ERRORS=BRIEF^
7945 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7946 Generate brief messages to @file{stderr} even if verbose mode set.
7947
7948 @item ^-c^/NOOUTPUT^
7949 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7950 Check only, no generation of binder output file.
7951
7952 @item ^-C^/BIND_FILE=C^
7953 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7954 Generate binder program in C
7955
7956 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7957 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7958 This switch can be used to change the default task stack size value
7959 to a specified size @var{nn}, which is expressed in bytes by default, or
7960 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7961 with @var{m}.
7962 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7963 in effect, to completing all task specs with
7964 @smallexample @c ada
7965 pragma Storage_Size (nn);
7966 @end smallexample
7967 When they do not already have such a pragma.
7968
7969 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7970 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7971 This switch can be used to change the default secondary stack size value
7972 to a specified size @var{nn}, which is expressed in bytes by default, or
7973 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7974 with @var{m}.
7975
7976 The secondary stack is used to deal with functions that return a variable
7977 sized result, for example a function returning an unconstrained
7978 String. There are two ways in which this secondary stack is allocated.
7979
7980 For most targets, the secondary stack is growing on demand and is allocated
7981 as a chain of blocks in the heap. The -D option is not very
7982 relevant. It only give some control over the size of the allocated
7983 blocks (whose size is the minimum of the default secondary stack size value,
7984 and the actual size needed for the current allocation request).
7985
7986 For certain targets, notably VxWorks 653,
7987 the secondary stack is allocated by carving off a fixed ratio chunk of the
7988 primary task stack. The -D option is used to define the
7989 size of the environment task's secondary stack.
7990
7991 @item ^-e^/ELABORATION_DEPENDENCIES^
7992 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7993 Output complete list of elaboration-order dependencies.
7994
7995 @item ^-E^/STORE_TRACEBACKS^
7996 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7997 Store tracebacks in exception occurrences when the target supports it.
7998 This is the default with the zero cost exception mechanism.
7999 @ignore
8000 @c The following may get moved to an appendix
8001 This option is currently supported on the following targets:
8002 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8003 @end ignore
8004 See also the packages @code{GNAT.Traceback} and
8005 @code{GNAT.Traceback.Symbolic} for more information.
8006 @ifclear vms
8007 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8008 @command{gcc} option.
8009 @end ifclear
8010
8011 @item ^-F^/FORCE_ELABS_FLAGS^
8012 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8013 Force the checks of elaboration flags. @command{gnatbind} does not normally
8014 generate checks of elaboration flags for the main executable, except when
8015 a Stand-Alone Library is used. However, there are cases when this cannot be
8016 detected by gnatbind. An example is importing an interface of a Stand-Alone
8017 Library through a pragma Import and only specifying through a linker switch
8018 this Stand-Alone Library. This switch is used to guarantee that elaboration
8019 flag checks are generated.
8020
8021 @item ^-h^/HELP^
8022 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8023 Output usage (help) information
8024
8025 @item ^-I^/SEARCH^
8026 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8027 Specify directory to be searched for source and ALI files.
8028
8029 @item ^-I-^/NOCURRENT_DIRECTORY^
8030 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8031 Do not look for sources in the current directory where @code{gnatbind} was
8032 invoked, and do not look for ALI files in the directory containing the
8033 ALI file named in the @code{gnatbind} command line.
8034
8035 @item ^-l^/ORDER_OF_ELABORATION^
8036 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8037 Output chosen elaboration order.
8038
8039 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8040 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8041 Bind the units for library building. In this case the adainit and
8042 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8043 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8044 ^@var{xxx}final^@var{XXX}FINAL^.
8045 Implies ^-n^/NOCOMPILE^.
8046 @ifclear vms
8047 (@xref{GNAT and Libraries}, for more details.)
8048 @end ifclear
8049 @ifset vms
8050 On OpenVMS, these init and final procedures are exported in uppercase
8051 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8052 the init procedure will be "TOTOINIT" and the exported name of the final
8053 procedure will be "TOTOFINAL".
8054 @end ifset
8055
8056 @item ^-Mxyz^/RENAME_MAIN=xyz^
8057 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8058 Rename generated main program from main to xyz. This option is
8059 supported on cross environments only.
8060
8061 @item ^-m^/ERROR_LIMIT=^@var{n}
8062 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8063 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8064 in the range 1..999999. The default value if no switch is
8065 given is 9999. If the number of warnings reaches this limit, then a
8066 message is output and further warnings are suppressed, the bind
8067 continues in this case. If the number of errors reaches this
8068 limit, then a message is output and the bind is abandoned.
8069 A value of zero means that no limit is enforced. The equal
8070 sign is optional.
8071
8072 @ifset unw
8073 Furthermore, under Windows, the sources pointed to by the libraries path
8074 set in the registry are not searched for.
8075 @end ifset
8076
8077 @item ^-n^/NOMAIN^
8078 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8079 No main program.
8080
8081 @item -nostdinc
8082 @cindex @option{-nostdinc} (@command{gnatbind})
8083 Do not look for sources in the system default directory.
8084
8085 @item -nostdlib
8086 @cindex @option{-nostdlib} (@command{gnatbind})
8087 Do not look for library files in the system default directory.
8088
8089 @item --RTS=@var{rts-path}
8090 @cindex @option{--RTS} (@code{gnatbind})
8091 Specifies the default location of the runtime library. Same meaning as the
8092 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8093
8094 @item ^-o ^/OUTPUT=^@var{file}
8095 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8096 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8097 Note that if this option is used, then linking must be done manually,
8098 gnatlink cannot be used.
8099
8100 @item ^-O^/OBJECT_LIST^
8101 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8102 Output object list.
8103
8104 @item ^-p^/PESSIMISTIC_ELABORATION^
8105 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8106 Pessimistic (worst-case) elaboration order
8107
8108 @item ^-R^-R^
8109 @cindex @option{^-R^-R^} (@command{gnatbind})
8110 Output closure source list.
8111
8112 @item ^-s^/READ_SOURCES=ALL^
8113 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8114 Require all source files to be present.
8115
8116 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8117 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8118 Specifies the value to be used when detecting uninitialized scalar
8119 objects with pragma Initialize_Scalars.
8120 The @var{xxx} ^string specified with the switch^option^ may be either
8121 @itemize @bullet
8122 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8123 @item ``@option{^lo^LOW^}'' for the lowest possible value
8124 @item ``@option{^hi^HIGH^}'' for the highest possible value
8125 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8126 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8127 @end itemize
8128
8129 In addition, you can specify @option{-Sev} to indicate that the value is
8130 to be set at run time. In this case, the program will look for an environment
8131 @cindex GNAT_INIT_SCALARS
8132 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8133 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8134 If no environment variable is found, or if it does not have a valid value,
8135 then the default is @option{in} (invalid values).
8136
8137 @ifclear vms
8138 @item -static
8139 @cindex @option{-static} (@code{gnatbind})
8140 Link against a static GNAT run time.
8141
8142 @item -shared
8143 @cindex @option{-shared} (@code{gnatbind})
8144 Link against a shared GNAT run time when available.
8145 @end ifclear
8146
8147 @item ^-t^/NOTIME_STAMP_CHECK^
8148 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8149 Tolerate time stamp and other consistency errors
8150
8151 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8152 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8153 Set the time slice value to @var{n} milliseconds. If the system supports
8154 the specification of a specific time slice value, then the indicated value
8155 is used. If the system does not support specific time slice values, but
8156 does support some general notion of round-robin scheduling, then any
8157 nonzero value will activate round-robin scheduling.
8158
8159 A value of zero is treated specially. It turns off time
8160 slicing, and in addition, indicates to the tasking run time that the
8161 semantics should match as closely as possible the Annex D
8162 requirements of the Ada RM, and in particular sets the default
8163 scheduling policy to @code{FIFO_Within_Priorities}.
8164
8165 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8166 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8167 Enable dynamic stack usage, with @var{n} results stored and displayed
8168 at program termination. A result is generated when a task
8169 terminates. Results that can't be stored are displayed on the fly, at
8170 task termination. This option is currently not supported on Itanium
8171 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8172
8173 @item ^-v^/REPORT_ERRORS=VERBOSE^
8174 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8175 Verbose mode. Write error messages, header, summary output to
8176 @file{stdout}.
8177
8178 @ifclear vms
8179 @item -w@var{x}
8180 @cindex @option{-w} (@code{gnatbind})
8181 Warning mode (@var{x}=s/e for suppress/treat as error)
8182 @end ifclear
8183
8184 @ifset vms
8185 @item /WARNINGS=NORMAL
8186 @cindex @option{/WARNINGS} (@code{gnatbind})
8187 Normal warnings mode. Warnings are issued but ignored
8188
8189 @item /WARNINGS=SUPPRESS
8190 @cindex @option{/WARNINGS} (@code{gnatbind})
8191 All warning messages are suppressed
8192
8193 @item /WARNINGS=ERROR
8194 @cindex @option{/WARNINGS} (@code{gnatbind})
8195 Warning messages are treated as fatal errors
8196 @end ifset
8197
8198 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8199 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8200 Override default wide character encoding for standard Text_IO files.
8201
8202 @item ^-x^/READ_SOURCES=NONE^
8203 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8204 Exclude source files (check object consistency only).
8205
8206 @ifset vms
8207 @item /READ_SOURCES=AVAILABLE
8208 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8209 Default mode, in which sources are checked for consistency only if
8210 they are available.
8211 @end ifset
8212
8213 @item ^-y^/ENABLE_LEAP_SECONDS^
8214 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8215 Enable leap seconds support in @code{Ada.Calendar} and its children.
8216
8217 @item ^-z^/ZERO_MAIN^
8218 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8219 No main subprogram.
8220 @end table
8221
8222 @ifclear vms
8223 @noindent
8224 You may obtain this listing of switches by running @code{gnatbind} with
8225 no arguments.
8226 @end ifclear
8227
8228 @node Consistency-Checking Modes
8229 @subsection Consistency-Checking Modes
8230
8231 @noindent
8232 As described earlier, by default @code{gnatbind} checks
8233 that object files are consistent with one another and are consistent
8234 with any source files it can locate. The following switches control binder
8235 access to sources.
8236
8237 @table @option
8238 @c !sort!
8239 @item ^-s^/READ_SOURCES=ALL^
8240 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8241 Require source files to be present. In this mode, the binder must be
8242 able to locate all source files that are referenced, in order to check
8243 their consistency. In normal mode, if a source file cannot be located it
8244 is simply ignored. If you specify this switch, a missing source
8245 file is an error.
8246
8247 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8248 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8249 Override default wide character encoding for standard Text_IO files.
8250 Normally the default wide character encoding method used for standard
8251 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8252 the main source input (see description of switch
8253 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8254 use of this switch for the binder (which has the same set of
8255 possible arguments) overrides this default as specified.
8256
8257 @item ^-x^/READ_SOURCES=NONE^
8258 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8259 Exclude source files. In this mode, the binder only checks that ALI
8260 files are consistent with one another. Source files are not accessed.
8261 The binder runs faster in this mode, and there is still a guarantee that
8262 the resulting program is self-consistent.
8263 If a source file has been edited since it was last compiled, and you
8264 specify this switch, the binder will not detect that the object
8265 file is out of date with respect to the source file. Note that this is the
8266 mode that is automatically used by @command{gnatmake} because in this
8267 case the checking against sources has already been performed by
8268 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8269
8270 @ifset vms
8271 @item /READ_SOURCES=AVAILABLE
8272 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8273 This is the default mode in which source files are checked if they are
8274 available, and ignored if they are not available.
8275 @end ifset
8276 @end table
8277
8278 @node Binder Error Message Control
8279 @subsection Binder Error Message Control
8280
8281 @noindent
8282 The following switches provide control over the generation of error
8283 messages from the binder:
8284
8285 @table @option
8286 @c !sort!
8287 @item ^-v^/REPORT_ERRORS=VERBOSE^
8288 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8289 Verbose mode. In the normal mode, brief error messages are generated to
8290 @file{stderr}. If this switch is present, a header is written
8291 to @file{stdout} and any error messages are directed to @file{stdout}.
8292 All that is written to @file{stderr} is a brief summary message.
8293
8294 @item ^-b^/REPORT_ERRORS=BRIEF^
8295 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8296 Generate brief error messages to @file{stderr} even if verbose mode is
8297 specified. This is relevant only when used with the
8298 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8299
8300 @ifclear vms
8301 @item -m@var{n}
8302 @cindex @option{-m} (@code{gnatbind})
8303 Limits the number of error messages to @var{n}, a decimal integer in the
8304 range 1-999. The binder terminates immediately if this limit is reached.
8305
8306 @item -M@var{xxx}
8307 @cindex @option{-M} (@code{gnatbind})
8308 Renames the generated main program from @code{main} to @code{xxx}.
8309 This is useful in the case of some cross-building environments, where
8310 the actual main program is separate from the one generated
8311 by @code{gnatbind}.
8312 @end ifclear
8313
8314 @item ^-ws^/WARNINGS=SUPPRESS^
8315 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8316 @cindex Warnings
8317 Suppress all warning messages.
8318
8319 @item ^-we^/WARNINGS=ERROR^
8320 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8321 Treat any warning messages as fatal errors.
8322
8323 @ifset vms
8324 @item /WARNINGS=NORMAL
8325 Standard mode with warnings generated, but warnings do not get treated
8326 as errors.
8327 @end ifset
8328
8329 @item ^-t^/NOTIME_STAMP_CHECK^
8330 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8331 @cindex Time stamp checks, in binder
8332 @cindex Binder consistency checks
8333 @cindex Consistency checks, in binder
8334 The binder performs a number of consistency checks including:
8335
8336 @itemize @bullet
8337 @item
8338 Check that time stamps of a given source unit are consistent
8339 @item
8340 Check that checksums of a given source unit are consistent
8341 @item
8342 Check that consistent versions of @code{GNAT} were used for compilation
8343 @item
8344 Check consistency of configuration pragmas as required
8345 @end itemize
8346
8347 @noindent
8348 Normally failure of such checks, in accordance with the consistency
8349 requirements of the Ada Reference Manual, causes error messages to be
8350 generated which abort the binder and prevent the output of a binder
8351 file and subsequent link to obtain an executable.
8352
8353 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8354 into warnings, so that
8355 binding and linking can continue to completion even in the presence of such
8356 errors. The result may be a failed link (due to missing symbols), or a
8357 non-functional executable which has undefined semantics.
8358 @emph{This means that
8359 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8360 with extreme care.}
8361 @end table
8362
8363 @node Elaboration Control
8364 @subsection Elaboration Control
8365
8366 @noindent
8367 The following switches provide additional control over the elaboration
8368 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8369
8370 @table @option
8371 @item ^-p^/PESSIMISTIC_ELABORATION^
8372 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8373 Normally the binder attempts to choose an elaboration order that is
8374 likely to minimize the likelihood of an elaboration order error resulting
8375 in raising a @code{Program_Error} exception. This switch reverses the
8376 action of the binder, and requests that it deliberately choose an order
8377 that is likely to maximize the likelihood of an elaboration error.
8378 This is useful in ensuring portability and avoiding dependence on
8379 accidental fortuitous elaboration ordering.
8380
8381 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8382 switch if dynamic
8383 elaboration checking is used (@option{-gnatE} switch used for compilation).
8384 This is because in the default static elaboration mode, all necessary
8385 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8386 These implicit pragmas are still respected by the binder in
8387 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8388 safe elaboration order is assured.
8389 @end table
8390
8391 @node Output Control
8392 @subsection Output Control
8393
8394 @noindent
8395 The following switches allow additional control over the output
8396 generated by the binder.
8397
8398 @table @option
8399 @c !sort!
8400
8401 @item ^-A^/BIND_FILE=ADA^
8402 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8403 Generate binder program in Ada (default). The binder program is named
8404 @file{b~@var{mainprog}.adb} by default. This can be changed with
8405 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8406
8407 @item ^-c^/NOOUTPUT^
8408 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8409 Check only. Do not generate the binder output file. In this mode the
8410 binder performs all error checks but does not generate an output file.
8411
8412 @item ^-C^/BIND_FILE=C^
8413 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8414 Generate binder program in C. The binder program is named
8415 @file{b_@var{mainprog}.c}.
8416 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8417 option.
8418
8419 @item ^-e^/ELABORATION_DEPENDENCIES^
8420 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8421 Output complete list of elaboration-order dependencies, showing the
8422 reason for each dependency. This output can be rather extensive but may
8423 be useful in diagnosing problems with elaboration order. The output is
8424 written to @file{stdout}.
8425
8426 @item ^-h^/HELP^
8427 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8428 Output usage information. The output is written to @file{stdout}.
8429
8430 @item ^-K^/LINKER_OPTION_LIST^
8431 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8432 Output linker options to @file{stdout}. Includes library search paths,
8433 contents of pragmas Ident and Linker_Options, and libraries added
8434 by @code{gnatbind}.
8435
8436 @item ^-l^/ORDER_OF_ELABORATION^
8437 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8438 Output chosen elaboration order. The output is written to @file{stdout}.
8439
8440 @item ^-O^/OBJECT_LIST^
8441 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8442 Output full names of all the object files that must be linked to provide
8443 the Ada component of the program. The output is written to @file{stdout}.
8444 This list includes the files explicitly supplied and referenced by the user
8445 as well as implicitly referenced run-time unit files. The latter are
8446 omitted if the corresponding units reside in shared libraries. The
8447 directory names for the run-time units depend on the system configuration.
8448
8449 @item ^-o ^/OUTPUT=^@var{file}
8450 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8451 Set name of output file to @var{file} instead of the normal
8452 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8453 binder generated body filename. In C mode you would normally give
8454 @var{file} an extension of @file{.c} because it will be a C source program.
8455 Note that if this option is used, then linking must be done manually.
8456 It is not possible to use gnatlink in this case, since it cannot locate
8457 the binder file.
8458
8459 @item ^-r^/RESTRICTION_LIST^
8460 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8461 Generate list of @code{pragma Restrictions} that could be applied to
8462 the current unit. This is useful for code audit purposes, and also may
8463 be used to improve code generation in some cases.
8464
8465 @end table
8466
8467 @node Binding with Non-Ada Main Programs
8468 @subsection Binding with Non-Ada Main Programs
8469
8470 @noindent
8471 In our description so far we have assumed that the main
8472 program is in Ada, and that the task of the binder is to generate a
8473 corresponding function @code{main} that invokes this Ada main
8474 program. GNAT also supports the building of executable programs where
8475 the main program is not in Ada, but some of the called routines are
8476 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8477 The following switch is used in this situation:
8478
8479 @table @option
8480 @item ^-n^/NOMAIN^
8481 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8482 No main program. The main program is not in Ada.
8483 @end table
8484
8485 @noindent
8486 In this case, most of the functions of the binder are still required,
8487 but instead of generating a main program, the binder generates a file
8488 containing the following callable routines:
8489
8490 @table @code
8491 @item adainit
8492 @findex adainit
8493 You must call this routine to initialize the Ada part of the program by
8494 calling the necessary elaboration routines. A call to @code{adainit} is
8495 required before the first call to an Ada subprogram.
8496
8497 Note that it is assumed that the basic execution environment must be setup
8498 to be appropriate for Ada execution at the point where the first Ada
8499 subprogram is called. In particular, if the Ada code will do any
8500 floating-point operations, then the FPU must be setup in an appropriate
8501 manner. For the case of the x86, for example, full precision mode is
8502 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8503 that the FPU is in the right state.
8504
8505 @item adafinal
8506 @findex adafinal
8507 You must call this routine to perform any library-level finalization
8508 required by the Ada subprograms. A call to @code{adafinal} is required
8509 after the last call to an Ada subprogram, and before the program
8510 terminates.
8511 @end table
8512
8513 @noindent
8514 If the @option{^-n^/NOMAIN^} switch
8515 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8516 @cindex Binder, multiple input files
8517 is given, more than one ALI file may appear on
8518 the command line for @code{gnatbind}. The normal @dfn{closure}
8519 calculation is performed for each of the specified units. Calculating
8520 the closure means finding out the set of units involved by tracing
8521 @code{with} references. The reason it is necessary to be able to
8522 specify more than one ALI file is that a given program may invoke two or
8523 more quite separate groups of Ada units.
8524
8525 The binder takes the name of its output file from the last specified ALI
8526 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8527 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8528 The output is an Ada unit in source form that can
8529 be compiled with GNAT unless the -C switch is used in which case the
8530 output is a C source file, which must be compiled using the C compiler.
8531 This compilation occurs automatically as part of the @command{gnatlink}
8532 processing.
8533
8534 Currently the GNAT run time requires a FPU using 80 bits mode
8535 precision. Under targets where this is not the default it is required to
8536 call GNAT.Float_Control.Reset before using floating point numbers (this
8537 include float computation, float input and output) in the Ada code. A
8538 side effect is that this could be the wrong mode for the foreign code
8539 where floating point computation could be broken after this call.
8540
8541 @node Binding Programs with No Main Subprogram
8542 @subsection Binding Programs with No Main Subprogram
8543
8544 @noindent
8545 It is possible to have an Ada program which does not have a main
8546 subprogram. This program will call the elaboration routines of all the
8547 packages, then the finalization routines.
8548
8549 The following switch is used to bind programs organized in this manner:
8550
8551 @table @option
8552 @item ^-z^/ZERO_MAIN^
8553 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8554 Normally the binder checks that the unit name given on the command line
8555 corresponds to a suitable main subprogram. When this switch is used,
8556 a list of ALI files can be given, and the execution of the program
8557 consists of elaboration of these units in an appropriate order. Note
8558 that the default wide character encoding method for standard Text_IO
8559 files is always set to Brackets if this switch is set (you can use
8560 the binder switch
8561 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8562 @end table
8563
8564 @node Command-Line Access
8565 @section Command-Line Access
8566
8567 @noindent
8568 The package @code{Ada.Command_Line} provides access to the command-line
8569 arguments and program name. In order for this interface to operate
8570 correctly, the two variables
8571
8572 @smallexample
8573 @group
8574 int gnat_argc;
8575 char **gnat_argv;
8576 @end group
8577 @end smallexample
8578
8579 @noindent
8580 @findex gnat_argv
8581 @findex gnat_argc
8582 are declared in one of the GNAT library routines. These variables must
8583 be set from the actual @code{argc} and @code{argv} values passed to the
8584 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8585 generates the C main program to automatically set these variables.
8586 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8587 set these variables. If they are not set, the procedures in
8588 @code{Ada.Command_Line} will not be available, and any attempt to use
8589 them will raise @code{Constraint_Error}. If command line access is
8590 required, your main program must set @code{gnat_argc} and
8591 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8592 it.
8593
8594 @node Search Paths for gnatbind
8595 @section Search Paths for @code{gnatbind}
8596
8597 @noindent
8598 The binder takes the name of an ALI file as its argument and needs to
8599 locate source files as well as other ALI files to verify object consistency.
8600
8601 For source files, it follows exactly the same search rules as @command{gcc}
8602 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8603 directories searched are:
8604
8605 @enumerate
8606 @item
8607 The directory containing the ALI file named in the command line, unless
8608 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8609
8610 @item
8611 All directories specified by @option{^-I^/SEARCH^}
8612 switches on the @code{gnatbind}
8613 command line, in the order given.
8614
8615 @item
8616 @findex ADA_PRJ_OBJECTS_FILE
8617 Each of the directories listed in the text file whose name is given
8618 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8619
8620 @noindent
8621 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8622 driver when project files are used. It should not normally be set
8623 by other means.
8624
8625 @item
8626 @findex ADA_OBJECTS_PATH
8627 Each of the directories listed in the value of the
8628 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8629 @ifset unw
8630 Construct this value
8631 exactly as the @env{PATH} environment variable: a list of directory
8632 names separated by colons (semicolons when working with the NT version
8633 of GNAT).
8634 @end ifset
8635 @ifset vms
8636 Normally, define this value as a logical name containing a comma separated
8637 list of directory names.
8638
8639 This variable can also be defined by means of an environment string
8640 (an argument to the HP C exec* set of functions).
8641
8642 Logical Name:
8643 @smallexample
8644 DEFINE ANOTHER_PATH FOO:[BAG]
8645 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8646 @end smallexample
8647
8648 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8649 first, followed by the standard Ada
8650 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8651 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8652 (Text_IO, Sequential_IO, etc)
8653 instead of the standard Ada packages. Thus, in order to get the standard Ada
8654 packages by default, ADA_OBJECTS_PATH must be redefined.
8655 @end ifset
8656
8657 @item
8658 The content of the @file{ada_object_path} file which is part of the GNAT
8659 installation tree and is used to store standard libraries such as the
8660 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8661 specified.
8662 @ifclear vms
8663 @ref{Installing a library}
8664 @end ifclear
8665 @end enumerate
8666
8667 @noindent
8668 In the binder the switch @option{^-I^/SEARCH^}
8669 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8670 is used to specify both source and
8671 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8672 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8673 instead if you want to specify
8674 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8675 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8676 if you want to specify library paths
8677 only. This means that for the binder
8678 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8679 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8680 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8681 The binder generates the bind file (a C language source file) in the
8682 current working directory.
8683
8684 @findex Ada
8685 @findex System
8686 @findex Interfaces
8687 @findex GNAT
8688 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8689 children make up the GNAT Run-Time Library, together with the package
8690 GNAT and its children, which contain a set of useful additional
8691 library functions provided by GNAT. The sources for these units are
8692 needed by the compiler and are kept together in one directory. The ALI
8693 files and object files generated by compiling the RTL are needed by the
8694 binder and the linker and are kept together in one directory, typically
8695 different from the directory containing the sources. In a normal
8696 installation, you need not specify these directory names when compiling
8697 or binding. Either the environment variables or the built-in defaults
8698 cause these files to be found.
8699
8700 Besides simplifying access to the RTL, a major use of search paths is
8701 in compiling sources from multiple directories. This can make
8702 development environments much more flexible.
8703
8704 @node Examples of gnatbind Usage
8705 @section Examples of @code{gnatbind} Usage
8706
8707 @noindent
8708 This section contains a number of examples of using the GNAT binding
8709 utility @code{gnatbind}.
8710
8711 @table @code
8712 @item gnatbind hello
8713 The main program @code{Hello} (source program in @file{hello.adb}) is
8714 bound using the standard switch settings. The generated main program is
8715 @file{b~hello.adb}. This is the normal, default use of the binder.
8716
8717 @ifclear vms
8718 @item gnatbind hello -o mainprog.adb
8719 @end ifclear
8720 @ifset vms
8721 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8722 @end ifset
8723 The main program @code{Hello} (source program in @file{hello.adb}) is
8724 bound using the standard switch settings. The generated main program is
8725 @file{mainprog.adb} with the associated spec in
8726 @file{mainprog.ads}. Note that you must specify the body here not the
8727 spec, in the case where the output is in Ada. Note that if this option
8728 is used, then linking must be done manually, since gnatlink will not
8729 be able to find the generated file.
8730
8731 @ifclear vms
8732 @item gnatbind main -C -o mainprog.c -x
8733 @end ifclear
8734 @ifset vms
8735 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8736 @end ifset
8737 The main program @code{Main} (source program in
8738 @file{main.adb}) is bound, excluding source files from the
8739 consistency checking, generating
8740 the file @file{mainprog.c}.
8741
8742 @ifclear vms
8743 @item gnatbind -x main_program -C -o mainprog.c
8744 This command is exactly the same as the previous example. Switches may
8745 appear anywhere in the command line, and single letter switches may be
8746 combined into a single switch.
8747 @end ifclear
8748
8749 @ifclear vms
8750 @item gnatbind -n math dbase -C -o ada-control.c
8751 @end ifclear
8752 @ifset vms
8753 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8754 @end ifset
8755 The main program is in a language other than Ada, but calls to
8756 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8757 to @code{gnatbind} generates the file @file{ada-control.c} containing
8758 the @code{adainit} and @code{adafinal} routines to be called before and
8759 after accessing the Ada units.
8760 @end table
8761
8762 @c ------------------------------------
8763 @node Linking Using gnatlink
8764 @chapter Linking Using @command{gnatlink}
8765 @c ------------------------------------
8766 @findex gnatlink
8767
8768 @noindent
8769 This chapter discusses @command{gnatlink}, a tool that links
8770 an Ada program and builds an executable file. This utility
8771 invokes the system linker ^(via the @command{gcc} command)^^
8772 with a correct list of object files and library references.
8773 @command{gnatlink} automatically determines the list of files and
8774 references for the Ada part of a program. It uses the binder file
8775 generated by the @command{gnatbind} to determine this list.
8776
8777 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8778 driver (see @ref{The GNAT Driver and Project Files}).
8779
8780 @menu
8781 * Running gnatlink::
8782 * Switches for gnatlink::
8783 @end menu
8784
8785 @node Running gnatlink
8786 @section Running @command{gnatlink}
8787
8788 @noindent
8789 The form of the @command{gnatlink} command is
8790
8791 @smallexample
8792 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8793 @ovar{non-Ada objects} @ovar{linker options}
8794 @end smallexample
8795
8796 @noindent
8797 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8798 non-Ada objects
8799 or linker options) may be in any order, provided that no non-Ada object may
8800 be mistaken for a main @file{ALI} file.
8801 Any file name @file{F} without the @file{.ali}
8802 extension will be taken as the main @file{ALI} file if a file exists
8803 whose name is the concatenation of @file{F} and @file{.ali}.
8804
8805 @noindent
8806 @file{@var{mainprog}.ali} references the ALI file of the main program.
8807 The @file{.ali} extension of this file can be omitted. From this
8808 reference, @command{gnatlink} locates the corresponding binder file
8809 @file{b~@var{mainprog}.adb} and, using the information in this file along
8810 with the list of non-Ada objects and linker options, constructs a
8811 linker command file to create the executable.
8812
8813 The arguments other than the @command{gnatlink} switches and the main
8814 @file{ALI} file are passed to the linker uninterpreted.
8815 They typically include the names of
8816 object files for units written in other languages than Ada and any library
8817 references required to resolve references in any of these foreign language
8818 units, or in @code{Import} pragmas in any Ada units.
8819
8820 @var{linker options} is an optional list of linker specific
8821 switches.
8822 The default linker called by gnatlink is @command{gcc} which in
8823 turn calls the appropriate system linker.
8824 Standard options for the linker such as @option{-lmy_lib} or
8825 @option{-Ldir} can be added as is.
8826 For options that are not recognized by
8827 @command{gcc} as linker options, use the @command{gcc} switches
8828 @option{-Xlinker} or @option{-Wl,}.
8829 Refer to the GCC documentation for
8830 details. Here is an example showing how to generate a linker map:
8831
8832 @smallexample
8833 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8834 @end smallexample
8835
8836 Using @var{linker options} it is possible to set the program stack and
8837 heap size.
8838 @ifset unw
8839 See @ref{Setting Stack Size from gnatlink} and
8840 @ref{Setting Heap Size from gnatlink}.
8841 @end ifset
8842
8843 @command{gnatlink} determines the list of objects required by the Ada
8844 program and prepends them to the list of objects passed to the linker.
8845 @command{gnatlink} also gathers any arguments set by the use of
8846 @code{pragma Linker_Options} and adds them to the list of arguments
8847 presented to the linker.
8848
8849 @ifset vms
8850 @command{gnatlink} accepts the following types of extra files on the command
8851 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8852 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8853 handled according to their extension.
8854 @end ifset
8855
8856 @node Switches for gnatlink
8857 @section Switches for @command{gnatlink}
8858
8859 @noindent
8860 The following switches are available with the @command{gnatlink} utility:
8861
8862 @table @option
8863 @c !sort!
8864
8865 @item --version
8866 @cindex @option{--version} @command{gnatlink}
8867 Display Copyright and version, then exit disregarding all other options.
8868
8869 @item --help
8870 @cindex @option{--help} @command{gnatlink}
8871 If @option{--version} was not used, display usage, then exit disregarding
8872 all other options.
8873
8874 @item ^-A^/BIND_FILE=ADA^
8875 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8876 The binder has generated code in Ada. This is the default.
8877
8878 @item ^-C^/BIND_FILE=C^
8879 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8880 If instead of generating a file in Ada, the binder has generated one in
8881 C, then the linker needs to know about it. Use this switch to signal
8882 to @command{gnatlink} that the binder has generated C code rather than
8883 Ada code.
8884
8885 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8886 @cindex Command line length
8887 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8888 On some targets, the command line length is limited, and @command{gnatlink}
8889 will generate a separate file for the linker if the list of object files
8890 is too long.
8891 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8892 to be generated even if
8893 the limit is not exceeded. This is useful in some cases to deal with
8894 special situations where the command line length is exceeded.
8895
8896 @item ^-g^/DEBUG^
8897 @cindex Debugging information, including
8898 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8899 The option to include debugging information causes the Ada bind file (in
8900 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8901 @option{^-g^/DEBUG^}.
8902 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8903 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8904 Without @option{^-g^/DEBUG^}, the binder removes these files by
8905 default. The same procedure apply if a C bind file was generated using
8906 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8907 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8908
8909 @item ^-n^/NOCOMPILE^
8910 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8911 Do not compile the file generated by the binder. This may be used when
8912 a link is rerun with different options, but there is no need to recompile
8913 the binder file.
8914
8915 @item ^-v^/VERBOSE^
8916 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8917 Causes additional information to be output, including a full list of the
8918 included object files. This switch option is most useful when you want
8919 to see what set of object files are being used in the link step.
8920
8921 @item ^-v -v^/VERBOSE/VERBOSE^
8922 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8923 Very verbose mode. Requests that the compiler operate in verbose mode when
8924 it compiles the binder file, and that the system linker run in verbose mode.
8925
8926 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8927 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8928 @var{exec-name} specifies an alternate name for the generated
8929 executable program. If this switch is omitted, the executable has the same
8930 name as the main unit. For example, @code{gnatlink try.ali} creates
8931 an executable called @file{^try^TRY.EXE^}.
8932
8933 @ifclear vms
8934 @item -b @var{target}
8935 @cindex @option{-b} (@command{gnatlink})
8936 Compile your program to run on @var{target}, which is the name of a
8937 system configuration. You must have a GNAT cross-compiler built if
8938 @var{target} is not the same as your host system.
8939
8940 @item -B@var{dir}
8941 @cindex @option{-B} (@command{gnatlink})
8942 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8943 from @var{dir} instead of the default location. Only use this switch
8944 when multiple versions of the GNAT compiler are available.
8945 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8946 for further details. You would normally use the @option{-b} or
8947 @option{-V} switch instead.
8948
8949 @item --GCC=@var{compiler_name}
8950 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8951 Program used for compiling the binder file. The default is
8952 @command{gcc}. You need to use quotes around @var{compiler_name} if
8953 @code{compiler_name} contains spaces or other separator characters.
8954 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8955 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8956 inserted after your command name. Thus in the above example the compiler
8957 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8958 A limitation of this syntax is that the name and path name of the executable
8959 itself must not include any embedded spaces. If the compiler executable is
8960 different from the default one (gcc or <prefix>-gcc), then the back-end
8961 switches in the ALI file are not used to compile the binder generated source.
8962 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8963 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8964 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8965 is taken into account. However, all the additional switches are also taken
8966 into account. Thus,
8967 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8968 @option{--GCC="bar -x -y -z -t"}.
8969
8970 @item --LINK=@var{name}
8971 @cindex @option{--LINK=} (@command{gnatlink})
8972 @var{name} is the name of the linker to be invoked. This is especially
8973 useful in mixed language programs since languages such as C++ require
8974 their own linker to be used. When this switch is omitted, the default
8975 name for the linker is @command{gcc}. When this switch is used, the
8976 specified linker is called instead of @command{gcc} with exactly the same
8977 parameters that would have been passed to @command{gcc} so if the desired
8978 linker requires different parameters it is necessary to use a wrapper
8979 script that massages the parameters before invoking the real linker. It
8980 may be useful to control the exact invocation by using the verbose
8981 switch.
8982
8983 @end ifclear
8984
8985 @ifset vms
8986 @item /DEBUG=TRACEBACK
8987 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8988 This qualifier causes sufficient information to be included in the
8989 executable file to allow a traceback, but does not include the full
8990 symbol information needed by the debugger.
8991
8992 @item /IDENTIFICATION="<string>"
8993 @code{"<string>"} specifies the string to be stored in the image file
8994 identification field in the image header.
8995 It overrides any pragma @code{Ident} specified string.
8996
8997 @item /NOINHIBIT-EXEC
8998 Generate the executable file even if there are linker warnings.
8999
9000 @item /NOSTART_FILES
9001 Don't link in the object file containing the ``main'' transfer address.
9002 Used when linking with a foreign language main program compiled with an
9003 HP compiler.
9004
9005 @item /STATIC
9006 Prefer linking with object libraries over sharable images, even without
9007 /DEBUG.
9008 @end ifset
9009
9010 @end table
9011
9012 @node The GNAT Make Program gnatmake
9013 @chapter The GNAT Make Program @command{gnatmake}
9014 @findex gnatmake
9015
9016 @menu
9017 * Running gnatmake::
9018 * Switches for gnatmake::
9019 * Mode Switches for gnatmake::
9020 * Notes on the Command Line::
9021 * How gnatmake Works::
9022 * Examples of gnatmake Usage::
9023 @end menu
9024 @noindent
9025 A typical development cycle when working on an Ada program consists of
9026 the following steps:
9027
9028 @enumerate
9029 @item
9030 Edit some sources to fix bugs.
9031
9032 @item
9033 Add enhancements.
9034
9035 @item
9036 Compile all sources affected.
9037
9038 @item
9039 Rebind and relink.
9040
9041 @item
9042 Test.
9043 @end enumerate
9044
9045 @noindent
9046 The third step can be tricky, because not only do the modified files
9047 @cindex Dependency rules
9048 have to be compiled, but any files depending on these files must also be
9049 recompiled. The dependency rules in Ada can be quite complex, especially
9050 in the presence of overloading, @code{use} clauses, generics and inlined
9051 subprograms.
9052
9053 @command{gnatmake} automatically takes care of the third and fourth steps
9054 of this process. It determines which sources need to be compiled,
9055 compiles them, and binds and links the resulting object files.
9056
9057 Unlike some other Ada make programs, the dependencies are always
9058 accurately recomputed from the new sources. The source based approach of
9059 the GNAT compilation model makes this possible. This means that if
9060 changes to the source program cause corresponding changes in
9061 dependencies, they will always be tracked exactly correctly by
9062 @command{gnatmake}.
9063
9064 @node Running gnatmake
9065 @section Running @command{gnatmake}
9066
9067 @noindent
9068 The usual form of the @command{gnatmake} command is
9069
9070 @smallexample
9071 $ gnatmake @ovar{switches} @var{file_name}
9072 @ovar{file_names} @ovar{mode_switches}
9073 @end smallexample
9074
9075 @noindent
9076 The only required argument is one @var{file_name}, which specifies
9077 a compilation unit that is a main program. Several @var{file_names} can be
9078 specified: this will result in several executables being built.
9079 If @code{switches} are present, they can be placed before the first
9080 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9081 If @var{mode_switches} are present, they must always be placed after
9082 the last @var{file_name} and all @code{switches}.
9083
9084 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9085 extension may be omitted from the @var{file_name} arguments. However, if
9086 you are using non-standard extensions, then it is required that the
9087 extension be given. A relative or absolute directory path can be
9088 specified in a @var{file_name}, in which case, the input source file will
9089 be searched for in the specified directory only. Otherwise, the input
9090 source file will first be searched in the directory where
9091 @command{gnatmake} was invoked and if it is not found, it will be search on
9092 the source path of the compiler as described in
9093 @ref{Search Paths and the Run-Time Library (RTL)}.
9094
9095 All @command{gnatmake} output (except when you specify
9096 @option{^-M^/DEPENDENCIES_LIST^}) is to
9097 @file{stderr}. The output produced by the
9098 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9099 @file{stdout}.
9100
9101 @node Switches for gnatmake
9102 @section Switches for @command{gnatmake}
9103
9104 @noindent
9105 You may specify any of the following switches to @command{gnatmake}:
9106
9107 @table @option
9108 @c !sort!
9109
9110 @item --version
9111 @cindex @option{--version} @command{gnatmake}
9112 Display Copyright and version, then exit disregarding all other options.
9113
9114 @item --help
9115 @cindex @option{--help} @command{gnatmake}
9116 If @option{--version} was not used, display usage, then exit disregarding
9117 all other options.
9118
9119 @ifclear vms
9120 @item --GCC=@var{compiler_name}
9121 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9122 Program used for compiling. The default is `@command{gcc}'. You need to use
9123 quotes around @var{compiler_name} if @code{compiler_name} contains
9124 spaces or other separator characters. As an example @option{--GCC="foo -x
9125 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9126 compiler. A limitation of this syntax is that the name and path name of
9127 the executable itself must not include any embedded spaces. Note that
9128 switch @option{-c} is always inserted after your command name. Thus in the
9129 above example the compiler command that will be used by @command{gnatmake}
9130 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9131 used, only the last @var{compiler_name} is taken into account. However,
9132 all the additional switches are also taken into account. Thus,
9133 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9134 @option{--GCC="bar -x -y -z -t"}.
9135
9136 @item --GNATBIND=@var{binder_name}
9137 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9138 Program used for binding. The default is `@code{gnatbind}'. You need to
9139 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9140 or other separator characters. As an example @option{--GNATBIND="bar -x
9141 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9142 binder. Binder switches that are normally appended by @command{gnatmake}
9143 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9144 A limitation of this syntax is that the name and path name of the executable
9145 itself must not include any embedded spaces.
9146
9147 @item --GNATLINK=@var{linker_name}
9148 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9149 Program used for linking. The default is `@command{gnatlink}'. You need to
9150 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9151 or other separator characters. As an example @option{--GNATLINK="lan -x
9152 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9153 linker. Linker switches that are normally appended by @command{gnatmake} to
9154 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9155 A limitation of this syntax is that the name and path name of the executable
9156 itself must not include any embedded spaces.
9157
9158 @end ifclear
9159
9160 @item ^-a^/ALL_FILES^
9161 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9162 Consider all files in the make process, even the GNAT internal system
9163 files (for example, the predefined Ada library files), as well as any
9164 locked files. Locked files are files whose ALI file is write-protected.
9165 By default,
9166 @command{gnatmake} does not check these files,
9167 because the assumption is that the GNAT internal files are properly up
9168 to date, and also that any write protected ALI files have been properly
9169 installed. Note that if there is an installation problem, such that one
9170 of these files is not up to date, it will be properly caught by the
9171 binder.
9172 You may have to specify this switch if you are working on GNAT
9173 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9174 in conjunction with @option{^-f^/FORCE_COMPILE^}
9175 if you need to recompile an entire application,
9176 including run-time files, using special configuration pragmas,
9177 such as a @code{Normalize_Scalars} pragma.
9178
9179 By default
9180 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9181 internal files with
9182 @ifclear vms
9183 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9184 @end ifclear
9185 @ifset vms
9186 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9187 @end ifset
9188
9189 @item ^-b^/ACTIONS=BIND^
9190 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9191 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9192 compilation and binding, but no link.
9193 Can be combined with @option{^-l^/ACTIONS=LINK^}
9194 to do binding and linking. When not combined with
9195 @option{^-c^/ACTIONS=COMPILE^}
9196 all the units in the closure of the main program must have been previously
9197 compiled and must be up to date. The root unit specified by @var{file_name}
9198 may be given without extension, with the source extension or, if no GNAT
9199 Project File is specified, with the ALI file extension.
9200
9201 @item ^-c^/ACTIONS=COMPILE^
9202 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9203 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9204 is also specified. Do not perform linking, except if both
9205 @option{^-b^/ACTIONS=BIND^} and
9206 @option{^-l^/ACTIONS=LINK^} are also specified.
9207 If the root unit specified by @var{file_name} is not a main unit, this is the
9208 default. Otherwise @command{gnatmake} will attempt binding and linking
9209 unless all objects are up to date and the executable is more recent than
9210 the objects.
9211
9212 @item ^-C^/MAPPING^
9213 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9214 Use a temporary mapping file. A mapping file is a way to communicate to the
9215 compiler two mappings: from unit names to file names (without any directory
9216 information) and from file names to path names (with full directory
9217 information). These mappings are used by the compiler to short-circuit the path
9218 search. When @command{gnatmake} is invoked with this switch, it will create
9219 a temporary mapping file, initially populated by the project manager,
9220 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9221 Each invocation of the compiler will add the newly accessed sources to the
9222 mapping file. This will improve the source search during the next invocation
9223 of the compiler.
9224
9225 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9226 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9227 Use a specific mapping file. The file, specified as a path name (absolute or
9228 relative) by this switch, should already exist, otherwise the switch is
9229 ineffective. The specified mapping file will be communicated to the compiler.
9230 This switch is not compatible with a project file
9231 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9232 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9233
9234 @item ^-d^/DISPLAY_PROGRESS^
9235 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9236 Display progress for each source, up to date or not, as a single line
9237
9238 @smallexample
9239 completed x out of y (zz%)
9240 @end smallexample
9241
9242 If the file needs to be compiled this is displayed after the invocation of
9243 the compiler. These lines are displayed even in quiet output mode.
9244
9245 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9246 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9247 Put all object files and ALI file in directory @var{dir}.
9248 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9249 and ALI files go in the current working directory.
9250
9251 This switch cannot be used when using a project file.
9252
9253 @ifclear vms
9254 @item -eL
9255 @cindex @option{-eL} (@command{gnatmake})
9256 Follow all symbolic links when processing project files.
9257 @end ifclear
9258
9259 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9260 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9261 Output the commands for the compiler, the binder and the linker
9262 on ^standard output^SYS$OUTPUT^,
9263 instead of ^standard error^SYS$ERROR^.
9264
9265 @item ^-f^/FORCE_COMPILE^
9266 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9267 Force recompilations. Recompile all sources, even though some object
9268 files may be up to date, but don't recompile predefined or GNAT internal
9269 files or locked files (files with a write-protected ALI file),
9270 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9271
9272 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9273 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9274 When using project files, if some errors or warnings are detected during
9275 parsing and verbose mode is not in effect (no use of switch
9276 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9277 file, rather than its simple file name.
9278
9279 @item ^-g^/DEBUG^
9280 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9281 Enable debugging. This switch is simply passed to the compiler and to the
9282 linker.
9283
9284 @item ^-i^/IN_PLACE^
9285 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9286 In normal mode, @command{gnatmake} compiles all object files and ALI files
9287 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9288 then instead object files and ALI files that already exist are overwritten
9289 in place. This means that once a large project is organized into separate
9290 directories in the desired manner, then @command{gnatmake} will automatically
9291 maintain and update this organization. If no ALI files are found on the
9292 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9293 the new object and ALI files are created in the
9294 directory containing the source being compiled. If another organization
9295 is desired, where objects and sources are kept in different directories,
9296 a useful technique is to create dummy ALI files in the desired directories.
9297 When detecting such a dummy file, @command{gnatmake} will be forced to
9298 recompile the corresponding source file, and it will be put the resulting
9299 object and ALI files in the directory where it found the dummy file.
9300
9301 @item ^-j^/PROCESSES=^@var{n}
9302 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9303 @cindex Parallel make
9304 Use @var{n} processes to carry out the (re)compilations. On a
9305 multiprocessor machine compilations will occur in parallel. In the
9306 event of compilation errors, messages from various compilations might
9307 get interspersed (but @command{gnatmake} will give you the full ordered
9308 list of failing compiles at the end). If this is problematic, rerun
9309 the make process with n set to 1 to get a clean list of messages.
9310
9311 @item ^-k^/CONTINUE_ON_ERROR^
9312 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9313 Keep going. Continue as much as possible after a compilation error. To
9314 ease the programmer's task in case of compilation errors, the list of
9315 sources for which the compile fails is given when @command{gnatmake}
9316 terminates.
9317
9318 If @command{gnatmake} is invoked with several @file{file_names} and with this
9319 switch, if there are compilation errors when building an executable,
9320 @command{gnatmake} will not attempt to build the following executables.
9321
9322 @item ^-l^/ACTIONS=LINK^
9323 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9324 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9325 and linking. Linking will not be performed if combined with
9326 @option{^-c^/ACTIONS=COMPILE^}
9327 but not with @option{^-b^/ACTIONS=BIND^}.
9328 When not combined with @option{^-b^/ACTIONS=BIND^}
9329 all the units in the closure of the main program must have been previously
9330 compiled and must be up to date, and the main program needs to have been bound.
9331 The root unit specified by @var{file_name}
9332 may be given without extension, with the source extension or, if no GNAT
9333 Project File is specified, with the ALI file extension.
9334
9335 @item ^-m^/MINIMAL_RECOMPILATION^
9336 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9337 Specify that the minimum necessary amount of recompilations
9338 be performed. In this mode @command{gnatmake} ignores time
9339 stamp differences when the only
9340 modifications to a source file consist in adding/removing comments,
9341 empty lines, spaces or tabs. This means that if you have changed the
9342 comments in a source file or have simply reformatted it, using this
9343 switch will tell @command{gnatmake} not to recompile files that depend on it
9344 (provided other sources on which these files depend have undergone no
9345 semantic modifications). Note that the debugging information may be
9346 out of date with respect to the sources if the @option{-m} switch causes
9347 a compilation to be switched, so the use of this switch represents a
9348 trade-off between compilation time and accurate debugging information.
9349
9350 @item ^-M^/DEPENDENCIES_LIST^
9351 @cindex Dependencies, producing list
9352 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9353 Check if all objects are up to date. If they are, output the object
9354 dependences to @file{stdout} in a form that can be directly exploited in
9355 a @file{Makefile}. By default, each source file is prefixed with its
9356 (relative or absolute) directory name. This name is whatever you
9357 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9358 and @option{^-I^/SEARCH^} switches. If you use
9359 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9360 @option{^-q^/QUIET^}
9361 (see below), only the source file names,
9362 without relative paths, are output. If you just specify the
9363 @option{^-M^/DEPENDENCIES_LIST^}
9364 switch, dependencies of the GNAT internal system files are omitted. This
9365 is typically what you want. If you also specify
9366 the @option{^-a^/ALL_FILES^} switch,
9367 dependencies of the GNAT internal files are also listed. Note that
9368 dependencies of the objects in external Ada libraries (see switch
9369 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9370 are never reported.
9371
9372 @item ^-n^/DO_OBJECT_CHECK^
9373 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9374 Don't compile, bind, or link. Checks if all objects are up to date.
9375 If they are not, the full name of the first file that needs to be
9376 recompiled is printed.
9377 Repeated use of this option, followed by compiling the indicated source
9378 file, will eventually result in recompiling all required units.
9379
9380 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9381 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9382 Output executable name. The name of the final executable program will be
9383 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9384 name for the executable will be the name of the input file in appropriate form
9385 for an executable file on the host system.
9386
9387 This switch cannot be used when invoking @command{gnatmake} with several
9388 @file{file_names}.
9389
9390 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9391 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9392 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9393 automatically missing object directories, library directories and exec
9394 directories.
9395
9396 @item ^-P^/PROJECT_FILE=^@var{project}
9397 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9398 Use project file @var{project}. Only one such switch can be used.
9399 @xref{gnatmake and Project Files}.
9400
9401 @item ^-q^/QUIET^
9402 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9403 Quiet. When this flag is not set, the commands carried out by
9404 @command{gnatmake} are displayed.
9405
9406 @item ^-s^/SWITCH_CHECK/^
9407 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9408 Recompile if compiler switches have changed since last compilation.
9409 All compiler switches but -I and -o are taken into account in the
9410 following way:
9411 orders between different ``first letter'' switches are ignored, but
9412 orders between same switches are taken into account. For example,
9413 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9414 is equivalent to @option{-O -g}.
9415
9416 This switch is recommended when Integrated Preprocessing is used.
9417
9418 @item ^-u^/UNIQUE^
9419 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9420 Unique. Recompile at most the main files. It implies -c. Combined with
9421 -f, it is equivalent to calling the compiler directly. Note that using
9422 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9423 (@pxref{Project Files and Main Subprograms}).
9424
9425 @item ^-U^/ALL_PROJECTS^
9426 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9427 When used without a project file or with one or several mains on the command
9428 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9429 on the command line, all sources of all project files are checked and compiled
9430 if not up to date, and libraries are rebuilt, if necessary.
9431
9432 @item ^-v^/REASONS^
9433 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9434 Verbose. Display the reason for all recompilations @command{gnatmake}
9435 decides are necessary, with the highest verbosity level.
9436
9437 @item ^-vl^/LOW_VERBOSITY^
9438 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9439 Verbosity level Low. Display fewer lines than in verbosity Medium.
9440
9441 @item ^-vm^/MEDIUM_VERBOSITY^
9442 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9443 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9444
9445 @item ^-vh^/HIGH_VERBOSITY^
9446 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9447 Verbosity level High. Equivalent to ^-v^/REASONS^.
9448
9449 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9450 Indicate the verbosity of the parsing of GNAT project files.
9451 @xref{Switches Related to Project Files}.
9452
9453 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9454 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9455 Indicate that sources that are not part of any Project File may be compiled.
9456 Normally, when using Project Files, only sources that are part of a Project
9457 File may be compile. When this switch is used, a source outside of all Project
9458 Files may be compiled. The ALI file and the object file will be put in the
9459 object directory of the main Project. The compilation switches used will only
9460 be those specified on the command line. Even when
9461 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9462 command line need to be sources of a project file.
9463
9464 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9465 Indicate that external variable @var{name} has the value @var{value}.
9466 The Project Manager will use this value for occurrences of
9467 @code{external(name)} when parsing the project file.
9468 @xref{Switches Related to Project Files}.
9469
9470 @item ^-z^/NOMAIN^
9471 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9472 No main subprogram. Bind and link the program even if the unit name
9473 given on the command line is a package name. The resulting executable
9474 will execute the elaboration routines of the package and its closure,
9475 then the finalization routines.
9476
9477 @end table
9478
9479 @table @asis
9480 @item @command{gcc} @asis{switches}
9481 @ifclear vms
9482 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9483 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9484 @end ifclear
9485 @ifset vms
9486 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9487 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9488 automatically treated as a compiler switch, and passed on to all
9489 compilations that are carried out.
9490 @end ifset
9491 @end table
9492
9493 @noindent
9494 Source and library search path switches:
9495
9496 @table @option
9497 @c !sort!
9498 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9499 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9500 When looking for source files also look in directory @var{dir}.
9501 The order in which source files search is undertaken is
9502 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9503
9504 @item ^-aL^/SKIP_MISSING=^@var{dir}
9505 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9506 Consider @var{dir} as being an externally provided Ada library.
9507 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9508 files have been located in directory @var{dir}. This allows you to have
9509 missing bodies for the units in @var{dir} and to ignore out of date bodies
9510 for the same units. You still need to specify
9511 the location of the specs for these units by using the switches
9512 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9513 or @option{^-I^/SEARCH=^@var{dir}}.
9514 Note: this switch is provided for compatibility with previous versions
9515 of @command{gnatmake}. The easier method of causing standard libraries
9516 to be excluded from consideration is to write-protect the corresponding
9517 ALI files.
9518
9519 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9520 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9521 When searching for library and object files, look in directory
9522 @var{dir}. The order in which library files are searched is described in
9523 @ref{Search Paths for gnatbind}.
9524
9525 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9526 @cindex Search paths, for @command{gnatmake}
9527 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9528 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9529 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9530
9531 @item ^-I^/SEARCH=^@var{dir}
9532 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9533 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9534 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9535
9536 @item ^-I-^/NOCURRENT_DIRECTORY^
9537 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9538 @cindex Source files, suppressing search
9539 Do not look for source files in the directory containing the source
9540 file named in the command line.
9541 Do not look for ALI or object files in the directory
9542 where @command{gnatmake} was invoked.
9543
9544 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9545 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9546 @cindex Linker libraries
9547 Add directory @var{dir} to the list of directories in which the linker
9548 will search for libraries. This is equivalent to
9549 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9550 @ifclear vms
9551 Furthermore, under Windows, the sources pointed to by the libraries path
9552 set in the registry are not searched for.
9553 @end ifclear
9554
9555 @item -nostdinc
9556 @cindex @option{-nostdinc} (@command{gnatmake})
9557 Do not look for source files in the system default directory.
9558
9559 @item -nostdlib
9560 @cindex @option{-nostdlib} (@command{gnatmake})
9561 Do not look for library files in the system default directory.
9562
9563 @item --RTS=@var{rts-path}
9564 @cindex @option{--RTS} (@command{gnatmake})
9565 Specifies the default location of the runtime library. GNAT looks for the
9566 runtime
9567 in the following directories, and stops as soon as a valid runtime is found
9568 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9569 @file{ada_object_path} present):
9570
9571 @itemize @bullet
9572 @item <current directory>/$rts_path
9573
9574 @item <default-search-dir>/$rts_path
9575
9576 @item <default-search-dir>/rts-$rts_path
9577 @end itemize
9578
9579 @noindent
9580 The selected path is handled like a normal RTS path.
9581
9582 @end table
9583
9584 @node Mode Switches for gnatmake
9585 @section Mode Switches for @command{gnatmake}
9586
9587 @noindent
9588 The mode switches (referred to as @code{mode_switches}) allow the
9589 inclusion of switches that are to be passed to the compiler itself, the
9590 binder or the linker. The effect of a mode switch is to cause all
9591 subsequent switches up to the end of the switch list, or up to the next
9592 mode switch, to be interpreted as switches to be passed on to the
9593 designated component of GNAT.
9594
9595 @table @option
9596 @c !sort!
9597 @item -cargs @var{switches}
9598 @cindex @option{-cargs} (@command{gnatmake})
9599 Compiler switches. Here @var{switches} is a list of switches
9600 that are valid switches for @command{gcc}. They will be passed on to
9601 all compile steps performed by @command{gnatmake}.
9602
9603 @item -bargs @var{switches}
9604 @cindex @option{-bargs} (@command{gnatmake})
9605 Binder switches. Here @var{switches} is a list of switches
9606 that are valid switches for @code{gnatbind}. They will be passed on to
9607 all bind steps performed by @command{gnatmake}.
9608
9609 @item -largs @var{switches}
9610 @cindex @option{-largs} (@command{gnatmake})
9611 Linker switches. Here @var{switches} is a list of switches
9612 that are valid switches for @command{gnatlink}. They will be passed on to
9613 all link steps performed by @command{gnatmake}.
9614
9615 @item -margs @var{switches}
9616 @cindex @option{-margs} (@command{gnatmake})
9617 Make switches. The switches are directly interpreted by @command{gnatmake},
9618 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9619 or @option{-largs}.
9620 @end table
9621
9622 @node Notes on the Command Line
9623 @section Notes on the Command Line
9624
9625 @noindent
9626 This section contains some additional useful notes on the operation
9627 of the @command{gnatmake} command.
9628
9629 @itemize @bullet
9630 @item
9631 @cindex Recompilation, by @command{gnatmake}
9632 If @command{gnatmake} finds no ALI files, it recompiles the main program
9633 and all other units required by the main program.
9634 This means that @command{gnatmake}
9635 can be used for the initial compile, as well as during subsequent steps of
9636 the development cycle.
9637
9638 @item
9639 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9640 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9641 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9642 warning.
9643
9644 @item
9645 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9646 is used to specify both source and
9647 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9648 instead if you just want to specify
9649 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9650 if you want to specify library paths
9651 only.
9652
9653 @item
9654 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9655 This may conveniently be used to exclude standard libraries from
9656 consideration and in particular it means that the use of the
9657 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9658 unless @option{^-a^/ALL_FILES^} is also specified.
9659
9660 @item
9661 @command{gnatmake} has been designed to make the use of Ada libraries
9662 particularly convenient. Assume you have an Ada library organized
9663 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9664 of your Ada compilation units,
9665 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9666 specs of these units, but no bodies. Then to compile a unit
9667 stored in @code{main.adb}, which uses this Ada library you would just type
9668
9669 @smallexample
9670 @ifclear vms
9671 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9672 @end ifclear
9673 @ifset vms
9674 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9675 /SKIP_MISSING=@i{[OBJ_DIR]} main
9676 @end ifset
9677 @end smallexample
9678
9679 @item
9680 Using @command{gnatmake} along with the
9681 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9682 switch provides a mechanism for avoiding unnecessary recompilations. Using
9683 this switch,
9684 you can update the comments/format of your
9685 source files without having to recompile everything. Note, however, that
9686 adding or deleting lines in a source files may render its debugging
9687 info obsolete. If the file in question is a spec, the impact is rather
9688 limited, as that debugging info will only be useful during the
9689 elaboration phase of your program. For bodies the impact can be more
9690 significant. In all events, your debugger will warn you if a source file
9691 is more recent than the corresponding object, and alert you to the fact
9692 that the debugging information may be out of date.
9693 @end itemize
9694
9695 @node How gnatmake Works
9696 @section How @command{gnatmake} Works
9697
9698 @noindent
9699 Generally @command{gnatmake} automatically performs all necessary
9700 recompilations and you don't need to worry about how it works. However,
9701 it may be useful to have some basic understanding of the @command{gnatmake}
9702 approach and in particular to understand how it uses the results of
9703 previous compilations without incorrectly depending on them.
9704
9705 First a definition: an object file is considered @dfn{up to date} if the
9706 corresponding ALI file exists and if all the source files listed in the
9707 dependency section of this ALI file have time stamps matching those in
9708 the ALI file. This means that neither the source file itself nor any
9709 files that it depends on have been modified, and hence there is no need
9710 to recompile this file.
9711
9712 @command{gnatmake} works by first checking if the specified main unit is up
9713 to date. If so, no compilations are required for the main unit. If not,
9714 @command{gnatmake} compiles the main program to build a new ALI file that
9715 reflects the latest sources. Then the ALI file of the main unit is
9716 examined to find all the source files on which the main program depends,
9717 and @command{gnatmake} recursively applies the above procedure on all these
9718 files.
9719
9720 This process ensures that @command{gnatmake} only trusts the dependencies
9721 in an existing ALI file if they are known to be correct. Otherwise it
9722 always recompiles to determine a new, guaranteed accurate set of
9723 dependencies. As a result the program is compiled ``upside down'' from what may
9724 be more familiar as the required order of compilation in some other Ada
9725 systems. In particular, clients are compiled before the units on which
9726 they depend. The ability of GNAT to compile in any order is critical in
9727 allowing an order of compilation to be chosen that guarantees that
9728 @command{gnatmake} will recompute a correct set of new dependencies if
9729 necessary.
9730
9731 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9732 imported by several of the executables, it will be recompiled at most once.
9733
9734 Note: when using non-standard naming conventions
9735 (@pxref{Using Other File Names}), changing through a configuration pragmas
9736 file the version of a source and invoking @command{gnatmake} to recompile may
9737 have no effect, if the previous version of the source is still accessible
9738 by @command{gnatmake}. It may be necessary to use the switch
9739 ^-f^/FORCE_COMPILE^.
9740
9741 @node Examples of gnatmake Usage
9742 @section Examples of @command{gnatmake} Usage
9743
9744 @table @code
9745 @item gnatmake hello.adb
9746 Compile all files necessary to bind and link the main program
9747 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9748 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9749
9750 @item gnatmake main1 main2 main3
9751 Compile all files necessary to bind and link the main programs
9752 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9753 (containing unit @code{Main2}) and @file{main3.adb}
9754 (containing unit @code{Main3}) and bind and link the resulting object files
9755 to generate three executable files @file{^main1^MAIN1.EXE^},
9756 @file{^main2^MAIN2.EXE^}
9757 and @file{^main3^MAIN3.EXE^}.
9758
9759 @ifclear vms
9760 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9761 @end ifclear
9762
9763 @ifset vms
9764 @item gnatmake Main_Unit /QUIET
9765 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9766 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9767 @end ifset
9768 Compile all files necessary to bind and link the main program unit
9769 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9770 be done with optimization level 2 and the order of elaboration will be
9771 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9772 displaying commands it is executing.
9773 @end table
9774
9775 @c *************************
9776 @node Improving Performance
9777 @chapter Improving Performance
9778 @cindex Improving performance
9779
9780 @noindent
9781 This chapter presents several topics related to program performance.
9782 It first describes some of the tradeoffs that need to be considered
9783 and some of the techniques for making your program run faster.
9784 It then documents the @command{gnatelim} tool and unused subprogram/data
9785 elimination feature, which can reduce the size of program executables.
9786
9787 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9788 driver (see @ref{The GNAT Driver and Project Files}).
9789
9790 @ifnottex
9791 @menu
9792 * Performance Considerations::
9793 * Text_IO Suggestions::
9794 * Reducing Size of Ada Executables with gnatelim::
9795 * Reducing Size of Executables with unused subprogram/data elimination::
9796 @end menu
9797 @end ifnottex
9798
9799 @c *****************************
9800 @node Performance Considerations
9801 @section Performance Considerations
9802
9803 @noindent
9804 The GNAT system provides a number of options that allow a trade-off
9805 between
9806
9807 @itemize @bullet
9808 @item
9809 performance of the generated code
9810
9811 @item
9812 speed of compilation
9813
9814 @item
9815 minimization of dependences and recompilation
9816
9817 @item
9818 the degree of run-time checking.
9819 @end itemize
9820
9821 @noindent
9822 The defaults (if no options are selected) aim at improving the speed
9823 of compilation and minimizing dependences, at the expense of performance
9824 of the generated code:
9825
9826 @itemize @bullet
9827 @item
9828 no optimization
9829
9830 @item
9831 no inlining of subprogram calls
9832
9833 @item
9834 all run-time checks enabled except overflow and elaboration checks
9835 @end itemize
9836
9837 @noindent
9838 These options are suitable for most program development purposes. This
9839 chapter describes how you can modify these choices, and also provides
9840 some guidelines on debugging optimized code.
9841
9842 @menu
9843 * Controlling Run-Time Checks::
9844 * Use of Restrictions::
9845 * Optimization Levels::
9846 * Debugging Optimized Code::
9847 * Inlining of Subprograms::
9848 * Other Optimization Switches::
9849 * Optimization and Strict Aliasing::
9850
9851 @ifset vms
9852 * Coverage Analysis::
9853 @end ifset
9854 @end menu
9855
9856 @node Controlling Run-Time Checks
9857 @subsection Controlling Run-Time Checks
9858
9859 @noindent
9860 By default, GNAT generates all run-time checks, except integer overflow
9861 checks, stack overflow checks, and checks for access before elaboration on
9862 subprogram calls. The latter are not required in default mode, because all
9863 necessary checking is done at compile time.
9864 @cindex @option{-gnatp} (@command{gcc})
9865 @cindex @option{-gnato} (@command{gcc})
9866 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9867 be modified. @xref{Run-Time Checks}.
9868
9869 Our experience is that the default is suitable for most development
9870 purposes.
9871
9872 We treat integer overflow specially because these
9873 are quite expensive and in our experience are not as important as other
9874 run-time checks in the development process. Note that division by zero
9875 is not considered an overflow check, and divide by zero checks are
9876 generated where required by default.
9877
9878 Elaboration checks are off by default, and also not needed by default, since
9879 GNAT uses a static elaboration analysis approach that avoids the need for
9880 run-time checking. This manual contains a full chapter discussing the issue
9881 of elaboration checks, and if the default is not satisfactory for your use,
9882 you should read this chapter.
9883
9884 For validity checks, the minimal checks required by the Ada Reference
9885 Manual (for case statements and assignments to array elements) are on
9886 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9887 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9888 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9889 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9890 are also suppressed entirely if @option{-gnatp} is used.
9891
9892 @cindex Overflow checks
9893 @cindex Checks, overflow
9894 @findex Suppress
9895 @findex Unsuppress
9896 @cindex pragma Suppress
9897 @cindex pragma Unsuppress
9898 Note that the setting of the switches controls the default setting of
9899 the checks. They may be modified using either @code{pragma Suppress} (to
9900 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9901 checks) in the program source.
9902
9903 @node Use of Restrictions
9904 @subsection Use of Restrictions
9905
9906 @noindent
9907 The use of pragma Restrictions allows you to control which features are
9908 permitted in your program. Apart from the obvious point that if you avoid
9909 relatively expensive features like finalization (enforceable by the use
9910 of pragma Restrictions (No_Finalization), the use of this pragma does not
9911 affect the generated code in most cases.
9912
9913 One notable exception to this rule is that the possibility of task abort
9914 results in some distributed overhead, particularly if finalization or
9915 exception handlers are used. The reason is that certain sections of code
9916 have to be marked as non-abortable.
9917
9918 If you use neither the @code{abort} statement, nor asynchronous transfer
9919 of control (@code{select @dots{} then abort}), then this distributed overhead
9920 is removed, which may have a general positive effect in improving
9921 overall performance. Especially code involving frequent use of tasking
9922 constructs and controlled types will show much improved performance.
9923 The relevant restrictions pragmas are
9924
9925 @smallexample @c ada
9926 pragma Restrictions (No_Abort_Statements);
9927 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9928 @end smallexample
9929
9930 @noindent
9931 It is recommended that these restriction pragmas be used if possible. Note
9932 that this also means that you can write code without worrying about the
9933 possibility of an immediate abort at any point.
9934
9935 @node Optimization Levels
9936 @subsection Optimization Levels
9937 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9938
9939 @noindent
9940 Without any optimization ^option,^qualifier,^
9941 the compiler's goal is to reduce the cost of
9942 compilation and to make debugging produce the expected results.
9943 Statements are independent: if you stop the program with a breakpoint between
9944 statements, you can then assign a new value to any variable or change
9945 the program counter to any other statement in the subprogram and get exactly
9946 the results you would expect from the source code.
9947
9948 Turning on optimization makes the compiler attempt to improve the
9949 performance and/or code size at the expense of compilation time and
9950 possibly the ability to debug the program.
9951
9952 If you use multiple
9953 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9954 the last such option is the one that is effective.
9955
9956 @noindent
9957 The default is optimization off. This results in the fastest compile
9958 times, but GNAT makes absolutely no attempt to optimize, and the
9959 generated programs are considerably larger and slower than when
9960 optimization is enabled. You can use the
9961 @ifclear vms
9962 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9963 @option{-O2}, @option{-O3}, and @option{-Os})
9964 @end ifclear
9965 @ifset vms
9966 @code{OPTIMIZE} qualifier
9967 @end ifset
9968 to @command{gcc} to control the optimization level:
9969
9970 @table @option
9971 @item ^-O0^/OPTIMIZE=NONE^
9972 No optimization (the default);
9973 generates unoptimized code but has
9974 the fastest compilation time.
9975
9976 Note that many other compilers do fairly extensive optimization
9977 even if ``no optimization'' is specified. With gcc, it is
9978 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9979 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9980 really does mean no optimization at all. This difference between
9981 gcc and other compilers should be kept in mind when doing
9982 performance comparisons.
9983
9984 @item ^-O1^/OPTIMIZE=SOME^
9985 Moderate optimization;
9986 optimizes reasonably well but does not
9987 degrade compilation time significantly.
9988
9989 @item ^-O2^/OPTIMIZE=ALL^
9990 @ifset vms
9991 @itemx /OPTIMIZE=DEVELOPMENT
9992 @end ifset
9993 Full optimization;
9994 generates highly optimized code and has
9995 the slowest compilation time.
9996
9997 @item ^-O3^/OPTIMIZE=INLINING^
9998 Full optimization as in @option{-O2},
9999 and also attempts automatic inlining of small
10000 subprograms within a unit (@pxref{Inlining of Subprograms}).
10001
10002 @item ^-Os^/OPTIMIZE=SPACE^
10003 Optimize space usage of resulting program.
10004 @end table
10005
10006 @noindent
10007 Higher optimization levels perform more global transformations on the
10008 program and apply more expensive analysis algorithms in order to generate
10009 faster and more compact code. The price in compilation time, and the
10010 resulting improvement in execution time,
10011 both depend on the particular application and the hardware environment.
10012 You should experiment to find the best level for your application.
10013
10014 Since the precise set of optimizations done at each level will vary from
10015 release to release (and sometime from target to target), it is best to think
10016 of the optimization settings in general terms.
10017 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10018 the GNU Compiler Collection (GCC)}, for details about
10019 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10020 individually enable or disable specific optimizations.
10021
10022 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10023 been tested extensively at all optimization levels. There are some bugs
10024 which appear only with optimization turned on, but there have also been
10025 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10026 level of optimization does not improve the reliability of the code
10027 generator, which in practice is highly reliable at all optimization
10028 levels.
10029
10030 Note regarding the use of @option{-O3}: The use of this optimization level
10031 is generally discouraged with GNAT, since it often results in larger
10032 executables which run more slowly. See further discussion of this point
10033 in @ref{Inlining of Subprograms}.
10034
10035 @node Debugging Optimized Code
10036 @subsection Debugging Optimized Code
10037 @cindex Debugging optimized code
10038 @cindex Optimization and debugging
10039
10040 @noindent
10041 Although it is possible to do a reasonable amount of debugging at
10042 @ifclear vms
10043 nonzero optimization levels,
10044 the higher the level the more likely that
10045 @end ifclear
10046 @ifset vms
10047 @option{/OPTIMIZE} settings other than @code{NONE},
10048 such settings will make it more likely that
10049 @end ifset
10050 source-level constructs will have been eliminated by optimization.
10051 For example, if a loop is strength-reduced, the loop
10052 control variable may be completely eliminated and thus cannot be
10053 displayed in the debugger.
10054 This can only happen at @option{-O2} or @option{-O3}.
10055 Explicit temporary variables that you code might be eliminated at
10056 ^level^setting^ @option{-O1} or higher.
10057
10058 The use of the @option{^-g^/DEBUG^} switch,
10059 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10060 which is needed for source-level debugging,
10061 affects the size of the program executable on disk,
10062 and indeed the debugging information can be quite large.
10063 However, it has no effect on the generated code (and thus does not
10064 degrade performance)
10065
10066 Since the compiler generates debugging tables for a compilation unit before
10067 it performs optimizations, the optimizing transformations may invalidate some
10068 of the debugging data. You therefore need to anticipate certain
10069 anomalous situations that may arise while debugging optimized code.
10070 These are the most common cases:
10071
10072 @enumerate
10073 @item
10074 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10075 commands show
10076 the PC bouncing back and forth in the code. This may result from any of
10077 the following optimizations:
10078
10079 @itemize @bullet
10080 @item
10081 @i{Common subexpression elimination:} using a single instance of code for a
10082 quantity that the source computes several times. As a result you
10083 may not be able to stop on what looks like a statement.
10084
10085 @item
10086 @i{Invariant code motion:} moving an expression that does not change within a
10087 loop, to the beginning of the loop.
10088
10089 @item
10090 @i{Instruction scheduling:} moving instructions so as to
10091 overlap loads and stores (typically) with other code, or in
10092 general to move computations of values closer to their uses. Often
10093 this causes you to pass an assignment statement without the assignment
10094 happening and then later bounce back to the statement when the
10095 value is actually needed. Placing a breakpoint on a line of code
10096 and then stepping over it may, therefore, not always cause all the
10097 expected side-effects.
10098 @end itemize
10099
10100 @item
10101 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10102 two identical pieces of code are merged and the program counter suddenly
10103 jumps to a statement that is not supposed to be executed, simply because
10104 it (and the code following) translates to the same thing as the code
10105 that @emph{was} supposed to be executed. This effect is typically seen in
10106 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10107 a @code{break} in a C @code{^switch^switch^} statement.
10108
10109 @item
10110 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10111 There are various reasons for this effect:
10112
10113 @itemize @bullet
10114 @item
10115 In a subprogram prologue, a parameter may not yet have been moved to its
10116 ``home''.
10117
10118 @item
10119 A variable may be dead, and its register re-used. This is
10120 probably the most common cause.
10121
10122 @item
10123 As mentioned above, the assignment of a value to a variable may
10124 have been moved.
10125
10126 @item
10127 A variable may be eliminated entirely by value propagation or
10128 other means. In this case, GCC may incorrectly generate debugging
10129 information for the variable
10130 @end itemize
10131
10132 @noindent
10133 In general, when an unexpected value appears for a local variable or parameter
10134 you should first ascertain if that value was actually computed by
10135 your program, as opposed to being incorrectly reported by the debugger.
10136 Record fields or
10137 array elements in an object designated by an access value
10138 are generally less of a problem, once you have ascertained that the access
10139 value is sensible.
10140 Typically, this means checking variables in the preceding code and in the
10141 calling subprogram to verify that the value observed is explainable from other
10142 values (one must apply the procedure recursively to those
10143 other values); or re-running the code and stopping a little earlier
10144 (perhaps before the call) and stepping to better see how the variable obtained
10145 the value in question; or continuing to step @emph{from} the point of the
10146 strange value to see if code motion had simply moved the variable's
10147 assignments later.
10148 @end enumerate
10149
10150 @noindent
10151 In light of such anomalies, a recommended technique is to use @option{-O0}
10152 early in the software development cycle, when extensive debugging capabilities
10153 are most needed, and then move to @option{-O1} and later @option{-O2} as
10154 the debugger becomes less critical.
10155 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10156 a release management issue.
10157 @ifclear vms
10158 Note that if you use @option{-g} you can then use the @command{strip} program
10159 on the resulting executable,
10160 which removes both debugging information and global symbols.
10161 @end ifclear
10162
10163 @node Inlining of Subprograms
10164 @subsection Inlining of Subprograms
10165
10166 @noindent
10167 A call to a subprogram in the current unit is inlined if all the
10168 following conditions are met:
10169
10170 @itemize @bullet
10171 @item
10172 The optimization level is at least @option{-O1}.
10173
10174 @item
10175 The called subprogram is suitable for inlining: It must be small enough
10176 and not contain something that @command{gcc} cannot support in inlined
10177 subprograms.
10178
10179 @item
10180 @cindex pragma Inline
10181 @findex Inline
10182 Either @code{pragma Inline} applies to the subprogram, or it is local
10183 to the unit and called once from within it, or it is small and automatic
10184 inlining (optimization level @option{-O3}) is specified.
10185 @end itemize
10186
10187 @noindent
10188 Calls to subprograms in @code{with}'ed units are normally not inlined.
10189 To achieve actual inlining (that is, replacement of the call by the code
10190 in the body of the subprogram), the following conditions must all be true.
10191
10192 @itemize @bullet
10193 @item
10194 The optimization level is at least @option{-O1}.
10195
10196 @item
10197 The called subprogram is suitable for inlining: It must be small enough
10198 and not contain something that @command{gcc} cannot support in inlined
10199 subprograms.
10200
10201 @item
10202 The call appears in a body (not in a package spec).
10203
10204 @item
10205 There is a @code{pragma Inline} for the subprogram.
10206
10207 @item
10208 @cindex @option{-gnatn} (@command{gcc})
10209 The @option{^-gnatn^/INLINE^} switch
10210 is used in the @command{gcc} command line
10211 @end itemize
10212
10213 Even if all these conditions are met, it may not be possible for
10214 the compiler to inline the call, due to the length of the body,
10215 or features in the body that make it impossible for the compiler
10216 to do the inlining.
10217
10218 Note that specifying the @option{-gnatn} switch causes additional
10219 compilation dependencies. Consider the following:
10220
10221 @smallexample @c ada
10222 @cartouche
10223 package R is
10224 procedure Q;
10225 pragma Inline (Q);
10226 end R;
10227 package body R is
10228 @dots{}
10229 end R;
10230
10231 with R;
10232 procedure Main is
10233 begin
10234 @dots{}
10235 R.Q;
10236 end Main;
10237 @end cartouche
10238 @end smallexample
10239
10240 @noindent
10241 With the default behavior (no @option{-gnatn} switch specified), the
10242 compilation of the @code{Main} procedure depends only on its own source,
10243 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10244 means that editing the body of @code{R} does not require recompiling
10245 @code{Main}.
10246
10247 On the other hand, the call @code{R.Q} is not inlined under these
10248 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10249 is compiled, the call will be inlined if the body of @code{Q} is small
10250 enough, but now @code{Main} depends on the body of @code{R} in
10251 @file{r.adb} as well as on the spec. This means that if this body is edited,
10252 the main program must be recompiled. Note that this extra dependency
10253 occurs whether or not the call is in fact inlined by @command{gcc}.
10254
10255 The use of front end inlining with @option{-gnatN} generates similar
10256 additional dependencies.
10257
10258 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10259 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10260 can be used to prevent
10261 all inlining. This switch overrides all other conditions and ensures
10262 that no inlining occurs. The extra dependences resulting from
10263 @option{-gnatn} will still be active, even if
10264 this switch is used to suppress the resulting inlining actions.
10265
10266 @cindex @option{-fno-inline-functions} (@command{gcc})
10267 Note: The @option{-fno-inline-functions} switch can be used to prevent
10268 automatic inlining of small subprograms if @option{-O3} is used.
10269
10270 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10271 Note: The @option{-fno-inline-functions-called-once} switch
10272 can be used to prevent inlining of subprograms local to the unit
10273 and called once from within it if @option{-O1} is used.
10274
10275 Note regarding the use of @option{-O3}: There is no difference in inlining
10276 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10277 pragma @code{Inline} assuming the use of @option{-gnatn}
10278 or @option{-gnatN} (the switches that activate inlining). If you have used
10279 pragma @code{Inline} in appropriate cases, then it is usually much better
10280 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10281 in this case only has the effect of inlining subprograms you did not
10282 think should be inlined. We often find that the use of @option{-O3} slows
10283 down code by performing excessive inlining, leading to increased instruction
10284 cache pressure from the increased code size. So the bottom line here is
10285 that you should not automatically assume that @option{-O3} is better than
10286 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10287 it actually improves performance.
10288
10289 @node Other Optimization Switches
10290 @subsection Other Optimization Switches
10291 @cindex Optimization Switches
10292
10293 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10294 @command{gcc} optimization switches are potentially usable. These switches
10295 have not been extensively tested with GNAT but can generally be expected
10296 to work. Examples of switches in this category are
10297 @option{-funroll-loops} and
10298 the various target-specific @option{-m} options (in particular, it has been
10299 observed that @option{-march=pentium4} can significantly improve performance
10300 on appropriate machines). For full details of these switches, see
10301 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10302 the GNU Compiler Collection (GCC)}.
10303
10304 @node Optimization and Strict Aliasing
10305 @subsection Optimization and Strict Aliasing
10306 @cindex Aliasing
10307 @cindex Strict Aliasing
10308 @cindex No_Strict_Aliasing
10309
10310 @noindent
10311 The strong typing capabilities of Ada allow an optimizer to generate
10312 efficient code in situations where other languages would be forced to
10313 make worst case assumptions preventing such optimizations. Consider
10314 the following example:
10315
10316 @smallexample @c ada
10317 @cartouche
10318 procedure R is
10319 type Int1 is new Integer;
10320 type Int2 is new Integer;
10321 type Int1A is access Int1;
10322 type Int2A is access Int2;
10323 Int1V : Int1A;
10324 Int2V : Int2A;
10325 @dots{}
10326
10327 begin
10328 @dots{}
10329 for J in Data'Range loop
10330 if Data (J) = Int1V.all then
10331 Int2V.all := Int2V.all + 1;
10332 end if;
10333 end loop;
10334 @dots{}
10335 end R;
10336 @end cartouche
10337 @end smallexample
10338
10339 @noindent
10340 In this example, since the variable @code{Int1V} can only access objects
10341 of type @code{Int1}, and @code{Int2V} can only access objects of type
10342 @code{Int2}, there is no possibility that the assignment to
10343 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10344 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10345 for all iterations of the loop and avoid the extra memory reference
10346 required to dereference it each time through the loop.
10347
10348 This kind of optimization, called strict aliasing analysis, is
10349 triggered by specifying an optimization level of @option{-O2} or
10350 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10351 when access values are involved.
10352
10353 However, although this optimization is always correct in terms of
10354 the formal semantics of the Ada Reference Manual, difficulties can
10355 arise if features like @code{Unchecked_Conversion} are used to break
10356 the typing system. Consider the following complete program example:
10357
10358 @smallexample @c ada
10359 @cartouche
10360 package p1 is
10361 type int1 is new integer;
10362 type int2 is new integer;
10363 type a1 is access int1;
10364 type a2 is access int2;
10365 end p1;
10366
10367 with p1; use p1;
10368 package p2 is
10369 function to_a2 (Input : a1) return a2;
10370 end p2;
10371
10372 with Unchecked_Conversion;
10373 package body p2 is
10374 function to_a2 (Input : a1) return a2 is
10375 function to_a2u is
10376 new Unchecked_Conversion (a1, a2);
10377 begin
10378 return to_a2u (Input);
10379 end to_a2;
10380 end p2;
10381
10382 with p2; use p2;
10383 with p1; use p1;
10384 with Text_IO; use Text_IO;
10385 procedure m is
10386 v1 : a1 := new int1;
10387 v2 : a2 := to_a2 (v1);
10388 begin
10389 v1.all := 1;
10390 v2.all := 0;
10391 put_line (int1'image (v1.all));
10392 end;
10393 @end cartouche
10394 @end smallexample
10395
10396 @noindent
10397 This program prints out 0 in @option{-O0} or @option{-O1}
10398 mode, but it prints out 1 in @option{-O2} mode. That's
10399 because in strict aliasing mode, the compiler can and
10400 does assume that the assignment to @code{v2.all} could not
10401 affect the value of @code{v1.all}, since different types
10402 are involved.
10403
10404 This behavior is not a case of non-conformance with the standard, since
10405 the Ada RM specifies that an unchecked conversion where the resulting
10406 bit pattern is not a correct value of the target type can result in an
10407 abnormal value and attempting to reference an abnormal value makes the
10408 execution of a program erroneous. That's the case here since the result
10409 does not point to an object of type @code{int2}. This means that the
10410 effect is entirely unpredictable.
10411
10412 However, although that explanation may satisfy a language
10413 lawyer, in practice an applications programmer expects an
10414 unchecked conversion involving pointers to create true
10415 aliases and the behavior of printing 1 seems plain wrong.
10416 In this case, the strict aliasing optimization is unwelcome.
10417
10418 Indeed the compiler recognizes this possibility, and the
10419 unchecked conversion generates a warning:
10420
10421 @smallexample
10422 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10423 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10424 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10425 @end smallexample
10426
10427 @noindent
10428 Unfortunately the problem is recognized when compiling the body of
10429 package @code{p2}, but the actual "bad" code is generated while
10430 compiling the body of @code{m} and this latter compilation does not see
10431 the suspicious @code{Unchecked_Conversion}.
10432
10433 As implied by the warning message, there are approaches you can use to
10434 avoid the unwanted strict aliasing optimization in a case like this.
10435
10436 One possibility is to simply avoid the use of @option{-O2}, but
10437 that is a bit drastic, since it throws away a number of useful
10438 optimizations that do not involve strict aliasing assumptions.
10439
10440 A less drastic approach is to compile the program using the
10441 option @option{-fno-strict-aliasing}. Actually it is only the
10442 unit containing the dereferencing of the suspicious pointer
10443 that needs to be compiled. So in this case, if we compile
10444 unit @code{m} with this switch, then we get the expected
10445 value of zero printed. Analyzing which units might need
10446 the switch can be painful, so a more reasonable approach
10447 is to compile the entire program with options @option{-O2}
10448 and @option{-fno-strict-aliasing}. If the performance is
10449 satisfactory with this combination of options, then the
10450 advantage is that the entire issue of possible "wrong"
10451 optimization due to strict aliasing is avoided.
10452
10453 To avoid the use of compiler switches, the configuration
10454 pragma @code{No_Strict_Aliasing} with no parameters may be
10455 used to specify that for all access types, the strict
10456 aliasing optimization should be suppressed.
10457
10458 However, these approaches are still overkill, in that they causes
10459 all manipulations of all access values to be deoptimized. A more
10460 refined approach is to concentrate attention on the specific
10461 access type identified as problematic.
10462
10463 First, if a careful analysis of uses of the pointer shows
10464 that there are no possible problematic references, then
10465 the warning can be suppressed by bracketing the
10466 instantiation of @code{Unchecked_Conversion} to turn
10467 the warning off:
10468
10469 @smallexample @c ada
10470 pragma Warnings (Off);
10471 function to_a2u is
10472 new Unchecked_Conversion (a1, a2);
10473 pragma Warnings (On);
10474 @end smallexample
10475
10476 @noindent
10477 Of course that approach is not appropriate for this particular
10478 example, since indeed there is a problematic reference. In this
10479 case we can take one of two other approaches.
10480
10481 The first possibility is to move the instantiation of unchecked
10482 conversion to the unit in which the type is declared. In
10483 this example, we would move the instantiation of
10484 @code{Unchecked_Conversion} from the body of package
10485 @code{p2} to the spec of package @code{p1}. Now the
10486 warning disappears. That's because any use of the
10487 access type knows there is a suspicious unchecked
10488 conversion, and the strict aliasing optimization
10489 is automatically suppressed for the type.
10490
10491 If it is not practical to move the unchecked conversion to the same unit
10492 in which the destination access type is declared (perhaps because the
10493 source type is not visible in that unit), you may use pragma
10494 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10495 same declarative sequence as the declaration of the access type:
10496
10497 @smallexample @c ada
10498 type a2 is access int2;
10499 pragma No_Strict_Aliasing (a2);
10500 @end smallexample
10501
10502 @noindent
10503 Here again, the compiler now knows that the strict aliasing optimization
10504 should be suppressed for any reference to type @code{a2} and the
10505 expected behavior is obtained.
10506
10507 Finally, note that although the compiler can generate warnings for
10508 simple cases of unchecked conversions, there are tricker and more
10509 indirect ways of creating type incorrect aliases which the compiler
10510 cannot detect. Examples are the use of address overlays and unchecked
10511 conversions involving composite types containing access types as
10512 components. In such cases, no warnings are generated, but there can
10513 still be aliasing problems. One safe coding practice is to forbid the
10514 use of address clauses for type overlaying, and to allow unchecked
10515 conversion only for primitive types. This is not really a significant
10516 restriction since any possible desired effect can be achieved by
10517 unchecked conversion of access values.
10518
10519 The aliasing analysis done in strict aliasing mode can certainly
10520 have significant benefits. We have seen cases of large scale
10521 application code where the time is increased by up to 5% by turning
10522 this optimization off. If you have code that includes significant
10523 usage of unchecked conversion, you might want to just stick with
10524 @option{-O1} and avoid the entire issue. If you get adequate
10525 performance at this level of optimization level, that's probably
10526 the safest approach. If tests show that you really need higher
10527 levels of optimization, then you can experiment with @option{-O2}
10528 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10529 has on size and speed of the code. If you really need to use
10530 @option{-O2} with strict aliasing in effect, then you should
10531 review any uses of unchecked conversion of access types,
10532 particularly if you are getting the warnings described above.
10533
10534 @ifset vms
10535 @node Coverage Analysis
10536 @subsection Coverage Analysis
10537
10538 @noindent
10539 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10540 the user to determine the distribution of execution time across a program,
10541 @pxref{Profiling} for details of usage.
10542 @end ifset
10543
10544
10545 @node Text_IO Suggestions
10546 @section @code{Text_IO} Suggestions
10547 @cindex @code{Text_IO} and performance
10548
10549 @noindent
10550 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10551 the requirement of maintaining page and line counts. If performance
10552 is critical, a recommendation is to use @code{Stream_IO} instead of
10553 @code{Text_IO} for volume output, since this package has less overhead.
10554
10555 If @code{Text_IO} must be used, note that by default output to the standard
10556 output and standard error files is unbuffered (this provides better
10557 behavior when output statements are used for debugging, or if the
10558 progress of a program is observed by tracking the output, e.g. by
10559 using the Unix @command{tail -f} command to watch redirected output.
10560
10561 If you are generating large volumes of output with @code{Text_IO} and
10562 performance is an important factor, use a designated file instead
10563 of the standard output file, or change the standard output file to
10564 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10565
10566
10567
10568 @node Reducing Size of Ada Executables with gnatelim
10569 @section Reducing Size of Ada Executables with @code{gnatelim}
10570 @findex gnatelim
10571
10572 @noindent
10573 This section describes @command{gnatelim}, a tool which detects unused
10574 subprograms and helps the compiler to create a smaller executable for your
10575 program.
10576
10577 @menu
10578 * About gnatelim::
10579 * Running gnatelim::
10580 * Correcting the List of Eliminate Pragmas::
10581 * Making Your Executables Smaller::
10582 * Summary of the gnatelim Usage Cycle::
10583 @end menu
10584
10585 @node About gnatelim
10586 @subsection About @code{gnatelim}
10587
10588 @noindent
10589 When a program shares a set of Ada
10590 packages with other programs, it may happen that this program uses
10591 only a fraction of the subprograms defined in these packages. The code
10592 created for these unused subprograms increases the size of the executable.
10593
10594 @code{gnatelim} tracks unused subprograms in an Ada program and
10595 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10596 subprograms that are declared but never called. By placing the list of
10597 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10598 recompiling your program, you may decrease the size of its executable,
10599 because the compiler will not generate the code for 'eliminated' subprograms.
10600 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10601 information about this pragma.
10602
10603 @code{gnatelim} needs as its input data the name of the main subprogram
10604 and a bind file for a main subprogram.
10605
10606 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10607 the main subprogram. @code{gnatelim} can work with both Ada and C
10608 bind files; when both are present, it uses the Ada bind file.
10609 The following commands will build the program and create the bind file:
10610
10611 @smallexample
10612 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10613 $ gnatbind main_prog
10614 @end smallexample
10615
10616 Note that @code{gnatelim} needs neither object nor ALI files.
10617
10618 @node Running gnatelim
10619 @subsection Running @code{gnatelim}
10620
10621 @noindent
10622 @code{gnatelim} has the following command-line interface:
10623
10624 @smallexample
10625 $ gnatelim @ovar{options} name
10626 @end smallexample
10627
10628 @noindent
10629 @code{name} should be a name of a source file that contains the main subprogram
10630 of a program (partition).
10631
10632 @code{gnatelim} has the following switches:
10633
10634 @table @option
10635 @c !sort!
10636 @item ^-q^/QUIET^
10637 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10638 Quiet mode: by default @code{gnatelim} outputs to the standard error
10639 stream the number of program units left to be processed. This option turns
10640 this trace off.
10641
10642 @item ^-v^/VERBOSE^
10643 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10644 Verbose mode: @code{gnatelim} version information is printed as Ada
10645 comments to the standard output stream. Also, in addition to the number of
10646 program units left @code{gnatelim} will output the name of the current unit
10647 being processed.
10648
10649 @item ^-a^/ALL^
10650 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10651 Also look for subprograms from the GNAT run time that can be eliminated. Note
10652 that when @file{gnat.adc} is produced using this switch, the entire program
10653 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10654
10655 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10656 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10657 When looking for source files also look in directory @var{dir}. Specifying
10658 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10659 sources in the current directory.
10660
10661 @item ^-b^/BIND_FILE=^@var{bind_file}
10662 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10663 Specifies @var{bind_file} as the bind file to process. If not set, the name
10664 of the bind file is computed from the full expanded Ada name
10665 of a main subprogram.
10666
10667 @item ^-C^/CONFIG_FILE=^@var{config_file}
10668 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10669 Specifies a file @var{config_file} that contains configuration pragmas. The
10670 file must be specified with full path.
10671
10672 @item ^--GCC^/COMPILER^=@var{compiler_name}
10673 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10674 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10675 available on the path.
10676
10677 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10678 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10679 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10680 available on the path.
10681 @end table
10682
10683 @noindent
10684 @code{gnatelim} sends its output to the standard output stream, and all the
10685 tracing and debug information is sent to the standard error stream.
10686 In order to produce a proper GNAT configuration file
10687 @file{gnat.adc}, redirection must be used:
10688
10689 @smallexample
10690 @ifset vms
10691 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10692 @end ifset
10693 @ifclear vms
10694 $ gnatelim main_prog.adb > gnat.adc
10695 @end ifclear
10696 @end smallexample
10697
10698 @ifclear vms
10699 @noindent
10700 or
10701
10702 @smallexample
10703 $ gnatelim main_prog.adb >> gnat.adc
10704 @end smallexample
10705
10706 @noindent
10707 in order to append the @code{gnatelim} output to the existing contents of
10708 @file{gnat.adc}.
10709 @end ifclear
10710
10711 @node Correcting the List of Eliminate Pragmas
10712 @subsection Correcting the List of Eliminate Pragmas
10713
10714 @noindent
10715 In some rare cases @code{gnatelim} may try to eliminate
10716 subprograms that are actually called in the program. In this case, the
10717 compiler will generate an error message of the form:
10718
10719 @smallexample
10720 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10721 @end smallexample
10722
10723 @noindent
10724 You will need to manually remove the wrong @code{Eliminate} pragmas from
10725 the @file{gnat.adc} file. You should recompile your program
10726 from scratch after that, because you need a consistent @file{gnat.adc} file
10727 during the entire compilation.
10728
10729 @node Making Your Executables Smaller
10730 @subsection Making Your Executables Smaller
10731
10732 @noindent
10733 In order to get a smaller executable for your program you now have to
10734 recompile the program completely with the new @file{gnat.adc} file
10735 created by @code{gnatelim} in your current directory:
10736
10737 @smallexample
10738 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10739 @end smallexample
10740
10741 @noindent
10742 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10743 recompile everything
10744 with the set of pragmas @code{Eliminate} that you have obtained with
10745 @command{gnatelim}).
10746
10747 Be aware that the set of @code{Eliminate} pragmas is specific to each
10748 program. It is not recommended to merge sets of @code{Eliminate}
10749 pragmas created for different programs in one @file{gnat.adc} file.
10750
10751 @node Summary of the gnatelim Usage Cycle
10752 @subsection Summary of the gnatelim Usage Cycle
10753
10754 @noindent
10755 Here is a quick summary of the steps to be taken in order to reduce
10756 the size of your executables with @code{gnatelim}. You may use
10757 other GNAT options to control the optimization level,
10758 to produce the debugging information, to set search path, etc.
10759
10760 @enumerate
10761 @item
10762 Produce a bind file
10763
10764 @smallexample
10765 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10766 $ gnatbind main_prog
10767 @end smallexample
10768
10769 @item
10770 Generate a list of @code{Eliminate} pragmas
10771 @smallexample
10772 @ifset vms
10773 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10774 @end ifset
10775 @ifclear vms
10776 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10777 @end ifclear
10778 @end smallexample
10779
10780 @item
10781 Recompile the application
10782
10783 @smallexample
10784 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10785 @end smallexample
10786
10787 @end enumerate
10788
10789 @node Reducing Size of Executables with unused subprogram/data elimination
10790 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10791 @findex unused subprogram/data elimination
10792
10793 @noindent
10794 This section describes how you can eliminate unused subprograms and data from
10795 your executable just by setting options at compilation time.
10796
10797 @menu
10798 * About unused subprogram/data elimination::
10799 * Compilation options::
10800 * Example of unused subprogram/data elimination::
10801 @end menu
10802
10803 @node About unused subprogram/data elimination
10804 @subsection About unused subprogram/data elimination
10805
10806 @noindent
10807 By default, an executable contains all code and data of its composing objects
10808 (directly linked or coming from statically linked libraries), even data or code
10809 never used by this executable.
10810
10811 This feature will allow you to eliminate such unused code from your
10812 executable, making it smaller (in disk and in memory).
10813
10814 This functionality is available on all Linux platforms except for the IA-64
10815 architecture and on all cross platforms using the ELF binary file format.
10816 In both cases GNU binutils version 2.16 or later are required to enable it.
10817
10818 @node Compilation options
10819 @subsection Compilation options
10820
10821 @noindent
10822 The operation of eliminating the unused code and data from the final executable
10823 is directly performed by the linker.
10824
10825 In order to do this, it has to work with objects compiled with the
10826 following options:
10827 @option{-ffunction-sections} @option{-fdata-sections}.
10828 @cindex @option{-ffunction-sections} (@command{gcc})
10829 @cindex @option{-fdata-sections} (@command{gcc})
10830 These options are usable with C and Ada files.
10831 They will place respectively each
10832 function or data in a separate section in the resulting object file.
10833
10834 Once the objects and static libraries are created with these options, the
10835 linker can perform the dead code elimination. You can do this by setting
10836 the @option{-Wl,--gc-sections} option to gcc command or in the
10837 @option{-largs} section of @command{gnatmake}. This will perform a
10838 garbage collection of code and data never referenced.
10839
10840 If the linker performs a partial link (@option{-r} ld linker option), then you
10841 will need to provide one or several entry point using the
10842 @option{-e} / @option{--entry} ld option.
10843
10844 Note that objects compiled without the @option{-ffunction-sections} and
10845 @option{-fdata-sections} options can still be linked with the executable.
10846 However, no dead code elimination will be performed on those objects (they will
10847 be linked as is).
10848
10849 The GNAT static library is now compiled with -ffunction-sections and
10850 -fdata-sections on some platforms. This allows you to eliminate the unused code
10851 and data of the GNAT library from your executable.
10852
10853 @node Example of unused subprogram/data elimination
10854 @subsection Example of unused subprogram/data elimination
10855
10856 @noindent
10857 Here is a simple example:
10858
10859 @smallexample @c ada
10860 with Aux;
10861
10862 procedure Test is
10863 begin
10864 Aux.Used (10);
10865 end Test;
10866
10867 package Aux is
10868 Used_Data : Integer;
10869 Unused_Data : Integer;
10870
10871 procedure Used (Data : Integer);
10872 procedure Unused (Data : Integer);
10873 end Aux;
10874
10875 package body Aux is
10876 procedure Used (Data : Integer) is
10877 begin
10878 Used_Data := Data;
10879 end Used;
10880
10881 procedure Unused (Data : Integer) is
10882 begin
10883 Unused_Data := Data;
10884 end Unused;
10885 end Aux;
10886 @end smallexample
10887
10888 @noindent
10889 @code{Unused} and @code{Unused_Data} are never referenced in this code
10890 excerpt, and hence they may be safely removed from the final executable.
10891
10892 @smallexample
10893 $ gnatmake test
10894
10895 $ nm test | grep used
10896 020015f0 T aux__unused
10897 02005d88 B aux__unused_data
10898 020015cc T aux__used
10899 02005d84 B aux__used_data
10900
10901 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10902 -largs -Wl,--gc-sections
10903
10904 $ nm test | grep used
10905 02005350 T aux__used
10906 0201ffe0 B aux__used_data
10907 @end smallexample
10908
10909 @noindent
10910 It can be observed that the procedure @code{Unused} and the object
10911 @code{Unused_Data} are removed by the linker when using the
10912 appropriate options.
10913
10914 @c ********************************
10915 @node Renaming Files Using gnatchop
10916 @chapter Renaming Files Using @code{gnatchop}
10917 @findex gnatchop
10918
10919 @noindent
10920 This chapter discusses how to handle files with multiple units by using
10921 the @code{gnatchop} utility. This utility is also useful in renaming
10922 files to meet the standard GNAT default file naming conventions.
10923
10924 @menu
10925 * Handling Files with Multiple Units::
10926 * Operating gnatchop in Compilation Mode::
10927 * Command Line for gnatchop::
10928 * Switches for gnatchop::
10929 * Examples of gnatchop Usage::
10930 @end menu
10931
10932 @node Handling Files with Multiple Units
10933 @section Handling Files with Multiple Units
10934
10935 @noindent
10936 The basic compilation model of GNAT requires that a file submitted to the
10937 compiler have only one unit and there be a strict correspondence
10938 between the file name and the unit name.
10939
10940 The @code{gnatchop} utility allows both of these rules to be relaxed,
10941 allowing GNAT to process files which contain multiple compilation units
10942 and files with arbitrary file names. @code{gnatchop}
10943 reads the specified file and generates one or more output files,
10944 containing one unit per file. The unit and the file name correspond,
10945 as required by GNAT.
10946
10947 If you want to permanently restructure a set of ``foreign'' files so that
10948 they match the GNAT rules, and do the remaining development using the
10949 GNAT structure, you can simply use @command{gnatchop} once, generate the
10950 new set of files and work with them from that point on.
10951
10952 Alternatively, if you want to keep your files in the ``foreign'' format,
10953 perhaps to maintain compatibility with some other Ada compilation
10954 system, you can set up a procedure where you use @command{gnatchop} each
10955 time you compile, regarding the source files that it writes as temporary
10956 files that you throw away.
10957
10958 Note that if your file containing multiple units starts with a byte order
10959 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10960 will each start with a copy of this BOM, meaning that they can be compiled
10961 automatically in UTF-8 mode without needing to specify an explicit encoding.
10962
10963 @node Operating gnatchop in Compilation Mode
10964 @section Operating gnatchop in Compilation Mode
10965
10966 @noindent
10967 The basic function of @code{gnatchop} is to take a file with multiple units
10968 and split it into separate files. The boundary between files is reasonably
10969 clear, except for the issue of comments and pragmas. In default mode, the
10970 rule is that any pragmas between units belong to the previous unit, except
10971 that configuration pragmas always belong to the following unit. Any comments
10972 belong to the following unit. These rules
10973 almost always result in the right choice of
10974 the split point without needing to mark it explicitly and most users will
10975 find this default to be what they want. In this default mode it is incorrect to
10976 submit a file containing only configuration pragmas, or one that ends in
10977 configuration pragmas, to @code{gnatchop}.
10978
10979 However, using a special option to activate ``compilation mode'',
10980 @code{gnatchop}
10981 can perform another function, which is to provide exactly the semantics
10982 required by the RM for handling of configuration pragmas in a compilation.
10983 In the absence of configuration pragmas (at the main file level), this
10984 option has no effect, but it causes such configuration pragmas to be handled
10985 in a quite different manner.
10986
10987 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10988 only configuration pragmas, then this file is appended to the
10989 @file{gnat.adc} file in the current directory. This behavior provides
10990 the required behavior described in the RM for the actions to be taken
10991 on submitting such a file to the compiler, namely that these pragmas
10992 should apply to all subsequent compilations in the same compilation
10993 environment. Using GNAT, the current directory, possibly containing a
10994 @file{gnat.adc} file is the representation
10995 of a compilation environment. For more information on the
10996 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10997
10998 Second, in compilation mode, if @code{gnatchop}
10999 is given a file that starts with
11000 configuration pragmas, and contains one or more units, then these
11001 configuration pragmas are prepended to each of the chopped files. This
11002 behavior provides the required behavior described in the RM for the
11003 actions to be taken on compiling such a file, namely that the pragmas
11004 apply to all units in the compilation, but not to subsequently compiled
11005 units.
11006
11007 Finally, if configuration pragmas appear between units, they are appended
11008 to the previous unit. This results in the previous unit being illegal,
11009 since the compiler does not accept configuration pragmas that follow
11010 a unit. This provides the required RM behavior that forbids configuration
11011 pragmas other than those preceding the first compilation unit of a
11012 compilation.
11013
11014 For most purposes, @code{gnatchop} will be used in default mode. The
11015 compilation mode described above is used only if you need exactly
11016 accurate behavior with respect to compilations, and you have files
11017 that contain multiple units and configuration pragmas. In this
11018 circumstance the use of @code{gnatchop} with the compilation mode
11019 switch provides the required behavior, and is for example the mode
11020 in which GNAT processes the ACVC tests.
11021
11022 @node Command Line for gnatchop
11023 @section Command Line for @code{gnatchop}
11024
11025 @noindent
11026 The @code{gnatchop} command has the form:
11027
11028 @smallexample
11029 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11030 @ovar{directory}
11031 @end smallexample
11032
11033 @noindent
11034 The only required argument is the file name of the file to be chopped.
11035 There are no restrictions on the form of this file name. The file itself
11036 contains one or more Ada units, in normal GNAT format, concatenated
11037 together. As shown, more than one file may be presented to be chopped.
11038
11039 When run in default mode, @code{gnatchop} generates one output file in
11040 the current directory for each unit in each of the files.
11041
11042 @var{directory}, if specified, gives the name of the directory to which
11043 the output files will be written. If it is not specified, all files are
11044 written to the current directory.
11045
11046 For example, given a
11047 file called @file{hellofiles} containing
11048
11049 @smallexample @c ada
11050 @group
11051 @cartouche
11052 procedure hello;
11053
11054 with Text_IO; use Text_IO;
11055 procedure hello is
11056 begin
11057 Put_Line ("Hello");
11058 end hello;
11059 @end cartouche
11060 @end group
11061 @end smallexample
11062
11063 @noindent
11064 the command
11065
11066 @smallexample
11067 $ gnatchop ^hellofiles^HELLOFILES.^
11068 @end smallexample
11069
11070 @noindent
11071 generates two files in the current directory, one called
11072 @file{hello.ads} containing the single line that is the procedure spec,
11073 and the other called @file{hello.adb} containing the remaining text. The
11074 original file is not affected. The generated files can be compiled in
11075 the normal manner.
11076
11077 @noindent
11078 When gnatchop is invoked on a file that is empty or that contains only empty
11079 lines and/or comments, gnatchop will not fail, but will not produce any
11080 new sources.
11081
11082 For example, given a
11083 file called @file{toto.txt} containing
11084
11085 @smallexample @c ada
11086 @group
11087 @cartouche
11088 -- Just a comment
11089 @end cartouche
11090 @end group
11091 @end smallexample
11092
11093 @noindent
11094 the command
11095
11096 @smallexample
11097 $ gnatchop ^toto.txt^TOT.TXT^
11098 @end smallexample
11099
11100 @noindent
11101 will not produce any new file and will result in the following warnings:
11102
11103 @smallexample
11104 toto.txt:1:01: warning: empty file, contains no compilation units
11105 no compilation units found
11106 no source files written
11107 @end smallexample
11108
11109 @node Switches for gnatchop
11110 @section Switches for @code{gnatchop}
11111
11112 @noindent
11113 @command{gnatchop} recognizes the following switches:
11114
11115 @table @option
11116 @c !sort!
11117
11118 @item --version
11119 @cindex @option{--version} @command{gnatchop}
11120 Display Copyright and version, then exit disregarding all other options.
11121
11122 @item --help
11123 @cindex @option{--help} @command{gnatchop}
11124 If @option{--version} was not used, display usage, then exit disregarding
11125 all other options.
11126
11127 @item ^-c^/COMPILATION^
11128 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11129 Causes @code{gnatchop} to operate in compilation mode, in which
11130 configuration pragmas are handled according to strict RM rules. See
11131 previous section for a full description of this mode.
11132
11133 @ifclear vms
11134 @item -gnat@var{xxx}
11135 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11136 used to parse the given file. Not all @var{xxx} options make sense,
11137 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11138 process a source file that uses Latin-2 coding for identifiers.
11139 @end ifclear
11140
11141 @item ^-h^/HELP^
11142 Causes @code{gnatchop} to generate a brief help summary to the standard
11143 output file showing usage information.
11144
11145 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11146 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11147 Limit generated file names to the specified number @code{mm}
11148 of characters.
11149 This is useful if the
11150 resulting set of files is required to be interoperable with systems
11151 which limit the length of file names.
11152 @ifset vms
11153 If no value is given, or
11154 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11155 a default of 39, suitable for OpenVMS Alpha
11156 Systems, is assumed
11157 @end ifset
11158 @ifclear vms
11159 No space is allowed between the @option{-k} and the numeric value. The numeric
11160 value may be omitted in which case a default of @option{-k8},
11161 suitable for use
11162 with DOS-like file systems, is used. If no @option{-k} switch
11163 is present then
11164 there is no limit on the length of file names.
11165 @end ifclear
11166
11167 @item ^-p^/PRESERVE^
11168 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11169 Causes the file ^modification^creation^ time stamp of the input file to be
11170 preserved and used for the time stamp of the output file(s). This may be
11171 useful for preserving coherency of time stamps in an environment where
11172 @code{gnatchop} is used as part of a standard build process.
11173
11174 @item ^-q^/QUIET^
11175 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11176 Causes output of informational messages indicating the set of generated
11177 files to be suppressed. Warnings and error messages are unaffected.
11178
11179 @item ^-r^/REFERENCE^
11180 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11181 @findex Source_Reference
11182 Generate @code{Source_Reference} pragmas. Use this switch if the output
11183 files are regarded as temporary and development is to be done in terms
11184 of the original unchopped file. This switch causes
11185 @code{Source_Reference} pragmas to be inserted into each of the
11186 generated files to refers back to the original file name and line number.
11187 The result is that all error messages refer back to the original
11188 unchopped file.
11189 In addition, the debugging information placed into the object file (when
11190 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11191 specified)
11192 also refers back to this original file so that tools like profilers and
11193 debuggers will give information in terms of the original unchopped file.
11194
11195 If the original file to be chopped itself contains
11196 a @code{Source_Reference}
11197 pragma referencing a third file, then gnatchop respects
11198 this pragma, and the generated @code{Source_Reference} pragmas
11199 in the chopped file refer to the original file, with appropriate
11200 line numbers. This is particularly useful when @code{gnatchop}
11201 is used in conjunction with @code{gnatprep} to compile files that
11202 contain preprocessing statements and multiple units.
11203
11204 @item ^-v^/VERBOSE^
11205 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11206 Causes @code{gnatchop} to operate in verbose mode. The version
11207 number and copyright notice are output, as well as exact copies of
11208 the gnat1 commands spawned to obtain the chop control information.
11209
11210 @item ^-w^/OVERWRITE^
11211 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11212 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11213 fatal error if there is already a file with the same name as a
11214 file it would otherwise output, in other words if the files to be
11215 chopped contain duplicated units. This switch bypasses this
11216 check, and causes all but the last instance of such duplicated
11217 units to be skipped.
11218
11219 @ifclear vms
11220 @item --GCC=@var{xxxx}
11221 @cindex @option{--GCC=} (@code{gnatchop})
11222 Specify the path of the GNAT parser to be used. When this switch is used,
11223 no attempt is made to add the prefix to the GNAT parser executable.
11224 @end ifclear
11225 @end table
11226
11227 @node Examples of gnatchop Usage
11228 @section Examples of @code{gnatchop} Usage
11229
11230 @table @code
11231 @ifset vms
11232 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11233 @end ifset
11234 @ifclear vms
11235 @item gnatchop -w hello_s.ada prerelease/files
11236 @end ifclear
11237
11238 Chops the source file @file{hello_s.ada}. The output files will be
11239 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11240 overwriting any
11241 files with matching names in that directory (no files in the current
11242 directory are modified).
11243
11244 @item gnatchop ^archive^ARCHIVE.^
11245 Chops the source file @file{^archive^ARCHIVE.^}
11246 into the current directory. One
11247 useful application of @code{gnatchop} is in sending sets of sources
11248 around, for example in email messages. The required sources are simply
11249 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11250 command), and then
11251 @command{gnatchop} is used at the other end to reconstitute the original
11252 file names.
11253
11254 @item gnatchop file1 file2 file3 direc
11255 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11256 the resulting files in the directory @file{direc}. Note that if any units
11257 occur more than once anywhere within this set of files, an error message
11258 is generated, and no files are written. To override this check, use the
11259 @option{^-w^/OVERWRITE^} switch,
11260 in which case the last occurrence in the last file will
11261 be the one that is output, and earlier duplicate occurrences for a given
11262 unit will be skipped.
11263 @end table
11264
11265 @node Configuration Pragmas
11266 @chapter Configuration Pragmas
11267 @cindex Configuration pragmas
11268 @cindex Pragmas, configuration
11269
11270 @noindent
11271 Configuration pragmas include those pragmas described as
11272 such in the Ada Reference Manual, as well as
11273 implementation-dependent pragmas that are configuration pragmas.
11274 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11275 for details on these additional GNAT-specific configuration pragmas.
11276 Most notably, the pragma @code{Source_File_Name}, which allows
11277 specifying non-default names for source files, is a configuration
11278 pragma. The following is a complete list of configuration pragmas
11279 recognized by GNAT:
11280
11281 @smallexample
11282 Ada_83
11283 Ada_95
11284 Ada_05
11285 Ada_2005
11286 Assertion_Policy
11287 C_Pass_By_Copy
11288 Check_Name
11289 Check_Policy
11290 Compile_Time_Error
11291 Compile_Time_Warning
11292 Compiler_Unit
11293 Component_Alignment
11294 Debug_Policy
11295 Detect_Blocking
11296 Discard_Names
11297 Elaboration_Checks
11298 Eliminate
11299 Extend_System
11300 External_Name_Casing
11301 Fast_Math
11302 Favor_Top_Level
11303 Float_Representation
11304 Implicit_Packing
11305 Initialize_Scalars
11306 Interrupt_State
11307 License
11308 Locking_Policy
11309 Long_Float
11310 No_Run_Time
11311 No_Strict_Aliasing
11312 Normalize_Scalars
11313 Optimize_Alignment
11314 Persistent_BSS
11315 Polling
11316 Priority_Specific_Dispatching
11317 Profile
11318 Profile_Warnings
11319 Propagate_Exceptions
11320 Queuing_Policy
11321 Ravenscar
11322 Restricted_Run_Time
11323 Restrictions
11324 Restrictions_Warnings
11325 Reviewable
11326 Source_File_Name
11327 Source_File_Name_Project
11328 Style_Checks
11329 Suppress
11330 Suppress_Exception_Locations
11331 Task_Dispatching_Policy
11332 Universal_Data
11333 Unsuppress
11334 Use_VADS_Size
11335 Validity_Checks
11336 Warnings
11337 Wide_Character_Encoding
11338
11339 @end smallexample
11340
11341 @menu
11342 * Handling of Configuration Pragmas::
11343 * The Configuration Pragmas Files::
11344 @end menu
11345
11346 @node Handling of Configuration Pragmas
11347 @section Handling of Configuration Pragmas
11348
11349 Configuration pragmas may either appear at the start of a compilation
11350 unit, in which case they apply only to that unit, or they may apply to
11351 all compilations performed in a given compilation environment.
11352
11353 GNAT also provides the @code{gnatchop} utility to provide an automatic
11354 way to handle configuration pragmas following the semantics for
11355 compilations (that is, files with multiple units), described in the RM.
11356 See @ref{Operating gnatchop in Compilation Mode} for details.
11357 However, for most purposes, it will be more convenient to edit the
11358 @file{gnat.adc} file that contains configuration pragmas directly,
11359 as described in the following section.
11360
11361 @node The Configuration Pragmas Files
11362 @section The Configuration Pragmas Files
11363 @cindex @file{gnat.adc}
11364
11365 @noindent
11366 In GNAT a compilation environment is defined by the current
11367 directory at the time that a compile command is given. This current
11368 directory is searched for a file whose name is @file{gnat.adc}. If
11369 this file is present, it is expected to contain one or more
11370 configuration pragmas that will be applied to the current compilation.
11371 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11372 considered.
11373
11374 Configuration pragmas may be entered into the @file{gnat.adc} file
11375 either by running @code{gnatchop} on a source file that consists only of
11376 configuration pragmas, or more conveniently by
11377 direct editing of the @file{gnat.adc} file, which is a standard format
11378 source file.
11379
11380 In addition to @file{gnat.adc}, additional files containing configuration
11381 pragmas may be applied to the current compilation using the switch
11382 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11383 contains only configuration pragmas. These configuration pragmas are
11384 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11385 is present and switch @option{-gnatA} is not used).
11386
11387 It is allowed to specify several switches @option{-gnatec}, all of which
11388 will be taken into account.
11389
11390 If you are using project file, a separate mechanism is provided using
11391 project attributes, see @ref{Specifying Configuration Pragmas} for more
11392 details.
11393
11394 @ifset vms
11395 Of special interest to GNAT OpenVMS Alpha is the following
11396 configuration pragma:
11397
11398 @smallexample @c ada
11399 @cartouche
11400 pragma Extend_System (Aux_DEC);
11401 @end cartouche
11402 @end smallexample
11403
11404 @noindent
11405 In the presence of this pragma, GNAT adds to the definition of the
11406 predefined package SYSTEM all the additional types and subprograms that are
11407 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11408 @end ifset
11409
11410 @node Handling Arbitrary File Naming Conventions Using gnatname
11411 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11412 @cindex Arbitrary File Naming Conventions
11413
11414 @menu
11415 * Arbitrary File Naming Conventions::
11416 * Running gnatname::
11417 * Switches for gnatname::
11418 * Examples of gnatname Usage::
11419 @end menu
11420
11421 @node Arbitrary File Naming Conventions
11422 @section Arbitrary File Naming Conventions
11423
11424 @noindent
11425 The GNAT compiler must be able to know the source file name of a compilation
11426 unit. When using the standard GNAT default file naming conventions
11427 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11428 does not need additional information.
11429
11430 @noindent
11431 When the source file names do not follow the standard GNAT default file naming
11432 conventions, the GNAT compiler must be given additional information through
11433 a configuration pragmas file (@pxref{Configuration Pragmas})
11434 or a project file.
11435 When the non-standard file naming conventions are well-defined,
11436 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11437 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11438 if the file naming conventions are irregular or arbitrary, a number
11439 of pragma @code{Source_File_Name} for individual compilation units
11440 must be defined.
11441 To help maintain the correspondence between compilation unit names and
11442 source file names within the compiler,
11443 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11444 set of files.
11445
11446 @node Running gnatname
11447 @section Running @code{gnatname}
11448
11449 @noindent
11450 The usual form of the @code{gnatname} command is
11451
11452 @smallexample
11453 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11454 @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11455 @end smallexample
11456
11457 @noindent
11458 All of the arguments are optional. If invoked without any argument,
11459 @code{gnatname} will display its usage.
11460
11461 @noindent
11462 When used with at least one naming pattern, @code{gnatname} will attempt to
11463 find all the compilation units in files that follow at least one of the
11464 naming patterns. To find these compilation units,
11465 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11466 regular files.
11467
11468 @noindent
11469 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11470 Each Naming Pattern is enclosed between double quotes.
11471 A Naming Pattern is a regular expression similar to the wildcard patterns
11472 used in file names by the Unix shells or the DOS prompt.
11473
11474 @noindent
11475 @code{gnatname} may be called with several sections of directories/patterns.
11476 Sections are separated by switch @code{--and}. In each section, there must be
11477 at least one pattern. If no directory is specified in a section, the current
11478 directory (or the project directory is @code{-P} is used) is implied.
11479 The options other that the directory switches and the patterns apply globally
11480 even if they are in different sections.
11481
11482 @noindent
11483 Examples of Naming Patterns are
11484
11485 @smallexample
11486 "*.[12].ada"
11487 "*.ad[sb]*"
11488 "body_*" "spec_*"
11489 @end smallexample
11490
11491 @noindent
11492 For a more complete description of the syntax of Naming Patterns,
11493 see the second kind of regular expressions described in @file{g-regexp.ads}
11494 (the ``Glob'' regular expressions).
11495
11496 @noindent
11497 When invoked with no switch @code{-P}, @code{gnatname} will create a
11498 configuration pragmas file @file{gnat.adc} in the current working directory,
11499 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11500 unit.
11501
11502 @node Switches for gnatname
11503 @section Switches for @code{gnatname}
11504
11505 @noindent
11506 Switches for @code{gnatname} must precede any specified Naming Pattern.
11507
11508 @noindent
11509 You may specify any of the following switches to @code{gnatname}:
11510
11511 @table @option
11512 @c !sort!
11513
11514 @item --version
11515 @cindex @option{--version} @command{gnatname}
11516 Display Copyright and version, then exit disregarding all other options.
11517
11518 @item --help
11519 @cindex @option{--help} @command{gnatname}
11520 If @option{--version} was not used, display usage, then exit disregarding
11521 all other options.
11522
11523 @item --and
11524 Start another section of directories/patterns.
11525
11526 @item ^-c^/CONFIG_FILE=^@file{file}
11527 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11528 Create a configuration pragmas file @file{file} (instead of the default
11529 @file{gnat.adc}).
11530 @ifclear vms
11531 There may be zero, one or more space between @option{-c} and
11532 @file{file}.
11533 @end ifclear
11534 @file{file} may include directory information. @file{file} must be
11535 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11536 When a switch @option{^-c^/CONFIG_FILE^} is
11537 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11538
11539 @item ^-d^/SOURCE_DIRS=^@file{dir}
11540 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11541 Look for source files in directory @file{dir}. There may be zero, one or more
11542 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11543 When a switch @option{^-d^/SOURCE_DIRS^}
11544 is specified, the current working directory will not be searched for source
11545 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11546 or @option{^-D^/DIR_FILES^} switch.
11547 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11548 If @file{dir} is a relative path, it is relative to the directory of
11549 the configuration pragmas file specified with switch
11550 @option{^-c^/CONFIG_FILE^},
11551 or to the directory of the project file specified with switch
11552 @option{^-P^/PROJECT_FILE^} or,
11553 if neither switch @option{^-c^/CONFIG_FILE^}
11554 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11555 current working directory. The directory
11556 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11557
11558 @item ^-D^/DIRS_FILE=^@file{file}
11559 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11560 Look for source files in all directories listed in text file @file{file}.
11561 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11562 and @file{file}.
11563 @file{file} must be an existing, readable text file.
11564 Each nonempty line in @file{file} must be a directory.
11565 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11566 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11567 @file{file}.
11568
11569 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11570 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11571 Foreign patterns. Using this switch, it is possible to add sources of languages
11572 other than Ada to the list of sources of a project file.
11573 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11574 For example,
11575 @smallexample
11576 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11577 @end smallexample
11578 @noindent
11579 will look for Ada units in all files with the @file{.ada} extension,
11580 and will add to the list of file for project @file{prj.gpr} the C files
11581 with extension @file{.^c^C^}.
11582
11583 @item ^-h^/HELP^
11584 @cindex @option{^-h^/HELP^} (@code{gnatname})
11585 Output usage (help) information. The output is written to @file{stdout}.
11586
11587 @item ^-P^/PROJECT_FILE=^@file{proj}
11588 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11589 Create or update project file @file{proj}. There may be zero, one or more space
11590 between @option{-P} and @file{proj}. @file{proj} may include directory
11591 information. @file{proj} must be writable.
11592 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11593 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11594 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11595
11596 @item ^-v^/VERBOSE^
11597 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11598 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11599 This includes name of the file written, the name of the directories to search
11600 and, for each file in those directories whose name matches at least one of
11601 the Naming Patterns, an indication of whether the file contains a unit,
11602 and if so the name of the unit.
11603
11604 @item ^-v -v^/VERBOSE /VERBOSE^
11605 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11606 Very Verbose mode. In addition to the output produced in verbose mode,
11607 for each file in the searched directories whose name matches none of
11608 the Naming Patterns, an indication is given that there is no match.
11609
11610 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11611 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11612 Excluded patterns. Using this switch, it is possible to exclude some files
11613 that would match the name patterns. For example,
11614 @smallexample
11615 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11616 @end smallexample
11617 @noindent
11618 will look for Ada units in all files with the @file{.ada} extension,
11619 except those whose names end with @file{_nt.ada}.
11620
11621 @end table
11622
11623 @node Examples of gnatname Usage
11624 @section Examples of @code{gnatname} Usage
11625
11626 @ifset vms
11627 @smallexample
11628 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11629 @end smallexample
11630 @end ifset
11631
11632 @ifclear vms
11633 @smallexample
11634 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11635 @end smallexample
11636 @end ifclear
11637
11638 @noindent
11639 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11640 and be writable. In addition, the directory
11641 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11642 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11643
11644 @ifclear vms
11645 Note the optional spaces after @option{-c} and @option{-d}.
11646 @end ifclear
11647
11648 @smallexample
11649 @ifclear vms
11650 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11651 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11652 @end ifclear
11653 @ifset vms
11654 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11655 /EXCLUDED_PATTERN=*_nt_body.ada
11656 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11657 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11658 @end ifset
11659 @end smallexample
11660
11661 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11662 even in conjunction with one or several switches
11663 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11664 are used in this example.
11665
11666 @c *****************************************
11667 @c * G N A T P r o j e c t M a n a g e r *
11668 @c *****************************************
11669 @node GNAT Project Manager
11670 @chapter GNAT Project Manager
11671
11672 @menu
11673 * Introduction::
11674 * Examples of Project Files::
11675 * Project File Syntax::
11676 * Objects and Sources in Project Files::
11677 * Importing Projects::
11678 * Project Extension::
11679 * Project Hierarchy Extension::
11680 * External References in Project Files::
11681 * Packages in Project Files::
11682 * Variables from Imported Projects::
11683 * Naming Schemes::
11684 * Library Projects::
11685 * Stand-alone Library Projects::
11686 * Switches Related to Project Files::
11687 * Tools Supporting Project Files::
11688 * An Extended Example::
11689 * Project File Complete Syntax::
11690 @end menu
11691
11692 @c ****************
11693 @c * Introduction *
11694 @c ****************
11695
11696 @node Introduction
11697 @section Introduction
11698
11699 @noindent
11700 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11701 you to manage complex builds involving a number of source files, directories,
11702 and compilation options for different system configurations. In particular,
11703 project files allow you to specify:
11704 @itemize @bullet
11705 @item
11706 The directory or set of directories containing the source files, and/or the
11707 names of the specific source files themselves
11708 @item
11709 The directory in which the compiler's output
11710 (@file{ALI} files, object files, tree files) is to be placed
11711 @item
11712 The directory in which the executable programs is to be placed
11713 @item
11714 ^Switch^Switch^ settings for any of the project-enabled tools
11715 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11716 @code{gnatfind}); you can apply these settings either globally or to individual
11717 compilation units.
11718 @item
11719 The source files containing the main subprogram(s) to be built
11720 @item
11721 The source programming language(s) (currently Ada and/or C)
11722 @item
11723 Source file naming conventions; you can specify these either globally or for
11724 individual compilation units
11725 @end itemize
11726
11727 @menu
11728 * Project Files::
11729 @end menu
11730
11731 @node Project Files
11732 @subsection Project Files
11733
11734 @noindent
11735 Project files are written in a syntax close to that of Ada, using familiar
11736 notions such as packages, context clauses, declarations, default values,
11737 assignments, and inheritance. Finally, project files can be built
11738 hierarchically from other project files, simplifying complex system
11739 integration and project reuse.
11740
11741 A @dfn{project} is a specific set of values for various compilation properties.
11742 The settings for a given project are described by means of
11743 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11744 Property values in project files are either strings or lists of strings.
11745 Properties that are not explicitly set receive default values. A project
11746 file may interrogate the values of @dfn{external variables} (user-defined
11747 command-line switches or environment variables), and it may specify property
11748 settings conditionally, based on the value of such variables.
11749
11750 In simple cases, a project's source files depend only on other source files
11751 in the same project, or on the predefined libraries. (@emph{Dependence} is
11752 used in
11753 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11754 the Project Manager also allows more sophisticated arrangements,
11755 where the source files in one project depend on source files in other
11756 projects:
11757 @itemize @bullet
11758 @item
11759 One project can @emph{import} other projects containing needed source files.
11760 @item
11761 You can organize GNAT projects in a hierarchy: a @emph{child} project
11762 can extend a @emph{parent} project, inheriting the parent's source files and
11763 optionally overriding any of them with alternative versions
11764 @end itemize
11765
11766 @noindent
11767 More generally, the Project Manager lets you structure large development
11768 efforts into hierarchical subsystems, where build decisions are delegated
11769 to the subsystem level, and thus different compilation environments
11770 (^switch^switch^ settings) used for different subsystems.
11771
11772 The Project Manager is invoked through the
11773 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11774 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11775 @ifclear vms
11776 There may be zero, one or more spaces between @option{-P} and
11777 @option{@emph{projectfile}}.
11778 @end ifclear
11779 If you want to define (on the command line) an external variable that is
11780 queried by the project file, you must use the
11781 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11782 The Project Manager parses and interprets the project file, and drives the
11783 invoked tool based on the project settings.
11784
11785 The Project Manager supports a wide range of development strategies,
11786 for systems of all sizes. Here are some typical practices that are
11787 easily handled:
11788 @itemize @bullet
11789 @item
11790 Using a common set of source files, but generating object files in different
11791 directories via different ^switch^switch^ settings
11792 @item
11793 Using a mostly-shared set of source files, but with different versions of
11794 some unit or units
11795 @end itemize
11796
11797 @noindent
11798 The destination of an executable can be controlled inside a project file
11799 using the @option{^-o^-o^}
11800 ^switch^switch^.
11801 In the absence of such a ^switch^switch^ either inside
11802 the project file or on the command line, any executable files generated by
11803 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11804 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11805 in the object directory of the project.
11806
11807 You can use project files to achieve some of the effects of a source
11808 versioning system (for example, defining separate projects for
11809 the different sets of sources that comprise different releases) but the
11810 Project Manager is independent of any source configuration management tools
11811 that might be used by the developers.
11812
11813 The next section introduces the main features of GNAT's project facility
11814 through a sequence of examples; subsequent sections will present the syntax
11815 and semantics in more detail. A more formal description of the project
11816 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11817 Reference Manual}.
11818
11819 @c *****************************
11820 @c * Examples of Project Files *
11821 @c *****************************
11822
11823 @node Examples of Project Files
11824 @section Examples of Project Files
11825 @noindent
11826 This section illustrates some of the typical uses of project files and
11827 explains their basic structure and behavior.
11828
11829 @menu
11830 * Common Sources with Different ^Switches^Switches^ and Directories::
11831 * Using External Variables::
11832 * Importing Other Projects::
11833 * Extending a Project::
11834 @end menu
11835
11836 @node Common Sources with Different ^Switches^Switches^ and Directories
11837 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11838
11839 @menu
11840 * Source Files::
11841 * Specifying the Object Directory::
11842 * Specifying the Exec Directory::
11843 * Project File Packages::
11844 * Specifying ^Switch^Switch^ Settings::
11845 * Main Subprograms::
11846 * Executable File Names::
11847 * Source File Naming Conventions::
11848 * Source Language(s)::
11849 @end menu
11850
11851 @noindent
11852 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11853 @file{proc.adb} are in the @file{/common} directory. The file
11854 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11855 package @code{Pack}. We want to compile these source files under two sets
11856 of ^switches^switches^:
11857 @itemize @bullet
11858 @item
11859 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11860 and the @option{^-gnata^-gnata^},
11861 @option{^-gnato^-gnato^},
11862 and @option{^-gnatE^-gnatE^} switches to the
11863 compiler; the compiler's output is to appear in @file{/common/debug}
11864 @item
11865 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11866 to the compiler; the compiler's output is to appear in @file{/common/release}
11867 @end itemize
11868
11869 @noindent
11870 The GNAT project files shown below, respectively @file{debug.gpr} and
11871 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11872
11873 Schematically:
11874 @smallexample
11875 @group
11876 ^/common^[COMMON]^
11877 debug.gpr
11878 release.gpr
11879 pack.ads
11880 pack.adb
11881 proc.adb
11882 @end group
11883 @group
11884 ^/common/debug^[COMMON.DEBUG]^
11885 proc.ali, proc.o
11886 pack.ali, pack.o
11887 @end group
11888 @group
11889 ^/common/release^[COMMON.RELEASE]^
11890 proc.ali, proc.o
11891 pack.ali, pack.o
11892 @end group
11893 @end smallexample
11894 Here are the corresponding project files:
11895
11896 @smallexample @c projectfile
11897 @group
11898 project Debug is
11899 for Object_Dir use "debug";
11900 for Main use ("proc");
11901
11902 package Builder is
11903 for ^Default_Switches^Default_Switches^ ("Ada")
11904 use ("^-g^-g^");
11905 for Executable ("proc.adb") use "proc1";
11906 end Builder;
11907 @end group
11908
11909 @group
11910 package Compiler is
11911 for ^Default_Switches^Default_Switches^ ("Ada")
11912 use ("-fstack-check",
11913 "^-gnata^-gnata^",
11914 "^-gnato^-gnato^",
11915 "^-gnatE^-gnatE^");
11916 end Compiler;
11917 end Debug;
11918 @end group
11919 @end smallexample
11920
11921 @smallexample @c projectfile
11922 @group
11923 project Release is
11924 for Object_Dir use "release";
11925 for Exec_Dir use ".";
11926 for Main use ("proc");
11927
11928 package Compiler is
11929 for ^Default_Switches^Default_Switches^ ("Ada")
11930 use ("^-O2^-O2^");
11931 end Compiler;
11932 end Release;
11933 @end group
11934 @end smallexample
11935
11936 @noindent
11937 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11938 insensitive), and analogously the project defined by @file{release.gpr} is
11939 @code{"Release"}. For consistency the file should have the same name as the
11940 project, and the project file's extension should be @code{"gpr"}. These
11941 conventions are not required, but a warning is issued if they are not followed.
11942
11943 If the current directory is @file{^/temp^[TEMP]^}, then the command
11944 @smallexample
11945 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11946 @end smallexample
11947
11948 @noindent
11949 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11950 as well as the @code{^proc1^PROC1.EXE^} executable,
11951 using the ^switch^switch^ settings defined in the project file.
11952
11953 Likewise, the command
11954 @smallexample
11955 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11956 @end smallexample
11957
11958 @noindent
11959 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11960 and the @code{^proc^PROC.EXE^}
11961 executable in @file{^/common^[COMMON]^},
11962 using the ^switch^switch^ settings from the project file.
11963
11964 @node Source Files
11965 @unnumberedsubsubsec Source Files
11966
11967 @noindent
11968 If a project file does not explicitly specify a set of source directories or
11969 a set of source files, then by default the project's source files are the
11970 Ada source files in the project file directory. Thus @file{pack.ads},
11971 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11972
11973 @node Specifying the Object Directory
11974 @unnumberedsubsubsec Specifying the Object Directory
11975
11976 @noindent
11977 Several project properties are modeled by Ada-style @emph{attributes};
11978 a property is defined by supplying the equivalent of an Ada attribute
11979 definition clause in the project file.
11980 A project's object directory is another such a property; the corresponding
11981 attribute is @code{Object_Dir}, and its value is also a string expression,
11982 specified either as absolute or relative. In the later case,
11983 it is relative to the project file directory. Thus the compiler's
11984 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11985 (for the @code{Debug} project)
11986 and to @file{^/common/release^[COMMON.RELEASE]^}
11987 (for the @code{Release} project).
11988 If @code{Object_Dir} is not specified, then the default is the project file
11989 directory itself.
11990
11991 @node Specifying the Exec Directory
11992 @unnumberedsubsubsec Specifying the Exec Directory
11993
11994 @noindent
11995 A project's exec directory is another property; the corresponding
11996 attribute is @code{Exec_Dir}, and its value is also a string expression,
11997 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11998 then the default is the object directory (which may also be the project file
11999 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12000 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12001 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12002 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12003
12004 @node Project File Packages
12005 @unnumberedsubsubsec Project File Packages
12006
12007 @noindent
12008 A GNAT tool that is integrated with the Project Manager is modeled by a
12009 corresponding package in the project file. In the example above,
12010 The @code{Debug} project defines the packages @code{Builder}
12011 (for @command{gnatmake}) and @code{Compiler};
12012 the @code{Release} project defines only the @code{Compiler} package.
12013
12014 The Ada-like package syntax is not to be taken literally. Although packages in
12015 project files bear a surface resemblance to packages in Ada source code, the
12016 notation is simply a way to convey a grouping of properties for a named
12017 entity. Indeed, the package names permitted in project files are restricted
12018 to a predefined set, corresponding to the project-aware tools, and the contents
12019 of packages are limited to a small set of constructs.
12020 The packages in the example above contain attribute definitions.
12021
12022 @node Specifying ^Switch^Switch^ Settings
12023 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12024
12025 @noindent
12026 ^Switch^Switch^ settings for a project-aware tool can be specified through
12027 attributes in the package that corresponds to the tool.
12028 The example above illustrates one of the relevant attributes,
12029 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12030 in both project files.
12031 Unlike simple attributes like @code{Source_Dirs},
12032 @code{^Default_Switches^Default_Switches^} is
12033 known as an @emph{associative array}. When you define this attribute, you must
12034 supply an ``index'' (a literal string), and the effect of the attribute
12035 definition is to set the value of the array at the specified index.
12036 For the @code{^Default_Switches^Default_Switches^} attribute,
12037 the index is a programming language (in our case, Ada),
12038 and the value specified (after @code{use}) must be a list
12039 of string expressions.
12040
12041 The attributes permitted in project files are restricted to a predefined set.
12042 Some may appear at project level, others in packages.
12043 For any attribute that is an associative array, the index must always be a
12044 literal string, but the restrictions on this string (e.g., a file name or a
12045 language name) depend on the individual attribute.
12046 Also depending on the attribute, its specified value will need to be either a
12047 string or a string list.
12048
12049 In the @code{Debug} project, we set the switches for two tools,
12050 @command{gnatmake} and the compiler, and thus we include the two corresponding
12051 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12052 attribute with index @code{"Ada"}.
12053 Note that the package corresponding to
12054 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
12055 similar, but only includes the @code{Compiler} package.
12056
12057 In project @code{Debug} above, the ^switches^switches^ starting with
12058 @option{-gnat} that are specified in package @code{Compiler}
12059 could have been placed in package @code{Builder}, since @command{gnatmake}
12060 transmits all such ^switches^switches^ to the compiler.
12061
12062 @node Main Subprograms
12063 @unnumberedsubsubsec Main Subprograms
12064
12065 @noindent
12066 One of the specifiable properties of a project is a list of files that contain
12067 main subprograms. This property is captured in the @code{Main} attribute,
12068 whose value is a list of strings. If a project defines the @code{Main}
12069 attribute, it is not necessary to identify the main subprogram(s) when
12070 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12071
12072 @node Executable File Names
12073 @unnumberedsubsubsec Executable File Names
12074
12075 @noindent
12076 By default, the executable file name corresponding to a main source is
12077 deduced from the main source file name. Through the attributes
12078 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12079 it is possible to change this default.
12080 In project @code{Debug} above, the executable file name
12081 for main source @file{^proc.adb^PROC.ADB^} is
12082 @file{^proc1^PROC1.EXE^}.
12083 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12084 of the executable files, when no attribute @code{Executable} applies:
12085 its value replace the platform-specific executable suffix.
12086 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12087 specify a non-default executable file name when several mains are built at once
12088 in a single @command{gnatmake} command.
12089
12090 @node Source File Naming Conventions
12091 @unnumberedsubsubsec Source File Naming Conventions
12092
12093 @noindent
12094 Since the project files above do not specify any source file naming
12095 conventions, the GNAT defaults are used. The mechanism for defining source
12096 file naming conventions -- a package named @code{Naming} --
12097 is described below (@pxref{Naming Schemes}).
12098
12099 @node Source Language(s)
12100 @unnumberedsubsubsec Source Language(s)
12101
12102 @noindent
12103 Since the project files do not specify a @code{Languages} attribute, by
12104 default the GNAT tools assume that the language of the project file is Ada.
12105 More generally, a project can comprise source files
12106 in Ada, C, and/or other languages.
12107
12108 @node Using External Variables
12109 @subsection Using External Variables
12110
12111 @noindent
12112 Instead of supplying different project files for debug and release, we can
12113 define a single project file that queries an external variable (set either
12114 on the command line or via an ^environment variable^logical name^) in order to
12115 conditionally define the appropriate settings. Again, assume that the
12116 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12117 located in directory @file{^/common^[COMMON]^}. The following project file,
12118 @file{build.gpr}, queries the external variable named @code{STYLE} and
12119 defines an object directory and ^switch^switch^ settings based on whether
12120 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12121 the default is @code{"deb"}.
12122
12123 @smallexample @c projectfile
12124 @group
12125 project Build is
12126 for Main use ("proc");
12127
12128 type Style_Type is ("deb", "rel");
12129 Style : Style_Type := external ("STYLE", "deb");
12130
12131 case Style is
12132 when "deb" =>
12133 for Object_Dir use "debug";
12134
12135 when "rel" =>
12136 for Object_Dir use "release";
12137 for Exec_Dir use ".";
12138 end case;
12139 @end group
12140
12141 @group
12142 package Builder is
12143
12144 case Style is
12145 when "deb" =>
12146 for ^Default_Switches^Default_Switches^ ("Ada")
12147 use ("^-g^-g^");
12148 for Executable ("proc") use "proc1";
12149 when others =>
12150 null;
12151 end case;
12152
12153 end Builder;
12154 @end group
12155
12156 @group
12157 package Compiler is
12158
12159 case Style is
12160 when "deb" =>
12161 for ^Default_Switches^Default_Switches^ ("Ada")
12162 use ("^-gnata^-gnata^",
12163 "^-gnato^-gnato^",
12164 "^-gnatE^-gnatE^");
12165
12166 when "rel" =>
12167 for ^Default_Switches^Default_Switches^ ("Ada")
12168 use ("^-O2^-O2^");
12169 end case;
12170
12171 end Compiler;
12172
12173 end Build;
12174 @end group
12175 @end smallexample
12176
12177 @noindent
12178 @code{Style_Type} is an example of a @emph{string type}, which is the project
12179 file analog of an Ada enumeration type but whose components are string literals
12180 rather than identifiers. @code{Style} is declared as a variable of this type.
12181
12182 The form @code{external("STYLE", "deb")} is known as an
12183 @emph{external reference}; its first argument is the name of an
12184 @emph{external variable}, and the second argument is a default value to be
12185 used if the external variable doesn't exist. You can define an external
12186 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12187 or you can use ^an environment variable^a logical name^
12188 as an external variable.
12189
12190 Each @code{case} construct is expanded by the Project Manager based on the
12191 value of @code{Style}. Thus the command
12192 @ifclear vms
12193 @smallexample
12194 gnatmake -P/common/build.gpr -XSTYLE=deb
12195 @end smallexample
12196 @end ifclear
12197
12198 @ifset vms
12199 @smallexample
12200 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12201 @end smallexample
12202 @end ifset
12203
12204 @noindent
12205 is equivalent to the @command{gnatmake} invocation using the project file
12206 @file{debug.gpr} in the earlier example. So is the command
12207 @smallexample
12208 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12209 @end smallexample
12210
12211 @noindent
12212 since @code{"deb"} is the default for @code{STYLE}.
12213
12214 Analogously,
12215
12216 @ifclear vms
12217 @smallexample
12218 gnatmake -P/common/build.gpr -XSTYLE=rel
12219 @end smallexample
12220 @end ifclear
12221
12222 @ifset vms
12223 @smallexample
12224 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12225 @end smallexample
12226 @end ifset
12227
12228 @noindent
12229 is equivalent to the @command{gnatmake} invocation using the project file
12230 @file{release.gpr} in the earlier example.
12231
12232 @node Importing Other Projects
12233 @subsection Importing Other Projects
12234 @cindex @code{ADA_PROJECT_PATH}
12235
12236 @noindent
12237 A compilation unit in a source file in one project may depend on compilation
12238 units in source files in other projects. To compile this unit under
12239 control of a project file, the
12240 dependent project must @emph{import} the projects containing the needed source
12241 files.
12242 This effect is obtained using syntax similar to an Ada @code{with} clause,
12243 but where @code{with}ed entities are strings that denote project files.
12244
12245 As an example, suppose that the two projects @code{GUI_Proj} and
12246 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12247 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12248 and @file{^/comm^[COMM]^}, respectively.
12249 Suppose that the source files for @code{GUI_Proj} are
12250 @file{gui.ads} and @file{gui.adb}, and that the source files for
12251 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12252 files is located in its respective project file directory. Schematically:
12253
12254 @smallexample
12255 @group
12256 ^/gui^[GUI]^
12257 gui_proj.gpr
12258 gui.ads
12259 gui.adb
12260 @end group
12261
12262 @group
12263 ^/comm^[COMM]^
12264 comm_proj.gpr
12265 comm.ads
12266 comm.adb
12267 @end group
12268 @end smallexample
12269
12270 @noindent
12271 We want to develop an application in directory @file{^/app^[APP]^} that
12272 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12273 the corresponding project files (e.g.@: the ^switch^switch^ settings
12274 and object directory).
12275 Skeletal code for a main procedure might be something like the following:
12276
12277 @smallexample @c ada
12278 @group
12279 with GUI, Comm;
12280 procedure App_Main is
12281 @dots{}
12282 begin
12283 @dots{}
12284 end App_Main;
12285 @end group
12286 @end smallexample
12287
12288 @noindent
12289 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12290 effect:
12291
12292 @smallexample @c projectfile
12293 @group
12294 with "/gui/gui_proj", "/comm/comm_proj";
12295 project App_Proj is
12296 for Main use ("app_main");
12297 end App_Proj;
12298 @end group
12299 @end smallexample
12300
12301 @noindent
12302 Building an executable is achieved through the command:
12303 @smallexample
12304 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12305 @end smallexample
12306 @noindent
12307 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12308 in the directory where @file{app_proj.gpr} resides.
12309
12310 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12311 (as illustrated above) the @code{with} clause can omit the extension.
12312
12313 Our example specified an absolute path for each imported project file.
12314 Alternatively, the directory name of an imported object can be omitted
12315 if either
12316 @itemize @bullet
12317 @item
12318 The imported project file is in the same directory as the importing project
12319 file, or
12320 @item
12321 You have defined ^an environment variable^a logical name^
12322 that includes the directory containing
12323 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12324 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12325 directory names separated by colons (semicolons on Windows).
12326 @end itemize
12327
12328 @noindent
12329 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12330 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12331 as follows:
12332
12333 @smallexample @c projectfile
12334 @group
12335 with "gui_proj", "comm_proj";
12336 project App_Proj is
12337 for Main use ("app_main");
12338 end App_Proj;
12339 @end group
12340 @end smallexample
12341
12342 @noindent
12343 Importing other projects can create ambiguities.
12344 For example, the same unit might be present in different imported projects, or
12345 it might be present in both the importing project and in an imported project.
12346 Both of these conditions are errors. Note that in the current version of
12347 the Project Manager, it is illegal to have an ambiguous unit even if the
12348 unit is never referenced by the importing project. This restriction may be
12349 relaxed in a future release.
12350
12351 @node Extending a Project
12352 @subsection Extending a Project
12353
12354 @noindent
12355 In large software systems it is common to have multiple
12356 implementations of a common interface; in Ada terms, multiple versions of a
12357 package body for the same spec. For example, one implementation
12358 might be safe for use in tasking programs, while another might only be used
12359 in sequential applications. This can be modeled in GNAT using the concept
12360 of @emph{project extension}. If one project (the ``child'') @emph{extends}
12361 another project (the ``parent'') then by default all source files of the
12362 parent project are inherited by the child, but the child project can
12363 override any of the parent's source files with new versions, and can also
12364 add new files. This facility is the project analog of a type extension in
12365 Object-Oriented Programming. Project hierarchies are permitted (a child
12366 project may be the parent of yet another project), and a project that
12367 inherits one project can also import other projects.
12368
12369 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12370 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12371 @file{pack.adb}, and @file{proc.adb}:
12372
12373 @smallexample
12374 @group
12375 ^/seq^[SEQ]^
12376 pack.ads
12377 pack.adb
12378 proc.adb
12379 seq_proj.gpr
12380 @end group
12381 @end smallexample
12382
12383 @noindent
12384 Note that the project file can simply be empty (that is, no attribute or
12385 package is defined):
12386
12387 @smallexample @c projectfile
12388 @group
12389 project Seq_Proj is
12390 end Seq_Proj;
12391 @end group
12392 @end smallexample
12393
12394 @noindent
12395 implying that its source files are all the Ada source files in the project
12396 directory.
12397
12398 Suppose we want to supply an alternate version of @file{pack.adb}, in
12399 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12400 @file{pack.ads} and @file{proc.adb}. We can define a project
12401 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12402
12403 @smallexample
12404 @group
12405 ^/tasking^[TASKING]^
12406 pack.adb
12407 tasking_proj.gpr
12408 @end group
12409
12410 @group
12411 project Tasking_Proj extends "/seq/seq_proj" is
12412 end Tasking_Proj;
12413 @end group
12414 @end smallexample
12415
12416 @noindent
12417 The version of @file{pack.adb} used in a build depends on which project file
12418 is specified.
12419
12420 Note that we could have obtained the desired behavior using project import
12421 rather than project inheritance; a @code{base} project would contain the
12422 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12423 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12424 would import @code{base} and add a different version of @file{pack.adb}. The
12425 choice depends on whether other sources in the original project need to be
12426 overridden. If they do, then project extension is necessary, otherwise,
12427 importing is sufficient.
12428
12429 @noindent
12430 In a project file that extends another project file, it is possible to
12431 indicate that an inherited source is not part of the sources of the extending
12432 project. This is necessary sometimes when a package spec has been overloaded
12433 and no longer requires a body: in this case, it is necessary to indicate that
12434 the inherited body is not part of the sources of the project, otherwise there
12435 will be a compilation error when compiling the spec.
12436
12437 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12438 Its value is a string list: a list of file names. It is also possible to use
12439 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12440 the file name of a text file containing a list of file names, one per line.
12441
12442 @smallexample @c @projectfile
12443 project B extends "a" is
12444 for Source_Files use ("pkg.ads");
12445 -- New spec of Pkg does not need a completion
12446 for Excluded_Source_Files use ("pkg.adb");
12447 end B;
12448 @end smallexample
12449
12450 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12451 is still needed: if it is possible to build using @command{gnatmake} when such
12452 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12453 it is possible to remove the source completely from a system that includes
12454 project P.
12455
12456 @c ***********************
12457 @c * Project File Syntax *
12458 @c ***********************
12459
12460 @node Project File Syntax
12461 @section Project File Syntax
12462
12463 @menu
12464 * Basic Syntax::
12465 * Qualified Projects::
12466 * Packages::
12467 * Expressions::
12468 * String Types::
12469 * Variables::
12470 * Attributes::
12471 * Associative Array Attributes::
12472 * case Constructions::
12473 @end menu
12474
12475 @noindent
12476 This section describes the structure of project files.
12477
12478 A project may be an @emph{independent project}, entirely defined by a single
12479 project file. Any Ada source file in an independent project depends only
12480 on the predefined library and other Ada source files in the same project.
12481
12482 @noindent
12483 A project may also @dfn{depend on} other projects, in either or both of
12484 the following ways:
12485 @itemize @bullet
12486 @item It may import any number of projects
12487 @item It may extend at most one other project
12488 @end itemize
12489
12490 @noindent
12491 The dependence relation is a directed acyclic graph (the subgraph reflecting
12492 the ``extends'' relation is a tree).
12493
12494 A project's @dfn{immediate sources} are the source files directly defined by
12495 that project, either implicitly by residing in the project file's directory,
12496 or explicitly through any of the source-related attributes described below.
12497 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12498 of @var{proj} together with the immediate sources (unless overridden) of any
12499 project on which @var{proj} depends (either directly or indirectly).
12500
12501 @node Basic Syntax
12502 @subsection Basic Syntax
12503
12504 @noindent
12505 As seen in the earlier examples, project files have an Ada-like syntax.
12506 The minimal project file is:
12507 @smallexample @c projectfile
12508 @group
12509 project Empty is
12510
12511 end Empty;
12512 @end group
12513 @end smallexample
12514
12515 @noindent
12516 The identifier @code{Empty} is the name of the project.
12517 This project name must be present after the reserved
12518 word @code{end} at the end of the project file, followed by a semi-colon.
12519
12520 Any name in a project file, such as the project name or a variable name,
12521 has the same syntax as an Ada identifier.
12522
12523 The reserved words of project files are the Ada 95 reserved words plus
12524 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
12525 reserved words currently used in project file syntax are:
12526
12527 @itemize @bullet
12528 @item
12529 @code{all}
12530 @item
12531 @code{at}
12532 @item
12533 @code{case}
12534 @item
12535 @code{end}
12536 @item
12537 @code{for}
12538 @item
12539 @code{is}
12540 @item
12541 @code{limited}
12542 @item
12543 @code{null}
12544 @item
12545 @code{others}
12546 @item
12547 @code{package}
12548 @item
12549 @code{renames}
12550 @item
12551 @code{type}
12552 @item
12553 @code{use}
12554 @item
12555 @code{when}
12556 @item
12557 @code{with}
12558 @end itemize
12559
12560 @noindent
12561 Comments in project files have the same syntax as in Ada, two consecutive
12562 hyphens through the end of the line.
12563
12564 @node Qualified Projects
12565 @subsection Qualified Projects
12566
12567 @noindent
12568 Before the reserved @code{project}, there may be one or two "qualifiers", that
12569 is identifiers or other reserved words, to qualify the project.
12570
12571 The current list of qualifiers is:
12572
12573 @itemize @bullet
12574 @item
12575 @code{abstract}: qualify a project with no sources. An abstract project must
12576 have a declaration specifying that there are no sources in the project, and,
12577 if it extends another project, the project it extends must also be a qualified
12578 abstract project.
12579
12580 @item
12581 @code{standard}: a standard project is a non library project with sources.
12582
12583 @item
12584 @code{aggregate}: for future extension
12585
12586 @item
12587 @code{aggregate library}: for future extension
12588
12589 @item
12590 @code{library}: a library project must declare both attributes
12591 @code{Library_Name} and @code{Library_Dir}.
12592
12593 @item
12594 @code{configuration}: a configuration project cannot be in a project tree.
12595 @end itemize
12596
12597 @node Packages
12598 @subsection Packages
12599
12600 @noindent
12601 A project file may contain @emph{packages}. The name of a package must be one
12602 of the identifiers from the following list. A package
12603 with a given name may only appear once in a project file. Package names are
12604 case insensitive. The following package names are legal:
12605
12606 @itemize @bullet
12607 @item
12608 @code{Naming}
12609 @item
12610 @code{Builder}
12611 @item
12612 @code{Compiler}
12613 @item
12614 @code{Binder}
12615 @item
12616 @code{Linker}
12617 @item
12618 @code{Finder}
12619 @item
12620 @code{Cross_Reference}
12621 @item
12622 @code{Eliminate}
12623 @item
12624 @code{Pretty_Printer}
12625 @item
12626 @code{Metrics}
12627 @item
12628 @code{gnatls}
12629 @item
12630 @code{gnatstub}
12631 @item
12632 @code{IDE}
12633 @item
12634 @code{Language_Processing}
12635 @end itemize
12636
12637 @noindent
12638 In its simplest form, a package may be empty:
12639
12640 @smallexample @c projectfile
12641 @group
12642 project Simple is
12643 package Builder is
12644 end Builder;
12645 end Simple;
12646 @end group
12647 @end smallexample
12648
12649 @noindent
12650 A package may contain @emph{attribute declarations},
12651 @emph{variable declarations} and @emph{case constructions}, as will be
12652 described below.
12653
12654 When there is ambiguity between a project name and a package name,
12655 the name always designates the project. To avoid possible confusion, it is
12656 always a good idea to avoid naming a project with one of the
12657 names allowed for packages or any name that starts with @code{gnat}.
12658
12659 @node Expressions
12660 @subsection Expressions
12661
12662 @noindent
12663 An @emph{expression} is either a @emph{string expression} or a
12664 @emph{string list expression}.
12665
12666 A @emph{string expression} is either a @emph{simple string expression} or a
12667 @emph{compound string expression}.
12668
12669 A @emph{simple string expression} is one of the following:
12670 @itemize @bullet
12671 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12672 @item A string-valued variable reference (@pxref{Variables})
12673 @item A string-valued attribute reference (@pxref{Attributes})
12674 @item An external reference (@pxref{External References in Project Files})
12675 @end itemize
12676
12677 @noindent
12678 A @emph{compound string expression} is a concatenation of string expressions,
12679 using the operator @code{"&"}
12680 @smallexample
12681 Path & "/" & File_Name & ".ads"
12682 @end smallexample
12683
12684 @noindent
12685 A @emph{string list expression} is either a
12686 @emph{simple string list expression} or a
12687 @emph{compound string list expression}.
12688
12689 A @emph{simple string list expression} is one of the following:
12690 @itemize @bullet
12691 @item A parenthesized list of zero or more string expressions,
12692 separated by commas
12693 @smallexample
12694 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12695 Empty_List := ();
12696 @end smallexample
12697 @item A string list-valued variable reference
12698 @item A string list-valued attribute reference
12699 @end itemize
12700
12701 @noindent
12702 A @emph{compound string list expression} is the concatenation (using
12703 @code{"&"}) of a simple string list expression and an expression. Note that
12704 each term in a compound string list expression, except the first, may be
12705 either a string expression or a string list expression.
12706
12707 @smallexample @c projectfile
12708 @group
12709 File_Name_List := () & File_Name; -- One string in this list
12710 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12711 -- Two strings
12712 Big_List := File_Name_List & Extended_File_Name_List;
12713 -- Concatenation of two string lists: three strings
12714 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12715 -- Illegal: must start with a string list
12716 @end group
12717 @end smallexample
12718
12719 @node String Types
12720 @subsection String Types
12721
12722 @noindent
12723 A @emph{string type declaration} introduces a discrete set of string literals.
12724 If a string variable is declared to have this type, its value
12725 is restricted to the given set of literals.
12726
12727 Here is an example of a string type declaration:
12728
12729 @smallexample @c projectfile
12730 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12731 @end smallexample
12732
12733 @noindent
12734 Variables of a string type are called @emph{typed variables}; all other
12735 variables are called @emph{untyped variables}. Typed variables are
12736 particularly useful in @code{case} constructions, to support conditional
12737 attribute declarations.
12738 (@pxref{case Constructions}).
12739
12740 The string literals in the list are case sensitive and must all be different.
12741 They may include any graphic characters allowed in Ada, including spaces.
12742
12743 A string type may only be declared at the project level, not inside a package.
12744
12745 A string type may be referenced by its name if it has been declared in the same
12746 project file, or by an expanded name whose prefix is the name of the project
12747 in which it is declared.
12748
12749 @node Variables
12750 @subsection Variables
12751
12752 @noindent
12753 A variable may be declared at the project file level, or within a package.
12754 Here are some examples of variable declarations:
12755
12756 @smallexample @c projectfile
12757 @group
12758 This_OS : OS := external ("OS"); -- a typed variable declaration
12759 That_OS := "GNU/Linux"; -- an untyped variable declaration
12760 @end group
12761 @end smallexample
12762
12763 @noindent
12764 The syntax of a @emph{typed variable declaration} is identical to the Ada
12765 syntax for an object declaration. By contrast, the syntax of an untyped
12766 variable declaration is identical to an Ada assignment statement. In fact,
12767 variable declarations in project files have some of the characteristics of
12768 an assignment, in that successive declarations for the same variable are
12769 allowed. Untyped variable declarations do establish the expected kind of the
12770 variable (string or string list), and successive declarations for it must
12771 respect the initial kind.
12772
12773 @noindent
12774 A string variable declaration (typed or untyped) declares a variable
12775 whose value is a string. This variable may be used as a string expression.
12776 @smallexample @c projectfile
12777 File_Name := "readme.txt";
12778 Saved_File_Name := File_Name & ".saved";
12779 @end smallexample
12780
12781 @noindent
12782 A string list variable declaration declares a variable whose value is a list
12783 of strings. The list may contain any number (zero or more) of strings.
12784
12785 @smallexample @c projectfile
12786 Empty_List := ();
12787 List_With_One_Element := ("^-gnaty^-gnaty^");
12788 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12789 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12790 "pack2.ada", "util_.ada", "util.ada");
12791 @end smallexample
12792
12793 @noindent
12794 The same typed variable may not be declared more than once at project level,
12795 and it may not be declared more than once in any package; it is in effect
12796 a constant.
12797
12798 The same untyped variable may be declared several times. Declarations are
12799 elaborated in the order in which they appear, so the new value replaces
12800 the old one, and any subsequent reference to the variable uses the new value.
12801 However, as noted above, if a variable has been declared as a string, all
12802 subsequent
12803 declarations must give it a string value. Similarly, if a variable has
12804 been declared as a string list, all subsequent declarations
12805 must give it a string list value.
12806
12807 A @emph{variable reference} may take several forms:
12808
12809 @itemize @bullet
12810 @item The simple variable name, for a variable in the current package (if any)
12811 or in the current project
12812 @item An expanded name, whose prefix is a context name.
12813 @end itemize
12814
12815 @noindent
12816 A @emph{context} may be one of the following:
12817
12818 @itemize @bullet
12819 @item The name of an existing package in the current project
12820 @item The name of an imported project of the current project
12821 @item The name of an ancestor project (i.e., a project extended by the current
12822 project, either directly or indirectly)
12823 @item An expanded name whose prefix is an imported/parent project name, and
12824 whose selector is a package name in that project.
12825 @end itemize
12826
12827 @noindent
12828 A variable reference may be used in an expression.
12829
12830 @node Attributes
12831 @subsection Attributes
12832
12833 @noindent
12834 A project (and its packages) may have @emph{attributes} that define
12835 the project's properties. Some attributes have values that are strings;
12836 others have values that are string lists.
12837
12838 There are two categories of attributes: @emph{simple attributes}
12839 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12840
12841 Legal project attribute names, and attribute names for each legal package are
12842 listed below. Attributes names are case-insensitive.
12843
12844 The following attributes are defined on projects (all are simple attributes):
12845
12846 @multitable @columnfractions .4 .3
12847 @item @emph{Attribute Name}
12848 @tab @emph{Value}
12849 @item @code{Source_Files}
12850 @tab string list
12851 @item @code{Source_Dirs}
12852 @tab string list
12853 @item @code{Source_List_File}
12854 @tab string
12855 @item @code{Object_Dir}
12856 @tab string
12857 @item @code{Exec_Dir}
12858 @tab string
12859 @item @code{Excluded_Source_Dirs}
12860 @tab string list
12861 @item @code{Excluded_Source_Files}
12862 @tab string list
12863 @item @code{Excluded_Source_List_File}
12864 @tab string
12865 @item @code{Languages}
12866 @tab string list
12867 @item @code{Main}
12868 @tab string list
12869 @item @code{Library_Dir}
12870 @tab string
12871 @item @code{Library_Name}
12872 @tab string
12873 @item @code{Library_Kind}
12874 @tab string
12875 @item @code{Library_Version}
12876 @tab string
12877 @item @code{Library_Interface}
12878 @tab string
12879 @item @code{Library_Auto_Init}
12880 @tab string
12881 @item @code{Library_Options}
12882 @tab string list
12883 @item @code{Library_Src_Dir}
12884 @tab string
12885 @item @code{Library_ALI_Dir}
12886 @tab string
12887 @item @code{Library_GCC}
12888 @tab string
12889 @item @code{Library_Symbol_File}
12890 @tab string
12891 @item @code{Library_Symbol_Policy}
12892 @tab string
12893 @item @code{Library_Reference_Symbol_File}
12894 @tab string
12895 @item @code{Externally_Built}
12896 @tab string
12897 @end multitable
12898
12899 @noindent
12900 The following attributes are defined for package @code{Naming}
12901 (@pxref{Naming Schemes}):
12902
12903 @multitable @columnfractions .4 .2 .2 .2
12904 @item Attribute Name @tab Category @tab Index @tab Value
12905 @item @code{Spec_Suffix}
12906 @tab associative array
12907 @tab language name
12908 @tab string
12909 @item @code{Body_Suffix}
12910 @tab associative array
12911 @tab language name
12912 @tab string
12913 @item @code{Separate_Suffix}
12914 @tab simple attribute
12915 @tab n/a
12916 @tab string
12917 @item @code{Casing}
12918 @tab simple attribute
12919 @tab n/a
12920 @tab string
12921 @item @code{Dot_Replacement}
12922 @tab simple attribute
12923 @tab n/a
12924 @tab string
12925 @item @code{Spec}
12926 @tab associative array
12927 @tab Ada unit name
12928 @tab string
12929 @item @code{Body}
12930 @tab associative array
12931 @tab Ada unit name
12932 @tab string
12933 @item @code{Specification_Exceptions}
12934 @tab associative array
12935 @tab language name
12936 @tab string list
12937 @item @code{Implementation_Exceptions}
12938 @tab associative array
12939 @tab language name
12940 @tab string list
12941 @end multitable
12942
12943 @noindent
12944 The following attributes are defined for packages @code{Builder},
12945 @code{Compiler}, @code{Binder},
12946 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12947 (@pxref{^Switches^Switches^ and Project Files}).
12948
12949 @multitable @columnfractions .4 .2 .2 .2
12950 @item Attribute Name @tab Category @tab Index @tab Value
12951 @item @code{^Default_Switches^Default_Switches^}
12952 @tab associative array
12953 @tab language name
12954 @tab string list
12955 @item @code{^Switches^Switches^}
12956 @tab associative array
12957 @tab file name
12958 @tab string list
12959 @end multitable
12960
12961 @noindent
12962 In addition, package @code{Compiler} has a single string attribute
12963 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12964 string attribute @code{Global_Configuration_Pragmas}.
12965
12966 @noindent
12967 Each simple attribute has a default value: the empty string (for string-valued
12968 attributes) and the empty list (for string list-valued attributes).
12969
12970 An attribute declaration defines a new value for an attribute.
12971
12972 Examples of simple attribute declarations:
12973
12974 @smallexample @c projectfile
12975 for Object_Dir use "objects";
12976 for Source_Dirs use ("units", "test/drivers");
12977 @end smallexample
12978
12979 @noindent
12980 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12981 attribute definition clause in Ada.
12982
12983 Attributes references may be appear in expressions.
12984 The general form for such a reference is @code{<entity>'<attribute>}:
12985 Associative array attributes are functions. Associative
12986 array attribute references must have an argument that is a string literal.
12987
12988 Examples are:
12989
12990 @smallexample @c projectfile
12991 project'Object_Dir
12992 Naming'Dot_Replacement
12993 Imported_Project'Source_Dirs
12994 Imported_Project.Naming'Casing
12995 Builder'^Default_Switches^Default_Switches^("Ada")
12996 @end smallexample
12997
12998 @noindent
12999 The prefix of an attribute may be:
13000 @itemize @bullet
13001 @item @code{project} for an attribute of the current project
13002 @item The name of an existing package of the current project
13003 @item The name of an imported project
13004 @item The name of a parent project that is extended by the current project
13005 @item An expanded name whose prefix is imported/parent project name,
13006 and whose selector is a package name
13007 @end itemize
13008
13009 @noindent
13010 Example:
13011 @smallexample @c projectfile
13012 @group
13013 project Prj is
13014 for Source_Dirs use project'Source_Dirs & "units";
13015 for Source_Dirs use project'Source_Dirs & "test/drivers"
13016 end Prj;
13017 @end group
13018 @end smallexample
13019
13020 @noindent
13021 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13022 has the default value: an empty string list. After this declaration,
13023 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13024 After the second attribute declaration @code{Source_Dirs} is a string list of
13025 two elements: @code{"units"} and @code{"test/drivers"}.
13026
13027 Note: this example is for illustration only. In practice,
13028 the project file would contain only one attribute declaration:
13029
13030 @smallexample @c projectfile
13031 for Source_Dirs use ("units", "test/drivers");
13032 @end smallexample
13033
13034 @node Associative Array Attributes
13035 @subsection Associative Array Attributes
13036
13037 @noindent
13038 Some attributes are defined as @emph{associative arrays}. An associative
13039 array may be regarded as a function that takes a string as a parameter
13040 and delivers a string or string list value as its result.
13041
13042 Here are some examples of single associative array attribute associations:
13043
13044 @smallexample @c projectfile
13045 for Body ("main") use "Main.ada";
13046 for ^Switches^Switches^ ("main.ada")
13047 use ("^-v^-v^",
13048 "^-gnatv^-gnatv^");
13049 for ^Switches^Switches^ ("main.ada")
13050 use Builder'^Switches^Switches^ ("main.ada")
13051 & "^-g^-g^";
13052 @end smallexample
13053
13054 @noindent
13055 Like untyped variables and simple attributes, associative array attributes
13056 may be declared several times. Each declaration supplies a new value for the
13057 attribute, and replaces the previous setting.
13058
13059 @noindent
13060 An associative array attribute may be declared as a full associative array
13061 declaration, with the value of the same attribute in an imported or extended
13062 project.
13063
13064 @smallexample @c projectfile
13065 package Builder is
13066 for Default_Switches use Default.Builder'Default_Switches;
13067 end Builder;
13068 @end smallexample
13069
13070 @noindent
13071 In this example, @code{Default} must be either a project imported by the
13072 current project, or the project that the current project extends. If the
13073 attribute is in a package (in this case, in package @code{Builder}), the same
13074 package needs to be specified.
13075
13076 @noindent
13077 A full associative array declaration replaces any other declaration for the
13078 attribute, including other full associative array declaration. Single
13079 associative array associations may be declare after a full associative
13080 declaration, modifying the value for a single association of the attribute.
13081
13082 @node case Constructions
13083 @subsection @code{case} Constructions
13084
13085 @noindent
13086 A @code{case} construction is used in a project file to effect conditional
13087 behavior.
13088 Here is a typical example:
13089
13090 @smallexample @c projectfile
13091 @group
13092 project MyProj is
13093 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13094
13095 OS : OS_Type := external ("OS", "GNU/Linux");
13096 @end group
13097
13098 @group
13099 package Compiler is
13100 case OS is
13101 when "GNU/Linux" | "Unix" =>
13102 for ^Default_Switches^Default_Switches^ ("Ada")
13103 use ("^-gnath^-gnath^");
13104 when "NT" =>
13105 for ^Default_Switches^Default_Switches^ ("Ada")
13106 use ("^-gnatP^-gnatP^");
13107 when others =>
13108 end case;
13109 end Compiler;
13110 end MyProj;
13111 @end group
13112 @end smallexample
13113
13114 @noindent
13115 The syntax of a @code{case} construction is based on the Ada case statement
13116 (although there is no @code{null} construction for empty alternatives).
13117
13118 The case expression must be a typed string variable.
13119 Each alternative comprises the reserved word @code{when}, either a list of
13120 literal strings separated by the @code{"|"} character or the reserved word
13121 @code{others}, and the @code{"=>"} token.
13122 Each literal string must belong to the string type that is the type of the
13123 case variable.
13124 An @code{others} alternative, if present, must occur last.
13125
13126 After each @code{=>}, there are zero or more constructions. The only
13127 constructions allowed in a case construction are other case constructions,
13128 attribute declarations and variable declarations. String type declarations and
13129 package declarations are not allowed. Variable declarations are restricted to
13130 variables that have already been declared before the case construction.
13131
13132 The value of the case variable is often given by an external reference
13133 (@pxref{External References in Project Files}).
13134
13135 @c ****************************************
13136 @c * Objects and Sources in Project Files *
13137 @c ****************************************
13138
13139 @node Objects and Sources in Project Files
13140 @section Objects and Sources in Project Files
13141
13142 @menu
13143 * Object Directory::
13144 * Exec Directory::
13145 * Source Directories::
13146 * Source File Names::
13147 @end menu
13148
13149 @noindent
13150 Each project has exactly one object directory and one or more source
13151 directories. The source directories must contain at least one source file,
13152 unless the project file explicitly specifies that no source files are present
13153 (@pxref{Source File Names}).
13154
13155 @node Object Directory
13156 @subsection Object Directory
13157
13158 @noindent
13159 The object directory for a project is the directory containing the compiler's
13160 output (such as @file{ALI} files and object files) for the project's immediate
13161 sources.
13162
13163 The object directory is given by the value of the attribute @code{Object_Dir}
13164 in the project file.
13165
13166 @smallexample @c projectfile
13167 for Object_Dir use "objects";
13168 @end smallexample
13169
13170 @noindent
13171 The attribute @code{Object_Dir} has a string value, the path name of the object
13172 directory. The path name may be absolute or relative to the directory of the
13173 project file. This directory must already exist, and be readable and writable.
13174
13175 By default, when the attribute @code{Object_Dir} is not given an explicit value
13176 or when its value is the empty string, the object directory is the same as the
13177 directory containing the project file.
13178
13179 @node Exec Directory
13180 @subsection Exec Directory
13181
13182 @noindent
13183 The exec directory for a project is the directory containing the executables
13184 for the project's main subprograms.
13185
13186 The exec directory is given by the value of the attribute @code{Exec_Dir}
13187 in the project file.
13188
13189 @smallexample @c projectfile
13190 for Exec_Dir use "executables";
13191 @end smallexample
13192
13193 @noindent
13194 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13195 directory. The path name may be absolute or relative to the directory of the
13196 project file. This directory must already exist, and be writable.
13197
13198 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13199 or when its value is the empty string, the exec directory is the same as the
13200 object directory of the project file.
13201
13202 @node Source Directories
13203 @subsection Source Directories
13204
13205 @noindent
13206 The source directories of a project are specified by the project file
13207 attribute @code{Source_Dirs}.
13208
13209 This attribute's value is a string list. If the attribute is not given an
13210 explicit value, then there is only one source directory, the one where the
13211 project file resides.
13212
13213 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13214 as in
13215
13216 @smallexample @c projectfile
13217 for Source_Dirs use ();
13218 @end smallexample
13219
13220 @noindent
13221 indicates that the project contains no source files.
13222
13223 Otherwise, each string in the string list designates one or more
13224 source directories.
13225
13226 @smallexample @c projectfile
13227 for Source_Dirs use ("sources", "test/drivers");
13228 @end smallexample
13229
13230 @noindent
13231 If a string in the list ends with @code{"/**"}, then the directory whose path
13232 name precedes the two asterisks, as well as all its subdirectories
13233 (recursively), are source directories.
13234
13235 @smallexample @c projectfile
13236 for Source_Dirs use ("/system/sources/**");
13237 @end smallexample
13238
13239 @noindent
13240 Here the directory @code{/system/sources} and all of its subdirectories
13241 (recursively) are source directories.
13242
13243 To specify that the source directories are the directory of the project file
13244 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13245 @smallexample @c projectfile
13246 for Source_Dirs use ("./**");
13247 @end smallexample
13248
13249 @noindent
13250 Each of the source directories must exist and be readable.
13251
13252 @node Source File Names
13253 @subsection Source File Names
13254
13255 @noindent
13256 In a project that contains source files, their names may be specified by the
13257 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13258 (a string). Source file names never include any directory information.
13259
13260 If the attribute @code{Source_Files} is given an explicit value, then each
13261 element of the list is a source file name.
13262
13263 @smallexample @c projectfile
13264 for Source_Files use ("main.adb");
13265 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13266 @end smallexample
13267
13268 @noindent
13269 If the attribute @code{Source_Files} is not given an explicit value,
13270 but the attribute @code{Source_List_File} is given a string value,
13271 then the source file names are contained in the text file whose path name
13272 (absolute or relative to the directory of the project file) is the
13273 value of the attribute @code{Source_List_File}.
13274
13275 Each line in the file that is not empty or is not a comment
13276 contains a source file name.
13277
13278 @smallexample @c projectfile
13279 for Source_List_File use "source_list.txt";
13280 @end smallexample
13281
13282 @noindent
13283 By default, if neither the attribute @code{Source_Files} nor the attribute
13284 @code{Source_List_File} is given an explicit value, then each file in the
13285 source directories that conforms to the project's naming scheme
13286 (@pxref{Naming Schemes}) is an immediate source of the project.
13287
13288 A warning is issued if both attributes @code{Source_Files} and
13289 @code{Source_List_File} are given explicit values. In this case, the attribute
13290 @code{Source_Files} prevails.
13291
13292 Each source file name must be the name of one existing source file
13293 in one of the source directories.
13294
13295 A @code{Source_Files} attribute whose value is an empty list
13296 indicates that there are no source files in the project.
13297
13298 If the order of the source directories is known statically, that is if
13299 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13300 be several files with the same source file name. In this case, only the file
13301 in the first directory is considered as an immediate source of the project
13302 file. If the order of the source directories is not known statically, it is
13303 an error to have several files with the same source file name.
13304
13305 Projects can be specified to have no Ada source
13306 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13307 list, or the @code{"Ada"} may be absent from @code{Languages}:
13308
13309 @smallexample @c projectfile
13310 for Source_Dirs use ();
13311 for Source_Files use ();
13312 for Languages use ("C", "C++");
13313 @end smallexample
13314
13315 @noindent
13316 Otherwise, a project must contain at least one immediate source.
13317
13318 Projects with no source files are useful as template packages
13319 (@pxref{Packages in Project Files}) for other projects; in particular to
13320 define a package @code{Naming} (@pxref{Naming Schemes}).
13321
13322 @c ****************************
13323 @c * Importing Projects *
13324 @c ****************************
13325
13326 @node Importing Projects
13327 @section Importing Projects
13328 @cindex @code{ADA_PROJECT_PATH}
13329
13330 @noindent
13331 An immediate source of a project P may depend on source files that
13332 are neither immediate sources of P nor in the predefined library.
13333 To get this effect, P must @emph{import} the projects that contain the needed
13334 source files.
13335
13336 @smallexample @c projectfile
13337 @group
13338 with "project1", "utilities.gpr";
13339 with "/namings/apex.gpr";
13340 project Main is
13341 @dots{}
13342 @end group
13343 @end smallexample
13344
13345 @noindent
13346 As can be seen in this example, the syntax for importing projects is similar
13347 to the syntax for importing compilation units in Ada. However, project files
13348 use literal strings instead of names, and the @code{with} clause identifies
13349 project files rather than packages.
13350
13351 Each literal string is the file name or path name (absolute or relative) of a
13352 project file. If a string corresponds to a file name, with no path or a
13353 relative path, then its location is determined by the @emph{project path}. The
13354 latter can be queried using @code{gnatls -v}. It contains:
13355
13356 @itemize @bullet
13357 @item
13358 In first position, the directory containing the current project file.
13359 @item
13360 In last position, the default project directory. This default project directory
13361 is part of the GNAT installation and is the standard place to install project
13362 files giving access to standard support libraries.
13363 @ifclear vms
13364 @ref{Installing a library}
13365 @end ifclear
13366
13367 @item
13368 In between, all the directories referenced in the
13369 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13370 @end itemize
13371
13372 @noindent
13373 If a relative pathname is used, as in
13374
13375 @smallexample @c projectfile
13376 with "tests/proj";
13377 @end smallexample
13378
13379 @noindent
13380 then the full path for the project is constructed by concatenating this
13381 relative path to those in the project path, in order, until a matching file is
13382 found. Any symbolic link will be fully resolved in the directory of the
13383 importing project file before the imported project file is examined.
13384
13385 If the @code{with}'ed project file name does not have an extension,
13386 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13387 then the file name as specified in the @code{with} clause (no extension) will
13388 be used. In the above example, if a file @code{project1.gpr} is found, then it
13389 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13390 then it will be used; if neither file exists, this is an error.
13391
13392 A warning is issued if the name of the project file does not match the
13393 name of the project; this check is case insensitive.
13394
13395 Any source file that is an immediate source of the imported project can be
13396 used by the immediate sources of the importing project, transitively. Thus
13397 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13398 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13399 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13400 because if and when @code{B} ceases to import @code{C}, some sources in
13401 @code{A} will no longer compile.
13402
13403 A side effect of this capability is that normally cyclic dependencies are not
13404 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13405 is not allowed to import @code{A}. However, there are cases when cyclic
13406 dependencies would be beneficial. For these cases, another form of import
13407 between projects exists, the @code{limited with}: a project @code{A} that
13408 imports a project @code{B} with a straight @code{with} may also be imported,
13409 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13410 to @code{A} include at least one @code{limited with}.
13411
13412 @smallexample @c 0projectfile
13413 with "../b/b.gpr";
13414 with "../c/c.gpr";
13415 project A is
13416 end A;
13417
13418 limited with "../a/a.gpr";
13419 project B is
13420 end B;
13421
13422 with "../d/d.gpr";
13423 project C is
13424 end C;
13425
13426 limited with "../a/a.gpr";
13427 project D is
13428 end D;
13429 @end smallexample
13430
13431 @noindent
13432 In the above legal example, there are two project cycles:
13433 @itemize @bullet
13434 @item A-> B-> A
13435 @item A -> C -> D -> A
13436 @end itemize
13437
13438 @noindent
13439 In each of these cycle there is one @code{limited with}: import of @code{A}
13440 from @code{B} and import of @code{A} from @code{D}.
13441
13442 The difference between straight @code{with} and @code{limited with} is that
13443 the name of a project imported with a @code{limited with} cannot be used in the
13444 project that imports it. In particular, its packages cannot be renamed and
13445 its variables cannot be referred to.
13446
13447 An exception to the above rules for @code{limited with} is that for the main
13448 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13449 @code{limited with} is equivalent to a straight @code{with}. For example,
13450 in the example above, projects @code{B} and @code{D} could not be main
13451 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13452 each have a @code{limited with} that is the only one in a cycle of importing
13453 projects.
13454
13455 @c *********************
13456 @c * Project Extension *
13457 @c *********************
13458
13459 @node Project Extension
13460 @section Project Extension
13461
13462 @noindent
13463 During development of a large system, it is sometimes necessary to use
13464 modified versions of some of the source files, without changing the original
13465 sources. This can be achieved through the @emph{project extension} facility.
13466
13467 @smallexample @c projectfile
13468 project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13469 @end smallexample
13470
13471 @noindent
13472 A project extension declaration introduces an extending project
13473 (the @emph{child}) and a project being extended (the @emph{parent}).
13474
13475 By default, a child project inherits all the sources of its parent.
13476 However, inherited sources can be overridden: a unit in a parent is hidden
13477 by a unit of the same name in the child.
13478
13479 Inherited sources are considered to be sources (but not immediate sources)
13480 of the child project; see @ref{Project File Syntax}.
13481
13482 An inherited source file retains any switches specified in the parent project.
13483
13484 For example if the project @code{Utilities} contains the spec and the
13485 body of an Ada package @code{Util_IO}, then the project
13486 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13487 The original body of @code{Util_IO} will not be considered in program builds.
13488 However, the package spec will still be found in the project
13489 @code{Utilities}.
13490
13491 A child project can have only one parent, except when it is qualified as
13492 abstract. But it may import any number of other projects.
13493
13494 A project is not allowed to import directly or indirectly at the same time a
13495 child project and any of its ancestors.
13496
13497 @c *******************************
13498 @c * Project Hierarchy Extension *
13499 @c *******************************
13500
13501 @node Project Hierarchy Extension
13502 @section Project Hierarchy Extension
13503
13504 @noindent
13505 When extending a large system spanning multiple projects, it is often
13506 inconvenient to extend every project in the hierarchy that is impacted by a
13507 small change introduced. In such cases, it is possible to create a virtual
13508 extension of entire hierarchy using @code{extends all} relationship.
13509
13510 When the project is extended using @code{extends all} inheritance, all projects
13511 that are imported by it, both directly and indirectly, are considered virtually
13512 extended. That is, the Project Manager creates "virtual projects"
13513 that extend every project in the hierarchy; all these virtual projects have
13514 no sources of their own and have as object directory the object directory of
13515 the root of "extending all" project.
13516
13517 It is possible to explicitly extend one or more projects in the hierarchy
13518 in order to modify the sources. These extending projects must be imported by
13519 the "extending all" project, which will replace the corresponding virtual
13520 projects with the explicit ones.
13521
13522 When building such a project hierarchy extension, the Project Manager will
13523 ensure that both modified sources and sources in virtual extending projects
13524 that depend on them, are recompiled.
13525
13526 By means of example, consider the following hierarchy of projects.
13527
13528 @enumerate
13529 @item
13530 project A, containing package P1
13531 @item
13532 project B importing A and containing package P2 which depends on P1
13533 @item
13534 project C importing B and containing package P3 which depends on P2
13535 @end enumerate
13536
13537 @noindent
13538 We want to modify packages P1 and P3.
13539
13540 This project hierarchy will need to be extended as follows:
13541
13542 @enumerate
13543 @item
13544 Create project A1 that extends A, placing modified P1 there:
13545
13546 @smallexample @c 0projectfile
13547 project A1 extends "(@dots{})/A" is
13548 end A1;
13549 @end smallexample
13550
13551 @item
13552 Create project C1 that "extends all" C and imports A1, placing modified
13553 P3 there:
13554
13555 @smallexample @c 0projectfile
13556 with "(@dots{})/A1";
13557 project C1 extends all "(@dots{})/C" is
13558 end C1;
13559 @end smallexample
13560 @end enumerate
13561
13562 When you build project C1, your entire modified project space will be
13563 recompiled, including the virtual project B1 that has been impacted by the
13564 "extending all" inheritance of project C.
13565
13566 Note that if a Library Project in the hierarchy is virtually extended,
13567 the virtual project that extends the Library Project is not a Library Project.
13568
13569 @c ****************************************
13570 @c * External References in Project Files *
13571 @c ****************************************
13572
13573 @node External References in Project Files
13574 @section External References in Project Files
13575
13576 @noindent
13577 A project file may contain references to external variables; such references
13578 are called @emph{external references}.
13579
13580 An external variable is either defined as part of the environment (an
13581 environment variable in Unix, for example) or else specified on the command
13582 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13583 If both, then the command line value is used.
13584
13585 The value of an external reference is obtained by means of the built-in
13586 function @code{external}, which returns a string value.
13587 This function has two forms:
13588 @itemize @bullet
13589 @item @code{external (external_variable_name)}
13590 @item @code{external (external_variable_name, default_value)}
13591 @end itemize
13592
13593 @noindent
13594 Each parameter must be a string literal. For example:
13595
13596 @smallexample @c projectfile
13597 external ("USER")
13598 external ("OS", "GNU/Linux")
13599 @end smallexample
13600
13601 @noindent
13602 In the form with one parameter, the function returns the value of
13603 the external variable given as parameter. If this name is not present in the
13604 environment, the function returns an empty string.
13605
13606 In the form with two string parameters, the second argument is
13607 the value returned when the variable given as the first argument is not
13608 present in the environment. In the example above, if @code{"OS"} is not
13609 the name of ^an environment variable^a logical name^ and is not passed on
13610 the command line, then the returned value is @code{"GNU/Linux"}.
13611
13612 An external reference may be part of a string expression or of a string
13613 list expression, and can therefore appear in a variable declaration or
13614 an attribute declaration.
13615
13616 @smallexample @c projectfile
13617 @group
13618 type Mode_Type is ("Debug", "Release");
13619 Mode : Mode_Type := external ("MODE");
13620 case Mode is
13621 when "Debug" =>
13622 @dots{}
13623 @end group
13624 @end smallexample
13625
13626 @c *****************************
13627 @c * Packages in Project Files *
13628 @c *****************************
13629
13630 @node Packages in Project Files
13631 @section Packages in Project Files
13632
13633 @noindent
13634 A @emph{package} defines the settings for project-aware tools within a
13635 project.
13636 For each such tool one can declare a package; the names for these
13637 packages are preset (@pxref{Packages}).
13638 A package may contain variable declarations, attribute declarations, and case
13639 constructions.
13640
13641 @smallexample @c projectfile
13642 @group
13643 project Proj is
13644 package Builder is -- used by gnatmake
13645 for ^Default_Switches^Default_Switches^ ("Ada")
13646 use ("^-v^-v^",
13647 "^-g^-g^");
13648 end Builder;
13649 end Proj;
13650 @end group
13651 @end smallexample
13652
13653 @noindent
13654 The syntax of package declarations mimics that of package in Ada.
13655
13656 Most of the packages have an attribute
13657 @code{^Default_Switches^Default_Switches^}.
13658 This attribute is an associative array, and its value is a string list.
13659 The index of the associative array is the name of a programming language (case
13660 insensitive). This attribute indicates the ^switch^switch^
13661 or ^switches^switches^ to be used
13662 with the corresponding tool.
13663
13664 Some packages also have another attribute, @code{^Switches^Switches^},
13665 an associative array whose value is a string list.
13666 The index is the name of a source file.
13667 This attribute indicates the ^switch^switch^
13668 or ^switches^switches^ to be used by the corresponding
13669 tool when dealing with this specific file.
13670
13671 Further information on these ^switch^switch^-related attributes is found in
13672 @ref{^Switches^Switches^ and Project Files}.
13673
13674 A package may be declared as a @emph{renaming} of another package; e.g., from
13675 the project file for an imported project.
13676
13677 @smallexample @c projectfile
13678 @group
13679 with "/global/apex.gpr";
13680 project Example is
13681 package Naming renames Apex.Naming;
13682 @dots{}
13683 end Example;
13684 @end group
13685 @end smallexample
13686
13687 @noindent
13688 Packages that are renamed in other project files often come from project files
13689 that have no sources: they are just used as templates. Any modification in the
13690 template will be reflected automatically in all the project files that rename
13691 a package from the template.
13692
13693 In addition to the tool-oriented packages, you can also declare a package
13694 named @code{Naming} to establish specialized source file naming conventions
13695 (@pxref{Naming Schemes}).
13696
13697 @c ************************************
13698 @c * Variables from Imported Projects *
13699 @c ************************************
13700
13701 @node Variables from Imported Projects
13702 @section Variables from Imported Projects
13703
13704 @noindent
13705 An attribute or variable defined in an imported or parent project can
13706 be used in expressions in the importing / extending project.
13707 Such an attribute or variable is denoted by an expanded name whose prefix
13708 is either the name of the project or the expanded name of a package within
13709 a project.
13710
13711 @smallexample @c projectfile
13712 @group
13713 with "imported";
13714 project Main extends "base" is
13715 Var1 := Imported.Var;
13716 Var2 := Base.Var & ".new";
13717 @end group
13718
13719 @group
13720 package Builder is
13721 for ^Default_Switches^Default_Switches^ ("Ada")
13722 use Imported.Builder'Ada_^Switches^Switches^ &
13723 "^-gnatg^-gnatg^" &
13724 "^-v^-v^";
13725 end Builder;
13726 @end group
13727
13728 @group
13729 package Compiler is
13730 for ^Default_Switches^Default_Switches^ ("Ada")
13731 use Base.Compiler'Ada_^Switches^Switches^;
13732 end Compiler;
13733 end Main;
13734 @end group
13735 @end smallexample
13736
13737 @noindent
13738 In this example:
13739
13740 @itemize @bullet
13741 @item
13742 The value of @code{Var1} is a copy of the variable @code{Var} defined
13743 in the project file @file{"imported.gpr"}
13744 @item
13745 the value of @code{Var2} is a copy of the value of variable @code{Var}
13746 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13747 @item
13748 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13749 @code{Builder} is a string list that includes in its value a copy of the value
13750 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13751 in project file @file{imported.gpr} plus two new elements:
13752 @option{"^-gnatg^-gnatg^"}
13753 and @option{"^-v^-v^"};
13754 @item
13755 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13756 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13757 defined in the @code{Compiler} package in project file @file{base.gpr},
13758 the project being extended.
13759 @end itemize
13760
13761 @c ******************
13762 @c * Naming Schemes *
13763 @c ******************
13764
13765 @node Naming Schemes
13766 @section Naming Schemes
13767
13768 @noindent
13769 Sometimes an Ada software system is ported from a foreign compilation
13770 environment to GNAT, and the file names do not use the default GNAT
13771 conventions. Instead of changing all the file names (which for a variety
13772 of reasons might not be possible), you can define the relevant file
13773 naming scheme in the @code{Naming} package in your project file.
13774
13775 @noindent
13776 Note that the use of pragmas described in
13777 @ref{Alternative File Naming Schemes} by mean of a configuration
13778 pragmas file is not supported when using project files. You must use
13779 the features described in this paragraph. You can however use specify
13780 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13781
13782 @ifclear vms
13783 For example, the following
13784 package models the Apex file naming rules:
13785
13786 @smallexample @c projectfile
13787 @group
13788 package Naming is
13789 for Casing use "lowercase";
13790 for Dot_Replacement use ".";
13791 for Spec_Suffix ("Ada") use ".1.ada";
13792 for Body_Suffix ("Ada") use ".2.ada";
13793 end Naming;
13794 @end group
13795 @end smallexample
13796 @end ifclear
13797
13798 @ifset vms
13799 For example, the following package models the HP Ada file naming rules:
13800
13801 @smallexample @c projectfile
13802 @group
13803 package Naming is
13804 for Casing use "lowercase";
13805 for Dot_Replacement use "__";
13806 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13807 for Body_Suffix ("Ada") use ".^ada^ada^";
13808 end Naming;
13809 @end group
13810 @end smallexample
13811
13812 @noindent
13813 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13814 names in lower case)
13815 @end ifset
13816
13817 @noindent
13818 You can define the following attributes in package @code{Naming}:
13819
13820 @table @code
13821
13822 @item @code{Casing}
13823 This must be a string with one of the three values @code{"lowercase"},
13824 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13825
13826 @noindent
13827 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13828
13829 @item @code{Dot_Replacement}
13830 This must be a string whose value satisfies the following conditions:
13831
13832 @itemize @bullet
13833 @item It must not be empty
13834 @item It cannot start or end with an alphanumeric character
13835 @item It cannot be a single underscore
13836 @item It cannot start with an underscore followed by an alphanumeric
13837 @item It cannot contain a dot @code{'.'} except if the entire string
13838 is @code{"."}
13839 @end itemize
13840
13841 @noindent
13842 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13843
13844 @item @code{Spec_Suffix}
13845 This is an associative array (indexed by the programming language name, case
13846 insensitive) whose value is a string that must satisfy the following
13847 conditions:
13848
13849 @itemize @bullet
13850 @item It must not be empty
13851 @item It must include at least one dot
13852 @end itemize
13853 @noindent
13854 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13855 @code{"^.ads^.ADS^"}.
13856
13857 @item @code{Body_Suffix}
13858 This is an associative array (indexed by the programming language name, case
13859 insensitive) whose value is a string that must satisfy the following
13860 conditions:
13861
13862 @itemize @bullet
13863 @item It must not be empty
13864 @item It must include at least one dot
13865 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13866 @end itemize
13867 @noindent
13868 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13869 same string, then a file name that ends with the longest of these two suffixes
13870 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13871 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13872
13873 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13874 @code{"^.adb^.ADB^"}.
13875
13876 @item @code{Separate_Suffix}
13877 This must be a string whose value satisfies the same conditions as
13878 @code{Body_Suffix}. The same "longest suffix" rules apply.
13879
13880 @noindent
13881 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13882 value as @code{Body_Suffix ("Ada")}.
13883
13884 @item @code{Spec}
13885 @noindent
13886 You can use the associative array attribute @code{Spec} to define
13887 the source file name for an individual Ada compilation unit's spec. The array
13888 index must be a string literal that identifies the Ada unit (case insensitive).
13889 The value of this attribute must be a string that identifies the file that
13890 contains this unit's spec (case sensitive or insensitive depending on the
13891 operating system).
13892
13893 @smallexample @c projectfile
13894 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13895 @end smallexample
13896
13897 When the source file contains several units, you can indicate at what
13898 position the unit occurs in the file, with the following. The first unit
13899 in the file has index 1
13900
13901 @smallexample @c projectfile
13902 for Body ("top") use "foo.a" at 1;
13903 for Body ("foo") use "foo.a" at 2;
13904 @end smallexample
13905
13906 @item @code{Body}
13907
13908 You can use the associative array attribute @code{Body} to
13909 define the source file name for an individual Ada compilation unit's body
13910 (possibly a subunit). The array index must be a string literal that identifies
13911 the Ada unit (case insensitive). The value of this attribute must be a string
13912 that identifies the file that contains this unit's body or subunit (case
13913 sensitive or insensitive depending on the operating system).
13914
13915 @smallexample @c projectfile
13916 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13917 @end smallexample
13918 @end table
13919
13920 @c ********************
13921 @c * Library Projects *
13922 @c ********************
13923
13924 @node Library Projects
13925 @section Library Projects
13926
13927 @noindent
13928 @emph{Library projects} are projects whose object code is placed in a library.
13929 (Note that this facility is not yet supported on all platforms).
13930
13931 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13932 single archive, which might either be a shared or a static library. This
13933 library can later on be linked with multiple executables, potentially
13934 reducing their sizes.
13935
13936 If your project file specifies languages other than Ada, but you are still
13937 using @code{gnatmake} to compile and link, the latter will not try to
13938 compile your sources other than Ada (you should use @code{gprbuild} if that
13939 is your intent). However, @code{gnatmake} will automatically link all object
13940 files found in the object directory, whether or not they were compiled from
13941 an Ada source file. This specific behavior only applies when multiple
13942 languages are specified.
13943
13944 To create a library project, you need to define in its project file
13945 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13946 Additionally, you may define other library-related attributes such as
13947 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13948 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13949
13950 The @code{Library_Name} attribute has a string value. There is no restriction
13951 on the name of a library. It is the responsibility of the developer to
13952 choose a name that will be accepted by the platform. It is recommended to
13953 choose names that could be Ada identifiers; such names are almost guaranteed
13954 to be acceptable on all platforms.
13955
13956 The @code{Library_Dir} attribute has a string value that designates the path
13957 (absolute or relative) of the directory where the library will reside.
13958 It must designate an existing directory, and this directory must be writable,
13959 different from the project's object directory and from any source directory
13960 in the project tree.
13961
13962 If both @code{Library_Name} and @code{Library_Dir} are specified and
13963 are legal, then the project file defines a library project. The optional
13964 library-related attributes are checked only for such project files.
13965
13966 The @code{Library_Kind} attribute has a string value that must be one of the
13967 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13968 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13969 attribute is not specified, the library is a static library, that is
13970 an archive of object files that can be potentially linked into a
13971 static executable. Otherwise, the library may be dynamic or
13972 relocatable, that is a library that is loaded only at the start of execution.
13973
13974 If you need to build both a static and a dynamic library, you should use two
13975 different object directories, since in some cases some extra code needs to
13976 be generated for the latter. For such cases, it is recommended to either use
13977 two different project files, or a single one which uses external variables
13978 to indicate what kind of library should be build.
13979
13980 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13981 directory where the ALI files of the library will be copied. When it is
13982 not specified, the ALI files are copied to the directory specified in
13983 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13984 must be writable and different from the project's object directory and from
13985 any source directory in the project tree.
13986
13987 The @code{Library_Version} attribute has a string value whose interpretation
13988 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13989 used only for dynamic/relocatable libraries as the internal name of the
13990 library (the @code{"soname"}). If the library file name (built from the
13991 @code{Library_Name}) is different from the @code{Library_Version}, then the
13992 library file will be a symbolic link to the actual file whose name will be
13993 @code{Library_Version}.
13994
13995 Example (on Unix):
13996
13997 @smallexample @c projectfile
13998 @group
13999 project Plib is
14000
14001 Version := "1";
14002
14003 for Library_Dir use "lib_dir";
14004 for Library_Name use "dummy";
14005 for Library_Kind use "relocatable";
14006 for Library_Version use "libdummy.so." & Version;
14007
14008 end Plib;
14009 @end group
14010 @end smallexample
14011
14012 @noindent
14013 Directory @file{lib_dir} will contain the internal library file whose name
14014 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14015 @file{libdummy.so.1}.
14016
14017 When @command{gnatmake} detects that a project file
14018 is a library project file, it will check all immediate sources of the project
14019 and rebuild the library if any of the sources have been recompiled.
14020
14021 Standard project files can import library project files. In such cases,
14022 the libraries will only be rebuilt if some of its sources are recompiled
14023 because they are in the closure of some other source in an importing project.
14024 Sources of the library project files that are not in such a closure will
14025 not be checked, unless the full library is checked, because one of its sources
14026 needs to be recompiled.
14027
14028 For instance, assume the project file @code{A} imports the library project file
14029 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14030 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14031 @file{l2.ads}, @file{l2.adb}.
14032
14033 If @file{l1.adb} has been modified, then the library associated with @code{L}
14034 will be rebuilt when compiling all the immediate sources of @code{A} only
14035 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14036 @code{"with L1;"}.
14037
14038 To be sure that all the sources in the library associated with @code{L} are
14039 up to date, and that all the sources of project @code{A} are also up to date,
14040 the following two commands needs to be used:
14041
14042 @smallexample
14043 gnatmake -Pl.gpr
14044 gnatmake -Pa.gpr
14045 @end smallexample
14046
14047 When a library is built or rebuilt, an attempt is made first to delete all
14048 files in the library directory.
14049 All @file{ALI} files will also be copied from the object directory to the
14050 library directory. To build executables, @command{gnatmake} will use the
14051 library rather than the individual object files.
14052
14053 @ifclear vms
14054 It is also possible to create library project files for third-party libraries
14055 that are precompiled and cannot be compiled locally thanks to the
14056 @code{externally_built} attribute. (See @ref{Installing a library}).
14057 @end ifclear
14058
14059 @c *******************************
14060 @c * Stand-alone Library Projects *
14061 @c *******************************
14062
14063 @node Stand-alone Library Projects
14064 @section Stand-alone Library Projects
14065
14066 @noindent
14067 A Stand-alone Library is a library that contains the necessary code to
14068 elaborate the Ada units that are included in the library. A Stand-alone
14069 Library is suitable to be used in an executable when the main is not
14070 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14071 subprogram.
14072
14073 A Stand-alone Library Project is a Library Project where the library is
14074 a Stand-alone Library.
14075
14076 To be a Stand-alone Library Project, in addition to the two attributes
14077 that make a project a Library Project (@code{Library_Name} and
14078 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14079 @code{Library_Interface} must be defined.
14080
14081 @smallexample @c projectfile
14082 @group
14083 for Library_Dir use "lib_dir";
14084 for Library_Name use "dummy";
14085 for Library_Interface use ("int1", "int1.child");
14086 @end group
14087 @end smallexample
14088
14089 Attribute @code{Library_Interface} has a nonempty string list value,
14090 each string in the list designating a unit contained in an immediate source
14091 of the project file.
14092
14093 When a Stand-alone Library is built, first the binder is invoked to build
14094 a package whose name depends on the library name
14095 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14096 This binder-generated package includes initialization and
14097 finalization procedures whose
14098 names depend on the library name (dummyinit and dummyfinal in the example
14099 above). The object corresponding to this package is included in the library.
14100
14101 A dynamic or relocatable Stand-alone Library is automatically initialized
14102 if automatic initialization of Stand-alone Libraries is supported on the
14103 platform and if attribute @code{Library_Auto_Init} is not specified or
14104 is specified with the value "true". A static Stand-alone Library is never
14105 automatically initialized.
14106
14107 Single string attribute @code{Library_Auto_Init} may be specified with only
14108 two possible values: "false" or "true" (case-insensitive). Specifying
14109 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14110 initialization of dynamic or relocatable libraries.
14111
14112 When a non-automatically initialized Stand-alone Library is used
14113 in an executable, its initialization procedure must be called before
14114 any service of the library is used.
14115 When the main subprogram is in Ada, it may mean that the initialization
14116 procedure has to be called during elaboration of another package.
14117
14118 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14119 (those that are listed in attribute @code{Library_Interface}) are copied to
14120 the Library Directory. As a consequence, only the Interface Units may be
14121 imported from Ada units outside of the library. If other units are imported,
14122 the binding phase will fail.
14123
14124 When a Stand-Alone Library is bound, the switches that are specified in
14125 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14126 used in the call to @command{gnatbind}.
14127
14128 The string list attribute @code{Library_Options} may be used to specified
14129 additional switches to the call to @command{gcc} to link the library.
14130
14131 The attribute @code{Library_Src_Dir}, may be specified for a
14132 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14133 single string value. Its value must be the path (absolute or relative to the
14134 project directory) of an existing directory. This directory cannot be the
14135 object directory or one of the source directories, but it can be the same as
14136 the library directory. The sources of the Interface
14137 Units of the library, necessary to an Ada client of the library, will be
14138 copied to the designated directory, called Interface Copy directory.
14139 These sources includes the specs of the Interface Units, but they may also
14140 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14141 are used, or when there is a generic units in the spec. Before the sources
14142 are copied to the Interface Copy directory, an attempt is made to delete all
14143 files in the Interface Copy directory.
14144
14145 @c *************************************
14146 @c * Switches Related to Project Files *
14147 @c *************************************
14148 @node Switches Related to Project Files
14149 @section Switches Related to Project Files
14150
14151 @noindent
14152 The following switches are used by GNAT tools that support project files:
14153
14154 @table @option
14155
14156 @item ^-P^/PROJECT_FILE=^@var{project}
14157 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14158 Indicates the name of a project file. This project file will be parsed with
14159 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14160 if any, and using the external references indicated
14161 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14162 @ifclear vms
14163 There may zero, one or more spaces between @option{-P} and @var{project}.
14164 @end ifclear
14165
14166 @noindent
14167 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14168
14169 @noindent
14170 Since the Project Manager parses the project file only after all the switches
14171 on the command line are checked, the order of the switches
14172 @option{^-P^/PROJECT_FILE^},
14173 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14174 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14175
14176 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14177 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14178 Indicates that external variable @var{name} has the value @var{value}.
14179 The Project Manager will use this value for occurrences of
14180 @code{external(name)} when parsing the project file.
14181
14182 @ifclear vms
14183 @noindent
14184 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14185 put between quotes.
14186 @smallexample
14187 -XOS=NT
14188 -X"user=John Doe"
14189 @end smallexample
14190 @end ifclear
14191
14192 @noindent
14193 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14194 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14195 @var{name}, only the last one is used.
14196
14197 @noindent
14198 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14199 takes precedence over the value of the same name in the environment.
14200
14201 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14202 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14203 Indicates the verbosity of the parsing of GNAT project files.
14204
14205 @ifclear vms
14206 @option{-vP0} means Default;
14207 @option{-vP1} means Medium;
14208 @option{-vP2} means High.
14209 @end ifclear
14210
14211 @ifset vms
14212 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14213 HIGH.
14214 @end ifset
14215
14216 @noindent
14217 The default is ^Default^DEFAULT^: no output for syntactically correct
14218 project files.
14219 @noindent
14220 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14221 only the last one is used.
14222
14223 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14224 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14225 Add directory <dir> at the beginning of the project search path, in order,
14226 after the current working directory.
14227
14228 @ifclear vms
14229 @item -eL
14230 @cindex @option{-eL} (any project-aware tool)
14231 Follow all symbolic links when processing project files.
14232 @end ifclear
14233
14234 @item ^--subdirs^/SUBDIRS^=<subdir>
14235 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14236 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14237 directories (except the source directories) are the subdirectories <subdir>
14238 of the directories specified in the project files. This applies in particular
14239 to object directories, library directories and exec directories. If the
14240 subdirectories do not exist, they are created automatically.
14241
14242 @end table
14243
14244 @c **********************************
14245 @c * Tools Supporting Project Files *
14246 @c **********************************
14247
14248 @node Tools Supporting Project Files
14249 @section Tools Supporting Project Files
14250
14251 @menu
14252 * gnatmake and Project Files::
14253 * The GNAT Driver and Project Files::
14254 @end menu
14255
14256 @node gnatmake and Project Files
14257 @subsection gnatmake and Project Files
14258
14259 @noindent
14260 This section covers several topics related to @command{gnatmake} and
14261 project files: defining ^switches^switches^ for @command{gnatmake}
14262 and for the tools that it invokes; specifying configuration pragmas;
14263 the use of the @code{Main} attribute; building and rebuilding library project
14264 files.
14265
14266 @menu
14267 * ^Switches^Switches^ and Project Files::
14268 * Specifying Configuration Pragmas::
14269 * Project Files and Main Subprograms::
14270 * Library Project Files::
14271 @end menu
14272
14273 @node ^Switches^Switches^ and Project Files
14274 @subsubsection ^Switches^Switches^ and Project Files
14275
14276 @ifset vms
14277 It is not currently possible to specify VMS style qualifiers in the project
14278 files; only Unix style ^switches^switches^ may be specified.
14279 @end ifset
14280
14281 @noindent
14282 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14283 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14284 attribute, a @code{^Switches^Switches^} attribute, or both;
14285 as their names imply, these ^switch^switch^-related
14286 attributes affect the ^switches^switches^ that are used for each of these GNAT
14287 components when
14288 @command{gnatmake} is invoked. As will be explained below, these
14289 component-specific ^switches^switches^ precede
14290 the ^switches^switches^ provided on the @command{gnatmake} command line.
14291
14292 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14293 array indexed by language name (case insensitive) whose value is a string list.
14294 For example:
14295
14296 @smallexample @c projectfile
14297 @group
14298 package Compiler is
14299 for ^Default_Switches^Default_Switches^ ("Ada")
14300 use ("^-gnaty^-gnaty^",
14301 "^-v^-v^");
14302 end Compiler;
14303 @end group
14304 @end smallexample
14305
14306 @noindent
14307 The @code{^Switches^Switches^} attribute is also an associative array,
14308 indexed by a file name (which may or may not be case sensitive, depending
14309 on the operating system) whose value is a string list. For example:
14310
14311 @smallexample @c projectfile
14312 @group
14313 package Builder is
14314 for ^Switches^Switches^ ("main1.adb")
14315 use ("^-O2^-O2^");
14316 for ^Switches^Switches^ ("main2.adb")
14317 use ("^-g^-g^");
14318 end Builder;
14319 @end group
14320 @end smallexample
14321
14322 @noindent
14323 For the @code{Builder} package, the file names must designate source files
14324 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
14325 file names must designate @file{ALI} or source files for main subprograms.
14326 In each case just the file name without an explicit extension is acceptable.
14327
14328 For each tool used in a program build (@command{gnatmake}, the compiler, the
14329 binder, and the linker), the corresponding package @dfn{contributes} a set of
14330 ^switches^switches^ for each file on which the tool is invoked, based on the
14331 ^switch^switch^-related attributes defined in the package.
14332 In particular, the ^switches^switches^
14333 that each of these packages contributes for a given file @var{f} comprise:
14334
14335 @itemize @bullet
14336 @item
14337 the value of attribute @code{^Switches^Switches^ (@var{f})},
14338 if it is specified in the package for the given file,
14339 @item
14340 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14341 if it is specified in the package.
14342 @end itemize
14343
14344 @noindent
14345 If neither of these attributes is defined in the package, then the package does
14346 not contribute any ^switches^switches^ for the given file.
14347
14348 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14349 two sets, in the following order: those contributed for the file
14350 by the @code{Builder} package;
14351 and the switches passed on the command line.
14352
14353 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14354 the ^switches^switches^ passed to the tool comprise three sets,
14355 in the following order:
14356
14357 @enumerate
14358 @item
14359 the applicable ^switches^switches^ contributed for the file
14360 by the @code{Builder} package in the project file supplied on the command line;
14361
14362 @item
14363 those contributed for the file by the package (in the relevant project file --
14364 see below) corresponding to the tool; and
14365
14366 @item
14367 the applicable switches passed on the command line.
14368 @end enumerate
14369
14370 @noindent
14371 The term @emph{applicable ^switches^switches^} reflects the fact that
14372 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14373 tools, depending on the individual ^switch^switch^.
14374
14375 @command{gnatmake} may invoke the compiler on source files from different
14376 projects. The Project Manager will use the appropriate project file to
14377 determine the @code{Compiler} package for each source file being compiled.
14378 Likewise for the @code{Binder} and @code{Linker} packages.
14379
14380 As an example, consider the following package in a project file:
14381
14382 @smallexample @c projectfile
14383 @group
14384 project Proj1 is
14385 package Compiler is
14386 for ^Default_Switches^Default_Switches^ ("Ada")
14387 use ("^-g^-g^");
14388 for ^Switches^Switches^ ("a.adb")
14389 use ("^-O1^-O1^");
14390 for ^Switches^Switches^ ("b.adb")
14391 use ("^-O2^-O2^",
14392 "^-gnaty^-gnaty^");
14393 end Compiler;
14394 end Proj1;
14395 @end group
14396 @end smallexample
14397
14398 @noindent
14399 If @command{gnatmake} is invoked with this project file, and it needs to
14400 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14401 @file{a.adb} will be compiled with the ^switch^switch^
14402 @option{^-O1^-O1^},
14403 @file{b.adb} with ^switches^switches^
14404 @option{^-O2^-O2^}
14405 and @option{^-gnaty^-gnaty^},
14406 and @file{c.adb} with @option{^-g^-g^}.
14407
14408 The following example illustrates the ordering of the ^switches^switches^
14409 contributed by different packages:
14410
14411 @smallexample @c projectfile
14412 @group
14413 project Proj2 is
14414 package Builder is
14415 for ^Switches^Switches^ ("main.adb")
14416 use ("^-g^-g^",
14417 "^-O1^-)1^",
14418 "^-f^-f^");
14419 end Builder;
14420 @end group
14421
14422 @group
14423 package Compiler is
14424 for ^Switches^Switches^ ("main.adb")
14425 use ("^-O2^-O2^");
14426 end Compiler;
14427 end Proj2;
14428 @end group
14429 @end smallexample
14430
14431 @noindent
14432 If you issue the command:
14433
14434 @smallexample
14435 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14436 @end smallexample
14437
14438 @noindent
14439 then the compiler will be invoked on @file{main.adb} with the following
14440 sequence of ^switches^switches^
14441
14442 @smallexample
14443 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14444 @end smallexample
14445
14446 with the last @option{^-O^-O^}
14447 ^switch^switch^ having precedence over the earlier ones;
14448 several other ^switches^switches^
14449 (such as @option{^-c^-c^}) are added implicitly.
14450
14451 The ^switches^switches^
14452 @option{^-g^-g^}
14453 and @option{^-O1^-O1^} are contributed by package
14454 @code{Builder}, @option{^-O2^-O2^} is contributed
14455 by the package @code{Compiler}
14456 and @option{^-O0^-O0^} comes from the command line.
14457
14458 The @option{^-g^-g^}
14459 ^switch^switch^ will also be passed in the invocation of
14460 @command{Gnatlink.}
14461
14462 A final example illustrates switch contributions from packages in different
14463 project files:
14464
14465 @smallexample @c projectfile
14466 @group
14467 project Proj3 is
14468 for Source_Files use ("pack.ads", "pack.adb");
14469 package Compiler is
14470 for ^Default_Switches^Default_Switches^ ("Ada")
14471 use ("^-gnata^-gnata^");
14472 end Compiler;
14473 end Proj3;
14474 @end group
14475
14476 @group
14477 with "Proj3";
14478 project Proj4 is
14479 for Source_Files use ("foo_main.adb", "bar_main.adb");
14480 package Builder is
14481 for ^Switches^Switches^ ("foo_main.adb")
14482 use ("^-s^-s^",
14483 "^-g^-g^");
14484 end Builder;
14485 end Proj4;
14486 @end group
14487
14488 @group
14489 -- Ada source file:
14490 with Pack;
14491 procedure Foo_Main is
14492 @dots{}
14493 end Foo_Main;
14494 @end group
14495 @end smallexample
14496
14497 If the command is
14498 @smallexample
14499 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14500 @end smallexample
14501
14502 @noindent
14503 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14504 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14505 @option{^-gnato^-gnato^} (passed on the command line).
14506 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14507 are @option{^-g^-g^} from @code{Proj4.Builder},
14508 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14509 and @option{^-gnato^-gnato^} from the command line.
14510
14511 @noindent
14512 When using @command{gnatmake} with project files, some ^switches^switches^ or
14513 arguments may be expressed as relative paths. As the working directory where
14514 compilation occurs may change, these relative paths are converted to absolute
14515 paths. For the ^switches^switches^ found in a project file, the relative paths
14516 are relative to the project file directory, for the switches on the command
14517 line, they are relative to the directory where @command{gnatmake} is invoked.
14518 The ^switches^switches^ for which this occurs are:
14519 ^-I^-I^,
14520 ^-A^-A^,
14521 ^-L^-L^,
14522 ^-aO^-aO^,
14523 ^-aL^-aL^,
14524 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14525 ^switch^switch^
14526 ^-o^-o^, object files specified in package @code{Linker} or after
14527 -largs on the command line). The exception to this rule is the ^switch^switch^
14528 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14529
14530 @node Specifying Configuration Pragmas
14531 @subsubsection Specifying Configuration Pragmas
14532
14533 When using @command{gnatmake} with project files, if there exists a file
14534 @file{gnat.adc} that contains configuration pragmas, this file will be
14535 ignored.
14536
14537 Configuration pragmas can be defined by means of the following attributes in
14538 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14539 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14540
14541 Both these attributes are single string attributes. Their values is the path
14542 name of a file containing configuration pragmas. If a path name is relative,
14543 then it is relative to the project directory of the project file where the
14544 attribute is defined.
14545
14546 When compiling a source, the configuration pragmas used are, in order,
14547 those listed in the file designated by attribute
14548 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14549 project file, if it is specified, and those listed in the file designated by
14550 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14551 the project file of the source, if it exists.
14552
14553 @node Project Files and Main Subprograms
14554 @subsubsection Project Files and Main Subprograms
14555
14556 @noindent
14557 When using a project file, you can invoke @command{gnatmake}
14558 with one or several main subprograms, by specifying their source files on the
14559 command line.
14560
14561 @smallexample
14562 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14563 @end smallexample
14564
14565 @noindent
14566 Each of these needs to be a source file of the same project, except
14567 when the switch ^-u^/UNIQUE^ is used.
14568
14569 @noindent
14570 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14571 same project, one of the project in the tree rooted at the project specified
14572 on the command line. The package @code{Builder} of this common project, the
14573 "main project" is the one that is considered by @command{gnatmake}.
14574
14575 @noindent
14576 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14577 imported directly or indirectly by the project specified on the command line.
14578 Note that if such a source file is not part of the project specified on the
14579 command line, the ^switches^switches^ found in package @code{Builder} of the
14580 project specified on the command line, if any, that are transmitted
14581 to the compiler will still be used, not those found in the project file of
14582 the source file.
14583
14584 @noindent
14585 When using a project file, you can also invoke @command{gnatmake} without
14586 explicitly specifying any main, and the effect depends on whether you have
14587 defined the @code{Main} attribute. This attribute has a string list value,
14588 where each element in the list is the name of a source file (the file
14589 extension is optional) that contains a unit that can be a main subprogram.
14590
14591 If the @code{Main} attribute is defined in a project file as a non-empty
14592 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14593 line, then invoking @command{gnatmake} with this project file but without any
14594 main on the command line is equivalent to invoking @command{gnatmake} with all
14595 the file names in the @code{Main} attribute on the command line.
14596
14597 Example:
14598 @smallexample @c projectfile
14599 @group
14600 project Prj is
14601 for Main use ("main1", "main2", "main3");
14602 end Prj;
14603 @end group
14604 @end smallexample
14605
14606 @noindent
14607 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14608 is equivalent to
14609 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14610
14611 When the project attribute @code{Main} is not specified, or is specified
14612 as an empty string list, or when the switch @option{-u} is used on the command
14613 line, then invoking @command{gnatmake} with no main on the command line will
14614 result in all immediate sources of the project file being checked, and
14615 potentially recompiled. Depending on the presence of the switch @option{-u},
14616 sources from other project files on which the immediate sources of the main
14617 project file depend are also checked and potentially recompiled. In other
14618 words, the @option{-u} switch is applied to all of the immediate sources of the
14619 main project file.
14620
14621 When no main is specified on the command line and attribute @code{Main} exists
14622 and includes several mains, or when several mains are specified on the
14623 command line, the default ^switches^switches^ in package @code{Builder} will
14624 be used for all mains, even if there are specific ^switches^switches^
14625 specified for one or several mains.
14626
14627 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14628 the specific ^switches^switches^ for each main, if they are specified.
14629
14630 @node Library Project Files
14631 @subsubsection Library Project Files
14632
14633 @noindent
14634 When @command{gnatmake} is invoked with a main project file that is a library
14635 project file, it is not allowed to specify one or more mains on the command
14636 line.
14637
14638 @noindent
14639 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14640 ^-l^/ACTION=LINK^ have special meanings.
14641
14642 @itemize @bullet
14643 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14644 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14645 library.
14646
14647 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14648 to @command{gnatmake} that the binder generated file should be compiled
14649 (in the case of a stand-alone library) and that the library should be built.
14650
14651 @end itemize
14652
14653 @node The GNAT Driver and Project Files
14654 @subsection The GNAT Driver and Project Files
14655
14656 @noindent
14657 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14658 can benefit from project files:
14659 @command{^gnatbind^gnatbind^},
14660 @command{^gnatcheck^gnatcheck^}),
14661 @command{^gnatclean^gnatclean^}),
14662 @command{^gnatelim^gnatelim^},
14663 @command{^gnatfind^gnatfind^},
14664 @command{^gnatlink^gnatlink^},
14665 @command{^gnatls^gnatls^},
14666 @command{^gnatmetric^gnatmetric^},
14667 @command{^gnatpp^gnatpp^},
14668 @command{^gnatstub^gnatstub^},
14669 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14670 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14671 They must be invoked through the @command{gnat} driver.
14672
14673 The @command{gnat} driver is a wrapper that accepts a number of commands and
14674 calls the corresponding tool. It was designed initially for VMS platforms (to
14675 convert VMS qualifiers to Unix-style switches), but it is now available on all
14676 GNAT platforms.
14677
14678 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14679 (case insensitive):
14680
14681 @itemize @bullet
14682 @item
14683 BIND to invoke @command{^gnatbind^gnatbind^}
14684 @item
14685 CHOP to invoke @command{^gnatchop^gnatchop^}
14686 @item
14687 CLEAN to invoke @command{^gnatclean^gnatclean^}
14688 @item
14689 COMP or COMPILE to invoke the compiler
14690 @item
14691 ELIM to invoke @command{^gnatelim^gnatelim^}
14692 @item
14693 FIND to invoke @command{^gnatfind^gnatfind^}
14694 @item
14695 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14696 @item
14697 LINK to invoke @command{^gnatlink^gnatlink^}
14698 @item
14699 LS or LIST to invoke @command{^gnatls^gnatls^}
14700 @item
14701 MAKE to invoke @command{^gnatmake^gnatmake^}
14702 @item
14703 NAME to invoke @command{^gnatname^gnatname^}
14704 @item
14705 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14706 @item
14707 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14708 @item
14709 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14710 @item
14711 STUB to invoke @command{^gnatstub^gnatstub^}
14712 @item
14713 XREF to invoke @command{^gnatxref^gnatxref^}
14714 @end itemize
14715
14716 @noindent
14717 (note that the compiler is invoked using the command
14718 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14719
14720 @noindent
14721 On non-VMS platforms, between @command{gnat} and the command, two
14722 special switches may be used:
14723
14724 @itemize @bullet
14725 @item
14726 @command{-v} to display the invocation of the tool.
14727 @item
14728 @command{-dn} to prevent the @command{gnat} driver from removing
14729 the temporary files it has created. These temporary files are
14730 configuration files and temporary file list files.
14731 @end itemize
14732
14733 @noindent
14734 The command may be followed by switches and arguments for the invoked
14735 tool.
14736
14737 @smallexample
14738 gnat bind -C main.ali
14739 gnat ls -a main
14740 gnat chop foo.txt
14741 @end smallexample
14742
14743 @noindent
14744 Switches may also be put in text files, one switch per line, and the text
14745 files may be specified with their path name preceded by '@@'.
14746
14747 @smallexample
14748 gnat bind @@args.txt main.ali
14749 @end smallexample
14750
14751 @noindent
14752 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14753 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14754 (@option{^-P^/PROJECT_FILE^},
14755 @option{^-X^/EXTERNAL_REFERENCE^} and
14756 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14757 the switches of the invoking tool.
14758
14759 @noindent
14760 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14761 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14762 the immediate sources of the specified project file.
14763
14764 @noindent
14765 When GNAT METRIC is used with a project file, but with no source
14766 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14767 with all the immediate sources of the specified project file and with
14768 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14769 of the project.
14770
14771 @noindent
14772 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14773 a project file, no source is specified on the command line and
14774 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14775 the underlying tool (^gnatpp^gnatpp^ or
14776 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14777 not only for the immediate sources of the main project.
14778 @ifclear vms
14779 (-U stands for Universal or Union of the project files of the project tree)
14780 @end ifclear
14781
14782 @noindent
14783 For each of the following commands, there is optionally a corresponding
14784 package in the main project.
14785
14786 @itemize @bullet
14787 @item
14788 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14789
14790 @item
14791 package @code{Check} for command CHECK (invoking
14792 @code{^gnatcheck^gnatcheck^})
14793
14794 @item
14795 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14796
14797 @item
14798 package @code{Cross_Reference} for command XREF (invoking
14799 @code{^gnatxref^gnatxref^})
14800
14801 @item
14802 package @code{Eliminate} for command ELIM (invoking
14803 @code{^gnatelim^gnatelim^})
14804
14805 @item
14806 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14807
14808 @item
14809 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14810
14811 @item
14812 package @code{Gnatstub} for command STUB
14813 (invoking @code{^gnatstub^gnatstub^})
14814
14815 @item
14816 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14817
14818 @item
14819 package @code{Metrics} for command METRIC
14820 (invoking @code{^gnatmetric^gnatmetric^})
14821
14822 @item
14823 package @code{Pretty_Printer} for command PP or PRETTY
14824 (invoking @code{^gnatpp^gnatpp^})
14825
14826 @end itemize
14827
14828 @noindent
14829 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14830 a simple variable with a string list value. It contains ^switches^switches^
14831 for the invocation of @code{^gnatls^gnatls^}.
14832
14833 @smallexample @c projectfile
14834 @group
14835 project Proj1 is
14836 package gnatls is
14837 for ^Switches^Switches^
14838 use ("^-a^-a^",
14839 "^-v^-v^");
14840 end gnatls;
14841 end Proj1;
14842 @end group
14843 @end smallexample
14844
14845 @noindent
14846 All other packages have two attribute @code{^Switches^Switches^} and
14847 @code{^Default_Switches^Default_Switches^}.
14848
14849 @noindent
14850 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14851 source file name, that has a string list value: the ^switches^switches^ to be
14852 used when the tool corresponding to the package is invoked for the specific
14853 source file.
14854
14855 @noindent
14856 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14857 indexed by the programming language that has a string list value.
14858 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14859 ^switches^switches^ for the invocation of the tool corresponding
14860 to the package, except if a specific @code{^Switches^Switches^} attribute
14861 is specified for the source file.
14862
14863 @smallexample @c projectfile
14864 @group
14865 project Proj is
14866
14867 for Source_Dirs use ("./**");
14868
14869 package gnatls is
14870 for ^Switches^Switches^ use
14871 ("^-a^-a^",
14872 "^-v^-v^");
14873 end gnatls;
14874 @end group
14875 @group
14876
14877 package Compiler is
14878 for ^Default_Switches^Default_Switches^ ("Ada")
14879 use ("^-gnatv^-gnatv^",
14880 "^-gnatwa^-gnatwa^");
14881 end Binder;
14882 @end group
14883 @group
14884
14885 package Binder is
14886 for ^Default_Switches^Default_Switches^ ("Ada")
14887 use ("^-C^-C^",
14888 "^-e^-e^");
14889 end Binder;
14890 @end group
14891 @group
14892
14893 package Linker is
14894 for ^Default_Switches^Default_Switches^ ("Ada")
14895 use ("^-C^-C^");
14896 for ^Switches^Switches^ ("main.adb")
14897 use ("^-C^-C^",
14898 "^-v^-v^",
14899 "^-v^-v^");
14900 end Linker;
14901 @end group
14902 @group
14903
14904 package Finder is
14905 for ^Default_Switches^Default_Switches^ ("Ada")
14906 use ("^-a^-a^",
14907 "^-f^-f^");
14908 end Finder;
14909 @end group
14910 @group
14911
14912 package Cross_Reference is
14913 for ^Default_Switches^Default_Switches^ ("Ada")
14914 use ("^-a^-a^",
14915 "^-f^-f^",
14916 "^-d^-d^",
14917 "^-u^-u^");
14918 end Cross_Reference;
14919 end Proj;
14920 @end group
14921 @end smallexample
14922
14923 @noindent
14924 With the above project file, commands such as
14925
14926 @smallexample
14927 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14928 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14929 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14930 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14931 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14932 @end smallexample
14933
14934 @noindent
14935 will set up the environment properly and invoke the tool with the switches
14936 found in the package corresponding to the tool:
14937 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14938 except @code{^Switches^Switches^ ("main.adb")}
14939 for @code{^gnatlink^gnatlink^}.
14940 It is also possible to invoke some of the tools,
14941 @code{^gnatcheck^gnatcheck^}),
14942 @code{^gnatmetric^gnatmetric^}),
14943 and @code{^gnatpp^gnatpp^})
14944 on a set of project units thanks to the combination of the switches
14945 @option{-P}, @option{-U} and possibly the main unit when one is interested
14946 in its closure. For instance,
14947 @smallexample
14948 gnat metric -Pproj
14949 @end smallexample
14950 will compute the metrics for all the immediate units of project
14951 @code{proj}.
14952 @smallexample
14953 gnat metric -Pproj -U
14954 @end smallexample
14955 will compute the metrics for all the units of the closure of projects
14956 rooted at @code{proj}.
14957 @smallexample
14958 gnat metric -Pproj -U main_unit
14959 @end smallexample
14960 will compute the metrics for the closure of units rooted at
14961 @code{main_unit}. This last possibility relies implicitly
14962 on @command{gnatbind}'s option @option{-R}.
14963
14964 @c **********************
14965 @node An Extended Example
14966 @section An Extended Example
14967
14968 @noindent
14969 Suppose that we have two programs, @var{prog1} and @var{prog2},
14970 whose sources are in corresponding directories. We would like
14971 to build them with a single @command{gnatmake} command, and we want to place
14972 their object files into @file{build} subdirectories of the source directories.
14973 Furthermore, we want to have to have two separate subdirectories
14974 in @file{build} -- @file{release} and @file{debug} -- which will contain
14975 the object files compiled with different set of compilation flags.
14976
14977 In other words, we have the following structure:
14978
14979 @smallexample
14980 @group
14981 main
14982 |- prog1
14983 | |- build
14984 | | debug
14985 | | release
14986 |- prog2
14987 |- build
14988 | debug
14989 | release
14990 @end group
14991 @end smallexample
14992
14993 @noindent
14994 Here are the project files that we must place in a directory @file{main}
14995 to maintain this structure:
14996
14997 @enumerate
14998
14999 @item We create a @code{Common} project with a package @code{Compiler} that
15000 specifies the compilation ^switches^switches^:
15001
15002 @smallexample
15003 File "common.gpr":
15004 @group
15005 @b{project} Common @b{is}
15006
15007 @b{for} Source_Dirs @b{use} (); -- No source files
15008 @end group
15009
15010 @group
15011 @b{type} Build_Type @b{is} ("release", "debug");
15012 Build : Build_Type := External ("BUILD", "debug");
15013 @end group
15014 @group
15015 @b{package} Compiler @b{is}
15016 @b{case} Build @b{is}
15017 @b{when} "release" =>
15018 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15019 @b{use} ("^-O2^-O2^");
15020 @b{when} "debug" =>
15021 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15022 @b{use} ("^-g^-g^");
15023 @b{end case};
15024 @b{end} Compiler;
15025
15026 @b{end} Common;
15027 @end group
15028 @end smallexample
15029
15030 @item We create separate projects for the two programs:
15031
15032 @smallexample
15033 @group
15034 File "prog1.gpr":
15035
15036 @b{with} "common";
15037 @b{project} Prog1 @b{is}
15038
15039 @b{for} Source_Dirs @b{use} ("prog1");
15040 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
15041
15042 @b{package} Compiler @b{renames} Common.Compiler;
15043
15044 @b{end} Prog1;
15045 @end group
15046 @end smallexample
15047
15048 @smallexample
15049 @group
15050 File "prog2.gpr":
15051
15052 @b{with} "common";
15053 @b{project} Prog2 @b{is}
15054
15055 @b{for} Source_Dirs @b{use} ("prog2");
15056 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
15057
15058 @b{package} Compiler @b{renames} Common.Compiler;
15059
15060 @end group
15061 @b{end} Prog2;
15062 @end smallexample
15063
15064 @item We create a wrapping project @code{Main}:
15065
15066 @smallexample
15067 @group
15068 File "main.gpr":
15069
15070 @b{with} "common";
15071 @b{with} "prog1";
15072 @b{with} "prog2";
15073 @b{project} Main @b{is}
15074
15075 @b{package} Compiler @b{renames} Common.Compiler;
15076
15077 @b{end} Main;
15078 @end group
15079 @end smallexample
15080
15081 @item Finally we need to create a dummy procedure that @code{with}s (either
15082 explicitly or implicitly) all the sources of our two programs.
15083
15084 @end enumerate
15085
15086 @noindent
15087 Now we can build the programs using the command
15088
15089 @smallexample
15090 gnatmake ^-P^/PROJECT_FILE=^main dummy
15091 @end smallexample
15092
15093 @noindent
15094 for the Debug mode, or
15095
15096 @ifclear vms
15097 @smallexample
15098 gnatmake -Pmain -XBUILD=release
15099 @end smallexample
15100 @end ifclear
15101
15102 @ifset vms
15103 @smallexample
15104 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15105 @end smallexample
15106 @end ifset
15107
15108 @noindent
15109 for the Release mode.
15110
15111 @c ********************************
15112 @c * Project File Complete Syntax *
15113 @c ********************************
15114
15115 @node Project File Complete Syntax
15116 @section Project File Complete Syntax
15117
15118 @smallexample
15119 project ::=
15120 context_clause project_declaration
15121
15122 context_clause ::=
15123 @{with_clause@}
15124
15125 with_clause ::=
15126 @b{with} path_name @{ , path_name @} ;
15127
15128 path_name ::=
15129 string_literal
15130
15131 project_declaration ::=
15132 simple_project_declaration | project_extension
15133
15134 simple_project_declaration ::=
15135 @b{project} <project_>simple_name @b{is}
15136 @{declarative_item@}
15137 @b{end} <project_>simple_name;
15138
15139 project_extension ::=
15140 @b{project} <project_>simple_name @b{extends} path_name @b{is}
15141 @{declarative_item@}
15142 @b{end} <project_>simple_name;
15143
15144 declarative_item ::=
15145 package_declaration |
15146 typed_string_declaration |
15147 other_declarative_item
15148
15149 package_declaration ::=
15150 package_spec | package_renaming
15151
15152 package_spec ::=
15153 @b{package} package_identifier @b{is}
15154 @{simple_declarative_item@}
15155 @b{end} package_identifier ;
15156
15157 package_identifier ::=
15158 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15159 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
15160 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
15161
15162 package_renaming ::==
15163 @b{package} package_identifier @b{renames}
15164 <project_>simple_name.package_identifier ;
15165
15166 typed_string_declaration ::=
15167 @b{type} <typed_string_>_simple_name @b{is}
15168 ( string_literal @{, string_literal@} );
15169
15170 other_declarative_item ::=
15171 attribute_declaration |
15172 typed_variable_declaration |
15173 variable_declaration |
15174 case_construction
15175
15176 attribute_declaration ::=
15177 full_associative_array_declaration |
15178 @b{for} attribute_designator @b{use} expression ;
15179
15180 full_associative_array_declaration ::=
15181 @b{for} <associative_array_attribute_>simple_name @b{use}
15182 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15183
15184 attribute_designator ::=
15185 <simple_attribute_>simple_name |
15186 <associative_array_attribute_>simple_name ( string_literal )
15187
15188 typed_variable_declaration ::=
15189 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
15190
15191 variable_declaration ::=
15192 <variable_>simple_name := expression;
15193
15194 expression ::=
15195 term @{& term@}
15196
15197 term ::=
15198 literal_string |
15199 string_list |
15200 <variable_>name |
15201 external_value |
15202 attribute_reference
15203
15204 string_literal ::=
15205 (same as Ada)
15206
15207 string_list ::=
15208 ( <string_>expression @{ , <string_>expression @} )
15209
15210 external_value ::=
15211 @b{external} ( string_literal [, string_literal] )
15212
15213 attribute_reference ::=
15214 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15215
15216 attribute_prefix ::=
15217 @b{project} |
15218 <project_>simple_name | package_identifier |
15219 <project_>simple_name . package_identifier
15220
15221 case_construction ::=
15222 @b{case} <typed_variable_>name @b{is}
15223 @{case_item@}
15224 @b{end case} ;
15225
15226 case_item ::=
15227 @b{when} discrete_choice_list =>
15228 @{case_construction | attribute_declaration@}
15229
15230 discrete_choice_list ::=
15231 string_literal @{| string_literal@} |
15232 @b{others}
15233
15234 name ::=
15235 simple_name @{. simple_name@}
15236
15237 simple_name ::=
15238 identifier (same as Ada)
15239
15240 @end smallexample
15241
15242 @node The Cross-Referencing Tools gnatxref and gnatfind
15243 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15244 @findex gnatxref
15245 @findex gnatfind
15246
15247 @noindent
15248 The compiler generates cross-referencing information (unless
15249 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15250 This information indicates where in the source each entity is declared and
15251 referenced. Note that entities in package Standard are not included, but
15252 entities in all other predefined units are included in the output.
15253
15254 Before using any of these two tools, you need to compile successfully your
15255 application, so that GNAT gets a chance to generate the cross-referencing
15256 information.
15257
15258 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15259 information to provide the user with the capability to easily locate the
15260 declaration and references to an entity. These tools are quite similar,
15261 the difference being that @code{gnatfind} is intended for locating
15262 definitions and/or references to a specified entity or entities, whereas
15263 @code{gnatxref} is oriented to generating a full report of all
15264 cross-references.
15265
15266 To use these tools, you must not compile your application using the
15267 @option{-gnatx} switch on the @command{gnatmake} command line
15268 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15269 information will not be generated.
15270
15271 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15272 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15273
15274 @menu
15275 * gnatxref Switches::
15276 * gnatfind Switches::
15277 * Project Files for gnatxref and gnatfind::
15278 * Regular Expressions in gnatfind and gnatxref::
15279 * Examples of gnatxref Usage::
15280 * Examples of gnatfind Usage::
15281 @end menu
15282
15283 @node gnatxref Switches
15284 @section @code{gnatxref} Switches
15285
15286 @noindent
15287 The command invocation for @code{gnatxref} is:
15288 @smallexample
15289 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15290 @end smallexample
15291
15292 @noindent
15293 where
15294
15295 @table @var
15296 @item sourcefile1
15297 @itemx sourcefile2
15298 identifies the source files for which a report is to be generated. The
15299 ``with''ed units will be processed too. You must provide at least one file.
15300
15301 These file names are considered to be regular expressions, so for instance
15302 specifying @file{source*.adb} is the same as giving every file in the current
15303 directory whose name starts with @file{source} and whose extension is
15304 @file{adb}.
15305
15306 You shouldn't specify any directory name, just base names. @command{gnatxref}
15307 and @command{gnatfind} will be able to locate these files by themselves using
15308 the source path. If you specify directories, no result is produced.
15309
15310 @end table
15311
15312 @noindent
15313 The switches can be:
15314 @table @option
15315 @c !sort!
15316 @item --version
15317 @cindex @option{--version} @command{gnatxref}
15318 Display Copyright and version, then exit disregarding all other options.
15319
15320 @item --help
15321 @cindex @option{--help} @command{gnatxref}
15322 If @option{--version} was not used, display usage, then exit disregarding
15323 all other options.
15324
15325 @item ^-a^/ALL_FILES^
15326 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15327 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15328 the read-only files found in the library search path. Otherwise, these files
15329 will be ignored. This option can be used to protect Gnat sources or your own
15330 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15331 much faster, and their output much smaller. Read-only here refers to access
15332 or permissions status in the file system for the current user.
15333
15334 @item -aIDIR
15335 @cindex @option{-aIDIR} (@command{gnatxref})
15336 When looking for source files also look in directory DIR. The order in which
15337 source file search is undertaken is the same as for @command{gnatmake}.
15338
15339 @item -aODIR
15340 @cindex @option{-aODIR} (@command{gnatxref})
15341 When searching for library and object files, look in directory
15342 DIR. The order in which library files are searched is the same as for
15343 @command{gnatmake}.
15344
15345 @item -nostdinc
15346 @cindex @option{-nostdinc} (@command{gnatxref})
15347 Do not look for sources in the system default directory.
15348
15349 @item -nostdlib
15350 @cindex @option{-nostdlib} (@command{gnatxref})
15351 Do not look for library files in the system default directory.
15352
15353 @item --RTS=@var{rts-path}
15354 @cindex @option{--RTS} (@command{gnatxref})
15355 Specifies the default location of the runtime library. Same meaning as the
15356 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15357
15358 @item ^-d^/DERIVED_TYPES^
15359 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15360 If this switch is set @code{gnatxref} will output the parent type
15361 reference for each matching derived types.
15362
15363 @item ^-f^/FULL_PATHNAME^
15364 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15365 If this switch is set, the output file names will be preceded by their
15366 directory (if the file was found in the search path). If this switch is
15367 not set, the directory will not be printed.
15368
15369 @item ^-g^/IGNORE_LOCALS^
15370 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15371 If this switch is set, information is output only for library-level
15372 entities, ignoring local entities. The use of this switch may accelerate
15373 @code{gnatfind} and @code{gnatxref}.
15374
15375 @item -IDIR
15376 @cindex @option{-IDIR} (@command{gnatxref})
15377 Equivalent to @samp{-aODIR -aIDIR}.
15378
15379 @item -pFILE
15380 @cindex @option{-pFILE} (@command{gnatxref})
15381 Specify a project file to use @xref{Project Files}.
15382 If you need to use the @file{.gpr}
15383 project files, you should use gnatxref through the GNAT driver
15384 (@command{gnat xref -Pproject}).
15385
15386 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15387 project file in the current directory.
15388
15389 If a project file is either specified or found by the tools, then the content
15390 of the source directory and object directory lines are added as if they
15391 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15392 and @samp{^-aO^OBJECT_SEARCH^}.
15393 @item ^-u^/UNUSED^
15394 Output only unused symbols. This may be really useful if you give your
15395 main compilation unit on the command line, as @code{gnatxref} will then
15396 display every unused entity and 'with'ed package.
15397
15398 @ifclear vms
15399 @item -v
15400 Instead of producing the default output, @code{gnatxref} will generate a
15401 @file{tags} file that can be used by vi. For examples how to use this
15402 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15403 to the standard output, thus you will have to redirect it to a file.
15404 @end ifclear
15405
15406 @end table
15407
15408 @noindent
15409 All these switches may be in any order on the command line, and may even
15410 appear after the file names. They need not be separated by spaces, thus
15411 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15412 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15413
15414 @node gnatfind Switches
15415 @section @code{gnatfind} Switches
15416
15417 @noindent
15418 The command line for @code{gnatfind} is:
15419
15420 @smallexample
15421 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15422 @r{[}@var{file1} @var{file2} @dots{}]
15423 @end smallexample
15424
15425 @noindent
15426 where
15427
15428 @table @var
15429 @item pattern
15430 An entity will be output only if it matches the regular expression found
15431 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15432
15433 Omitting the pattern is equivalent to specifying @samp{*}, which
15434 will match any entity. Note that if you do not provide a pattern, you
15435 have to provide both a sourcefile and a line.
15436
15437 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15438 for matching purposes. At the current time there is no support for
15439 8-bit codes other than Latin-1, or for wide characters in identifiers.
15440
15441 @item sourcefile
15442 @code{gnatfind} will look for references, bodies or declarations
15443 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15444 and column @var{column}. See @ref{Examples of gnatfind Usage}
15445 for syntax examples.
15446
15447 @item line
15448 is a decimal integer identifying the line number containing
15449 the reference to the entity (or entities) to be located.
15450
15451 @item column
15452 is a decimal integer identifying the exact location on the
15453 line of the first character of the identifier for the
15454 entity reference. Columns are numbered from 1.
15455
15456 @item file1 file2 @dots{}
15457 The search will be restricted to these source files. If none are given, then
15458 the search will be done for every library file in the search path.
15459 These file must appear only after the pattern or sourcefile.
15460
15461 These file names are considered to be regular expressions, so for instance
15462 specifying @file{source*.adb} is the same as giving every file in the current
15463 directory whose name starts with @file{source} and whose extension is
15464 @file{adb}.
15465
15466 The location of the spec of the entity will always be displayed, even if it
15467 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
15468 occurrences of the entity in the separate units of the ones given on the
15469 command line will also be displayed.
15470
15471 Note that if you specify at least one file in this part, @code{gnatfind} may
15472 sometimes not be able to find the body of the subprograms.
15473
15474 @end table
15475
15476 @noindent
15477 At least one of 'sourcefile' or 'pattern' has to be present on
15478 the command line.
15479
15480 The following switches are available:
15481 @table @option
15482 @c !sort!
15483
15484 @cindex @option{--version} @command{gnatfind}
15485 Display Copyright and version, then exit disregarding all other options.
15486
15487 @item --help
15488 @cindex @option{--help} @command{gnatfind}
15489 If @option{--version} was not used, display usage, then exit disregarding
15490 all other options.
15491
15492 @item ^-a^/ALL_FILES^
15493 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15494 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15495 the read-only files found in the library search path. Otherwise, these files
15496 will be ignored. This option can be used to protect Gnat sources or your own
15497 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15498 much faster, and their output much smaller. Read-only here refers to access
15499 or permission status in the file system for the current user.
15500
15501 @item -aIDIR
15502 @cindex @option{-aIDIR} (@command{gnatfind})
15503 When looking for source files also look in directory DIR. The order in which
15504 source file search is undertaken is the same as for @command{gnatmake}.
15505
15506 @item -aODIR
15507 @cindex @option{-aODIR} (@command{gnatfind})
15508 When searching for library and object files, look in directory
15509 DIR. The order in which library files are searched is the same as for
15510 @command{gnatmake}.
15511
15512 @item -nostdinc
15513 @cindex @option{-nostdinc} (@command{gnatfind})
15514 Do not look for sources in the system default directory.
15515
15516 @item -nostdlib
15517 @cindex @option{-nostdlib} (@command{gnatfind})
15518 Do not look for library files in the system default directory.
15519
15520 @item --RTS=@var{rts-path}
15521 @cindex @option{--RTS} (@command{gnatfind})
15522 Specifies the default location of the runtime library. Same meaning as the
15523 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15524
15525 @item ^-d^/DERIVED_TYPE_INFORMATION^
15526 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15527 If this switch is set, then @code{gnatfind} will output the parent type
15528 reference for each matching derived types.
15529
15530 @item ^-e^/EXPRESSIONS^
15531 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15532 By default, @code{gnatfind} accept the simple regular expression set for
15533 @samp{pattern}. If this switch is set, then the pattern will be
15534 considered as full Unix-style regular expression.
15535
15536 @item ^-f^/FULL_PATHNAME^
15537 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15538 If this switch is set, the output file names will be preceded by their
15539 directory (if the file was found in the search path). If this switch is
15540 not set, the directory will not be printed.
15541
15542 @item ^-g^/IGNORE_LOCALS^
15543 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15544 If this switch is set, information is output only for library-level
15545 entities, ignoring local entities. The use of this switch may accelerate
15546 @code{gnatfind} and @code{gnatxref}.
15547
15548 @item -IDIR
15549 @cindex @option{-IDIR} (@command{gnatfind})
15550 Equivalent to @samp{-aODIR -aIDIR}.
15551
15552 @item -pFILE
15553 @cindex @option{-pFILE} (@command{gnatfind})
15554 Specify a project file (@pxref{Project Files}) to use.
15555 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15556 project file in the current directory.
15557
15558 If a project file is either specified or found by the tools, then the content
15559 of the source directory and object directory lines are added as if they
15560 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15561 @samp{^-aO^/OBJECT_SEARCH^}.
15562
15563 @item ^-r^/REFERENCES^
15564 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15565 By default, @code{gnatfind} will output only the information about the
15566 declaration, body or type completion of the entities. If this switch is
15567 set, the @code{gnatfind} will locate every reference to the entities in
15568 the files specified on the command line (or in every file in the search
15569 path if no file is given on the command line).
15570
15571 @item ^-s^/PRINT_LINES^
15572 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15573 If this switch is set, then @code{gnatfind} will output the content
15574 of the Ada source file lines were the entity was found.
15575
15576 @item ^-t^/TYPE_HIERARCHY^
15577 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15578 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15579 the specified type. It act like -d option but recursively from parent
15580 type to parent type. When this switch is set it is not possible to
15581 specify more than one file.
15582
15583 @end table
15584
15585 @noindent
15586 All these switches may be in any order on the command line, and may even
15587 appear after the file names. They need not be separated by spaces, thus
15588 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15589 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15590
15591 As stated previously, gnatfind will search in every directory in the
15592 search path. You can force it to look only in the current directory if
15593 you specify @code{*} at the end of the command line.
15594
15595 @node Project Files for gnatxref and gnatfind
15596 @section Project Files for @command{gnatxref} and @command{gnatfind}
15597
15598 @noindent
15599 Project files allow a programmer to specify how to compile its
15600 application, where to find sources, etc. These files are used
15601 @ifclear vms
15602 primarily by GPS, but they can also be used
15603 @end ifclear
15604 by the two tools
15605 @code{gnatxref} and @code{gnatfind}.
15606
15607 A project file name must end with @file{.gpr}. If a single one is
15608 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15609 extract the information from it. If multiple project files are found, none of
15610 them is read, and you have to use the @samp{-p} switch to specify the one
15611 you want to use.
15612
15613 The following lines can be included, even though most of them have default
15614 values which can be used in most cases.
15615 The lines can be entered in any order in the file.
15616 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15617 each line. If you have multiple instances, only the last one is taken into
15618 account.
15619
15620 @table @code
15621 @item src_dir=DIR
15622 [default: @code{"^./^[]^"}]
15623 specifies a directory where to look for source files. Multiple @code{src_dir}
15624 lines can be specified and they will be searched in the order they
15625 are specified.
15626
15627 @item obj_dir=DIR
15628 [default: @code{"^./^[]^"}]
15629 specifies a directory where to look for object and library files. Multiple
15630 @code{obj_dir} lines can be specified, and they will be searched in the order
15631 they are specified
15632
15633 @item comp_opt=SWITCHES
15634 [default: @code{""}]
15635 creates a variable which can be referred to subsequently by using
15636 the @code{$@{comp_opt@}} notation. This is intended to store the default
15637 switches given to @command{gnatmake} and @command{gcc}.
15638
15639 @item bind_opt=SWITCHES
15640 [default: @code{""}]
15641 creates a variable which can be referred to subsequently by using
15642 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15643 switches given to @command{gnatbind}.
15644
15645 @item link_opt=SWITCHES
15646 [default: @code{""}]
15647 creates a variable which can be referred to subsequently by using
15648 the @samp{$@{link_opt@}} notation. This is intended to store the default
15649 switches given to @command{gnatlink}.
15650
15651 @item main=EXECUTABLE
15652 [default: @code{""}]
15653 specifies the name of the executable for the application. This variable can
15654 be referred to in the following lines by using the @samp{$@{main@}} notation.
15655
15656 @ifset vms
15657 @item comp_cmd=COMMAND
15658 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15659 @end ifset
15660 @ifclear vms
15661 @item comp_cmd=COMMAND
15662 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15663 @end ifclear
15664 specifies the command used to compile a single file in the application.
15665
15666 @ifset vms
15667 @item make_cmd=COMMAND
15668 [default: @code{"GNAT MAKE $@{main@}
15669 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15670 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15671 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15672 @end ifset
15673 @ifclear vms
15674 @item make_cmd=COMMAND
15675 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15676 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15677 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15678 @end ifclear
15679 specifies the command used to recompile the whole application.
15680
15681 @item run_cmd=COMMAND
15682 [default: @code{"$@{main@}"}]
15683 specifies the command used to run the application.
15684
15685 @item debug_cmd=COMMAND
15686 [default: @code{"gdb $@{main@}"}]
15687 specifies the command used to debug the application
15688
15689 @end table
15690
15691 @noindent
15692 @command{gnatxref} and @command{gnatfind} only take into account the
15693 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15694
15695 @node Regular Expressions in gnatfind and gnatxref
15696 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15697
15698 @noindent
15699 As specified in the section about @command{gnatfind}, the pattern can be a
15700 regular expression. Actually, there are to set of regular expressions
15701 which are recognized by the program:
15702
15703 @table @code
15704 @item globbing patterns
15705 These are the most usual regular expression. They are the same that you
15706 generally used in a Unix shell command line, or in a DOS session.
15707
15708 Here is a more formal grammar:
15709 @smallexample
15710 @group
15711 @iftex
15712 @leftskip=.5cm
15713 @end iftex
15714 regexp ::= term
15715 term ::= elmt -- matches elmt
15716 term ::= elmt elmt -- concatenation (elmt then elmt)
15717 term ::= * -- any string of 0 or more characters
15718 term ::= ? -- matches any character
15719 term ::= [char @{char@}] -- matches any character listed
15720 term ::= [char - char] -- matches any character in range
15721 @end group
15722 @end smallexample
15723
15724 @item full regular expression
15725 The second set of regular expressions is much more powerful. This is the
15726 type of regular expressions recognized by utilities such a @file{grep}.
15727
15728 The following is the form of a regular expression, expressed in Ada
15729 reference manual style BNF is as follows
15730
15731 @smallexample
15732 @iftex
15733 @leftskip=.5cm
15734 @end iftex
15735 @group
15736 regexp ::= term @{| term@} -- alternation (term or term @dots{})
15737
15738 term ::= item @{item@} -- concatenation (item then item)
15739
15740 item ::= elmt -- match elmt
15741 item ::= elmt * -- zero or more elmt's
15742 item ::= elmt + -- one or more elmt's
15743 item ::= elmt ? -- matches elmt or nothing
15744 @end group
15745 @group
15746 elmt ::= nschar -- matches given character
15747 elmt ::= [nschar @{nschar@}] -- matches any character listed
15748 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15749 elmt ::= [char - char] -- matches chars in given range
15750 elmt ::= \ char -- matches given character
15751 elmt ::= . -- matches any single character
15752 elmt ::= ( regexp ) -- parens used for grouping
15753
15754 char ::= any character, including special characters
15755 nschar ::= any character except ()[].*+?^^^
15756 @end group
15757 @end smallexample
15758
15759 Following are a few examples:
15760
15761 @table @samp
15762 @item abcde|fghi
15763 will match any of the two strings @samp{abcde} and @samp{fghi},
15764
15765 @item abc*d
15766 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15767 @samp{abcccd}, and so on,
15768
15769 @item [a-z]+
15770 will match any string which has only lowercase characters in it (and at
15771 least one character.
15772
15773 @end table
15774 @end table
15775
15776 @node Examples of gnatxref Usage
15777 @section Examples of @code{gnatxref} Usage
15778
15779 @subsection General Usage
15780
15781 @noindent
15782 For the following examples, we will consider the following units:
15783
15784 @smallexample @c ada
15785 @group
15786 @cartouche
15787 main.ads:
15788 1: with Bar;
15789 2: package Main is
15790 3: procedure Foo (B : in Integer);
15791 4: C : Integer;
15792 5: private
15793 6: D : Integer;
15794 7: end Main;
15795
15796 main.adb:
15797 1: package body Main is
15798 2: procedure Foo (B : in Integer) is
15799 3: begin
15800 4: C := B;
15801 5: D := B;
15802 6: Bar.Print (B);
15803 7: Bar.Print (C);
15804 8: end Foo;
15805 9: end Main;
15806
15807 bar.ads:
15808 1: package Bar is
15809 2: procedure Print (B : Integer);
15810 3: end bar;
15811 @end cartouche
15812 @end group
15813 @end smallexample
15814
15815 @table @code
15816
15817 @noindent
15818 The first thing to do is to recompile your application (for instance, in
15819 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15820 the cross-referencing information.
15821 You can then issue any of the following commands:
15822
15823 @item gnatxref main.adb
15824 @code{gnatxref} generates cross-reference information for main.adb
15825 and every unit 'with'ed by main.adb.
15826
15827 The output would be:
15828 @smallexample
15829 @iftex
15830 @leftskip=0cm
15831 @end iftex
15832 B Type: Integer
15833 Decl: bar.ads 2:22
15834 B Type: Integer
15835 Decl: main.ads 3:20
15836 Body: main.adb 2:20
15837 Ref: main.adb 4:13 5:13 6:19
15838 Bar Type: Unit
15839 Decl: bar.ads 1:9
15840 Ref: main.adb 6:8 7:8
15841 main.ads 1:6
15842 C Type: Integer
15843 Decl: main.ads 4:5
15844 Modi: main.adb 4:8
15845 Ref: main.adb 7:19
15846 D Type: Integer
15847 Decl: main.ads 6:5
15848 Modi: main.adb 5:8
15849 Foo Type: Unit
15850 Decl: main.ads 3:15
15851 Body: main.adb 2:15
15852 Main Type: Unit
15853 Decl: main.ads 2:9
15854 Body: main.adb 1:14
15855 Print Type: Unit
15856 Decl: bar.ads 2:15
15857 Ref: main.adb 6:12 7:12
15858 @end smallexample
15859
15860 @noindent
15861 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15862 its body is in main.adb, line 1, column 14 and is not referenced any where.
15863
15864 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15865 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15866
15867 @item gnatxref package1.adb package2.ads
15868 @code{gnatxref} will generates cross-reference information for
15869 package1.adb, package2.ads and any other package 'with'ed by any
15870 of these.
15871
15872 @end table
15873
15874 @ifclear vms
15875 @subsection Using gnatxref with vi
15876
15877 @code{gnatxref} can generate a tags file output, which can be used
15878 directly from @command{vi}. Note that the standard version of @command{vi}
15879 will not work properly with overloaded symbols. Consider using another
15880 free implementation of @command{vi}, such as @command{vim}.
15881
15882 @smallexample
15883 $ gnatxref -v gnatfind.adb > tags
15884 @end smallexample
15885
15886 @noindent
15887 will generate the tags file for @code{gnatfind} itself (if the sources
15888 are in the search path!).
15889
15890 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15891 (replacing @var{entity} by whatever you are looking for), and vi will
15892 display a new file with the corresponding declaration of entity.
15893 @end ifclear
15894
15895 @node Examples of gnatfind Usage
15896 @section Examples of @code{gnatfind} Usage
15897
15898 @table @code
15899
15900 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15901 Find declarations for all entities xyz referenced at least once in
15902 main.adb. The references are search in every library file in the search
15903 path.
15904
15905 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15906 switch is set)
15907
15908 The output will look like:
15909 @smallexample
15910 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15911 ^directory/^[directory]^main.adb:24:10: xyz <= body
15912 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15913 @end smallexample
15914
15915 @noindent
15916 that is to say, one of the entities xyz found in main.adb is declared at
15917 line 12 of main.ads (and its body is in main.adb), and another one is
15918 declared at line 45 of foo.ads
15919
15920 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15921 This is the same command as the previous one, instead @code{gnatfind} will
15922 display the content of the Ada source file lines.
15923
15924 The output will look like:
15925
15926 @smallexample
15927 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15928 procedure xyz;
15929 ^directory/^[directory]^main.adb:24:10: xyz <= body
15930 procedure xyz is
15931 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15932 xyz : Integer;
15933 @end smallexample
15934
15935 @noindent
15936 This can make it easier to find exactly the location your are looking
15937 for.
15938
15939 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15940 Find references to all entities containing an x that are
15941 referenced on line 123 of main.ads.
15942 The references will be searched only in main.ads and foo.adb.
15943
15944 @item gnatfind main.ads:123
15945 Find declarations and bodies for all entities that are referenced on
15946 line 123 of main.ads.
15947
15948 This is the same as @code{gnatfind "*":main.adb:123}.
15949
15950 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15951 Find the declaration for the entity referenced at column 45 in
15952 line 123 of file main.adb in directory mydir. Note that it
15953 is usual to omit the identifier name when the column is given,
15954 since the column position identifies a unique reference.
15955
15956 The column has to be the beginning of the identifier, and should not
15957 point to any character in the middle of the identifier.
15958
15959 @end table
15960
15961 @c *********************************
15962 @node The GNAT Pretty-Printer gnatpp
15963 @chapter The GNAT Pretty-Printer @command{gnatpp}
15964 @findex gnatpp
15965 @cindex Pretty-Printer
15966
15967 @noindent
15968 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15969 for source reformatting / pretty-printing.
15970 It takes an Ada source file as input and generates a reformatted
15971 version as output.
15972 You can specify various style directives via switches; e.g.,
15973 identifier case conventions, rules of indentation, and comment layout.
15974
15975 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15976 tree for the input source and thus requires the input to be syntactically and
15977 semantically legal.
15978 If this condition is not met, @command{gnatpp} will terminate with an
15979 error message; no output file will be generated.
15980
15981 If the source files presented to @command{gnatpp} contain
15982 preprocessing directives, then the output file will
15983 correspond to the generated source after all
15984 preprocessing is carried out. There is no way
15985 using @command{gnatpp} to obtain pretty printed files that
15986 include the preprocessing directives.
15987
15988 If the compilation unit
15989 contained in the input source depends semantically upon units located
15990 outside the current directory, you have to provide the source search path
15991 when invoking @command{gnatpp}, if these units are contained in files with
15992 names that do not follow the GNAT file naming rules, you have to provide
15993 the configuration file describing the corresponding naming scheme;
15994 see the description of the @command{gnatpp}
15995 switches below. Another possibility is to use a project file and to
15996 call @command{gnatpp} through the @command{gnat} driver
15997
15998 The @command{gnatpp} command has the form
15999
16000 @smallexample
16001 $ gnatpp @ovar{switches} @var{filename}
16002 @end smallexample
16003
16004 @noindent
16005 where
16006 @itemize @bullet
16007 @item
16008 @var{switches} is an optional sequence of switches defining such properties as
16009 the formatting rules, the source search path, and the destination for the
16010 output source file
16011
16012 @item
16013 @var{filename} is the name (including the extension) of the source file to
16014 reformat; ``wildcards'' or several file names on the same gnatpp command are
16015 allowed. The file name may contain path information; it does not have to
16016 follow the GNAT file naming rules
16017 @end itemize
16018
16019 @menu
16020 * Switches for gnatpp::
16021 * Formatting Rules::
16022 @end menu
16023
16024 @node Switches for gnatpp
16025 @section Switches for @command{gnatpp}
16026
16027 @noindent
16028 The following subsections describe the various switches accepted by
16029 @command{gnatpp}, organized by category.
16030
16031 @ifclear vms
16032 You specify a switch by supplying a name and generally also a value.
16033 In many cases the values for a switch with a given name are incompatible with
16034 each other
16035 (for example the switch that controls the casing of a reserved word may have
16036 exactly one value: upper case, lower case, or
16037 mixed case) and thus exactly one such switch can be in effect for an
16038 invocation of @command{gnatpp}.
16039 If more than one is supplied, the last one is used.
16040 However, some values for the same switch are mutually compatible.
16041 You may supply several such switches to @command{gnatpp}, but then
16042 each must be specified in full, with both the name and the value.
16043 Abbreviated forms (the name appearing once, followed by each value) are
16044 not permitted.
16045 For example, to set
16046 the alignment of the assignment delimiter both in declarations and in
16047 assignment statements, you must write @option{-A2A3}
16048 (or @option{-A2 -A3}), but not @option{-A23}.
16049 @end ifclear
16050
16051 @ifset vms
16052 In many cases the set of options for a given qualifier are incompatible with
16053 each other (for example the qualifier that controls the casing of a reserved
16054 word may have exactly one option, which specifies either upper case, lower
16055 case, or mixed case), and thus exactly one such option can be in effect for
16056 an invocation of @command{gnatpp}.
16057 If more than one is supplied, the last one is used.
16058 However, some qualifiers have options that are mutually compatible,
16059 and then you may then supply several such options when invoking
16060 @command{gnatpp}.
16061 @end ifset
16062
16063 In most cases, it is obvious whether or not the
16064 ^values for a switch with a given name^options for a given qualifier^
16065 are compatible with each other.
16066 When the semantics might not be evident, the summaries below explicitly
16067 indicate the effect.
16068
16069 @menu
16070 * Alignment Control::
16071 * Casing Control::
16072 * Construct Layout Control::
16073 * General Text Layout Control::
16074 * Other Formatting Options::
16075 * Setting the Source Search Path::
16076 * Output File Control::
16077 * Other gnatpp Switches::
16078 @end menu
16079
16080 @node Alignment Control
16081 @subsection Alignment Control
16082 @cindex Alignment control in @command{gnatpp}
16083
16084 @noindent
16085 Programs can be easier to read if certain constructs are vertically aligned.
16086 By default all alignments are set ON.
16087 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16088 OFF, and then use one or more of the other
16089 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16090 to activate alignment for specific constructs.
16091
16092 @table @option
16093 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16094
16095 @ifset vms
16096 @item /ALIGN=ON
16097 Set all alignments to ON
16098 @end ifset
16099
16100 @item ^-A0^/ALIGN=OFF^
16101 Set all alignments to OFF
16102
16103 @item ^-A1^/ALIGN=COLONS^
16104 Align @code{:} in declarations
16105
16106 @item ^-A2^/ALIGN=DECLARATIONS^
16107 Align @code{:=} in initializations in declarations
16108
16109 @item ^-A3^/ALIGN=STATEMENTS^
16110 Align @code{:=} in assignment statements
16111
16112 @item ^-A4^/ALIGN=ARROWS^
16113 Align @code{=>} in associations
16114
16115 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16116 Align @code{at} keywords in the component clauses in record
16117 representation clauses
16118 @end table
16119
16120 @noindent
16121 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16122 is allowed.
16123
16124 @node Casing Control
16125 @subsection Casing Control
16126 @cindex Casing control in @command{gnatpp}
16127
16128 @noindent
16129 @command{gnatpp} allows you to specify the casing for reserved words,
16130 pragma names, attribute designators and identifiers.
16131 For identifiers you may define a
16132 general rule for name casing but also override this rule
16133 via a set of dictionary files.
16134
16135 Three types of casing are supported: lower case, upper case, and mixed case.
16136 Lower and upper case are self-explanatory (but since some letters in
16137 Latin1 and other GNAT-supported character sets
16138 exist only in lower-case form, an upper case conversion will have no
16139 effect on them.)
16140 ``Mixed case'' means that the first letter, and also each letter immediately
16141 following an underscore, are converted to their uppercase forms;
16142 all the other letters are converted to their lowercase forms.
16143
16144 @table @option
16145 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16146 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16147 Attribute designators are lower case
16148
16149 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16150 Attribute designators are upper case
16151
16152 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16153 Attribute designators are mixed case (this is the default)
16154
16155 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16156 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16157 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16158 lower case (this is the default)
16159
16160 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16161 Keywords are upper case
16162
16163 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16164 @item ^-nD^/NAME_CASING=AS_DECLARED^
16165 Name casing for defining occurrences are as they appear in the source file
16166 (this is the default)
16167
16168 @item ^-nU^/NAME_CASING=UPPER_CASE^
16169 Names are in upper case
16170
16171 @item ^-nL^/NAME_CASING=LOWER_CASE^
16172 Names are in lower case
16173
16174 @item ^-nM^/NAME_CASING=MIXED_CASE^
16175 Names are in mixed case
16176
16177 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16178 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16179 Pragma names are lower case
16180
16181 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16182 Pragma names are upper case
16183
16184 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16185 Pragma names are mixed case (this is the default)
16186
16187 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16188 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16189 Use @var{file} as a @emph{dictionary file} that defines
16190 the casing for a set of specified names,
16191 thereby overriding the effect on these names by
16192 any explicit or implicit
16193 ^-n^/NAME_CASING^ switch.
16194 To supply more than one dictionary file,
16195 use ^several @option{-D} switches^a list of files as options^.
16196
16197 @noindent
16198 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16199 to define the casing for the Ada predefined names and
16200 the names declared in the GNAT libraries.
16201
16202 @item ^-D-^/SPECIFIC_CASING^
16203 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16204 Do not use the default dictionary file;
16205 instead, use the casing
16206 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16207 dictionary file(s)
16208 @end table
16209
16210 @noindent
16211 The structure of a dictionary file, and details on the conventions
16212 used in the default dictionary file, are defined in @ref{Name Casing}.
16213
16214 The @option{^-D-^/SPECIFIC_CASING^} and
16215 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16216 compatible.
16217
16218 @node Construct Layout Control
16219 @subsection Construct Layout Control
16220 @cindex Layout control in @command{gnatpp}
16221
16222 @noindent
16223 This group of @command{gnatpp} switches controls the layout of comments and
16224 complex syntactic constructs. See @ref{Formatting Comments} for details
16225 on their effect.
16226
16227 @table @option
16228 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16229 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16230 All the comments remain unchanged
16231
16232 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16233 GNAT-style comment line indentation (this is the default).
16234
16235 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16236 Reference-manual comment line indentation.
16237
16238 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16239 GNAT-style comment beginning
16240
16241 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16242 Reformat comment blocks
16243
16244 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16245 Keep unchanged special form comments
16246
16247 Reformat comment blocks
16248
16249 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16250 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16251 GNAT-style layout (this is the default)
16252
16253 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16254 Compact layout
16255
16256 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16257 Uncompact layout
16258
16259 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16260 @item ^-N^/NOTABS^
16261 All the VT characters are removed from the comment text. All the HT characters
16262 are expanded with the sequences of space characters to get to the next tab
16263 stops.
16264
16265 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16266 @item ^--no-separate-is^/NO_SEPARATE_IS^
16267 Do not place the keyword @code{is} on a separate line in a subprogram body in
16268 case if the spec occupies more then one line.
16269
16270 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16271 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16272 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16273 keyword @code{then} in IF statements on a separate line.
16274
16275 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16276 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16277 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16278 keyword @code{then} in IF statements on a separate line. This option is
16279 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16280
16281 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16282 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16283 Start each USE clause in a context clause from a separate line.
16284
16285 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16286 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16287 Use a separate line for a loop or block statement name, but do not use an extra
16288 indentation level for the statement itself.
16289
16290 @end table
16291
16292 @ifclear vms
16293 @noindent
16294 The @option{-c1} and @option{-c2} switches are incompatible.
16295 The @option{-c3} and @option{-c4} switches are compatible with each other and
16296 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16297 the other comment formatting switches.
16298
16299 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16300 @end ifclear
16301
16302 @ifset vms
16303 @noindent
16304 For the @option{/COMMENTS_LAYOUT} qualifier:
16305 @itemize @bullet
16306 @item
16307 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16308 @item
16309 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16310 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16311 @end itemize
16312
16313 @noindent
16314 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16315 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16316 @end ifset
16317
16318 @node General Text Layout Control
16319 @subsection General Text Layout Control
16320
16321 @noindent
16322 These switches allow control over line length and indentation.
16323
16324 @table @option
16325 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16326 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16327 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16328
16329 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16330 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16331 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16332
16333 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16334 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16335 Indentation level for continuation lines (relative to the line being
16336 continued), @var{nnn} from 1@dots{}9.
16337 The default
16338 value is one less then the (normal) indentation level, unless the
16339 indentation is set to 1 (in which case the default value for continuation
16340 line indentation is also 1)
16341 @end table
16342
16343 @node Other Formatting Options
16344 @subsection Other Formatting Options
16345
16346 @noindent
16347 These switches control the inclusion of missing end/exit labels, and
16348 the indentation level in @b{case} statements.
16349
16350 @table @option
16351 @item ^-e^/NO_MISSED_LABELS^
16352 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16353 Do not insert missing end/exit labels. An end label is the name of
16354 a construct that may optionally be repeated at the end of the
16355 construct's declaration;
16356 e.g., the names of packages, subprograms, and tasks.
16357 An exit label is the name of a loop that may appear as target
16358 of an exit statement within the loop.
16359 By default, @command{gnatpp} inserts these end/exit labels when
16360 they are absent from the original source. This option suppresses such
16361 insertion, so that the formatted source reflects the original.
16362
16363 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16364 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16365 Insert a Form Feed character after a pragma Page.
16366
16367 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16368 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16369 Do not use an additional indentation level for @b{case} alternatives
16370 and variants if there are @var{nnn} or more (the default
16371 value is 10).
16372 If @var{nnn} is 0, an additional indentation level is
16373 used for @b{case} alternatives and variants regardless of their number.
16374 @end table
16375
16376 @node Setting the Source Search Path
16377 @subsection Setting the Source Search Path
16378
16379 @noindent
16380 To define the search path for the input source file, @command{gnatpp}
16381 uses the same switches as the GNAT compiler, with the same effects.
16382
16383 @table @option
16384 @item ^-I^/SEARCH=^@var{dir}
16385 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16386 The same as the corresponding gcc switch
16387
16388 @item ^-I-^/NOCURRENT_DIRECTORY^
16389 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16390 The same as the corresponding gcc switch
16391
16392 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16393 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16394 The same as the corresponding gcc switch
16395
16396 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16397 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16398 The same as the corresponding gcc switch
16399
16400 @end table
16401
16402 @node Output File Control
16403 @subsection Output File Control
16404
16405 @noindent
16406 By default the output is sent to the file whose name is obtained by appending
16407 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16408 (if the file with this name already exists, it is unconditionally overwritten).
16409 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16410 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16411 as output file.
16412 The output may be redirected by the following switches:
16413
16414 @table @option
16415 @item ^-pipe^/STANDARD_OUTPUT^
16416 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16417 Send the output to @code{Standard_Output}
16418
16419 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16420 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16421 Write the output into @var{output_file}.
16422 If @var{output_file} already exists, @command{gnatpp} terminates without
16423 reading or processing the input file.
16424
16425 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16426 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16427 Write the output into @var{output_file}, overwriting the existing file
16428 (if one is present).
16429
16430 @item ^-r^/REPLACE^
16431 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16432 Replace the input source file with the reformatted output, and copy the
16433 original input source into the file whose name is obtained by appending the
16434 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16435 If a file with this name already exists, @command{gnatpp} terminates without
16436 reading or processing the input file.
16437
16438 @item ^-rf^/OVERRIDING_REPLACE^
16439 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16440 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16441 already exists, it is overwritten.
16442
16443 @item ^-rnb^/REPLACE_NO_BACKUP^
16444 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16445 Replace the input source file with the reformatted output without
16446 creating any backup copy of the input source.
16447
16448 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16449 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16450 Specifies the format of the reformatted output file. The @var{xxx}
16451 ^string specified with the switch^option^ may be either
16452 @itemize @bullet
16453 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16454 @item ``@option{^crlf^CRLF^}''
16455 the same as @option{^crlf^CRLF^}
16456 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16457 @item ``@option{^lf^LF^}''
16458 the same as @option{^unix^UNIX^}
16459 @end itemize
16460
16461 @item ^-W^/RESULT_ENCODING=^@var{e}
16462 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16463 Specify the wide character encoding method used to write the code in the
16464 result file
16465 @var{e} is one of the following:
16466
16467 @itemize @bullet
16468
16469 @item ^h^HEX^
16470 Hex encoding
16471
16472 @item ^u^UPPER^
16473 Upper half encoding
16474
16475 @item ^s^SHIFT_JIS^
16476 Shift/JIS encoding
16477
16478 @item ^e^EUC^
16479 EUC encoding
16480
16481 @item ^8^UTF8^
16482 UTF-8 encoding
16483
16484 @item ^b^BRACKETS^
16485 Brackets encoding (default value)
16486 @end itemize
16487
16488 @end table
16489
16490 @noindent
16491 Options @option{^-pipe^/STANDARD_OUTPUT^},
16492 @option{^-o^/OUTPUT^} and
16493 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16494 contains only one file to reformat.
16495 Option
16496 @option{^--eol^/END_OF_LINE^}
16497 and
16498 @option{^-W^/RESULT_ENCODING^}
16499 cannot be used together
16500 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16501
16502 @node Other gnatpp Switches
16503 @subsection Other @code{gnatpp} Switches
16504
16505 @noindent
16506 The additional @command{gnatpp} switches are defined in this subsection.
16507
16508 @table @option
16509 @item ^-files @var{filename}^/FILES=@var{output_file}^
16510 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16511 Take the argument source files from the specified file. This file should be an
16512 ordinary textual file containing file names separated by spaces or
16513 line breaks. You can use this switch more then once in the same call to
16514 @command{gnatpp}. You also can combine this switch with explicit list of
16515 files.
16516
16517 @item ^-v^/VERBOSE^
16518 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16519 Verbose mode;
16520 @command{gnatpp} generates version information and then
16521 a trace of the actions it takes to produce or obtain the ASIS tree.
16522
16523 @item ^-w^/WARNINGS^
16524 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16525 Warning mode;
16526 @command{gnatpp} generates a warning whenever it cannot provide
16527 a required layout in the result source.
16528 @end table
16529
16530 @node Formatting Rules
16531 @section Formatting Rules
16532
16533 @noindent
16534 The following subsections show how @command{gnatpp} treats ``white space'',
16535 comments, program layout, and name casing.
16536 They provide the detailed descriptions of the switches shown above.
16537
16538 @menu
16539 * White Space and Empty Lines::
16540 * Formatting Comments::
16541 * Construct Layout::
16542 * Name Casing::
16543 @end menu
16544
16545 @node White Space and Empty Lines
16546 @subsection White Space and Empty Lines
16547
16548 @noindent
16549 @command{gnatpp} does not have an option to control space characters.
16550 It will add or remove spaces according to the style illustrated by the
16551 examples in the @cite{Ada Reference Manual}.
16552
16553 The only format effectors
16554 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16555 that will appear in the output file are platform-specific line breaks,
16556 and also format effectors within (but not at the end of) comments.
16557 In particular, each horizontal tab character that is not inside
16558 a comment will be treated as a space and thus will appear in the
16559 output file as zero or more spaces depending on
16560 the reformatting of the line in which it appears.
16561 The only exception is a Form Feed character, which is inserted after a
16562 pragma @code{Page} when @option{-ff} is set.
16563
16564 The output file will contain no lines with trailing ``white space'' (spaces,
16565 format effectors).
16566
16567 Empty lines in the original source are preserved
16568 only if they separate declarations or statements.
16569 In such contexts, a
16570 sequence of two or more empty lines is replaced by exactly one empty line.
16571 Note that a blank line will be removed if it separates two ``comment blocks''
16572 (a comment block is a sequence of whole-line comments).
16573 In order to preserve a visual separation between comment blocks, use an
16574 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16575 Likewise, if for some reason you wish to have a sequence of empty lines,
16576 use a sequence of empty comments instead.
16577
16578 @node Formatting Comments
16579 @subsection Formatting Comments
16580
16581 @noindent
16582 Comments in Ada code are of two kinds:
16583 @itemize @bullet
16584 @item
16585 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16586 ``white space'') on a line
16587
16588 @item
16589 an @emph{end-of-line comment}, which follows some other Ada lexical element
16590 on the same line.
16591 @end itemize
16592
16593 @noindent
16594 The indentation of a whole-line comment is that of either
16595 the preceding or following line in
16596 the formatted source, depending on switch settings as will be described below.
16597
16598 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16599 between the end of the preceding Ada lexical element and the beginning
16600 of the comment as appear in the original source,
16601 unless either the comment has to be split to
16602 satisfy the line length limitation, or else the next line contains a
16603 whole line comment that is considered a continuation of this end-of-line
16604 comment (because it starts at the same position).
16605 In the latter two
16606 cases, the start of the end-of-line comment is moved right to the nearest
16607 multiple of the indentation level.
16608 This may result in a ``line overflow'' (the right-shifted comment extending
16609 beyond the maximum line length), in which case the comment is split as
16610 described below.
16611
16612 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16613 (GNAT-style comment line indentation)
16614 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16615 (reference-manual comment line indentation).
16616 With reference-manual style, a whole-line comment is indented as if it
16617 were a declaration or statement at the same place
16618 (i.e., according to the indentation of the preceding line(s)).
16619 With GNAT style, a whole-line comment that is immediately followed by an
16620 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16621 word @b{begin}, is indented based on the construct that follows it.
16622
16623 For example:
16624 @smallexample @c ada
16625 @cartouche
16626 if A then
16627 null;
16628 -- some comment
16629 else
16630 null;
16631 end if;
16632 @end cartouche
16633 @end smallexample
16634
16635 @noindent
16636 Reference-manual indentation produces:
16637
16638 @smallexample @c ada
16639 @cartouche
16640 if A then
16641 null;
16642 -- some comment
16643 else
16644 null;
16645 end if;
16646 @end cartouche
16647 @end smallexample
16648
16649 @noindent
16650 while GNAT-style indentation produces:
16651
16652 @smallexample @c ada
16653 @cartouche
16654 if A then
16655 null;
16656 -- some comment
16657 else
16658 null;
16659 end if;
16660 @end cartouche
16661 @end smallexample
16662
16663 @noindent
16664 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16665 (GNAT style comment beginning) has the following
16666 effect:
16667
16668 @itemize @bullet
16669 @item
16670 For each whole-line comment that does not end with two hyphens,
16671 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16672 to ensure that there are at least two spaces between these hyphens and the
16673 first non-blank character of the comment.
16674 @end itemize
16675
16676 @noindent
16677 For an end-of-line comment, if in the original source the next line is a
16678 whole-line comment that starts at the same position
16679 as the end-of-line comment,
16680 then the whole-line comment (and all whole-line comments
16681 that follow it and that start at the same position)
16682 will start at this position in the output file.
16683
16684 @noindent
16685 That is, if in the original source we have:
16686
16687 @smallexample @c ada
16688 @cartouche
16689 begin
16690 A := B + C; -- B must be in the range Low1..High1
16691 -- C must be in the range Low2..High2
16692 --B+C will be in the range Low1+Low2..High1+High2
16693 X := X + 1;
16694 @end cartouche
16695 @end smallexample
16696
16697 @noindent
16698 Then in the formatted source we get
16699
16700 @smallexample @c ada
16701 @cartouche
16702 begin
16703 A := B + C; -- B must be in the range Low1..High1
16704 -- C must be in the range Low2..High2
16705 -- B+C will be in the range Low1+Low2..High1+High2
16706 X := X + 1;
16707 @end cartouche
16708 @end smallexample
16709
16710 @noindent
16711 A comment that exceeds the line length limit will be split.
16712 Unless switch
16713 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16714 the line belongs to a reformattable block, splitting the line generates a
16715 @command{gnatpp} warning.
16716 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16717 comments may be reformatted in typical
16718 word processor style (that is, moving words between lines and putting as
16719 many words in a line as possible).
16720
16721 @noindent
16722 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16723 that has a special format (that is, a character that is neither a letter nor digit
16724 not white space nor line break immediately following the leading @code{--} of
16725 the comment) should be without any change moved from the argument source
16726 into reformatted source. This switch allows to preserve comments that are used
16727 as a special marks in the code (e.g.@: SPARK annotation).
16728
16729 @node Construct Layout
16730 @subsection Construct Layout
16731
16732 @noindent
16733 In several cases the suggested layout in the Ada Reference Manual includes
16734 an extra level of indentation that many programmers prefer to avoid. The
16735 affected cases include:
16736
16737 @itemize @bullet
16738
16739 @item Record type declaration (RM 3.8)
16740
16741 @item Record representation clause (RM 13.5.1)
16742
16743 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16744
16745 @item Block statement in case if a block has a statement identifier (RM 5.6)
16746 @end itemize
16747
16748 @noindent
16749 In compact mode (when GNAT style layout or compact layout is set),
16750 the pretty printer uses one level of indentation instead
16751 of two. This is achieved in the record definition and record representation
16752 clause cases by putting the @code{record} keyword on the same line as the
16753 start of the declaration or representation clause, and in the block and loop
16754 case by putting the block or loop header on the same line as the statement
16755 identifier.
16756
16757 @noindent
16758 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16759 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16760 layout on the one hand, and uncompact layout
16761 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16762 can be illustrated by the following examples:
16763
16764 @iftex
16765 @cartouche
16766 @multitable @columnfractions .5 .5
16767 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16768
16769 @item
16770 @smallexample @c ada
16771 type q is record
16772 a : integer;
16773 b : integer;
16774 end record;
16775 @end smallexample
16776 @tab
16777 @smallexample @c ada
16778 type q is
16779 record
16780 a : integer;
16781 b : integer;
16782 end record;
16783 @end smallexample
16784
16785 @item
16786 @smallexample @c ada
16787 for q use record
16788 a at 0 range 0 .. 31;
16789 b at 4 range 0 .. 31;
16790 end record;
16791 @end smallexample
16792 @tab
16793 @smallexample @c ada
16794 for q use
16795 record
16796 a at 0 range 0 .. 31;
16797 b at 4 range 0 .. 31;
16798 end record;
16799 @end smallexample
16800
16801 @item
16802 @smallexample @c ada
16803 Block : declare
16804 A : Integer := 3;
16805 begin
16806 Proc (A, A);
16807 end Block;
16808 @end smallexample
16809 @tab
16810 @smallexample @c ada
16811 Block :
16812 declare
16813 A : Integer := 3;
16814 begin
16815 Proc (A, A);
16816 end Block;
16817 @end smallexample
16818
16819 @item
16820 @smallexample @c ada
16821 Clear : for J in 1 .. 10 loop
16822 A (J) := 0;
16823 end loop Clear;
16824 @end smallexample
16825 @tab
16826 @smallexample @c ada
16827 Clear :
16828 for J in 1 .. 10 loop
16829 A (J) := 0;
16830 end loop Clear;
16831 @end smallexample
16832 @end multitable
16833 @end cartouche
16834 @end iftex
16835
16836 @ifnottex
16837 @smallexample
16838 @cartouche
16839 GNAT style, compact layout Uncompact layout
16840
16841 type q is record type q is
16842 a : integer; record
16843 b : integer; a : integer;
16844 end record; b : integer;
16845 end record;
16846
16847 for q use record for q use
16848 a at 0 range 0 .. 31; record
16849 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16850 end record; b at 4 range 0 .. 31;
16851 end record;
16852
16853 Block : declare Block :
16854 A : Integer := 3; declare
16855 begin A : Integer := 3;
16856 Proc (A, A); begin
16857 end Block; Proc (A, A);
16858 end Block;
16859
16860 Clear : for J in 1 .. 10 loop Clear :
16861 A (J) := 0; for J in 1 .. 10 loop
16862 end loop Clear; A (J) := 0;
16863 end loop Clear;
16864 @end cartouche
16865 @end smallexample
16866 @end ifnottex
16867
16868 @noindent
16869 A further difference between GNAT style layout and compact layout is that
16870 GNAT style layout inserts empty lines as separation for
16871 compound statements, return statements and bodies.
16872
16873 Note that the layout specified by
16874 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16875 for named block and loop statements overrides the layout defined by these
16876 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16877 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16878 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16879
16880 @node Name Casing
16881 @subsection Name Casing
16882
16883 @noindent
16884 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16885 the same casing as the corresponding defining identifier.
16886
16887 You control the casing for defining occurrences via the
16888 @option{^-n^/NAME_CASING^} switch.
16889 @ifclear vms
16890 With @option{-nD} (``as declared'', which is the default),
16891 @end ifclear
16892 @ifset vms
16893 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16894 @end ifset
16895 defining occurrences appear exactly as in the source file
16896 where they are declared.
16897 The other ^values for this switch^options for this qualifier^ ---
16898 @option{^-nU^UPPER_CASE^},
16899 @option{^-nL^LOWER_CASE^},
16900 @option{^-nM^MIXED_CASE^} ---
16901 result in
16902 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16903 If @command{gnatpp} changes the casing of a defining
16904 occurrence, it analogously changes the casing of all the
16905 usage occurrences of this name.
16906
16907 If the defining occurrence of a name is not in the source compilation unit
16908 currently being processed by @command{gnatpp}, the casing of each reference to
16909 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16910 switch (subject to the dictionary file mechanism described below).
16911 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16912 had affected the
16913 casing for the defining occurrence of the name.
16914
16915 Some names may need to be spelled with casing conventions that are not
16916 covered by the upper-, lower-, and mixed-case transformations.
16917 You can arrange correct casing by placing such names in a
16918 @emph{dictionary file},
16919 and then supplying a @option{^-D^/DICTIONARY^} switch.
16920 The casing of names from dictionary files overrides
16921 any @option{^-n^/NAME_CASING^} switch.
16922
16923 To handle the casing of Ada predefined names and the names from GNAT libraries,
16924 @command{gnatpp} assumes a default dictionary file.
16925 The name of each predefined entity is spelled with the same casing as is used
16926 for the entity in the @cite{Ada Reference Manual}.
16927 The name of each entity in the GNAT libraries is spelled with the same casing
16928 as is used in the declaration of that entity.
16929
16930 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16931 default dictionary file.
16932 Instead, the casing for predefined and GNAT-defined names will be established
16933 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16934 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16935 will appear as just shown,
16936 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16937 To ensure that even such names are rendered in uppercase,
16938 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16939 (or else, less conveniently, place these names in upper case in a dictionary
16940 file).
16941
16942 A dictionary file is
16943 a plain text file; each line in this file can be either a blank line
16944 (containing only space characters and ASCII.HT characters), an Ada comment
16945 line, or the specification of exactly one @emph{casing schema}.
16946
16947 A casing schema is a string that has the following syntax:
16948
16949 @smallexample
16950 @cartouche
16951 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16952
16953 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16954 @end cartouche
16955 @end smallexample
16956
16957 @noindent
16958 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16959 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16960
16961 The casing schema string can be followed by white space and/or an Ada-style
16962 comment; any amount of white space is allowed before the string.
16963
16964 If a dictionary file is passed as
16965 @ifclear vms
16966 the value of a @option{-D@var{file}} switch
16967 @end ifclear
16968 @ifset vms
16969 an option to the @option{/DICTIONARY} qualifier
16970 @end ifset
16971 then for every
16972 simple name and every identifier, @command{gnatpp} checks if the dictionary
16973 defines the casing for the name or for some of its parts (the term ``subword''
16974 is used below to denote the part of a name which is delimited by ``_'' or by
16975 the beginning or end of the word and which does not contain any ``_'' inside):
16976
16977 @itemize @bullet
16978 @item
16979 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16980 the casing defined by the dictionary; no subwords are checked for this word
16981
16982 @item
16983 for every subword @command{gnatpp} checks if the dictionary contains the
16984 corresponding string of the form @code{*@var{simple_identifier}*},
16985 and if it does, the casing of this @var{simple_identifier} is used
16986 for this subword
16987
16988 @item
16989 if the whole name does not contain any ``_'' inside, and if for this name
16990 the dictionary contains two entries - one of the form @var{identifier},
16991 and another - of the form *@var{simple_identifier}*, then the first one
16992 is applied to define the casing of this name
16993
16994 @item
16995 if more than one dictionary file is passed as @command{gnatpp} switches, each
16996 dictionary adds new casing exceptions and overrides all the existing casing
16997 exceptions set by the previous dictionaries
16998
16999 @item
17000 when @command{gnatpp} checks if the word or subword is in the dictionary,
17001 this check is not case sensitive
17002 @end itemize
17003
17004 @noindent
17005 For example, suppose we have the following source to reformat:
17006
17007 @smallexample @c ada
17008 @cartouche
17009 procedure test is
17010 name1 : integer := 1;
17011 name4_name3_name2 : integer := 2;
17012 name2_name3_name4 : Boolean;
17013 name1_var : Float;
17014 begin
17015 name2_name3_name4 := name4_name3_name2 > name1;
17016 end;
17017 @end cartouche
17018 @end smallexample
17019
17020 @noindent
17021 And suppose we have two dictionaries:
17022
17023 @smallexample
17024 @cartouche
17025 @i{dict1:}
17026 NAME1
17027 *NaMe3*
17028 *Name1*
17029 @end cartouche
17030
17031 @cartouche
17032 @i{dict2:}
17033 *NAME3*
17034 @end cartouche
17035 @end smallexample
17036
17037 @noindent
17038 If @command{gnatpp} is called with the following switches:
17039
17040 @smallexample
17041 @ifclear vms
17042 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17043 @end ifclear
17044 @ifset vms
17045 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17046 @end ifset
17047 @end smallexample
17048
17049 @noindent
17050 then we will get the following name casing in the @command{gnatpp} output:
17051
17052 @smallexample @c ada
17053 @cartouche
17054 procedure Test is
17055 NAME1 : Integer := 1;
17056 Name4_NAME3_Name2 : Integer := 2;
17057 Name2_NAME3_Name4 : Boolean;
17058 Name1_Var : Float;
17059 begin
17060 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17061 end Test;
17062 @end cartouche
17063 @end smallexample
17064
17065 @c *********************************
17066 @node The GNAT Metric Tool gnatmetric
17067 @chapter The GNAT Metric Tool @command{gnatmetric}
17068 @findex gnatmetric
17069 @cindex Metric tool
17070
17071 @noindent
17072 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17073 for computing various program metrics.
17074 It takes an Ada source file as input and generates a file containing the
17075 metrics data as output. Various switches control which
17076 metrics are computed and output.
17077
17078 @command{gnatmetric} generates and uses the ASIS
17079 tree for the input source and thus requires the input to be syntactically and
17080 semantically legal.
17081 If this condition is not met, @command{gnatmetric} will generate
17082 an error message; no metric information for this file will be
17083 computed and reported.
17084
17085 If the compilation unit contained in the input source depends semantically
17086 upon units in files located outside the current directory, you have to provide
17087 the source search path when invoking @command{gnatmetric}.
17088 If it depends semantically upon units that are contained
17089 in files with names that do not follow the GNAT file naming rules, you have to
17090 provide the configuration file describing the corresponding naming scheme (see
17091 the description of the @command{gnatmetric} switches below.)
17092 Alternatively, you may use a project file and invoke @command{gnatmetric}
17093 through the @command{gnat} driver.
17094
17095 The @command{gnatmetric} command has the form
17096
17097 @smallexample
17098 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17099 @end smallexample
17100
17101 @noindent
17102 where
17103 @itemize @bullet
17104 @item
17105 @var{switches} specify the metrics to compute and define the destination for
17106 the output
17107
17108 @item
17109 Each @var{filename} is the name (including the extension) of a source
17110 file to process. ``Wildcards'' are allowed, and
17111 the file name may contain path information.
17112 If no @var{filename} is supplied, then the @var{switches} list must contain
17113 at least one
17114 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17115 Including both a @option{-files} switch and one or more
17116 @var{filename} arguments is permitted.
17117
17118 @item
17119 @samp{-cargs @var{gcc_switches}} is a list of switches for
17120 @command{gcc}. They will be passed on to all compiler invocations made by
17121 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17122 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17123 and use the @option{-gnatec} switch to set the configuration file.
17124 @end itemize
17125
17126 @menu
17127 * Switches for gnatmetric::
17128 @end menu
17129
17130 @node Switches for gnatmetric
17131 @section Switches for @command{gnatmetric}
17132
17133 @noindent
17134 The following subsections describe the various switches accepted by
17135 @command{gnatmetric}, organized by category.
17136
17137 @menu
17138 * Output Files Control::
17139 * Disable Metrics For Local Units::
17140 * Specifying a set of metrics to compute::
17141 * Other gnatmetric Switches::
17142 * Generate project-wide metrics::
17143 @end menu
17144
17145 @node Output Files Control
17146 @subsection Output File Control
17147 @cindex Output file control in @command{gnatmetric}
17148
17149 @noindent
17150 @command{gnatmetric} has two output formats. It can generate a
17151 textual (human-readable) form, and also XML. By default only textual
17152 output is generated.
17153
17154 When generating the output in textual form, @command{gnatmetric} creates
17155 for each Ada source file a corresponding text file
17156 containing the computed metrics, except for the case when the set of metrics
17157 specified by gnatmetric parameters consists only of metrics that are computed
17158 for the whole set of analyzed sources, but not for each Ada source.
17159 By default, this file is placed in the same directory as where the source
17160 file is located, and its name is obtained
17161 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17162 input file.
17163
17164 All the output information generated in XML format is placed in a single
17165 file. By default this file is placed in the current directory and has the
17166 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17167
17168 Some of the computed metrics are summed over the units passed to
17169 @command{gnatmetric}; for example, the total number of lines of code.
17170 By default this information is sent to @file{stdout}, but a file
17171 can be specified with the @option{-og} switch.
17172
17173 The following switches control the @command{gnatmetric} output:
17174
17175 @table @option
17176 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17177 @item ^-x^/XML^
17178 Generate the XML output
17179
17180 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17181 @item ^-nt^/NO_TEXT^
17182 Do not generate the output in text form (implies @option{^-x^/XML^})
17183
17184 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17185 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17186 Put textual files with detailed metrics into @var{output_dir}
17187
17188 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17189 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17190 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17191 in the name of the output file.
17192
17193 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17194 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17195 Put global metrics into @var{file_name}
17196
17197 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17198 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17199 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17200
17201 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17202 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17203 Use ``short'' source file names in the output. (The @command{gnatmetric}
17204 output includes the name(s) of the Ada source file(s) from which the metrics
17205 are computed. By default each name includes the absolute path. The
17206 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17207 to exclude all directory information from the file names that are output.)
17208
17209 @end table
17210
17211 @node Disable Metrics For Local Units
17212 @subsection Disable Metrics For Local Units
17213 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17214
17215 @noindent
17216 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17217 one compilation
17218 unit per one source file. It computes line metrics for the whole source
17219 file, and it also computes syntax
17220 and complexity metrics for the file's outermost unit.
17221
17222 By default, @command{gnatmetric} will also compute all metrics for certain
17223 kinds of locally declared program units:
17224
17225 @itemize @bullet
17226 @item
17227 subprogram (and generic subprogram) bodies;
17228
17229 @item
17230 package (and generic package) specs and bodies;
17231
17232 @item
17233 task object and type specifications and bodies;
17234
17235 @item
17236 protected object and type specifications and bodies.
17237 @end itemize
17238
17239 @noindent
17240 These kinds of entities will be referred to as
17241 @emph{eligible local program units}, or simply @emph{eligible local units},
17242 @cindex Eligible local unit (for @command{gnatmetric})
17243 in the discussion below.
17244
17245 Note that a subprogram declaration, generic instantiation,
17246 or renaming declaration only receives metrics
17247 computation when it appear as the outermost entity
17248 in a source file.
17249
17250 Suppression of metrics computation for eligible local units can be
17251 obtained via the following switch:
17252
17253 @table @option
17254 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17255 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17256 Do not compute detailed metrics for eligible local program units
17257
17258 @end table
17259
17260 @node Specifying a set of metrics to compute
17261 @subsection Specifying a set of metrics to compute
17262
17263 @noindent
17264 By default all the metrics are computed and reported. The switches
17265 described in this subsection allow you to control, on an individual
17266 basis, whether metrics are computed and
17267 reported. If at least one positive metric
17268 switch is specified (that is, a switch that defines that a given
17269 metric or set of metrics is to be computed), then only
17270 explicitly specified metrics are reported.
17271
17272 @menu
17273 * Line Metrics Control::
17274 * Syntax Metrics Control::
17275 * Complexity Metrics Control::
17276 * Object-Oriented Metrics Control::
17277 @end menu
17278
17279 @node Line Metrics Control
17280 @subsubsection Line Metrics Control
17281 @cindex Line metrics control in @command{gnatmetric}
17282
17283 @noindent
17284 For any (legal) source file, and for each of its
17285 eligible local program units, @command{gnatmetric} computes the following
17286 metrics:
17287
17288 @itemize @bullet
17289 @item
17290 the total number of lines;
17291
17292 @item
17293 the total number of code lines (i.e., non-blank lines that are not comments)
17294
17295 @item
17296 the number of comment lines
17297
17298 @item
17299 the number of code lines containing end-of-line comments;
17300
17301 @item
17302 the comment percentage: the ratio between the number of lines that contain
17303 comments and the number of all non-blank lines, expressed as a percentage;
17304
17305 @item
17306 the number of empty lines and lines containing only space characters and/or
17307 format effectors (blank lines)
17308
17309 @item
17310 the average number of code lines in subprogram bodies, task bodies, entry
17311 bodies and statement sequences in package bodies (this metric is only computed
17312 across the whole set of the analyzed units)
17313
17314 @end itemize
17315
17316 @noindent
17317 @command{gnatmetric} sums the values of the line metrics for all the
17318 files being processed and then generates the cumulative results. The tool
17319 also computes for all the files being processed the average number of code
17320 lines in bodies.
17321
17322 You can use the following switches to select the specific line metrics
17323 to be computed and reported.
17324
17325 @table @option
17326 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17327
17328 @ifclear vms
17329 @cindex @option{--no-lines@var{x}}
17330 @end ifclear
17331
17332 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17333 Report all the line metrics
17334
17335 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17336 Do not report any of line metrics
17337
17338 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17339 Report the number of all lines
17340
17341 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17342 Do not report the number of all lines
17343
17344 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17345 Report the number of code lines
17346
17347 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17348 Do not report the number of code lines
17349
17350 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17351 Report the number of comment lines
17352
17353 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17354 Do not report the number of comment lines
17355
17356 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17357 Report the number of code lines containing
17358 end-of-line comments
17359
17360 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17361 Do not report the number of code lines containing
17362 end-of-line comments
17363
17364 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17365 Report the comment percentage in the program text
17366
17367 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17368 Do not report the comment percentage in the program text
17369
17370 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17371 Report the number of blank lines
17372
17373 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17374 Do not report the number of blank lines
17375
17376 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17377 Report the average number of code lines in subprogram bodies, task bodies,
17378 entry bodies and statement sequences in package bodies. The metric is computed
17379 and reported for the whole set of processed Ada sources only.
17380
17381 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17382 Do not report the average number of code lines in subprogram bodies,
17383 task bodies, entry bodies and statement sequences in package bodies.
17384
17385 @end table
17386
17387 @node Syntax Metrics Control
17388 @subsubsection Syntax Metrics Control
17389 @cindex Syntax metrics control in @command{gnatmetric}
17390
17391 @noindent
17392 @command{gnatmetric} computes various syntactic metrics for the
17393 outermost unit and for each eligible local unit:
17394
17395 @table @emph
17396 @item LSLOC (``Logical Source Lines Of Code'')
17397 The total number of declarations and the total number of statements
17398
17399 @item Maximal static nesting level of inner program units
17400 According to
17401 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17402 package, a task unit, a protected unit, a
17403 protected entry, a generic unit, or an explicitly declared subprogram other
17404 than an enumeration literal.''
17405
17406 @item Maximal nesting level of composite syntactic constructs
17407 This corresponds to the notion of the
17408 maximum nesting level in the GNAT built-in style checks
17409 (@pxref{Style Checking})
17410 @end table
17411
17412 @noindent
17413 For the outermost unit in the file, @command{gnatmetric} additionally computes
17414 the following metrics:
17415
17416 @table @emph
17417 @item Public subprograms
17418 This metric is computed for package specs. It is the
17419 number of subprograms and generic subprograms declared in the visible
17420 part (including the visible part of nested packages, protected objects, and
17421 protected types).
17422
17423 @item All subprograms
17424 This metric is computed for bodies and subunits. The
17425 metric is equal to a total number of subprogram bodies in the compilation
17426 unit.
17427 Neither generic instantiations nor renamings-as-a-body nor body stubs
17428 are counted. Any subprogram body is counted, independently of its nesting
17429 level and enclosing constructs. Generic bodies and bodies of protected
17430 subprograms are counted in the same way as ``usual'' subprogram bodies.
17431
17432 @item Public types
17433 This metric is computed for package specs and
17434 generic package declarations. It is the total number of types
17435 that can be referenced from outside this compilation unit, plus the
17436 number of types from all the visible parts of all the visible generic
17437 packages. Generic formal types are not counted. Only types, not subtypes,
17438 are included.
17439
17440 @noindent
17441 Along with the total number of public types, the following
17442 types are counted and reported separately:
17443
17444 @itemize @bullet
17445 @item
17446 Abstract types
17447
17448 @item
17449 Root tagged types (abstract, non-abstract, private, non-private). Type
17450 extensions are @emph{not} counted
17451
17452 @item
17453 Private types (including private extensions)
17454
17455 @item
17456 Task types
17457
17458 @item
17459 Protected types
17460
17461 @end itemize
17462
17463 @item All types
17464 This metric is computed for any compilation unit. It is equal to the total
17465 number of the declarations of different types given in the compilation unit.
17466 The private and the corresponding full type declaration are counted as one
17467 type declaration. Incomplete type declarations and generic formal types
17468 are not counted.
17469 No distinction is made among different kinds of types (abstract,
17470 private etc.); the total number of types is computed and reported.
17471
17472 @end table
17473
17474 @noindent
17475 By default, all the syntax metrics are computed and reported. You can use the
17476 following switches to select specific syntax metrics.
17477
17478 @table @option
17479
17480 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17481
17482 @ifclear vms
17483 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17484 @end ifclear
17485
17486 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17487 Report all the syntax metrics
17488
17489 @item ^--no-syntax-all^/ALL_OFF^
17490 Do not report any of syntax metrics
17491
17492 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17493 Report the total number of declarations
17494
17495 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17496 Do not report the total number of declarations
17497
17498 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17499 Report the total number of statements
17500
17501 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17502 Do not report the total number of statements
17503
17504 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17505 Report the number of public subprograms in a compilation unit
17506
17507 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17508 Do not report the number of public subprograms in a compilation unit
17509
17510 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17511 Report the number of all the subprograms in a compilation unit
17512
17513 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17514 Do not report the number of all the subprograms in a compilation unit
17515
17516 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17517 Report the number of public types in a compilation unit
17518
17519 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17520 Do not report the number of public types in a compilation unit
17521
17522 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17523 Report the number of all the types in a compilation unit
17524
17525 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17526 Do not report the number of all the types in a compilation unit
17527
17528 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17529 Report the maximal program unit nesting level
17530
17531 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17532 Do not report the maximal program unit nesting level
17533
17534 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17535 Report the maximal construct nesting level
17536
17537 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17538 Do not report the maximal construct nesting level
17539
17540 @end table
17541
17542 @node Complexity Metrics Control
17543 @subsubsection Complexity Metrics Control
17544 @cindex Complexity metrics control in @command{gnatmetric}
17545
17546 @noindent
17547 For a program unit that is an executable body (a subprogram body (including
17548 generic bodies), task body, entry body or a package body containing
17549 its own statement sequence) @command{gnatmetric} computes the following
17550 complexity metrics:
17551
17552 @itemize @bullet
17553 @item
17554 McCabe cyclomatic complexity;
17555
17556 @item
17557 McCabe essential complexity;
17558
17559 @item
17560 maximal loop nesting level
17561
17562 @end itemize
17563
17564 @noindent
17565 The McCabe complexity metrics are defined
17566 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17567
17568 According to McCabe, both control statements and short-circuit control forms
17569 should be taken into account when computing cyclomatic complexity. For each
17570 body, we compute three metric values:
17571
17572 @itemize @bullet
17573 @item
17574 the complexity introduced by control
17575 statements only, without taking into account short-circuit forms,
17576
17577 @item
17578 the complexity introduced by short-circuit control forms only, and
17579
17580 @item
17581 the total
17582 cyclomatic complexity, which is the sum of these two values.
17583 @end itemize
17584
17585 @noindent
17586 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17587 the code in the exception handlers and in all the nested program units.
17588
17589 By default, all the complexity metrics are computed and reported.
17590 For more fine-grained control you can use
17591 the following switches:
17592
17593 @table @option
17594 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17595
17596 @ifclear vms
17597 @cindex @option{--no-complexity@var{x}}
17598 @end ifclear
17599
17600 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17601 Report all the complexity metrics
17602
17603 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17604 Do not report any of complexity metrics
17605
17606 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17607 Report the McCabe Cyclomatic Complexity
17608
17609 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17610 Do not report the McCabe Cyclomatic Complexity
17611
17612 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17613 Report the Essential Complexity
17614
17615 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17616 Do not report the Essential Complexity
17617
17618 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17619 Report maximal loop nesting level
17620
17621 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17622 Do not report maximal loop nesting level
17623
17624 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17625 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17626 task bodies, entry bodies and statement sequences in package bodies.
17627 The metric is computed and reported for whole set of processed Ada sources
17628 only.
17629
17630 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17631 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17632 bodies, task bodies, entry bodies and statement sequences in package bodies
17633
17634 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17635 @item ^-ne^/NO_EXITS_AS_GOTOS^
17636 Do not consider @code{exit} statements as @code{goto}s when
17637 computing Essential Complexity
17638
17639 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS_ON^
17640 Report the extra exit points for subprogram bodies
17641
17642 @item ^--no-extra-exit-points^/EXTRA_EXIT_POINTS_OFF^
17643 Do not report the extra exit points for subprogram bodies
17644 @end table
17645
17646
17647 @node Object-Oriented Metrics Control
17648 @subsubsection Object-Oriented Metrics Control
17649 @cindex Object-Oriented metrics control in @command{gnatmetric}
17650
17651 @noindent
17652 @cindex Coupling metrics (in in @command{gnatmetric})
17653 Coupling metrics are object-oriented metrics that measure the
17654 dependencies between a given class (or a group of classes) and the
17655 ``external world'' (that is, the other classes in the program). In this
17656 subsection the term ``class'' is used in its
17657 traditional object-oriented programming sense
17658 (an instantiable module that contains data and/or method members).
17659 A @emph{category} (of classes)
17660 is a group of closely related classes that are reused and/or
17661 modified together.
17662
17663 A class @code{K}'s @emph{efferent coupling} is the number of classes
17664 that @code{K} depends upon.
17665 A category's efferent coupling is the number of classes outside the
17666 category that the classes inside the category depend upon.
17667
17668 A class @code{K}'s @emph{afferent coupling} is the number of classes
17669 that depend upon @code{K}.
17670 A category's afferent coupling is the number of classes outside the
17671 category that depend on classes belonging to the category.
17672
17673 Ada's implementation of the object-oriented paradigm does not use the
17674 traditional class notion, so the definition of the coupling
17675 metrics for Ada maps the class and class category notions
17676 onto Ada constructs.
17677
17678 For the coupling metrics, several kinds of modules -- a library package,
17679 a library generic package, and a library generic package instantiation --
17680 that define a tagged type or an interface type are
17681 considered to be a class. A category consists of a library package (or
17682 a library generic package) that defines a tagged or an interface type,
17683 together with all its descendant (generic) packages that define tagged
17684 or interface types. For any package counted as a class,
17685 its body (if any) is considered
17686 together with its spec when counting the dependencies. For dependencies
17687 between classes, the Ada semantic dependencies are considered.
17688 For coupling metrics, only dependencies on units that are considered as
17689 classes, are considered.
17690
17691 When computing coupling metrics, @command{gnatmetric} counts only
17692 dependencies between units that are arguments of the gnatmetric call.
17693 Coupling metrics are program-wide (or project-wide) metrics, so to
17694 get a valid result, you should call @command{gnatmetric} for
17695 the whole set of sources that make up your program. It can be done
17696 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17697 option (see See @ref{The GNAT Driver and Project Files} for details.
17698
17699 By default, all the coupling metrics are disabled. You can use the following
17700 switches to specify the coupling metrics to be computed and reported:
17701
17702 @table @option
17703
17704 @ifclear vms
17705 @cindex @option{--package@var{x}} (@command{gnatmetric})
17706 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17707 @cindex @option{--category@var{x}} (@command{gnatmetric})
17708 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17709 @end ifclear
17710
17711 @ifset vms
17712 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17713 @end ifset
17714
17715 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17716 Report all the coupling metrics
17717
17718 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17719 Do not report any of metrics
17720
17721 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17722 Report package efferent coupling
17723
17724 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17725 Do not report package efferent coupling
17726
17727 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17728 Report package afferent coupling
17729
17730 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17731 Do not report package afferent coupling
17732
17733 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17734 Report category efferent coupling
17735
17736 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17737 Do not report category efferent coupling
17738
17739 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17740 Report category afferent coupling
17741
17742 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17743 Do not report category afferent coupling
17744
17745 @end table
17746
17747 @node Other gnatmetric Switches
17748 @subsection Other @code{gnatmetric} Switches
17749
17750 @noindent
17751 Additional @command{gnatmetric} switches are as follows:
17752
17753 @table @option
17754 @item ^-files @var{filename}^/FILES=@var{filename}^
17755 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17756 Take the argument source files from the specified file. This file should be an
17757 ordinary text file containing file names separated by spaces or
17758 line breaks. You can use this switch more then once in the same call to
17759 @command{gnatmetric}. You also can combine this switch with
17760 an explicit list of files.
17761
17762 @item ^-v^/VERBOSE^
17763 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17764 Verbose mode;
17765 @command{gnatmetric} generates version information and then
17766 a trace of sources being processed.
17767
17768 @item ^-dv^/DEBUG_OUTPUT^
17769 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17770 Debug mode;
17771 @command{gnatmetric} generates various messages useful to understand what
17772 happens during the metrics computation
17773
17774 @item ^-q^/QUIET^
17775 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17776 Quiet mode.
17777 @end table
17778
17779 @node Generate project-wide metrics
17780 @subsection Generate project-wide metrics
17781
17782 In order to compute metrics on all units of a given project, you can use
17783 the @command{gnat} driver along with the @option{-P} option:
17784 @smallexample
17785 gnat metric -Pproj
17786 @end smallexample
17787
17788 @noindent
17789 If the project @code{proj} depends upon other projects, you can compute
17790 the metrics on the project closure using the @option{-U} option:
17791 @smallexample
17792 gnat metric -Pproj -U
17793 @end smallexample
17794
17795 @noindent
17796 Finally, if not all the units are relevant to a particular main
17797 program in the project closure, you can generate metrics for the set
17798 of units needed to create a given main program (unit closure) using
17799 the @option{-U} option followed by the name of the main unit:
17800 @smallexample
17801 gnat metric -Pproj -U main
17802 @end smallexample
17803
17804
17805 @c ***********************************
17806 @node File Name Krunching Using gnatkr
17807 @chapter File Name Krunching Using @code{gnatkr}
17808 @findex gnatkr
17809
17810 @noindent
17811 This chapter discusses the method used by the compiler to shorten
17812 the default file names chosen for Ada units so that they do not
17813 exceed the maximum length permitted. It also describes the
17814 @code{gnatkr} utility that can be used to determine the result of
17815 applying this shortening.
17816 @menu
17817 * About gnatkr::
17818 * Using gnatkr::
17819 * Krunching Method::
17820 * Examples of gnatkr Usage::
17821 @end menu
17822
17823 @node About gnatkr
17824 @section About @code{gnatkr}
17825
17826 @noindent
17827 The default file naming rule in GNAT
17828 is that the file name must be derived from
17829 the unit name. The exact default rule is as follows:
17830 @itemize @bullet
17831 @item
17832 Take the unit name and replace all dots by hyphens.
17833 @item
17834 If such a replacement occurs in the
17835 second character position of a name, and the first character is
17836 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17837 then replace the dot by the character
17838 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17839 instead of a minus.
17840 @end itemize
17841 The reason for this exception is to avoid clashes
17842 with the standard names for children of System, Ada, Interfaces,
17843 and GNAT, which use the prefixes
17844 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17845 respectively.
17846
17847 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17848 switch of the compiler activates a ``krunching''
17849 circuit that limits file names to nn characters (where nn is a decimal
17850 integer). For example, using OpenVMS,
17851 where the maximum file name length is
17852 39, the value of nn is usually set to 39, but if you want to generate
17853 a set of files that would be usable if ported to a system with some
17854 different maximum file length, then a different value can be specified.
17855 The default value of 39 for OpenVMS need not be specified.
17856
17857 The @code{gnatkr} utility can be used to determine the krunched name for
17858 a given file, when krunched to a specified maximum length.
17859
17860 @node Using gnatkr
17861 @section Using @code{gnatkr}
17862
17863 @noindent
17864 The @code{gnatkr} command has the form
17865
17866 @ifclear vms
17867 @smallexample
17868 $ gnatkr @var{name} @ovar{length}
17869 @end smallexample
17870 @end ifclear
17871
17872 @ifset vms
17873 @smallexample
17874 $ gnatkr @var{name} /COUNT=nn
17875 @end smallexample
17876 @end ifset
17877
17878 @noindent
17879 @var{name} is the uncrunched file name, derived from the name of the unit
17880 in the standard manner described in the previous section (i.e., in particular
17881 all dots are replaced by hyphens). The file name may or may not have an
17882 extension (defined as a suffix of the form period followed by arbitrary
17883 characters other than period). If an extension is present then it will
17884 be preserved in the output. For example, when krunching @file{hellofile.ads}
17885 to eight characters, the result will be hellofil.ads.
17886
17887 Note: for compatibility with previous versions of @code{gnatkr} dots may
17888 appear in the name instead of hyphens, but the last dot will always be
17889 taken as the start of an extension. So if @code{gnatkr} is given an argument
17890 such as @file{Hello.World.adb} it will be treated exactly as if the first
17891 period had been a hyphen, and for example krunching to eight characters
17892 gives the result @file{hellworl.adb}.
17893
17894 Note that the result is always all lower case (except on OpenVMS where it is
17895 all upper case). Characters of the other case are folded as required.
17896
17897 @var{length} represents the length of the krunched name. The default
17898 when no argument is given is ^8^39^ characters. A length of zero stands for
17899 unlimited, in other words do not chop except for system files where the
17900 implied crunching length is always eight characters.
17901
17902 @noindent
17903 The output is the krunched name. The output has an extension only if the
17904 original argument was a file name with an extension.
17905
17906 @node Krunching Method
17907 @section Krunching Method
17908
17909 @noindent
17910 The initial file name is determined by the name of the unit that the file
17911 contains. The name is formed by taking the full expanded name of the
17912 unit and replacing the separating dots with hyphens and
17913 using ^lowercase^uppercase^
17914 for all letters, except that a hyphen in the second character position is
17915 replaced by a ^tilde^dollar sign^ if the first character is
17916 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17917 The extension is @code{.ads} for a
17918 spec and @code{.adb} for a body.
17919 Krunching does not affect the extension, but the file name is shortened to
17920 the specified length by following these rules:
17921
17922 @itemize @bullet
17923 @item
17924 The name is divided into segments separated by hyphens, tildes or
17925 underscores and all hyphens, tildes, and underscores are
17926 eliminated. If this leaves the name short enough, we are done.
17927
17928 @item
17929 If the name is too long, the longest segment is located (left-most
17930 if there are two of equal length), and shortened by dropping
17931 its last character. This is repeated until the name is short enough.
17932
17933 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17934 to fit the name into 8 characters as required by some operating systems.
17935
17936 @smallexample
17937 our-strings-wide_fixed 22
17938 our strings wide fixed 19
17939 our string wide fixed 18
17940 our strin wide fixed 17
17941 our stri wide fixed 16
17942 our stri wide fixe 15
17943 our str wide fixe 14
17944 our str wid fixe 13
17945 our str wid fix 12
17946 ou str wid fix 11
17947 ou st wid fix 10
17948 ou st wi fix 9
17949 ou st wi fi 8
17950 Final file name: oustwifi.adb
17951 @end smallexample
17952
17953 @item
17954 The file names for all predefined units are always krunched to eight
17955 characters. The krunching of these predefined units uses the following
17956 special prefix replacements:
17957
17958 @table @file
17959 @item ada-
17960 replaced by @file{^a^A^-}
17961
17962 @item gnat-
17963 replaced by @file{^g^G^-}
17964
17965 @item interfaces-
17966 replaced by @file{^i^I^-}
17967
17968 @item system-
17969 replaced by @file{^s^S^-}
17970 @end table
17971
17972 These system files have a hyphen in the second character position. That
17973 is why normal user files replace such a character with a
17974 ^tilde^dollar sign^, to
17975 avoid confusion with system file names.
17976
17977 As an example of this special rule, consider
17978 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17979
17980 @smallexample
17981 ada-strings-wide_fixed 22
17982 a- strings wide fixed 18
17983 a- string wide fixed 17
17984 a- strin wide fixed 16
17985 a- stri wide fixed 15
17986 a- stri wide fixe 14
17987 a- str wide fixe 13
17988 a- str wid fixe 12
17989 a- str wid fix 11
17990 a- st wid fix 10
17991 a- st wi fix 9
17992 a- st wi fi 8
17993 Final file name: a-stwifi.adb
17994 @end smallexample
17995 @end itemize
17996
17997 Of course no file shortening algorithm can guarantee uniqueness over all
17998 possible unit names, and if file name krunching is used then it is your
17999 responsibility to ensure that no name clashes occur. The utility
18000 program @code{gnatkr} is supplied for conveniently determining the
18001 krunched name of a file.
18002
18003 @node Examples of gnatkr Usage
18004 @section Examples of @code{gnatkr} Usage
18005
18006 @smallexample
18007 @iftex
18008 @leftskip=0cm
18009 @end iftex
18010 @ifclear vms
18011 $ gnatkr very_long_unit_name.ads --> velounna.ads
18012 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18013 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18014 $ gnatkr grandparent-parent-child --> grparchi
18015 @end ifclear
18016 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18017 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18018 @end smallexample
18019
18020 @node Preprocessing Using gnatprep
18021 @chapter Preprocessing Using @code{gnatprep}
18022 @findex gnatprep
18023
18024 @noindent
18025 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18026 preprocessing.
18027 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18028 special GNAT features.
18029 For further discussion of conditional compilation in general, see
18030 @ref{Conditional Compilation}.
18031
18032 @menu
18033 * Preprocessing Symbols::
18034 * Using gnatprep::
18035 * Switches for gnatprep::
18036 * Form of Definitions File::
18037 * Form of Input Text for gnatprep::
18038 @end menu
18039
18040 @node Preprocessing Symbols
18041 @section Preprocessing Symbols
18042
18043 @noindent
18044 Preprocessing symbols are defined in definition files and referred to in
18045 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18046 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18047 all characters need to be in the ASCII set (no accented letters).
18048
18049 @node Using gnatprep
18050 @section Using @code{gnatprep}
18051
18052 @noindent
18053 To call @code{gnatprep} use
18054
18055 @smallexample
18056 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18057 @end smallexample
18058
18059 @noindent
18060 where
18061 @table @var
18062 @item switches
18063 is an optional sequence of switches as described in the next section.
18064
18065 @item infile
18066 is the full name of the input file, which is an Ada source
18067 file containing preprocessor directives.
18068
18069 @item outfile
18070 is the full name of the output file, which is an Ada source
18071 in standard Ada form. When used with GNAT, this file name will
18072 normally have an ads or adb suffix.
18073
18074 @item deffile
18075 is the full name of a text file containing definitions of
18076 preprocessing symbols to be referenced by the preprocessor. This argument is
18077 optional, and can be replaced by the use of the @option{-D} switch.
18078
18079 @end table
18080
18081 @node Switches for gnatprep
18082 @section Switches for @code{gnatprep}
18083
18084 @table @option
18085 @c !sort!
18086
18087 @item ^-b^/BLANK_LINES^
18088 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18089 Causes both preprocessor lines and the lines deleted by
18090 preprocessing to be replaced by blank lines in the output source file,
18091 preserving line numbers in the output file.
18092
18093 @item ^-c^/COMMENTS^
18094 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18095 Causes both preprocessor lines and the lines deleted
18096 by preprocessing to be retained in the output source as comments marked
18097 with the special string @code{"--! "}. This option will result in line numbers
18098 being preserved in the output file.
18099
18100 @item ^-C^/REPLACE_IN_COMMENTS^
18101 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18102 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18103 If this option is specified, then comments are scanned and any $symbol
18104 substitutions performed as in program text. This is particularly useful
18105 when structured comments are used (e.g., when writing programs in the
18106 SPARK dialect of Ada). Note that this switch is not available when
18107 doing integrated preprocessing (it would be useless in this context
18108 since comments are ignored by the compiler in any case).
18109
18110 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18111 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18112 Defines a new preprocessing symbol, associated with value. If no value is given
18113 on the command line, then symbol is considered to be @code{True}. This switch
18114 can be used in place of a definition file.
18115
18116 @ifset vms
18117 @item /REMOVE
18118 @cindex @option{/REMOVE} (@command{gnatprep})
18119 This is the default setting which causes lines deleted by preprocessing
18120 to be entirely removed from the output file.
18121 @end ifset
18122
18123 @item ^-r^/REFERENCE^
18124 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18125 Causes a @code{Source_Reference} pragma to be generated that
18126 references the original input file, so that error messages will use
18127 the file name of this original file. The use of this switch implies
18128 that preprocessor lines are not to be removed from the file, so its
18129 use will force @option{^-b^/BLANK_LINES^} mode if
18130 @option{^-c^/COMMENTS^}
18131 has not been specified explicitly.
18132
18133 Note that if the file to be preprocessed contains multiple units, then
18134 it will be necessary to @code{gnatchop} the output file from
18135 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18136 in the preprocessed file, it will be respected by
18137 @code{gnatchop ^-r^/REFERENCE^}
18138 so that the final chopped files will correctly refer to the original
18139 input source file for @code{gnatprep}.
18140
18141 @item ^-s^/SYMBOLS^
18142 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18143 Causes a sorted list of symbol names and values to be
18144 listed on the standard output file.
18145
18146 @item ^-u^/UNDEFINED^
18147 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18148 Causes undefined symbols to be treated as having the value FALSE in the context
18149 of a preprocessor test. In the absence of this option, an undefined symbol in
18150 a @code{#if} or @code{#elsif} test will be treated as an error.
18151
18152 @end table
18153
18154 @ifclear vms
18155 @noindent
18156 Note: if neither @option{-b} nor @option{-c} is present,
18157 then preprocessor lines and
18158 deleted lines are completely removed from the output, unless -r is
18159 specified, in which case -b is assumed.
18160 @end ifclear
18161
18162 @node Form of Definitions File
18163 @section Form of Definitions File
18164
18165 @noindent
18166 The definitions file contains lines of the form
18167
18168 @smallexample
18169 symbol := value
18170 @end smallexample
18171
18172 @noindent
18173 where symbol is a preprocessing symbol, and value is one of the following:
18174
18175 @itemize @bullet
18176 @item
18177 Empty, corresponding to a null substitution
18178 @item
18179 A string literal using normal Ada syntax
18180 @item
18181 Any sequence of characters from the set
18182 (letters, digits, period, underline).
18183 @end itemize
18184
18185 @noindent
18186 Comment lines may also appear in the definitions file, starting with
18187 the usual @code{--},
18188 and comments may be added to the definitions lines.
18189
18190 @node Form of Input Text for gnatprep
18191 @section Form of Input Text for @code{gnatprep}
18192
18193 @noindent
18194 The input text may contain preprocessor conditional inclusion lines,
18195 as well as general symbol substitution sequences.
18196
18197 The preprocessor conditional inclusion commands have the form
18198
18199 @smallexample
18200 @group
18201 @cartouche
18202 #if @i{expression} @r{[}then@r{]}
18203 lines
18204 #elsif @i{expression} @r{[}then@r{]}
18205 lines
18206 #elsif @i{expression} @r{[}then@r{]}
18207 lines
18208 @dots{}
18209 #else
18210 lines
18211 #end if;
18212 @end cartouche
18213 @end group
18214 @end smallexample
18215
18216 @noindent
18217 In this example, @i{expression} is defined by the following grammar:
18218 @smallexample
18219 @i{expression} ::= <symbol>
18220 @i{expression} ::= <symbol> = "<value>"
18221 @i{expression} ::= <symbol> = <symbol>
18222 @i{expression} ::= <symbol> 'Defined
18223 @i{expression} ::= not @i{expression}
18224 @i{expression} ::= @i{expression} and @i{expression}
18225 @i{expression} ::= @i{expression} or @i{expression}
18226 @i{expression} ::= @i{expression} and then @i{expression}
18227 @i{expression} ::= @i{expression} or else @i{expression}
18228 @i{expression} ::= ( @i{expression} )
18229 @end smallexample
18230
18231 The following restriction exists: it is not allowed to have "and" or "or"
18232 following "not" in the same expression without parentheses. For example, this
18233 is not allowed:
18234
18235 @smallexample
18236 not X or Y
18237 @end smallexample
18238
18239 This should be one of the following:
18240
18241 @smallexample
18242 (not X) or Y
18243 not (X or Y)
18244 @end smallexample
18245
18246 @noindent
18247 For the first test (@i{expression} ::= <symbol>) the symbol must have
18248 either the value true or false, that is to say the right-hand of the
18249 symbol definition must be one of the (case-insensitive) literals
18250 @code{True} or @code{False}. If the value is true, then the
18251 corresponding lines are included, and if the value is false, they are
18252 excluded.
18253
18254 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18255 the symbol has been defined in the definition file or by a @option{-D}
18256 switch on the command line. Otherwise, the test is false.
18257
18258 The equality tests are case insensitive, as are all the preprocessor lines.
18259
18260 If the symbol referenced is not defined in the symbol definitions file,
18261 then the effect depends on whether or not switch @option{-u}
18262 is specified. If so, then the symbol is treated as if it had the value
18263 false and the test fails. If this switch is not specified, then
18264 it is an error to reference an undefined symbol. It is also an error to
18265 reference a symbol that is defined with a value other than @code{True}
18266 or @code{False}.
18267
18268 The use of the @code{not} operator inverts the sense of this logical test.
18269 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18270 operators, without parentheses. For example, "if not X or Y then" is not
18271 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18272
18273 The @code{then} keyword is optional as shown
18274
18275 The @code{#} must be the first non-blank character on a line, but
18276 otherwise the format is free form. Spaces or tabs may appear between
18277 the @code{#} and the keyword. The keywords and the symbols are case
18278 insensitive as in normal Ada code. Comments may be used on a
18279 preprocessor line, but other than that, no other tokens may appear on a
18280 preprocessor line. Any number of @code{elsif} clauses can be present,
18281 including none at all. The @code{else} is optional, as in Ada.
18282
18283 The @code{#} marking the start of a preprocessor line must be the first
18284 non-blank character on the line, i.e., it must be preceded only by
18285 spaces or horizontal tabs.
18286
18287 Symbol substitution outside of preprocessor lines is obtained by using
18288 the sequence
18289
18290 @smallexample
18291 $symbol
18292 @end smallexample
18293
18294 @noindent
18295 anywhere within a source line, except in a comment or within a
18296 string literal. The identifier
18297 following the @code{$} must match one of the symbols defined in the symbol
18298 definition file, and the result is to substitute the value of the
18299 symbol in place of @code{$symbol} in the output file.
18300
18301 Note that although the substitution of strings within a string literal
18302 is not possible, it is possible to have a symbol whose defined value is
18303 a string literal. So instead of setting XYZ to @code{hello} and writing:
18304
18305 @smallexample
18306 Header : String := "$XYZ";
18307 @end smallexample
18308
18309 @noindent
18310 you should set XYZ to @code{"hello"} and write:
18311
18312 @smallexample
18313 Header : String := $XYZ;
18314 @end smallexample
18315
18316 @noindent
18317 and then the substitution will occur as desired.
18318
18319 @ifset vms
18320 @node The GNAT Run-Time Library Builder gnatlbr
18321 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18322 @findex gnatlbr
18323 @cindex Library builder
18324
18325 @noindent
18326 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18327 supplied configuration pragmas.
18328
18329 @menu
18330 * Running gnatlbr::
18331 * Switches for gnatlbr::
18332 * Examples of gnatlbr Usage::
18333 @end menu
18334
18335 @node Running gnatlbr
18336 @section Running @code{gnatlbr}
18337
18338 @noindent
18339 The @code{gnatlbr} command has the form
18340
18341 @smallexample
18342 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18343 @end smallexample
18344
18345 @node Switches for gnatlbr
18346 @section Switches for @code{gnatlbr}
18347
18348 @noindent
18349 @code{gnatlbr} recognizes the following switches:
18350
18351 @table @option
18352 @c !sort!
18353 @item /CREATE=directory
18354 @cindex @code{/CREATE} (@code{gnatlbr})
18355 Create the new run-time library in the specified directory.
18356
18357 @item /SET=directory
18358 @cindex @code{/SET} (@code{gnatlbr})
18359 Make the library in the specified directory the current run-time library.
18360
18361 @item /DELETE=directory
18362 @cindex @code{/DELETE} (@code{gnatlbr})
18363 Delete the run-time library in the specified directory.
18364
18365 @item /CONFIG=file
18366 @cindex @code{/CONFIG} (@code{gnatlbr})
18367 With /CREATE: Use the configuration pragmas in the specified file when
18368 building the library.
18369
18370 With /SET: Use the configuration pragmas in the specified file when
18371 compiling.
18372
18373 @end table
18374
18375 @node Examples of gnatlbr Usage
18376 @section Example of @code{gnatlbr} Usage
18377
18378 @smallexample
18379 Contents of VAXFLOAT.ADC:
18380 pragma Float_Representation (VAX_Float);
18381
18382 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18383
18384 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18385
18386 @end smallexample
18387 @end ifset
18388
18389 @node The GNAT Library Browser gnatls
18390 @chapter The GNAT Library Browser @code{gnatls}
18391 @findex gnatls
18392 @cindex Library browser
18393
18394 @noindent
18395 @code{gnatls} is a tool that outputs information about compiled
18396 units. It gives the relationship between objects, unit names and source
18397 files. It can also be used to check the source dependencies of a unit
18398 as well as various characteristics.
18399
18400 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18401 driver (see @ref{The GNAT Driver and Project Files}).
18402
18403 @menu
18404 * Running gnatls::
18405 * Switches for gnatls::
18406 * Examples of gnatls Usage::
18407 @end menu
18408
18409 @node Running gnatls
18410 @section Running @code{gnatls}
18411
18412 @noindent
18413 The @code{gnatls} command has the form
18414
18415 @smallexample
18416 $ gnatls switches @var{object_or_ali_file}
18417 @end smallexample
18418
18419 @noindent
18420 The main argument is the list of object or @file{ali} files
18421 (@pxref{The Ada Library Information Files})
18422 for which information is requested.
18423
18424 In normal mode, without additional option, @code{gnatls} produces a
18425 four-column listing. Each line represents information for a specific
18426 object. The first column gives the full path of the object, the second
18427 column gives the name of the principal unit in this object, the third
18428 column gives the status of the source and the fourth column gives the
18429 full path of the source representing this unit.
18430 Here is a simple example of use:
18431
18432 @smallexample
18433 $ gnatls *.o
18434 ^./^[]^demo1.o demo1 DIF demo1.adb
18435 ^./^[]^demo2.o demo2 OK demo2.adb
18436 ^./^[]^hello.o h1 OK hello.adb
18437 ^./^[]^instr-child.o instr.child MOK instr-child.adb
18438 ^./^[]^instr.o instr OK instr.adb
18439 ^./^[]^tef.o tef DIF tef.adb
18440 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
18441 ^./^[]^tgef.o tgef DIF tgef.adb
18442 @end smallexample
18443
18444 @noindent
18445 The first line can be interpreted as follows: the main unit which is
18446 contained in
18447 object file @file{demo1.o} is demo1, whose main source is in
18448 @file{demo1.adb}. Furthermore, the version of the source used for the
18449 compilation of demo1 has been modified (DIF). Each source file has a status
18450 qualifier which can be:
18451
18452 @table @code
18453 @item OK (unchanged)
18454 The version of the source file used for the compilation of the
18455 specified unit corresponds exactly to the actual source file.
18456
18457 @item MOK (slightly modified)
18458 The version of the source file used for the compilation of the
18459 specified unit differs from the actual source file but not enough to
18460 require recompilation. If you use gnatmake with the qualifier
18461 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18462 MOK will not be recompiled.
18463
18464 @item DIF (modified)
18465 No version of the source found on the path corresponds to the source
18466 used to build this object.
18467
18468 @item ??? (file not found)
18469 No source file was found for this unit.
18470
18471 @item HID (hidden, unchanged version not first on PATH)
18472 The version of the source that corresponds exactly to the source used
18473 for compilation has been found on the path but it is hidden by another
18474 version of the same source that has been modified.
18475
18476 @end table
18477
18478 @node Switches for gnatls
18479 @section Switches for @code{gnatls}
18480
18481 @noindent
18482 @code{gnatls} recognizes the following switches:
18483
18484 @table @option
18485 @c !sort!
18486 @cindex @option{--version} @command{gnatls}
18487 Display Copyright and version, then exit disregarding all other options.
18488
18489 @item --help
18490 @cindex @option{--help} @command{gnatls}
18491 If @option{--version} was not used, display usage, then exit disregarding
18492 all other options.
18493
18494 @item ^-a^/ALL_UNITS^
18495 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18496 Consider all units, including those of the predefined Ada library.
18497 Especially useful with @option{^-d^/DEPENDENCIES^}.
18498
18499 @item ^-d^/DEPENDENCIES^
18500 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18501 List sources from which specified units depend on.
18502
18503 @item ^-h^/OUTPUT=OPTIONS^
18504 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18505 Output the list of options.
18506
18507 @item ^-o^/OUTPUT=OBJECTS^
18508 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18509 Only output information about object files.
18510
18511 @item ^-s^/OUTPUT=SOURCES^
18512 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18513 Only output information about source files.
18514
18515 @item ^-u^/OUTPUT=UNITS^
18516 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18517 Only output information about compilation units.
18518
18519 @item ^-files^/FILES^=@var{file}
18520 @cindex @option{^-files^/FILES^} (@code{gnatls})
18521 Take as arguments the files listed in text file @var{file}.
18522 Text file @var{file} may contain empty lines that are ignored.
18523 Each nonempty line should contain the name of an existing file.
18524 Several such switches may be specified simultaneously.
18525
18526 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18527 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18528 @itemx ^-I^/SEARCH=^@var{dir}
18529 @itemx ^-I-^/NOCURRENT_DIRECTORY^
18530 @itemx -nostdinc
18531 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18532 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18533 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18534 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18535 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18536 flags (@pxref{Switches for gnatmake}).
18537
18538 @item --RTS=@var{rts-path}
18539 @cindex @option{--RTS} (@code{gnatls})
18540 Specifies the default location of the runtime library. Same meaning as the
18541 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18542
18543 @item ^-v^/OUTPUT=VERBOSE^
18544 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18545 Verbose mode. Output the complete source, object and project paths. Do not use
18546 the default column layout but instead use long format giving as much as
18547 information possible on each requested units, including special
18548 characteristics such as:
18549
18550 @table @code
18551 @item Preelaborable
18552 The unit is preelaborable in the Ada sense.
18553
18554 @item No_Elab_Code
18555 No elaboration code has been produced by the compiler for this unit.
18556
18557 @item Pure
18558 The unit is pure in the Ada sense.
18559
18560 @item Elaborate_Body
18561 The unit contains a pragma Elaborate_Body.
18562
18563 @item Remote_Types
18564 The unit contains a pragma Remote_Types.
18565
18566 @item Shared_Passive
18567 The unit contains a pragma Shared_Passive.
18568
18569 @item Predefined
18570 This unit is part of the predefined environment and cannot be modified
18571 by the user.
18572
18573 @item Remote_Call_Interface
18574 The unit contains a pragma Remote_Call_Interface.
18575
18576 @end table
18577
18578 @end table
18579
18580 @node Examples of gnatls Usage
18581 @section Example of @code{gnatls} Usage
18582 @ifclear vms
18583
18584 @noindent
18585 Example of using the verbose switch. Note how the source and
18586 object paths are affected by the -I switch.
18587
18588 @smallexample
18589 $ gnatls -v -I.. demo1.o
18590
18591 GNATLS 5.03w (20041123-34)
18592 Copyright 1997-2004 Free Software Foundation, Inc.
18593
18594 Source Search Path:
18595 <Current_Directory>
18596 ../
18597 /home/comar/local/adainclude/
18598
18599 Object Search Path:
18600 <Current_Directory>
18601 ../
18602 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18603
18604 Project Search Path:
18605 <Current_Directory>
18606 /home/comar/local/lib/gnat/
18607
18608 ./demo1.o
18609 Unit =>
18610 Name => demo1
18611 Kind => subprogram body
18612 Flags => No_Elab_Code
18613 Source => demo1.adb modified
18614 @end smallexample
18615
18616 @noindent
18617 The following is an example of use of the dependency list.
18618 Note the use of the -s switch
18619 which gives a straight list of source files. This can be useful for
18620 building specialized scripts.
18621
18622 @smallexample
18623 $ gnatls -d demo2.o
18624 ./demo2.o demo2 OK demo2.adb
18625 OK gen_list.ads
18626 OK gen_list.adb
18627 OK instr.ads
18628 OK instr-child.ads
18629
18630 $ gnatls -d -s -a demo1.o
18631 demo1.adb
18632 /home/comar/local/adainclude/ada.ads
18633 /home/comar/local/adainclude/a-finali.ads
18634 /home/comar/local/adainclude/a-filico.ads
18635 /home/comar/local/adainclude/a-stream.ads
18636 /home/comar/local/adainclude/a-tags.ads
18637 gen_list.ads
18638 gen_list.adb
18639 /home/comar/local/adainclude/gnat.ads
18640 /home/comar/local/adainclude/g-io.ads
18641 instr.ads
18642 /home/comar/local/adainclude/system.ads
18643 /home/comar/local/adainclude/s-exctab.ads
18644 /home/comar/local/adainclude/s-finimp.ads
18645 /home/comar/local/adainclude/s-finroo.ads
18646 /home/comar/local/adainclude/s-secsta.ads
18647 /home/comar/local/adainclude/s-stalib.ads
18648 /home/comar/local/adainclude/s-stoele.ads
18649 /home/comar/local/adainclude/s-stratt.ads
18650 /home/comar/local/adainclude/s-tasoli.ads
18651 /home/comar/local/adainclude/s-unstyp.ads
18652 /home/comar/local/adainclude/unchconv.ads
18653 @end smallexample
18654 @end ifclear
18655
18656 @ifset vms
18657 @smallexample
18658 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18659
18660 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18661 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18662 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18663 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18664 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18665 demo1.adb
18666 gen_list.ads
18667 gen_list.adb
18668 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18669 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18670 instr.ads
18671 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18672 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18673 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18674 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18675 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18676 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18677 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18678 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18679 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18680 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18681 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18682 @end smallexample
18683 @end ifset
18684
18685 @node Cleaning Up Using gnatclean
18686 @chapter Cleaning Up Using @code{gnatclean}
18687 @findex gnatclean
18688 @cindex Cleaning tool
18689
18690 @noindent
18691 @code{gnatclean} is a tool that allows the deletion of files produced by the
18692 compiler, binder and linker, including ALI files, object files, tree files,
18693 expanded source files, library files, interface copy source files, binder
18694 generated files and executable files.
18695
18696 @menu
18697 * Running gnatclean::
18698 * Switches for gnatclean::
18699 @c * Examples of gnatclean Usage::
18700 @end menu
18701
18702 @node Running gnatclean
18703 @section Running @code{gnatclean}
18704
18705 @noindent
18706 The @code{gnatclean} command has the form:
18707
18708 @smallexample
18709 $ gnatclean switches @var{names}
18710 @end smallexample
18711
18712 @noindent
18713 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18714 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18715 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18716
18717 @noindent
18718 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18719 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18720 the linker. In informative-only mode, specified by switch
18721 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18722 normal mode is listed, but no file is actually deleted.
18723
18724 @node Switches for gnatclean
18725 @section Switches for @code{gnatclean}
18726
18727 @noindent
18728 @code{gnatclean} recognizes the following switches:
18729
18730 @table @option
18731 @c !sort!
18732 @cindex @option{--version} @command{gnatclean}
18733 Display Copyright and version, then exit disregarding all other options.
18734
18735 @item --help
18736 @cindex @option{--help} @command{gnatclean}
18737 If @option{--version} was not used, display usage, then exit disregarding
18738 all other options.
18739
18740 @item ^-c^/COMPILER_FILES_ONLY^
18741 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18742 Only attempt to delete the files produced by the compiler, not those produced
18743 by the binder or the linker. The files that are not to be deleted are library
18744 files, interface copy files, binder generated files and executable files.
18745
18746 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18747 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18748 Indicate that ALI and object files should normally be found in directory
18749 @var{dir}.
18750
18751 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18752 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18753 When using project files, if some errors or warnings are detected during
18754 parsing and verbose mode is not in effect (no use of switch
18755 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18756 file, rather than its simple file name.
18757
18758 @item ^-h^/HELP^
18759 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18760 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18761
18762 @item ^-n^/NODELETE^
18763 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18764 Informative-only mode. Do not delete any files. Output the list of the files
18765 that would have been deleted if this switch was not specified.
18766
18767 @item ^-P^/PROJECT_FILE=^@var{project}
18768 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18769 Use project file @var{project}. Only one such switch can be used.
18770 When cleaning a project file, the files produced by the compilation of the
18771 immediate sources or inherited sources of the project files are to be
18772 deleted. This is not depending on the presence or not of executable names
18773 on the command line.
18774
18775 @item ^-q^/QUIET^
18776 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18777 Quiet output. If there are no errors, do not output anything, except in
18778 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18779 (switch ^-n^/NODELETE^).
18780
18781 @item ^-r^/RECURSIVE^
18782 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18783 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18784 clean all imported and extended project files, recursively. If this switch
18785 is not specified, only the files related to the main project file are to be
18786 deleted. This switch has no effect if no project file is specified.
18787
18788 @item ^-v^/VERBOSE^
18789 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18790 Verbose mode.
18791
18792 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18793 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18794 Indicates the verbosity of the parsing of GNAT project files.
18795 @xref{Switches Related to Project Files}.
18796
18797 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18798 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18799 Indicates that external variable @var{name} has the value @var{value}.
18800 The Project Manager will use this value for occurrences of
18801 @code{external(name)} when parsing the project file.
18802 @xref{Switches Related to Project Files}.
18803
18804 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18805 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18806 When searching for ALI and object files, look in directory
18807 @var{dir}.
18808
18809 @item ^-I^/SEARCH=^@var{dir}
18810 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18811 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18812
18813 @item ^-I-^/NOCURRENT_DIRECTORY^
18814 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18815 @cindex Source files, suppressing search
18816 Do not look for ALI or object files in the directory
18817 where @code{gnatclean} was invoked.
18818
18819 @end table
18820
18821 @c @node Examples of gnatclean Usage
18822 @c @section Examples of @code{gnatclean} Usage
18823
18824 @ifclear vms
18825 @node GNAT and Libraries
18826 @chapter GNAT and Libraries
18827 @cindex Library, building, installing, using
18828
18829 @noindent
18830 This chapter describes how to build and use libraries with GNAT, and also shows
18831 how to recompile the GNAT run-time library. You should be familiar with the
18832 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18833 chapter.
18834
18835 @menu
18836 * Introduction to Libraries in GNAT::
18837 * General Ada Libraries::
18838 * Stand-alone Ada Libraries::
18839 * Rebuilding the GNAT Run-Time Library::
18840 @end menu
18841
18842 @node Introduction to Libraries in GNAT
18843 @section Introduction to Libraries in GNAT
18844
18845 @noindent
18846 A library is, conceptually, a collection of objects which does not have its
18847 own main thread of execution, but rather provides certain services to the
18848 applications that use it. A library can be either statically linked with the
18849 application, in which case its code is directly included in the application,
18850 or, on platforms that support it, be dynamically linked, in which case
18851 its code is shared by all applications making use of this library.
18852
18853 GNAT supports both types of libraries.
18854 In the static case, the compiled code can be provided in different ways. The
18855 simplest approach is to provide directly the set of objects resulting from
18856 compilation of the library source files. Alternatively, you can group the
18857 objects into an archive using whatever commands are provided by the operating
18858 system. For the latter case, the objects are grouped into a shared library.
18859
18860 In the GNAT environment, a library has three types of components:
18861 @itemize @bullet
18862 @item
18863 Source files.
18864 @item
18865 @file{ALI} files.
18866 @xref{The Ada Library Information Files}.
18867 @item
18868 Object files, an archive or a shared library.
18869 @end itemize
18870
18871 @noindent
18872 A GNAT library may expose all its source files, which is useful for
18873 documentation purposes. Alternatively, it may expose only the units needed by
18874 an external user to make use of the library. That is to say, the specs
18875 reflecting the library services along with all the units needed to compile
18876 those specs, which can include generic bodies or any body implementing an
18877 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18878 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18879
18880 All compilation units comprising an application, including those in a library,
18881 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18882 computes the elaboration order from the @file{ALI} files and this is why they
18883 constitute a mandatory part of GNAT libraries. Except in the case of
18884 @emph{stand-alone libraries}, where a specific library elaboration routine is
18885 produced independently of the application(s) using the library.
18886
18887 @node General Ada Libraries
18888 @section General Ada Libraries
18889
18890 @menu
18891 * Building a library::
18892 * Installing a library::
18893 * Using a library::
18894 @end menu
18895
18896 @node Building a library
18897 @subsection Building a library
18898
18899 @noindent
18900 The easiest way to build a library is to use the Project Manager,
18901 which supports a special type of project called a @emph{Library Project}
18902 (@pxref{Library Projects}).
18903
18904 A project is considered a library project, when two project-level attributes
18905 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18906 control different aspects of library configuration, additional optional
18907 project-level attributes can be specified:
18908 @table @code
18909 @item Library_Kind
18910 This attribute controls whether the library is to be static or dynamic
18911
18912 @item Library_Version
18913 This attribute specifies the library version; this value is used
18914 during dynamic linking of shared libraries to determine if the currently
18915 installed versions of the binaries are compatible.
18916
18917 @item Library_Options
18918 @item Library_GCC
18919 These attributes specify additional low-level options to be used during
18920 library generation, and redefine the actual application used to generate
18921 library.
18922 @end table
18923
18924 @noindent
18925 The GNAT Project Manager takes full care of the library maintenance task,
18926 including recompilation of the source files for which objects do not exist
18927 or are not up to date, assembly of the library archive, and installation of
18928 the library (i.e., copying associated source, object and @file{ALI} files
18929 to the specified location).
18930
18931 Here is a simple library project file:
18932 @smallexample @c ada
18933 project My_Lib is
18934 for Source_Dirs use ("src1", "src2");
18935 for Object_Dir use "obj";
18936 for Library_Name use "mylib";
18937 for Library_Dir use "lib";
18938 for Library_Kind use "dynamic";
18939 end My_lib;
18940 @end smallexample
18941
18942 @noindent
18943 and the compilation command to build and install the library:
18944
18945 @smallexample @c ada
18946 $ gnatmake -Pmy_lib
18947 @end smallexample
18948
18949 @noindent
18950 It is not entirely trivial to perform manually all the steps required to
18951 produce a library. We recommend that you use the GNAT Project Manager
18952 for this task. In special cases where this is not desired, the necessary
18953 steps are discussed below.
18954
18955 There are various possibilities for compiling the units that make up the
18956 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18957 with a conventional script. For simple libraries, it is also possible to create
18958 a dummy main program which depends upon all the packages that comprise the
18959 interface of the library. This dummy main program can then be given to
18960 @command{gnatmake}, which will ensure that all necessary objects are built.
18961
18962 After this task is accomplished, you should follow the standard procedure
18963 of the underlying operating system to produce the static or shared library.
18964
18965 Here is an example of such a dummy program:
18966 @smallexample @c ada
18967 @group
18968 with My_Lib.Service1;
18969 with My_Lib.Service2;
18970 with My_Lib.Service3;
18971 procedure My_Lib_Dummy is
18972 begin
18973 null;
18974 end;
18975 @end group
18976 @end smallexample
18977
18978 @noindent
18979 Here are the generic commands that will build an archive or a shared library.
18980
18981 @smallexample
18982 # compiling the library
18983 $ gnatmake -c my_lib_dummy.adb
18984
18985 # we don't need the dummy object itself
18986 $ rm my_lib_dummy.o my_lib_dummy.ali
18987
18988 # create an archive with the remaining objects
18989 $ ar rc libmy_lib.a *.o
18990 # some systems may require "ranlib" to be run as well
18991
18992 # or create a shared library
18993 $ gcc -shared -o libmy_lib.so *.o
18994 # some systems may require the code to have been compiled with -fPIC
18995
18996 # remove the object files that are now in the library
18997 $ rm *.o
18998
18999 # Make the ALI files read-only so that gnatmake will not try to
19000 # regenerate the objects that are in the library
19001 $ chmod -w *.ali
19002 @end smallexample
19003
19004 @noindent
19005 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19006 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19007 be accessed by the directive @option{-l@var{xxx}} at link time.
19008
19009 @node Installing a library
19010 @subsection Installing a library
19011 @cindex @code{ADA_PROJECT_PATH}
19012
19013 @noindent
19014 If you use project files, library installation is part of the library build
19015 process. Thus no further action is needed in order to make use of the
19016 libraries that are built as part of the general application build. A usable
19017 version of the library is installed in the directory specified by the
19018 @code{Library_Dir} attribute of the library project file.
19019
19020 You may want to install a library in a context different from where the library
19021 is built. This situation arises with third party suppliers, who may want
19022 to distribute a library in binary form where the user is not expected to be
19023 able to recompile the library. The simplest option in this case is to provide
19024 a project file slightly different from the one used to build the library, by
19025 using the @code{externally_built} attribute. For instance, the project
19026 file used to build the library in the previous section can be changed into the
19027 following one when the library is installed:
19028
19029 @smallexample @c projectfile
19030 project My_Lib is
19031 for Source_Dirs use ("src1", "src2");
19032 for Library_Name use "mylib";
19033 for Library_Dir use "lib";
19034 for Library_Kind use "dynamic";
19035 for Externally_Built use "true";
19036 end My_lib;
19037 @end smallexample
19038
19039 @noindent
19040 This project file assumes that the directories @file{src1},
19041 @file{src2}, and @file{lib} exist in
19042 the directory containing the project file. The @code{externally_built}
19043 attribute makes it clear to the GNAT builder that it should not attempt to
19044 recompile any of the units from this library. It allows the library provider to
19045 restrict the source set to the minimum necessary for clients to make use of the
19046 library as described in the first section of this chapter. It is the
19047 responsibility of the library provider to install the necessary sources, ALI
19048 files and libraries in the directories mentioned in the project file. For
19049 convenience, the user's library project file should be installed in a location
19050 that will be searched automatically by the GNAT
19051 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
19052 environment variable (@pxref{Importing Projects}), and also the default GNAT
19053 library location that can be queried with @command{gnatls -v} and is usually of
19054 the form $gnat_install_root/lib/gnat.
19055
19056 When project files are not an option, it is also possible, but not recommended,
19057 to install the library so that the sources needed to use the library are on the
19058 Ada source path and the ALI files & libraries be on the Ada Object path (see
19059 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19060 administrator can place general-purpose libraries in the default compiler
19061 paths, by specifying the libraries' location in the configuration files
19062 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19063 must be located in the GNAT installation tree at the same place as the gcc spec
19064 file. The location of the gcc spec file can be determined as follows:
19065 @smallexample
19066 $ gcc -v
19067 @end smallexample
19068
19069 @noindent
19070 The configuration files mentioned above have a simple format: each line
19071 must contain one unique directory name.
19072 Those names are added to the corresponding path
19073 in their order of appearance in the file. The names can be either absolute
19074 or relative; in the latter case, they are relative to where theses files
19075 are located.
19076
19077 The files @file{ada_source_path} and @file{ada_object_path} might not be
19078 present in a
19079 GNAT installation, in which case, GNAT will look for its run-time library in
19080 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19081 objects and @file{ALI} files). When the files exist, the compiler does not
19082 look in @file{adainclude} and @file{adalib}, and thus the
19083 @file{ada_source_path} file
19084 must contain the location for the GNAT run-time sources (which can simply
19085 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19086 contain the location for the GNAT run-time objects (which can simply
19087 be @file{adalib}).
19088
19089 You can also specify a new default path to the run-time library at compilation
19090 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19091 the run-time library you want your program to be compiled with. This switch is
19092 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19093 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19094
19095 It is possible to install a library before or after the standard GNAT
19096 library, by reordering the lines in the configuration files. In general, a
19097 library must be installed before the GNAT library if it redefines
19098 any part of it.
19099
19100 @node Using a library
19101 @subsection Using a library
19102
19103 @noindent Once again, the project facility greatly simplifies the use of
19104 libraries. In this context, using a library is just a matter of adding a
19105 @code{with} clause in the user project. For instance, to make use of the
19106 library @code{My_Lib} shown in examples in earlier sections, you can
19107 write:
19108
19109 @smallexample @c projectfile
19110 with "my_lib";
19111 project My_Proj is
19112 @dots{}
19113 end My_Proj;
19114 @end smallexample
19115
19116 Even if you have a third-party, non-Ada library, you can still use GNAT's
19117 Project Manager facility to provide a wrapper for it. For example, the
19118 following project, when @code{with}ed by your main project, will link with the
19119 third-party library @file{liba.a}:
19120
19121 @smallexample @c projectfile
19122 @group
19123 project Liba is
19124 for Externally_Built use "true";
19125 for Source_Files use ();
19126 for Library_Dir use "lib";
19127 for Library_Name use "a";
19128 for Library_Kind use "static";
19129 end Liba;
19130 @end group
19131 @end smallexample
19132 This is an alternative to the use of @code{pragma Linker_Options}. It is
19133 especially interesting in the context of systems with several interdependent
19134 static libraries where finding a proper linker order is not easy and best be
19135 left to the tools having visibility over project dependence information.
19136
19137 @noindent
19138 In order to use an Ada library manually, you need to make sure that this
19139 library is on both your source and object path
19140 (see @ref{Search Paths and the Run-Time Library (RTL)}
19141 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19142 in an archive or a shared library, you need to specify the desired
19143 library at link time.
19144
19145 For example, you can use the library @file{mylib} installed in
19146 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19147
19148 @smallexample
19149 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19150 -largs -lmy_lib
19151 @end smallexample
19152
19153 @noindent
19154 This can be expressed more simply:
19155 @smallexample
19156 $ gnatmake my_appl
19157 @end smallexample
19158 @noindent
19159 when the following conditions are met:
19160 @itemize @bullet
19161 @item
19162 @file{/dir/my_lib_src} has been added by the user to the environment
19163 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19164 @file{ada_source_path}
19165 @item
19166 @file{/dir/my_lib_obj} has been added by the user to the environment
19167 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19168 @file{ada_object_path}
19169 @item
19170 a pragma @code{Linker_Options} has been added to one of the sources.
19171 For example:
19172
19173 @smallexample @c ada
19174 pragma Linker_Options ("-lmy_lib");
19175 @end smallexample
19176 @end itemize
19177
19178 @node Stand-alone Ada Libraries
19179 @section Stand-alone Ada Libraries
19180 @cindex Stand-alone library, building, using
19181
19182 @menu
19183 * Introduction to Stand-alone Libraries::
19184 * Building a Stand-alone Library::
19185 * Creating a Stand-alone Library to be used in a non-Ada context::
19186 * Restrictions in Stand-alone Libraries::
19187 @end menu
19188
19189 @node Introduction to Stand-alone Libraries
19190 @subsection Introduction to Stand-alone Libraries
19191
19192 @noindent
19193 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19194 necessary code to
19195 elaborate the Ada units that are included in the library. In contrast with
19196 an ordinary library, which consists of all sources, objects and @file{ALI}
19197 files of the
19198 library, a SAL may specify a restricted subset of compilation units
19199 to serve as a library interface. In this case, the fully
19200 self-sufficient set of files will normally consist of an objects
19201 archive, the sources of interface units' specs, and the @file{ALI}
19202 files of interface units.
19203 If an interface spec contains a generic unit or an inlined subprogram,
19204 the body's
19205 source must also be provided; if the units that must be provided in the source
19206 form depend on other units, the source and @file{ALI} files of those must
19207 also be provided.
19208
19209 The main purpose of a SAL is to minimize the recompilation overhead of client
19210 applications when a new version of the library is installed. Specifically,
19211 if the interface sources have not changed, client applications do not need to
19212 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19213 version, controlled by @code{Library_Version} attribute, is not changed,
19214 then the clients do not need to be relinked.
19215
19216 SALs also allow the library providers to minimize the amount of library source
19217 text exposed to the clients. Such ``information hiding'' might be useful or
19218 necessary for various reasons.
19219
19220 Stand-alone libraries are also well suited to be used in an executable whose
19221 main routine is not written in Ada.
19222
19223 @node Building a Stand-alone Library
19224 @subsection Building a Stand-alone Library
19225
19226 @noindent
19227 GNAT's Project facility provides a simple way of building and installing
19228 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19229 To be a Stand-alone Library Project, in addition to the two attributes
19230 that make a project a Library Project (@code{Library_Name} and
19231 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19232 @code{Library_Interface} must be defined. For example:
19233
19234 @smallexample @c projectfile
19235 @group
19236 for Library_Dir use "lib_dir";
19237 for Library_Name use "dummy";
19238 for Library_Interface use ("int1", "int1.child");
19239 @end group
19240 @end smallexample
19241
19242 @noindent
19243 Attribute @code{Library_Interface} has a non-empty string list value,
19244 each string in the list designating a unit contained in an immediate source
19245 of the project file.
19246
19247 When a Stand-alone Library is built, first the binder is invoked to build
19248 a package whose name depends on the library name
19249 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19250 This binder-generated package includes initialization and
19251 finalization procedures whose
19252 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19253 in the example
19254 above). The object corresponding to this package is included in the library.
19255
19256 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19257 calling of these procedures if a static SAL is built, or if a shared SAL
19258 is built
19259 with the project-level attribute @code{Library_Auto_Init} set to
19260 @code{"false"}.
19261
19262 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19263 (those that are listed in attribute @code{Library_Interface}) are copied to
19264 the Library Directory. As a consequence, only the Interface Units may be
19265 imported from Ada units outside of the library. If other units are imported,
19266 the binding phase will fail.
19267
19268 The attribute @code{Library_Src_Dir} may be specified for a
19269 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19270 single string value. Its value must be the path (absolute or relative to the
19271 project directory) of an existing directory. This directory cannot be the
19272 object directory or one of the source directories, but it can be the same as
19273 the library directory. The sources of the Interface
19274 Units of the library that are needed by an Ada client of the library will be
19275 copied to the designated directory, called the Interface Copy directory.
19276 These sources include the specs of the Interface Units, but they may also
19277 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19278 are used, or when there is a generic unit in the spec. Before the sources
19279 are copied to the Interface Copy directory, an attempt is made to delete all
19280 files in the Interface Copy directory.
19281
19282 Building stand-alone libraries by hand is somewhat tedious, but for those
19283 occasions when it is necessary here are the steps that you need to perform:
19284 @itemize @bullet
19285 @item
19286 Compile all library sources.
19287
19288 @item
19289 Invoke the binder with the switch @option{-n} (No Ada main program),
19290 with all the @file{ALI} files of the interfaces, and
19291 with the switch @option{-L} to give specific names to the @code{init}
19292 and @code{final} procedures. For example:
19293 @smallexample
19294 gnatbind -n int1.ali int2.ali -Lsal1
19295 @end smallexample
19296
19297 @item
19298 Compile the binder generated file:
19299 @smallexample
19300 gcc -c b~int2.adb
19301 @end smallexample
19302
19303 @item
19304 Link the dynamic library with all the necessary object files,
19305 indicating to the linker the names of the @code{init} (and possibly
19306 @code{final}) procedures for automatic initialization (and finalization).
19307 The built library should be placed in a directory different from
19308 the object directory.
19309
19310 @item
19311 Copy the @code{ALI} files of the interface to the library directory,
19312 add in this copy an indication that it is an interface to a SAL
19313 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19314 with letter ``P'') and make the modified copy of the @file{ALI} file
19315 read-only.
19316 @end itemize
19317
19318 @noindent
19319 Using SALs is not different from using other libraries
19320 (see @ref{Using a library}).
19321
19322 @node Creating a Stand-alone Library to be used in a non-Ada context
19323 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19324
19325 @noindent
19326 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19327 a non-Ada context.
19328
19329 The only extra step required is to ensure that library interface subprograms
19330 are compatible with the main program, by means of @code{pragma Export}
19331 or @code{pragma Convention}.
19332
19333 Here is an example of simple library interface for use with C main program:
19334
19335 @smallexample @c ada
19336 package Interface is
19337
19338 procedure Do_Something;
19339 pragma Export (C, Do_Something, "do_something");
19340
19341 procedure Do_Something_Else;
19342 pragma Export (C, Do_Something_Else, "do_something_else");
19343
19344 end Interface;
19345 @end smallexample
19346
19347 @noindent
19348 On the foreign language side, you must provide a ``foreign'' view of the
19349 library interface; remember that it should contain elaboration routines in
19350 addition to interface subprograms.
19351
19352 The example below shows the content of @code{mylib_interface.h} (note
19353 that there is no rule for the naming of this file, any name can be used)
19354 @smallexample
19355 /* the library elaboration procedure */
19356 extern void mylibinit (void);
19357
19358 /* the library finalization procedure */
19359 extern void mylibfinal (void);
19360
19361 /* the interface exported by the library */
19362 extern void do_something (void);
19363 extern void do_something_else (void);
19364 @end smallexample
19365
19366 @noindent
19367 Libraries built as explained above can be used from any program, provided
19368 that the elaboration procedures (named @code{mylibinit} in the previous
19369 example) are called before the library services are used. Any number of
19370 libraries can be used simultaneously, as long as the elaboration
19371 procedure of each library is called.
19372
19373 Below is an example of a C program that uses the @code{mylib} library.
19374
19375 @smallexample
19376 #include "mylib_interface.h"
19377
19378 int
19379 main (void)
19380 @{
19381 /* First, elaborate the library before using it */
19382 mylibinit ();
19383
19384 /* Main program, using the library exported entities */
19385 do_something ();
19386 do_something_else ();
19387
19388 /* Library finalization at the end of the program */
19389 mylibfinal ();
19390 return 0;
19391 @}
19392 @end smallexample
19393
19394 @noindent
19395 Note that invoking any library finalization procedure generated by
19396 @code{gnatbind} shuts down the Ada run-time environment.
19397 Consequently, the
19398 finalization of all Ada libraries must be performed at the end of the program.
19399 No call to these libraries or to the Ada run-time library should be made
19400 after the finalization phase.
19401
19402 @node Restrictions in Stand-alone Libraries
19403 @subsection Restrictions in Stand-alone Libraries
19404
19405 @noindent
19406 The pragmas listed below should be used with caution inside libraries,
19407 as they can create incompatibilities with other Ada libraries:
19408 @itemize @bullet
19409 @item pragma @code{Locking_Policy}
19410 @item pragma @code{Queuing_Policy}
19411 @item pragma @code{Task_Dispatching_Policy}
19412 @item pragma @code{Unreserve_All_Interrupts}
19413 @end itemize
19414
19415 @noindent
19416 When using a library that contains such pragmas, the user must make sure
19417 that all libraries use the same pragmas with the same values. Otherwise,
19418 @code{Program_Error} will
19419 be raised during the elaboration of the conflicting
19420 libraries. The usage of these pragmas and its consequences for the user
19421 should therefore be well documented.
19422
19423 Similarly, the traceback in the exception occurrence mechanism should be
19424 enabled or disabled in a consistent manner across all libraries.
19425 Otherwise, Program_Error will be raised during the elaboration of the
19426 conflicting libraries.
19427
19428 If the @code{Version} or @code{Body_Version}
19429 attributes are used inside a library, then you need to
19430 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19431 libraries, so that version identifiers can be properly computed.
19432 In practice these attributes are rarely used, so this is unlikely
19433 to be a consideration.
19434
19435 @node Rebuilding the GNAT Run-Time Library
19436 @section Rebuilding the GNAT Run-Time Library
19437 @cindex GNAT Run-Time Library, rebuilding
19438 @cindex Building the GNAT Run-Time Library
19439 @cindex Rebuilding the GNAT Run-Time Library
19440 @cindex Run-Time Library, rebuilding
19441
19442 @noindent
19443 It may be useful to recompile the GNAT library in various contexts, the
19444 most important one being the use of partition-wide configuration pragmas
19445 such as @code{Normalize_Scalars}. A special Makefile called
19446 @code{Makefile.adalib} is provided to that effect and can be found in
19447 the directory containing the GNAT library. The location of this
19448 directory depends on the way the GNAT environment has been installed and can
19449 be determined by means of the command:
19450
19451 @smallexample
19452 $ gnatls -v
19453 @end smallexample
19454
19455 @noindent
19456 The last entry in the object search path usually contains the
19457 gnat library. This Makefile contains its own documentation and in
19458 particular the set of instructions needed to rebuild a new library and
19459 to use it.
19460
19461 @node Using the GNU make Utility
19462 @chapter Using the GNU @code{make} Utility
19463 @findex make
19464
19465 @noindent
19466 This chapter offers some examples of makefiles that solve specific
19467 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19468 make, make, GNU @code{make}}), nor does it try to replace the
19469 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19470
19471 All the examples in this section are specific to the GNU version of
19472 make. Although @command{make} is a standard utility, and the basic language
19473 is the same, these examples use some advanced features found only in
19474 @code{GNU make}.
19475
19476 @menu
19477 * Using gnatmake in a Makefile::
19478 * Automatically Creating a List of Directories::
19479 * Generating the Command Line Switches::
19480 * Overcoming Command Line Length Limits::
19481 @end menu
19482
19483 @node Using gnatmake in a Makefile
19484 @section Using gnatmake in a Makefile
19485 @findex makefile
19486 @cindex GNU make
19487
19488 @noindent
19489 Complex project organizations can be handled in a very powerful way by
19490 using GNU make combined with gnatmake. For instance, here is a Makefile
19491 which allows you to build each subsystem of a big project into a separate
19492 shared library. Such a makefile allows you to significantly reduce the link
19493 time of very big applications while maintaining full coherence at
19494 each step of the build process.
19495
19496 The list of dependencies are handled automatically by
19497 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19498 the appropriate directories.
19499
19500 Note that you should also read the example on how to automatically
19501 create the list of directories
19502 (@pxref{Automatically Creating a List of Directories})
19503 which might help you in case your project has a lot of subdirectories.
19504
19505 @smallexample
19506 @iftex
19507 @leftskip=0cm
19508 @font@heightrm=cmr8
19509 @heightrm
19510 @end iftex
19511 ## This Makefile is intended to be used with the following directory
19512 ## configuration:
19513 ## - The sources are split into a series of csc (computer software components)
19514 ## Each of these csc is put in its own directory.
19515 ## Their name are referenced by the directory names.
19516 ## They will be compiled into shared library (although this would also work
19517 ## with static libraries
19518 ## - The main program (and possibly other packages that do not belong to any
19519 ## csc is put in the top level directory (where the Makefile is).
19520 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
19521 ## \_ second_csc (sources) __ lib (will contain the library)
19522 ## \_ @dots{}
19523 ## Although this Makefile is build for shared library, it is easy to modify
19524 ## to build partial link objects instead (modify the lines with -shared and
19525 ## gnatlink below)
19526 ##
19527 ## With this makefile, you can change any file in the system or add any new
19528 ## file, and everything will be recompiled correctly (only the relevant shared
19529 ## objects will be recompiled, and the main program will be re-linked).
19530
19531 # The list of computer software component for your project. This might be
19532 # generated automatically.
19533 CSC_LIST=aa bb cc
19534
19535 # Name of the main program (no extension)
19536 MAIN=main
19537
19538 # If we need to build objects with -fPIC, uncomment the following line
19539 #NEED_FPIC=-fPIC
19540
19541 # The following variable should give the directory containing libgnat.so
19542 # You can get this directory through 'gnatls -v'. This is usually the last
19543 # directory in the Object_Path.
19544 GLIB=@dots{}
19545
19546 # The directories for the libraries
19547 # (This macro expands the list of CSC to the list of shared libraries, you
19548 # could simply use the expanded form:
19549 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19550 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19551
19552 $@{MAIN@}: objects $@{LIB_DIR@}
19553 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19554 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19555
19556 objects::
19557 # recompile the sources
19558 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19559
19560 # Note: In a future version of GNAT, the following commands will be simplified
19561 # by a new tool, gnatmlib
19562 $@{LIB_DIR@}:
19563 mkdir -p $@{dir $@@ @}
19564 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19565 cd $@{dir $@@ @} && cp -f ../*.ali .
19566
19567 # The dependencies for the modules
19568 # Note that we have to force the expansion of *.o, since in some cases
19569 # make won't be able to do it itself.
19570 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19571 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19572 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19573
19574 # Make sure all of the shared libraries are in the path before starting the
19575 # program
19576 run::
19577 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19578
19579 clean::
19580 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19581 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19582 $@{RM@} $@{CSC_LIST:%=%/*.o@}
19583 $@{RM@} *.o *.ali $@{MAIN@}
19584 @end smallexample
19585
19586 @node Automatically Creating a List of Directories
19587 @section Automatically Creating a List of Directories
19588
19589 @noindent
19590 In most makefiles, you will have to specify a list of directories, and
19591 store it in a variable. For small projects, it is often easier to
19592 specify each of them by hand, since you then have full control over what
19593 is the proper order for these directories, which ones should be
19594 included.
19595
19596 However, in larger projects, which might involve hundreds of
19597 subdirectories, it might be more convenient to generate this list
19598 automatically.
19599
19600 The example below presents two methods. The first one, although less
19601 general, gives you more control over the list. It involves wildcard
19602 characters, that are automatically expanded by @command{make}. Its
19603 shortcoming is that you need to explicitly specify some of the
19604 organization of your project, such as for instance the directory tree
19605 depth, whether some directories are found in a separate tree, @enddots{}
19606
19607 The second method is the most general one. It requires an external
19608 program, called @command{find}, which is standard on all Unix systems. All
19609 the directories found under a given root directory will be added to the
19610 list.
19611
19612 @smallexample
19613 @iftex
19614 @leftskip=0cm
19615 @font@heightrm=cmr8
19616 @heightrm
19617 @end iftex
19618 # The examples below are based on the following directory hierarchy:
19619 # All the directories can contain any number of files
19620 # ROOT_DIRECTORY -> a -> aa -> aaa
19621 # -> ab
19622 # -> ac
19623 # -> b -> ba -> baa
19624 # -> bb
19625 # -> bc
19626 # This Makefile creates a variable called DIRS, that can be reused any time
19627 # you need this list (see the other examples in this section)
19628
19629 # The root of your project's directory hierarchy
19630 ROOT_DIRECTORY=.
19631
19632 ####
19633 # First method: specify explicitly the list of directories
19634 # This allows you to specify any subset of all the directories you need.
19635 ####
19636
19637 DIRS := a/aa/ a/ab/ b/ba/
19638
19639 ####
19640 # Second method: use wildcards
19641 # Note that the argument(s) to wildcard below should end with a '/'.
19642 # Since wildcards also return file names, we have to filter them out
19643 # to avoid duplicate directory names.
19644 # We thus use make's @code{dir} and @code{sort} functions.
19645 # It sets DIRs to the following value (note that the directories aaa and baa
19646 # are not given, unless you change the arguments to wildcard).
19647 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19648 ####
19649
19650 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19651 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19652
19653 ####
19654 # Third method: use an external program
19655 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19656 # This is the most complete command: it sets DIRs to the following value:
19657 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19658 ####
19659
19660 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19661
19662 @end smallexample
19663
19664 @node Generating the Command Line Switches
19665 @section Generating the Command Line Switches
19666
19667 @noindent
19668 Once you have created the list of directories as explained in the
19669 previous section (@pxref{Automatically Creating a List of Directories}),
19670 you can easily generate the command line arguments to pass to gnatmake.
19671
19672 For the sake of completeness, this example assumes that the source path
19673 is not the same as the object path, and that you have two separate lists
19674 of directories.
19675
19676 @smallexample
19677 # see "Automatically creating a list of directories" to create
19678 # these variables
19679 SOURCE_DIRS=
19680 OBJECT_DIRS=
19681
19682 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19683 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19684
19685 all:
19686 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19687 @end smallexample
19688
19689 @node Overcoming Command Line Length Limits
19690 @section Overcoming Command Line Length Limits
19691
19692 @noindent
19693 One problem that might be encountered on big projects is that many
19694 operating systems limit the length of the command line. It is thus hard to give
19695 gnatmake the list of source and object directories.
19696
19697 This example shows how you can set up environment variables, which will
19698 make @command{gnatmake} behave exactly as if the directories had been
19699 specified on the command line, but have a much higher length limit (or
19700 even none on most systems).
19701
19702 It assumes that you have created a list of directories in your Makefile,
19703 using one of the methods presented in
19704 @ref{Automatically Creating a List of Directories}.
19705 For the sake of completeness, we assume that the object
19706 path (where the ALI files are found) is different from the sources patch.
19707
19708 Note a small trick in the Makefile below: for efficiency reasons, we
19709 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19710 expanded immediately by @code{make}. This way we overcome the standard
19711 make behavior which is to expand the variables only when they are
19712 actually used.
19713
19714 On Windows, if you are using the standard Windows command shell, you must
19715 replace colons with semicolons in the assignments to these variables.
19716
19717 @smallexample
19718 @iftex
19719 @leftskip=0cm
19720 @font@heightrm=cmr8
19721 @heightrm
19722 @end iftex
19723 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19724 # This is the same thing as putting the -I arguments on the command line.
19725 # (the equivalent of using -aI on the command line would be to define
19726 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19727 # You can of course have different values for these variables.
19728 #
19729 # Note also that we need to keep the previous values of these variables, since
19730 # they might have been set before running 'make' to specify where the GNAT
19731 # library is installed.
19732
19733 # see "Automatically creating a list of directories" to create these
19734 # variables
19735 SOURCE_DIRS=
19736 OBJECT_DIRS=
19737
19738 empty:=
19739 space:=$@{empty@} $@{empty@}
19740 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19741 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19742 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19743 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19744 export ADA_INCLUDE_PATH
19745 export ADA_OBJECT_PATH
19746
19747 all:
19748 gnatmake main_unit
19749 @end smallexample
19750 @end ifclear
19751
19752 @node Memory Management Issues
19753 @chapter Memory Management Issues
19754
19755 @noindent
19756 This chapter describes some useful memory pools provided in the GNAT library
19757 and in particular the GNAT Debug Pool facility, which can be used to detect
19758 incorrect uses of access values (including ``dangling references'').
19759 @ifclear vms
19760 It also describes the @command{gnatmem} tool, which can be used to track down
19761 ``memory leaks''.
19762 @end ifclear
19763
19764 @menu
19765 * Some Useful Memory Pools::
19766 * The GNAT Debug Pool Facility::
19767 @ifclear vms
19768 * The gnatmem Tool::
19769 @end ifclear
19770 @end menu
19771
19772 @node Some Useful Memory Pools
19773 @section Some Useful Memory Pools
19774 @findex Memory Pool
19775 @cindex storage, pool
19776
19777 @noindent
19778 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19779 storage pool. Allocations use the standard system call @code{malloc} while
19780 deallocations use the standard system call @code{free}. No reclamation is
19781 performed when the pool goes out of scope. For performance reasons, the
19782 standard default Ada allocators/deallocators do not use any explicit storage
19783 pools but if they did, they could use this storage pool without any change in
19784 behavior. That is why this storage pool is used when the user
19785 manages to make the default implicit allocator explicit as in this example:
19786 @smallexample @c ada
19787 type T1 is access Something;
19788 -- no Storage pool is defined for T2
19789 type T2 is access Something_Else;
19790 for T2'Storage_Pool use T1'Storage_Pool;
19791 -- the above is equivalent to
19792 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19793 @end smallexample
19794
19795 @noindent
19796 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19797 pool. The allocation strategy is similar to @code{Pool_Local}'s
19798 except that the all
19799 storage allocated with this pool is reclaimed when the pool object goes out of
19800 scope. This pool provides a explicit mechanism similar to the implicit one
19801 provided by several Ada 83 compilers for allocations performed through a local
19802 access type and whose purpose was to reclaim memory when exiting the
19803 scope of a given local access. As an example, the following program does not
19804 leak memory even though it does not perform explicit deallocation:
19805
19806 @smallexample @c ada
19807 with System.Pool_Local;
19808 procedure Pooloc1 is
19809 procedure Internal is
19810 type A is access Integer;
19811 X : System.Pool_Local.Unbounded_Reclaim_Pool;
19812 for A'Storage_Pool use X;
19813 v : A;
19814 begin
19815 for I in 1 .. 50 loop
19816 v := new Integer;
19817 end loop;
19818 end Internal;
19819 begin
19820 for I in 1 .. 100 loop
19821 Internal;
19822 end loop;
19823 end Pooloc1;
19824 @end smallexample
19825
19826 @noindent
19827 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19828 @code{Storage_Size} is specified for an access type.
19829 The whole storage for the pool is
19830 allocated at once, usually on the stack at the point where the access type is
19831 elaborated. It is automatically reclaimed when exiting the scope where the
19832 access type is defined. This package is not intended to be used directly by the
19833 user and it is implicitly used for each such declaration:
19834
19835 @smallexample @c ada
19836 type T1 is access Something;
19837 for T1'Storage_Size use 10_000;
19838 @end smallexample
19839
19840 @node The GNAT Debug Pool Facility
19841 @section The GNAT Debug Pool Facility
19842 @findex Debug Pool
19843 @cindex storage, pool, memory corruption
19844
19845 @noindent
19846 The use of unchecked deallocation and unchecked conversion can easily
19847 lead to incorrect memory references. The problems generated by such
19848 references are usually difficult to tackle because the symptoms can be
19849 very remote from the origin of the problem. In such cases, it is
19850 very helpful to detect the problem as early as possible. This is the
19851 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19852
19853 In order to use the GNAT specific debugging pool, the user must
19854 associate a debug pool object with each of the access types that may be
19855 related to suspected memory problems. See Ada Reference Manual 13.11.
19856 @smallexample @c ada
19857 type Ptr is access Some_Type;
19858 Pool : GNAT.Debug_Pools.Debug_Pool;
19859 for Ptr'Storage_Pool use Pool;
19860 @end smallexample
19861
19862 @noindent
19863 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19864 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19865 allow the user to redefine allocation and deallocation strategies. They
19866 also provide a checkpoint for each dereference, through the use of
19867 the primitive operation @code{Dereference} which is implicitly called at
19868 each dereference of an access value.
19869
19870 Once an access type has been associated with a debug pool, operations on
19871 values of the type may raise four distinct exceptions,
19872 which correspond to four potential kinds of memory corruption:
19873 @itemize @bullet
19874 @item
19875 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19876 @item
19877 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19878 @item
19879 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19880 @item
19881 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19882 @end itemize
19883
19884 @noindent
19885 For types associated with a Debug_Pool, dynamic allocation is performed using
19886 the standard GNAT allocation routine. References to all allocated chunks of
19887 memory are kept in an internal dictionary. Several deallocation strategies are
19888 provided, whereupon the user can choose to release the memory to the system,
19889 keep it allocated for further invalid access checks, or fill it with an easily
19890 recognizable pattern for debug sessions. The memory pattern is the old IBM
19891 hexadecimal convention: @code{16#DEADBEEF#}.
19892
19893 See the documentation in the file g-debpoo.ads for more information on the
19894 various strategies.
19895
19896 Upon each dereference, a check is made that the access value denotes a
19897 properly allocated memory location. Here is a complete example of use of
19898 @code{Debug_Pools}, that includes typical instances of memory corruption:
19899 @smallexample @c ada
19900 @iftex
19901 @leftskip=0cm
19902 @end iftex
19903 with Gnat.Io; use Gnat.Io;
19904 with Unchecked_Deallocation;
19905 with Unchecked_Conversion;
19906 with GNAT.Debug_Pools;
19907 with System.Storage_Elements;
19908 with Ada.Exceptions; use Ada.Exceptions;
19909 procedure Debug_Pool_Test is
19910
19911 type T is access Integer;
19912 type U is access all T;
19913
19914 P : GNAT.Debug_Pools.Debug_Pool;
19915 for T'Storage_Pool use P;
19916
19917 procedure Free is new Unchecked_Deallocation (Integer, T);
19918 function UC is new Unchecked_Conversion (U, T);
19919 A, B : aliased T;
19920
19921 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19922
19923 begin
19924 Info (P);
19925 A := new Integer;
19926 B := new Integer;
19927 B := A;
19928 Info (P);
19929 Free (A);
19930 begin
19931 Put_Line (Integer'Image(B.all));
19932 exception
19933 when E : others => Put_Line ("raised: " & Exception_Name (E));
19934 end;
19935 begin
19936 Free (B);
19937 exception
19938 when E : others => Put_Line ("raised: " & Exception_Name (E));
19939 end;
19940 B := UC(A'Access);
19941 begin
19942 Put_Line (Integer'Image(B.all));
19943 exception
19944 when E : others => Put_Line ("raised: " & Exception_Name (E));
19945 end;
19946 begin
19947 Free (B);
19948 exception
19949 when E : others => Put_Line ("raised: " & Exception_Name (E));
19950 end;
19951 Info (P);
19952 end Debug_Pool_Test;
19953 @end smallexample
19954
19955 @noindent
19956 The debug pool mechanism provides the following precise diagnostics on the
19957 execution of this erroneous program:
19958 @smallexample
19959 Debug Pool info:
19960 Total allocated bytes : 0
19961 Total deallocated bytes : 0
19962 Current Water Mark: 0
19963 High Water Mark: 0
19964
19965 Debug Pool info:
19966 Total allocated bytes : 8
19967 Total deallocated bytes : 0
19968 Current Water Mark: 8
19969 High Water Mark: 8
19970
19971 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19972 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19973 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19974 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19975 Debug Pool info:
19976 Total allocated bytes : 8
19977 Total deallocated bytes : 4
19978 Current Water Mark: 4
19979 High Water Mark: 8
19980 @end smallexample
19981
19982 @ifclear vms
19983 @node The gnatmem Tool
19984 @section The @command{gnatmem} Tool
19985 @findex gnatmem
19986
19987 @noindent
19988 The @code{gnatmem} utility monitors dynamic allocation and
19989 deallocation activity in a program, and displays information about
19990 incorrect deallocations and possible sources of memory leaks.
19991 It is designed to work in association with a static runtime library
19992 only and in this context provides three types of information:
19993 @itemize @bullet
19994 @item
19995 General information concerning memory management, such as the total
19996 number of allocations and deallocations, the amount of allocated
19997 memory and the high water mark, i.e.@: the largest amount of allocated
19998 memory in the course of program execution.
19999
20000 @item
20001 Backtraces for all incorrect deallocations, that is to say deallocations
20002 which do not correspond to a valid allocation.
20003
20004 @item
20005 Information on each allocation that is potentially the origin of a memory
20006 leak.
20007 @end itemize
20008
20009 @menu
20010 * Running gnatmem::
20011 * Switches for gnatmem::
20012 * Example of gnatmem Usage::
20013 @end menu
20014
20015 @node Running gnatmem
20016 @subsection Running @code{gnatmem}
20017
20018 @noindent
20019 @code{gnatmem} makes use of the output created by the special version of
20020 allocation and deallocation routines that record call information. This
20021 allows to obtain accurate dynamic memory usage history at a minimal cost to
20022 the execution speed. Note however, that @code{gnatmem} is not supported on
20023 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20024 Solaris and Windows NT/2000/XP (x86).
20025
20026 @noindent
20027 The @code{gnatmem} command has the form
20028
20029 @smallexample
20030 $ gnatmem @ovar{switches} user_program
20031 @end smallexample
20032
20033 @noindent
20034 The program must have been linked with the instrumented version of the
20035 allocation and deallocation routines. This is done by linking with the
20036 @file{libgmem.a} library. For correct symbolic backtrace information,
20037 the user program should be compiled with debugging options
20038 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20039
20040 @smallexample
20041 $ gnatmake -g my_program -largs -lgmem
20042 @end smallexample
20043
20044 @noindent
20045 As library @file{libgmem.a} contains an alternate body for package
20046 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20047 when an executable is linked with library @file{libgmem.a}. It is then not
20048 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20049
20050 @noindent
20051 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20052 This file contains information about all allocations and deallocations
20053 performed by the program. It is produced by the instrumented allocations and
20054 deallocations routines and will be used by @code{gnatmem}.
20055
20056 In order to produce symbolic backtrace information for allocations and
20057 deallocations performed by the GNAT run-time library, you need to use a
20058 version of that library that has been compiled with the @option{-g} switch
20059 (see @ref{Rebuilding the GNAT Run-Time Library}).
20060
20061 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20062 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20063 @option{-i} switch, gnatmem will assume that this file can be found in the
20064 current directory. For example, after you have executed @file{my_program},
20065 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20066
20067 @smallexample
20068 $ gnatmem my_program
20069 @end smallexample
20070
20071 @noindent
20072 This will produce the output with the following format:
20073
20074 *************** debut cc
20075 @smallexample
20076 $ gnatmem my_program
20077
20078 Global information
20079 ------------------
20080 Total number of allocations : 45
20081 Total number of deallocations : 6
20082 Final Water Mark (non freed mem) : 11.29 Kilobytes
20083 High Water Mark : 11.40 Kilobytes
20084
20085 .
20086 .
20087 .
20088 Allocation Root # 2
20089 -------------------
20090 Number of non freed allocations : 11
20091 Final Water Mark (non freed mem) : 1.16 Kilobytes
20092 High Water Mark : 1.27 Kilobytes
20093 Backtrace :
20094 my_program.adb:23 my_program.alloc
20095 .
20096 .
20097 .
20098 @end smallexample
20099
20100 The first block of output gives general information. In this case, the
20101 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20102 Unchecked_Deallocation routine occurred.
20103
20104 @noindent
20105 Subsequent paragraphs display information on all allocation roots.
20106 An allocation root is a specific point in the execution of the program
20107 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20108 construct. This root is represented by an execution backtrace (or subprogram
20109 call stack). By default the backtrace depth for allocations roots is 1, so
20110 that a root corresponds exactly to a source location. The backtrace can
20111 be made deeper, to make the root more specific.
20112
20113 @node Switches for gnatmem
20114 @subsection Switches for @code{gnatmem}
20115
20116 @noindent
20117 @code{gnatmem} recognizes the following switches:
20118
20119 @table @option
20120
20121 @item -q
20122 @cindex @option{-q} (@code{gnatmem})
20123 Quiet. Gives the minimum output needed to identify the origin of the
20124 memory leaks. Omits statistical information.
20125
20126 @item @var{N}
20127 @cindex @var{N} (@code{gnatmem})
20128 N is an integer literal (usually between 1 and 10) which controls the
20129 depth of the backtraces defining allocation root. The default value for
20130 N is 1. The deeper the backtrace, the more precise the localization of
20131 the root. Note that the total number of roots can depend on this
20132 parameter. This parameter must be specified @emph{before} the name of the
20133 executable to be analyzed, to avoid ambiguity.
20134
20135 @item -b n
20136 @cindex @option{-b} (@code{gnatmem})
20137 This switch has the same effect as just depth parameter.
20138
20139 @item -i @var{file}
20140 @cindex @option{-i} (@code{gnatmem})
20141 Do the @code{gnatmem} processing starting from @file{file}, rather than
20142 @file{gmem.out} in the current directory.
20143
20144 @item -m n
20145 @cindex @option{-m} (@code{gnatmem})
20146 This switch causes @code{gnatmem} to mask the allocation roots that have less
20147 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20148 examine even the roots that didn't result in leaks.
20149
20150 @item -s order
20151 @cindex @option{-s} (@code{gnatmem})
20152 This switch causes @code{gnatmem} to sort the allocation roots according to the
20153 specified order of sort criteria, each identified by a single letter. The
20154 currently supported criteria are @code{n, h, w} standing respectively for
20155 number of unfreed allocations, high watermark, and final watermark
20156 corresponding to a specific root. The default order is @code{nwh}.
20157
20158 @end table
20159
20160 @node Example of gnatmem Usage
20161 @subsection Example of @code{gnatmem} Usage
20162
20163 @noindent
20164 The following example shows the use of @code{gnatmem}
20165 on a simple memory-leaking program.
20166 Suppose that we have the following Ada program:
20167
20168 @smallexample @c ada
20169 @group
20170 @cartouche
20171 with Unchecked_Deallocation;
20172 procedure Test_Gm is
20173
20174 type T is array (1..1000) of Integer;
20175 type Ptr is access T;
20176 procedure Free is new Unchecked_Deallocation (T, Ptr);
20177 A : Ptr;
20178
20179 procedure My_Alloc is
20180 begin
20181 A := new T;
20182 end My_Alloc;
20183
20184 procedure My_DeAlloc is
20185 B : Ptr := A;
20186 begin
20187 Free (B);
20188 end My_DeAlloc;
20189
20190 begin
20191 My_Alloc;
20192 for I in 1 .. 5 loop
20193 for J in I .. 5 loop
20194 My_Alloc;
20195 end loop;
20196 My_Dealloc;
20197 end loop;
20198 end;
20199 @end cartouche
20200 @end group
20201 @end smallexample
20202
20203 @noindent
20204 The program needs to be compiled with debugging option and linked with
20205 @code{gmem} library:
20206
20207 @smallexample
20208 $ gnatmake -g test_gm -largs -lgmem
20209 @end smallexample
20210
20211 @noindent
20212 Then we execute the program as usual:
20213
20214 @smallexample
20215 $ test_gm
20216 @end smallexample
20217
20218 @noindent
20219 Then @code{gnatmem} is invoked simply with
20220 @smallexample
20221 $ gnatmem test_gm
20222 @end smallexample
20223
20224 @noindent
20225 which produces the following output (result may vary on different platforms):
20226
20227 @smallexample
20228 Global information
20229 ------------------
20230 Total number of allocations : 18
20231 Total number of deallocations : 5
20232 Final Water Mark (non freed mem) : 53.00 Kilobytes
20233 High Water Mark : 56.90 Kilobytes
20234
20235 Allocation Root # 1
20236 -------------------
20237 Number of non freed allocations : 11
20238 Final Water Mark (non freed mem) : 42.97 Kilobytes
20239 High Water Mark : 46.88 Kilobytes
20240 Backtrace :
20241 test_gm.adb:11 test_gm.my_alloc
20242
20243 Allocation Root # 2
20244 -------------------
20245 Number of non freed allocations : 1
20246 Final Water Mark (non freed mem) : 10.02 Kilobytes
20247 High Water Mark : 10.02 Kilobytes
20248 Backtrace :
20249 s-secsta.adb:81 system.secondary_stack.ss_init
20250
20251 Allocation Root # 3
20252 -------------------
20253 Number of non freed allocations : 1
20254 Final Water Mark (non freed mem) : 12 Bytes
20255 High Water Mark : 12 Bytes
20256 Backtrace :
20257 s-secsta.adb:181 system.secondary_stack.ss_init
20258 @end smallexample
20259
20260 @noindent
20261 Note that the GNAT run time contains itself a certain number of
20262 allocations that have no corresponding deallocation,
20263 as shown here for root #2 and root
20264 #3. This is a normal behavior when the number of non-freed allocations
20265 is one, it allocates dynamic data structures that the run time needs for
20266 the complete lifetime of the program. Note also that there is only one
20267 allocation root in the user program with a single line back trace:
20268 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20269 program shows that 'My_Alloc' is called at 2 different points in the
20270 source (line 21 and line 24). If those two allocation roots need to be
20271 distinguished, the backtrace depth parameter can be used:
20272
20273 @smallexample
20274 $ gnatmem 3 test_gm
20275 @end smallexample
20276
20277 @noindent
20278 which will give the following output:
20279
20280 @smallexample
20281 Global information
20282 ------------------
20283 Total number of allocations : 18
20284 Total number of deallocations : 5
20285 Final Water Mark (non freed mem) : 53.00 Kilobytes
20286 High Water Mark : 56.90 Kilobytes
20287
20288 Allocation Root # 1
20289 -------------------
20290 Number of non freed allocations : 10
20291 Final Water Mark (non freed mem) : 39.06 Kilobytes
20292 High Water Mark : 42.97 Kilobytes
20293 Backtrace :
20294 test_gm.adb:11 test_gm.my_alloc
20295 test_gm.adb:24 test_gm
20296 b_test_gm.c:52 main
20297
20298 Allocation Root # 2
20299 -------------------
20300 Number of non freed allocations : 1
20301 Final Water Mark (non freed mem) : 10.02 Kilobytes
20302 High Water Mark : 10.02 Kilobytes
20303 Backtrace :
20304 s-secsta.adb:81 system.secondary_stack.ss_init
20305 s-secsta.adb:283 <system__secondary_stack___elabb>
20306 b_test_gm.c:33 adainit
20307
20308 Allocation Root # 3
20309 -------------------
20310 Number of non freed allocations : 1
20311 Final Water Mark (non freed mem) : 3.91 Kilobytes
20312 High Water Mark : 3.91 Kilobytes
20313 Backtrace :
20314 test_gm.adb:11 test_gm.my_alloc
20315 test_gm.adb:21 test_gm
20316 b_test_gm.c:52 main
20317
20318 Allocation Root # 4
20319 -------------------
20320 Number of non freed allocations : 1
20321 Final Water Mark (non freed mem) : 12 Bytes
20322 High Water Mark : 12 Bytes
20323 Backtrace :
20324 s-secsta.adb:181 system.secondary_stack.ss_init
20325 s-secsta.adb:283 <system__secondary_stack___elabb>
20326 b_test_gm.c:33 adainit
20327 @end smallexample
20328
20329 @noindent
20330 The allocation root #1 of the first example has been split in 2 roots #1
20331 and #3 thanks to the more precise associated backtrace.
20332
20333 @end ifclear
20334
20335 @node Stack Related Facilities
20336 @chapter Stack Related Facilities
20337
20338 @noindent
20339 This chapter describes some useful tools associated with stack
20340 checking and analysis. In
20341 particular, it deals with dynamic and static stack usage measurements.
20342
20343 @menu
20344 * Stack Overflow Checking::
20345 * Static Stack Usage Analysis::
20346 * Dynamic Stack Usage Analysis::
20347 @end menu
20348
20349 @node Stack Overflow Checking
20350 @section Stack Overflow Checking
20351 @cindex Stack Overflow Checking
20352 @cindex -fstack-check
20353
20354 @noindent
20355 For most operating systems, @command{gcc} does not perform stack overflow
20356 checking by default. This means that if the main environment task or
20357 some other task exceeds the available stack space, then unpredictable
20358 behavior will occur. Most native systems offer some level of protection by
20359 adding a guard page at the end of each task stack. This mechanism is usually
20360 not enough for dealing properly with stack overflow situations because
20361 a large local variable could ``jump'' above the guard page.
20362 Furthermore, when the
20363 guard page is hit, there may not be any space left on the stack for executing
20364 the exception propagation code. Enabling stack checking avoids
20365 such situations.
20366
20367 To activate stack checking, compile all units with the gcc option
20368 @option{-fstack-check}. For example:
20369
20370 @smallexample
20371 gcc -c -fstack-check package1.adb
20372 @end smallexample
20373
20374 @noindent
20375 Units compiled with this option will generate extra instructions to check
20376 that any use of the stack (for procedure calls or for declaring local
20377 variables in declare blocks) does not exceed the available stack space.
20378 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20379
20380 For declared tasks, the stack size is controlled by the size
20381 given in an applicable @code{Storage_Size} pragma or by the value specified
20382 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20383 the default size as defined in the GNAT runtime otherwise.
20384
20385 For the environment task, the stack size depends on
20386 system defaults and is unknown to the compiler. Stack checking
20387 may still work correctly if a fixed
20388 size stack is allocated, but this cannot be guaranteed.
20389 @ifclear vms
20390 To ensure that a clean exception is signalled for stack
20391 overflow, set the environment variable
20392 @env{GNAT_STACK_LIMIT} to indicate the maximum
20393 stack area that can be used, as in:
20394 @cindex GNAT_STACK_LIMIT
20395
20396 @smallexample
20397 SET GNAT_STACK_LIMIT 1600
20398 @end smallexample
20399
20400 @noindent
20401 The limit is given in kilobytes, so the above declaration would
20402 set the stack limit of the environment task to 1.6 megabytes.
20403 Note that the only purpose of this usage is to limit the amount
20404 of stack used by the environment task. If it is necessary to
20405 increase the amount of stack for the environment task, then this
20406 is an operating systems issue, and must be addressed with the
20407 appropriate operating systems commands.
20408 @end ifclear
20409 @ifset vms
20410 To have a fixed size stack in the environment task, the stack must be put
20411 in the P0 address space and its size specified. Use these switches to
20412 create a p0 image:
20413
20414 @smallexample
20415 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20416 @end smallexample
20417
20418 @noindent
20419 The quotes are required to keep case. The number after @samp{STACK=} is the
20420 size of the environmental task stack in pagelets (512 bytes). In this example
20421 the stack size is about 2 megabytes.
20422
20423 @noindent
20424 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20425 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
20426 more details about the @option{/p0image} qualifier and the @option{stack}
20427 option.
20428 @end ifset
20429
20430 @node Static Stack Usage Analysis
20431 @section Static Stack Usage Analysis
20432 @cindex Static Stack Usage Analysis
20433 @cindex -fstack-usage
20434
20435 @noindent
20436 A unit compiled with @option{-fstack-usage} will generate an extra file
20437 that specifies
20438 the maximum amount of stack used, on a per-function basis.
20439 The file has the same
20440 basename as the target object file with a @file{.su} extension.
20441 Each line of this file is made up of three fields:
20442
20443 @itemize
20444 @item
20445 The name of the function.
20446 @item
20447 A number of bytes.
20448 @item
20449 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20450 @end itemize
20451
20452 The second field corresponds to the size of the known part of the function
20453 frame.
20454
20455 The qualifier @code{static} means that the function frame size
20456 is purely static.
20457 It usually means that all local variables have a static size.
20458 In this case, the second field is a reliable measure of the function stack
20459 utilization.
20460
20461 The qualifier @code{dynamic} means that the function frame size is not static.
20462 It happens mainly when some local variables have a dynamic size. When this
20463 qualifier appears alone, the second field is not a reliable measure
20464 of the function stack analysis. When it is qualified with @code{bounded}, it
20465 means that the second field is a reliable maximum of the function stack
20466 utilization.
20467
20468 @node Dynamic Stack Usage Analysis
20469 @section Dynamic Stack Usage Analysis
20470
20471 @noindent
20472 It is possible to measure the maximum amount of stack used by a task, by
20473 adding a switch to @command{gnatbind}, as:
20474
20475 @smallexample
20476 $ gnatbind -u0 file
20477 @end smallexample
20478
20479 @noindent
20480 With this option, at each task termination, its stack usage is output on
20481 @file{stderr}.
20482 It is not always convenient to output the stack usage when the program
20483 is still running. Hence, it is possible to delay this output until program
20484 termination. for a given number of tasks specified as the argument of the
20485 @option{-u} option. For instance:
20486
20487 @smallexample
20488 $ gnatbind -u100 file
20489 @end smallexample
20490
20491 @noindent
20492 will buffer the stack usage information of the first 100 tasks to terminate and
20493 output this info at program termination. Results are displayed in four
20494 columns:
20495
20496 @noindent
20497 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20498
20499 @noindent
20500 where:
20501
20502 @table @emph
20503 @item Index
20504 is a number associated with each task.
20505
20506 @item Task Name
20507 is the name of the task analyzed.
20508
20509 @item Stack Size
20510 is the maximum size for the stack.
20511
20512 @item Stack Usage
20513 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20514 is not entirely analyzed, and it's not possible to know exactly how
20515 much has actually been used. The report thus contains the theoretical stack usage
20516 (Value) and the possible variation (Variation) around this value.
20517
20518 @end table
20519
20520 @noindent
20521 The environment task stack, e.g., the stack that contains the main unit, is
20522 only processed when the environment variable GNAT_STACK_LIMIT is set.
20523
20524
20525 @c *********************************
20526 @c * GNATCHECK *
20527 @c *********************************
20528 @node Verifying Properties Using gnatcheck
20529 @chapter Verifying Properties Using @command{gnatcheck}
20530 @findex gnatcheck
20531 @cindex @command{gnatcheck}
20532
20533 @noindent
20534 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20535 of Ada source files according to a given set of semantic rules.
20536 @cindex ASIS
20537
20538 In order to check compliance with a given rule, @command{gnatcheck} has to
20539 semantically analyze the Ada sources.
20540 Therefore, checks can only be performed on
20541 legal Ada units. Moreover, when a unit depends semantically upon units located
20542 outside the current directory, the source search path has to be provided when
20543 calling @command{gnatcheck}, either through a specified project file or
20544 through @command{gnatcheck} switches as described below.
20545
20546 A number of rules are predefined in @command{gnatcheck} and are described
20547 later in this chapter.
20548 You can also add new rules, by modifying the @command{gnatcheck} code and
20549 rebuilding the tool. In order to add a simple rule making some local checks,
20550 a small amount of straightforward ASIS-based programming is usually needed.
20551
20552 Project support for @command{gnatcheck} is provided by the GNAT
20553 driver (see @ref{The GNAT Driver and Project Files}).
20554
20555 Invoking @command{gnatcheck} on the command line has the form:
20556
20557 @smallexample
20558 $ gnatcheck @ovar{switches} @{@var{filename}@}
20559 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20560 @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20561 @end smallexample
20562
20563 @noindent
20564 where
20565 @itemize @bullet
20566 @item
20567 @var{switches} specify the general tool options
20568
20569 @item
20570 Each @var{filename} is the name (including the extension) of a source
20571 file to process. ``Wildcards'' are allowed, and
20572 the file name may contain path information.
20573
20574 @item
20575 Each @var{arg_list_filename} is the name (including the extension) of a text
20576 file containing the names of the source files to process, separated by spaces
20577 or line breaks.
20578
20579 @item
20580 @var{gcc_switches} is a list of switches for
20581 @command{gcc}. They will be passed on to all compiler invocations made by
20582 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20583 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20584 and use the @option{-gnatec} switch to set the configuration file.
20585
20586 @item
20587 @var{rule_options} is a list of options for controlling a set of
20588 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20589 @end itemize
20590
20591 @noindent
20592 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20593
20594 @menu
20595 * Format of the Report File::
20596 * General gnatcheck Switches::
20597 * gnatcheck Rule Options::
20598 * Adding the Results of Compiler Checks to gnatcheck Output::
20599 * Project-Wide Checks::
20600 * Predefined Rules::
20601 @end menu
20602
20603 @node Format of the Report File
20604 @section Format of the Report File
20605 @cindex Report file (for @code{gnatcheck})
20606
20607 @noindent
20608 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20609 rule violations.
20610 It also creates a text file that
20611 contains the complete report of the last gnatcheck run. By default this file is
20612 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20613 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20614 location of the report file. This report contains:
20615 @itemize @bullet
20616 @item a list of the Ada source files being checked,
20617 @item a list of enabled and disabled rules,
20618 @item a list of the diagnostic messages, ordered in three different ways
20619 and collected in three separate
20620 sections. Section 1 contains the raw list of diagnostic messages. It
20621 corresponds to the output going to @file{stdout}. Section 2 contains
20622 messages ordered by rules.
20623 Section 3 contains messages ordered by source files.
20624 @end itemize
20625
20626 @node General gnatcheck Switches
20627 @section General @command{gnatcheck} Switches
20628
20629 @noindent
20630 The following switches control the general @command{gnatcheck} behavior
20631
20632 @table @option
20633 @c !sort!
20634 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20635 @item ^-a^/ALL^
20636 Process all units including those with read-only ALI files such as
20637 those from GNAT Run-Time library.
20638
20639 @ifclear vms
20640 @ignore
20641 @cindex @option{-d} (@command{gnatcheck})
20642 @item -d
20643 Debug mode
20644 @end ignore
20645
20646 @cindex @option{-dd} (@command{gnatcheck})
20647 @item -dd
20648 Progress indicator mode (for use in GPS)
20649 @end ifclear
20650
20651 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20652 @item ^-h^/HELP^
20653 List the predefined and user-defined rules. For more details see
20654 @ref{Predefined Rules}.
20655
20656 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20657 @item ^-l^/LOCS^
20658 Use full source locations references in the report file. For a construct from
20659 a generic instantiation a full source location is a chain from the location
20660 of this construct in the generic unit to the place where this unit is
20661 instantiated.
20662
20663 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20664 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20665 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20666 the default value is 500. Zero means that there is no limitation on
20667 the number of diagnostic messages to be printed into Stdout.
20668
20669 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20670 @item ^-q^/QUIET^
20671 Quiet mode. All the diagnoses about rule violations are placed in the
20672 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20673
20674 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20675 @item ^-s^/SHORT^
20676 Short format of the report file (no version information, no list of applied
20677 rules, no list of checked sources is included)
20678
20679 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20680 @item ^-s1^/COMPILER_STYLE^
20681 Include the compiler-style section in the report file
20682
20683 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20684 @item ^-s2^/BY_RULES^
20685 Include the section containing diagnoses ordered by rules in the report file
20686
20687 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20688 @item ^-s3^/BY_FILES_BY_RULES^
20689 Include the section containing diagnoses ordered by files and then by rules
20690 in the report file
20691
20692 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20693 @item ^-v^/VERBOSE^
20694 Verbose mode; @command{gnatcheck} generates version information and then
20695 a trace of sources being processed.
20696
20697
20698 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20699 @item ^-o ^/OUTPUT=^@var{report_file}
20700 Set name of report file file to @var{report_file} .
20701
20702 @end table
20703
20704 @noindent
20705 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20706 @option{^-s2^/BY_RULES^} or
20707 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20708 then the @command{gnatcheck} report file will only contain sections
20709 explicitly denoted by these options.
20710
20711 @node gnatcheck Rule Options
20712 @section @command{gnatcheck} Rule Options
20713
20714 @noindent
20715 The following options control the processing performed by
20716 @command{gnatcheck}.
20717
20718 @table @option
20719 @cindex @option{+ALL} (@command{gnatcheck})
20720 @item +ALL
20721 Turn all the rule checks ON.
20722
20723 @cindex @option{-ALL} (@command{gnatcheck})
20724 @item -ALL
20725 Turn all the rule checks OFF.
20726
20727 @cindex @option{+R} (@command{gnatcheck})
20728 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20729 Turn on the check for a specified rule with the specified parameter, if any.
20730 @var{rule_id} must be the identifier of one of the currently implemented rules
20731 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20732 are not case-sensitive. The @var{param} item must
20733 be a string representing a valid parameter(s) for the specified rule.
20734 If it contains any space characters then this string must be enclosed in
20735 quotation marks.
20736
20737 @cindex @option{-R} (@command{gnatcheck})
20738 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20739 Turn off the check for a specified rule with the specified parameter, if any.
20740
20741 @cindex @option{-from} (@command{gnatcheck})
20742 @item -from=@var{rule_option_filename}
20743 Read the rule options from the text file @var{rule_option_filename}, referred as
20744 ``rule file'' below.
20745
20746 @end table
20747
20748 @noindent
20749 The default behavior is that all the rule checks are disabled.
20750
20751 A rule file is a text file containing a set of rule options.
20752 @cindex Rule file (for @code{gnatcheck})
20753 The file may contain empty lines and Ada-style comments (comment
20754 lines and end-of-line comments). The rule file has free format; that is,
20755 you do not have to start a new rule option on a new line.
20756
20757 A rule file may contain other @option{-from=@var{rule_option_filename}}
20758 options, each such option being replaced with the content of the
20759 corresponding rule file during the rule files processing. In case a
20760 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20761 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20762 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20763 the processing of rule files is interrupted and a part of their content
20764 is ignored.
20765
20766
20767 @node Adding the Results of Compiler Checks to gnatcheck Output
20768 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20769
20770 @noindent
20771 The @command{gnatcheck} tool can include in the generated diagnostic messages
20772 and in
20773 the report file the results of the checks performed by the compiler. Though
20774 disabled by default, this effect may be obtained by using @option{+R} with
20775 the following rule identifiers and parameters:
20776
20777 @table @option
20778 @item Restrictions
20779 To record restrictions violations (that are performed by the compiler if the
20780 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20781 use the rule named
20782 @code{Restrictions} with the same parameters as pragma
20783 @code{Restrictions} or @code{Restriction_Warnings}.
20784
20785 @item Style_Checks
20786 To record compiler style checks(@pxref{Style Checking}), use the rule named
20787 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20788 which enables all the standard style checks that corresponds to @option{-gnatyy}
20789 GNAT style check option, or a string that has exactly the same
20790 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20791 @code{Style_Checks} (for further information about this pragma,
20792 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20793
20794 @item Warnings
20795 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20796 named @code{Warnings} with a parameter that is a valid
20797 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20798 (for further information about this pragma, @pxref{Pragma Warnings,,,
20799 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20800 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20801 all the specific warnings, but not suppresses the warning mode,
20802 and 'e' parameter, corresponding to @option{-gnatwe} that means
20803 "treat warnings as errors", does not have any effect.
20804
20805 @end table
20806
20807 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20808 option with the corresponding restriction name as a parameter. @code{-R} is
20809 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20810 warnings and style checks, use the corresponding warning and style options.
20811
20812 @node Project-Wide Checks
20813 @section Project-Wide Checks
20814 @cindex Project-wide checks (for @command{gnatcheck})
20815
20816 @noindent
20817 In order to perform checks on all units of a given project, you can use
20818 the GNAT driver along with the @option{-P} option:
20819 @smallexample
20820 gnat check -Pproj -rules -from=my_rules
20821 @end smallexample
20822
20823 @noindent
20824 If the project @code{proj} depends upon other projects, you can perform
20825 checks on the project closure using the @option{-U} option:
20826 @smallexample
20827 gnat check -Pproj -U -rules -from=my_rules
20828 @end smallexample
20829
20830 @noindent
20831 Finally, if not all the units are relevant to a particular main
20832 program in the project closure, you can perform checks for the set
20833 of units needed to create a given main program (unit closure) using
20834 the @option{-U} option followed by the name of the main unit:
20835 @smallexample
20836 gnat check -Pproj -U main -rules -from=my_rules
20837 @end smallexample
20838
20839
20840 @node Predefined Rules
20841 @section Predefined Rules
20842 @cindex Predefined rules (for @command{gnatcheck})
20843
20844 @ignore
20845 @c (Jan 2007) Since the global rules are still under development and are not
20846 @c documented, there is no point in explaining the difference between
20847 @c global and local rules
20848 @noindent
20849 A rule in @command{gnatcheck} is either local or global.
20850 A @emph{local rule} is a rule that applies to a well-defined section
20851 of a program and that can be checked by analyzing only this section.
20852 A @emph{global rule} requires analysis of some global properties of the
20853 whole program (mostly related to the program call graph).
20854 As of @value{NOW}, the implementation of global rules should be
20855 considered to be at a preliminary stage. You can use the
20856 @option{+GLOBAL} option to enable all the global rules, and the
20857 @option{-GLOBAL} rule option to disable all the global rules.
20858
20859 All the global rules in the list below are
20860 so indicated by marking them ``GLOBAL''.
20861 This +GLOBAL and -GLOBAL options are not
20862 included in the list of gnatcheck options above, because at the moment they
20863 are considered as a temporary debug options.
20864
20865 @command{gnatcheck} performs rule checks for generic
20866 instances only for global rules. This limitation may be relaxed in a later
20867 release.
20868 @end ignore
20869
20870 @noindent
20871 The following subsections document the rules implemented in
20872 @command{gnatcheck}.
20873 The subsection title is the same as the rule identifier, which may be
20874 used as a parameter of the @option{+R} or @option{-R} options.
20875
20876
20877 @menu
20878 * Abstract_Type_Declarations::
20879 * Anonymous_Arrays::
20880 * Anonymous_Subtypes::
20881 * Blocks::
20882 * Boolean_Relational_Operators::
20883 @ignore
20884 * Ceiling_Violations::
20885 @end ignore
20886 * Controlled_Type_Declarations::
20887 * Declarations_In_Blocks::
20888 * Default_Parameters::
20889 * Discriminated_Records::
20890 * Enumeration_Ranges_In_CASE_Statements::
20891 * Exceptions_As_Control_Flow::
20892 * EXIT_Statements_With_No_Loop_Name::
20893 * Expanded_Loop_Exit_Names::
20894 * Explicit_Full_Discrete_Ranges::
20895 * Float_Equality_Checks::
20896 * Forbidden_Pragmas::
20897 * Function_Style_Procedures::
20898 * Generics_In_Subprograms::
20899 * GOTO_Statements::
20900 * Implicit_IN_Mode_Parameters::
20901 * Implicit_SMALL_For_Fixed_Point_Types::
20902 * Improperly_Located_Instantiations::
20903 * Improper_Returns::
20904 * Library_Level_Subprograms::
20905 * Local_Packages::
20906 @ignore
20907 * Improperly_Called_Protected_Entries::
20908 @end ignore
20909 * Metrics::
20910 * Misnamed_Identifiers::
20911 * Multiple_Entries_In_Protected_Definitions::
20912 * Name_Clashes::
20913 * Non_Qualified_Aggregates::
20914 * Non_Short_Circuit_Operators::
20915 * Non_SPARK_Attributes::
20916 * Non_Tagged_Derived_Types::
20917 * Non_Visible_Exceptions::
20918 * Numeric_Literals::
20919 * OTHERS_In_Aggregates::
20920 * OTHERS_In_CASE_Statements::
20921 * OTHERS_In_Exception_Handlers::
20922 * Outer_Loop_Exits::
20923 * Overloaded_Operators::
20924 * Overly_Nested_Control_Structures::
20925 * Parameters_Out_Of_Order::
20926 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20927 * Positional_Actuals_For_Defaulted_Parameters::
20928 * Positional_Components::
20929 * Positional_Generic_Parameters::
20930 * Positional_Parameters::
20931 * Predefined_Numeric_Types::
20932 * Raising_External_Exceptions::
20933 * Raising_Predefined_Exceptions::
20934 * Separate_Numeric_Error_Handlers::
20935 @ignore
20936 * Recursion::
20937 * Side_Effect_Functions::
20938 @end ignore
20939 * Slices::
20940 * Unassigned_OUT_Parameters::
20941 * Uncommented_BEGIN_In_Package_Bodies::
20942 * Unconstrained_Array_Returns::
20943 * Universal_Ranges::
20944 * Unnamed_Blocks_And_Loops::
20945 @ignore
20946 * Unused_Subprograms::
20947 @end ignore
20948 * USE_PACKAGE_Clauses::
20949 * Volatile_Objects_Without_Address_Clauses::
20950 @end menu
20951
20952
20953 @node Abstract_Type_Declarations
20954 @subsection @code{Abstract_Type_Declarations}
20955 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20956
20957 @noindent
20958 Flag all declarations of abstract types. For an abstract private
20959 type, both the private and full type declarations are flagged.
20960
20961 This rule has no parameters.
20962
20963
20964 @node Anonymous_Arrays
20965 @subsection @code{Anonymous_Arrays}
20966 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20967
20968 @noindent
20969 Flag all anonymous array type definitions (by Ada semantics these can only
20970 occur in object declarations).
20971
20972 This rule has no parameters.
20973
20974 @node Anonymous_Subtypes
20975 @subsection @code{Anonymous_Subtypes}
20976 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20977
20978 @noindent
20979 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20980 any instance of a subtype indication with a constraint, other than one
20981 that occurs immediately within a subtype declaration. Any use of a range
20982 other than as a constraint used immediately within a subtype declaration
20983 is considered as an anonymous subtype.
20984
20985 An effect of this rule is that @code{for} loops such as the following are
20986 flagged (since @code{1..N} is formally a ``range''):
20987
20988 @smallexample @c ada
20989 for I in 1 .. N loop
20990 @dots{}
20991 end loop;
20992 @end smallexample
20993
20994 @noindent
20995 Declaring an explicit subtype solves the problem:
20996
20997 @smallexample @c ada
20998 subtype S is Integer range 1..N;
20999 @dots{}
21000 for I in S loop
21001 @dots{}
21002 end loop;
21003 @end smallexample
21004
21005 @noindent
21006 This rule has no parameters.
21007
21008 @node Blocks
21009 @subsection @code{Blocks}
21010 @cindex @code{Blocks} rule (for @command{gnatcheck})
21011
21012 @noindent
21013 Flag each block statement.
21014
21015 This rule has no parameters.
21016
21017 @node Boolean_Relational_Operators
21018 @subsection @code{Boolean_Relational_Operators}
21019 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21020
21021 @noindent
21022 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21023 ``>='', ``='' and ``/='') for the predefined Boolean type.
21024 (This rule is useful in enforcing the SPARK language restrictions.)
21025
21026 Calls to predefined relational operators of any type derived from
21027 @code{Standard.Boolean} are not detected. Calls to user-defined functions
21028 with these designators, and uses of operators that are renamings
21029 of the predefined relational operators for @code{Standard.Boolean},
21030 are likewise not detected.
21031
21032 This rule has no parameters.
21033
21034 @ignore
21035 @node Ceiling_Violations
21036 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
21037 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21038
21039 @noindent
21040 Flag invocations of a protected operation by a task whose priority exceeds
21041 the protected object's ceiling.
21042
21043 As of @value{NOW}, this rule has the following limitations:
21044
21045 @itemize @bullet
21046
21047 @item
21048 We consider only pragmas Priority and Interrupt_Priority as means to define
21049 a task/protected operation priority. We do not consider the effect of using
21050 Ada.Dynamic_Priorities.Set_Priority procedure;
21051
21052 @item
21053 We consider only base task priorities, and no priority inheritance. That is,
21054 we do not make a difference between calls issued during task activation and
21055 execution of the sequence of statements from task body;
21056
21057 @item
21058 Any situation when the priority of protected operation caller is set by a
21059 dynamic expression (that is, the corresponding Priority or
21060 Interrupt_Priority pragma has a non-static expression as an argument) we
21061 treat as a priority inconsistency (and, therefore, detect this situation).
21062 @end itemize
21063
21064 @noindent
21065 At the moment the notion of the main subprogram is not implemented in
21066 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21067 if this subprogram can be a main subprogram of a partition) changes the
21068 priority of an environment task. So if we have more then one such pragma in
21069 the set of processed sources, the pragma that is processed last, defines the
21070 priority of an environment task.
21071
21072 This rule has no parameters.
21073 @end ignore
21074
21075 @node Controlled_Type_Declarations
21076 @subsection @code{Controlled_Type_Declarations}
21077 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21078
21079 @noindent
21080 Flag all declarations of controlled types. A declaration of a private type
21081 is flagged if its full declaration declares a controlled type. A declaration
21082 of a derived type is flagged if its ancestor type is controlled. Subtype
21083 declarations are not checked. A declaration of a type that itself is not a
21084 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21085 component is not checked.
21086
21087 This rule has no parameters.
21088
21089
21090
21091 @node Declarations_In_Blocks
21092 @subsection @code{Declarations_In_Blocks}
21093 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21094
21095 @noindent
21096 Flag all block statements containing local declarations. A @code{declare}
21097 block with an empty @i{declarative_part} or with a @i{declarative part}
21098 containing only pragmas and/or @code{use} clauses is not flagged.
21099
21100 This rule has no parameters.
21101
21102
21103 @node Default_Parameters
21104 @subsection @code{Default_Parameters}
21105 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21106
21107 @noindent
21108 Flag all default expressions for subprogram parameters. Parameter
21109 declarations of formal and generic subprograms are also checked.
21110
21111 This rule has no parameters.
21112
21113
21114 @node Discriminated_Records
21115 @subsection @code{Discriminated_Records}
21116 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21117
21118 @noindent
21119 Flag all declarations of record types with discriminants. Only the
21120 declarations of record and record extension types are checked. Incomplete,
21121 formal, private, derived and private extension type declarations are not
21122 checked. Task and protected type declarations also are not checked.
21123
21124 This rule has no parameters.
21125
21126
21127 @node Enumeration_Ranges_In_CASE_Statements
21128 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21129 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21130
21131 @noindent
21132 Flag each use of a range of enumeration literals as a choice in a
21133 @code{case} statement.
21134 All forms for specifying a range (explicit ranges
21135 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21136 An enumeration range is
21137 flagged even if contains exactly one enumeration value or no values at all. A
21138 type derived from an enumeration type is considered as an enumeration type.
21139
21140 This rule helps prevent maintenance problems arising from adding an
21141 enumeration value to a type and having it implicitly handled by an existing
21142 @code{case} statement with an enumeration range that includes the new literal.
21143
21144 This rule has no parameters.
21145
21146
21147 @node Exceptions_As_Control_Flow
21148 @subsection @code{Exceptions_As_Control_Flow}
21149 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21150
21151 @noindent
21152 Flag each place where an exception is explicitly raised and handled in the
21153 same subprogram body. A @code{raise} statement in an exception handler,
21154 package body, task body or entry body is not flagged.
21155
21156 The rule has no parameters.
21157
21158 @node EXIT_Statements_With_No_Loop_Name
21159 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21160 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21161
21162 @noindent
21163 Flag each @code{exit} statement that does not specify the name of the loop
21164 being exited.
21165
21166 The rule has no parameters.
21167
21168
21169 @node Expanded_Loop_Exit_Names
21170 @subsection @code{Expanded_Loop_Exit_Names}
21171 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21172
21173 @noindent
21174 Flag all expanded loop names in @code{exit} statements.
21175
21176 This rule has no parameters.
21177
21178 @node Explicit_Full_Discrete_Ranges
21179 @subsection @code{Explicit_Full_Discrete_Ranges}
21180 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21181
21182 @noindent
21183 Flag each discrete range that has the form @code{A'First .. A'Last}.
21184
21185 This rule has no parameters.
21186
21187 @node Float_Equality_Checks
21188 @subsection @code{Float_Equality_Checks}
21189 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21190
21191 @noindent
21192 Flag all calls to the predefined equality operations for floating-point types.
21193 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21194 User-defined equality operations are not flagged, nor are ``@code{=}''
21195 and ``@code{/=}'' operations for fixed-point types.
21196
21197 This rule has no parameters.
21198
21199
21200 @node Forbidden_Pragmas
21201 @subsection @code{Forbidden_Pragmas}
21202 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21203
21204 @noindent
21205 Flag each use of the specified pragmas. The pragmas to be detected
21206 are named in the rule's parameters.
21207
21208 This rule has the following parameters:
21209
21210 @itemize @bullet
21211 @item For the @option{+R} option
21212
21213 @table @asis
21214 @item @emph{Pragma_Name}
21215 Adds the specified pragma to the set of pragmas to be
21216 checked and sets the checks for all the specified pragmas
21217 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21218 does not correspond to any pragma name defined in the Ada
21219 standard or to the name of a GNAT-specific pragma defined
21220 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21221 Manual}, it is treated as the name of unknown pragma.
21222
21223 @item @code{GNAT}
21224 All the GNAT-specific pragmas are detected; this sets
21225 the checks for all the specified pragmas ON.
21226
21227 @item @code{ALL}
21228 All pragmas are detected; this sets the rule ON.
21229 @end table
21230
21231 @item For the @option{-R} option
21232 @table @asis
21233 @item @emph{Pragma_Name}
21234 Removes the specified pragma from the set of pragmas to be
21235 checked without affecting checks for
21236 other pragmas. @emph{Pragma_Name} is treated as a name
21237 of a pragma. If it does not correspond to any pragma
21238 defined in the Ada standard or to any name defined in
21239 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21240 this option is treated as turning OFF detection of all unknown pragmas.
21241
21242 @item GNAT
21243 Turn OFF detection of all GNAT-specific pragmas
21244
21245 @item ALL
21246 Clear the list of the pragmas to be detected and
21247 turn the rule OFF.
21248 @end table
21249 @end itemize
21250
21251 @noindent
21252 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21253 the syntax of an Ada identifier and therefore can not be considered
21254 as a pragma name, a diagnostic message is generated and the corresponding
21255 parameter is ignored.
21256
21257 When more then one parameter is given in the same rule option, the parameters
21258 must be separated by a comma.
21259
21260 If more then one option for this rule is specified for the @command{gnatcheck}
21261 call, a new option overrides the previous one(s).
21262
21263 The @option{+R} option with no parameters turns the rule ON with the set of
21264 pragmas to be detected defined by the previous rule options.
21265 (By default this set is empty, so if the only option specified for the rule is
21266 @option{+RForbidden_Pragmas} (with
21267 no parameter), then the rule is enabled, but it does not detect anything).
21268 The @option{-R} option with no parameter turns the rule OFF, but it does not
21269 affect the set of pragmas to be detected.
21270
21271
21272
21273
21274 @node Function_Style_Procedures
21275 @subsection @code{Function_Style_Procedures}
21276 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21277
21278 @noindent
21279 Flag each procedure that can be rewritten as a function. A procedure can be
21280 converted into a function if it has exactly one parameter of mode @code{out}
21281 and no parameters of mode @code{in out}. Procedure declarations,
21282 formal procedure declarations, and generic procedure declarations are always
21283 checked. Procedure
21284 bodies and body stubs are flagged only if they do not have corresponding
21285 separate declarations. Procedure renamings and procedure instantiations are
21286 not flagged.
21287
21288 If a procedure can be rewritten as a function, but its @code{out} parameter is
21289 of a limited type, it is not flagged.
21290
21291 Protected procedures are not flagged. Null procedures also are not flagged.
21292
21293 This rule has no parameters.
21294
21295
21296 @node Generics_In_Subprograms
21297 @subsection @code{Generics_In_Subprograms}
21298 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21299
21300 @noindent
21301 Flag each declaration of a generic unit in a subprogram. Generic
21302 declarations in the bodies of generic subprograms are also flagged.
21303 A generic unit nested in another generic unit is not flagged.
21304 If a generic unit is
21305 declared in a local package that is declared in a subprogram body, the
21306 generic unit is flagged.
21307
21308 This rule has no parameters.
21309
21310
21311 @node GOTO_Statements
21312 @subsection @code{GOTO_Statements}
21313 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21314
21315 @noindent
21316 Flag each occurrence of a @code{goto} statement.
21317
21318 This rule has no parameters.
21319
21320
21321 @node Implicit_IN_Mode_Parameters
21322 @subsection @code{Implicit_IN_Mode_Parameters}
21323 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21324
21325 @noindent
21326 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21327 Note that @code{access} parameters, although they technically behave
21328 like @code{in} parameters, are not flagged.
21329
21330 This rule has no parameters.
21331
21332
21333 @node Implicit_SMALL_For_Fixed_Point_Types
21334 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21335 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21336
21337 @noindent
21338 Flag each fixed point type declaration that lacks an explicit
21339 representation clause to define its @code{'Small} value.
21340 Since @code{'Small} can be defined only for ordinary fixed point types,
21341 decimal fixed point type declarations are not checked.
21342
21343 This rule has no parameters.
21344
21345
21346 @node Improperly_Located_Instantiations
21347 @subsection @code{Improperly_Located_Instantiations}
21348 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21349
21350 @noindent
21351 Flag all generic instantiations in library-level package specs
21352 (including library generic packages) and in all subprogram bodies.
21353
21354 Instantiations in task and entry bodies are not flagged. Instantiations in the
21355 bodies of protected subprograms are flagged.
21356
21357 This rule has no parameters.
21358
21359
21360
21361 @node Improper_Returns
21362 @subsection @code{Improper_Returns}
21363 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21364
21365 @noindent
21366 Flag each explicit @code{return} statement in procedures, and
21367 multiple @code{return} statements in functions.
21368 Diagnostic messages are generated for all @code{return} statements
21369 in a procedure (thus each procedure must be written so that it
21370 returns implicitly at the end of its statement part),
21371 and for all @code{return} statements in a function after the first one.
21372 This rule supports the stylistic convention that each subprogram
21373 should have no more than one point of normal return.
21374
21375 This rule has no parameters.
21376
21377
21378 @node Library_Level_Subprograms
21379 @subsection @code{Library_Level_Subprograms}
21380 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21381
21382 @noindent
21383 Flag all library-level subprograms (including generic subprogram instantiations).
21384
21385 This rule has no parameters.
21386
21387
21388 @node Local_Packages
21389 @subsection @code{Local_Packages}
21390 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21391
21392 @noindent
21393 Flag all local packages declared in package and generic package
21394 specs.
21395 Local packages in bodies are not flagged.
21396
21397 This rule has no parameters.
21398
21399 @ignore
21400 @node Improperly_Called_Protected_Entries
21401 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21402 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21403
21404 @noindent
21405 Flag each protected entry that can be called from more than one task.
21406
21407 This rule has no parameters.
21408 @end ignore
21409
21410 @node Metrics
21411 @subsection @code{Metrics}
21412 @cindex @code{Metrics} rule (for @command{gnatcheck})
21413
21414 @noindent
21415 There is a set of checks based on computing a metric value and comparing the
21416 result with the specified upper (or lower, depending on a specific metric)
21417 value specified for a given metric. A construct is flagged if a given metric
21418 is applicable (can be computed) for it and the computed value is greater
21419 then (lover then) the specified upper (lower) bound.
21420
21421 The name of any metric-based rule consists of the prefix @code{Metrics_}
21422 followed by the name of the corresponding metric (see the table below).
21423 For @option{+R} option, each metric-based rule has a numeric parameter
21424 specifying the bound (integer or real, depending on a metric), @option{-R}
21425 option for metric rules does not have a parameter.
21426
21427 The following table shows the metric names for that the corresponding
21428 metrics-based checks are supported by gnatcheck, including the
21429 constraint that must be satisfied by the bound that is specified for the check
21430 and what bound - upper (U) or lower (L) - should be specified.
21431
21432 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21433 @ifnothtml
21434 @headitem Check Name @tab Description @tab Bounds Value
21435 @end ifnothtml
21436 @ifhtml
21437 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21438 @end ifhtml
21439 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21440 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21441 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21442 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21443 @end multitable
21444
21445 @noindent
21446 The meaning and the computed values for all these metrics are exactly
21447 the same as for the corresponding metrics in @command{gnatmetric}.
21448
21449 @emph{Example:} the rule
21450 @smallexample
21451 +RMetrics_Cyclomatic_Complexity : 7
21452 @end smallexample
21453 @noindent
21454 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21455
21456 To turn OFF the check for cyclomatic complexity metric, use the following option:
21457 @smallexample
21458 -RMetrics_Cyclomatic_Complexity
21459 @end smallexample
21460
21461 @node Misnamed_Identifiers
21462 @subsection @code{Misnamed_Identifiers}
21463 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21464
21465 @noindent
21466 Flag the declaration of each identifier that does not have a suffix
21467 corresponding to the kind of entity being declared.
21468 The following declarations are checked:
21469
21470 @itemize @bullet
21471 @item
21472 type declarations
21473
21474 @item
21475 constant declarations (but not number declarations)
21476
21477 @item
21478 package renaming declarations (but not generic package renaming
21479 declarations)
21480 @end itemize
21481
21482 @noindent
21483 This rule may have parameters. When used without parameters, the rule enforces
21484 the following checks:
21485
21486 @itemize @bullet
21487 @item
21488 type-defining names end with @code{_T}, unless the type is an access type,
21489 in which case the suffix must be @code{_A}
21490 @item
21491 constant names end with @code{_C}
21492 @item
21493 names defining package renamings end with @code{_R}
21494 @end itemize
21495
21496 @noindent
21497 For a private or incomplete type declaration the following checks are
21498 made for the defining name suffix:
21499
21500 @itemize @bullet
21501 @item
21502 For an incomplete type declaration: if the corresponding full type
21503 declaration is available, the defining identifier from the full type
21504 declaration is checked, but the defining identifier from the incomplete type
21505 declaration is not; otherwise the defining identifier from the incomplete
21506 type declaration is checked against the suffix specified for type
21507 declarations.
21508
21509 @item
21510 For a private type declaration (including private extensions), the defining
21511 identifier from the private type declaration is checked against the type
21512 suffix (even if the corresponding full declaration is an access type
21513 declaration), and the defining identifier from the corresponding full type
21514 declaration is not checked.
21515 @end itemize
21516
21517 @noindent
21518 For a deferred constant, the defining name in the corresponding full constant
21519 declaration is not checked.
21520
21521 Defining names of formal types are not checked.
21522
21523 The rule may have the following parameters:
21524
21525 @itemize @bullet
21526 @item
21527 For the @option{+R} option:
21528 @table @code
21529 @item Default
21530 Sets the default listed above for all the names to be checked.
21531
21532 @item Type_Suffix=@emph{string}
21533 Specifies the suffix for a type name.
21534
21535 @item Access_Suffix=@emph{string}
21536 Specifies the suffix for an access type name. If
21537 this parameter is set, it overrides for access
21538 types the suffix set by the @code{Type_Suffix} parameter.
21539
21540 @item Constant_Suffix=@emph{string}
21541 Specifies the suffix for a constant name.
21542
21543 @item Renaming_Suffix=@emph{string}
21544 Specifies the suffix for a package renaming name.
21545 @end table
21546
21547 @item
21548 For the @option{-R} option:
21549 @table @code
21550 @item All_Suffixes
21551 Remove all the suffixes specified for the
21552 identifier suffix checks, whether by default or
21553 as specified by other rule parameters. All the
21554 checks for this rule are disabled as a result.
21555
21556 @item Type_Suffix
21557 Removes the suffix specified for types. This
21558 disables checks for types but does not disable
21559 any other checks for this rule (including the
21560 check for access type names if @code{Access_Suffix} is
21561 set).
21562
21563 @item Access_Suffix
21564 Removes the suffix specified for access types.
21565 This disables checks for access type names but
21566 does not disable any other checks for this rule.
21567 If @code{Type_Suffix} is set, access type names are
21568 checked as ordinary type names.
21569
21570 @item Constant_Suffix
21571 Removes the suffix specified for constants. This
21572 disables checks for constant names but does not
21573 disable any other checks for this rule.
21574
21575 @item Renaming_Suffix
21576 Removes the suffix specified for package
21577 renamings. This disables checks for package
21578 renamings but does not disable any other checks
21579 for this rule.
21580 @end table
21581 @end itemize
21582
21583 @noindent
21584 If more than one parameter is used, parameters must be separated by commas.
21585
21586 If more than one option is specified for the @command{gnatcheck} invocation,
21587 a new option overrides the previous one(s).
21588
21589 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21590 checks for all the
21591 name suffixes specified by previous options used for this rule.
21592
21593 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21594 all the checks but keeps
21595 all the suffixes specified by previous options used for this rule.
21596
21597 The @emph{string} value must be a valid suffix for an Ada identifier (after
21598 trimming all the leading and trailing space characters, if any).
21599 Parameters are not case sensitive, except the @emph{string} part.
21600
21601 If any error is detected in a rule parameter, the parameter is ignored.
21602 In such a case the options that are set for the rule are not
21603 specified.
21604
21605
21606
21607 @node Multiple_Entries_In_Protected_Definitions
21608 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21609 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21610
21611 @noindent
21612 Flag each protected definition (i.e., each protected object/type declaration)
21613 that defines more than one entry.
21614 Diagnostic messages are generated for all the entry declarations
21615 except the first one. An entry family is counted as one entry. Entries from
21616 the private part of the protected definition are also checked.
21617
21618 This rule has no parameters.
21619
21620 @node Name_Clashes
21621 @subsection @code{Name_Clashes}
21622 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21623
21624 @noindent
21625 Check that certain names are not used as defining identifiers. To activate
21626 this rule, you need to supply a reference to the dictionary file(s) as a rule
21627 parameter(s) (more then one dictionary file can be specified). If no
21628 dictionary file is set, this rule will not cause anything to be flagged.
21629 Only defining occurrences, not references, are checked.
21630 The check is not case-sensitive.
21631
21632 This rule is enabled by default, but without setting any corresponding
21633 dictionary file(s); thus the default effect is to do no checks.
21634
21635 A dictionary file is a plain text file. The maximum line length for this file
21636 is 1024 characters. If the line is longer then this limit, extra characters
21637 are ignored.
21638
21639 Each line can be either an empty line, a comment line, or a line containing
21640 a list of identifiers separated by space or HT characters.
21641 A comment is an Ada-style comment (from @code{--} to end-of-line).
21642 Identifiers must follow the Ada syntax for identifiers.
21643 A line containing one or more identifiers may end with a comment.
21644
21645 @node Non_Qualified_Aggregates
21646 @subsection @code{Non_Qualified_Aggregates}
21647 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21648
21649 @noindent
21650 Flag each non-qualified aggregate.
21651 A non-qualified aggregate is an
21652 aggregate that is not the expression of a qualified expression. A
21653 string literal is not considered an aggregate, but an array
21654 aggregate of a string type is considered as a normal aggregate.
21655 Aggregates of anonymous array types are not flagged.
21656
21657 This rule has no parameters.
21658
21659
21660 @node Non_Short_Circuit_Operators
21661 @subsection @code{Non_Short_Circuit_Operators}
21662 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21663
21664 @noindent
21665 Flag all calls to predefined @code{and} and @code{or} operators for
21666 any boolean type. Calls to
21667 user-defined @code{and} and @code{or} and to operators defined by renaming
21668 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21669 operators for modular types or boolean array types are not flagged.
21670
21671 This rule has no parameters.
21672
21673
21674
21675 @node Non_SPARK_Attributes
21676 @subsection @code{Non_SPARK_Attributes}
21677 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21678
21679 @noindent
21680 The SPARK language defines the following subset of Ada 95 attribute
21681 designators as those that can be used in SPARK programs. The use of
21682 any other attribute is flagged.
21683
21684 @itemize @bullet
21685 @item @code{'Adjacent}
21686 @item @code{'Aft}
21687 @item @code{'Base}
21688 @item @code{'Ceiling}
21689 @item @code{'Component_Size}
21690 @item @code{'Compose}
21691 @item @code{'Copy_Sign}
21692 @item @code{'Delta}
21693 @item @code{'Denorm}
21694 @item @code{'Digits}
21695 @item @code{'Exponent}
21696 @item @code{'First}
21697 @item @code{'Floor}
21698 @item @code{'Fore}
21699 @item @code{'Fraction}
21700 @item @code{'Last}
21701 @item @code{'Leading_Part}
21702 @item @code{'Length}
21703 @item @code{'Machine}
21704 @item @code{'Machine_Emax}
21705 @item @code{'Machine_Emin}
21706 @item @code{'Machine_Mantissa}
21707 @item @code{'Machine_Overflows}
21708 @item @code{'Machine_Radix}
21709 @item @code{'Machine_Rounds}
21710 @item @code{'Max}
21711 @item @code{'Min}
21712 @item @code{'Model}
21713 @item @code{'Model_Emin}
21714 @item @code{'Model_Epsilon}
21715 @item @code{'Model_Mantissa}
21716 @item @code{'Model_Small}
21717 @item @code{'Modulus}
21718 @item @code{'Pos}
21719 @item @code{'Pred}
21720 @item @code{'Range}
21721 @item @code{'Remainder}
21722 @item @code{'Rounding}
21723 @item @code{'Safe_First}
21724 @item @code{'Safe_Last}
21725 @item @code{'Scaling}
21726 @item @code{'Signed_Zeros}
21727 @item @code{'Size}
21728 @item @code{'Small}
21729 @item @code{'Succ}
21730 @item @code{'Truncation}
21731 @item @code{'Unbiased_Rounding}
21732 @item @code{'Val}
21733 @item @code{'Valid}
21734 @end itemize
21735
21736 @noindent
21737 This rule has no parameters.
21738
21739
21740 @node Non_Tagged_Derived_Types
21741 @subsection @code{Non_Tagged_Derived_Types}
21742 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21743
21744 @noindent
21745 Flag all derived type declarations that do not have a record extension part.
21746
21747 This rule has no parameters.
21748
21749
21750
21751 @node Non_Visible_Exceptions
21752 @subsection @code{Non_Visible_Exceptions}
21753 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21754
21755 @noindent
21756 Flag constructs leading to the possibility of propagating an exception
21757 out of the scope in which the exception is declared.
21758 Two cases are detected:
21759
21760 @itemize @bullet
21761 @item
21762 An exception declaration in a subprogram body, task body or block
21763 statement is flagged if the body or statement does not contain a handler for
21764 that exception or a handler with an @code{others} choice.
21765
21766 @item
21767 A @code{raise} statement in an exception handler of a subprogram body,
21768 task body or block statement is flagged if it (re)raises a locally
21769 declared exception. This may occur under the following circumstances:
21770 @itemize @minus
21771 @item
21772 it explicitly raises a locally declared exception, or
21773 @item
21774 it does not specify an exception name (i.e., it is simply @code{raise;})
21775 and the enclosing handler contains a locally declared exception in its
21776 exception choices.
21777 @end itemize
21778 @end itemize
21779
21780 @noindent
21781 Renamings of local exceptions are not flagged.
21782
21783 This rule has no parameters.
21784
21785
21786 @node Numeric_Literals
21787 @subsection @code{Numeric_Literals}
21788 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21789
21790 @noindent
21791 Flag each use of a numeric literal in an index expression, and in any
21792 circumstance except for the following:
21793
21794 @itemize @bullet
21795 @item
21796 a literal occurring in the initialization expression for a constant
21797 declaration or a named number declaration, or
21798
21799 @item
21800 an integer literal that is less than or equal to a value
21801 specified by the @option{N} rule parameter.
21802 @end itemize
21803
21804 @noindent
21805 This rule may have the following parameters for the @option{+R} option:
21806
21807 @table @asis
21808 @item @emph{N}
21809 @emph{N} is an integer literal used as the maximal value that is not flagged
21810 (i.e., integer literals not exceeding this value are allowed)
21811
21812 @item @code{ALL}
21813 All integer literals are flagged
21814 @end table
21815
21816 @noindent
21817 If no parameters are set, the maximum unflagged value is 1.
21818
21819 The last specified check limit (or the fact that there is no limit at
21820 all) is used when multiple @option{+R} options appear.
21821
21822 The @option{-R} option for this rule has no parameters.
21823 It disables the rule but retains the last specified maximum unflagged value.
21824 If the @option{+R} option subsequently appears, this value is used as the
21825 threshold for the check.
21826
21827
21828 @node OTHERS_In_Aggregates
21829 @subsection @code{OTHERS_In_Aggregates}
21830 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21831
21832 @noindent
21833 Flag each use of an @code{others} choice in extension aggregates.
21834 In record and array aggregates, an @code{others} choice is flagged unless
21835 it is used to refer to all components, or to all but one component.
21836
21837 If, in case of a named array aggregate, there are two associations, one
21838 with an @code{others} choice and another with a discrete range, the
21839 @code{others} choice is flagged even if the discrete range specifies
21840 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21841
21842 This rule has no parameters.
21843
21844 @node OTHERS_In_CASE_Statements
21845 @subsection @code{OTHERS_In_CASE_Statements}
21846 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21847
21848 @noindent
21849 Flag any use of an @code{others} choice in a @code{case} statement.
21850
21851 This rule has no parameters.
21852
21853 @node OTHERS_In_Exception_Handlers
21854 @subsection @code{OTHERS_In_Exception_Handlers}
21855 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21856
21857 @noindent
21858 Flag any use of an @code{others} choice in an exception handler.
21859
21860 This rule has no parameters.
21861
21862
21863 @node Outer_Loop_Exits
21864 @subsection @code{Outer_Loop_Exits}
21865 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21866
21867 @noindent
21868 Flag each @code{exit} statement containing a loop name that is not the name
21869 of the immediately enclosing @code{loop} statement.
21870
21871 This rule has no parameters.
21872
21873
21874 @node Overloaded_Operators
21875 @subsection @code{Overloaded_Operators}
21876 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21877
21878 @noindent
21879 Flag each function declaration that overloads an operator symbol.
21880 A function body is checked only if the body does not have a
21881 separate spec. Formal functions are also checked. For a
21882 renaming declaration, only renaming-as-declaration is checked
21883
21884 This rule has no parameters.
21885
21886
21887 @node Overly_Nested_Control_Structures
21888 @subsection @code{Overly_Nested_Control_Structures}
21889 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21890
21891 @noindent
21892 Flag each control structure whose nesting level exceeds the value provided
21893 in the rule parameter.
21894
21895 The control structures checked are the following:
21896
21897 @itemize @bullet
21898 @item @code{if} statement
21899 @item @code{case} statement
21900 @item @code{loop} statement
21901 @item Selective accept statement
21902 @item Timed entry call statement
21903 @item Conditional entry call
21904 @item Asynchronous select statement
21905 @end itemize
21906
21907 @noindent
21908 The rule has the following parameter for the @option{+R} option:
21909
21910 @table @emph
21911 @item N
21912 Positive integer specifying the maximal control structure nesting
21913 level that is not flagged
21914 @end table
21915
21916 @noindent
21917 If the parameter for the @option{+R} option is not specified or
21918 if it is not a positive integer, @option{+R} option is ignored.
21919
21920 If more then one option is specified for the gnatcheck call, the later option and
21921 new parameter override the previous one(s).
21922
21923
21924 @node Parameters_Out_Of_Order
21925 @subsection @code{Parameters_Out_Of_Order}
21926 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21927
21928 @noindent
21929 Flag each subprogram and entry declaration whose formal parameters are not
21930 ordered according to the following scheme:
21931
21932 @itemize @bullet
21933
21934 @item @code{in} and @code{access} parameters first,
21935 then @code{in out} parameters,
21936 and then @code{out} parameters;
21937
21938 @item for @code{in} mode, parameters with default initialization expressions
21939 occur last
21940 @end itemize
21941
21942 @noindent
21943 Only the first violation of the described order is flagged.
21944
21945 The following constructs are checked:
21946
21947 @itemize @bullet
21948 @item subprogram declarations (including null procedures);
21949 @item generic subprogram declarations;
21950 @item formal subprogram declarations;
21951 @item entry declarations;
21952 @item subprogram bodies and subprogram body stubs that do not
21953 have separate specifications
21954 @end itemize
21955
21956 @noindent
21957 Subprogram renamings are not checked.
21958
21959 This rule has no parameters.
21960
21961
21962 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21963 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21964 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21965
21966 @noindent
21967 Flag each generic actual parameter corresponding to a generic formal
21968 parameter with a default initialization, if positional notation is used.
21969
21970 This rule has no parameters.
21971
21972 @node Positional_Actuals_For_Defaulted_Parameters
21973 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21974 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21975
21976 @noindent
21977 Flag each actual parameter to a subprogram or entry call where the
21978 corresponding formal parameter has a default expression, if positional
21979 notation is used.
21980
21981 This rule has no parameters.
21982
21983 @node Positional_Components
21984 @subsection @code{Positional_Components}
21985 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21986
21987 @noindent
21988 Flag each array, record and extension aggregate that includes positional
21989 notation.
21990
21991 This rule has no parameters.
21992
21993
21994 @node Positional_Generic_Parameters
21995 @subsection @code{Positional_Generic_Parameters}
21996 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21997
21998 @noindent
21999 Flag each instantiation using positional parameter notation.
22000
22001 This rule has no parameters.
22002
22003
22004 @node Positional_Parameters
22005 @subsection @code{Positional_Parameters}
22006 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22007
22008 @noindent
22009 Flag each subprogram or entry call using positional parameter notation,
22010 except for the following:
22011
22012 @itemize @bullet
22013 @item
22014 Invocations of prefix or infix operators are not flagged
22015 @item
22016 If the called subprogram or entry has only one formal parameter,
22017 the call is not flagged;
22018 @item
22019 If a subprogram call uses the @emph{Object.Operation} notation, then
22020 @itemize @minus
22021 @item
22022 the first parameter (that is, @emph{Object}) is not flagged;
22023 @item
22024 if the called subprogram has only two parameters, the second parameter
22025 of the call is not flagged;
22026 @end itemize
22027 @end itemize
22028
22029 @noindent
22030 This rule has no parameters.
22031
22032
22033
22034
22035 @node Predefined_Numeric_Types
22036 @subsection @code{Predefined_Numeric_Types}
22037 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22038
22039 @noindent
22040 Flag each explicit use of the name of any numeric type or subtype defined
22041 in package @code{Standard}.
22042
22043 The rationale for this rule is to detect when the
22044 program may depend on platform-specific characteristics of the implementation
22045 of the predefined numeric types. Note that this rule is over-pessimistic;
22046 for example, a program that uses @code{String} indexing
22047 likely needs a variable of type @code{Integer}.
22048 Another example is the flagging of predefined numeric types with explicit
22049 constraints:
22050
22051 @smallexample @c ada
22052 subtype My_Integer is Integer range Left .. Right;
22053 Vy_Var : My_Integer;
22054 @end smallexample
22055
22056 @noindent
22057 This rule detects only numeric types and subtypes defined in
22058 @code{Standard}. The use of numeric types and subtypes defined in other
22059 predefined packages (such as @code{System.Any_Priority} or
22060 @code{Ada.Text_IO.Count}) is not flagged
22061
22062 This rule has no parameters.
22063
22064
22065
22066 @node Raising_External_Exceptions
22067 @subsection @code{Raising_External_Exceptions}
22068 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22069
22070 @noindent
22071 Flag any @code{raise} statement, in a program unit declared in a library
22072 package or in a generic library package, for an exception that is
22073 neither a predefined exception nor an exception that is also declared (or
22074 renamed) in the visible part of the package.
22075
22076 This rule has no parameters.
22077
22078
22079
22080 @node Raising_Predefined_Exceptions
22081 @subsection @code{Raising_Predefined_Exceptions}
22082 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22083
22084 @noindent
22085 Flag each @code{raise} statement that raises a predefined exception
22086 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22087 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22088
22089 This rule has no parameters.
22090
22091 @node Separate_Numeric_Error_Handlers
22092 @subsection @code{Separate_Numeric_Error_Handlers}
22093 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22094
22095 @noindent
22096 Flags each exception handler that contains a choice for
22097 the predefined @code{Constraint_Error} exception, but does not contain
22098 the choice for the predefined @code{Numeric_Error} exception, or
22099 that contains the choice for @code{Numeric_Error}, but does not contain the
22100 choice for @code{Constraint_Error}.
22101
22102 This rule has no parameters.
22103
22104 @ignore
22105 @node Recursion
22106 @subsection @code{Recursion} (under construction, GLOBAL)
22107 @cindex @code{Recursion} rule (for @command{gnatcheck})
22108
22109 @noindent
22110 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22111 calls, of recursive subprograms are detected.
22112
22113 This rule has no parameters.
22114 @end ignore
22115
22116 @ignore
22117 @node Side_Effect_Functions
22118 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22119 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22120
22121 @noindent
22122 Flag functions with side effects.
22123
22124 We define a side effect as changing any data object that is not local for the
22125 body of this function.
22126
22127 At the moment, we do NOT consider a side effect any input-output operations
22128 (changing a state or a content of any file).
22129
22130 We do not consider protected functions for this rule (???)
22131
22132 There are the following sources of side effect:
22133
22134 @enumerate
22135 @item Explicit (or direct) side-effect:
22136
22137 @itemize @bullet
22138 @item
22139 direct assignment to a non-local variable;
22140
22141 @item
22142 direct call to an entity that is known to change some data object that is
22143 not local for the body of this function (Note, that if F1 calls F2 and F2
22144 does have a side effect, this does not automatically mean that F1 also
22145 have a side effect, because it may be the case that F2 is declared in
22146 F1's body and it changes some data object that is global for F2, but
22147 local for F1);
22148 @end itemize
22149
22150 @item Indirect side-effect:
22151 @itemize @bullet
22152 @item
22153 Subprogram calls implicitly issued by:
22154 @itemize @bullet
22155 @item
22156 computing initialization expressions from type declarations as a part
22157 of object elaboration or allocator evaluation;
22158 @item
22159 computing implicit parameters of subprogram or entry calls or generic
22160 instantiations;
22161 @end itemize
22162
22163 @item
22164 activation of a task that change some non-local data object (directly or
22165 indirectly);
22166
22167 @item
22168 elaboration code of a package that is a result of a package instantiation;
22169
22170 @item
22171 controlled objects;
22172 @end itemize
22173
22174 @item Situations when we can suspect a side-effect, but the full static check
22175 is either impossible or too hard:
22176 @itemize @bullet
22177 @item
22178 assignment to access variables or to the objects pointed by access
22179 variables;
22180
22181 @item
22182 call to a subprogram pointed by access-to-subprogram value
22183
22184 @item
22185 dispatching calls;
22186 @end itemize
22187 @end enumerate
22188
22189 @noindent
22190 This rule has no parameters.
22191 @end ignore
22192
22193 @node Slices
22194 @subsection @code{Slices}
22195 @cindex @code{Slices} rule (for @command{gnatcheck})
22196
22197 @noindent
22198 Flag all uses of array slicing
22199
22200 This rule has no parameters.
22201
22202
22203 @node Unassigned_OUT_Parameters
22204 @subsection @code{Unassigned_OUT_Parameters}
22205 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22206
22207 @noindent
22208 Flags procedures' @code{out} parameters that are not assigned, and
22209 identifies the contexts in which the assignments are missing.
22210
22211 An @code{out} parameter is flagged in the statements in the procedure
22212 body's handled sequence of statements (before the procedure body's
22213 @code{exception} part, if any) if this sequence of statements contains
22214 no assignments to the parameter.
22215
22216 An @code{out} parameter is flagged in an exception handler in the exception
22217 part of the procedure body's handled sequence of statements if the handler
22218 contains no assignment to the parameter.
22219
22220 Bodies of generic procedures are also considered.
22221
22222 The following are treated as assignments to an @code{out} parameter:
22223
22224 @itemize @bullet
22225 @item
22226 an assignment statement, with the parameter or some component as the target;
22227
22228 @item
22229 passing the parameter (or one of its components) as an @code{out} or
22230 @code{in out} parameter.
22231 @end itemize
22232
22233 @noindent
22234 This rule does not have any parameters.
22235
22236
22237
22238 @node Uncommented_BEGIN_In_Package_Bodies
22239 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22240 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22241
22242 @noindent
22243 Flags each package body with declarations and a statement part that does not
22244 include a trailing comment on the line containing the @code{begin} keyword;
22245 this trailing comment needs to specify the package name and nothing else.
22246 The @code{begin} is not flagged if the package body does not
22247 contain any declarations.
22248
22249 If the @code{begin} keyword is placed on the
22250 same line as the last declaration or the first statement, it is flagged
22251 independently of whether the line contains a trailing comment. The
22252 diagnostic message is attached to the line containing the first statement.
22253
22254 This rule has no parameters.
22255
22256
22257 @node Unconstrained_Array_Returns
22258 @subsection @code{Unconstrained_Array_Returns}
22259 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22260
22261 @noindent
22262 Flag each function returning an unconstrained array. Function declarations,
22263 function bodies (and body stubs) having no separate specifications,
22264 and generic function instantiations are checked.
22265 Generic function declarations, function calls and function renamings are
22266 not checked.
22267
22268 This rule has no parameters.
22269
22270 @node Universal_Ranges
22271 @subsection @code{Universal_Ranges}
22272 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22273
22274 @noindent
22275 Flag discrete ranges that are a part of an index constraint, constrained
22276 array definition, or @code{for}-loop parameter specification, and whose bounds
22277 are both of type @i{universal_integer}. Ranges that have at least one
22278 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22279 or an expression of non-universal type) are not flagged.
22280
22281 This rule has no parameters.
22282
22283
22284 @node Unnamed_Blocks_And_Loops
22285 @subsection @code{Unnamed_Blocks_And_Loops}
22286 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22287
22288 @noindent
22289 Flag each unnamed block statement and loop statement.
22290
22291 The rule has no parameters.
22292
22293
22294
22295 @ignore
22296 @node Unused_Subprograms
22297 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22298 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22299
22300 @noindent
22301 Flag all unused subprograms.
22302
22303 This rule has no parameters.
22304 @end ignore
22305
22306
22307
22308
22309 @node USE_PACKAGE_Clauses
22310 @subsection @code{USE_PACKAGE_Clauses}
22311 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22312
22313 @noindent
22314 Flag all @code{use} clauses for packages; @code{use type} clauses are
22315 not flagged.
22316
22317 This rule has no parameters.
22318
22319
22320
22321 @node Volatile_Objects_Without_Address_Clauses
22322 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22323 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22324
22325 @noindent
22326 Flag each volatile object that does not have an address clause.
22327
22328 The following check is made: if the pragma @code{Volatile} is applied to a
22329 data object or to its type, then an address clause must
22330 be supplied for this object.
22331
22332 This rule does not check the components of data objects,
22333 array components that are volatile as a result of the pragma
22334 @code{Volatile_Components}, or objects that are volatile because
22335 they are atomic as a result of pragmas @code{Atomic} or
22336 @code{Atomic_Components}.
22337
22338 Only variable declarations, and not constant declarations, are checked.
22339
22340 This rule has no parameters.
22341
22342
22343 @c *********************************
22344 @node Creating Sample Bodies Using gnatstub
22345 @chapter Creating Sample Bodies Using @command{gnatstub}
22346 @findex gnatstub
22347
22348 @noindent
22349 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22350 for library unit declarations.
22351
22352 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22353 driver (see @ref{The GNAT Driver and Project Files}).
22354
22355 To create a body stub, @command{gnatstub} has to compile the library
22356 unit declaration. Therefore, bodies can be created only for legal
22357 library units. Moreover, if a library unit depends semantically upon
22358 units located outside the current directory, you have to provide
22359 the source search path when calling @command{gnatstub}, see the description
22360 of @command{gnatstub} switches below.
22361
22362 By default, all the program unit body stubs generated by @code{gnatstub}
22363 raise the predefined @code{Program_Error} exception, which will catch
22364 accidental calls of generated stubs. This behavior can be changed with
22365 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22366
22367 @menu
22368 * Running gnatstub::
22369 * Switches for gnatstub::
22370 @end menu
22371
22372 @node Running gnatstub
22373 @section Running @command{gnatstub}
22374
22375 @noindent
22376 @command{gnatstub} has the command-line interface of the form
22377
22378 @smallexample
22379 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22380 @end smallexample
22381
22382 @noindent
22383 where
22384 @table @var
22385 @item filename
22386 is the name of the source file that contains a library unit declaration
22387 for which a body must be created. The file name may contain the path
22388 information.
22389 The file name does not have to follow the GNAT file name conventions. If the
22390 name
22391 does not follow GNAT file naming conventions, the name of the body file must
22392 be provided
22393 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22394 If the file name follows the GNAT file naming
22395 conventions and the name of the body file is not provided,
22396 @command{gnatstub}
22397 creates the name
22398 of the body file from the argument file name by replacing the @file{.ads}
22399 suffix
22400 with the @file{.adb} suffix.
22401
22402 @item directory
22403 indicates the directory in which the body stub is to be placed (the default
22404 is the
22405 current directory)
22406
22407 @item switches
22408 is an optional sequence of switches as described in the next section
22409 @end table
22410
22411 @node Switches for gnatstub
22412 @section Switches for @command{gnatstub}
22413
22414 @table @option
22415 @c !sort!
22416
22417 @item ^-f^/FULL^
22418 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22419 If the destination directory already contains a file with the name of the
22420 body file
22421 for the argument spec file, replace it with the generated body stub.
22422
22423 @item ^-hs^/HEADER=SPEC^
22424 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22425 Put the comment header (i.e., all the comments preceding the
22426 compilation unit) from the source of the library unit declaration
22427 into the body stub.
22428
22429 @item ^-hg^/HEADER=GENERAL^
22430 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22431 Put a sample comment header into the body stub.
22432
22433 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22434 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22435 Use the content of the file as the comment header for a generated body stub.
22436
22437 @ifclear vms
22438 @item -IDIR
22439 @cindex @option{-IDIR} (@command{gnatstub})
22440 @itemx -I-
22441 @cindex @option{-I-} (@command{gnatstub})
22442 @end ifclear
22443 @ifset vms
22444 @item /NOCURRENT_DIRECTORY
22445 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22446 @end ifset
22447 ^These switches have ^This switch has^ the same meaning as in calls to
22448 @command{gcc}.
22449 ^They define ^It defines ^ the source search path in the call to
22450 @command{gcc} issued
22451 by @command{gnatstub} to compile an argument source file.
22452
22453 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22454 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22455 This switch has the same meaning as in calls to @command{gcc}.
22456 It defines the additional configuration file to be passed to the call to
22457 @command{gcc} issued
22458 by @command{gnatstub} to compile an argument source file.
22459
22460 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22461 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22462 (@var{n} is a non-negative integer). Set the maximum line length in the
22463 body stub to @var{n}; the default is 79. The maximum value that can be
22464 specified is 32767. Note that in the special case of configuration
22465 pragma files, the maximum is always 32767 regardless of whether or
22466 not this switch appears.
22467
22468 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22469 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22470 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22471 the generated body sample to @var{n}.
22472 The default indentation is 3.
22473
22474 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22475 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22476 Order local bodies alphabetically. (By default local bodies are ordered
22477 in the same way as the corresponding local specs in the argument spec file.)
22478
22479 @item ^-i^/INDENTATION=^@var{n}
22480 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22481 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22482
22483 @item ^-k^/TREE_FILE=SAVE^
22484 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22485 Do not remove the tree file (i.e., the snapshot of the compiler internal
22486 structures used by @command{gnatstub}) after creating the body stub.
22487
22488 @item ^-l^/LINE_LENGTH=^@var{n}
22489 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22490 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22491
22492 @item ^--no-exception^/NO_EXCEPTION^
22493 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22494 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22495 This is not always possible for function stubs.
22496
22497 @item ^-o ^/BODY=^@var{body-name}
22498 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22499 Body file name. This should be set if the argument file name does not
22500 follow
22501 the GNAT file naming
22502 conventions. If this switch is omitted the default name for the body will be
22503 obtained
22504 from the argument file name according to the GNAT file naming conventions.
22505
22506 @item ^-q^/QUIET^
22507 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22508 Quiet mode: do not generate a confirmation when a body is
22509 successfully created, and do not generate a message when a body is not
22510 required for an
22511 argument unit.
22512
22513 @item ^-r^/TREE_FILE=REUSE^
22514 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22515 Reuse the tree file (if it exists) instead of creating it. Instead of
22516 creating the tree file for the library unit declaration, @command{gnatstub}
22517 tries to find it in the current directory and use it for creating
22518 a body. If the tree file is not found, no body is created. This option
22519 also implies @option{^-k^/SAVE^}, whether or not
22520 the latter is set explicitly.
22521
22522 @item ^-t^/TREE_FILE=OVERWRITE^
22523 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22524 Overwrite the existing tree file. If the current directory already
22525 contains the file which, according to the GNAT file naming rules should
22526 be considered as a tree file for the argument source file,
22527 @command{gnatstub}
22528 will refuse to create the tree file needed to create a sample body
22529 unless this option is set.
22530
22531 @item ^-v^/VERBOSE^
22532 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22533 Verbose mode: generate version information.
22534
22535 @end table
22536
22537 @c *********************************
22538 @node Generating Ada Bindings for C and C++ headers
22539 @chapter Generating Ada Bindings for C and C++ headers
22540 @findex binding
22541
22542 @noindent
22543 GNAT now comes with a new experimental binding generator for C and C++
22544 headers which is intended to do 95% of the tedious work of generating
22545 Ada specs from C or C++ header files. Note that this still is a work in
22546 progress, not designed to generate 100% correct Ada specs.
22547
22548 The code generated is using the Ada 2005 syntax, which makes it
22549 easier to interface with other languages than previous versions of Ada.
22550
22551 @menu
22552 * Running the binding generator::
22553 * Generating bindings for C++ headers::
22554 * Switches::
22555 @end menu
22556
22557 @node Running the binding generator
22558 @section Running the binding generator
22559
22560 @noindent
22561 The binding generator is part of the @command{gcc} compiler and can be
22562 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22563 spec files for the header files specified on the command line, and all
22564 header files needed by these files transitivitely. For example:
22565
22566 @smallexample
22567 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22568 $ gcc -c -gnat05 *.ads
22569 @end smallexample
22570
22571 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22572 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22573 correspond to the files @file{/usr/include/time.h},
22574 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22575 mode these Ada specs.
22576
22577 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22578 and will attempt to generate corresponding Ada comments.
22579
22580 If you want to generate a single Ada file and not the transitive closure, you
22581 can use instead the @option{-fdump-ada-spec-slim} switch.
22582
22583 Note that we recommend when possible to use the @command{g++} driver to
22584 generate bindings, even for most C headers, since this will in general
22585 generate better Ada specs. For generating bindings for C++ headers, it is
22586 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22587 is equivalent in this case. If @command{g++} cannot work on your C headers
22588 because of incompatibilities between C and C++, then you can fallback to
22589 @command{gcc} instead.
22590
22591 For an example of better bindings generated from the C++ front-end,
22592 the name of the parameters (when available) are actually ignored by the C
22593 front-end. Consider the following C header:
22594
22595 @smallexample
22596 extern void foo (int variable);
22597 @end smallexample
22598
22599 with the C front-end, @code{variable} is ignored, and the above is handled as:
22600
22601 @smallexample
22602 extern void foo (int);
22603 @end smallexample
22604
22605 generating a generic:
22606
22607 @smallexample
22608 procedure foo (param1 : int);
22609 @end smallexample
22610
22611 with the C++ front-end, the name is available, and we generate:
22612
22613 @smallexample
22614 procedure foo (variable : int);
22615 @end smallexample
22616
22617 In some cases, the generated bindings will be more complete or more meaningful
22618 when defining some macros, which you can do via the @option{-D} switch. This
22619 is for example the case with @file{Xlib.h} under GNU/Linux:
22620
22621 @smallexample
22622 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22623 @end smallexample
22624
22625 The above will generate more complete bindings than a straight call without
22626 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22627
22628 In other cases, it is not possible to parse a header file in a stand alone
22629 manner, because other include files need to be included first. In this
22630 case, the solution is to create a small header file including the needed
22631 @code{#include} and possible @code{#define} directives. For example, to
22632 generate Ada bindings for @file{readline/readline.h}, you need to first
22633 include @file{stdio.h}, so you can create a file with the following two
22634 lines in e.g. @file{readline1.h}:
22635
22636 @smallexample
22637 #include <stdio.h>
22638 #include <readline/readline.h>
22639 @end smallexample
22640
22641 and then generate Ada bindings from this file:
22642
22643 @smallexample
22644 $ g++ -c -fdump-ada-spec readline1.h
22645 @end smallexample
22646
22647 @node Generating bindings for C++ headers
22648 @section Generating bindings for C++ headers
22649
22650 @noindent
22651 Generating bindings for C++ headers is done using the same options, always
22652 with the @command{g++} compiler.
22653
22654 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22655 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22656 multiple inheritance of abstract classes will be mapped to Ada interfaces
22657 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22658 information on interfacing to C++).
22659
22660 For example, given the following C++ header file:
22661
22662 @smallexample
22663 @group
22664 @cartouche
22665 class Carnivore @{
22666 public:
22667 virtual int Number_Of_Teeth () = 0;
22668 @};
22669
22670 class Domestic @{
22671 public:
22672 virtual void Set_Owner (char* Name) = 0;
22673 @};
22674
22675 class Animal @{
22676 public:
22677 int Age_Count;
22678 virtual void Set_Age (int New_Age);
22679 @};
22680
22681 class Dog : Animal, Carnivore, Domestic @{
22682 public:
22683 int Tooth_Count;
22684 char *Owner;
22685
22686 virtual int Number_Of_Teeth ();
22687 virtual void Set_Owner (char* Name);
22688
22689 Dog();
22690 @};
22691 @end cartouche
22692 @end group
22693 @end smallexample
22694
22695 The corresponding Ada code is generated:
22696
22697 @smallexample @c ada
22698 @group
22699 @cartouche
22700 package Class_Carnivore is
22701 type Carnivore is limited interface;
22702 pragma Import (CPP, Carnivore);
22703
22704 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22705 end;
22706 use Class_Carnivore;
22707
22708 package Class_Domestic is
22709 type Domestic is limited interface;
22710 pragma Import (CPP, Domestic);
22711
22712 procedure Set_Owner
22713 (this : access Domestic;
22714 Name : Interfaces.C.Strings.chars_ptr) is abstract;
22715 end;
22716 use Class_Domestic;
22717
22718 package Class_Animal is
22719 type Animal is tagged limited record
22720 Age_Count : aliased int;
22721 end record;
22722 pragma Import (CPP, Animal);
22723
22724 procedure Set_Age (this : access Animal; New_Age : int);
22725 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22726 end;
22727 use Class_Animal;
22728
22729 package Class_Dog is
22730 type Dog is new Animal and Carnivore and Domestic with record
22731 Tooth_Count : aliased int;
22732 Owner : Interfaces.C.Strings.chars_ptr;
22733 end record;
22734 pragma Import (CPP, Dog);
22735
22736 function Number_Of_Teeth (this : access Dog) return int;
22737 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22738
22739 procedure Set_Owner
22740 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22741 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22742
22743 function New_Dog return Dog'Class;
22744 pragma CPP_Constructor (New_Dog);
22745 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22746 end;
22747 use Class_Dog;
22748 @end cartouche
22749 @end group
22750 @end smallexample
22751
22752 @node Switches
22753 @section Switches
22754
22755 @table @option
22756 @item -fdump-ada-spec
22757 @cindex @option{-fdump-ada-spec} (@command{gcc})
22758 Generate Ada spec files for the given header files transitively (including
22759 all header files that these headers depend upon).
22760
22761 @item -fdump-ada-spec-slim
22762 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22763 Generate Ada spec files for the header files specified on the command line
22764 only.
22765
22766 @item -C
22767 @cindex @option{-C} (@command{gcc})
22768 Extract comments from headers and generate Ada comments in the Ada spec files.
22769 @end table
22770
22771 @node Other Utility Programs
22772 @chapter Other Utility Programs
22773
22774 @noindent
22775 This chapter discusses some other utility programs available in the Ada
22776 environment.
22777
22778 @menu
22779 * Using Other Utility Programs with GNAT::
22780 * The External Symbol Naming Scheme of GNAT::
22781 * Converting Ada Files to html with gnathtml::
22782 * Installing gnathtml::
22783 @ifset vms
22784 * LSE::
22785 * Profiling::
22786 @end ifset
22787 @end menu
22788
22789 @node Using Other Utility Programs with GNAT
22790 @section Using Other Utility Programs with GNAT
22791
22792 @noindent
22793 The object files generated by GNAT are in standard system format and in
22794 particular the debugging information uses this format. This means
22795 programs generated by GNAT can be used with existing utilities that
22796 depend on these formats.
22797
22798 @ifclear vms
22799 In general, any utility program that works with C will also often work with
22800 Ada programs generated by GNAT. This includes software utilities such as
22801 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22802 as Purify.
22803 @end ifclear
22804
22805 @node The External Symbol Naming Scheme of GNAT
22806 @section The External Symbol Naming Scheme of GNAT
22807
22808 @noindent
22809 In order to interpret the output from GNAT, when using tools that are
22810 originally intended for use with other languages, it is useful to
22811 understand the conventions used to generate link names from the Ada
22812 entity names.
22813
22814 All link names are in all lowercase letters. With the exception of library
22815 procedure names, the mechanism used is simply to use the full expanded
22816 Ada name with dots replaced by double underscores. For example, suppose
22817 we have the following package spec:
22818
22819 @smallexample @c ada
22820 @group
22821 @cartouche
22822 package QRS is
22823 MN : Integer;
22824 end QRS;
22825 @end cartouche
22826 @end group
22827 @end smallexample
22828
22829 @noindent
22830 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22831 the corresponding link name is @code{qrs__mn}.
22832 @findex Export
22833 Of course if a @code{pragma Export} is used this may be overridden:
22834
22835 @smallexample @c ada
22836 @group
22837 @cartouche
22838 package Exports is
22839 Var1 : Integer;
22840 pragma Export (Var1, C, External_Name => "var1_name");
22841 Var2 : Integer;
22842 pragma Export (Var2, C, Link_Name => "var2_link_name");
22843 end Exports;
22844 @end cartouche
22845 @end group
22846 @end smallexample
22847
22848 @noindent
22849 In this case, the link name for @var{Var1} is whatever link name the
22850 C compiler would assign for the C function @var{var1_name}. This typically
22851 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22852 system conventions, but other possibilities exist. The link name for
22853 @var{Var2} is @var{var2_link_name}, and this is not operating system
22854 dependent.
22855
22856 @findex _main
22857 One exception occurs for library level procedures. A potential ambiguity
22858 arises between the required name @code{_main} for the C main program,
22859 and the name we would otherwise assign to an Ada library level procedure
22860 called @code{Main} (which might well not be the main program).
22861
22862 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22863 names. So if we have a library level procedure such as
22864
22865 @smallexample @c ada
22866 @group
22867 @cartouche
22868 procedure Hello (S : String);
22869 @end cartouche
22870 @end group
22871 @end smallexample
22872
22873 @noindent
22874 the external name of this procedure will be @var{_ada_hello}.
22875
22876
22877 @node Converting Ada Files to html with gnathtml
22878 @section Converting Ada Files to HTML with @code{gnathtml}
22879
22880 @noindent
22881 This @code{Perl} script allows Ada source files to be browsed using
22882 standard Web browsers. For installation procedure, see the section
22883 @xref{Installing gnathtml}.
22884
22885 Ada reserved keywords are highlighted in a bold font and Ada comments in
22886 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22887 switch to suppress the generation of cross-referencing information, user
22888 defined variables and types will appear in a different color; you will
22889 be able to click on any identifier and go to its declaration.
22890
22891 The command line is as follow:
22892 @smallexample
22893 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22894 @end smallexample
22895
22896 @noindent
22897 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22898 an html file for every ada file, and a global file called @file{index.htm}.
22899 This file is an index of every identifier defined in the files.
22900
22901 The available ^switches^options^ are the following ones:
22902
22903 @table @option
22904 @item -83
22905 @cindex @option{-83} (@code{gnathtml})
22906 Only the Ada 83 subset of keywords will be highlighted.
22907
22908 @item -cc @var{color}
22909 @cindex @option{-cc} (@code{gnathtml})
22910 This option allows you to change the color used for comments. The default
22911 value is green. The color argument can be any name accepted by html.
22912
22913 @item -d
22914 @cindex @option{-d} (@code{gnathtml})
22915 If the Ada files depend on some other files (for instance through
22916 @code{with} clauses, the latter files will also be converted to html.
22917 Only the files in the user project will be converted to html, not the files
22918 in the run-time library itself.
22919
22920 @item -D
22921 @cindex @option{-D} (@code{gnathtml})
22922 This command is the same as @option{-d} above, but @command{gnathtml} will
22923 also look for files in the run-time library, and generate html files for them.
22924
22925 @item -ext @var{extension}
22926 @cindex @option{-ext} (@code{gnathtml})
22927 This option allows you to change the extension of the generated HTML files.
22928 If you do not specify an extension, it will default to @file{htm}.
22929
22930 @item -f
22931 @cindex @option{-f} (@code{gnathtml})
22932 By default, gnathtml will generate html links only for global entities
22933 ('with'ed units, global variables and types,@dots{}). If you specify
22934 @option{-f} on the command line, then links will be generated for local
22935 entities too.
22936
22937 @item -l @var{number}
22938 @cindex @option{-l} (@code{gnathtml})
22939 If this ^switch^option^ is provided and @var{number} is not 0, then
22940 @code{gnathtml} will number the html files every @var{number} line.
22941
22942 @item -I @var{dir}
22943 @cindex @option{-I} (@code{gnathtml})
22944 Specify a directory to search for library files (@file{.ALI} files) and
22945 source files. You can provide several -I switches on the command line,
22946 and the directories will be parsed in the order of the command line.
22947
22948 @item -o @var{dir}
22949 @cindex @option{-o} (@code{gnathtml})
22950 Specify the output directory for html files. By default, gnathtml will
22951 saved the generated html files in a subdirectory named @file{html/}.
22952
22953 @item -p @var{file}
22954 @cindex @option{-p} (@code{gnathtml})
22955 If you are using Emacs and the most recent Emacs Ada mode, which provides
22956 a full Integrated Development Environment for compiling, checking,
22957 running and debugging applications, you may use @file{.gpr} files
22958 to give the directories where Emacs can find sources and object files.
22959
22960 Using this ^switch^option^, you can tell gnathtml to use these files.
22961 This allows you to get an html version of your application, even if it
22962 is spread over multiple directories.
22963
22964 @item -sc @var{color}
22965 @cindex @option{-sc} (@code{gnathtml})
22966 This ^switch^option^ allows you to change the color used for symbol
22967 definitions.
22968 The default value is red. The color argument can be any name accepted by html.
22969
22970 @item -t @var{file}
22971 @cindex @option{-t} (@code{gnathtml})
22972 This ^switch^option^ provides the name of a file. This file contains a list of
22973 file names to be converted, and the effect is exactly as though they had
22974 appeared explicitly on the command line. This
22975 is the recommended way to work around the command line length limit on some
22976 systems.
22977
22978 @end table
22979
22980 @node Installing gnathtml
22981 @section Installing @code{gnathtml}
22982
22983 @noindent
22984 @code{Perl} needs to be installed on your machine to run this script.
22985 @code{Perl} is freely available for almost every architecture and
22986 Operating System via the Internet.
22987
22988 On Unix systems, you may want to modify the first line of the script
22989 @code{gnathtml}, to explicitly tell the Operating system where Perl
22990 is. The syntax of this line is:
22991 @smallexample
22992 #!full_path_name_to_perl
22993 @end smallexample
22994
22995 @noindent
22996 Alternatively, you may run the script using the following command line:
22997
22998 @smallexample
22999 $ perl gnathtml.pl @ovar{switches} @var{files}
23000 @end smallexample
23001
23002 @ifset vms
23003 @node LSE
23004 @section LSE
23005 @findex LSE
23006
23007 @noindent
23008 The GNAT distribution provides an Ada 95 template for the HP Language
23009 Sensitive Editor (LSE), a component of DECset. In order to
23010 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23011
23012 @node Profiling
23013 @section Profiling
23014 @findex PCA
23015
23016 @noindent
23017 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23018 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23019 the collection phase with the /DEBUG qualifier.
23020
23021 @smallexample
23022 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23023 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23024 $ RUN/DEBUG <PROGRAM_NAME>
23025 @end smallexample
23026 @noindent
23027 @end ifset
23028
23029 @ifclear vms
23030 @c ******************************
23031 @node Code Coverage and Profiling
23032 @chapter Code Coverage and Profiling
23033 @cindex Code Coverage
23034 @cindex Profiling
23035
23036 @noindent
23037 This chapter describes how to use @code{gcov} - coverage testing tool - and
23038 @code{gprof} - profiler tool - on your Ada programs.
23039
23040 @menu
23041 * Code Coverage of Ada Programs using gcov::
23042 * Profiling an Ada Program using gprof::
23043 @end menu
23044
23045 @node Code Coverage of Ada Programs using gcov
23046 @section Code Coverage of Ada Programs using gcov
23047 @cindex gcov
23048 @cindex -fprofile-arcs
23049 @cindex -ftest-coverage
23050 @cindex -coverage
23051 @cindex Code Coverage
23052
23053 @noindent
23054 @code{gcov} is a test coverage program: it analyzes the execution of a given
23055 program on selected tests, to help you determine the portions of the program
23056 that are still untested.
23057
23058 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23059 User's Guide. You can refer to this documentation for a more complete
23060 description.
23061
23062 This chapter provides a quick startup guide, and
23063 details some Gnat-specific features.
23064
23065 @menu
23066 * Quick startup guide::
23067 * Gnat specifics::
23068 @end menu
23069
23070 @node Quick startup guide
23071 @subsection Quick startup guide
23072
23073 In order to perform coverage analysis of a program using @code{gcov}, 3
23074 steps are needed:
23075
23076 @itemize @bullet
23077 @item
23078 Code instrumentation during the compilation process
23079 @item
23080 Execution of the instrumented program
23081 @item
23082 Execution of the @code{gcov} tool to generate the result.
23083 @end itemize
23084
23085 The code instrumentation needed by gcov is created at the object level:
23086 The source code is not modified in any way, because the instrumentation code is
23087 inserted by gcc during the compilation process. To compile your code with code
23088 coverage activated, you need to recompile your whole project using the
23089 switches
23090 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23091 @code{-fprofile-arcs}.
23092
23093 @smallexample
23094 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23095 -largs -fprofile-arcs
23096 @end smallexample
23097
23098 This compilation process will create @file{.gcno} files together with
23099 the usual object files.
23100
23101 Once the program is compiled with coverage instrumentation, you can
23102 run it as many times as needed - on portions of a test suite for
23103 example. The first execution will produce @file{.gcda} files at the
23104 same location as the @file{.gcno} files. The following executions
23105 will update those files, so that a cumulative result of the covered
23106 portions of the program is generated.
23107
23108 Finally, you need to call the @code{gcov} tool. The different options of
23109 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23110
23111 This will create annotated source files with a @file{.gcov} extension:
23112 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23113
23114 @node Gnat specifics
23115 @subsection Gnat specifics
23116
23117 Because Ada semantics, portions of the source code may be shared among
23118 several object files. This is the case for example when generics are
23119 involved, when inlining is active or when declarations generate initialisation
23120 calls. In order to take
23121 into account this shared code, you need to call @code{gcov} on all
23122 source files of the tested program at once.
23123
23124 The list of source files might exceed the system's maximum command line
23125 length. In order to bypass this limitation, a new mechanism has been
23126 implemented in @code{gcov}: you can now list all your project's files into a
23127 text file, and provide this file to gcov as a parameter, preceded by a @@
23128 (e.g. @samp{gcov @@mysrclist.txt}).
23129
23130 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23131 not supported as there can be unresolved symbols during the final link.
23132
23133 @node Profiling an Ada Program using gprof
23134 @section Profiling an Ada Program using gprof
23135 @cindex gprof
23136 @cindex -pg
23137 @cindex Profiling
23138
23139 @noindent
23140 This section is not meant to be an exhaustive documentation of @code{gprof}.
23141 Full documentation for it can be found in the GNU Profiler User's Guide
23142 documentation that is part of this GNAT distribution.
23143
23144 Profiling a program helps determine the parts of a program that are executed
23145 most often, and are therefore the most time-consuming.
23146
23147 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23148 better handle Ada programs and multitasking.
23149 It is currently supported on the following platforms
23150 @itemize @bullet
23151 @item
23152 linux x86/x86_64
23153 @item
23154 solaris sparc/sparc64/x86
23155 @item
23156 windows x86
23157 @end itemize
23158
23159 @noindent
23160 In order to profile a program using @code{gprof}, 3 steps are needed:
23161
23162 @itemize @bullet
23163 @item
23164 Code instrumentation, requiring a full recompilation of the project with the
23165 proper switches.
23166 @item
23167 Execution of the program under the analysis conditions, i.e. with the desired
23168 input.
23169 @item
23170 Analysis of the results using the @code{gprof} tool.
23171 @end itemize
23172
23173 @noindent
23174 The following sections detail the different steps, and indicate how
23175 to interpret the results:
23176 @menu
23177 * Compilation for profiling::
23178 * Program execution::
23179 * Running gprof::
23180 * Interpretation of profiling results::
23181 @end menu
23182
23183 @node Compilation for profiling
23184 @subsection Compilation for profiling
23185 @cindex -pg
23186 @cindex Profiling
23187
23188 In order to profile a program the first step is to tell the compiler
23189 to generate the necessary profiling information. The compiler switch to be used
23190 is @code{-pg}, which must be added to other compilation switches. This
23191 switch needs to be specified both during compilation and link stages, and can
23192 be specified once when using gnatmake:
23193
23194 @smallexample
23195 gnatmake -f -pg -P my_project
23196 @end smallexample
23197
23198 @noindent
23199 Note that only the objects that were compiled with the @samp{-pg} switch will be
23200 profiled; if you need to profile your whole project, use the
23201 @samp{-f} gnatmake switch to force full recompilation.
23202
23203 @node Program execution
23204 @subsection Program execution
23205
23206 @noindent
23207 Once the program has been compiled for profiling, you can run it as usual.
23208
23209 The only constraint imposed by profiling is that the program must terminate
23210 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23211 properly analyzed.
23212
23213 Once the program completes execution, a data file called @file{gmon.out} is
23214 generated in the directory where the program was launched from. If this file
23215 already exists, it will be overwritten.
23216
23217 @node Running gprof
23218 @subsection Running gprof
23219
23220 @noindent
23221 The @code{gprof} tool is called as follow:
23222
23223 @smallexample
23224 gprof my_prog gmon.out
23225 @end smallexample
23226
23227 @noindent
23228 or simpler:
23229
23230 @smallexample
23231 gprof my_prog
23232 @end smallexample
23233
23234 @noindent
23235 The complete form of the gprof command line is the following:
23236
23237 @smallexample
23238 gprof [^switches^options^] [executable [data-file]]
23239 @end smallexample
23240
23241 @noindent
23242 @code{gprof} supports numerous ^switch^options^. The order of these
23243 ^switch^options^ does not matter. The full list of options can be found in
23244 the GNU Profiler User's Guide documentation that comes with this documentation.
23245
23246 The following is the subset of those switches that is most relevant:
23247
23248 @table @option
23249
23250 @item --demangle[=@var{style}]
23251 @itemx --no-demangle
23252 @cindex @option{--demangle} (@code{gprof})
23253 These options control whether symbol names should be demangled when
23254 printing output. The default is to demangle C++ symbols. The
23255 @code{--no-demangle} option may be used to turn off demangling. Different
23256 compilers have different mangling styles. The optional demangling style
23257 argument can be used to choose an appropriate demangling style for your
23258 compiler, in particular Ada symbols generated by GNAT can be demangled using
23259 @code{--demangle=gnat}.
23260
23261 @item -e @var{function_name}
23262 @cindex @option{-e} (@code{gprof})
23263 The @samp{-e @var{function}} option tells @code{gprof} not to print
23264 information about the function @var{function_name} (and its
23265 children@dots{}) in the call graph. The function will still be listed
23266 as a child of any functions that call it, but its index number will be
23267 shown as @samp{[not printed]}. More than one @samp{-e} option may be
23268 given; only one @var{function_name} may be indicated with each @samp{-e}
23269 option.
23270
23271 @item -E @var{function_name}
23272 @cindex @option{-E} (@code{gprof})
23273 The @code{-E @var{function}} option works like the @code{-e} option, but
23274 execution time spent in the function (and children who were not called from
23275 anywhere else), will not be used to compute the percentages-of-time for
23276 the call graph. More than one @samp{-E} option may be given; only one
23277 @var{function_name} may be indicated with each @samp{-E} option.
23278
23279 @item -f @var{function_name}
23280 @cindex @option{-f} (@code{gprof})
23281 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23282 call graph to the function @var{function_name} and its children (and
23283 their children@dots{}). More than one @samp{-f} option may be given;
23284 only one @var{function_name} may be indicated with each @samp{-f}
23285 option.
23286
23287 @item -F @var{function_name}
23288 @cindex @option{-F} (@code{gprof})
23289 The @samp{-F @var{function}} option works like the @code{-f} option, but
23290 only time spent in the function and its children (and their
23291 children@dots{}) will be used to determine total-time and
23292 percentages-of-time for the call graph. More than one @samp{-F} option
23293 may be given; only one @var{function_name} may be indicated with each
23294 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
23295
23296 @end table
23297
23298 @node Interpretation of profiling results
23299 @subsection Interpretation of profiling results
23300
23301 @noindent
23302
23303 The results of the profiling analysis are represented by two arrays: the
23304 'flat profile' and the 'call graph'. Full documentation of those outputs
23305 can be found in the GNU Profiler User's Guide.
23306
23307 The flat profile shows the time spent in each function of the program, and how
23308 many time it has been called. This allows you to locate easily the most
23309 time-consuming functions.
23310
23311 The call graph shows, for each subprogram, the subprograms that call it,
23312 and the subprograms that it calls. It also provides an estimate of the time
23313 spent in each of those callers/called subprograms.
23314 @end ifclear
23315
23316 @c ******************************
23317 @node Running and Debugging Ada Programs
23318 @chapter Running and Debugging Ada Programs
23319 @cindex Debugging
23320
23321 @noindent
23322 This chapter discusses how to debug Ada programs.
23323 @ifset vms
23324 It applies to GNAT on the Alpha OpenVMS platform;
23325 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23326 since HP has implemented Ada support in the OpenVMS debugger on I64.
23327 @end ifset
23328
23329 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23330
23331 @enumerate
23332 @item
23333 The illegality may be a violation of the static semantics of Ada. In
23334 that case GNAT diagnoses the constructs in the program that are illegal.
23335 It is then a straightforward matter for the user to modify those parts of
23336 the program.
23337
23338 @item
23339 The illegality may be a violation of the dynamic semantics of Ada. In
23340 that case the program compiles and executes, but may generate incorrect
23341 results, or may terminate abnormally with some exception.
23342
23343 @item
23344 When presented with a program that contains convoluted errors, GNAT
23345 itself may terminate abnormally without providing full diagnostics on
23346 the incorrect user program.
23347 @end enumerate
23348
23349 @menu
23350 * The GNAT Debugger GDB::
23351 * Running GDB::
23352 * Introduction to GDB Commands::
23353 * Using Ada Expressions::
23354 * Calling User-Defined Subprograms::
23355 * Using the Next Command in a Function::
23356 * Ada Exceptions::
23357 * Ada Tasks::
23358 * Debugging Generic Units::
23359 * GNAT Abnormal Termination or Failure to Terminate::
23360 * Naming Conventions for GNAT Source Files::
23361 * Getting Internal Debugging Information::
23362 * Stack Traceback::
23363 @end menu
23364
23365 @cindex Debugger
23366 @findex gdb
23367
23368 @node The GNAT Debugger GDB
23369 @section The GNAT Debugger GDB
23370
23371 @noindent
23372 @code{GDB} is a general purpose, platform-independent debugger that
23373 can be used to debug mixed-language programs compiled with @command{gcc},
23374 and in particular is capable of debugging Ada programs compiled with
23375 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23376 complex Ada data structures.
23377
23378 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23379 @ifset vms
23380 located in the GNU:[DOCS] directory,
23381 @end ifset
23382 for full details on the usage of @code{GDB}, including a section on
23383 its usage on programs. This manual should be consulted for full
23384 details. The section that follows is a brief introduction to the
23385 philosophy and use of @code{GDB}.
23386
23387 When GNAT programs are compiled, the compiler optionally writes debugging
23388 information into the generated object file, including information on
23389 line numbers, and on declared types and variables. This information is
23390 separate from the generated code. It makes the object files considerably
23391 larger, but it does not add to the size of the actual executable that
23392 will be loaded into memory, and has no impact on run-time performance. The
23393 generation of debug information is triggered by the use of the
23394 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23395 used to carry out the compilations. It is important to emphasize that
23396 the use of these options does not change the generated code.
23397
23398 The debugging information is written in standard system formats that
23399 are used by many tools, including debuggers and profilers. The format
23400 of the information is typically designed to describe C types and
23401 semantics, but GNAT implements a translation scheme which allows full
23402 details about Ada types and variables to be encoded into these
23403 standard C formats. Details of this encoding scheme may be found in
23404 the file exp_dbug.ads in the GNAT source distribution. However, the
23405 details of this encoding are, in general, of no interest to a user,
23406 since @code{GDB} automatically performs the necessary decoding.
23407
23408 When a program is bound and linked, the debugging information is
23409 collected from the object files, and stored in the executable image of
23410 the program. Again, this process significantly increases the size of
23411 the generated executable file, but it does not increase the size of
23412 the executable program itself. Furthermore, if this program is run in
23413 the normal manner, it runs exactly as if the debug information were
23414 not present, and takes no more actual memory.
23415
23416 However, if the program is run under control of @code{GDB}, the
23417 debugger is activated. The image of the program is loaded, at which
23418 point it is ready to run. If a run command is given, then the program
23419 will run exactly as it would have if @code{GDB} were not present. This
23420 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
23421 entirely non-intrusive until a breakpoint is encountered. If no
23422 breakpoint is ever hit, the program will run exactly as it would if no
23423 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23424 the debugging information and can respond to user commands to inspect
23425 variables, and more generally to report on the state of execution.
23426
23427 @c **************
23428 @node Running GDB
23429 @section Running GDB
23430
23431 @noindent
23432 This section describes how to initiate the debugger.
23433 @c The above sentence is really just filler, but it was otherwise
23434 @c clumsy to get the first paragraph nonindented given the conditional
23435 @c nature of the description
23436
23437 @ifclear vms
23438 The debugger can be launched from a @code{GPS} menu or
23439 directly from the command line. The description below covers the latter use.
23440 All the commands shown can be used in the @code{GPS} debug console window,
23441 but there are usually more GUI-based ways to achieve the same effect.
23442 @end ifclear
23443
23444 The command to run @code{GDB} is
23445
23446 @smallexample
23447 $ ^gdb program^GDB PROGRAM^
23448 @end smallexample
23449
23450 @noindent
23451 where @code{^program^PROGRAM^} is the name of the executable file. This
23452 activates the debugger and results in a prompt for debugger commands.
23453 The simplest command is simply @code{run}, which causes the program to run
23454 exactly as if the debugger were not present. The following section
23455 describes some of the additional commands that can be given to @code{GDB}.
23456
23457 @c *******************************
23458 @node Introduction to GDB Commands
23459 @section Introduction to GDB Commands
23460
23461 @noindent
23462 @code{GDB} contains a large repertoire of commands. @xref{Top,,
23463 Debugging with GDB, gdb, Debugging with GDB},
23464 @ifset vms
23465 located in the GNU:[DOCS] directory,
23466 @end ifset
23467 for extensive documentation on the use
23468 of these commands, together with examples of their use. Furthermore,
23469 the command @command{help} invoked from within GDB activates a simple help
23470 facility which summarizes the available commands and their options.
23471 In this section we summarize a few of the most commonly
23472 used commands to give an idea of what @code{GDB} is about. You should create
23473 a simple program with debugging information and experiment with the use of
23474 these @code{GDB} commands on the program as you read through the
23475 following section.
23476
23477 @table @code
23478 @item set args @var{arguments}
23479 The @var{arguments} list above is a list of arguments to be passed to
23480 the program on a subsequent run command, just as though the arguments
23481 had been entered on a normal invocation of the program. The @code{set args}
23482 command is not needed if the program does not require arguments.
23483
23484 @item run
23485 The @code{run} command causes execution of the program to start from
23486 the beginning. If the program is already running, that is to say if
23487 you are currently positioned at a breakpoint, then a prompt will ask
23488 for confirmation that you want to abandon the current execution and
23489 restart.
23490
23491 @item breakpoint @var{location}
23492 The breakpoint command sets a breakpoint, that is to say a point at which
23493 execution will halt and @code{GDB} will await further
23494 commands. @var{location} is
23495 either a line number within a file, given in the format @code{file:linenumber},
23496 or it is the name of a subprogram. If you request that a breakpoint be set on
23497 a subprogram that is overloaded, a prompt will ask you to specify on which of
23498 those subprograms you want to breakpoint. You can also
23499 specify that all of them should be breakpointed. If the program is run
23500 and execution encounters the breakpoint, then the program
23501 stops and @code{GDB} signals that the breakpoint was encountered by
23502 printing the line of code before which the program is halted.
23503
23504 @item breakpoint exception @var{name}
23505 A special form of the breakpoint command which breakpoints whenever
23506 exception @var{name} is raised.
23507 If @var{name} is omitted,
23508 then a breakpoint will occur when any exception is raised.
23509
23510 @item print @var{expression}
23511 This will print the value of the given expression. Most simple
23512 Ada expression formats are properly handled by @code{GDB}, so the expression
23513 can contain function calls, variables, operators, and attribute references.
23514
23515 @item continue
23516 Continues execution following a breakpoint, until the next breakpoint or the
23517 termination of the program.
23518
23519 @item step
23520 Executes a single line after a breakpoint. If the next statement
23521 is a subprogram call, execution continues into (the first statement of)
23522 the called subprogram.
23523
23524 @item next
23525 Executes a single line. If this line is a subprogram call, executes and
23526 returns from the call.
23527
23528 @item list
23529 Lists a few lines around the current source location. In practice, it
23530 is usually more convenient to have a separate edit window open with the
23531 relevant source file displayed. Successive applications of this command
23532 print subsequent lines. The command can be given an argument which is a
23533 line number, in which case it displays a few lines around the specified one.
23534
23535 @item backtrace
23536 Displays a backtrace of the call chain. This command is typically
23537 used after a breakpoint has occurred, to examine the sequence of calls that
23538 leads to the current breakpoint. The display includes one line for each
23539 activation record (frame) corresponding to an active subprogram.
23540
23541 @item up
23542 At a breakpoint, @code{GDB} can display the values of variables local
23543 to the current frame. The command @code{up} can be used to
23544 examine the contents of other active frames, by moving the focus up
23545 the stack, that is to say from callee to caller, one frame at a time.
23546
23547 @item down
23548 Moves the focus of @code{GDB} down from the frame currently being
23549 examined to the frame of its callee (the reverse of the previous command),
23550
23551 @item frame @var{n}
23552 Inspect the frame with the given number. The value 0 denotes the frame
23553 of the current breakpoint, that is to say the top of the call stack.
23554
23555 @end table
23556
23557 @noindent
23558 The above list is a very short introduction to the commands that
23559 @code{GDB} provides. Important additional capabilities, including conditional
23560 breakpoints, the ability to execute command sequences on a breakpoint,
23561 the ability to debug at the machine instruction level and many other
23562 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23563 Debugging with GDB}. Note that most commands can be abbreviated
23564 (for example, c for continue, bt for backtrace).
23565
23566 @node Using Ada Expressions
23567 @section Using Ada Expressions
23568 @cindex Ada expressions
23569
23570 @noindent
23571 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23572 extensions. The philosophy behind the design of this subset is
23573
23574 @itemize @bullet
23575 @item
23576 That @code{GDB} should provide basic literals and access to operations for
23577 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23578 leaving more sophisticated computations to subprograms written into the
23579 program (which therefore may be called from @code{GDB}).
23580
23581 @item
23582 That type safety and strict adherence to Ada language restrictions
23583 are not particularly important to the @code{GDB} user.
23584
23585 @item
23586 That brevity is important to the @code{GDB} user.
23587 @end itemize
23588
23589 @noindent
23590 Thus, for brevity, the debugger acts as if there were
23591 implicit @code{with} and @code{use} clauses in effect for all user-written
23592 packages, thus making it unnecessary to fully qualify most names with
23593 their packages, regardless of context. Where this causes ambiguity,
23594 @code{GDB} asks the user's intent.
23595
23596 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23597 GDB, gdb, Debugging with GDB}.
23598
23599 @node Calling User-Defined Subprograms
23600 @section Calling User-Defined Subprograms
23601
23602 @noindent
23603 An important capability of @code{GDB} is the ability to call user-defined
23604 subprograms while debugging. This is achieved simply by entering
23605 a subprogram call statement in the form:
23606
23607 @smallexample
23608 call subprogram-name (parameters)
23609 @end smallexample
23610
23611 @noindent
23612 The keyword @code{call} can be omitted in the normal case where the
23613 @code{subprogram-name} does not coincide with any of the predefined
23614 @code{GDB} commands.
23615
23616 The effect is to invoke the given subprogram, passing it the
23617 list of parameters that is supplied. The parameters can be expressions and
23618 can include variables from the program being debugged. The
23619 subprogram must be defined
23620 at the library level within your program, and @code{GDB} will call the
23621 subprogram within the environment of your program execution (which
23622 means that the subprogram is free to access or even modify variables
23623 within your program).
23624
23625 The most important use of this facility is in allowing the inclusion of
23626 debugging routines that are tailored to particular data structures
23627 in your program. Such debugging routines can be written to provide a suitably
23628 high-level description of an abstract type, rather than a low-level dump
23629 of its physical layout. After all, the standard
23630 @code{GDB print} command only knows the physical layout of your
23631 types, not their abstract meaning. Debugging routines can provide information
23632 at the desired semantic level and are thus enormously useful.
23633
23634 For example, when debugging GNAT itself, it is crucial to have access to
23635 the contents of the tree nodes used to represent the program internally.
23636 But tree nodes are represented simply by an integer value (which in turn
23637 is an index into a table of nodes).
23638 Using the @code{print} command on a tree node would simply print this integer
23639 value, which is not very useful. But the PN routine (defined in file
23640 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23641 a useful high level representation of the tree node, which includes the
23642 syntactic category of the node, its position in the source, the integers
23643 that denote descendant nodes and parent node, as well as varied
23644 semantic information. To study this example in more detail, you might want to
23645 look at the body of the PN procedure in the stated file.
23646
23647 @node Using the Next Command in a Function
23648 @section Using the Next Command in a Function
23649
23650 @noindent
23651 When you use the @code{next} command in a function, the current source
23652 location will advance to the next statement as usual. A special case
23653 arises in the case of a @code{return} statement.
23654
23655 Part of the code for a return statement is the ``epilog'' of the function.
23656 This is the code that returns to the caller. There is only one copy of
23657 this epilog code, and it is typically associated with the last return
23658 statement in the function if there is more than one return. In some
23659 implementations, this epilog is associated with the first statement
23660 of the function.
23661
23662 The result is that if you use the @code{next} command from a return
23663 statement that is not the last return statement of the function you
23664 may see a strange apparent jump to the last return statement or to
23665 the start of the function. You should simply ignore this odd jump.
23666 The value returned is always that from the first return statement
23667 that was stepped through.
23668
23669 @node Ada Exceptions
23670 @section Breaking on Ada Exceptions
23671 @cindex Exceptions
23672
23673 @noindent
23674 You can set breakpoints that trip when your program raises
23675 selected exceptions.
23676
23677 @table @code
23678 @item break exception
23679 Set a breakpoint that trips whenever (any task in the) program raises
23680 any exception.
23681
23682 @item break exception @var{name}
23683 Set a breakpoint that trips whenever (any task in the) program raises
23684 the exception @var{name}.
23685
23686 @item break exception unhandled
23687 Set a breakpoint that trips whenever (any task in the) program raises an
23688 exception for which there is no handler.
23689
23690 @item info exceptions
23691 @itemx info exceptions @var{regexp}
23692 The @code{info exceptions} command permits the user to examine all defined
23693 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23694 argument, prints out only those exceptions whose name matches @var{regexp}.
23695 @end table
23696
23697 @node Ada Tasks
23698 @section Ada Tasks
23699 @cindex Tasks
23700
23701 @noindent
23702 @code{GDB} allows the following task-related commands:
23703
23704 @table @code
23705 @item info tasks
23706 This command shows a list of current Ada tasks, as in the following example:
23707
23708 @smallexample
23709 @iftex
23710 @leftskip=0cm
23711 @end iftex
23712 (gdb) info tasks
23713 ID TID P-ID Thread Pri State Name
23714 1 8088000 0 807e000 15 Child Activation Wait main_task
23715 2 80a4000 1 80ae000 15 Accept/Select Wait b
23716 3 809a800 1 80a4800 15 Child Activation Wait a
23717 * 4 80ae800 3 80b8000 15 Running c
23718 @end smallexample
23719
23720 @noindent
23721 In this listing, the asterisk before the first task indicates it to be the
23722 currently running task. The first column lists the task ID that is used
23723 to refer to tasks in the following commands.
23724
23725 @item break @var{linespec} task @var{taskid}
23726 @itemx break @var{linespec} task @var{taskid} if @dots{}
23727 @cindex Breakpoints and tasks
23728 These commands are like the @code{break @dots{} thread @dots{}}.
23729 @var{linespec} specifies source lines.
23730
23731 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23732 to specify that you only want @code{GDB} to stop the program when a
23733 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23734 numeric task identifiers assigned by @code{GDB}, shown in the first
23735 column of the @samp{info tasks} display.
23736
23737 If you do not specify @samp{task @var{taskid}} when you set a
23738 breakpoint, the breakpoint applies to @emph{all} tasks of your
23739 program.
23740
23741 You can use the @code{task} qualifier on conditional breakpoints as
23742 well; in this case, place @samp{task @var{taskid}} before the
23743 breakpoint condition (before the @code{if}).
23744
23745 @item task @var{taskno}
23746 @cindex Task switching
23747
23748 This command allows to switch to the task referred by @var{taskno}. In
23749 particular, This allows to browse the backtrace of the specified
23750 task. It is advised to switch back to the original task before
23751 continuing execution otherwise the scheduling of the program may be
23752 perturbed.
23753 @end table
23754
23755 @noindent
23756 For more detailed information on the tasking support,
23757 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23758
23759 @node Debugging Generic Units
23760 @section Debugging Generic Units
23761 @cindex Debugging Generic Units
23762 @cindex Generics
23763
23764 @noindent
23765 GNAT always uses code expansion for generic instantiation. This means that
23766 each time an instantiation occurs, a complete copy of the original code is
23767 made, with appropriate substitutions of formals by actuals.
23768
23769 It is not possible to refer to the original generic entities in
23770 @code{GDB}, but it is always possible to debug a particular instance of
23771 a generic, by using the appropriate expanded names. For example, if we have
23772
23773 @smallexample @c ada
23774 @group
23775 @cartouche
23776 procedure g is
23777
23778 generic package k is
23779 procedure kp (v1 : in out integer);
23780 end k;
23781
23782 package body k is
23783 procedure kp (v1 : in out integer) is
23784 begin
23785 v1 := v1 + 1;
23786 end kp;
23787 end k;
23788
23789 package k1 is new k;
23790 package k2 is new k;
23791
23792 var : integer := 1;
23793
23794 begin
23795 k1.kp (var);
23796 k2.kp (var);
23797 k1.kp (var);
23798 k2.kp (var);
23799 end;
23800 @end cartouche
23801 @end group
23802 @end smallexample
23803
23804 @noindent
23805 Then to break on a call to procedure kp in the k2 instance, simply
23806 use the command:
23807
23808 @smallexample
23809 (gdb) break g.k2.kp
23810 @end smallexample
23811
23812 @noindent
23813 When the breakpoint occurs, you can step through the code of the
23814 instance in the normal manner and examine the values of local variables, as for
23815 other units.
23816
23817 @node GNAT Abnormal Termination or Failure to Terminate
23818 @section GNAT Abnormal Termination or Failure to Terminate
23819 @cindex GNAT Abnormal Termination or Failure to Terminate
23820
23821 @noindent
23822 When presented with programs that contain serious errors in syntax
23823 or semantics,
23824 GNAT may on rare occasions experience problems in operation, such
23825 as aborting with a
23826 segmentation fault or illegal memory access, raising an internal
23827 exception, terminating abnormally, or failing to terminate at all.
23828 In such cases, you can activate
23829 various features of GNAT that can help you pinpoint the construct in your
23830 program that is the likely source of the problem.
23831
23832 The following strategies are presented in increasing order of
23833 difficulty, corresponding to your experience in using GNAT and your
23834 familiarity with compiler internals.
23835
23836 @enumerate
23837 @item
23838 Run @command{gcc} with the @option{-gnatf}. This first
23839 switch causes all errors on a given line to be reported. In its absence,
23840 only the first error on a line is displayed.
23841
23842 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23843 are encountered, rather than after compilation is terminated. If GNAT
23844 terminates prematurely or goes into an infinite loop, the last error
23845 message displayed may help to pinpoint the culprit.
23846
23847 @item
23848 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23849 mode, @command{gcc} produces ongoing information about the progress of the
23850 compilation and provides the name of each procedure as code is
23851 generated. This switch allows you to find which Ada procedure was being
23852 compiled when it encountered a code generation problem.
23853
23854 @item
23855 @cindex @option{-gnatdc} switch
23856 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23857 switch that does for the front-end what @option{^-v^VERBOSE^} does
23858 for the back end. The system prints the name of each unit,
23859 either a compilation unit or nested unit, as it is being analyzed.
23860 @item
23861 Finally, you can start
23862 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23863 front-end of GNAT, and can be run independently (normally it is just
23864 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23865 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23866 @code{where} command is the first line of attack; the variable
23867 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23868 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23869 which the execution stopped, and @code{input_file name} indicates the name of
23870 the source file.
23871 @end enumerate
23872
23873 @node Naming Conventions for GNAT Source Files
23874 @section Naming Conventions for GNAT Source Files
23875
23876 @noindent
23877 In order to examine the workings of the GNAT system, the following
23878 brief description of its organization may be helpful:
23879
23880 @itemize @bullet
23881 @item
23882 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23883
23884 @item
23885 All files prefixed with @file{^par^PAR^} are components of the parser. The
23886 numbers correspond to chapters of the Ada Reference Manual. For example,
23887 parsing of select statements can be found in @file{par-ch9.adb}.
23888
23889 @item
23890 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23891 numbers correspond to chapters of the Ada standard. For example, all
23892 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23893 addition, some features of the language require sufficient special processing
23894 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23895 dynamic dispatching, etc.
23896
23897 @item
23898 All files prefixed with @file{^exp^EXP^} perform normalization and
23899 expansion of the intermediate representation (abstract syntax tree, or AST).
23900 these files use the same numbering scheme as the parser and semantics files.
23901 For example, the construction of record initialization procedures is done in
23902 @file{exp_ch3.adb}.
23903
23904 @item
23905 The files prefixed with @file{^bind^BIND^} implement the binder, which
23906 verifies the consistency of the compilation, determines an order of
23907 elaboration, and generates the bind file.
23908
23909 @item
23910 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23911 data structures used by the front-end.
23912
23913 @item
23914 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23915 the abstract syntax tree as produced by the parser.
23916
23917 @item
23918 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23919 all entities, computed during semantic analysis.
23920
23921 @item
23922 Library management issues are dealt with in files with prefix
23923 @file{^lib^LIB^}.
23924
23925 @item
23926 @findex Ada
23927 @cindex Annex A
23928 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23929 defined in Annex A.
23930
23931 @item
23932 @findex Interfaces
23933 @cindex Annex B
23934 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23935 defined in Annex B.
23936
23937 @item
23938 @findex System
23939 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23940 both language-defined children and GNAT run-time routines.
23941
23942 @item
23943 @findex GNAT
23944 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23945 general-purpose packages, fully documented in their specs. All
23946 the other @file{.c} files are modifications of common @command{gcc} files.
23947 @end itemize
23948
23949 @node Getting Internal Debugging Information
23950 @section Getting Internal Debugging Information
23951
23952 @noindent
23953 Most compilers have internal debugging switches and modes. GNAT
23954 does also, except GNAT internal debugging switches and modes are not
23955 secret. A summary and full description of all the compiler and binder
23956 debug flags are in the file @file{debug.adb}. You must obtain the
23957 sources of the compiler to see the full detailed effects of these flags.
23958
23959 The switches that print the source of the program (reconstructed from
23960 the internal tree) are of general interest for user programs, as are the
23961 options to print
23962 the full internal tree, and the entity table (the symbol table
23963 information). The reconstructed source provides a readable version of the
23964 program after the front-end has completed analysis and expansion,
23965 and is useful when studying the performance of specific constructs.
23966 For example, constraint checks are indicated, complex aggregates
23967 are replaced with loops and assignments, and tasking primitives
23968 are replaced with run-time calls.
23969
23970 @node Stack Traceback
23971 @section Stack Traceback
23972 @cindex traceback
23973 @cindex stack traceback
23974 @cindex stack unwinding
23975
23976 @noindent
23977 Traceback is a mechanism to display the sequence of subprogram calls that
23978 leads to a specified execution point in a program. Often (but not always)
23979 the execution point is an instruction at which an exception has been raised.
23980 This mechanism is also known as @i{stack unwinding} because it obtains
23981 its information by scanning the run-time stack and recovering the activation
23982 records of all active subprograms. Stack unwinding is one of the most
23983 important tools for program debugging.
23984
23985 The first entry stored in traceback corresponds to the deepest calling level,
23986 that is to say the subprogram currently executing the instruction
23987 from which we want to obtain the traceback.
23988
23989 Note that there is no runtime performance penalty when stack traceback
23990 is enabled, and no exception is raised during program execution.
23991
23992 @menu
23993 * Non-Symbolic Traceback::
23994 * Symbolic Traceback::
23995 @end menu
23996
23997 @node Non-Symbolic Traceback
23998 @subsection Non-Symbolic Traceback
23999 @cindex traceback, non-symbolic
24000
24001 @noindent
24002 Note: this feature is not supported on all platforms. See
24003 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24004 platforms.
24005
24006 @menu
24007 * Tracebacks From an Unhandled Exception::
24008 * Tracebacks From Exception Occurrences (non-symbolic)::
24009 * Tracebacks From Anywhere in a Program (non-symbolic)::
24010 @end menu
24011
24012 @node Tracebacks From an Unhandled Exception
24013 @subsubsection Tracebacks From an Unhandled Exception
24014
24015 @noindent
24016 A runtime non-symbolic traceback is a list of addresses of call instructions.
24017 To enable this feature you must use the @option{-E}
24018 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24019 of exception information. You can retrieve this information using the
24020 @code{addr2line} tool.
24021
24022 Here is a simple example:
24023
24024 @smallexample @c ada
24025 @cartouche
24026 procedure STB is
24027
24028 procedure P1 is
24029 begin
24030 raise Constraint_Error;
24031 end P1;
24032
24033 procedure P2 is
24034 begin
24035 P1;
24036 end P2;
24037
24038 begin
24039 P2;
24040 end STB;
24041 @end cartouche
24042 @end smallexample
24043
24044 @smallexample
24045 $ gnatmake stb -bargs -E
24046 $ stb
24047
24048 Execution terminated by unhandled exception
24049 Exception name: CONSTRAINT_ERROR
24050 Message: stb.adb:5
24051 Call stack traceback locations:
24052 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24053 @end smallexample
24054
24055 @noindent
24056 As we see the traceback lists a sequence of addresses for the unhandled
24057 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24058 guess that this exception come from procedure P1. To translate these
24059 addresses into the source lines where the calls appear, the
24060 @code{addr2line} tool, described below, is invaluable. The use of this tool
24061 requires the program to be compiled with debug information.
24062
24063 @smallexample
24064 $ gnatmake -g stb -bargs -E
24065 $ stb
24066
24067 Execution terminated by unhandled exception
24068 Exception name: CONSTRAINT_ERROR
24069 Message: stb.adb:5
24070 Call stack traceback locations:
24071 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24072
24073 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24074 0x4011f1 0x77e892a4
24075
24076 00401373 at d:/stb/stb.adb:5
24077 0040138B at d:/stb/stb.adb:10
24078 0040139C at d:/stb/stb.adb:14
24079 00401335 at d:/stb/b~stb.adb:104
24080 004011C4 at /build/@dots{}/crt1.c:200
24081 004011F1 at /build/@dots{}/crt1.c:222
24082 77E892A4 in ?? at ??:0
24083 @end smallexample
24084
24085 @noindent
24086 The @code{addr2line} tool has several other useful options:
24087
24088 @table @code
24089 @item --functions
24090 to get the function name corresponding to any location
24091
24092 @item --demangle=gnat
24093 to use the gnat decoding mode for the function names. Note that
24094 for binutils version 2.9.x the option is simply @option{--demangle}.
24095 @end table
24096
24097 @smallexample
24098 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24099 0x40139c 0x401335 0x4011c4 0x4011f1
24100
24101 00401373 in stb.p1 at d:/stb/stb.adb:5
24102 0040138B in stb.p2 at d:/stb/stb.adb:10
24103 0040139C in stb at d:/stb/stb.adb:14
24104 00401335 in main at d:/stb/b~stb.adb:104
24105 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24106 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24107 @end smallexample
24108
24109 @noindent
24110 From this traceback we can see that the exception was raised in
24111 @file{stb.adb} at line 5, which was reached from a procedure call in
24112 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24113 which contains the call to the main program.
24114 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24115 and the output will vary from platform to platform.
24116
24117 It is also possible to use @code{GDB} with these traceback addresses to debug
24118 the program. For example, we can break at a given code location, as reported
24119 in the stack traceback:
24120
24121 @smallexample
24122 $ gdb -nw stb
24123 @ifclear vms
24124 @noindent
24125 Furthermore, this feature is not implemented inside Windows DLL. Only
24126 the non-symbolic traceback is reported in this case.
24127 @end ifclear
24128
24129 (gdb) break *0x401373
24130 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24131 @end smallexample
24132
24133 @noindent
24134 It is important to note that the stack traceback addresses
24135 do not change when debug information is included. This is particularly useful
24136 because it makes it possible to release software without debug information (to
24137 minimize object size), get a field report that includes a stack traceback
24138 whenever an internal bug occurs, and then be able to retrieve the sequence
24139 of calls with the same program compiled with debug information.
24140
24141 @node Tracebacks From Exception Occurrences (non-symbolic)
24142 @subsubsection Tracebacks From Exception Occurrences
24143
24144 @noindent
24145 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24146 The stack traceback is attached to the exception information string, and can
24147 be retrieved in an exception handler within the Ada program, by means of the
24148 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24149
24150 @smallexample @c ada
24151 with Ada.Text_IO;
24152 with Ada.Exceptions;
24153
24154 procedure STB is
24155
24156 use Ada;
24157 use Ada.Exceptions;
24158
24159 procedure P1 is
24160 K : Positive := 1;
24161 begin
24162 K := K - 1;
24163 exception
24164 when E : others =>
24165 Text_IO.Put_Line (Exception_Information (E));
24166 end P1;
24167
24168 procedure P2 is
24169 begin
24170 P1;
24171 end P2;
24172
24173 begin
24174 P2;
24175 end STB;
24176 @end smallexample
24177
24178 @noindent
24179 This program will output:
24180
24181 @smallexample
24182 $ stb
24183
24184 Exception name: CONSTRAINT_ERROR
24185 Message: stb.adb:12
24186 Call stack traceback locations:
24187 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24188 @end smallexample
24189
24190 @node Tracebacks From Anywhere in a Program (non-symbolic)
24191 @subsubsection Tracebacks From Anywhere in a Program
24192
24193 @noindent
24194 It is also possible to retrieve a stack traceback from anywhere in a
24195 program. For this you need to
24196 use the @code{GNAT.Traceback} API. This package includes a procedure called
24197 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24198 display procedures described below. It is not necessary to use the
24199 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24200 is invoked explicitly.
24201
24202 @noindent
24203 In the following example we compute a traceback at a specific location in
24204 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24205 convert addresses to strings:
24206
24207 @smallexample @c ada
24208 with Ada.Text_IO;
24209 with GNAT.Traceback;
24210 with GNAT.Debug_Utilities;
24211
24212 procedure STB is
24213
24214 use Ada;
24215 use GNAT;
24216 use GNAT.Traceback;
24217
24218 procedure P1 is
24219 TB : Tracebacks_Array (1 .. 10);
24220 -- We are asking for a maximum of 10 stack frames.
24221 Len : Natural;
24222 -- Len will receive the actual number of stack frames returned.
24223 begin
24224 Call_Chain (TB, Len);
24225
24226 Text_IO.Put ("In STB.P1 : ");
24227
24228 for K in 1 .. Len loop
24229 Text_IO.Put (Debug_Utilities.Image (TB (K)));
24230 Text_IO.Put (' ');
24231 end loop;
24232
24233 Text_IO.New_Line;
24234 end P1;
24235
24236 procedure P2 is
24237 begin
24238 P1;
24239 end P2;
24240
24241 begin
24242 P2;
24243 end STB;
24244 @end smallexample
24245
24246 @smallexample
24247 $ gnatmake -g stb
24248 $ stb
24249
24250 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24251 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24252 @end smallexample
24253
24254 @noindent
24255 You can then get further information by invoking the @code{addr2line}
24256 tool as described earlier (note that the hexadecimal addresses
24257 need to be specified in C format, with a leading ``0x'').
24258
24259 @node Symbolic Traceback
24260 @subsection Symbolic Traceback
24261 @cindex traceback, symbolic
24262
24263 @noindent
24264 A symbolic traceback is a stack traceback in which procedure names are
24265 associated with each code location.
24266
24267 @noindent
24268 Note that this feature is not supported on all platforms. See
24269 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24270 list of currently supported platforms.
24271
24272 @noindent
24273 Note that the symbolic traceback requires that the program be compiled
24274 with debug information. If it is not compiled with debug information
24275 only the non-symbolic information will be valid.
24276
24277 @menu
24278 * Tracebacks From Exception Occurrences (symbolic)::
24279 * Tracebacks From Anywhere in a Program (symbolic)::
24280 @end menu
24281
24282 @node Tracebacks From Exception Occurrences (symbolic)
24283 @subsubsection Tracebacks From Exception Occurrences
24284
24285 @smallexample @c ada
24286 with Ada.Text_IO;
24287 with GNAT.Traceback.Symbolic;
24288
24289 procedure STB is
24290
24291 procedure P1 is
24292 begin
24293 raise Constraint_Error;
24294 end P1;
24295
24296 procedure P2 is
24297 begin
24298 P1;
24299 end P2;
24300
24301 procedure P3 is
24302 begin
24303 P2;
24304 end P3;
24305
24306 begin
24307 P3;
24308 exception
24309 when E : others =>
24310 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24311 end STB;
24312 @end smallexample
24313
24314 @smallexample
24315 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24316 $ stb
24317
24318 0040149F in stb.p1 at stb.adb:8
24319 004014B7 in stb.p2 at stb.adb:13
24320 004014CF in stb.p3 at stb.adb:18
24321 004015DD in ada.stb at stb.adb:22
24322 00401461 in main at b~stb.adb:168
24323 004011C4 in __mingw_CRTStartup at crt1.c:200
24324 004011F1 in mainCRTStartup at crt1.c:222
24325 77E892A4 in ?? at ??:0
24326 @end smallexample
24327
24328 @noindent
24329 In the above example the ``.\'' syntax in the @command{gnatmake} command
24330 is currently required by @command{addr2line} for files that are in
24331 the current working directory.
24332 Moreover, the exact sequence of linker options may vary from platform
24333 to platform.
24334 The above @option{-largs} section is for Windows platforms. By contrast,
24335 under Unix there is no need for the @option{-largs} section.
24336 Differences across platforms are due to details of linker implementation.
24337
24338 @node Tracebacks From Anywhere in a Program (symbolic)
24339 @subsubsection Tracebacks From Anywhere in a Program
24340
24341 @noindent
24342 It is possible to get a symbolic stack traceback
24343 from anywhere in a program, just as for non-symbolic tracebacks.
24344 The first step is to obtain a non-symbolic
24345 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24346 information. Here is an example:
24347
24348 @smallexample @c ada
24349 with Ada.Text_IO;
24350 with GNAT.Traceback;
24351 with GNAT.Traceback.Symbolic;
24352
24353 procedure STB is
24354
24355 use Ada;
24356 use GNAT.Traceback;
24357 use GNAT.Traceback.Symbolic;
24358
24359 procedure P1 is
24360 TB : Tracebacks_Array (1 .. 10);
24361 -- We are asking for a maximum of 10 stack frames.
24362 Len : Natural;
24363 -- Len will receive the actual number of stack frames returned.
24364 begin
24365 Call_Chain (TB, Len);
24366 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24367 end P1;
24368
24369 procedure P2 is
24370 begin
24371 P1;
24372 end P2;
24373
24374 begin
24375 P2;
24376 end STB;
24377 @end smallexample
24378
24379 @c ******************************
24380 @ifset vms
24381 @node Compatibility with HP Ada
24382 @chapter Compatibility with HP Ada
24383 @cindex Compatibility
24384
24385 @noindent
24386 @cindex DEC Ada
24387 @cindex HP Ada
24388 @cindex Compatibility between GNAT and HP Ada
24389 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24390 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24391 GNAT is highly compatible
24392 with HP Ada, and it should generally be straightforward to port code
24393 from the HP Ada environment to GNAT. However, there are a few language
24394 and implementation differences of which the user must be aware. These
24395 differences are discussed in this chapter. In
24396 addition, the operating environment and command structure for the
24397 compiler are different, and these differences are also discussed.
24398
24399 For further details on these and other compatibility issues,
24400 see Appendix E of the HP publication
24401 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24402
24403 Except where otherwise indicated, the description of GNAT for OpenVMS
24404 applies to both the Alpha and I64 platforms.
24405
24406 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24407 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24408
24409 The discussion in this chapter addresses specifically the implementation
24410 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24411 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24412 GNAT always follows the Alpha implementation.
24413
24414 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24415 attributes are recognized, although only a subset of them can sensibly
24416 be implemented. The description of pragmas in
24417 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24418 indicates whether or not they are applicable to non-VMS systems.
24419
24420 @menu
24421 * Ada Language Compatibility::
24422 * Differences in the Definition of Package System::
24423 * Language-Related Features::
24424 * The Package STANDARD::
24425 * The Package SYSTEM::
24426 * Tasking and Task-Related Features::
24427 * Pragmas and Pragma-Related Features::
24428 * Library of Predefined Units::
24429 * Bindings::
24430 * Main Program Definition::
24431 * Implementation-Defined Attributes::
24432 * Compiler and Run-Time Interfacing::
24433 * Program Compilation and Library Management::
24434 * Input-Output::
24435 * Implementation Limits::
24436 * Tools and Utilities::
24437 @end menu
24438
24439 @node Ada Language Compatibility
24440 @section Ada Language Compatibility
24441
24442 @noindent
24443 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24444 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24445 with Ada 83, and therefore Ada 83 programs will compile
24446 and run under GNAT with
24447 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24448 provides details on specific incompatibilities.
24449
24450 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24451 as well as the pragma @code{ADA_83}, to force the compiler to
24452 operate in Ada 83 mode. This mode does not guarantee complete
24453 conformance to Ada 83, but in practice is sufficient to
24454 eliminate most sources of incompatibilities.
24455 In particular, it eliminates the recognition of the
24456 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24457 in Ada 83 programs is legal, and handles the cases of packages
24458 with optional bodies, and generics that instantiate unconstrained
24459 types without the use of @code{(<>)}.
24460
24461 @node Differences in the Definition of Package System
24462 @section Differences in the Definition of Package @code{System}
24463
24464 @noindent
24465 An Ada compiler is allowed to add
24466 implementation-dependent declarations to package @code{System}.
24467 In normal mode,
24468 GNAT does not take advantage of this permission, and the version of
24469 @code{System} provided by GNAT exactly matches that defined in the Ada
24470 Reference Manual.
24471
24472 However, HP Ada adds an extensive set of declarations to package
24473 @code{System},
24474 as fully documented in the HP Ada manuals. To minimize changes required
24475 for programs that make use of these extensions, GNAT provides the pragma
24476 @code{Extend_System} for extending the definition of package System. By using:
24477 @cindex pragma @code{Extend_System}
24478 @cindex @code{Extend_System} pragma
24479
24480 @smallexample @c ada
24481 @group
24482 @cartouche
24483 pragma Extend_System (Aux_DEC);
24484 @end cartouche
24485 @end group
24486 @end smallexample
24487
24488 @noindent
24489 the set of definitions in @code{System} is extended to include those in
24490 package @code{System.Aux_DEC}.
24491 @cindex @code{System.Aux_DEC} package
24492 @cindex @code{Aux_DEC} package (child of @code{System})
24493 These definitions are incorporated directly into package @code{System},
24494 as though they had been declared there. For a
24495 list of the declarations added, see the spec of this package,
24496 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24497 @cindex @file{s-auxdec.ads} file
24498 The pragma @code{Extend_System} is a configuration pragma, which means that
24499 it can be placed in the file @file{gnat.adc}, so that it will automatically
24500 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24501 for further details.
24502
24503 An alternative approach that avoids the use of the non-standard
24504 @code{Extend_System} pragma is to add a context clause to the unit that
24505 references these facilities:
24506
24507 @smallexample @c ada
24508 @cartouche
24509 with System.Aux_DEC;
24510 use System.Aux_DEC;
24511 @end cartouche
24512 @end smallexample
24513
24514 @noindent
24515 The effect is not quite semantically identical to incorporating
24516 the declarations directly into package @code{System},
24517 but most programs will not notice a difference
24518 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24519 to reference the entities directly in package @code{System}.
24520 For units containing such references,
24521 the prefixes must either be removed, or the pragma @code{Extend_System}
24522 must be used.
24523
24524 @node Language-Related Features
24525 @section Language-Related Features
24526
24527 @noindent
24528 The following sections highlight differences in types,
24529 representations of types, operations, alignment, and
24530 related topics.
24531
24532 @menu
24533 * Integer Types and Representations::
24534 * Floating-Point Types and Representations::
24535 * Pragmas Float_Representation and Long_Float::
24536 * Fixed-Point Types and Representations::
24537 * Record and Array Component Alignment::
24538 * Address Clauses::
24539 * Other Representation Clauses::
24540 @end menu
24541
24542 @node Integer Types and Representations
24543 @subsection Integer Types and Representations
24544
24545 @noindent
24546 The set of predefined integer types is identical in HP Ada and GNAT.
24547 Furthermore the representation of these integer types is also identical,
24548 including the capability of size clauses forcing biased representation.
24549
24550 In addition,
24551 HP Ada for OpenVMS Alpha systems has defined the
24552 following additional integer types in package @code{System}:
24553
24554 @itemize @bullet
24555
24556 @item
24557 @code{INTEGER_8}
24558
24559 @item
24560 @code{INTEGER_16}
24561
24562 @item
24563 @code{INTEGER_32}
24564
24565 @item
24566 @code{INTEGER_64}
24567
24568 @item
24569 @code{LARGEST_INTEGER}
24570 @end itemize
24571
24572 @noindent
24573 In GNAT, the first four of these types may be obtained from the
24574 standard Ada package @code{Interfaces}.
24575 Alternatively, by use of the pragma @code{Extend_System}, identical
24576 declarations can be referenced directly in package @code{System}.
24577 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24578
24579 @node Floating-Point Types and Representations
24580 @subsection Floating-Point Types and Representations
24581 @cindex Floating-Point types
24582
24583 @noindent
24584 The set of predefined floating-point types is identical in HP Ada and GNAT.
24585 Furthermore the representation of these floating-point
24586 types is also identical. One important difference is that the default
24587 representation for HP Ada is @code{VAX_Float}, but the default representation
24588 for GNAT is IEEE.
24589
24590 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24591 pragma @code{Float_Representation} as described in the HP Ada
24592 documentation.
24593 For example, the declarations:
24594
24595 @smallexample @c ada
24596 @cartouche
24597 type F_Float is digits 6;
24598 pragma Float_Representation (VAX_Float, F_Float);
24599 @end cartouche
24600 @end smallexample
24601
24602 @noindent
24603 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24604 format.
24605 This set of declarations actually appears in @code{System.Aux_DEC},
24606 which contains
24607 the full set of additional floating-point declarations provided in
24608 the HP Ada version of package @code{System}.
24609 This and similar declarations may be accessed in a user program
24610 by using pragma @code{Extend_System}. The use of this
24611 pragma, and the related pragma @code{Long_Float} is described in further
24612 detail in the following section.
24613
24614 @node Pragmas Float_Representation and Long_Float
24615 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24616
24617 @noindent
24618 HP Ada provides the pragma @code{Float_Representation}, which
24619 acts as a program library switch to allow control over
24620 the internal representation chosen for the predefined
24621 floating-point types declared in the package @code{Standard}.
24622 The format of this pragma is as follows:
24623
24624 @smallexample @c ada
24625 @cartouche
24626 pragma Float_Representation(VAX_Float | IEEE_Float);
24627 @end cartouche
24628 @end smallexample
24629
24630 @noindent
24631 This pragma controls the representation of floating-point
24632 types as follows:
24633
24634 @itemize @bullet
24635 @item
24636 @code{VAX_Float} specifies that floating-point
24637 types are represented by default with the VAX system hardware types
24638 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24639 Note that the @code{H-floating}
24640 type was available only on VAX systems, and is not available
24641 in either HP Ada or GNAT.
24642
24643 @item
24644 @code{IEEE_Float} specifies that floating-point
24645 types are represented by default with the IEEE single and
24646 double floating-point types.
24647 @end itemize
24648
24649 @noindent
24650 GNAT provides an identical implementation of the pragma
24651 @code{Float_Representation}, except that it functions as a
24652 configuration pragma. Note that the
24653 notion of configuration pragma corresponds closely to the
24654 HP Ada notion of a program library switch.
24655
24656 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24657 which is different
24658 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24659 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24660 advisable to change the format of numbers passed to standard library
24661 routines, and if necessary explicit type conversions may be needed.
24662
24663 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24664 efficient, and (given that it conforms to an international standard)
24665 potentially more portable.
24666 The situation in which @code{VAX_Float} may be useful is in interfacing
24667 to existing code and data that expect the use of @code{VAX_Float}.
24668 In such a situation use the predefined @code{VAX_Float}
24669 types in package @code{System}, as extended by
24670 @code{Extend_System}. For example, use @code{System.F_Float}
24671 to specify the 32-bit @code{F-Float} format.
24672
24673 @noindent
24674 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24675 to allow control over the internal representation chosen
24676 for the predefined type @code{Long_Float} and for floating-point
24677 type declarations with digits specified in the range 7 .. 15.
24678 The format of this pragma is as follows:
24679
24680 @smallexample @c ada
24681 @cartouche
24682 pragma Long_Float (D_FLOAT | G_FLOAT);
24683 @end cartouche
24684 @end smallexample
24685
24686 @node Fixed-Point Types and Representations
24687 @subsection Fixed-Point Types and Representations
24688
24689 @noindent
24690 On HP Ada for OpenVMS Alpha systems, rounding is
24691 away from zero for both positive and negative numbers.
24692 Therefore, @code{+0.5} rounds to @code{1},
24693 and @code{-0.5} rounds to @code{-1}.
24694
24695 On GNAT the results of operations
24696 on fixed-point types are in accordance with the Ada
24697 rules. In particular, results of operations on decimal
24698 fixed-point types are truncated.
24699
24700 @node Record and Array Component Alignment
24701 @subsection Record and Array Component Alignment
24702
24703 @noindent
24704 On HP Ada for OpenVMS Alpha, all non-composite components
24705 are aligned on natural boundaries. For example, 1-byte
24706 components are aligned on byte boundaries, 2-byte
24707 components on 2-byte boundaries, 4-byte components on 4-byte
24708 byte boundaries, and so on. The OpenVMS Alpha hardware
24709 runs more efficiently with naturally aligned data.
24710
24711 On GNAT, alignment rules are compatible
24712 with HP Ada for OpenVMS Alpha.
24713
24714 @node Address Clauses
24715 @subsection Address Clauses
24716
24717 @noindent
24718 In HP Ada and GNAT, address clauses are supported for
24719 objects and imported subprograms.
24720 The predefined type @code{System.Address} is a private type
24721 in both compilers on Alpha OpenVMS, with the same representation
24722 (it is simply a machine pointer). Addition, subtraction, and comparison
24723 operations are available in the standard Ada package
24724 @code{System.Storage_Elements}, or in package @code{System}
24725 if it is extended to include @code{System.Aux_DEC} using a
24726 pragma @code{Extend_System} as previously described.
24727
24728 Note that code that @code{with}'s both this extended package @code{System}
24729 and the package @code{System.Storage_Elements} should not @code{use}
24730 both packages, or ambiguities will result. In general it is better
24731 not to mix these two sets of facilities. The Ada package was
24732 designed specifically to provide the kind of features that HP Ada
24733 adds directly to package @code{System}.
24734
24735 The type @code{System.Address} is a 64-bit integer type in GNAT for
24736 I64 OpenVMS. For more information,
24737 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24738
24739 GNAT is compatible with HP Ada in its handling of address
24740 clauses, except for some limitations in
24741 the form of address clauses for composite objects with
24742 initialization. Such address clauses are easily replaced
24743 by the use of an explicitly-defined constant as described
24744 in the Ada Reference Manual (13.1(22)). For example, the sequence
24745 of declarations:
24746
24747 @smallexample @c ada
24748 @cartouche
24749 X, Y : Integer := Init_Func;
24750 Q : String (X .. Y) := "abc";
24751 @dots{}
24752 for Q'Address use Compute_Address;
24753 @end cartouche
24754 @end smallexample
24755
24756 @noindent
24757 will be rejected by GNAT, since the address cannot be computed at the time
24758 that @code{Q} is declared. To achieve the intended effect, write instead:
24759
24760 @smallexample @c ada
24761 @group
24762 @cartouche
24763 X, Y : Integer := Init_Func;
24764 Q_Address : constant Address := Compute_Address;
24765 Q : String (X .. Y) := "abc";
24766 @dots{}
24767 for Q'Address use Q_Address;
24768 @end cartouche
24769 @end group
24770 @end smallexample
24771
24772 @noindent
24773 which will be accepted by GNAT (and other Ada compilers), and is also
24774 compatible with Ada 83. A fuller description of the restrictions
24775 on address specifications is found in @ref{Top, GNAT Reference Manual,
24776 About This Guide, gnat_rm, GNAT Reference Manual}.
24777
24778 @node Other Representation Clauses
24779 @subsection Other Representation Clauses
24780
24781 @noindent
24782 GNAT implements in a compatible manner all the representation
24783 clauses supported by HP Ada. In addition, GNAT
24784 implements the representation clause forms that were introduced in Ada 95,
24785 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24786
24787 @node The Package STANDARD
24788 @section The Package @code{STANDARD}
24789
24790 @noindent
24791 The package @code{STANDARD}, as implemented by HP Ada, is fully
24792 described in the @cite{Ada Reference Manual} and in the
24793 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24794 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24795
24796 In addition, HP Ada supports the Latin-1 character set in
24797 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24798 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24799 the type @code{WIDE_CHARACTER}.
24800
24801 The floating-point types supported by GNAT are those
24802 supported by HP Ada, but the defaults are different, and are controlled by
24803 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24804
24805 @node The Package SYSTEM
24806 @section The Package @code{SYSTEM}
24807
24808 @noindent
24809 HP Ada provides a specific version of the package
24810 @code{SYSTEM} for each platform on which the language is implemented.
24811 For the complete spec of the package @code{SYSTEM}, see
24812 Appendix F of the @cite{HP Ada Language Reference Manual}.
24813
24814 On HP Ada, the package @code{SYSTEM} includes the following conversion
24815 functions:
24816 @itemize @bullet
24817 @item @code{TO_ADDRESS(INTEGER)}
24818
24819 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24820
24821 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24822
24823 @item @code{TO_INTEGER(ADDRESS)}
24824
24825 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24826
24827 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24828 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24829 @end itemize
24830
24831 @noindent
24832 By default, GNAT supplies a version of @code{SYSTEM} that matches
24833 the definition given in the @cite{Ada Reference Manual}.
24834 This
24835 is a subset of the HP system definitions, which is as
24836 close as possible to the original definitions. The only difference
24837 is that the definition of @code{SYSTEM_NAME} is different:
24838
24839 @smallexample @c ada
24840 @cartouche
24841 type Name is (SYSTEM_NAME_GNAT);
24842 System_Name : constant Name := SYSTEM_NAME_GNAT;
24843 @end cartouche
24844 @end smallexample
24845
24846 @noindent
24847 Also, GNAT adds the Ada declarations for
24848 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24849
24850 However, the use of the following pragma causes GNAT
24851 to extend the definition of package @code{SYSTEM} so that it
24852 encompasses the full set of HP-specific extensions,
24853 including the functions listed above:
24854
24855 @smallexample @c ada
24856 @cartouche
24857 pragma Extend_System (Aux_DEC);
24858 @end cartouche
24859 @end smallexample
24860
24861 @noindent
24862 The pragma @code{Extend_System} is a configuration pragma that
24863 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24864 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24865
24866 HP Ada does not allow the recompilation of the package
24867 @code{SYSTEM}. Instead HP Ada provides several pragmas
24868 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24869 to modify values in the package @code{SYSTEM}.
24870 On OpenVMS Alpha systems, the pragma
24871 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24872 its single argument.
24873
24874 GNAT does permit the recompilation of package @code{SYSTEM} using
24875 the special switch @option{-gnatg}, and this switch can be used if
24876 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24877 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24878 or @code{MEMORY_SIZE} by any other means.
24879
24880 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24881 enumeration literal @code{SYSTEM_NAME_GNAT}.
24882
24883 The definitions provided by the use of
24884
24885 @smallexample @c ada
24886 pragma Extend_System (AUX_Dec);
24887 @end smallexample
24888
24889 @noindent
24890 are virtually identical to those provided by the HP Ada 83 package
24891 @code{SYSTEM}. One important difference is that the name of the
24892 @code{TO_ADDRESS}
24893 function for type @code{UNSIGNED_LONGWORD} is changed to
24894 @code{TO_ADDRESS_LONG}.
24895 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24896 discussion of why this change was necessary.
24897
24898 @noindent
24899 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24900 is in fact
24901 an extension to Ada 83 not strictly compatible with the reference manual.
24902 GNAT, in order to be exactly compatible with the standard,
24903 does not provide this capability. In HP Ada 83, the
24904 point of this definition is to deal with a call like:
24905
24906 @smallexample @c ada
24907 TO_ADDRESS (16#12777#);
24908 @end smallexample
24909
24910 @noindent
24911 Normally, according to Ada 83 semantics, one would expect this to be
24912 ambiguous, since it matches both the @code{INTEGER} and
24913 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24914 However, in HP Ada 83, there is no ambiguity, since the
24915 definition using @i{universal_integer} takes precedence.
24916
24917 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24918 it is
24919 not possible to be 100% compatible. Since there are many programs using
24920 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24921 GNAT was
24922 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24923 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24924
24925 @smallexample @c ada
24926 function To_Address (X : Integer) return Address;
24927 pragma Pure_Function (To_Address);
24928
24929 function To_Address_Long (X : Unsigned_Longword) return Address;
24930 pragma Pure_Function (To_Address_Long);
24931 @end smallexample
24932
24933 @noindent
24934 This means that programs using @code{TO_ADDRESS} for
24935 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24936
24937 @node Tasking and Task-Related Features
24938 @section Tasking and Task-Related Features
24939
24940 @noindent
24941 This section compares the treatment of tasking in GNAT
24942 and in HP Ada for OpenVMS Alpha.
24943 The GNAT description applies to both Alpha and I64 OpenVMS.
24944 For detailed information on tasking in
24945 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24946 relevant run-time reference manual.
24947
24948 @menu
24949 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24950 * Assigning Task IDs::
24951 * Task IDs and Delays::
24952 * Task-Related Pragmas::
24953 * Scheduling and Task Priority::
24954 * The Task Stack::
24955 * External Interrupts::
24956 @end menu
24957
24958 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24959 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24960
24961 @noindent
24962 On OpenVMS Alpha systems, each Ada task (except a passive
24963 task) is implemented as a single stream of execution
24964 that is created and managed by the kernel. On these
24965 systems, HP Ada tasking support is based on DECthreads,
24966 an implementation of the POSIX standard for threads.
24967
24968 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24969 code that calls DECthreads routines can be used together.
24970 The interaction between Ada tasks and DECthreads routines
24971 can have some benefits. For example when on OpenVMS Alpha,
24972 HP Ada can call C code that is already threaded.
24973
24974 GNAT uses the facilities of DECthreads,
24975 and Ada tasks are mapped to threads.
24976
24977 @node Assigning Task IDs
24978 @subsection Assigning Task IDs
24979
24980 @noindent
24981 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24982 the environment task that executes the main program. On
24983 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24984 that have been created but are not yet activated.
24985
24986 On OpenVMS Alpha systems, task IDs are assigned at
24987 activation. On GNAT systems, task IDs are also assigned at
24988 task creation but do not have the same form or values as
24989 task ID values in HP Ada. There is no null task, and the
24990 environment task does not have a specific task ID value.
24991
24992 @node Task IDs and Delays
24993 @subsection Task IDs and Delays
24994
24995 @noindent
24996 On OpenVMS Alpha systems, tasking delays are implemented
24997 using Timer System Services. The Task ID is used for the
24998 identification of the timer request (the @code{REQIDT} parameter).
24999 If Timers are used in the application take care not to use
25000 @code{0} for the identification, because cancelling such a timer
25001 will cancel all timers and may lead to unpredictable results.
25002
25003 @node Task-Related Pragmas
25004 @subsection Task-Related Pragmas
25005
25006 @noindent
25007 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25008 specification of the size of the guard area for a task
25009 stack. (The guard area forms an area of memory that has no
25010 read or write access and thus helps in the detection of
25011 stack overflow.) On OpenVMS Alpha systems, if the pragma
25012 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25013 area is created. In the absence of a pragma @code{TASK_STORAGE},
25014 a default guard area is created.
25015
25016 GNAT supplies the following task-related pragmas:
25017
25018 @itemize @bullet
25019 @item @code{TASK_INFO}
25020
25021 This pragma appears within a task definition and
25022 applies to the task in which it appears. The argument
25023 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25024
25025 @item @code{TASK_STORAGE}
25026
25027 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25028 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25029 @code{SUPPRESS}, and @code{VOLATILE}.
25030 @end itemize
25031 @node Scheduling and Task Priority
25032 @subsection Scheduling and Task Priority
25033
25034 @noindent
25035 HP Ada implements the Ada language requirement that
25036 when two tasks are eligible for execution and they have
25037 different priorities, the lower priority task does not
25038 execute while the higher priority task is waiting. The HP
25039 Ada Run-Time Library keeps a task running until either the
25040 task is suspended or a higher priority task becomes ready.
25041
25042 On OpenVMS Alpha systems, the default strategy is round-
25043 robin with preemption. Tasks of equal priority take turns
25044 at the processor. A task is run for a certain period of
25045 time and then placed at the tail of the ready queue for
25046 its priority level.
25047
25048 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25049 which can be used to enable or disable round-robin
25050 scheduling of tasks with the same priority.
25051 See the relevant HP Ada run-time reference manual for
25052 information on using the pragmas to control HP Ada task
25053 scheduling.
25054
25055 GNAT follows the scheduling rules of Annex D (Real-Time
25056 Annex) of the @cite{Ada Reference Manual}. In general, this
25057 scheduling strategy is fully compatible with HP Ada
25058 although it provides some additional constraints (as
25059 fully documented in Annex D).
25060 GNAT implements time slicing control in a manner compatible with
25061 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25062 are identical to the HP Ada 83 pragma of the same name.
25063 Note that it is not possible to mix GNAT tasking and
25064 HP Ada 83 tasking in the same program, since the two run-time
25065 libraries are not compatible.
25066
25067 @node The Task Stack
25068 @subsection The Task Stack
25069
25070 @noindent
25071 In HP Ada, a task stack is allocated each time a
25072 non-passive task is activated. As soon as the task is
25073 terminated, the storage for the task stack is deallocated.
25074 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25075 a default stack size is used. Also, regardless of the size
25076 specified, some additional space is allocated for task
25077 management purposes. On OpenVMS Alpha systems, at least
25078 one page is allocated.
25079
25080 GNAT handles task stacks in a similar manner. In accordance with
25081 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25082 an alternative method for controlling the task stack size.
25083 The specification of the attribute @code{T'STORAGE_SIZE} is also
25084 supported in a manner compatible with HP Ada.
25085
25086 @node External Interrupts
25087 @subsection External Interrupts
25088
25089 @noindent
25090 On HP Ada, external interrupts can be associated with task entries.
25091 GNAT is compatible with HP Ada in its handling of external interrupts.
25092
25093 @node Pragmas and Pragma-Related Features
25094 @section Pragmas and Pragma-Related Features
25095
25096 @noindent
25097 Both HP Ada and GNAT supply all language-defined pragmas
25098 as specified by the Ada 83 standard. GNAT also supplies all
25099 language-defined pragmas introduced by Ada 95 and Ada 2005.
25100 In addition, GNAT implements the implementation-defined pragmas
25101 from HP Ada 83.
25102
25103 @itemize @bullet
25104 @item @code{AST_ENTRY}
25105
25106 @item @code{COMMON_OBJECT}
25107
25108 @item @code{COMPONENT_ALIGNMENT}
25109
25110 @item @code{EXPORT_EXCEPTION}
25111
25112 @item @code{EXPORT_FUNCTION}
25113
25114 @item @code{EXPORT_OBJECT}
25115
25116 @item @code{EXPORT_PROCEDURE}
25117
25118 @item @code{EXPORT_VALUED_PROCEDURE}
25119
25120 @item @code{FLOAT_REPRESENTATION}
25121
25122 @item @code{IDENT}
25123
25124 @item @code{IMPORT_EXCEPTION}
25125
25126 @item @code{IMPORT_FUNCTION}
25127
25128 @item @code{IMPORT_OBJECT}
25129
25130 @item @code{IMPORT_PROCEDURE}
25131
25132 @item @code{IMPORT_VALUED_PROCEDURE}
25133
25134 @item @code{INLINE_GENERIC}
25135
25136 @item @code{INTERFACE_NAME}
25137
25138 @item @code{LONG_FLOAT}
25139
25140 @item @code{MAIN_STORAGE}
25141
25142 @item @code{PASSIVE}
25143
25144 @item @code{PSECT_OBJECT}
25145
25146 @item @code{SHARE_GENERIC}
25147
25148 @item @code{SUPPRESS_ALL}
25149
25150 @item @code{TASK_STORAGE}
25151
25152 @item @code{TIME_SLICE}
25153
25154 @item @code{TITLE}
25155 @end itemize
25156
25157 @noindent
25158 These pragmas are all fully implemented, with the exception of @code{TITLE},
25159 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25160 recognized, but which have no
25161 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25162 use of Ada protected objects. In GNAT, all generics are inlined.
25163
25164 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25165 a separate subprogram specification which must appear before the
25166 subprogram body.
25167
25168 GNAT also supplies a number of implementation-defined pragmas as follows:
25169 @itemize @bullet
25170 @item @code{ABORT_DEFER}
25171
25172 @item @code{ADA_83}
25173
25174 @item @code{ADA_95}
25175
25176 @item @code{ADA_05}
25177
25178 @item @code{ANNOTATE}
25179
25180 @item @code{ASSERT}
25181
25182 @item @code{C_PASS_BY_COPY}
25183
25184 @item @code{CPP_CLASS}
25185
25186 @item @code{CPP_CONSTRUCTOR}
25187
25188 @item @code{CPP_DESTRUCTOR}
25189
25190 @item @code{DEBUG}
25191
25192 @item @code{EXTEND_SYSTEM}
25193
25194 @item @code{LINKER_ALIAS}
25195
25196 @item @code{LINKER_SECTION}
25197
25198 @item @code{MACHINE_ATTRIBUTE}
25199
25200 @item @code{NO_RETURN}
25201
25202 @item @code{PURE_FUNCTION}
25203
25204 @item @code{SOURCE_FILE_NAME}
25205
25206 @item @code{SOURCE_REFERENCE}
25207
25208 @item @code{TASK_INFO}
25209
25210 @item @code{UNCHECKED_UNION}
25211
25212 @item @code{UNIMPLEMENTED_UNIT}
25213
25214 @item @code{UNIVERSAL_DATA}
25215
25216 @item @code{UNSUPPRESS}
25217
25218 @item @code{WARNINGS}
25219
25220 @item @code{WEAK_EXTERNAL}
25221 @end itemize
25222
25223 @noindent
25224 For full details on these GNAT implementation-defined pragmas,
25225 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25226 Manual}.
25227
25228 @menu
25229 * Restrictions on the Pragma INLINE::
25230 * Restrictions on the Pragma INTERFACE::
25231 * Restrictions on the Pragma SYSTEM_NAME::
25232 @end menu
25233
25234 @node Restrictions on the Pragma INLINE
25235 @subsection Restrictions on Pragma @code{INLINE}
25236
25237 @noindent
25238 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25239 @itemize @bullet
25240 @item Parameters cannot have a task type.
25241
25242 @item Function results cannot be task types, unconstrained
25243 array types, or unconstrained types with discriminants.
25244
25245 @item Bodies cannot declare the following:
25246 @itemize @bullet
25247 @item Subprogram body or stub (imported subprogram is allowed)
25248
25249 @item Tasks
25250
25251 @item Generic declarations
25252
25253 @item Instantiations
25254
25255 @item Exceptions
25256
25257 @item Access types (types derived from access types allowed)
25258
25259 @item Array or record types
25260
25261 @item Dependent tasks
25262
25263 @item Direct recursive calls of subprogram or containing
25264 subprogram, directly or via a renaming
25265
25266 @end itemize
25267 @end itemize
25268
25269 @noindent
25270 In GNAT, the only restriction on pragma @code{INLINE} is that the
25271 body must occur before the call if both are in the same
25272 unit, and the size must be appropriately small. There are
25273 no other specific restrictions which cause subprograms to
25274 be incapable of being inlined.
25275
25276 @node Restrictions on the Pragma INTERFACE
25277 @subsection Restrictions on Pragma @code{INTERFACE}
25278
25279 @noindent
25280 The following restrictions on pragma @code{INTERFACE}
25281 are enforced by both HP Ada and GNAT:
25282 @itemize @bullet
25283 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
25284 Default is the default on OpenVMS Alpha systems.
25285
25286 @item Parameter passing: Language specifies default
25287 mechanisms but can be overridden with an @code{EXPORT} pragma.
25288
25289 @itemize @bullet
25290 @item Ada: Use internal Ada rules.
25291
25292 @item Bliss, C: Parameters must be mode @code{in}; cannot be
25293 record or task type. Result cannot be a string, an
25294 array, or a record.
25295
25296 @item Fortran: Parameters cannot have a task type. Result cannot
25297 be a string, an array, or a record.
25298 @end itemize
25299 @end itemize
25300
25301 @noindent
25302 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25303 record parameters for all languages.
25304
25305 @node Restrictions on the Pragma SYSTEM_NAME
25306 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
25307
25308 @noindent
25309 For HP Ada for OpenVMS Alpha, the enumeration literal
25310 for the type @code{NAME} is @code{OPENVMS_AXP}.
25311 In GNAT, the enumeration
25312 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25313
25314 @node Library of Predefined Units
25315 @section Library of Predefined Units
25316
25317 @noindent
25318 A library of predefined units is provided as part of the
25319 HP Ada and GNAT implementations. HP Ada does not provide
25320 the package @code{MACHINE_CODE} but instead recommends importing
25321 assembler code.
25322
25323 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25324 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25325 version.
25326 The HP Ada Predefined Library units are modified to remove post-Ada 83
25327 incompatibilities and to make them interoperable with GNAT
25328 (@pxref{Changes to DECLIB}, for details).
25329 The units are located in the @file{DECLIB} directory.
25330
25331 The GNAT RTL is contained in
25332 the @file{ADALIB} directory, and
25333 the default search path is set up to find @code{DECLIB} units in preference
25334 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25335 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25336
25337 @menu
25338 * Changes to DECLIB::
25339 @end menu
25340
25341 @node Changes to DECLIB
25342 @subsection Changes to @code{DECLIB}
25343
25344 @noindent
25345 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25346 compatibility are minor and include the following:
25347
25348 @itemize @bullet
25349 @item Adjusting the location of pragmas and record representation
25350 clauses to obey Ada 95 (and thus Ada 2005) rules
25351
25352 @item Adding the proper notation to generic formal parameters
25353 that take unconstrained types in instantiation
25354
25355 @item Adding pragma @code{ELABORATE_BODY} to package specs
25356 that have package bodies not otherwise allowed
25357
25358 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25359 ``@code{PROTECTD}''.
25360 Currently these are found only in the @code{STARLET} package spec.
25361
25362 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25363 where the address size is constrained to 32 bits.
25364 @end itemize
25365
25366 @noindent
25367 None of the above changes is visible to users.
25368
25369 @node Bindings
25370 @section Bindings
25371
25372 @noindent
25373 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25374 @itemize @bullet
25375
25376 @item Command Language Interpreter (CLI interface)
25377
25378 @item DECtalk Run-Time Library (DTK interface)
25379
25380 @item Librarian utility routines (LBR interface)
25381
25382 @item General Purpose Run-Time Library (LIB interface)
25383
25384 @item Math Run-Time Library (MTH interface)
25385
25386 @item National Character Set Run-Time Library (NCS interface)
25387
25388 @item Compiled Code Support Run-Time Library (OTS interface)
25389
25390 @item Parallel Processing Run-Time Library (PPL interface)
25391
25392 @item Screen Management Run-Time Library (SMG interface)
25393
25394 @item Sort Run-Time Library (SOR interface)
25395
25396 @item String Run-Time Library (STR interface)
25397
25398 @item STARLET System Library
25399 @findex Starlet
25400
25401 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
25402
25403 @item X Windows Toolkit (XT interface)
25404
25405 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
25406 @end itemize
25407
25408 @noindent
25409 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25410 directory, on both the Alpha and I64 OpenVMS platforms.
25411
25412 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25413 in the
25414 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25415 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25416 @code{Xt}, and @code{X_Lib}
25417 causing the default X/Motif sharable image libraries to be linked in. This
25418 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25419 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25420
25421 It may be necessary to edit these options files to update or correct the
25422 library names if, for example, the newer X/Motif bindings from
25423 @file{ADA$EXAMPLES}
25424 had been (previous to installing GNAT) copied and renamed to supersede the
25425 default @file{ADA$PREDEFINED} versions.
25426
25427 @menu
25428 * Shared Libraries and Options Files::
25429 * Interfaces to C::
25430 @end menu
25431
25432 @node Shared Libraries and Options Files
25433 @subsection Shared Libraries and Options Files
25434
25435 @noindent
25436 When using the HP Ada
25437 predefined X and Motif bindings, the linking with their sharable images is
25438 done automatically by @command{GNAT LINK}.
25439 When using other X and Motif bindings, you need
25440 to add the corresponding sharable images to the command line for
25441 @code{GNAT LINK}. When linking with shared libraries, or with
25442 @file{.OPT} files, you must
25443 also add them to the command line for @command{GNAT LINK}.
25444
25445 A shared library to be used with GNAT is built in the same way as other
25446 libraries under VMS. The VMS Link command can be used in standard fashion.
25447
25448 @node Interfaces to C
25449 @subsection Interfaces to C
25450
25451 @noindent
25452 HP Ada
25453 provides the following Ada types and operations:
25454
25455 @itemize @bullet
25456 @item C types package (@code{C_TYPES})
25457
25458 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25459
25460 @item Other_types (@code{SHORT_INT})
25461 @end itemize
25462
25463 @noindent
25464 Interfacing to C with GNAT, you can use the above approach
25465 described for HP Ada or the facilities of Annex B of
25466 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25467 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25468 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25469
25470 The @option{-gnatF} qualifier forces default and explicit
25471 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25472 to be uppercased for compatibility with the default behavior
25473 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25474
25475 @node Main Program Definition
25476 @section Main Program Definition
25477
25478 @noindent
25479 The following section discusses differences in the
25480 definition of main programs on HP Ada and GNAT.
25481 On HP Ada, main programs are defined to meet the
25482 following conditions:
25483 @itemize @bullet
25484 @item Procedure with no formal parameters (returns @code{0} upon
25485 normal completion)
25486
25487 @item Procedure with no formal parameters (returns @code{42} when
25488 an unhandled exception is raised)
25489
25490 @item Function with no formal parameters whose returned value
25491 is of a discrete type
25492
25493 @item Procedure with one @code{out} formal of a discrete type for
25494 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25495
25496 @end itemize
25497
25498 @noindent
25499 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25500 a main function or main procedure returns a discrete
25501 value whose size is less than 64 bits (32 on VAX systems),
25502 the value is zero- or sign-extended as appropriate.
25503 On GNAT, main programs are defined as follows:
25504 @itemize @bullet
25505 @item Must be a non-generic, parameterless subprogram that
25506 is either a procedure or function returning an Ada
25507 @code{STANDARD.INTEGER} (the predefined type)
25508
25509 @item Cannot be a generic subprogram or an instantiation of a
25510 generic subprogram
25511 @end itemize
25512
25513 @node Implementation-Defined Attributes
25514 @section Implementation-Defined Attributes
25515
25516 @noindent
25517 GNAT provides all HP Ada implementation-defined
25518 attributes.
25519
25520 @node Compiler and Run-Time Interfacing
25521 @section Compiler and Run-Time Interfacing
25522
25523 @noindent
25524 HP Ada provides the following qualifiers to pass options to the linker
25525 (ACS LINK):
25526 @itemize @bullet
25527 @item @option{/WAIT} and @option{/SUBMIT}
25528
25529 @item @option{/COMMAND}
25530
25531 @item @option{/@r{[}NO@r{]}MAP}
25532
25533 @item @option{/OUTPUT=@var{file-spec}}
25534
25535 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25536 @end itemize
25537
25538 @noindent
25539 To pass options to the linker, GNAT provides the following
25540 switches:
25541
25542 @itemize @bullet
25543 @item @option{/EXECUTABLE=@var{exec-name}}
25544
25545 @item @option{/VERBOSE}
25546
25547 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25548 @end itemize
25549
25550 @noindent
25551 For more information on these switches, see
25552 @ref{Switches for gnatlink}.
25553 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25554 to control optimization. HP Ada also supplies the
25555 following pragmas:
25556 @itemize @bullet
25557 @item @code{OPTIMIZE}
25558
25559 @item @code{INLINE}
25560
25561 @item @code{INLINE_GENERIC}
25562
25563 @item @code{SUPPRESS_ALL}
25564
25565 @item @code{PASSIVE}
25566 @end itemize
25567
25568 @noindent
25569 In GNAT, optimization is controlled strictly by command
25570 line parameters, as described in the corresponding section of this guide.
25571 The HP pragmas for control of optimization are
25572 recognized but ignored.
25573
25574 Note that in GNAT, the default is optimization off, whereas in HP Ada
25575 the default is that optimization is turned on.
25576
25577 @node Program Compilation and Library Management
25578 @section Program Compilation and Library Management
25579
25580 @noindent
25581 HP Ada and GNAT provide a comparable set of commands to
25582 build programs. HP Ada also provides a program library,
25583 which is a concept that does not exist on GNAT. Instead,
25584 GNAT provides directories of sources that are compiled as
25585 needed.
25586
25587 The following table summarizes
25588 the HP Ada commands and provides
25589 equivalent GNAT commands. In this table, some GNAT
25590 equivalents reflect the fact that GNAT does not use the
25591 concept of a program library. Instead, it uses a model
25592 in which collections of source and object files are used
25593 in a manner consistent with other languages like C and
25594 Fortran. Therefore, standard system file commands are used
25595 to manipulate these elements. Those GNAT commands are marked with
25596 an asterisk.
25597 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25598
25599 @need 1500
25600 @multitable @columnfractions .35 .65
25601
25602 @item @emph{HP Ada Command}
25603 @tab @emph{GNAT Equivalent / Description}
25604
25605 @item @command{ADA}
25606 @tab @command{GNAT COMPILE}@*
25607 Invokes the compiler to compile one or more Ada source files.
25608
25609 @item @command{ACS ATTACH}@*
25610 @tab [No equivalent]@*
25611 Switches control of terminal from current process running the program
25612 library manager.
25613
25614 @item @command{ACS CHECK}
25615 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25616 Forms the execution closure of one
25617 or more compiled units and checks completeness and currency.
25618
25619 @item @command{ACS COMPILE}
25620 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25621 Forms the execution closure of one or
25622 more specified units, checks completeness and currency,
25623 identifies units that have revised source files, compiles same,
25624 and recompiles units that are or will become obsolete.
25625 Also completes incomplete generic instantiations.
25626
25627 @item @command{ACS COPY FOREIGN}
25628 @tab Copy (*)@*
25629 Copies a foreign object file into the program library as a
25630 library unit body.
25631
25632 @item @command{ACS COPY UNIT}
25633 @tab Copy (*)@*
25634 Copies a compiled unit from one program library to another.
25635
25636 @item @command{ACS CREATE LIBRARY}
25637 @tab Create /directory (*)@*
25638 Creates a program library.
25639
25640 @item @command{ACS CREATE SUBLIBRARY}
25641 @tab Create /directory (*)@*
25642 Creates a program sublibrary.
25643
25644 @item @command{ACS DELETE LIBRARY}
25645 @tab @*
25646 Deletes a program library and its contents.
25647
25648 @item @command{ACS DELETE SUBLIBRARY}
25649 @tab @*
25650 Deletes a program sublibrary and its contents.
25651
25652 @item @command{ACS DELETE UNIT}
25653 @tab Delete file (*)@*
25654 On OpenVMS systems, deletes one or more compiled units from
25655 the current program library.
25656
25657 @item @command{ACS DIRECTORY}
25658 @tab Directory (*)@*
25659 On OpenVMS systems, lists units contained in the current
25660 program library.
25661
25662 @item @command{ACS ENTER FOREIGN}
25663 @tab Copy (*)@*
25664 Allows the import of a foreign body as an Ada library
25665 spec and enters a reference to a pointer.
25666
25667 @item @command{ACS ENTER UNIT}
25668 @tab Copy (*)@*
25669 Enters a reference (pointer) from the current program library to
25670 a unit compiled into another program library.
25671
25672 @item @command{ACS EXIT}
25673 @tab [No equivalent]@*
25674 Exits from the program library manager.
25675
25676 @item @command{ACS EXPORT}
25677 @tab Copy (*)@*
25678 Creates an object file that contains system-specific object code
25679 for one or more units. With GNAT, object files can simply be copied
25680 into the desired directory.
25681
25682 @item @command{ACS EXTRACT SOURCE}
25683 @tab Copy (*)@*
25684 Allows access to the copied source file for each Ada compilation unit
25685
25686 @item @command{ACS HELP}
25687 @tab @command{HELP GNAT}@*
25688 Provides online help.
25689
25690 @item @command{ACS LINK}
25691 @tab @command{GNAT LINK}@*
25692 Links an object file containing Ada units into an executable file.
25693
25694 @item @command{ACS LOAD}
25695 @tab Copy (*)@*
25696 Loads (partially compiles) Ada units into the program library.
25697 Allows loading a program from a collection of files into a library
25698 without knowing the relationship among units.
25699
25700 @item @command{ACS MERGE}
25701 @tab Copy (*)@*
25702 Merges into the current program library, one or more units from
25703 another library where they were modified.
25704
25705 @item @command{ACS RECOMPILE}
25706 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25707 Recompiles from external or copied source files any obsolete
25708 unit in the closure. Also, completes any incomplete generic
25709 instantiations.
25710
25711 @item @command{ACS REENTER}
25712 @tab @command{GNAT MAKE}@*
25713 Reenters current references to units compiled after last entered
25714 with the @command{ACS ENTER UNIT} command.
25715
25716 @item @command{ACS SET LIBRARY}
25717 @tab Set default (*)@*
25718 Defines a program library to be the compilation context as well
25719 as the target library for compiler output and commands in general.
25720
25721 @item @command{ACS SET PRAGMA}
25722 @tab Edit @file{gnat.adc} (*)@*
25723 Redefines specified values of the library characteristics
25724 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25725 and @code{Float_Representation}.
25726
25727 @item @command{ACS SET SOURCE}
25728 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25729 Defines the source file search list for the @command{ACS COMPILE} command.
25730
25731 @item @command{ACS SHOW LIBRARY}
25732 @tab Directory (*)@*
25733 Lists information about one or more program libraries.
25734
25735 @item @command{ACS SHOW PROGRAM}
25736 @tab [No equivalent]@*
25737 Lists information about the execution closure of one or
25738 more units in the program library.
25739
25740 @item @command{ACS SHOW SOURCE}
25741 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25742 Shows the source file search used when compiling units.
25743
25744 @item @command{ACS SHOW VERSION}
25745 @tab Compile with @option{VERBOSE} option
25746 Displays the version number of the compiler and program library
25747 manager used.
25748
25749 @item @command{ACS SPAWN}
25750 @tab [No equivalent]@*
25751 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25752 command).
25753
25754 @item @command{ACS VERIFY}
25755 @tab [No equivalent]@*
25756 Performs a series of consistency checks on a program library to
25757 determine whether the library structure and library files are in
25758 valid form.
25759 @end multitable
25760
25761 @noindent
25762
25763 @node Input-Output
25764 @section Input-Output
25765
25766 @noindent
25767 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25768 Management Services (RMS) to perform operations on
25769 external files.
25770
25771 @noindent
25772 HP Ada and GNAT predefine an identical set of input-
25773 output packages. To make the use of the
25774 generic @code{TEXT_IO} operations more convenient, HP Ada
25775 provides predefined library packages that instantiate the
25776 integer and floating-point operations for the predefined
25777 integer and floating-point types as shown in the following table.
25778
25779 @multitable @columnfractions .45 .55
25780 @item @emph{Package Name} @tab Instantiation
25781
25782 @item @code{INTEGER_TEXT_IO}
25783 @tab @code{INTEGER_IO(INTEGER)}
25784
25785 @item @code{SHORT_INTEGER_TEXT_IO}
25786 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25787
25788 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25789 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25790
25791 @item @code{FLOAT_TEXT_IO}
25792 @tab @code{FLOAT_IO(FLOAT)}
25793
25794 @item @code{LONG_FLOAT_TEXT_IO}
25795 @tab @code{FLOAT_IO(LONG_FLOAT)}
25796 @end multitable
25797
25798 @noindent
25799 The HP Ada predefined packages and their operations
25800 are implemented using OpenVMS Alpha files and input-output
25801 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25802 Familiarity with the following is recommended:
25803 @itemize @bullet
25804 @item RMS file organizations and access methods
25805
25806 @item OpenVMS file specifications and directories
25807
25808 @item OpenVMS File Definition Language (FDL)
25809 @end itemize
25810
25811 @noindent
25812 GNAT provides I/O facilities that are completely
25813 compatible with HP Ada. The distribution includes the
25814 standard HP Ada versions of all I/O packages, operating
25815 in a manner compatible with HP Ada. In particular, the
25816 following packages are by default the HP Ada (Ada 83)
25817 versions of these packages rather than the renamings
25818 suggested in Annex J of the Ada Reference Manual:
25819 @itemize @bullet
25820 @item @code{TEXT_IO}
25821
25822 @item @code{SEQUENTIAL_IO}
25823
25824 @item @code{DIRECT_IO}
25825 @end itemize
25826
25827 @noindent
25828 The use of the standard child package syntax (for
25829 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25830 packages.
25831 GNAT provides HP-compatible predefined instantiations
25832 of the @code{TEXT_IO} packages, and also
25833 provides the standard predefined instantiations required
25834 by the @cite{Ada Reference Manual}.
25835
25836 For further information on how GNAT interfaces to the file
25837 system or how I/O is implemented in programs written in
25838 mixed languages, see @ref{Implementation of the Standard I/O,,,
25839 gnat_rm, GNAT Reference Manual}.
25840 This chapter covers the following:
25841 @itemize @bullet
25842 @item Standard I/O packages
25843
25844 @item @code{FORM} strings
25845
25846 @item @code{ADA.DIRECT_IO}
25847
25848 @item @code{ADA.SEQUENTIAL_IO}
25849
25850 @item @code{ADA.TEXT_IO}
25851
25852 @item Stream pointer positioning
25853
25854 @item Reading and writing non-regular files
25855
25856 @item @code{GET_IMMEDIATE}
25857
25858 @item Treating @code{TEXT_IO} files as streams
25859
25860 @item Shared files
25861
25862 @item Open modes
25863 @end itemize
25864
25865 @node Implementation Limits
25866 @section Implementation Limits
25867
25868 @noindent
25869 The following table lists implementation limits for HP Ada
25870 and GNAT systems.
25871 @multitable @columnfractions .60 .20 .20
25872 @sp 1
25873 @item @emph{Compilation Parameter}
25874 @tab @emph{HP Ada}
25875 @tab @emph{GNAT}
25876 @sp 1
25877
25878 @item In a subprogram or entry declaration, maximum number of
25879 formal parameters that are of an unconstrained record type
25880 @tab 32
25881 @tab No set limit
25882 @sp 1
25883
25884 @item Maximum identifier length (number of characters)
25885 @tab 255
25886 @tab 32766
25887 @sp 1
25888
25889 @item Maximum number of characters in a source line
25890 @tab 255
25891 @tab 32766
25892 @sp 1
25893
25894 @item Maximum collection size (number of bytes)
25895 @tab 2**31-1
25896 @tab 2**31-1
25897 @sp 1
25898
25899 @item Maximum number of discriminants for a record type
25900 @tab 245
25901 @tab No set limit
25902 @sp 1
25903
25904 @item Maximum number of formal parameters in an entry or
25905 subprogram declaration
25906 @tab 246
25907 @tab No set limit
25908 @sp 1
25909
25910 @item Maximum number of dimensions in an array type
25911 @tab 255
25912 @tab No set limit
25913 @sp 1
25914
25915 @item Maximum number of library units and subunits in a compilation.
25916 @tab 4095
25917 @tab No set limit
25918 @sp 1
25919
25920 @item Maximum number of library units and subunits in an execution.
25921 @tab 16383
25922 @tab No set limit
25923 @sp 1
25924
25925 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25926 or @code{PSECT_OBJECT}
25927 @tab 32757
25928 @tab No set limit
25929 @sp 1
25930
25931 @item Maximum number of enumeration literals in an enumeration type
25932 definition
25933 @tab 65535
25934 @tab No set limit
25935 @sp 1
25936
25937 @item Maximum number of lines in a source file
25938 @tab 65534
25939 @tab No set limit
25940 @sp 1
25941
25942 @item Maximum number of bits in any object
25943 @tab 2**31-1
25944 @tab 2**31-1
25945 @sp 1
25946
25947 @item Maximum size of the static portion of a stack frame (approximate)
25948 @tab 2**31-1
25949 @tab 2**31-1
25950 @end multitable
25951
25952 @node Tools and Utilities
25953 @section Tools and Utilities
25954
25955 @noindent
25956 The following table lists some of the OpenVMS development tools
25957 available for HP Ada, and the corresponding tools for
25958 use with @value{EDITION} on Alpha and I64 platforms.
25959 Aside from the debugger, all the OpenVMS tools identified are part
25960 of the DECset package.
25961
25962 @iftex
25963 @c Specify table in TeX since Texinfo does a poor job
25964 @tex
25965 \smallskip
25966 \smallskip
25967 \settabs\+Language-Sensitive Editor\quad
25968 &Product with HP Ada\quad
25969 &\cr
25970 \+\it Tool
25971 &\it Product with HP Ada
25972 & \it Product with GNAT Pro\cr
25973 \smallskip
25974 \+Code Management System
25975 &HP CMS
25976 & HP CMS\cr
25977 \smallskip
25978 \+Language-Sensitive Editor
25979 &HP LSE
25980 & emacs or HP LSE (Alpha)\cr
25981 \+
25982 &
25983 & HP LSE (I64)\cr
25984 \smallskip
25985 \+Debugger
25986 &OpenVMS Debug
25987 & gdb (Alpha),\cr
25988 \+
25989 &
25990 & OpenVMS Debug (I64)\cr
25991 \smallskip
25992 \+Source Code Analyzer /
25993 &HP SCA
25994 & GNAT XREF\cr
25995 \+Cross Referencer
25996 &
25997 &\cr
25998 \smallskip
25999 \+Test Manager
26000 &HP Digital Test
26001 & HP DTM\cr
26002 \+
26003 &Manager (DTM)
26004 &\cr
26005 \smallskip
26006 \+Performance and
26007 & HP PCA
26008 & HP PCA\cr
26009 \+Coverage Analyzer
26010 &
26011 &\cr
26012 \smallskip
26013 \+Module Management
26014 & HP MMS
26015 & Not applicable\cr
26016 \+ System
26017 &
26018 &\cr
26019 \smallskip
26020 \smallskip
26021 @end tex
26022 @end iftex
26023
26024 @ifnottex
26025 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
26026 @c the TeX version above for the printed version
26027 @flushleft
26028 @c @multitable @columnfractions .3 .4 .4
26029 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26030 @item @i{Tool}
26031 @tab @i{Tool with HP Ada}
26032 @tab @i{Tool with @value{EDITION}}
26033 @item Code Management@*System
26034 @tab HP CMS
26035 @tab HP CMS
26036 @item Language-Sensitive@*Editor
26037 @tab HP LSE
26038 @tab emacs or HP LSE (Alpha)
26039 @item
26040 @tab
26041 @tab HP LSE (I64)
26042 @item Debugger
26043 @tab OpenVMS Debug
26044 @tab gdb (Alpha),
26045 @item
26046 @tab
26047 @tab OpenVMS Debug (I64)
26048 @item Source Code Analyzer /@*Cross Referencer
26049 @tab HP SCA
26050 @tab GNAT XREF
26051 @item Test Manager
26052 @tab HP Digital Test@*Manager (DTM)
26053 @tab HP DTM
26054 @item Performance and@*Coverage Analyzer
26055 @tab HP PCA
26056 @tab HP PCA
26057 @item Module Management@*System
26058 @tab HP MMS
26059 @tab Not applicable
26060 @end multitable
26061 @end flushleft
26062 @end ifnottex
26063
26064 @end ifset
26065
26066 @c **************************************
26067 @node Platform-Specific Information for the Run-Time Libraries
26068 @appendix Platform-Specific Information for the Run-Time Libraries
26069 @cindex Tasking and threads libraries
26070 @cindex Threads libraries and tasking
26071 @cindex Run-time libraries (platform-specific information)
26072
26073 @noindent
26074 The GNAT run-time implementation may vary with respect to both the
26075 underlying threads library and the exception handling scheme.
26076 For threads support, one or more of the following are supplied:
26077 @itemize @bullet
26078 @item @b{native threads library}, a binding to the thread package from
26079 the underlying operating system
26080
26081 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26082 POSIX thread package
26083 @end itemize
26084
26085 @noindent
26086 For exception handling, either or both of two models are supplied:
26087 @itemize @bullet
26088 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26089 Most programs should experience a substantial speed improvement by
26090 being compiled with a ZCX run-time.
26091 This is especially true for
26092 tasking applications or applications with many exception handlers.}
26093 @cindex Zero-Cost Exceptions
26094 @cindex ZCX (Zero-Cost Exceptions)
26095 which uses binder-generated tables that
26096 are interrogated at run time to locate a handler
26097
26098 @item @b{setjmp / longjmp} (``SJLJ''),
26099 @cindex setjmp/longjmp Exception Model
26100 @cindex SJLJ (setjmp/longjmp Exception Model)
26101 which uses dynamically-set data to establish
26102 the set of handlers
26103 @end itemize
26104
26105 @noindent
26106 This appendix summarizes which combinations of threads and exception support
26107 are supplied on various GNAT platforms.
26108 It then shows how to select a particular library either
26109 permanently or temporarily,
26110 explains the properties of (and tradeoffs among) the various threads
26111 libraries, and provides some additional
26112 information about several specific platforms.
26113
26114 @menu
26115 * Summary of Run-Time Configurations::
26116 * Specifying a Run-Time Library::
26117 * Choosing the Scheduling Policy::
26118 * Solaris-Specific Considerations::
26119 * Linux-Specific Considerations::
26120 * AIX-Specific Considerations::
26121 * Irix-Specific Considerations::
26122 * RTX-Specific Considerations::
26123 @end menu
26124
26125 @node Summary of Run-Time Configurations
26126 @section Summary of Run-Time Configurations
26127
26128 @multitable @columnfractions .30 .70
26129 @item @b{alpha-openvms}
26130 @item @code{@ @ }@i{rts-native (default)}
26131 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26132 @item @code{@ @ @ @ }Exceptions @tab ZCX
26133 @*
26134 @item @b{alpha-tru64}
26135 @item @code{@ @ }@i{rts-native (default)}
26136 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26137 @item @code{@ @ @ @ }Exceptions @tab ZCX
26138 @*
26139 @item @code{@ @ }@i{rts-sjlj}
26140 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26141 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26142 @*
26143 @item @b{ia64-hp_linux}
26144 @item @code{@ @ }@i{rts-native (default)}
26145 @item @code{@ @ @ @ }Tasking @tab pthread library
26146 @item @code{@ @ @ @ }Exceptions @tab ZCX
26147 @*
26148 @item @b{ia64-hpux}
26149 @item @code{@ @ }@i{rts-native (default)}
26150 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26151 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26152 @*
26153 @item @b{ia64-openvms}
26154 @item @code{@ @ }@i{rts-native (default)}
26155 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26156 @item @code{@ @ @ @ }Exceptions @tab ZCX
26157 @*
26158 @item @b{ia64-sgi_linux}
26159 @item @code{@ @ }@i{rts-native (default)}
26160 @item @code{@ @ @ @ }Tasking @tab pthread library
26161 @item @code{@ @ @ @ }Exceptions @tab ZCX
26162 @*
26163 @item @b{mips-irix}
26164 @item @code{@ @ }@i{rts-native (default)}
26165 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
26166 @item @code{@ @ @ @ }Exceptions @tab ZCX
26167 @*
26168 @item @b{pa-hpux}
26169 @item @code{@ @ }@i{rts-native (default)}
26170 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26171 @item @code{@ @ @ @ }Exceptions @tab ZCX
26172 @*
26173 @item @code{@ @ }@i{rts-sjlj}
26174 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26175 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26176 @*
26177 @item @b{ppc-aix}
26178 @item @code{@ @ }@i{rts-native (default)}
26179 @item @code{@ @ @ @ }Tasking @tab native AIX threads
26180 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26181 @*
26182 @item @b{ppc-darwin}
26183 @item @code{@ @ }@i{rts-native (default)}
26184 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
26185 @item @code{@ @ @ @ }Exceptions @tab ZCX
26186 @*
26187 @item @b{sparc-solaris} @tab
26188 @item @code{@ @ }@i{rts-native (default)}
26189 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26190 @item @code{@ @ @ @ }Exceptions @tab ZCX
26191 @*
26192 @item @code{@ @ }@i{rts-pthread}
26193 @item @code{@ @ @ @ }Tasking @tab pthread library
26194 @item @code{@ @ @ @ }Exceptions @tab ZCX
26195 @*
26196 @item @code{@ @ }@i{rts-sjlj}
26197 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26198 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26199 @*
26200 @item @b{sparc64-solaris} @tab
26201 @item @code{@ @ }@i{rts-native (default)}
26202 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26203 @item @code{@ @ @ @ }Exceptions @tab ZCX
26204 @*
26205 @item @b{x86-linux}
26206 @item @code{@ @ }@i{rts-native (default)}
26207 @item @code{@ @ @ @ }Tasking @tab pthread library
26208 @item @code{@ @ @ @ }Exceptions @tab ZCX
26209 @*
26210 @item @code{@ @ }@i{rts-sjlj}
26211 @item @code{@ @ @ @ }Tasking @tab pthread library
26212 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26213 @*
26214 @item @b{x86-lynx}
26215 @item @code{@ @ }@i{rts-native (default)}
26216 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
26217 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26218 @*
26219 @item @b{x86-solaris}
26220 @item @code{@ @ }@i{rts-native (default)}
26221 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
26222 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26223 @*
26224 @item @b{x86-windows}
26225 @item @code{@ @ }@i{rts-native (default)}
26226 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26227 @item @code{@ @ @ @ }Exceptions @tab ZCX
26228 @*
26229 @item @code{@ @ }@i{rts-sjlj (default)}
26230 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26231 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26232 @*
26233 @item @b{x86-windows-rtx}
26234 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26235 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
26236 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26237 @*
26238 @item @code{@ @ }@i{rts-rtx-w32}
26239 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
26240 @item @code{@ @ @ @ }Exceptions @tab ZCX
26241 @*
26242 @item @b{x86_64-linux}
26243 @item @code{@ @ }@i{rts-native (default)}
26244 @item @code{@ @ @ @ }Tasking @tab pthread library
26245 @item @code{@ @ @ @ }Exceptions @tab ZCX
26246 @*
26247 @item @code{@ @ }@i{rts-sjlj}
26248 @item @code{@ @ @ @ }Tasking @tab pthread library
26249 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26250 @*
26251 @end multitable
26252
26253 @node Specifying a Run-Time Library
26254 @section Specifying a Run-Time Library
26255
26256 @noindent
26257 The @file{adainclude} subdirectory containing the sources of the GNAT
26258 run-time library, and the @file{adalib} subdirectory containing the
26259 @file{ALI} files and the static and/or shared GNAT library, are located
26260 in the gcc target-dependent area:
26261
26262 @smallexample
26263 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26264 @end smallexample
26265
26266 @noindent
26267 As indicated above, on some platforms several run-time libraries are supplied.
26268 These libraries are installed in the target dependent area and
26269 contain a complete source and binary subdirectory. The detailed description
26270 below explains the differences between the different libraries in terms of
26271 their thread support.
26272
26273 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26274 This default run time is selected by the means of soft links.
26275 For example on x86-linux:
26276
26277 @smallexample
26278 @group
26279 $(target-dir)
26280 |
26281 +--- adainclude----------+
26282 | |
26283 +--- adalib-----------+ |
26284 | | |
26285 +--- rts-native | |
26286 | | | |
26287 | +--- adainclude <---+
26288 | | |
26289 | +--- adalib <----+
26290 |
26291 +--- rts-sjlj
26292 |
26293 +--- adainclude
26294 |
26295 +--- adalib
26296 @end group
26297 @end smallexample
26298
26299 @noindent
26300 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26301 these soft links can be modified with the following commands:
26302
26303 @smallexample
26304 $ cd $target
26305 $ rm -f adainclude adalib
26306 $ ln -s rts-sjlj/adainclude adainclude
26307 $ ln -s rts-sjlj/adalib adalib
26308 @end smallexample
26309
26310 @noindent
26311 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26312 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26313 @file{$target/ada_object_path}.
26314
26315 Selecting another run-time library temporarily can be
26316 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26317 @cindex @option{--RTS} option
26318
26319 @node Choosing the Scheduling Policy
26320 @section Choosing the Scheduling Policy
26321
26322 @noindent
26323 When using a POSIX threads implementation, you have a choice of several
26324 scheduling policies: @code{SCHED_FIFO},
26325 @cindex @code{SCHED_FIFO} scheduling policy
26326 @code{SCHED_RR}
26327 @cindex @code{SCHED_RR} scheduling policy
26328 and @code{SCHED_OTHER}.
26329 @cindex @code{SCHED_OTHER} scheduling policy
26330 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26331 or @code{SCHED_RR} requires special (e.g., root) privileges.
26332
26333 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26334 @code{SCHED_FIFO},
26335 @cindex @code{SCHED_FIFO} scheduling policy
26336 you can use one of the following:
26337
26338 @itemize @bullet
26339 @item
26340 @code{pragma Time_Slice (0.0)}
26341 @cindex pragma Time_Slice
26342 @item
26343 the corresponding binder option @option{-T0}
26344 @cindex @option{-T0} option
26345 @item
26346 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26347 @cindex pragma Task_Dispatching_Policy
26348 @end itemize
26349
26350 @noindent
26351 To specify @code{SCHED_RR},
26352 @cindex @code{SCHED_RR} scheduling policy
26353 you should use @code{pragma Time_Slice} with a
26354 value greater than @code{0.0}, or else use the corresponding @option{-T}
26355 binder option.
26356
26357 @node Solaris-Specific Considerations
26358 @section Solaris-Specific Considerations
26359 @cindex Solaris Sparc threads libraries
26360
26361 @noindent
26362 This section addresses some topics related to the various threads libraries
26363 on Sparc Solaris.
26364
26365 @menu
26366 * Solaris Threads Issues::
26367 @end menu
26368
26369 @node Solaris Threads Issues
26370 @subsection Solaris Threads Issues
26371
26372 @noindent
26373 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26374 library based on POSIX threads --- @emph{rts-pthread}.
26375 @cindex rts-pthread threads library
26376 This run-time library has the advantage of being mostly shared across all
26377 POSIX-compliant thread implementations, and it also provides under
26378 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26379 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26380 and @code{PTHREAD_PRIO_PROTECT}
26381 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26382 semantics that can be selected using the predefined pragma
26383 @code{Locking_Policy}
26384 @cindex pragma Locking_Policy (under rts-pthread)
26385 with respectively
26386 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26387 @cindex @code{Inheritance_Locking} (under rts-pthread)
26388 @cindex @code{Ceiling_Locking} (under rts-pthread)
26389
26390 As explained above, the native run-time library is based on the Solaris thread
26391 library (@code{libthread}) and is the default library.
26392
26393 When the Solaris threads library is used (this is the default), programs
26394 compiled with GNAT can automatically take advantage of
26395 and can thus execute on multiple processors.
26396 The user can alternatively specify a processor on which the program should run
26397 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26398 is made by
26399 setting the environment variable @env{GNAT_PROCESSOR}
26400 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26401 to one of the following:
26402
26403 @table @code
26404 @item -2
26405 Use the default configuration (run the program on all
26406 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26407 unset
26408
26409 @item -1
26410 Let the run-time implementation choose one processor and run the program on
26411 that processor
26412
26413 @item 0 .. Last_Proc
26414 Run the program on the specified processor.
26415 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26416 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26417 @end table
26418
26419 @node Linux-Specific Considerations
26420 @section Linux-Specific Considerations
26421 @cindex Linux threads libraries
26422
26423 @noindent
26424 On GNU/Linux without NPTL support (usually system with GNU C Library
26425 older than 2.3), the signal model is not POSIX compliant, which means
26426 that to send a signal to the process, you need to send the signal to all
26427 threads, e.g.@: by using @code{killpg()}.
26428
26429 @node AIX-Specific Considerations
26430 @section AIX-Specific Considerations
26431 @cindex AIX resolver library
26432
26433 @noindent
26434 On AIX, the resolver library initializes some internal structure on
26435 the first call to @code{get*by*} functions, which are used to implement
26436 @code{GNAT.Sockets.Get_Host_By_Name} and
26437 @code{GNAT.Sockets.Get_Host_By_Address}.
26438 If such initialization occurs within an Ada task, and the stack size for
26439 the task is the default size, a stack overflow may occur.
26440
26441 To avoid this overflow, the user should either ensure that the first call
26442 to @code{GNAT.Sockets.Get_Host_By_Name} or
26443 @code{GNAT.Sockets.Get_Host_By_Addrss}
26444 occurs in the environment task, or use @code{pragma Storage_Size} to
26445 specify a sufficiently large size for the stack of the task that contains
26446 this call.
26447
26448 @node Irix-Specific Considerations
26449 @section Irix-Specific Considerations
26450 @cindex Irix libraries
26451
26452 @noindent
26453 The GCC support libraries coming with the Irix compiler have moved to
26454 their canonical place with respect to the general Irix ABI related
26455 conventions. Running applications built with the default shared GNAT
26456 run-time now requires the LD_LIBRARY_PATH environment variable to
26457 include this location. A possible way to achieve this is to issue the
26458 following command line on a bash prompt:
26459
26460 @smallexample
26461 @group
26462 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26463 @end group
26464 @end smallexample
26465
26466 @node RTX-Specific Considerations
26467 @section RTX-Specific Considerations
26468 @cindex RTX libraries
26469
26470 @noindent
26471 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26472 API. Applications can be built to work in two different modes:
26473
26474 @itemize @bullet
26475 @item
26476 Windows executables that run in Ring 3 to utilize memory protection
26477 (@emph{rts-rtx-w32}).
26478
26479 @item
26480 Real-time subsystem (RTSS) executables that run in Ring 0, where
26481 performance can be optimized with RTSS applications taking precedent
26482 over all Windows applications (@emph{rts-rtx-rtss}).
26483
26484 @end itemize
26485
26486 @c *******************************
26487 @node Example of Binder Output File
26488 @appendix Example of Binder Output File
26489
26490 @noindent
26491 This Appendix displays the source code for @command{gnatbind}'s output
26492 file generated for a simple ``Hello World'' program.
26493 Comments have been added for clarification purposes.
26494
26495 @smallexample @c adanocomment
26496 @iftex
26497 @leftskip=0cm
26498 @end iftex
26499 -- The package is called Ada_Main unless this name is actually used
26500 -- as a unit name in the partition, in which case some other unique
26501 -- name is used.
26502
26503 with System;
26504 package ada_main is
26505
26506 Elab_Final_Code : Integer;
26507 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26508
26509 -- The main program saves the parameters (argument count,
26510 -- argument values, environment pointer) in global variables
26511 -- for later access by other units including
26512 -- Ada.Command_Line.
26513
26514 gnat_argc : Integer;
26515 gnat_argv : System.Address;
26516 gnat_envp : System.Address;
26517
26518 -- The actual variables are stored in a library routine. This
26519 -- is useful for some shared library situations, where there
26520 -- are problems if variables are not in the library.
26521
26522 pragma Import (C, gnat_argc);
26523 pragma Import (C, gnat_argv);
26524 pragma Import (C, gnat_envp);
26525
26526 -- The exit status is similarly an external location
26527
26528 gnat_exit_status : Integer;
26529 pragma Import (C, gnat_exit_status);
26530
26531 GNAT_Version : constant String :=
26532 "GNAT Version: 6.0.0w (20061115)";
26533 pragma Export (C, GNAT_Version, "__gnat_version");
26534
26535 -- This is the generated adafinal routine that performs
26536 -- finalization at the end of execution. In the case where
26537 -- Ada is the main program, this main program makes a call
26538 -- to adafinal at program termination.
26539
26540 procedure adafinal;
26541 pragma Export (C, adafinal, "adafinal");
26542
26543 -- This is the generated adainit routine that performs
26544 -- initialization at the start of execution. In the case
26545 -- where Ada is the main program, this main program makes
26546 -- a call to adainit at program startup.
26547
26548 procedure adainit;
26549 pragma Export (C, adainit, "adainit");
26550
26551 -- This routine is called at the start of execution. It is
26552 -- a dummy routine that is used by the debugger to breakpoint
26553 -- at the start of execution.
26554
26555 procedure Break_Start;
26556 pragma Import (C, Break_Start, "__gnat_break_start");
26557
26558 -- This is the actual generated main program (it would be
26559 -- suppressed if the no main program switch were used). As
26560 -- required by standard system conventions, this program has
26561 -- the external name main.
26562
26563 function main
26564 (argc : Integer;
26565 argv : System.Address;
26566 envp : System.Address)
26567 return Integer;
26568 pragma Export (C, main, "main");
26569
26570 -- The following set of constants give the version
26571 -- identification values for every unit in the bound
26572 -- partition. This identification is computed from all
26573 -- dependent semantic units, and corresponds to the
26574 -- string that would be returned by use of the
26575 -- Body_Version or Version attributes.
26576
26577 type Version_32 is mod 2 ** 32;
26578 u00001 : constant Version_32 := 16#7880BEB3#;
26579 u00002 : constant Version_32 := 16#0D24CBD0#;
26580 u00003 : constant Version_32 := 16#3283DBEB#;
26581 u00004 : constant Version_32 := 16#2359F9ED#;
26582 u00005 : constant Version_32 := 16#664FB847#;
26583 u00006 : constant Version_32 := 16#68E803DF#;
26584 u00007 : constant Version_32 := 16#5572E604#;
26585 u00008 : constant Version_32 := 16#46B173D8#;
26586 u00009 : constant Version_32 := 16#156A40CF#;
26587 u00010 : constant Version_32 := 16#033DABE0#;
26588 u00011 : constant Version_32 := 16#6AB38FEA#;
26589 u00012 : constant Version_32 := 16#22B6217D#;
26590 u00013 : constant Version_32 := 16#68A22947#;
26591 u00014 : constant Version_32 := 16#18CC4A56#;
26592 u00015 : constant Version_32 := 16#08258E1B#;
26593 u00016 : constant Version_32 := 16#367D5222#;
26594 u00017 : constant Version_32 := 16#20C9ECA4#;
26595 u00018 : constant Version_32 := 16#50D32CB6#;
26596 u00019 : constant Version_32 := 16#39A8BB77#;
26597 u00020 : constant Version_32 := 16#5CF8FA2B#;
26598 u00021 : constant Version_32 := 16#2F1EB794#;
26599 u00022 : constant Version_32 := 16#31AB6444#;
26600 u00023 : constant Version_32 := 16#1574B6E9#;
26601 u00024 : constant Version_32 := 16#5109C189#;
26602 u00025 : constant Version_32 := 16#56D770CD#;
26603 u00026 : constant Version_32 := 16#02F9DE3D#;
26604 u00027 : constant Version_32 := 16#08AB6B2C#;
26605 u00028 : constant Version_32 := 16#3FA37670#;
26606 u00029 : constant Version_32 := 16#476457A0#;
26607 u00030 : constant Version_32 := 16#731E1B6E#;
26608 u00031 : constant Version_32 := 16#23C2E789#;
26609 u00032 : constant Version_32 := 16#0F1BD6A1#;
26610 u00033 : constant Version_32 := 16#7C25DE96#;
26611 u00034 : constant Version_32 := 16#39ADFFA2#;
26612 u00035 : constant Version_32 := 16#571DE3E7#;
26613 u00036 : constant Version_32 := 16#5EB646AB#;
26614 u00037 : constant Version_32 := 16#4249379B#;
26615 u00038 : constant Version_32 := 16#0357E00A#;
26616 u00039 : constant Version_32 := 16#3784FB72#;
26617 u00040 : constant Version_32 := 16#2E723019#;
26618 u00041 : constant Version_32 := 16#623358EA#;
26619 u00042 : constant Version_32 := 16#107F9465#;
26620 u00043 : constant Version_32 := 16#6843F68A#;
26621 u00044 : constant Version_32 := 16#63305874#;
26622 u00045 : constant Version_32 := 16#31E56CE1#;
26623 u00046 : constant Version_32 := 16#02917970#;
26624 u00047 : constant Version_32 := 16#6CCBA70E#;
26625 u00048 : constant Version_32 := 16#41CD4204#;
26626 u00049 : constant Version_32 := 16#572E3F58#;
26627 u00050 : constant Version_32 := 16#20729FF5#;
26628 u00051 : constant Version_32 := 16#1D4F93E8#;
26629 u00052 : constant Version_32 := 16#30B2EC3D#;
26630 u00053 : constant Version_32 := 16#34054F96#;
26631 u00054 : constant Version_32 := 16#5A199860#;
26632 u00055 : constant Version_32 := 16#0E7F912B#;
26633 u00056 : constant Version_32 := 16#5760634A#;
26634 u00057 : constant Version_32 := 16#5D851835#;
26635
26636 -- The following Export pragmas export the version numbers
26637 -- with symbolic names ending in B (for body) or S
26638 -- (for spec) so that they can be located in a link. The
26639 -- information provided here is sufficient to track down
26640 -- the exact versions of units used in a given build.
26641
26642 pragma Export (C, u00001, "helloB");
26643 pragma Export (C, u00002, "system__standard_libraryB");
26644 pragma Export (C, u00003, "system__standard_libraryS");
26645 pragma Export (C, u00004, "adaS");
26646 pragma Export (C, u00005, "ada__text_ioB");
26647 pragma Export (C, u00006, "ada__text_ioS");
26648 pragma Export (C, u00007, "ada__exceptionsB");
26649 pragma Export (C, u00008, "ada__exceptionsS");
26650 pragma Export (C, u00009, "gnatS");
26651 pragma Export (C, u00010, "gnat__heap_sort_aB");
26652 pragma Export (C, u00011, "gnat__heap_sort_aS");
26653 pragma Export (C, u00012, "systemS");
26654 pragma Export (C, u00013, "system__exception_tableB");
26655 pragma Export (C, u00014, "system__exception_tableS");
26656 pragma Export (C, u00015, "gnat__htableB");
26657 pragma Export (C, u00016, "gnat__htableS");
26658 pragma Export (C, u00017, "system__exceptionsS");
26659 pragma Export (C, u00018, "system__machine_state_operationsB");
26660 pragma Export (C, u00019, "system__machine_state_operationsS");
26661 pragma Export (C, u00020, "system__machine_codeS");
26662 pragma Export (C, u00021, "system__storage_elementsB");
26663 pragma Export (C, u00022, "system__storage_elementsS");
26664 pragma Export (C, u00023, "system__secondary_stackB");
26665 pragma Export (C, u00024, "system__secondary_stackS");
26666 pragma Export (C, u00025, "system__parametersB");
26667 pragma Export (C, u00026, "system__parametersS");
26668 pragma Export (C, u00027, "system__soft_linksB");
26669 pragma Export (C, u00028, "system__soft_linksS");
26670 pragma Export (C, u00029, "system__stack_checkingB");
26671 pragma Export (C, u00030, "system__stack_checkingS");
26672 pragma Export (C, u00031, "system__tracebackB");
26673 pragma Export (C, u00032, "system__tracebackS");
26674 pragma Export (C, u00033, "ada__streamsS");
26675 pragma Export (C, u00034, "ada__tagsB");
26676 pragma Export (C, u00035, "ada__tagsS");
26677 pragma Export (C, u00036, "system__string_opsB");
26678 pragma Export (C, u00037, "system__string_opsS");
26679 pragma Export (C, u00038, "interfacesS");
26680 pragma Export (C, u00039, "interfaces__c_streamsB");
26681 pragma Export (C, u00040, "interfaces__c_streamsS");
26682 pragma Export (C, u00041, "system__file_ioB");
26683 pragma Export (C, u00042, "system__file_ioS");
26684 pragma Export (C, u00043, "ada__finalizationB");
26685 pragma Export (C, u00044, "ada__finalizationS");
26686 pragma Export (C, u00045, "system__finalization_rootB");
26687 pragma Export (C, u00046, "system__finalization_rootS");
26688 pragma Export (C, u00047, "system__finalization_implementationB");
26689 pragma Export (C, u00048, "system__finalization_implementationS");
26690 pragma Export (C, u00049, "system__string_ops_concat_3B");
26691 pragma Export (C, u00050, "system__string_ops_concat_3S");
26692 pragma Export (C, u00051, "system__stream_attributesB");
26693 pragma Export (C, u00052, "system__stream_attributesS");
26694 pragma Export (C, u00053, "ada__io_exceptionsS");
26695 pragma Export (C, u00054, "system__unsigned_typesS");
26696 pragma Export (C, u00055, "system__file_control_blockS");
26697 pragma Export (C, u00056, "ada__finalization__list_controllerB");
26698 pragma Export (C, u00057, "ada__finalization__list_controllerS");
26699
26700 -- BEGIN ELABORATION ORDER
26701 -- ada (spec)
26702 -- gnat (spec)
26703 -- gnat.heap_sort_a (spec)
26704 -- gnat.heap_sort_a (body)
26705 -- gnat.htable (spec)
26706 -- gnat.htable (body)
26707 -- interfaces (spec)
26708 -- system (spec)
26709 -- system.machine_code (spec)
26710 -- system.parameters (spec)
26711 -- system.parameters (body)
26712 -- interfaces.c_streams (spec)
26713 -- interfaces.c_streams (body)
26714 -- system.standard_library (spec)
26715 -- ada.exceptions (spec)
26716 -- system.exception_table (spec)
26717 -- system.exception_table (body)
26718 -- ada.io_exceptions (spec)
26719 -- system.exceptions (spec)
26720 -- system.storage_elements (spec)
26721 -- system.storage_elements (body)
26722 -- system.machine_state_operations (spec)
26723 -- system.machine_state_operations (body)
26724 -- system.secondary_stack (spec)
26725 -- system.stack_checking (spec)
26726 -- system.soft_links (spec)
26727 -- system.soft_links (body)
26728 -- system.stack_checking (body)
26729 -- system.secondary_stack (body)
26730 -- system.standard_library (body)
26731 -- system.string_ops (spec)
26732 -- system.string_ops (body)
26733 -- ada.tags (spec)
26734 -- ada.tags (body)
26735 -- ada.streams (spec)
26736 -- system.finalization_root (spec)
26737 -- system.finalization_root (body)
26738 -- system.string_ops_concat_3 (spec)
26739 -- system.string_ops_concat_3 (body)
26740 -- system.traceback (spec)
26741 -- system.traceback (body)
26742 -- ada.exceptions (body)
26743 -- system.unsigned_types (spec)
26744 -- system.stream_attributes (spec)
26745 -- system.stream_attributes (body)
26746 -- system.finalization_implementation (spec)
26747 -- system.finalization_implementation (body)
26748 -- ada.finalization (spec)
26749 -- ada.finalization (body)
26750 -- ada.finalization.list_controller (spec)
26751 -- ada.finalization.list_controller (body)
26752 -- system.file_control_block (spec)
26753 -- system.file_io (spec)
26754 -- system.file_io (body)
26755 -- ada.text_io (spec)
26756 -- ada.text_io (body)
26757 -- hello (body)
26758 -- END ELABORATION ORDER
26759
26760 end ada_main;
26761
26762 -- The following source file name pragmas allow the generated file
26763 -- names to be unique for different main programs. They are needed
26764 -- since the package name will always be Ada_Main.
26765
26766 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26767 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26768
26769 -- Generated package body for Ada_Main starts here
26770
26771 package body ada_main is
26772
26773 -- The actual finalization is performed by calling the
26774 -- library routine in System.Standard_Library.Adafinal
26775
26776 procedure Do_Finalize;
26777 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26778
26779 -------------
26780 -- adainit --
26781 -------------
26782
26783 @findex adainit
26784 procedure adainit is
26785
26786 -- These booleans are set to True once the associated unit has
26787 -- been elaborated. It is also used to avoid elaborating the
26788 -- same unit twice.
26789
26790 E040 : Boolean;
26791 pragma Import (Ada, E040, "interfaces__c_streams_E");
26792
26793 E008 : Boolean;
26794 pragma Import (Ada, E008, "ada__exceptions_E");
26795
26796 E014 : Boolean;
26797 pragma Import (Ada, E014, "system__exception_table_E");
26798
26799 E053 : Boolean;
26800 pragma Import (Ada, E053, "ada__io_exceptions_E");
26801
26802 E017 : Boolean;
26803 pragma Import (Ada, E017, "system__exceptions_E");
26804
26805 E024 : Boolean;
26806 pragma Import (Ada, E024, "system__secondary_stack_E");
26807
26808 E030 : Boolean;
26809 pragma Import (Ada, E030, "system__stack_checking_E");
26810
26811 E028 : Boolean;
26812 pragma Import (Ada, E028, "system__soft_links_E");
26813
26814 E035 : Boolean;
26815 pragma Import (Ada, E035, "ada__tags_E");
26816
26817 E033 : Boolean;
26818 pragma Import (Ada, E033, "ada__streams_E");
26819
26820 E046 : Boolean;
26821 pragma Import (Ada, E046, "system__finalization_root_E");
26822
26823 E048 : Boolean;
26824 pragma Import (Ada, E048, "system__finalization_implementation_E");
26825
26826 E044 : Boolean;
26827 pragma Import (Ada, E044, "ada__finalization_E");
26828
26829 E057 : Boolean;
26830 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26831
26832 E055 : Boolean;
26833 pragma Import (Ada, E055, "system__file_control_block_E");
26834
26835 E042 : Boolean;
26836 pragma Import (Ada, E042, "system__file_io_E");
26837
26838 E006 : Boolean;
26839 pragma Import (Ada, E006, "ada__text_io_E");
26840
26841 -- Set_Globals is a library routine that stores away the
26842 -- value of the indicated set of global values in global
26843 -- variables within the library.
26844
26845 procedure Set_Globals
26846 (Main_Priority : Integer;
26847 Time_Slice_Value : Integer;
26848 WC_Encoding : Character;
26849 Locking_Policy : Character;
26850 Queuing_Policy : Character;
26851 Task_Dispatching_Policy : Character;
26852 Adafinal : System.Address;
26853 Unreserve_All_Interrupts : Integer;
26854 Exception_Tracebacks : Integer);
26855 @findex __gnat_set_globals
26856 pragma Import (C, Set_Globals, "__gnat_set_globals");
26857
26858 -- SDP_Table_Build is a library routine used to build the
26859 -- exception tables. See unit Ada.Exceptions in files
26860 -- a-except.ads/adb for full details of how zero cost
26861 -- exception handling works. This procedure, the call to
26862 -- it, and the two following tables are all omitted if the
26863 -- build is in longjmp/setjmp exception mode.
26864
26865 @findex SDP_Table_Build
26866 @findex Zero Cost Exceptions
26867 procedure SDP_Table_Build
26868 (SDP_Addresses : System.Address;
26869 SDP_Count : Natural;
26870 Elab_Addresses : System.Address;
26871 Elab_Addr_Count : Natural);
26872 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26873
26874 -- Table of Unit_Exception_Table addresses. Used for zero
26875 -- cost exception handling to build the top level table.
26876
26877 ST : aliased constant array (1 .. 23) of System.Address := (
26878 Hello'UET_Address,
26879 Ada.Text_Io'UET_Address,
26880 Ada.Exceptions'UET_Address,
26881 Gnat.Heap_Sort_A'UET_Address,
26882 System.Exception_Table'UET_Address,
26883 System.Machine_State_Operations'UET_Address,
26884 System.Secondary_Stack'UET_Address,
26885 System.Parameters'UET_Address,
26886 System.Soft_Links'UET_Address,
26887 System.Stack_Checking'UET_Address,
26888 System.Traceback'UET_Address,
26889 Ada.Streams'UET_Address,
26890 Ada.Tags'UET_Address,
26891 System.String_Ops'UET_Address,
26892 Interfaces.C_Streams'UET_Address,
26893 System.File_Io'UET_Address,
26894 Ada.Finalization'UET_Address,
26895 System.Finalization_Root'UET_Address,
26896 System.Finalization_Implementation'UET_Address,
26897 System.String_Ops_Concat_3'UET_Address,
26898 System.Stream_Attributes'UET_Address,
26899 System.File_Control_Block'UET_Address,
26900 Ada.Finalization.List_Controller'UET_Address);
26901
26902 -- Table of addresses of elaboration routines. Used for
26903 -- zero cost exception handling to make sure these
26904 -- addresses are included in the top level procedure
26905 -- address table.
26906
26907 EA : aliased constant array (1 .. 23) of System.Address := (
26908 adainit'Code_Address,
26909 Do_Finalize'Code_Address,
26910 Ada.Exceptions'Elab_Spec'Address,
26911 System.Exceptions'Elab_Spec'Address,
26912 Interfaces.C_Streams'Elab_Spec'Address,
26913 System.Exception_Table'Elab_Body'Address,
26914 Ada.Io_Exceptions'Elab_Spec'Address,
26915 System.Stack_Checking'Elab_Spec'Address,
26916 System.Soft_Links'Elab_Body'Address,
26917 System.Secondary_Stack'Elab_Body'Address,
26918 Ada.Tags'Elab_Spec'Address,
26919 Ada.Tags'Elab_Body'Address,
26920 Ada.Streams'Elab_Spec'Address,
26921 System.Finalization_Root'Elab_Spec'Address,
26922 Ada.Exceptions'Elab_Body'Address,
26923 System.Finalization_Implementation'Elab_Spec'Address,
26924 System.Finalization_Implementation'Elab_Body'Address,
26925 Ada.Finalization'Elab_Spec'Address,
26926 Ada.Finalization.List_Controller'Elab_Spec'Address,
26927 System.File_Control_Block'Elab_Spec'Address,
26928 System.File_Io'Elab_Body'Address,
26929 Ada.Text_Io'Elab_Spec'Address,
26930 Ada.Text_Io'Elab_Body'Address);
26931
26932 -- Start of processing for adainit
26933
26934 begin
26935
26936 -- Call SDP_Table_Build to build the top level procedure
26937 -- table for zero cost exception handling (omitted in
26938 -- longjmp/setjmp mode).
26939
26940 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26941
26942 -- Call Set_Globals to record various information for
26943 -- this partition. The values are derived by the binder
26944 -- from information stored in the ali files by the compiler.
26945
26946 @findex __gnat_set_globals
26947 Set_Globals
26948 (Main_Priority => -1,
26949 -- Priority of main program, -1 if no pragma Priority used
26950
26951 Time_Slice_Value => -1,
26952 -- Time slice from Time_Slice pragma, -1 if none used
26953
26954 WC_Encoding => 'b',
26955 -- Wide_Character encoding used, default is brackets
26956
26957 Locking_Policy => ' ',
26958 -- Locking_Policy used, default of space means not
26959 -- specified, otherwise it is the first character of
26960 -- the policy name.
26961
26962 Queuing_Policy => ' ',
26963 -- Queuing_Policy used, default of space means not
26964 -- specified, otherwise it is the first character of
26965 -- the policy name.
26966
26967 Task_Dispatching_Policy => ' ',
26968 -- Task_Dispatching_Policy used, default of space means
26969 -- not specified, otherwise first character of the
26970 -- policy name.
26971
26972 Adafinal => System.Null_Address,
26973 -- Address of Adafinal routine, not used anymore
26974
26975 Unreserve_All_Interrupts => 0,
26976 -- Set true if pragma Unreserve_All_Interrupts was used
26977
26978 Exception_Tracebacks => 0);
26979 -- Indicates if exception tracebacks are enabled
26980
26981 Elab_Final_Code := 1;
26982
26983 -- Now we have the elaboration calls for all units in the partition.
26984 -- The Elab_Spec and Elab_Body attributes generate references to the
26985 -- implicit elaboration procedures generated by the compiler for
26986 -- each unit that requires elaboration.
26987
26988 if not E040 then
26989 Interfaces.C_Streams'Elab_Spec;
26990 end if;
26991 E040 := True;
26992 if not E008 then
26993 Ada.Exceptions'Elab_Spec;
26994 end if;
26995 if not E014 then
26996 System.Exception_Table'Elab_Body;
26997 E014 := True;
26998 end if;
26999 if not E053 then
27000 Ada.Io_Exceptions'Elab_Spec;
27001 E053 := True;
27002 end if;
27003 if not E017 then
27004 System.Exceptions'Elab_Spec;
27005 E017 := True;
27006 end if;
27007 if not E030 then
27008 System.Stack_Checking'Elab_Spec;
27009 end if;
27010 if not E028 then
27011 System.Soft_Links'Elab_Body;
27012 E028 := True;
27013 end if;
27014 E030 := True;
27015 if not E024 then
27016 System.Secondary_Stack'Elab_Body;
27017 E024 := True;
27018 end if;
27019 if not E035 then
27020 Ada.Tags'Elab_Spec;
27021 end if;
27022 if not E035 then
27023 Ada.Tags'Elab_Body;
27024 E035 := True;
27025 end if;
27026 if not E033 then
27027 Ada.Streams'Elab_Spec;
27028 E033 := True;
27029 end if;
27030 if not E046 then
27031 System.Finalization_Root'Elab_Spec;
27032 end if;
27033 E046 := True;
27034 if not E008 then
27035 Ada.Exceptions'Elab_Body;
27036 E008 := True;
27037 end if;
27038 if not E048 then
27039 System.Finalization_Implementation'Elab_Spec;
27040 end if;
27041 if not E048 then
27042 System.Finalization_Implementation'Elab_Body;
27043 E048 := True;
27044 end if;
27045 if not E044 then
27046 Ada.Finalization'Elab_Spec;
27047 end if;
27048 E044 := True;
27049 if not E057 then
27050 Ada.Finalization.List_Controller'Elab_Spec;
27051 end if;
27052 E057 := True;
27053 if not E055 then
27054 System.File_Control_Block'Elab_Spec;
27055 E055 := True;
27056 end if;
27057 if not E042 then
27058 System.File_Io'Elab_Body;
27059 E042 := True;
27060 end if;
27061 if not E006 then
27062 Ada.Text_Io'Elab_Spec;
27063 end if;
27064 if not E006 then
27065 Ada.Text_Io'Elab_Body;
27066 E006 := True;
27067 end if;
27068
27069 Elab_Final_Code := 0;
27070 end adainit;
27071
27072 --------------
27073 -- adafinal --
27074 --------------
27075
27076 @findex adafinal
27077 procedure adafinal is
27078 begin
27079 Do_Finalize;
27080 end adafinal;
27081
27082 ----------
27083 -- main --
27084 ----------
27085
27086 -- main is actually a function, as in the ANSI C standard,
27087 -- defined to return the exit status. The three parameters
27088 -- are the argument count, argument values and environment
27089 -- pointer.
27090
27091 @findex Main Program
27092 function main
27093 (argc : Integer;
27094 argv : System.Address;
27095 envp : System.Address)
27096 return Integer
27097 is
27098 -- The initialize routine performs low level system
27099 -- initialization using a standard library routine which
27100 -- sets up signal handling and performs any other
27101 -- required setup. The routine can be found in file
27102 -- a-init.c.
27103
27104 @findex __gnat_initialize
27105 procedure initialize;
27106 pragma Import (C, initialize, "__gnat_initialize");
27107
27108 -- The finalize routine performs low level system
27109 -- finalization using a standard library routine. The
27110 -- routine is found in file a-final.c and in the standard
27111 -- distribution is a dummy routine that does nothing, so
27112 -- really this is a hook for special user finalization.
27113
27114 @findex __gnat_finalize
27115 procedure finalize;
27116 pragma Import (C, finalize, "__gnat_finalize");
27117
27118 -- We get to the main program of the partition by using
27119 -- pragma Import because if we try to with the unit and
27120 -- call it Ada style, then not only do we waste time
27121 -- recompiling it, but also, we don't really know the right
27122 -- switches (e.g.@: identifier character set) to be used
27123 -- to compile it.
27124
27125 procedure Ada_Main_Program;
27126 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27127
27128 -- Start of processing for main
27129
27130 begin
27131 -- Save global variables
27132
27133 gnat_argc := argc;
27134 gnat_argv := argv;
27135 gnat_envp := envp;
27136
27137 -- Call low level system initialization
27138
27139 Initialize;
27140
27141 -- Call our generated Ada initialization routine
27142
27143 adainit;
27144
27145 -- This is the point at which we want the debugger to get
27146 -- control
27147
27148 Break_Start;
27149
27150 -- Now we call the main program of the partition
27151
27152 Ada_Main_Program;
27153
27154 -- Perform Ada finalization
27155
27156 adafinal;
27157
27158 -- Perform low level system finalization
27159
27160 Finalize;
27161
27162 -- Return the proper exit status
27163 return (gnat_exit_status);
27164 end;
27165
27166 -- This section is entirely comments, so it has no effect on the
27167 -- compilation of the Ada_Main package. It provides the list of
27168 -- object files and linker options, as well as some standard
27169 -- libraries needed for the link. The gnatlink utility parses
27170 -- this b~hello.adb file to read these comment lines to generate
27171 -- the appropriate command line arguments for the call to the
27172 -- system linker. The BEGIN/END lines are used for sentinels for
27173 -- this parsing operation.
27174
27175 -- The exact file names will of course depend on the environment,
27176 -- host/target and location of files on the host system.
27177
27178 @findex Object file list
27179 -- BEGIN Object file/option list
27180 -- ./hello.o
27181 -- -L./
27182 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27183 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27184 -- END Object file/option list
27185
27186 end ada_main;
27187 @end smallexample
27188
27189 @noindent
27190 The Ada code in the above example is exactly what is generated by the
27191 binder. We have added comments to more clearly indicate the function
27192 of each part of the generated @code{Ada_Main} package.
27193
27194 The code is standard Ada in all respects, and can be processed by any
27195 tools that handle Ada. In particular, it is possible to use the debugger
27196 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27197 suppose that for reasons that you do not understand, your program is crashing
27198 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27199 you can place a breakpoint on the call:
27200
27201 @smallexample @c ada
27202 Ada.Text_Io'Elab_Body;
27203 @end smallexample
27204
27205 @noindent
27206 and trace the elaboration routine for this package to find out where
27207 the problem might be (more usually of course you would be debugging
27208 elaboration code in your own application).
27209
27210 @node Elaboration Order Handling in GNAT
27211 @appendix Elaboration Order Handling in GNAT
27212 @cindex Order of elaboration
27213 @cindex Elaboration control
27214
27215 @menu
27216 * Elaboration Code::
27217 * Checking the Elaboration Order::
27218 * Controlling the Elaboration Order::
27219 * Controlling Elaboration in GNAT - Internal Calls::
27220 * Controlling Elaboration in GNAT - External Calls::
27221 * Default Behavior in GNAT - Ensuring Safety::
27222 * Treatment of Pragma Elaborate::
27223 * Elaboration Issues for Library Tasks::
27224 * Mixing Elaboration Models::
27225 * What to Do If the Default Elaboration Behavior Fails::
27226 * Elaboration for Access-to-Subprogram Values::
27227 * Summary of Procedures for Elaboration Control::
27228 * Other Elaboration Order Considerations::
27229 @end menu
27230
27231 @noindent
27232 This chapter describes the handling of elaboration code in Ada and
27233 in GNAT, and discusses how the order of elaboration of program units can
27234 be controlled in GNAT, either automatically or with explicit programming
27235 features.
27236
27237 @node Elaboration Code
27238 @section Elaboration Code
27239
27240 @noindent
27241 Ada provides rather general mechanisms for executing code at elaboration
27242 time, that is to say before the main program starts executing. Such code arises
27243 in three contexts:
27244
27245 @table @asis
27246 @item Initializers for variables.
27247 Variables declared at the library level, in package specs or bodies, can
27248 require initialization that is performed at elaboration time, as in:
27249 @smallexample @c ada
27250 @cartouche
27251 Sqrt_Half : Float := Sqrt (0.5);
27252 @end cartouche
27253 @end smallexample
27254
27255 @item Package initialization code
27256 Code in a @code{BEGIN-END} section at the outer level of a package body is
27257 executed as part of the package body elaboration code.
27258
27259 @item Library level task allocators
27260 Tasks that are declared using task allocators at the library level
27261 start executing immediately and hence can execute at elaboration time.
27262 @end table
27263
27264 @noindent
27265 Subprogram calls are possible in any of these contexts, which means that
27266 any arbitrary part of the program may be executed as part of the elaboration
27267 code. It is even possible to write a program which does all its work at
27268 elaboration time, with a null main program, although stylistically this
27269 would usually be considered an inappropriate way to structure
27270 a program.
27271
27272 An important concern arises in the context of elaboration code:
27273 we have to be sure that it is executed in an appropriate order. What we
27274 have is a series of elaboration code sections, potentially one section
27275 for each unit in the program. It is important that these execute
27276 in the correct order. Correctness here means that, taking the above
27277 example of the declaration of @code{Sqrt_Half},
27278 if some other piece of
27279 elaboration code references @code{Sqrt_Half},
27280 then it must run after the
27281 section of elaboration code that contains the declaration of
27282 @code{Sqrt_Half}.
27283
27284 There would never be any order of elaboration problem if we made a rule
27285 that whenever you @code{with} a unit, you must elaborate both the spec and body
27286 of that unit before elaborating the unit doing the @code{with}'ing:
27287
27288 @smallexample @c ada
27289 @group
27290 @cartouche
27291 with Unit_1;
27292 package Unit_2 is @dots{}
27293 @end cartouche
27294 @end group
27295 @end smallexample
27296
27297 @noindent
27298 would require that both the body and spec of @code{Unit_1} be elaborated
27299 before the spec of @code{Unit_2}. However, a rule like that would be far too
27300 restrictive. In particular, it would make it impossible to have routines
27301 in separate packages that were mutually recursive.
27302
27303 You might think that a clever enough compiler could look at the actual
27304 elaboration code and determine an appropriate correct order of elaboration,
27305 but in the general case, this is not possible. Consider the following
27306 example.
27307
27308 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27309 that references
27310 the variable @code{Sqrt_1}, which is declared in the elaboration code
27311 of the body of @code{Unit_1}:
27312
27313 @smallexample @c ada
27314 @cartouche
27315 Sqrt_1 : Float := Sqrt (0.1);
27316 @end cartouche
27317 @end smallexample
27318
27319 @noindent
27320 The elaboration code of the body of @code{Unit_1} also contains:
27321
27322 @smallexample @c ada
27323 @group
27324 @cartouche
27325 if expression_1 = 1 then
27326 Q := Unit_2.Func_2;
27327 end if;
27328 @end cartouche
27329 @end group
27330 @end smallexample
27331
27332 @noindent
27333 @code{Unit_2} is exactly parallel,
27334 it has a procedure @code{Func_2} that references
27335 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27336 the body @code{Unit_2}:
27337
27338 @smallexample @c ada
27339 @cartouche
27340 Sqrt_2 : Float := Sqrt (0.1);
27341 @end cartouche
27342 @end smallexample
27343
27344 @noindent
27345 The elaboration code of the body of @code{Unit_2} also contains:
27346
27347 @smallexample @c ada
27348 @group
27349 @cartouche
27350 if expression_2 = 2 then
27351 Q := Unit_1.Func_1;
27352 end if;
27353 @end cartouche
27354 @end group
27355 @end smallexample
27356
27357 @noindent
27358 Now the question is, which of the following orders of elaboration is
27359 acceptable:
27360
27361 @smallexample
27362 @group
27363 Spec of Unit_1
27364 Spec of Unit_2
27365 Body of Unit_1
27366 Body of Unit_2
27367 @end group
27368 @end smallexample
27369
27370 @noindent
27371 or
27372
27373 @smallexample
27374 @group
27375 Spec of Unit_2
27376 Spec of Unit_1
27377 Body of Unit_2
27378 Body of Unit_1
27379 @end group
27380 @end smallexample
27381
27382 @noindent
27383 If you carefully analyze the flow here, you will see that you cannot tell
27384 at compile time the answer to this question.
27385 If @code{expression_1} is not equal to 1,
27386 and @code{expression_2} is not equal to 2,
27387 then either order is acceptable, because neither of the function calls is
27388 executed. If both tests evaluate to true, then neither order is acceptable
27389 and in fact there is no correct order.
27390
27391 If one of the two expressions is true, and the other is false, then one
27392 of the above orders is correct, and the other is incorrect. For example,
27393 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27394 then the call to @code{Func_1}
27395 will occur, but not the call to @code{Func_2.}
27396 This means that it is essential
27397 to elaborate the body of @code{Unit_1} before
27398 the body of @code{Unit_2}, so the first
27399 order of elaboration is correct and the second is wrong.
27400
27401 By making @code{expression_1} and @code{expression_2}
27402 depend on input data, or perhaps
27403 the time of day, we can make it impossible for the compiler or binder
27404 to figure out which of these expressions will be true, and hence it
27405 is impossible to guarantee a safe order of elaboration at run time.
27406
27407 @node Checking the Elaboration Order
27408 @section Checking the Elaboration Order
27409
27410 @noindent
27411 In some languages that involve the same kind of elaboration problems,
27412 e.g.@: Java and C++, the programmer is expected to worry about these
27413 ordering problems himself, and it is common to
27414 write a program in which an incorrect elaboration order gives
27415 surprising results, because it references variables before they
27416 are initialized.
27417 Ada is designed to be a safe language, and a programmer-beware approach is
27418 clearly not sufficient. Consequently, the language provides three lines
27419 of defense:
27420
27421 @table @asis
27422 @item Standard rules
27423 Some standard rules restrict the possible choice of elaboration
27424 order. In particular, if you @code{with} a unit, then its spec is always
27425 elaborated before the unit doing the @code{with}. Similarly, a parent
27426 spec is always elaborated before the child spec, and finally
27427 a spec is always elaborated before its corresponding body.
27428
27429 @item Dynamic elaboration checks
27430 @cindex Elaboration checks
27431 @cindex Checks, elaboration
27432 Dynamic checks are made at run time, so that if some entity is accessed
27433 before it is elaborated (typically by means of a subprogram call)
27434 then the exception (@code{Program_Error}) is raised.
27435
27436 @item Elaboration control
27437 Facilities are provided for the programmer to specify the desired order
27438 of elaboration.
27439 @end table
27440
27441 Let's look at these facilities in more detail. First, the rules for
27442 dynamic checking. One possible rule would be simply to say that the
27443 exception is raised if you access a variable which has not yet been
27444 elaborated. The trouble with this approach is that it could require
27445 expensive checks on every variable reference. Instead Ada has two
27446 rules which are a little more restrictive, but easier to check, and
27447 easier to state:
27448
27449 @table @asis
27450 @item Restrictions on calls
27451 A subprogram can only be called at elaboration time if its body
27452 has been elaborated. The rules for elaboration given above guarantee
27453 that the spec of the subprogram has been elaborated before the
27454 call, but not the body. If this rule is violated, then the
27455 exception @code{Program_Error} is raised.
27456
27457 @item Restrictions on instantiations
27458 A generic unit can only be instantiated if the body of the generic
27459 unit has been elaborated. Again, the rules for elaboration given above
27460 guarantee that the spec of the generic unit has been elaborated
27461 before the instantiation, but not the body. If this rule is
27462 violated, then the exception @code{Program_Error} is raised.
27463 @end table
27464
27465 @noindent
27466 The idea is that if the body has been elaborated, then any variables
27467 it references must have been elaborated; by checking for the body being
27468 elaborated we guarantee that none of its references causes any
27469 trouble. As we noted above, this is a little too restrictive, because a
27470 subprogram that has no non-local references in its body may in fact be safe
27471 to call. However, it really would be unsafe to rely on this, because
27472 it would mean that the caller was aware of details of the implementation
27473 in the body. This goes against the basic tenets of Ada.
27474
27475 A plausible implementation can be described as follows.
27476 A Boolean variable is associated with each subprogram
27477 and each generic unit. This variable is initialized to False, and is set to
27478 True at the point body is elaborated. Every call or instantiation checks the
27479 variable, and raises @code{Program_Error} if the variable is False.
27480
27481 Note that one might think that it would be good enough to have one Boolean
27482 variable for each package, but that would not deal with cases of trying
27483 to call a body in the same package as the call
27484 that has not been elaborated yet.
27485 Of course a compiler may be able to do enough analysis to optimize away
27486 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27487 does such optimizations, but still the easiest conceptual model is to
27488 think of there being one variable per subprogram.
27489
27490 @node Controlling the Elaboration Order
27491 @section Controlling the Elaboration Order
27492
27493 @noindent
27494 In the previous section we discussed the rules in Ada which ensure
27495 that @code{Program_Error} is raised if an incorrect elaboration order is
27496 chosen. This prevents erroneous executions, but we need mechanisms to
27497 specify a correct execution and avoid the exception altogether.
27498 To achieve this, Ada provides a number of features for controlling
27499 the order of elaboration. We discuss these features in this section.
27500
27501 First, there are several ways of indicating to the compiler that a given
27502 unit has no elaboration problems:
27503
27504 @table @asis
27505 @item packages that do not require a body
27506 A library package that does not require a body does not permit
27507 a body (this rule was introduced in Ada 95).
27508 Thus if we have a such a package, as in:
27509
27510 @smallexample @c ada
27511 @group
27512 @cartouche
27513 package Definitions is
27514 generic
27515 type m is new integer;
27516 package Subp is
27517 type a is array (1 .. 10) of m;
27518 type b is array (1 .. 20) of m;
27519 end Subp;
27520 end Definitions;
27521 @end cartouche
27522 @end group
27523 @end smallexample
27524
27525 @noindent
27526 A package that @code{with}'s @code{Definitions} may safely instantiate
27527 @code{Definitions.Subp} because the compiler can determine that there
27528 definitely is no package body to worry about in this case
27529
27530 @item pragma Pure
27531 @cindex pragma Pure
27532 @findex Pure
27533 Places sufficient restrictions on a unit to guarantee that
27534 no call to any subprogram in the unit can result in an
27535 elaboration problem. This means that the compiler does not need
27536 to worry about the point of elaboration of such units, and in
27537 particular, does not need to check any calls to any subprograms
27538 in this unit.
27539
27540 @item pragma Preelaborate
27541 @findex Preelaborate
27542 @cindex pragma Preelaborate
27543 This pragma places slightly less stringent restrictions on a unit than
27544 does pragma Pure,
27545 but these restrictions are still sufficient to ensure that there
27546 are no elaboration problems with any calls to the unit.
27547
27548 @item pragma Elaborate_Body
27549 @findex Elaborate_Body
27550 @cindex pragma Elaborate_Body
27551 This pragma requires that the body of a unit be elaborated immediately
27552 after its spec. Suppose a unit @code{A} has such a pragma,
27553 and unit @code{B} does
27554 a @code{with} of unit @code{A}. Recall that the standard rules require
27555 the spec of unit @code{A}
27556 to be elaborated before the @code{with}'ing unit; given the pragma in
27557 @code{A}, we also know that the body of @code{A}
27558 will be elaborated before @code{B}, so
27559 that calls to @code{A} are safe and do not need a check.
27560 @end table
27561
27562 @noindent
27563 Note that,
27564 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27565 the use of
27566 @code{Elaborate_Body} does not guarantee that the program is
27567 free of elaboration problems, because it may not be possible
27568 to satisfy the requested elaboration order.
27569 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27570 If a programmer
27571 marks @code{Unit_1} as @code{Elaborate_Body},
27572 and not @code{Unit_2,} then the order of
27573 elaboration will be:
27574
27575 @smallexample
27576 @group
27577 Spec of Unit_2
27578 Spec of Unit_1
27579 Body of Unit_1
27580 Body of Unit_2
27581 @end group
27582 @end smallexample
27583
27584 @noindent
27585 Now that means that the call to @code{Func_1} in @code{Unit_2}
27586 need not be checked,
27587 it must be safe. But the call to @code{Func_2} in
27588 @code{Unit_1} may still fail if
27589 @code{Expression_1} is equal to 1,
27590 and the programmer must still take
27591 responsibility for this not being the case.
27592
27593 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27594 eliminated, except for calls entirely within a body, which are
27595 in any case fully under programmer control. However, using the pragma
27596 everywhere is not always possible.
27597 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27598 we marked both of them as having pragma @code{Elaborate_Body}, then
27599 clearly there would be no possible elaboration order.
27600
27601 The above pragmas allow a server to guarantee safe use by clients, and
27602 clearly this is the preferable approach. Consequently a good rule
27603 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27604 and if this is not possible,
27605 mark them as @code{Elaborate_Body} if possible.
27606 As we have seen, there are situations where neither of these
27607 three pragmas can be used.
27608 So we also provide methods for clients to control the
27609 order of elaboration of the servers on which they depend:
27610
27611 @table @asis
27612 @item pragma Elaborate (unit)
27613 @findex Elaborate
27614 @cindex pragma Elaborate
27615 This pragma is placed in the context clause, after a @code{with} clause,
27616 and it requires that the body of the named unit be elaborated before
27617 the unit in which the pragma occurs. The idea is to use this pragma
27618 if the current unit calls at elaboration time, directly or indirectly,
27619 some subprogram in the named unit.
27620
27621 @item pragma Elaborate_All (unit)
27622 @findex Elaborate_All
27623 @cindex pragma Elaborate_All
27624 This is a stronger version of the Elaborate pragma. Consider the
27625 following example:
27626
27627 @smallexample
27628 Unit A @code{with}'s unit B and calls B.Func in elab code
27629 Unit B @code{with}'s unit C, and B.Func calls C.Func
27630 @end smallexample
27631
27632 @noindent
27633 Now if we put a pragma @code{Elaborate (B)}
27634 in unit @code{A}, this ensures that the
27635 body of @code{B} is elaborated before the call, but not the
27636 body of @code{C}, so
27637 the call to @code{C.Func} could still cause @code{Program_Error} to
27638 be raised.
27639
27640 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27641 not only that the body of the named unit be elaborated before the
27642 unit doing the @code{with}, but also the bodies of all units that the
27643 named unit uses, following @code{with} links transitively. For example,
27644 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27645 then it requires
27646 not only that the body of @code{B} be elaborated before @code{A},
27647 but also the
27648 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27649 @end table
27650
27651 @noindent
27652 We are now in a position to give a usage rule in Ada for avoiding
27653 elaboration problems, at least if dynamic dispatching and access to
27654 subprogram values are not used. We will handle these cases separately
27655 later.
27656
27657 The rule is simple. If a unit has elaboration code that can directly or
27658 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27659 a generic package in a @code{with}'ed unit,
27660 then if the @code{with}'ed unit does not have
27661 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27662 a pragma @code{Elaborate_All}
27663 for the @code{with}'ed unit. By following this rule a client is
27664 assured that calls can be made without risk of an exception.
27665
27666 For generic subprogram instantiations, the rule can be relaxed to
27667 require only a pragma @code{Elaborate} since elaborating the body
27668 of a subprogram cannot cause any transitive elaboration (we are
27669 not calling the subprogram in this case, just elaborating its
27670 declaration).
27671
27672 If this rule is not followed, then a program may be in one of four
27673 states:
27674
27675 @table @asis
27676 @item No order exists
27677 No order of elaboration exists which follows the rules, taking into
27678 account any @code{Elaborate}, @code{Elaborate_All},
27679 or @code{Elaborate_Body} pragmas. In
27680 this case, an Ada compiler must diagnose the situation at bind
27681 time, and refuse to build an executable program.
27682
27683 @item One or more orders exist, all incorrect
27684 One or more acceptable elaboration orders exist, and all of them
27685 generate an elaboration order problem. In this case, the binder
27686 can build an executable program, but @code{Program_Error} will be raised
27687 when the program is run.
27688
27689 @item Several orders exist, some right, some incorrect
27690 One or more acceptable elaboration orders exists, and some of them
27691 work, and some do not. The programmer has not controlled
27692 the order of elaboration, so the binder may or may not pick one of
27693 the correct orders, and the program may or may not raise an
27694 exception when it is run. This is the worst case, because it means
27695 that the program may fail when moved to another compiler, or even
27696 another version of the same compiler.
27697
27698 @item One or more orders exists, all correct
27699 One ore more acceptable elaboration orders exist, and all of them
27700 work. In this case the program runs successfully. This state of
27701 affairs can be guaranteed by following the rule we gave above, but
27702 may be true even if the rule is not followed.
27703 @end table
27704
27705 @noindent
27706 Note that one additional advantage of following our rules on the use
27707 of @code{Elaborate} and @code{Elaborate_All}
27708 is that the program continues to stay in the ideal (all orders OK) state
27709 even if maintenance
27710 changes some bodies of some units. Conversely, if a program that does
27711 not follow this rule happens to be safe at some point, this state of affairs
27712 may deteriorate silently as a result of maintenance changes.
27713
27714 You may have noticed that the above discussion did not mention
27715 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27716 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27717 code in the body makes calls to some other unit, so it is still necessary
27718 to use @code{Elaborate_All} on such units.
27719
27720 @node Controlling Elaboration in GNAT - Internal Calls
27721 @section Controlling Elaboration in GNAT - Internal Calls
27722
27723 @noindent
27724 In the case of internal calls, i.e., calls within a single package, the
27725 programmer has full control over the order of elaboration, and it is up
27726 to the programmer to elaborate declarations in an appropriate order. For
27727 example writing:
27728
27729 @smallexample @c ada
27730 @group
27731 @cartouche
27732 function One return Float;
27733
27734 Q : Float := One;
27735
27736 function One return Float is
27737 begin
27738 return 1.0;
27739 end One;
27740 @end cartouche
27741 @end group
27742 @end smallexample
27743
27744 @noindent
27745 will obviously raise @code{Program_Error} at run time, because function
27746 One will be called before its body is elaborated. In this case GNAT will
27747 generate a warning that the call will raise @code{Program_Error}:
27748
27749 @smallexample
27750 @group
27751 @cartouche
27752 1. procedure y is
27753 2. function One return Float;
27754 3.
27755 4. Q : Float := One;
27756 |
27757 >>> warning: cannot call "One" before body is elaborated
27758 >>> warning: Program_Error will be raised at run time
27759
27760 5.
27761 6. function One return Float is
27762 7. begin
27763 8. return 1.0;
27764 9. end One;
27765 10.
27766 11. begin
27767 12. null;
27768 13. end;
27769 @end cartouche
27770 @end group
27771 @end smallexample
27772
27773 @noindent
27774 Note that in this particular case, it is likely that the call is safe, because
27775 the function @code{One} does not access any global variables.
27776 Nevertheless in Ada, we do not want the validity of the check to depend on
27777 the contents of the body (think about the separate compilation case), so this
27778 is still wrong, as we discussed in the previous sections.
27779
27780 The error is easily corrected by rearranging the declarations so that the
27781 body of @code{One} appears before the declaration containing the call
27782 (note that in Ada 95 and Ada 2005,
27783 declarations can appear in any order, so there is no restriction that
27784 would prevent this reordering, and if we write:
27785
27786 @smallexample @c ada
27787 @group
27788 @cartouche
27789 function One return Float;
27790
27791 function One return Float is
27792 begin
27793 return 1.0;
27794 end One;
27795
27796 Q : Float := One;
27797 @end cartouche
27798 @end group
27799 @end smallexample
27800
27801 @noindent
27802 then all is well, no warning is generated, and no
27803 @code{Program_Error} exception
27804 will be raised.
27805 Things are more complicated when a chain of subprograms is executed:
27806
27807 @smallexample @c ada
27808 @group
27809 @cartouche
27810 function A return Integer;
27811 function B return Integer;
27812 function C return Integer;
27813
27814 function B return Integer is begin return A; end;
27815 function C return Integer is begin return B; end;
27816
27817 X : Integer := C;
27818
27819 function A return Integer is begin return 1; end;
27820 @end cartouche
27821 @end group
27822 @end smallexample
27823
27824 @noindent
27825 Now the call to @code{C}
27826 at elaboration time in the declaration of @code{X} is correct, because
27827 the body of @code{C} is already elaborated,
27828 and the call to @code{B} within the body of
27829 @code{C} is correct, but the call
27830 to @code{A} within the body of @code{B} is incorrect, because the body
27831 of @code{A} has not been elaborated, so @code{Program_Error}
27832 will be raised on the call to @code{A}.
27833 In this case GNAT will generate a
27834 warning that @code{Program_Error} may be
27835 raised at the point of the call. Let's look at the warning:
27836
27837 @smallexample
27838 @group
27839 @cartouche
27840 1. procedure x is
27841 2. function A return Integer;
27842 3. function B return Integer;
27843 4. function C return Integer;
27844 5.
27845 6. function B return Integer is begin return A; end;
27846 |
27847 >>> warning: call to "A" before body is elaborated may
27848 raise Program_Error
27849 >>> warning: "B" called at line 7
27850 >>> warning: "C" called at line 9
27851
27852 7. function C return Integer is begin return B; end;
27853 8.
27854 9. X : Integer := C;
27855 10.
27856 11. function A return Integer is begin return 1; end;
27857 12.
27858 13. begin
27859 14. null;
27860 15. end;
27861 @end cartouche
27862 @end group
27863 @end smallexample
27864
27865 @noindent
27866 Note that the message here says ``may raise'', instead of the direct case,
27867 where the message says ``will be raised''. That's because whether
27868 @code{A} is
27869 actually called depends in general on run-time flow of control.
27870 For example, if the body of @code{B} said
27871
27872 @smallexample @c ada
27873 @group
27874 @cartouche
27875 function B return Integer is
27876 begin
27877 if some-condition-depending-on-input-data then
27878 return A;
27879 else
27880 return 1;
27881 end if;
27882 end B;
27883 @end cartouche
27884 @end group
27885 @end smallexample
27886
27887 @noindent
27888 then we could not know until run time whether the incorrect call to A would
27889 actually occur, so @code{Program_Error} might
27890 or might not be raised. It is possible for a compiler to
27891 do a better job of analyzing bodies, to
27892 determine whether or not @code{Program_Error}
27893 might be raised, but it certainly
27894 couldn't do a perfect job (that would require solving the halting problem
27895 and is provably impossible), and because this is a warning anyway, it does
27896 not seem worth the effort to do the analysis. Cases in which it
27897 would be relevant are rare.
27898
27899 In practice, warnings of either of the forms given
27900 above will usually correspond to
27901 real errors, and should be examined carefully and eliminated.
27902 In the rare case where a warning is bogus, it can be suppressed by any of
27903 the following methods:
27904
27905 @itemize @bullet
27906 @item
27907 Compile with the @option{-gnatws} switch set
27908
27909 @item
27910 Suppress @code{Elaboration_Check} for the called subprogram
27911
27912 @item
27913 Use pragma @code{Warnings_Off} to turn warnings off for the call
27914 @end itemize
27915
27916 @noindent
27917 For the internal elaboration check case,
27918 GNAT by default generates the
27919 necessary run-time checks to ensure
27920 that @code{Program_Error} is raised if any
27921 call fails an elaboration check. Of course this can only happen if a
27922 warning has been issued as described above. The use of pragma
27923 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27924 some of these checks, meaning that it may be possible (but is not
27925 guaranteed) for a program to be able to call a subprogram whose body
27926 is not yet elaborated, without raising a @code{Program_Error} exception.
27927
27928 @node Controlling Elaboration in GNAT - External Calls
27929 @section Controlling Elaboration in GNAT - External Calls
27930
27931 @noindent
27932 The previous section discussed the case in which the execution of a
27933 particular thread of elaboration code occurred entirely within a
27934 single unit. This is the easy case to handle, because a programmer
27935 has direct and total control over the order of elaboration, and
27936 furthermore, checks need only be generated in cases which are rare
27937 and which the compiler can easily detect.
27938 The situation is more complex when separate compilation is taken into account.
27939 Consider the following:
27940
27941 @smallexample @c ada
27942 @cartouche
27943 @group
27944 package Math is
27945 function Sqrt (Arg : Float) return Float;
27946 end Math;
27947
27948 package body Math is
27949 function Sqrt (Arg : Float) return Float is
27950 begin
27951 @dots{}
27952 end Sqrt;
27953 end Math;
27954 @end group
27955 @group
27956 with Math;
27957 package Stuff is
27958 X : Float := Math.Sqrt (0.5);
27959 end Stuff;
27960
27961 with Stuff;
27962 procedure Main is
27963 begin
27964 @dots{}
27965 end Main;
27966 @end group
27967 @end cartouche
27968 @end smallexample
27969
27970 @noindent
27971 where @code{Main} is the main program. When this program is executed, the
27972 elaboration code must first be executed, and one of the jobs of the
27973 binder is to determine the order in which the units of a program are
27974 to be elaborated. In this case we have four units: the spec and body
27975 of @code{Math},
27976 the spec of @code{Stuff} and the body of @code{Main}).
27977 In what order should the four separate sections of elaboration code
27978 be executed?
27979
27980 There are some restrictions in the order of elaboration that the binder
27981 can choose. In particular, if unit U has a @code{with}
27982 for a package @code{X}, then you
27983 are assured that the spec of @code{X}
27984 is elaborated before U , but you are
27985 not assured that the body of @code{X}
27986 is elaborated before U.
27987 This means that in the above case, the binder is allowed to choose the
27988 order:
27989
27990 @smallexample
27991 spec of Math
27992 spec of Stuff
27993 body of Math
27994 body of Main
27995 @end smallexample
27996
27997 @noindent
27998 but that's not good, because now the call to @code{Math.Sqrt}
27999 that happens during
28000 the elaboration of the @code{Stuff}
28001 spec happens before the body of @code{Math.Sqrt} is
28002 elaborated, and hence causes @code{Program_Error} exception to be raised.
28003 At first glance, one might say that the binder is misbehaving, because
28004 obviously you want to elaborate the body of something you @code{with}
28005 first, but
28006 that is not a general rule that can be followed in all cases. Consider
28007
28008 @smallexample @c ada
28009 @group
28010 @cartouche
28011 package X is @dots{}
28012
28013 package Y is @dots{}
28014
28015 with X;
28016 package body Y is @dots{}
28017
28018 with Y;
28019 package body X is @dots{}
28020 @end cartouche
28021 @end group
28022 @end smallexample
28023
28024 @noindent
28025 This is a common arrangement, and, apart from the order of elaboration
28026 problems that might arise in connection with elaboration code, this works fine.
28027 A rule that says that you must first elaborate the body of anything you
28028 @code{with} cannot work in this case:
28029 the body of @code{X} @code{with}'s @code{Y},
28030 which means you would have to
28031 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28032 which means
28033 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28034 loop that cannot be broken.
28035
28036 It is true that the binder can in many cases guess an order of elaboration
28037 that is unlikely to cause a @code{Program_Error}
28038 exception to be raised, and it tries to do so (in the
28039 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28040 by default
28041 elaborate the body of @code{Math} right after its spec, so all will be well).
28042
28043 However, a program that blindly relies on the binder to be helpful can
28044 get into trouble, as we discussed in the previous sections, so
28045 GNAT
28046 provides a number of facilities for assisting the programmer in
28047 developing programs that are robust with respect to elaboration order.
28048
28049 @node Default Behavior in GNAT - Ensuring Safety
28050 @section Default Behavior in GNAT - Ensuring Safety
28051
28052 @noindent
28053 The default behavior in GNAT ensures elaboration safety. In its
28054 default mode GNAT implements the
28055 rule we previously described as the right approach. Let's restate it:
28056
28057 @itemize
28058 @item
28059 @emph{If a unit has elaboration code that can directly or indirectly make a
28060 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28061 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28062 does not have pragma @code{Pure} or
28063 @code{Preelaborate}, then the client should have an
28064 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28065
28066 @emph{In the case of instantiating a generic subprogram, it is always
28067 sufficient to have only an @code{Elaborate} pragma for the
28068 @code{with}'ed unit.}
28069 @end itemize
28070
28071 @noindent
28072 By following this rule a client is assured that calls and instantiations
28073 can be made without risk of an exception.
28074
28075 In this mode GNAT traces all calls that are potentially made from
28076 elaboration code, and puts in any missing implicit @code{Elaborate}
28077 and @code{Elaborate_All} pragmas.
28078 The advantage of this approach is that no elaboration problems
28079 are possible if the binder can find an elaboration order that is
28080 consistent with these implicit @code{Elaborate} and
28081 @code{Elaborate_All} pragmas. The
28082 disadvantage of this approach is that no such order may exist.
28083
28084 If the binder does not generate any diagnostics, then it means that it has
28085 found an elaboration order that is guaranteed to be safe. However, the binder
28086 may still be relying on implicitly generated @code{Elaborate} and
28087 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28088 guaranteed.
28089
28090 If it is important to guarantee portability, then the compilations should
28091 use the
28092 @option{-gnatwl}
28093 (warn on elaboration problems) switch. This will cause warning messages
28094 to be generated indicating the missing @code{Elaborate} and
28095 @code{Elaborate_All} pragmas.
28096 Consider the following source program:
28097
28098 @smallexample @c ada
28099 @group
28100 @cartouche
28101 with k;
28102 package j is
28103 m : integer := k.r;
28104 end;
28105 @end cartouche
28106 @end group
28107 @end smallexample
28108
28109 @noindent
28110 where it is clear that there
28111 should be a pragma @code{Elaborate_All}
28112 for unit @code{k}. An implicit pragma will be generated, and it is
28113 likely that the binder will be able to honor it. However, if you want
28114 to port this program to some other Ada compiler than GNAT.
28115 it is safer to include the pragma explicitly in the source. If this
28116 unit is compiled with the
28117 @option{-gnatwl}
28118 switch, then the compiler outputs a warning:
28119
28120 @smallexample
28121 @group
28122 @cartouche
28123 1. with k;
28124 2. package j is
28125 3. m : integer := k.r;
28126 |
28127 >>> warning: call to "r" may raise Program_Error
28128 >>> warning: missing pragma Elaborate_All for "k"
28129
28130 4. end;
28131 @end cartouche
28132 @end group
28133 @end smallexample
28134
28135 @noindent
28136 and these warnings can be used as a guide for supplying manually
28137 the missing pragmas. It is usually a bad idea to use this warning
28138 option during development. That's because it will warn you when
28139 you need to put in a pragma, but cannot warn you when it is time
28140 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28141 unnecessary dependencies and even false circularities.
28142
28143 This default mode is more restrictive than the Ada Reference
28144 Manual, and it is possible to construct programs which will compile
28145 using the dynamic model described there, but will run into a
28146 circularity using the safer static model we have described.
28147
28148 Of course any Ada compiler must be able to operate in a mode
28149 consistent with the requirements of the Ada Reference Manual,
28150 and in particular must have the capability of implementing the
28151 standard dynamic model of elaboration with run-time checks.
28152
28153 In GNAT, this standard mode can be achieved either by the use of
28154 the @option{-gnatE} switch on the compiler (@command{gcc} or
28155 @command{gnatmake}) command, or by the use of the configuration pragma:
28156
28157 @smallexample @c ada
28158 pragma Elaboration_Checks (RM);
28159 @end smallexample
28160
28161 @noindent
28162 Either approach will cause the unit affected to be compiled using the
28163 standard dynamic run-time elaboration checks described in the Ada
28164 Reference Manual. The static model is generally preferable, since it
28165 is clearly safer to rely on compile and link time checks rather than
28166 run-time checks. However, in the case of legacy code, it may be
28167 difficult to meet the requirements of the static model. This
28168 issue is further discussed in
28169 @ref{What to Do If the Default Elaboration Behavior Fails}.
28170
28171 Note that the static model provides a strict subset of the allowed
28172 behavior and programs of the Ada Reference Manual, so if you do
28173 adhere to the static model and no circularities exist,
28174 then you are assured that your program will
28175 work using the dynamic model, providing that you remove any
28176 pragma Elaborate statements from the source.
28177
28178 @node Treatment of Pragma Elaborate
28179 @section Treatment of Pragma Elaborate
28180 @cindex Pragma Elaborate
28181
28182 @noindent
28183 The use of @code{pragma Elaborate}
28184 should generally be avoided in Ada 95 and Ada 2005 programs,
28185 since there is no guarantee that transitive calls
28186 will be properly handled. Indeed at one point, this pragma was placed
28187 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28188
28189 Now that's a bit restrictive. In practice, the case in which
28190 @code{pragma Elaborate} is useful is when the caller knows that there
28191 are no transitive calls, or that the called unit contains all necessary
28192 transitive @code{pragma Elaborate} statements, and legacy code often
28193 contains such uses.
28194
28195 Strictly speaking the static mode in GNAT should ignore such pragmas,
28196 since there is no assurance at compile time that the necessary safety
28197 conditions are met. In practice, this would cause GNAT to be incompatible
28198 with correctly written Ada 83 code that had all necessary
28199 @code{pragma Elaborate} statements in place. Consequently, we made the
28200 decision that GNAT in its default mode will believe that if it encounters
28201 a @code{pragma Elaborate} then the programmer knows what they are doing,
28202 and it will trust that no elaboration errors can occur.
28203
28204 The result of this decision is two-fold. First to be safe using the
28205 static mode, you should remove all @code{pragma Elaborate} statements.
28206 Second, when fixing circularities in existing code, you can selectively
28207 use @code{pragma Elaborate} statements to convince the static mode of
28208 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28209 statement.
28210
28211 When using the static mode with @option{-gnatwl}, any use of
28212 @code{pragma Elaborate} will generate a warning about possible
28213 problems.
28214
28215 @node Elaboration Issues for Library Tasks
28216 @section Elaboration Issues for Library Tasks
28217 @cindex Library tasks, elaboration issues
28218 @cindex Elaboration of library tasks
28219
28220 @noindent
28221 In this section we examine special elaboration issues that arise for
28222 programs that declare library level tasks.
28223
28224 Generally the model of execution of an Ada program is that all units are
28225 elaborated, and then execution of the program starts. However, the
28226 declaration of library tasks definitely does not fit this model. The
28227 reason for this is that library tasks start as soon as they are declared
28228 (more precisely, as soon as the statement part of the enclosing package
28229 body is reached), that is to say before elaboration
28230 of the program is complete. This means that if such a task calls a
28231 subprogram, or an entry in another task, the callee may or may not be
28232 elaborated yet, and in the standard
28233 Reference Manual model of dynamic elaboration checks, you can even
28234 get timing dependent Program_Error exceptions, since there can be
28235 a race between the elaboration code and the task code.
28236
28237 The static model of elaboration in GNAT seeks to avoid all such
28238 dynamic behavior, by being conservative, and the conservative
28239 approach in this particular case is to assume that all the code
28240 in a task body is potentially executed at elaboration time if
28241 a task is declared at the library level.
28242
28243 This can definitely result in unexpected circularities. Consider
28244 the following example
28245
28246 @smallexample @c ada
28247 package Decls is
28248 task Lib_Task is
28249 entry Start;
28250 end Lib_Task;
28251
28252 type My_Int is new Integer;
28253
28254 function Ident (M : My_Int) return My_Int;
28255 end Decls;
28256
28257 with Utils;
28258 package body Decls is
28259 task body Lib_Task is
28260 begin
28261 accept Start;
28262 Utils.Put_Val (2);
28263 end Lib_Task;
28264
28265 function Ident (M : My_Int) return My_Int is
28266 begin
28267 return M;
28268 end Ident;
28269 end Decls;
28270
28271 with Decls;
28272 package Utils is
28273 procedure Put_Val (Arg : Decls.My_Int);
28274 end Utils;
28275
28276 with Text_IO;
28277 package body Utils is
28278 procedure Put_Val (Arg : Decls.My_Int) is
28279 begin
28280 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28281 end Put_Val;
28282 end Utils;
28283
28284 with Decls;
28285 procedure Main is
28286 begin
28287 Decls.Lib_Task.Start;
28288 end;
28289 @end smallexample
28290
28291 @noindent
28292 If the above example is compiled in the default static elaboration
28293 mode, then a circularity occurs. The circularity comes from the call
28294 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28295 this call occurs in elaboration code, we need an implicit pragma
28296 @code{Elaborate_All} for @code{Utils}. This means that not only must
28297 the spec and body of @code{Utils} be elaborated before the body
28298 of @code{Decls}, but also the spec and body of any unit that is
28299 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28300 the body of @code{Decls}. This is the transitive implication of
28301 pragma @code{Elaborate_All} and it makes sense, because in general
28302 the body of @code{Put_Val} might have a call to something in a
28303 @code{with'ed} unit.
28304
28305 In this case, the body of Utils (actually its spec) @code{with's}
28306 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28307 must be elaborated before itself, in case there is a call from the
28308 body of @code{Utils}.
28309
28310 Here is the exact chain of events we are worrying about:
28311
28312 @enumerate
28313 @item
28314 In the body of @code{Decls} a call is made from within the body of a library
28315 task to a subprogram in the package @code{Utils}. Since this call may
28316 occur at elaboration time (given that the task is activated at elaboration
28317 time), we have to assume the worst, i.e., that the
28318 call does happen at elaboration time.
28319
28320 @item
28321 This means that the body and spec of @code{Util} must be elaborated before
28322 the body of @code{Decls} so that this call does not cause an access before
28323 elaboration.
28324
28325 @item
28326 Within the body of @code{Util}, specifically within the body of
28327 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28328 by this package.
28329
28330 @item
28331 One such @code{with}'ed package is package @code{Decls}, so there
28332 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28333 In fact there is such a call in this example, but we would have to
28334 assume that there was such a call even if it were not there, since
28335 we are not supposed to write the body of @code{Decls} knowing what
28336 is in the body of @code{Utils}; certainly in the case of the
28337 static elaboration model, the compiler does not know what is in
28338 other bodies and must assume the worst.
28339
28340 @item
28341 This means that the spec and body of @code{Decls} must also be
28342 elaborated before we elaborate the unit containing the call, but
28343 that unit is @code{Decls}! This means that the body of @code{Decls}
28344 must be elaborated before itself, and that's a circularity.
28345 @end enumerate
28346
28347 @noindent
28348 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28349 the body of @code{Decls} you will get a true Ada Reference Manual
28350 circularity that makes the program illegal.
28351
28352 In practice, we have found that problems with the static model of
28353 elaboration in existing code often arise from library tasks, so
28354 we must address this particular situation.
28355
28356 Note that if we compile and run the program above, using the dynamic model of
28357 elaboration (that is to say use the @option{-gnatE} switch),
28358 then it compiles, binds,
28359 links, and runs, printing the expected result of 2. Therefore in some sense
28360 the circularity here is only apparent, and we need to capture
28361 the properties of this program that distinguish it from other library-level
28362 tasks that have real elaboration problems.
28363
28364 We have four possible answers to this question:
28365
28366 @itemize @bullet
28367
28368 @item
28369 Use the dynamic model of elaboration.
28370
28371 If we use the @option{-gnatE} switch, then as noted above, the program works.
28372 Why is this? If we examine the task body, it is apparent that the task cannot
28373 proceed past the
28374 @code{accept} statement until after elaboration has been completed, because
28375 the corresponding entry call comes from the main program, not earlier.
28376 This is why the dynamic model works here. But that's really giving
28377 up on a precise analysis, and we prefer to take this approach only if we cannot
28378 solve the
28379 problem in any other manner. So let us examine two ways to reorganize
28380 the program to avoid the potential elaboration problem.
28381
28382 @item
28383 Split library tasks into separate packages.
28384
28385 Write separate packages, so that library tasks are isolated from
28386 other declarations as much as possible. Let us look at a variation on
28387 the above program.
28388
28389 @smallexample @c ada
28390 package Decls1 is
28391 task Lib_Task is
28392 entry Start;
28393 end Lib_Task;
28394 end Decls1;
28395
28396 with Utils;
28397 package body Decls1 is
28398 task body Lib_Task is
28399 begin
28400 accept Start;
28401 Utils.Put_Val (2);
28402 end Lib_Task;
28403 end Decls1;
28404
28405 package Decls2 is
28406 type My_Int is new Integer;
28407 function Ident (M : My_Int) return My_Int;
28408 end Decls2;
28409
28410 with Utils;
28411 package body Decls2 is
28412 function Ident (M : My_Int) return My_Int is
28413 begin
28414 return M;
28415 end Ident;
28416 end Decls2;
28417
28418 with Decls2;
28419 package Utils is
28420 procedure Put_Val (Arg : Decls2.My_Int);
28421 end Utils;
28422
28423 with Text_IO;
28424 package body Utils is
28425 procedure Put_Val (Arg : Decls2.My_Int) is
28426 begin
28427 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28428 end Put_Val;
28429 end Utils;
28430
28431 with Decls1;
28432 procedure Main is
28433 begin
28434 Decls1.Lib_Task.Start;
28435 end;
28436 @end smallexample
28437
28438 @noindent
28439 All we have done is to split @code{Decls} into two packages, one
28440 containing the library task, and one containing everything else. Now
28441 there is no cycle, and the program compiles, binds, links and executes
28442 using the default static model of elaboration.
28443
28444 @item
28445 Declare separate task types.
28446
28447 A significant part of the problem arises because of the use of the
28448 single task declaration form. This means that the elaboration of
28449 the task type, and the elaboration of the task itself (i.e.@: the
28450 creation of the task) happen at the same time. A good rule
28451 of style in Ada is to always create explicit task types. By
28452 following the additional step of placing task objects in separate
28453 packages from the task type declaration, many elaboration problems
28454 are avoided. Here is another modified example of the example program:
28455
28456 @smallexample @c ada
28457 package Decls is
28458 task type Lib_Task_Type is
28459 entry Start;
28460 end Lib_Task_Type;
28461
28462 type My_Int is new Integer;
28463
28464 function Ident (M : My_Int) return My_Int;
28465 end Decls;
28466
28467 with Utils;
28468 package body Decls is
28469 task body Lib_Task_Type is
28470 begin
28471 accept Start;
28472 Utils.Put_Val (2);
28473 end Lib_Task_Type;
28474
28475 function Ident (M : My_Int) return My_Int is
28476 begin
28477 return M;
28478 end Ident;
28479 end Decls;
28480
28481 with Decls;
28482 package Utils is
28483 procedure Put_Val (Arg : Decls.My_Int);
28484 end Utils;
28485
28486 with Text_IO;
28487 package body Utils is
28488 procedure Put_Val (Arg : Decls.My_Int) is
28489 begin
28490 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28491 end Put_Val;
28492 end Utils;
28493
28494 with Decls;
28495 package Declst is
28496 Lib_Task : Decls.Lib_Task_Type;
28497 end Declst;
28498
28499 with Declst;
28500 procedure Main is
28501 begin
28502 Declst.Lib_Task.Start;
28503 end;
28504 @end smallexample
28505
28506 @noindent
28507 What we have done here is to replace the @code{task} declaration in
28508 package @code{Decls} with a @code{task type} declaration. Then we
28509 introduce a separate package @code{Declst} to contain the actual
28510 task object. This separates the elaboration issues for
28511 the @code{task type}
28512 declaration, which causes no trouble, from the elaboration issues
28513 of the task object, which is also unproblematic, since it is now independent
28514 of the elaboration of @code{Utils}.
28515 This separation of concerns also corresponds to
28516 a generally sound engineering principle of separating declarations
28517 from instances. This version of the program also compiles, binds, links,
28518 and executes, generating the expected output.
28519
28520 @item
28521 Use No_Entry_Calls_In_Elaboration_Code restriction.
28522 @cindex No_Entry_Calls_In_Elaboration_Code
28523
28524 The previous two approaches described how a program can be restructured
28525 to avoid the special problems caused by library task bodies. in practice,
28526 however, such restructuring may be difficult to apply to existing legacy code,
28527 so we must consider solutions that do not require massive rewriting.
28528
28529 Let us consider more carefully why our original sample program works
28530 under the dynamic model of elaboration. The reason is that the code
28531 in the task body blocks immediately on the @code{accept}
28532 statement. Now of course there is nothing to prohibit elaboration
28533 code from making entry calls (for example from another library level task),
28534 so we cannot tell in isolation that
28535 the task will not execute the accept statement during elaboration.
28536
28537 However, in practice it is very unusual to see elaboration code
28538 make any entry calls, and the pattern of tasks starting
28539 at elaboration time and then immediately blocking on @code{accept} or
28540 @code{select} statements is very common. What this means is that
28541 the compiler is being too pessimistic when it analyzes the
28542 whole package body as though it might be executed at elaboration
28543 time.
28544
28545 If we know that the elaboration code contains no entry calls, (a very safe
28546 assumption most of the time, that could almost be made the default
28547 behavior), then we can compile all units of the program under control
28548 of the following configuration pragma:
28549
28550 @smallexample
28551 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28552 @end smallexample
28553
28554 @noindent
28555 This pragma can be placed in the @file{gnat.adc} file in the usual
28556 manner. If we take our original unmodified program and compile it
28557 in the presence of a @file{gnat.adc} containing the above pragma,
28558 then once again, we can compile, bind, link, and execute, obtaining
28559 the expected result. In the presence of this pragma, the compiler does
28560 not trace calls in a task body, that appear after the first @code{accept}
28561 or @code{select} statement, and therefore does not report a potential
28562 circularity in the original program.
28563
28564 The compiler will check to the extent it can that the above
28565 restriction is not violated, but it is not always possible to do a
28566 complete check at compile time, so it is important to use this
28567 pragma only if the stated restriction is in fact met, that is to say
28568 no task receives an entry call before elaboration of all units is completed.
28569
28570 @end itemize
28571
28572 @node Mixing Elaboration Models
28573 @section Mixing Elaboration Models
28574 @noindent
28575 So far, we have assumed that the entire program is either compiled
28576 using the dynamic model or static model, ensuring consistency. It
28577 is possible to mix the two models, but rules have to be followed
28578 if this mixing is done to ensure that elaboration checks are not
28579 omitted.
28580
28581 The basic rule is that @emph{a unit compiled with the static model cannot
28582 be @code{with'ed} by a unit compiled with the dynamic model}. The
28583 reason for this is that in the static model, a unit assumes that
28584 its clients guarantee to use (the equivalent of) pragma
28585 @code{Elaborate_All} so that no elaboration checks are required
28586 in inner subprograms, and this assumption is violated if the
28587 client is compiled with dynamic checks.
28588
28589 The precise rule is as follows. A unit that is compiled with dynamic
28590 checks can only @code{with} a unit that meets at least one of the
28591 following criteria:
28592
28593 @itemize @bullet
28594
28595 @item
28596 The @code{with'ed} unit is itself compiled with dynamic elaboration
28597 checks (that is with the @option{-gnatE} switch.
28598
28599 @item
28600 The @code{with'ed} unit is an internal GNAT implementation unit from
28601 the System, Interfaces, Ada, or GNAT hierarchies.
28602
28603 @item
28604 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28605
28606 @item
28607 The @code{with'ing} unit (that is the client) has an explicit pragma
28608 @code{Elaborate_All} for the @code{with'ed} unit.
28609
28610 @end itemize
28611
28612 @noindent
28613 If this rule is violated, that is if a unit with dynamic elaboration
28614 checks @code{with's} a unit that does not meet one of the above four
28615 criteria, then the binder (@code{gnatbind}) will issue a warning
28616 similar to that in the following example:
28617
28618 @smallexample
28619 warning: "x.ads" has dynamic elaboration checks and with's
28620 warning: "y.ads" which has static elaboration checks
28621 @end smallexample
28622
28623 @noindent
28624 These warnings indicate that the rule has been violated, and that as a result
28625 elaboration checks may be missed in the resulting executable file.
28626 This warning may be suppressed using the @option{-ws} binder switch
28627 in the usual manner.
28628
28629 One useful application of this mixing rule is in the case of a subsystem
28630 which does not itself @code{with} units from the remainder of the
28631 application. In this case, the entire subsystem can be compiled with
28632 dynamic checks to resolve a circularity in the subsystem, while
28633 allowing the main application that uses this subsystem to be compiled
28634 using the more reliable default static model.
28635
28636 @node What to Do If the Default Elaboration Behavior Fails
28637 @section What to Do If the Default Elaboration Behavior Fails
28638
28639 @noindent
28640 If the binder cannot find an acceptable order, it outputs detailed
28641 diagnostics. For example:
28642 @smallexample
28643 @group
28644 @iftex
28645 @leftskip=0cm
28646 @end iftex
28647 error: elaboration circularity detected
28648 info: "proc (body)" must be elaborated before "pack (body)"
28649 info: reason: Elaborate_All probably needed in unit "pack (body)"
28650 info: recompile "pack (body)" with -gnatwl
28651 info: for full details
28652 info: "proc (body)"
28653 info: is needed by its spec:
28654 info: "proc (spec)"
28655 info: which is withed by:
28656 info: "pack (body)"
28657 info: "pack (body)" must be elaborated before "proc (body)"
28658 info: reason: pragma Elaborate in unit "proc (body)"
28659 @end group
28660
28661 @end smallexample
28662
28663 @noindent
28664 In this case we have a cycle that the binder cannot break. On the one
28665 hand, there is an explicit pragma Elaborate in @code{proc} for
28666 @code{pack}. This means that the body of @code{pack} must be elaborated
28667 before the body of @code{proc}. On the other hand, there is elaboration
28668 code in @code{pack} that calls a subprogram in @code{proc}. This means
28669 that for maximum safety, there should really be a pragma
28670 Elaborate_All in @code{pack} for @code{proc} which would require that
28671 the body of @code{proc} be elaborated before the body of
28672 @code{pack}. Clearly both requirements cannot be satisfied.
28673 Faced with a circularity of this kind, you have three different options.
28674
28675 @table @asis
28676 @item Fix the program
28677 The most desirable option from the point of view of long-term maintenance
28678 is to rearrange the program so that the elaboration problems are avoided.
28679 One useful technique is to place the elaboration code into separate
28680 child packages. Another is to move some of the initialization code to
28681 explicitly called subprograms, where the program controls the order
28682 of initialization explicitly. Although this is the most desirable option,
28683 it may be impractical and involve too much modification, especially in
28684 the case of complex legacy code.
28685
28686 @item Perform dynamic checks
28687 If the compilations are done using the
28688 @option{-gnatE}
28689 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28690 manner. Dynamic checks are generated for all calls that could possibly result
28691 in raising an exception. With this switch, the compiler does not generate
28692 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28693 exactly as specified in the @cite{Ada Reference Manual}.
28694 The binder will generate
28695 an executable program that may or may not raise @code{Program_Error}, and then
28696 it is the programmer's job to ensure that it does not raise an exception. Note
28697 that it is important to compile all units with the switch, it cannot be used
28698 selectively.
28699
28700 @item Suppress checks
28701 The drawback of dynamic checks is that they generate a
28702 significant overhead at run time, both in space and time. If you
28703 are absolutely sure that your program cannot raise any elaboration
28704 exceptions, and you still want to use the dynamic elaboration model,
28705 then you can use the configuration pragma
28706 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28707 example this pragma could be placed in the @file{gnat.adc} file.
28708
28709 @item Suppress checks selectively
28710 When you know that certain calls or instantiations in elaboration code cannot
28711 possibly lead to an elaboration error, and the binder nevertheless complains
28712 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28713 elaboration circularities, it is possible to remove those warnings locally and
28714 obtain a program that will bind. Clearly this can be unsafe, and it is the
28715 responsibility of the programmer to make sure that the resulting program has no
28716 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28717 used with different granularity to suppress warnings and break elaboration
28718 circularities:
28719
28720 @itemize @bullet
28721 @item
28722 Place the pragma that names the called subprogram in the declarative part
28723 that contains the call.
28724
28725 @item
28726 Place the pragma in the declarative part, without naming an entity. This
28727 disables warnings on all calls in the corresponding declarative region.
28728
28729 @item
28730 Place the pragma in the package spec that declares the called subprogram,
28731 and name the subprogram. This disables warnings on all elaboration calls to
28732 that subprogram.
28733
28734 @item
28735 Place the pragma in the package spec that declares the called subprogram,
28736 without naming any entity. This disables warnings on all elaboration calls to
28737 all subprograms declared in this spec.
28738
28739 @item Use Pragma Elaborate
28740 As previously described in section @xref{Treatment of Pragma Elaborate},
28741 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28742 that no elaboration checks are required on calls to the designated unit.
28743 There may be cases in which the caller knows that no transitive calls
28744 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28745 case where @code{pragma Elaborate_All} would cause a circularity.
28746 @end itemize
28747
28748 @noindent
28749 These five cases are listed in order of decreasing safety, and therefore
28750 require increasing programmer care in their application. Consider the
28751 following program:
28752
28753 @smallexample @c adanocomment
28754 package Pack1 is
28755 function F1 return Integer;
28756 X1 : Integer;
28757 end Pack1;
28758
28759 package Pack2 is
28760 function F2 return Integer;
28761 function Pure (x : integer) return integer;
28762 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
28763 -- pragma Suppress (Elaboration_Check); -- (4)
28764 end Pack2;
28765
28766 with Pack2;
28767 package body Pack1 is
28768 function F1 return Integer is
28769 begin
28770 return 100;
28771 end F1;
28772 Val : integer := Pack2.Pure (11); -- Elab. call (1)
28773 begin
28774 declare
28775 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
28776 -- pragma Suppress(Elaboration_Check); -- (2)
28777 begin
28778 X1 := Pack2.F2 + 1; -- Elab. call (2)
28779 end;
28780 end Pack1;
28781
28782 with Pack1;
28783 package body Pack2 is
28784 function F2 return Integer is
28785 begin
28786 return Pack1.F1;
28787 end F2;
28788 function Pure (x : integer) return integer is
28789 begin
28790 return x ** 3 - 3 * x;
28791 end;
28792 end Pack2;
28793
28794 with Pack1, Ada.Text_IO;
28795 procedure Proc3 is
28796 begin
28797 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28798 end Proc3;
28799 @end smallexample
28800 In the absence of any pragmas, an attempt to bind this program produces
28801 the following diagnostics:
28802 @smallexample
28803 @group
28804 @iftex
28805 @leftskip=.5cm
28806 @end iftex
28807 error: elaboration circularity detected
28808 info: "pack1 (body)" must be elaborated before "pack1 (body)"
28809 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
28810 info: recompile "pack1 (body)" with -gnatwl for full details
28811 info: "pack1 (body)"
28812 info: must be elaborated along with its spec:
28813 info: "pack1 (spec)"
28814 info: which is withed by:
28815 info: "pack2 (body)"
28816 info: which must be elaborated along with its spec:
28817 info: "pack2 (spec)"
28818 info: which is withed by:
28819 info: "pack1 (body)"
28820 @end group
28821 @end smallexample
28822 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28823 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28824 F2 is safe, even though F2 calls F1, because the call appears after the
28825 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28826 remove the warning on the call. It is also possible to use pragma (2)
28827 because there are no other potentially unsafe calls in the block.
28828
28829 @noindent
28830 The call to @code{Pure} is safe because this function does not depend on the
28831 state of @code{Pack2}. Therefore any call to this function is safe, and it
28832 is correct to place pragma (3) in the corresponding package spec.
28833
28834 @noindent
28835 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28836 warnings on all calls to functions declared therein. Note that this is not
28837 necessarily safe, and requires more detailed examination of the subprogram
28838 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28839 be already elaborated.
28840 @end table
28841
28842 @noindent
28843 It is hard to generalize on which of these four approaches should be
28844 taken. Obviously if it is possible to fix the program so that the default
28845 treatment works, this is preferable, but this may not always be practical.
28846 It is certainly simple enough to use
28847 @option{-gnatE}
28848 but the danger in this case is that, even if the GNAT binder
28849 finds a correct elaboration order, it may not always do so,
28850 and certainly a binder from another Ada compiler might not. A
28851 combination of testing and analysis (for which the warnings generated
28852 with the
28853 @option{-gnatwl}
28854 switch can be useful) must be used to ensure that the program is free
28855 of errors. One switch that is useful in this testing is the
28856 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28857 switch for
28858 @code{gnatbind}.
28859 Normally the binder tries to find an order that has the best chance
28860 of avoiding elaboration problems. However, if this switch is used, the binder
28861 plays a devil's advocate role, and tries to choose the order that
28862 has the best chance of failing. If your program works even with this
28863 switch, then it has a better chance of being error free, but this is still
28864 not a guarantee.
28865
28866 For an example of this approach in action, consider the C-tests (executable
28867 tests) from the ACVC suite. If these are compiled and run with the default
28868 treatment, then all but one of them succeed without generating any error
28869 diagnostics from the binder. However, there is one test that fails, and
28870 this is not surprising, because the whole point of this test is to ensure
28871 that the compiler can handle cases where it is impossible to determine
28872 a correct order statically, and it checks that an exception is indeed
28873 raised at run time.
28874
28875 This one test must be compiled and run using the
28876 @option{-gnatE}
28877 switch, and then it passes. Alternatively, the entire suite can
28878 be run using this switch. It is never wrong to run with the dynamic
28879 elaboration switch if your code is correct, and we assume that the
28880 C-tests are indeed correct (it is less efficient, but efficiency is
28881 not a factor in running the ACVC tests.)
28882
28883 @node Elaboration for Access-to-Subprogram Values
28884 @section Elaboration for Access-to-Subprogram Values
28885 @cindex Access-to-subprogram
28886
28887 @noindent
28888 Access-to-subprogram types (introduced in Ada 95) complicate
28889 the handling of elaboration. The trouble is that it becomes
28890 impossible to tell at compile time which procedure
28891 is being called. This means that it is not possible for the binder
28892 to analyze the elaboration requirements in this case.
28893
28894 If at the point at which the access value is created
28895 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28896 the body of the subprogram is
28897 known to have been elaborated, then the access value is safe, and its use
28898 does not require a check. This may be achieved by appropriate arrangement
28899 of the order of declarations if the subprogram is in the current unit,
28900 or, if the subprogram is in another unit, by using pragma
28901 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28902 on the referenced unit.
28903
28904 If the referenced body is not known to have been elaborated at the point
28905 the access value is created, then any use of the access value must do a
28906 dynamic check, and this dynamic check will fail and raise a
28907 @code{Program_Error} exception if the body has not been elaborated yet.
28908 GNAT will generate the necessary checks, and in addition, if the
28909 @option{-gnatwl}
28910 switch is set, will generate warnings that such checks are required.
28911
28912 The use of dynamic dispatching for tagged types similarly generates
28913 a requirement for dynamic checks, and premature calls to any primitive
28914 operation of a tagged type before the body of the operation has been
28915 elaborated, will result in the raising of @code{Program_Error}.
28916
28917 @node Summary of Procedures for Elaboration Control
28918 @section Summary of Procedures for Elaboration Control
28919 @cindex Elaboration control
28920
28921 @noindent
28922 First, compile your program with the default options, using none of
28923 the special elaboration control switches. If the binder successfully
28924 binds your program, then you can be confident that, apart from issues
28925 raised by the use of access-to-subprogram types and dynamic dispatching,
28926 the program is free of elaboration errors. If it is important that the
28927 program be portable, then use the
28928 @option{-gnatwl}
28929 switch to generate warnings about missing @code{Elaborate} or
28930 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28931
28932 If the program fails to bind using the default static elaboration
28933 handling, then you can fix the program to eliminate the binder
28934 message, or recompile the entire program with the
28935 @option{-gnatE} switch to generate dynamic elaboration checks,
28936 and, if you are sure there really are no elaboration problems,
28937 use a global pragma @code{Suppress (Elaboration_Check)}.
28938
28939 @node Other Elaboration Order Considerations
28940 @section Other Elaboration Order Considerations
28941 @noindent
28942 This section has been entirely concerned with the issue of finding a valid
28943 elaboration order, as defined by the Ada Reference Manual. In a case
28944 where several elaboration orders are valid, the task is to find one
28945 of the possible valid elaboration orders (and the static model in GNAT
28946 will ensure that this is achieved).
28947
28948 The purpose of the elaboration rules in the Ada Reference Manual is to
28949 make sure that no entity is accessed before it has been elaborated. For
28950 a subprogram, this means that the spec and body must have been elaborated
28951 before the subprogram is called. For an object, this means that the object
28952 must have been elaborated before its value is read or written. A violation
28953 of either of these two requirements is an access before elaboration order,
28954 and this section has been all about avoiding such errors.
28955
28956 In the case where more than one order of elaboration is possible, in the
28957 sense that access before elaboration errors are avoided, then any one of
28958 the orders is ``correct'' in the sense that it meets the requirements of
28959 the Ada Reference Manual, and no such error occurs.
28960
28961 However, it may be the case for a given program, that there are
28962 constraints on the order of elaboration that come not from consideration
28963 of avoiding elaboration errors, but rather from extra-lingual logic
28964 requirements. Consider this example:
28965
28966 @smallexample @c ada
28967 with Init_Constants;
28968 package Constants is
28969 X : Integer := 0;
28970 Y : Integer := 0;
28971 end Constants;
28972
28973 package Init_Constants is
28974 procedure P; -- require a body
28975 end Init_Constants;
28976
28977 with Constants;
28978 package body Init_Constants is
28979 procedure P is begin null; end;
28980 begin
28981 Constants.X := 3;
28982 Constants.Y := 4;
28983 end Init_Constants;
28984
28985 with Constants;
28986 package Calc is
28987 Z : Integer := Constants.X + Constants.Y;
28988 end Calc;
28989
28990 with Calc;
28991 with Text_IO; use Text_IO;
28992 procedure Main is
28993 begin
28994 Put_Line (Calc.Z'Img);
28995 end Main;
28996 @end smallexample
28997
28998 @noindent
28999 In this example, there is more than one valid order of elaboration. For
29000 example both the following are correct orders:
29001
29002 @smallexample
29003 Init_Constants spec
29004 Constants spec
29005 Calc spec
29006 Init_Constants body
29007 Main body
29008
29009 and
29010
29011 Init_Constants spec
29012 Init_Constants body
29013 Constants spec
29014 Calc spec
29015 Main body
29016 @end smallexample
29017
29018 @noindent
29019 There is no language rule to prefer one or the other, both are correct
29020 from an order of elaboration point of view. But the programmatic effects
29021 of the two orders are very different. In the first, the elaboration routine
29022 of @code{Calc} initializes @code{Z} to zero, and then the main program
29023 runs with this value of zero. But in the second order, the elaboration
29024 routine of @code{Calc} runs after the body of Init_Constants has set
29025 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29026 runs.
29027
29028 One could perhaps by applying pretty clever non-artificial intelligence
29029 to the situation guess that it is more likely that the second order of
29030 elaboration is the one desired, but there is no formal linguistic reason
29031 to prefer one over the other. In fact in this particular case, GNAT will
29032 prefer the second order, because of the rule that bodies are elaborated
29033 as soon as possible, but it's just luck that this is what was wanted
29034 (if indeed the second order was preferred).
29035
29036 If the program cares about the order of elaboration routines in a case like
29037 this, it is important to specify the order required. In this particular
29038 case, that could have been achieved by adding to the spec of Calc:
29039
29040 @smallexample @c ada
29041 pragma Elaborate_All (Constants);
29042 @end smallexample
29043
29044 @noindent
29045 which requires that the body (if any) and spec of @code{Constants},
29046 as well as the body and spec of any unit @code{with}'ed by
29047 @code{Constants} be elaborated before @code{Calc} is elaborated.
29048
29049 Clearly no automatic method can always guess which alternative you require,
29050 and if you are working with legacy code that had constraints of this kind
29051 which were not properly specified by adding @code{Elaborate} or
29052 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29053 compilers can choose different orders.
29054
29055 However, GNAT does attempt to diagnose the common situation where there
29056 are uninitialized variables in the visible part of a package spec, and the
29057 corresponding package body has an elaboration block that directly or
29058 indirectly initialized one or more of these variables. This is the situation
29059 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29060 a warning that suggests this addition if it detects this situation.
29061
29062 The @code{gnatbind}
29063 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29064 out problems. This switch causes bodies to be elaborated as late as possible
29065 instead of as early as possible. In the example above, it would have forced
29066 the choice of the first elaboration order. If you get different results
29067 when using this switch, and particularly if one set of results is right,
29068 and one is wrong as far as you are concerned, it shows that you have some
29069 missing @code{Elaborate} pragmas. For the example above, we have the
29070 following output:
29071
29072 @smallexample
29073 gnatmake -f -q main
29074 main
29075 7
29076 gnatmake -f -q main -bargs -p
29077 main
29078 0
29079 @end smallexample
29080
29081 @noindent
29082 It is of course quite unlikely that both these results are correct, so
29083 it is up to you in a case like this to investigate the source of the
29084 difference, by looking at the two elaboration orders that are chosen,
29085 and figuring out which is correct, and then adding the necessary
29086 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29087
29088
29089
29090 @c *******************************
29091 @node Conditional Compilation
29092 @appendix Conditional Compilation
29093 @c *******************************
29094 @cindex Conditional compilation
29095
29096 @noindent
29097 It is often necessary to arrange for a single source program
29098 to serve multiple purposes, where it is compiled in different
29099 ways to achieve these different goals. Some examples of the
29100 need for this feature are
29101
29102 @itemize @bullet
29103 @item Adapting a program to a different hardware environment
29104 @item Adapting a program to a different target architecture
29105 @item Turning debugging features on and off
29106 @item Arranging for a program to compile with different compilers
29107 @end itemize
29108
29109 @noindent
29110 In C, or C++, the typical approach would be to use the preprocessor
29111 that is defined as part of the language. The Ada language does not
29112 contain such a feature. This is not an oversight, but rather a very
29113 deliberate design decision, based on the experience that overuse of
29114 the preprocessing features in C and C++ can result in programs that
29115 are extremely difficult to maintain. For example, if we have ten
29116 switches that can be on or off, this means that there are a thousand
29117 separate programs, any one of which might not even be syntactically
29118 correct, and even if syntactically correct, the resulting program
29119 might not work correctly. Testing all combinations can quickly become
29120 impossible.
29121
29122 Nevertheless, the need to tailor programs certainly exists, and in
29123 this Appendix we will discuss how this can
29124 be achieved using Ada in general, and GNAT in particular.
29125
29126 @menu
29127 * Use of Boolean Constants::
29128 * Debugging - A Special Case::
29129 * Conditionalizing Declarations::
29130 * Use of Alternative Implementations::
29131 * Preprocessing::
29132 @end menu
29133
29134 @node Use of Boolean Constants
29135 @section Use of Boolean Constants
29136
29137 @noindent
29138 In the case where the difference is simply which code
29139 sequence is executed, the cleanest solution is to use Boolean
29140 constants to control which code is executed.
29141
29142 @smallexample @c ada
29143 @group
29144 FP_Initialize_Required : constant Boolean := True;
29145 @dots{}
29146 if FP_Initialize_Required then
29147 @dots{}
29148 end if;
29149 @end group
29150 @end smallexample
29151
29152 @noindent
29153 Not only will the code inside the @code{if} statement not be executed if
29154 the constant Boolean is @code{False}, but it will also be completely
29155 deleted from the program.
29156 However, the code is only deleted after the @code{if} statement
29157 has been checked for syntactic and semantic correctness.
29158 (In contrast, with preprocessors the code is deleted before the
29159 compiler ever gets to see it, so it is not checked until the switch
29160 is turned on.)
29161 @cindex Preprocessors (contrasted with conditional compilation)
29162
29163 Typically the Boolean constants will be in a separate package,
29164 something like:
29165
29166 @smallexample @c ada
29167 @group
29168 package Config is
29169 FP_Initialize_Required : constant Boolean := True;
29170 Reset_Available : constant Boolean := False;
29171 @dots{}
29172 end Config;
29173 @end group
29174 @end smallexample
29175
29176 @noindent
29177 The @code{Config} package exists in multiple forms for the various targets,
29178 with an appropriate script selecting the version of @code{Config} needed.
29179 Then any other unit requiring conditional compilation can do a @code{with}
29180 of @code{Config} to make the constants visible.
29181
29182
29183 @node Debugging - A Special Case
29184 @section Debugging - A Special Case
29185
29186 @noindent
29187 A common use of conditional code is to execute statements (for example
29188 dynamic checks, or output of intermediate results) under control of a
29189 debug switch, so that the debugging behavior can be turned on and off.
29190 This can be done using a Boolean constant to control whether the code
29191 is active:
29192
29193 @smallexample @c ada
29194 @group
29195 if Debugging then
29196 Put_Line ("got to the first stage!");
29197 end if;
29198 @end group
29199 @end smallexample
29200
29201 @noindent
29202 or
29203
29204 @smallexample @c ada
29205 @group
29206 if Debugging and then Temperature > 999.0 then
29207 raise Temperature_Crazy;
29208 end if;
29209 @end group
29210 @end smallexample
29211
29212 @noindent
29213 Since this is a common case, there are special features to deal with
29214 this in a convenient manner. For the case of tests, Ada 2005 has added
29215 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29216 @cindex pragma @code{Assert}
29217 on the @code{Assert} pragma that has always been available in GNAT, so this
29218 feature may be used with GNAT even if you are not using Ada 2005 features.
29219 The use of pragma @code{Assert} is described in
29220 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29221 example, the last test could be written:
29222
29223 @smallexample @c ada
29224 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29225 @end smallexample
29226
29227 @noindent
29228 or simply
29229
29230 @smallexample @c ada
29231 pragma Assert (Temperature <= 999.0);
29232 @end smallexample
29233
29234 @noindent
29235 In both cases, if assertions are active and the temperature is excessive,
29236 the exception @code{Assert_Failure} will be raised, with the given string in
29237 the first case or a string indicating the location of the pragma in the second
29238 case used as the exception message.
29239
29240 You can turn assertions on and off by using the @code{Assertion_Policy}
29241 pragma.
29242 @cindex pragma @code{Assertion_Policy}
29243 This is an Ada 2005 pragma which is implemented in all modes by
29244 GNAT, but only in the latest versions of GNAT which include Ada 2005
29245 capability. Alternatively, you can use the @option{-gnata} switch
29246 @cindex @option{-gnata} switch
29247 to enable assertions from the command line (this is recognized by all versions
29248 of GNAT).
29249
29250 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29251 @code{Debug} can be used:
29252 @cindex pragma @code{Debug}
29253
29254 @smallexample @c ada
29255 pragma Debug (Put_Line ("got to the first stage!"));
29256 @end smallexample
29257
29258 @noindent
29259 If debug pragmas are enabled, the argument, which must be of the form of
29260 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29261 Only one call can be present, but of course a special debugging procedure
29262 containing any code you like can be included in the program and then
29263 called in a pragma @code{Debug} argument as needed.
29264
29265 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29266 construct is that pragma @code{Debug} can appear in declarative contexts,
29267 such as at the very beginning of a procedure, before local declarations have
29268 been elaborated.
29269
29270 Debug pragmas are enabled using either the @option{-gnata} switch that also
29271 controls assertions, or with a separate Debug_Policy pragma.
29272 @cindex pragma @code{Debug_Policy}
29273 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29274 in Ada 95 and Ada 83 programs as well), and is analogous to
29275 pragma @code{Assertion_Policy} to control assertions.
29276
29277 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29278 and thus they can appear in @file{gnat.adc} if you are not using a
29279 project file, or in the file designated to contain configuration pragmas
29280 in a project file.
29281 They then apply to all subsequent compilations. In practice the use of
29282 the @option{-gnata} switch is often the most convenient method of controlling
29283 the status of these pragmas.
29284
29285 Note that a pragma is not a statement, so in contexts where a statement
29286 sequence is required, you can't just write a pragma on its own. You have
29287 to add a @code{null} statement.
29288
29289 @smallexample @c ada
29290 @group
29291 if @dots{} then
29292 @dots{} -- some statements
29293 else
29294 pragma Assert (Num_Cases < 10);
29295 null;
29296 end if;
29297 @end group
29298 @end smallexample
29299
29300
29301 @node Conditionalizing Declarations
29302 @section Conditionalizing Declarations
29303
29304 @noindent
29305 In some cases, it may be necessary to conditionalize declarations to meet
29306 different requirements. For example we might want a bit string whose length
29307 is set to meet some hardware message requirement.
29308
29309 In some cases, it may be possible to do this using declare blocks controlled
29310 by conditional constants:
29311
29312 @smallexample @c ada
29313 @group
29314 if Small_Machine then
29315 declare
29316 X : Bit_String (1 .. 10);
29317 begin
29318 @dots{}
29319 end;
29320 else
29321 declare
29322 X : Large_Bit_String (1 .. 1000);
29323 begin
29324 @dots{}
29325 end;
29326 end if;
29327 @end group
29328 @end smallexample
29329
29330 @noindent
29331 Note that in this approach, both declarations are analyzed by the
29332 compiler so this can only be used where both declarations are legal,
29333 even though one of them will not be used.
29334
29335 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29336 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29337 that are parameterized by these constants. For example
29338
29339 @smallexample @c ada
29340 @group
29341 for Rec use
29342 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29343 end record;
29344 @end group
29345 @end smallexample
29346
29347 @noindent
29348 If @code{Bits_Per_Word} is set to 32, this generates either
29349
29350 @smallexample @c ada
29351 @group
29352 for Rec use
29353 Field1 at 0 range 0 .. 32;
29354 end record;
29355 @end group
29356 @end smallexample
29357
29358 @noindent
29359 for the big endian case, or
29360
29361 @smallexample @c ada
29362 @group
29363 for Rec use record
29364 Field1 at 0 range 10 .. 32;
29365 end record;
29366 @end group
29367 @end smallexample
29368
29369 @noindent
29370 for the little endian case. Since a powerful subset of Ada expression
29371 notation is usable for creating static constants, clever use of this
29372 feature can often solve quite difficult problems in conditionalizing
29373 compilation (note incidentally that in Ada 95, the little endian
29374 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29375 need to define this one yourself).
29376
29377
29378 @node Use of Alternative Implementations
29379 @section Use of Alternative Implementations
29380
29381 @noindent
29382 In some cases, none of the approaches described above are adequate. This
29383 can occur for example if the set of declarations required is radically
29384 different for two different configurations.
29385
29386 In this situation, the official Ada way of dealing with conditionalizing
29387 such code is to write separate units for the different cases. As long as
29388 this does not result in excessive duplication of code, this can be done
29389 without creating maintenance problems. The approach is to share common
29390 code as far as possible, and then isolate the code and declarations
29391 that are different. Subunits are often a convenient method for breaking
29392 out a piece of a unit that is to be conditionalized, with separate files
29393 for different versions of the subunit for different targets, where the
29394 build script selects the right one to give to the compiler.
29395 @cindex Subunits (and conditional compilation)
29396
29397 As an example, consider a situation where a new feature in Ada 2005
29398 allows something to be done in a really nice way. But your code must be able
29399 to compile with an Ada 95 compiler. Conceptually you want to say:
29400
29401 @smallexample @c ada
29402 @group
29403 if Ada_2005 then
29404 @dots{} neat Ada 2005 code
29405 else
29406 @dots{} not quite as neat Ada 95 code
29407 end if;
29408 @end group
29409 @end smallexample
29410
29411 @noindent
29412 where @code{Ada_2005} is a Boolean constant.
29413
29414 But this won't work when @code{Ada_2005} is set to @code{False},
29415 since the @code{then} clause will be illegal for an Ada 95 compiler.
29416 (Recall that although such unreachable code would eventually be deleted
29417 by the compiler, it still needs to be legal. If it uses features
29418 introduced in Ada 2005, it will be illegal in Ada 95.)
29419
29420 So instead we write
29421
29422 @smallexample @c ada
29423 procedure Insert is separate;
29424 @end smallexample
29425
29426 @noindent
29427 Then we have two files for the subunit @code{Insert}, with the two sets of
29428 code.
29429 If the package containing this is called @code{File_Queries}, then we might
29430 have two files
29431
29432 @itemize @bullet
29433 @item @file{file_queries-insert-2005.adb}
29434 @item @file{file_queries-insert-95.adb}
29435 @end itemize
29436
29437 @noindent
29438 and the build script renames the appropriate file to
29439
29440 @smallexample
29441 file_queries-insert.adb
29442 @end smallexample
29443
29444 @noindent
29445 and then carries out the compilation.
29446
29447 This can also be done with project files' naming schemes. For example:
29448
29449 @smallexample @c project
29450 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29451 @end smallexample
29452
29453 @noindent
29454 Note also that with project files it is desirable to use a different extension
29455 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29456 conflict may arise through another commonly used feature: to declare as part
29457 of the project a set of directories containing all the sources obeying the
29458 default naming scheme.
29459
29460 The use of alternative units is certainly feasible in all situations,
29461 and for example the Ada part of the GNAT run-time is conditionalized
29462 based on the target architecture using this approach. As a specific example,
29463 consider the implementation of the AST feature in VMS. There is one
29464 spec:
29465
29466 @smallexample
29467 s-asthan.ads
29468 @end smallexample
29469
29470 @noindent
29471 which is the same for all architectures, and three bodies:
29472
29473 @table @file
29474 @item s-asthan.adb
29475 used for all non-VMS operating systems
29476 @item s-asthan-vms-alpha.adb
29477 used for VMS on the Alpha
29478 @item s-asthan-vms-ia64.adb
29479 used for VMS on the ia64
29480 @end table
29481
29482 @noindent
29483 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29484 this operating system feature is not available, and the two remaining
29485 versions interface with the corresponding versions of VMS to provide
29486 VMS-compatible AST handling. The GNAT build script knows the architecture
29487 and operating system, and automatically selects the right version,
29488 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29489
29490 Another style for arranging alternative implementations is through Ada's
29491 access-to-subprogram facility.
29492 In case some functionality is to be conditionally included,
29493 you can declare an access-to-procedure variable @code{Ref} that is initialized
29494 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29495 when appropriate.
29496 In some library package, set @code{Ref} to @code{Proc'Access} for some
29497 procedure @code{Proc} that performs the relevant processing.
29498 The initialization only occurs if the library package is included in the
29499 program.
29500 The same idea can also be implemented using tagged types and dispatching
29501 calls.
29502
29503
29504 @node Preprocessing
29505 @section Preprocessing
29506 @cindex Preprocessing
29507
29508 @noindent
29509 Although it is quite possible to conditionalize code without the use of
29510 C-style preprocessing, as described earlier in this section, it is
29511 nevertheless convenient in some cases to use the C approach. Moreover,
29512 older Ada compilers have often provided some preprocessing capability,
29513 so legacy code may depend on this approach, even though it is not
29514 standard.
29515
29516 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29517 extent on the various preprocessors that have been used
29518 with legacy code on other compilers, to enable easier transition).
29519
29520 The preprocessor may be used in two separate modes. It can be used quite
29521 separately from the compiler, to generate a separate output source file
29522 that is then fed to the compiler as a separate step. This is the
29523 @code{gnatprep} utility, whose use is fully described in
29524 @ref{Preprocessing Using gnatprep}.
29525 @cindex @code{gnatprep}
29526
29527 The preprocessing language allows such constructs as
29528
29529 @smallexample
29530 @group
29531 #if DEBUG or PRIORITY > 4 then
29532 bunch of declarations
29533 #else
29534 completely different bunch of declarations
29535 #end if;
29536 @end group
29537 @end smallexample
29538
29539 @noindent
29540 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29541 defined either on the command line or in a separate file.
29542
29543 The other way of running the preprocessor is even closer to the C style and
29544 often more convenient. In this approach the preprocessing is integrated into
29545 the compilation process. The compiler is fed the preprocessor input which
29546 includes @code{#if} lines etc, and then the compiler carries out the
29547 preprocessing internally and processes the resulting output.
29548 For more details on this approach, see @ref{Integrated Preprocessing}.
29549
29550
29551 @c *******************************
29552 @node Inline Assembler
29553 @appendix Inline Assembler
29554 @c *******************************
29555
29556 @noindent
29557 If you need to write low-level software that interacts directly
29558 with the hardware, Ada provides two ways to incorporate assembly
29559 language code into your program. First, you can import and invoke
29560 external routines written in assembly language, an Ada feature fully
29561 supported by GNAT@. However, for small sections of code it may be simpler
29562 or more efficient to include assembly language statements directly
29563 in your Ada source program, using the facilities of the implementation-defined
29564 package @code{System.Machine_Code}, which incorporates the gcc
29565 Inline Assembler. The Inline Assembler approach offers a number of advantages,
29566 including the following:
29567
29568 @itemize @bullet
29569 @item No need to use non-Ada tools
29570 @item Consistent interface over different targets
29571 @item Automatic usage of the proper calling conventions
29572 @item Access to Ada constants and variables
29573 @item Definition of intrinsic routines
29574 @item Possibility of inlining a subprogram comprising assembler code
29575 @item Code optimizer can take Inline Assembler code into account
29576 @end itemize
29577
29578 This chapter presents a series of examples to show you how to use
29579 the Inline Assembler. Although it focuses on the Intel x86,
29580 the general approach applies also to other processors.
29581 It is assumed that you are familiar with Ada
29582 and with assembly language programming.
29583
29584 @menu
29585 * Basic Assembler Syntax::
29586 * A Simple Example of Inline Assembler::
29587 * Output Variables in Inline Assembler::
29588 * Input Variables in Inline Assembler::
29589 * Inlining Inline Assembler Code::
29590 * Other Asm Functionality::
29591 @end menu
29592
29593 @c ---------------------------------------------------------------------------
29594 @node Basic Assembler Syntax
29595 @section Basic Assembler Syntax
29596
29597 @noindent
29598 The assembler used by GNAT and gcc is based not on the Intel assembly
29599 language, but rather on a language that descends from the AT&T Unix
29600 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29601 The following table summarizes the main features of @emph{as} syntax
29602 and points out the differences from the Intel conventions.
29603 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29604 pre-processor) documentation for further information.
29605
29606 @table @asis
29607 @item Register names
29608 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29609 @*
29610 Intel: No extra punctuation; for example @code{eax}
29611
29612 @item Immediate operand
29613 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29614 @*
29615 Intel: No extra punctuation; for example @code{4}
29616
29617 @item Address
29618 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29619 @*
29620 Intel: No extra punctuation; for example @code{loc}
29621
29622 @item Memory contents
29623 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29624 @*
29625 Intel: Square brackets; for example @code{[loc]}
29626
29627 @item Register contents
29628 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29629 @*
29630 Intel: Square brackets; for example @code{[eax]}
29631
29632 @item Hexadecimal numbers
29633 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29634 @*
29635 Intel: Trailing ``h''; for example @code{A0h}
29636
29637 @item Operand size
29638 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29639 a 16-bit word
29640 @*
29641 Intel: Implicit, deduced by assembler; for example @code{mov}
29642
29643 @item Instruction repetition
29644 gcc / @emph{as}: Split into two lines; for example
29645 @*
29646 @code{rep}
29647 @*
29648 @code{stosl}
29649 @*
29650 Intel: Keep on one line; for example @code{rep stosl}
29651
29652 @item Order of operands
29653 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29654 @*
29655 Intel: Destination first; for example @code{mov eax, 4}
29656 @end table
29657
29658 @c ---------------------------------------------------------------------------
29659 @node A Simple Example of Inline Assembler
29660 @section A Simple Example of Inline Assembler
29661
29662 @noindent
29663 The following example will generate a single assembly language statement,
29664 @code{nop}, which does nothing. Despite its lack of run-time effect,
29665 the example will be useful in illustrating the basics of
29666 the Inline Assembler facility.
29667
29668 @smallexample @c ada
29669 @group
29670 with System.Machine_Code; use System.Machine_Code;
29671 procedure Nothing is
29672 begin
29673 Asm ("nop");
29674 end Nothing;
29675 @end group
29676 @end smallexample
29677
29678 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29679 here it takes one parameter, a @emph{template string} that must be a static
29680 expression and that will form the generated instruction.
29681 @code{Asm} may be regarded as a compile-time procedure that parses
29682 the template string and additional parameters (none here),
29683 from which it generates a sequence of assembly language instructions.
29684
29685 The examples in this chapter will illustrate several of the forms
29686 for invoking @code{Asm}; a complete specification of the syntax
29687 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29688 Manual}.
29689
29690 Under the standard GNAT conventions, the @code{Nothing} procedure
29691 should be in a file named @file{nothing.adb}.
29692 You can build the executable in the usual way:
29693 @smallexample
29694 gnatmake nothing
29695 @end smallexample
29696 However, the interesting aspect of this example is not its run-time behavior
29697 but rather the generated assembly code.
29698 To see this output, invoke the compiler as follows:
29699 @smallexample
29700 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29701 @end smallexample
29702 where the options are:
29703
29704 @table @code
29705 @item -c
29706 compile only (no bind or link)
29707 @item -S
29708 generate assembler listing
29709 @item -fomit-frame-pointer
29710 do not set up separate stack frames
29711 @item -gnatp
29712 do not add runtime checks
29713 @end table
29714
29715 This gives a human-readable assembler version of the code. The resulting
29716 file will have the same name as the Ada source file, but with a @code{.s}
29717 extension. In our example, the file @file{nothing.s} has the following
29718 contents:
29719
29720 @smallexample
29721 @group
29722 .file "nothing.adb"
29723 gcc2_compiled.:
29724 ___gnu_compiled_ada:
29725 .text
29726 .align 4
29727 .globl __ada_nothing
29728 __ada_nothing:
29729 #APP
29730 nop
29731 #NO_APP
29732 jmp L1
29733 .align 2,0x90
29734 L1:
29735 ret
29736 @end group
29737 @end smallexample
29738
29739 The assembly code you included is clearly indicated by
29740 the compiler, between the @code{#APP} and @code{#NO_APP}
29741 delimiters. The character before the 'APP' and 'NOAPP'
29742 can differ on different targets. For example, GNU/Linux uses '#APP' while
29743 on NT you will see '/APP'.
29744
29745 If you make a mistake in your assembler code (such as using the
29746 wrong size modifier, or using a wrong operand for the instruction) GNAT
29747 will report this error in a temporary file, which will be deleted when
29748 the compilation is finished. Generating an assembler file will help
29749 in such cases, since you can assemble this file separately using the
29750 @emph{as} assembler that comes with gcc.
29751
29752 Assembling the file using the command
29753
29754 @smallexample
29755 as @file{nothing.s}
29756 @end smallexample
29757 @noindent
29758 will give you error messages whose lines correspond to the assembler
29759 input file, so you can easily find and correct any mistakes you made.
29760 If there are no errors, @emph{as} will generate an object file
29761 @file{nothing.out}.
29762
29763 @c ---------------------------------------------------------------------------
29764 @node Output Variables in Inline Assembler
29765 @section Output Variables in Inline Assembler
29766
29767 @noindent
29768 The examples in this section, showing how to access the processor flags,
29769 illustrate how to specify the destination operands for assembly language
29770 statements.
29771
29772 @smallexample @c ada
29773 @group
29774 with Interfaces; use Interfaces;
29775 with Ada.Text_IO; use Ada.Text_IO;
29776 with System.Machine_Code; use System.Machine_Code;
29777 procedure Get_Flags is
29778 Flags : Unsigned_32;
29779 use ASCII;
29780 begin
29781 Asm ("pushfl" & LF & HT & -- push flags on stack
29782 "popl %%eax" & LF & HT & -- load eax with flags
29783 "movl %%eax, %0", -- store flags in variable
29784 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29785 Put_Line ("Flags register:" & Flags'Img);
29786 end Get_Flags;
29787 @end group
29788 @end smallexample
29789
29790 In order to have a nicely aligned assembly listing, we have separated
29791 multiple assembler statements in the Asm template string with linefeed
29792 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29793 The resulting section of the assembly output file is:
29794
29795 @smallexample
29796 @group
29797 #APP
29798 pushfl
29799 popl %eax
29800 movl %eax, -40(%ebp)
29801 #NO_APP
29802 @end group
29803 @end smallexample
29804
29805 It would have been legal to write the Asm invocation as:
29806
29807 @smallexample
29808 Asm ("pushfl popl %%eax movl %%eax, %0")
29809 @end smallexample
29810
29811 but in the generated assembler file, this would come out as:
29812
29813 @smallexample
29814 #APP
29815 pushfl popl %eax movl %eax, -40(%ebp)
29816 #NO_APP
29817 @end smallexample
29818
29819 which is not so convenient for the human reader.
29820
29821 We use Ada comments
29822 at the end of each line to explain what the assembler instructions
29823 actually do. This is a useful convention.
29824
29825 When writing Inline Assembler instructions, you need to precede each register
29826 and variable name with a percent sign. Since the assembler already requires
29827 a percent sign at the beginning of a register name, you need two consecutive
29828 percent signs for such names in the Asm template string, thus @code{%%eax}.
29829 In the generated assembly code, one of the percent signs will be stripped off.
29830
29831 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29832 variables: operands you later define using @code{Input} or @code{Output}
29833 parameters to @code{Asm}.
29834 An output variable is illustrated in
29835 the third statement in the Asm template string:
29836 @smallexample
29837 movl %%eax, %0
29838 @end smallexample
29839 The intent is to store the contents of the eax register in a variable that can
29840 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
29841 necessarily work, since the compiler might optimize by using a register
29842 to hold Flags, and the expansion of the @code{movl} instruction would not be
29843 aware of this optimization. The solution is not to store the result directly
29844 but rather to advise the compiler to choose the correct operand form;
29845 that is the purpose of the @code{%0} output variable.
29846
29847 Information about the output variable is supplied in the @code{Outputs}
29848 parameter to @code{Asm}:
29849 @smallexample
29850 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29851 @end smallexample
29852
29853 The output is defined by the @code{Asm_Output} attribute of the target type;
29854 the general format is
29855 @smallexample
29856 Type'Asm_Output (constraint_string, variable_name)
29857 @end smallexample
29858
29859 The constraint string directs the compiler how
29860 to store/access the associated variable. In the example
29861 @smallexample
29862 Unsigned_32'Asm_Output ("=m", Flags);
29863 @end smallexample
29864 the @code{"m"} (memory) constraint tells the compiler that the variable
29865 @code{Flags} should be stored in a memory variable, thus preventing
29866 the optimizer from keeping it in a register. In contrast,
29867 @smallexample
29868 Unsigned_32'Asm_Output ("=r", Flags);
29869 @end smallexample
29870 uses the @code{"r"} (register) constraint, telling the compiler to
29871 store the variable in a register.
29872
29873 If the constraint is preceded by the equal character (@strong{=}), it tells
29874 the compiler that the variable will be used to store data into it.
29875
29876 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29877 allowing the optimizer to choose whatever it deems best.
29878
29879 There are a fairly large number of constraints, but the ones that are
29880 most useful (for the Intel x86 processor) are the following:
29881
29882 @table @code
29883 @item =
29884 output constraint
29885 @item g
29886 global (i.e.@: can be stored anywhere)
29887 @item m
29888 in memory
29889 @item I
29890 a constant
29891 @item a
29892 use eax
29893 @item b
29894 use ebx
29895 @item c
29896 use ecx
29897 @item d
29898 use edx
29899 @item S
29900 use esi
29901 @item D
29902 use edi
29903 @item r
29904 use one of eax, ebx, ecx or edx
29905 @item q
29906 use one of eax, ebx, ecx, edx, esi or edi
29907 @end table
29908
29909 The full set of constraints is described in the gcc and @emph{as}
29910 documentation; note that it is possible to combine certain constraints
29911 in one constraint string.
29912
29913 You specify the association of an output variable with an assembler operand
29914 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29915 integer. Thus in
29916 @smallexample @c ada
29917 @group
29918 Asm ("pushfl" & LF & HT & -- push flags on stack
29919 "popl %%eax" & LF & HT & -- load eax with flags
29920 "movl %%eax, %0", -- store flags in variable
29921 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29922 @end group
29923 @end smallexample
29924 @noindent
29925 @code{%0} will be replaced in the expanded code by the appropriate operand,
29926 whatever
29927 the compiler decided for the @code{Flags} variable.
29928
29929 In general, you may have any number of output variables:
29930 @itemize @bullet
29931 @item
29932 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29933 @item
29934 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29935 of @code{Asm_Output} attributes
29936 @end itemize
29937
29938 For example:
29939 @smallexample @c ada
29940 @group
29941 Asm ("movl %%eax, %0" & LF & HT &
29942 "movl %%ebx, %1" & LF & HT &
29943 "movl %%ecx, %2",
29944 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
29945 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
29946 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
29947 @end group
29948 @end smallexample
29949 @noindent
29950 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29951 in the Ada program.
29952
29953 As a variation on the @code{Get_Flags} example, we can use the constraints
29954 string to direct the compiler to store the eax register into the @code{Flags}
29955 variable, instead of including the store instruction explicitly in the
29956 @code{Asm} template string:
29957
29958 @smallexample @c ada
29959 @group
29960 with Interfaces; use Interfaces;
29961 with Ada.Text_IO; use Ada.Text_IO;
29962 with System.Machine_Code; use System.Machine_Code;
29963 procedure Get_Flags_2 is
29964 Flags : Unsigned_32;
29965 use ASCII;
29966 begin
29967 Asm ("pushfl" & LF & HT & -- push flags on stack
29968 "popl %%eax", -- save flags in eax
29969 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29970 Put_Line ("Flags register:" & Flags'Img);
29971 end Get_Flags_2;
29972 @end group
29973 @end smallexample
29974
29975 @noindent
29976 The @code{"a"} constraint tells the compiler that the @code{Flags}
29977 variable will come from the eax register. Here is the resulting code:
29978
29979 @smallexample
29980 @group
29981 #APP
29982 pushfl
29983 popl %eax
29984 #NO_APP
29985 movl %eax,-40(%ebp)
29986 @end group
29987 @end smallexample
29988
29989 @noindent
29990 The compiler generated the store of eax into Flags after
29991 expanding the assembler code.
29992
29993 Actually, there was no need to pop the flags into the eax register;
29994 more simply, we could just pop the flags directly into the program variable:
29995
29996 @smallexample @c ada
29997 @group
29998 with Interfaces; use Interfaces;
29999 with Ada.Text_IO; use Ada.Text_IO;
30000 with System.Machine_Code; use System.Machine_Code;
30001 procedure Get_Flags_3 is
30002 Flags : Unsigned_32;
30003 use ASCII;
30004 begin
30005 Asm ("pushfl" & LF & HT & -- push flags on stack
30006 "pop %0", -- save flags in Flags
30007 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30008 Put_Line ("Flags register:" & Flags'Img);
30009 end Get_Flags_3;
30010 @end group
30011 @end smallexample
30012
30013 @c ---------------------------------------------------------------------------
30014 @node Input Variables in Inline Assembler
30015 @section Input Variables in Inline Assembler
30016
30017 @noindent
30018 The example in this section illustrates how to specify the source operands
30019 for assembly language statements.
30020 The program simply increments its input value by 1:
30021
30022 @smallexample @c ada
30023 @group
30024 with Interfaces; use Interfaces;
30025 with Ada.Text_IO; use Ada.Text_IO;
30026 with System.Machine_Code; use System.Machine_Code;
30027 procedure Increment is
30028
30029 function Incr (Value : Unsigned_32) return Unsigned_32 is
30030 Result : Unsigned_32;
30031 begin
30032 Asm ("incl %0",
30033 Inputs => Unsigned_32'Asm_Input ("a", Value),
30034 Outputs => Unsigned_32'Asm_Output ("=a", Result));
30035 return Result;
30036 end Incr;
30037
30038 Value : Unsigned_32;
30039
30040 begin
30041 Value := 5;
30042 Put_Line ("Value before is" & Value'Img);
30043 Value := Incr (Value);
30044 Put_Line ("Value after is" & Value'Img);
30045 end Increment;
30046 @end group
30047 @end smallexample
30048
30049 The @code{Outputs} parameter to @code{Asm} specifies
30050 that the result will be in the eax register and that it is to be stored
30051 in the @code{Result} variable.
30052
30053 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30054 but with an @code{Asm_Input} attribute.
30055 The @code{"="} constraint, indicating an output value, is not present.
30056
30057 You can have multiple input variables, in the same way that you can have more
30058 than one output variable.
30059
30060 The parameter count (%0, %1) etc, now starts at the first input
30061 statement, and continues with the output statements.
30062 When both parameters use the same variable, the
30063 compiler will treat them as the same %n operand, which is the case here.
30064
30065 Just as the @code{Outputs} parameter causes the register to be stored into the
30066 target variable after execution of the assembler statements, so does the
30067 @code{Inputs} parameter cause its variable to be loaded into the register
30068 before execution of the assembler statements.
30069
30070 Thus the effect of the @code{Asm} invocation is:
30071 @enumerate
30072 @item load the 32-bit value of @code{Value} into eax
30073 @item execute the @code{incl %eax} instruction
30074 @item store the contents of eax into the @code{Result} variable
30075 @end enumerate
30076
30077 The resulting assembler file (with @option{-O2} optimization) contains:
30078 @smallexample
30079 @group
30080 _increment__incr.1:
30081 subl $4,%esp
30082 movl 8(%esp),%eax
30083 #APP
30084 incl %eax
30085 #NO_APP
30086 movl %eax,%edx
30087 movl %ecx,(%esp)
30088 addl $4,%esp
30089 ret
30090 @end group
30091 @end smallexample
30092
30093 @c ---------------------------------------------------------------------------
30094 @node Inlining Inline Assembler Code
30095 @section Inlining Inline Assembler Code
30096
30097 @noindent
30098 For a short subprogram such as the @code{Incr} function in the previous
30099 section, the overhead of the call and return (creating / deleting the stack
30100 frame) can be significant, compared to the amount of code in the subprogram
30101 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30102 which directs the compiler to expand invocations of the subprogram at the
30103 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30104 Here is the resulting program:
30105
30106 @smallexample @c ada
30107 @group
30108 with Interfaces; use Interfaces;
30109 with Ada.Text_IO; use Ada.Text_IO;
30110 with System.Machine_Code; use System.Machine_Code;
30111 procedure Increment_2 is
30112
30113 function Incr (Value : Unsigned_32) return Unsigned_32 is
30114 Result : Unsigned_32;
30115 begin
30116 Asm ("incl %0",
30117 Inputs => Unsigned_32'Asm_Input ("a", Value),
30118 Outputs => Unsigned_32'Asm_Output ("=a", Result));
30119 return Result;
30120 end Incr;
30121 pragma Inline (Increment);
30122
30123 Value : Unsigned_32;
30124
30125 begin
30126 Value := 5;
30127 Put_Line ("Value before is" & Value'Img);
30128 Value := Increment (Value);
30129 Put_Line ("Value after is" & Value'Img);
30130 end Increment_2;
30131 @end group
30132 @end smallexample
30133
30134 Compile the program with both optimization (@option{-O2}) and inlining
30135 (@option{-gnatn}) enabled.
30136
30137 The @code{Incr} function is still compiled as usual, but at the
30138 point in @code{Increment} where our function used to be called:
30139
30140 @smallexample
30141 @group
30142 pushl %edi
30143 call _increment__incr.1
30144 @end group
30145 @end smallexample
30146
30147 @noindent
30148 the code for the function body directly appears:
30149
30150 @smallexample
30151 @group
30152 movl %esi,%eax
30153 #APP
30154 incl %eax
30155 #NO_APP
30156 movl %eax,%edx
30157 @end group
30158 @end smallexample
30159
30160 @noindent
30161 thus saving the overhead of stack frame setup and an out-of-line call.
30162
30163 @c ---------------------------------------------------------------------------
30164 @node Other Asm Functionality
30165 @section Other @code{Asm} Functionality
30166
30167 @noindent
30168 This section describes two important parameters to the @code{Asm}
30169 procedure: @code{Clobber}, which identifies register usage;
30170 and @code{Volatile}, which inhibits unwanted optimizations.
30171
30172 @menu
30173 * The Clobber Parameter::
30174 * The Volatile Parameter::
30175 @end menu
30176
30177 @c ---------------------------------------------------------------------------
30178 @node The Clobber Parameter
30179 @subsection The @code{Clobber} Parameter
30180
30181 @noindent
30182 One of the dangers of intermixing assembly language and a compiled language
30183 such as Ada is that the compiler needs to be aware of which registers are
30184 being used by the assembly code. In some cases, such as the earlier examples,
30185 the constraint string is sufficient to indicate register usage (e.g.,
30186 @code{"a"} for
30187 the eax register). But more generally, the compiler needs an explicit
30188 identification of the registers that are used by the Inline Assembly
30189 statements.
30190
30191 Using a register that the compiler doesn't know about
30192 could be a side effect of an instruction (like @code{mull}
30193 storing its result in both eax and edx).
30194 It can also arise from explicit register usage in your
30195 assembly code; for example:
30196 @smallexample
30197 @group
30198 Asm ("movl %0, %%ebx" & LF & HT &
30199 "movl %%ebx, %1",
30200 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30201 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30202 @end group
30203 @end smallexample
30204 @noindent
30205 where the compiler (since it does not analyze the @code{Asm} template string)
30206 does not know you are using the ebx register.
30207
30208 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30209 to identify the registers that will be used by your assembly code:
30210
30211 @smallexample
30212 @group
30213 Asm ("movl %0, %%ebx" & LF & HT &
30214 "movl %%ebx, %1",
30215 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30216 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30217 Clobber => "ebx");
30218 @end group
30219 @end smallexample
30220
30221 The Clobber parameter is a static string expression specifying the
30222 register(s) you are using. Note that register names are @emph{not} prefixed
30223 by a percent sign. Also, if more than one register is used then their names
30224 are separated by commas; e.g., @code{"eax, ebx"}
30225
30226 The @code{Clobber} parameter has several additional uses:
30227 @enumerate
30228 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30229 @item Use ``register'' name @code{memory} if you changed a memory location
30230 @end enumerate
30231
30232 @c ---------------------------------------------------------------------------
30233 @node The Volatile Parameter
30234 @subsection The @code{Volatile} Parameter
30235 @cindex Volatile parameter
30236
30237 @noindent
30238 Compiler optimizations in the presence of Inline Assembler may sometimes have
30239 unwanted effects. For example, when an @code{Asm} invocation with an input
30240 variable is inside a loop, the compiler might move the loading of the input
30241 variable outside the loop, regarding it as a one-time initialization.
30242
30243 If this effect is not desired, you can disable such optimizations by setting
30244 the @code{Volatile} parameter to @code{True}; for example:
30245
30246 @smallexample @c ada
30247 @group
30248 Asm ("movl %0, %%ebx" & LF & HT &
30249 "movl %%ebx, %1",
30250 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30251 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30252 Clobber => "ebx",
30253 Volatile => True);
30254 @end group
30255 @end smallexample
30256
30257 By default, @code{Volatile} is set to @code{False} unless there is no
30258 @code{Outputs} parameter.
30259
30260 Although setting @code{Volatile} to @code{True} prevents unwanted
30261 optimizations, it will also disable other optimizations that might be
30262 important for efficiency. In general, you should set @code{Volatile}
30263 to @code{True} only if the compiler's optimizations have created
30264 problems.
30265 @c END OF INLINE ASSEMBLER CHAPTER
30266 @c ===============================
30267
30268 @c ***********************************
30269 @c * Compatibility and Porting Guide *
30270 @c ***********************************
30271 @node Compatibility and Porting Guide
30272 @appendix Compatibility and Porting Guide
30273
30274 @noindent
30275 This chapter describes the compatibility issues that may arise between
30276 GNAT and other Ada compilation systems (including those for Ada 83),
30277 and shows how GNAT can expedite porting
30278 applications developed in other Ada environments.
30279
30280 @menu
30281 * Compatibility with Ada 83::
30282 * Compatibility between Ada 95 and Ada 2005::
30283 * Implementation-dependent characteristics::
30284 * Compatibility with Other Ada Systems::
30285 * Representation Clauses::
30286 @ifclear vms
30287 @c Brief section is only in non-VMS version
30288 @c Full chapter is in VMS version
30289 * Compatibility with HP Ada 83::
30290 @end ifclear
30291 @ifset vms
30292 * Transitioning to 64-Bit GNAT for OpenVMS::
30293 @end ifset
30294 @end menu
30295
30296 @node Compatibility with Ada 83
30297 @section Compatibility with Ada 83
30298 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30299
30300 @noindent
30301 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
30302 particular, the design intention was that the difficulties associated
30303 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30304 that occur when moving from one Ada 83 system to another.
30305
30306 However, there are a number of points at which there are minor
30307 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
30308 full details of these issues,
30309 and should be consulted for a complete treatment.
30310 In practice the
30311 following subsections treat the most likely issues to be encountered.
30312
30313 @menu
30314 * Legal Ada 83 programs that are illegal in Ada 95::
30315 * More deterministic semantics::
30316 * Changed semantics::
30317 * Other language compatibility issues::
30318 @end menu
30319
30320 @node Legal Ada 83 programs that are illegal in Ada 95
30321 @subsection Legal Ada 83 programs that are illegal in Ada 95
30322
30323 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30324 Ada 95 and thus also in Ada 2005:
30325
30326 @table @emph
30327 @item Character literals
30328 Some uses of character literals are ambiguous. Since Ada 95 has introduced
30329 @code{Wide_Character} as a new predefined character type, some uses of
30330 character literals that were legal in Ada 83 are illegal in Ada 95.
30331 For example:
30332 @smallexample @c ada
30333 for Char in 'A' .. 'Z' loop @dots{} end loop;
30334 @end smallexample
30335
30336 @noindent
30337 The problem is that @code{'A'} and @code{'Z'} could be from either
30338 @code{Character} or @code{Wide_Character}. The simplest correction
30339 is to make the type explicit; e.g.:
30340 @smallexample @c ada
30341 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30342 @end smallexample
30343
30344 @item New reserved words
30345 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30346 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30347 Existing Ada 83 code using any of these identifiers must be edited to
30348 use some alternative name.
30349
30350 @item Freezing rules
30351 The rules in Ada 95 are slightly different with regard to the point at
30352 which entities are frozen, and representation pragmas and clauses are
30353 not permitted past the freeze point. This shows up most typically in
30354 the form of an error message complaining that a representation item
30355 appears too late, and the appropriate corrective action is to move
30356 the item nearer to the declaration of the entity to which it refers.
30357
30358 A particular case is that representation pragmas
30359 @ifset vms
30360 (including the
30361 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30362 @end ifset
30363 cannot be applied to a subprogram body. If necessary, a separate subprogram
30364 declaration must be introduced to which the pragma can be applied.
30365
30366 @item Optional bodies for library packages
30367 In Ada 83, a package that did not require a package body was nevertheless
30368 allowed to have one. This lead to certain surprises in compiling large
30369 systems (situations in which the body could be unexpectedly ignored by the
30370 binder). In Ada 95, if a package does not require a body then it is not
30371 permitted to have a body. To fix this problem, simply remove a redundant
30372 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30373 into the spec that makes the body required. One approach is to add a private
30374 part to the package declaration (if necessary), and define a parameterless
30375 procedure called @code{Requires_Body}, which must then be given a dummy
30376 procedure body in the package body, which then becomes required.
30377 Another approach (assuming that this does not introduce elaboration
30378 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30379 since one effect of this pragma is to require the presence of a package body.
30380
30381 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30382 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30383 @code{Constraint_Error}.
30384 This means that it is illegal to have separate exception handlers for
30385 the two exceptions. The fix is simply to remove the handler for the
30386 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30387 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30388
30389 @item Indefinite subtypes in generics
30390 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30391 as the actual for a generic formal private type, but then the instantiation
30392 would be illegal if there were any instances of declarations of variables
30393 of this type in the generic body. In Ada 95, to avoid this clear violation
30394 of the methodological principle known as the ``contract model'',
30395 the generic declaration explicitly indicates whether
30396 or not such instantiations are permitted. If a generic formal parameter
30397 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30398 type name, then it can be instantiated with indefinite types, but no
30399 stand-alone variables can be declared of this type. Any attempt to declare
30400 such a variable will result in an illegality at the time the generic is
30401 declared. If the @code{(<>)} notation is not used, then it is illegal
30402 to instantiate the generic with an indefinite type.
30403 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30404 It will show up as a compile time error, and
30405 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30406 @end table
30407
30408 @node More deterministic semantics
30409 @subsection More deterministic semantics
30410
30411 @table @emph
30412 @item Conversions
30413 Conversions from real types to integer types round away from 0. In Ada 83
30414 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
30415 implementation freedom was intended to support unbiased rounding in
30416 statistical applications, but in practice it interfered with portability.
30417 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30418 is required. Numeric code may be affected by this change in semantics.
30419 Note, though, that this issue is no worse than already existed in Ada 83
30420 when porting code from one vendor to another.
30421
30422 @item Tasking
30423 The Real-Time Annex introduces a set of policies that define the behavior of
30424 features that were implementation dependent in Ada 83, such as the order in
30425 which open select branches are executed.
30426 @end table
30427
30428 @node Changed semantics
30429 @subsection Changed semantics
30430
30431 @noindent
30432 The worst kind of incompatibility is one where a program that is legal in
30433 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30434 possible in Ada 83. Fortunately this is extremely rare, but the one
30435 situation that you should be alert to is the change in the predefined type
30436 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30437
30438 @table @emph
30439 @item Range of type @code{Character}
30440 The range of @code{Standard.Character} is now the full 256 characters
30441 of Latin-1, whereas in most Ada 83 implementations it was restricted
30442 to 128 characters. Although some of the effects of
30443 this change will be manifest in compile-time rejection of legal
30444 Ada 83 programs it is possible for a working Ada 83 program to have
30445 a different effect in Ada 95, one that was not permitted in Ada 83.
30446 As an example, the expression
30447 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30448 delivers @code{255} as its value.
30449 In general, you should look at the logic of any
30450 character-processing Ada 83 program and see whether it needs to be adapted
30451 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
30452 character handling package that may be relevant if code needs to be adapted
30453 to account for the additional Latin-1 elements.
30454 The desirable fix is to
30455 modify the program to accommodate the full character set, but in some cases
30456 it may be convenient to define a subtype or derived type of Character that
30457 covers only the restricted range.
30458 @cindex Latin-1
30459 @end table
30460
30461 @node Other language compatibility issues
30462 @subsection Other language compatibility issues
30463
30464 @table @emph
30465 @item @option{-gnat83} switch
30466 All implementations of GNAT provide a switch that causes GNAT to operate
30467 in Ada 83 mode. In this mode, some but not all compatibility problems
30468 of the type described above are handled automatically. For example, the
30469 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30470 as identifiers as in Ada 83.
30471 However,
30472 in practice, it is usually advisable to make the necessary modifications
30473 to the program to remove the need for using this switch.
30474 See @ref{Compiling Different Versions of Ada}.
30475
30476 @item Support for removed Ada 83 pragmas and attributes
30477 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30478 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
30479 compilers are allowed, but not required, to implement these missing
30480 elements. In contrast with some other compilers, GNAT implements all
30481 such pragmas and attributes, eliminating this compatibility concern. These
30482 include @code{pragma Interface} and the floating point type attributes
30483 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30484 @end table
30485
30486
30487 @node Compatibility between Ada 95 and Ada 2005
30488 @section Compatibility between Ada 95 and Ada 2005
30489 @cindex Compatibility between Ada 95 and Ada 2005
30490
30491 @noindent
30492 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30493 a number of incompatibilities. Several are enumerated below;
30494 for a complete description please see the
30495 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30496 @cite{Rationale for Ada 2005}.
30497
30498 @table @emph
30499 @item New reserved words.
30500 The words @code{interface}, @code{overriding} and @code{synchronized} are
30501 reserved in Ada 2005.
30502 A pre-Ada 2005 program that uses any of these as an identifier will be
30503 illegal.
30504
30505 @item New declarations in predefined packages.
30506 A number of packages in the predefined environment contain new declarations:
30507 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30508 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30509 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30510 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30511 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30512 If an Ada 95 program does a @code{with} and @code{use} of any of these
30513 packages, the new declarations may cause name clashes.
30514
30515 @item Access parameters.
30516 A nondispatching subprogram with an access parameter cannot be renamed
30517 as a dispatching operation. This was permitted in Ada 95.
30518
30519 @item Access types, discriminants, and constraints.
30520 Rule changes in this area have led to some incompatibilities; for example,
30521 constrained subtypes of some access types are not permitted in Ada 2005.
30522
30523 @item Aggregates for limited types.
30524 The allowance of aggregates for limited types in Ada 2005 raises the
30525 possibility of ambiguities in legal Ada 95 programs, since additional types
30526 now need to be considered in expression resolution.
30527
30528 @item Fixed-point multiplication and division.
30529 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30530 were legal in Ada 95 and invoked the predefined versions of these operations,
30531 are now ambiguous.
30532 The ambiguity may be resolved either by applying a type conversion to the
30533 expression, or by explicitly invoking the operation from package
30534 @code{Standard}.
30535
30536 @item Return-by-reference types.
30537 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
30538 can declare a function returning a value from an anonymous access type.
30539 @end table
30540
30541
30542 @node Implementation-dependent characteristics
30543 @section Implementation-dependent characteristics
30544 @noindent
30545 Although the Ada language defines the semantics of each construct as
30546 precisely as practical, in some situations (for example for reasons of
30547 efficiency, or where the effect is heavily dependent on the host or target
30548 platform) the implementation is allowed some freedom. In porting Ada 83
30549 code to GNAT, you need to be aware of whether / how the existing code
30550 exercised such implementation dependencies. Such characteristics fall into
30551 several categories, and GNAT offers specific support in assisting the
30552 transition from certain Ada 83 compilers.
30553
30554 @menu
30555 * Implementation-defined pragmas::
30556 * Implementation-defined attributes::
30557 * Libraries::
30558 * Elaboration order::
30559 * Target-specific aspects::
30560 @end menu
30561
30562 @node Implementation-defined pragmas
30563 @subsection Implementation-defined pragmas
30564
30565 @noindent
30566 Ada compilers are allowed to supplement the language-defined pragmas, and
30567 these are a potential source of non-portability. All GNAT-defined pragmas
30568 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30569 Reference Manual}, and these include several that are specifically
30570 intended to correspond to other vendors' Ada 83 pragmas.
30571 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30572 For compatibility with HP Ada 83, GNAT supplies the pragmas
30573 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30574 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30575 and @code{Volatile}.
30576 Other relevant pragmas include @code{External} and @code{Link_With}.
30577 Some vendor-specific
30578 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30579 recognized, thus
30580 avoiding compiler rejection of units that contain such pragmas; they are not
30581 relevant in a GNAT context and hence are not otherwise implemented.
30582
30583 @node Implementation-defined attributes
30584 @subsection Implementation-defined attributes
30585
30586 Analogous to pragmas, the set of attributes may be extended by an
30587 implementation. All GNAT-defined attributes are described in
30588 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30589 Manual}, and these include several that are specifically intended
30590 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
30591 the attribute @code{VADS_Size} may be useful. For compatibility with HP
30592 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30593 @code{Type_Class}.
30594
30595 @node Libraries
30596 @subsection Libraries
30597 @noindent
30598 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
30599 code uses vendor-specific libraries then there are several ways to manage
30600 this in Ada 95 or Ada 2005:
30601 @enumerate
30602 @item
30603 If the source code for the libraries (specs and bodies) are
30604 available, then the libraries can be migrated in the same way as the
30605 application.
30606 @item
30607 If the source code for the specs but not the bodies are
30608 available, then you can reimplement the bodies.
30609 @item
30610 Some features introduced by Ada 95 obviate the need for library support. For
30611 example most Ada 83 vendors supplied a package for unsigned integers. The
30612 Ada 95 modular type feature is the preferred way to handle this need, so
30613 instead of migrating or reimplementing the unsigned integer package it may
30614 be preferable to retrofit the application using modular types.
30615 @end enumerate
30616
30617 @node Elaboration order
30618 @subsection Elaboration order
30619 @noindent
30620 The implementation can choose any elaboration order consistent with the unit
30621 dependency relationship. This freedom means that some orders can result in
30622 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30623 to invoke a subprogram its body has been elaborated, or to instantiate a
30624 generic before the generic body has been elaborated. By default GNAT
30625 attempts to choose a safe order (one that will not encounter access before
30626 elaboration problems) by implicitly inserting @code{Elaborate} or
30627 @code{Elaborate_All} pragmas where
30628 needed. However, this can lead to the creation of elaboration circularities
30629 and a resulting rejection of the program by gnatbind. This issue is
30630 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30631 In brief, there are several
30632 ways to deal with this situation:
30633
30634 @itemize @bullet
30635 @item
30636 Modify the program to eliminate the circularities, e.g.@: by moving
30637 elaboration-time code into explicitly-invoked procedures
30638 @item
30639 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30640 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30641 @code{Elaborate_All}
30642 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30643 (by selectively suppressing elaboration checks via pragma
30644 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30645 @end itemize
30646
30647 @node Target-specific aspects
30648 @subsection Target-specific aspects
30649 @noindent
30650 Low-level applications need to deal with machine addresses, data
30651 representations, interfacing with assembler code, and similar issues. If
30652 such an Ada 83 application is being ported to different target hardware (for
30653 example where the byte endianness has changed) then you will need to
30654 carefully examine the program logic; the porting effort will heavily depend
30655 on the robustness of the original design. Moreover, Ada 95 (and thus
30656 Ada 2005) are sometimes
30657 incompatible with typical Ada 83 compiler practices regarding implicit
30658 packing, the meaning of the Size attribute, and the size of access values.
30659 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30660
30661 @node Compatibility with Other Ada Systems
30662 @section Compatibility with Other Ada Systems
30663
30664 @noindent
30665 If programs avoid the use of implementation dependent and
30666 implementation defined features, as documented in the @cite{Ada
30667 Reference Manual}, there should be a high degree of portability between
30668 GNAT and other Ada systems. The following are specific items which
30669 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30670 compilers, but do not affect porting code to GNAT@.
30671 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30672 the following issues may or may not arise for Ada 2005 programs
30673 when other compilers appear.)
30674
30675 @table @emph
30676 @item Ada 83 Pragmas and Attributes
30677 Ada 95 compilers are allowed, but not required, to implement the missing
30678 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30679 GNAT implements all such pragmas and attributes, eliminating this as
30680 a compatibility concern, but some other Ada 95 compilers reject these
30681 pragmas and attributes.
30682
30683 @item Specialized Needs Annexes
30684 GNAT implements the full set of special needs annexes. At the
30685 current time, it is the only Ada 95 compiler to do so. This means that
30686 programs making use of these features may not be portable to other Ada
30687 95 compilation systems.
30688
30689 @item Representation Clauses
30690 Some other Ada 95 compilers implement only the minimal set of
30691 representation clauses required by the Ada 95 reference manual. GNAT goes
30692 far beyond this minimal set, as described in the next section.
30693 @end table
30694
30695 @node Representation Clauses
30696 @section Representation Clauses
30697
30698 @noindent
30699 The Ada 83 reference manual was quite vague in describing both the minimal
30700 required implementation of representation clauses, and also their precise
30701 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
30702 minimal set of capabilities required is still quite limited.
30703
30704 GNAT implements the full required set of capabilities in
30705 Ada 95 and Ada 2005, but also goes much further, and in particular
30706 an effort has been made to be compatible with existing Ada 83 usage to the
30707 greatest extent possible.
30708
30709 A few cases exist in which Ada 83 compiler behavior is incompatible with
30710 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
30711 intentional or accidental dependence on specific implementation dependent
30712 characteristics of these Ada 83 compilers. The following is a list of
30713 the cases most likely to arise in existing Ada 83 code.
30714
30715 @table @emph
30716 @item Implicit Packing
30717 Some Ada 83 compilers allowed a Size specification to cause implicit
30718 packing of an array or record. This could cause expensive implicit
30719 conversions for change of representation in the presence of derived
30720 types, and the Ada design intends to avoid this possibility.
30721 Subsequent AI's were issued to make it clear that such implicit
30722 change of representation in response to a Size clause is inadvisable,
30723 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30724 Reference Manuals as implementation advice that is followed by GNAT@.
30725 The problem will show up as an error
30726 message rejecting the size clause. The fix is simply to provide
30727 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30728 a Component_Size clause.
30729
30730 @item Meaning of Size Attribute
30731 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30732 the minimal number of bits required to hold values of the type. For example,
30733 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30734 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
30735 some 32 in this situation. This problem will usually show up as a compile
30736 time error, but not always. It is a good idea to check all uses of the
30737 'Size attribute when porting Ada 83 code. The GNAT specific attribute
30738 Object_Size can provide a useful way of duplicating the behavior of
30739 some Ada 83 compiler systems.
30740
30741 @item Size of Access Types
30742 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30743 and that therefore it will be the same size as a System.Address value. This
30744 assumption is true for GNAT in most cases with one exception. For the case of
30745 a pointer to an unconstrained array type (where the bounds may vary from one
30746 value of the access type to another), the default is to use a ``fat pointer'',
30747 which is represented as two separate pointers, one to the bounds, and one to
30748 the array. This representation has a number of advantages, including improved
30749 efficiency. However, it may cause some difficulties in porting existing Ada 83
30750 code which makes the assumption that, for example, pointers fit in 32 bits on
30751 a machine with 32-bit addressing.
30752
30753 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30754 access types in this case (where the designated type is an unconstrained array
30755 type). These thin pointers are indeed the same size as a System.Address value.
30756 To specify a thin pointer, use a size clause for the type, for example:
30757
30758 @smallexample @c ada
30759 type X is access all String;
30760 for X'Size use Standard'Address_Size;
30761 @end smallexample
30762
30763 @noindent
30764 which will cause the type X to be represented using a single pointer.
30765 When using this representation, the bounds are right behind the array.
30766 This representation is slightly less efficient, and does not allow quite
30767 such flexibility in the use of foreign pointers or in using the
30768 Unrestricted_Access attribute to create pointers to non-aliased objects.
30769 But for any standard portable use of the access type it will work in
30770 a functionally correct manner and allow porting of existing code.
30771 Note that another way of forcing a thin pointer representation
30772 is to use a component size clause for the element size in an array,
30773 or a record representation clause for an access field in a record.
30774 @end table
30775
30776 @ifclear vms
30777 @c This brief section is only in the non-VMS version
30778 @c The complete chapter on HP Ada is in the VMS version
30779 @node Compatibility with HP Ada 83
30780 @section Compatibility with HP Ada 83
30781
30782 @noindent
30783 The VMS version of GNAT fully implements all the pragmas and attributes
30784 provided by HP Ada 83, as well as providing the standard HP Ada 83
30785 libraries, including Starlet. In addition, data layouts and parameter
30786 passing conventions are highly compatible. This means that porting
30787 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30788 most other porting efforts. The following are some of the most
30789 significant differences between GNAT and HP Ada 83.
30790
30791 @table @emph
30792 @item Default floating-point representation
30793 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30794 it is VMS format. GNAT does implement the necessary pragmas
30795 (Long_Float, Float_Representation) for changing this default.
30796
30797 @item System
30798 The package System in GNAT exactly corresponds to the definition in the
30799 Ada 95 reference manual, which means that it excludes many of the
30800 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
30801 that contains the additional definitions, and a special pragma,
30802 Extend_System allows this package to be treated transparently as an
30803 extension of package System.
30804
30805 @item To_Address
30806 The definitions provided by Aux_DEC are exactly compatible with those
30807 in the HP Ada 83 version of System, with one exception.
30808 HP Ada provides the following declarations:
30809
30810 @smallexample @c ada
30811 TO_ADDRESS (INTEGER)
30812 TO_ADDRESS (UNSIGNED_LONGWORD)
30813 TO_ADDRESS (@i{universal_integer})
30814 @end smallexample
30815
30816 @noindent
30817 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30818 an extension to Ada 83 not strictly compatible with the reference manual.
30819 In GNAT, we are constrained to be exactly compatible with the standard,
30820 and this means we cannot provide this capability. In HP Ada 83, the
30821 point of this definition is to deal with a call like:
30822
30823 @smallexample @c ada
30824 TO_ADDRESS (16#12777#);
30825 @end smallexample
30826
30827 @noindent
30828 Normally, according to the Ada 83 standard, one would expect this to be
30829 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30830 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
30831 definition using @i{universal_integer} takes precedence.
30832
30833 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30834 is not possible to be 100% compatible. Since there are many programs using
30835 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30836 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30837 declarations provided in the GNAT version of AUX_Dec are:
30838
30839 @smallexample @c ada
30840 function To_Address (X : Integer) return Address;
30841 pragma Pure_Function (To_Address);
30842
30843 function To_Address_Long (X : Unsigned_Longword)
30844 return Address;
30845 pragma Pure_Function (To_Address_Long);
30846 @end smallexample
30847
30848 @noindent
30849 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30850 change the name to TO_ADDRESS_LONG@.
30851
30852 @item Task_Id values
30853 The Task_Id values assigned will be different in the two systems, and GNAT
30854 does not provide a specified value for the Task_Id of the environment task,
30855 which in GNAT is treated like any other declared task.
30856 @end table
30857
30858 @noindent
30859 For full details on these and other less significant compatibility issues,
30860 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30861 Overview and Comparison on HP Platforms}.
30862
30863 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30864 attributes are recognized, although only a subset of them can sensibly
30865 be implemented. The description of pragmas in @ref{Implementation
30866 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30867 indicates whether or not they are applicable to non-VMS systems.
30868 @end ifclear
30869
30870 @ifset vms
30871 @node Transitioning to 64-Bit GNAT for OpenVMS
30872 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30873
30874 @noindent
30875 This section is meant to assist users of pre-2006 @value{EDITION}
30876 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30877 the version of the GNAT technology supplied in 2006 and later for
30878 OpenVMS on both Alpha and I64.
30879
30880 @menu
30881 * Introduction to transitioning::
30882 * Migration of 32 bit code::
30883 * Taking advantage of 64 bit addressing::
30884 * Technical details::
30885 @end menu
30886
30887 @node Introduction to transitioning
30888 @subsection Introduction
30889
30890 @noindent
30891 64-bit @value{EDITION} for Open VMS has been designed to meet
30892 three main goals:
30893
30894 @enumerate
30895 @item
30896 Providing a full conforming implementation of Ada 95 and Ada 2005
30897
30898 @item
30899 Allowing maximum backward compatibility, thus easing migration of existing
30900 Ada source code
30901
30902 @item
30903 Supplying a path for exploiting the full 64-bit address range
30904 @end enumerate
30905
30906 @noindent
30907 Ada's strong typing semantics has made it
30908 impractical to have different 32-bit and 64-bit modes. As soon as
30909 one object could possibly be outside the 32-bit address space, this
30910 would make it necessary for the @code{System.Address} type to be 64 bits.
30911 In particular, this would cause inconsistencies if 32-bit code is
30912 called from 64-bit code that raises an exception.
30913
30914 This issue has been resolved by always using 64-bit addressing
30915 at the system level, but allowing for automatic conversions between
30916 32-bit and 64-bit addresses where required. Thus users who
30917 do not currently require 64-bit addressing capabilities, can
30918 recompile their code with only minimal changes (and indeed
30919 if the code is written in portable Ada, with no assumptions about
30920 the size of the @code{Address} type, then no changes at all are necessary).
30921 At the same time,
30922 this approach provides a simple, gradual upgrade path to future
30923 use of larger memories than available for 32-bit systems.
30924 Also, newly written applications or libraries will by default
30925 be fully compatible with future systems exploiting 64-bit
30926 addressing capabilities.
30927
30928 @ref{Migration of 32 bit code}, will focus on porting applications
30929 that do not require more than 2 GB of
30930 addressable memory. This code will be referred to as
30931 @emph{32-bit code}.
30932 For applications intending to exploit the full 64-bit address space,
30933 @ref{Taking advantage of 64 bit addressing},
30934 will consider further changes that may be required.
30935 Such code will be referred to below as @emph{64-bit code}.
30936
30937 @node Migration of 32 bit code
30938 @subsection Migration of 32-bit code
30939
30940 @menu
30941 * Address types::
30942 * Access types::
30943 * Unchecked conversions::
30944 * Predefined constants::
30945 * Interfacing with C::
30946 * Experience with source compatibility::
30947 @end menu
30948
30949 @node Address types
30950 @subsubsection Address types
30951
30952 @noindent
30953 To solve the problem of mixing 64-bit and 32-bit addressing,
30954 while maintaining maximum backward compatibility, the following
30955 approach has been taken:
30956
30957 @itemize @bullet
30958 @item
30959 @code{System.Address} always has a size of 64 bits
30960
30961 @item
30962 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30963 @end itemize
30964
30965 @noindent
30966 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30967 a @code{Short_Address}
30968 may be used where an @code{Address} is required, and vice versa, without
30969 needing explicit type conversions.
30970 By virtue of the Open VMS parameter passing conventions,
30971 even imported
30972 and exported subprograms that have 32-bit address parameters are
30973 compatible with those that have 64-bit address parameters.
30974 (See @ref{Making code 64 bit clean} for details.)
30975
30976 The areas that may need attention are those where record types have
30977 been defined that contain components of the type @code{System.Address}, and
30978 where objects of this type are passed to code expecting a record layout with
30979 32-bit addresses.
30980
30981 Different compilers on different platforms cannot be
30982 expected to represent the same type in the same way,
30983 since alignment constraints
30984 and other system-dependent properties affect the compiler's decision.
30985 For that reason, Ada code
30986 generally uses representation clauses to specify the expected
30987 layout where required.
30988
30989 If such a representation clause uses 32 bits for a component having
30990 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30991 will detect that error and produce a specific diagnostic message.
30992 The developer should then determine whether the representation
30993 should be 64 bits or not and make either of two changes:
30994 change the size to 64 bits and leave the type as @code{System.Address}, or
30995 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30996 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30997 required in any code setting or accessing the field; the compiler will
30998 automatically perform any needed conversions between address
30999 formats.
31000
31001 @node Access types
31002 @subsubsection Access types
31003
31004 @noindent
31005 By default, objects designated by access values are always
31006 allocated in the 32-bit
31007 address space. Thus legacy code will never contain
31008 any objects that are not addressable with 32-bit addresses, and
31009 the compiler will never raise exceptions as result of mixing
31010 32-bit and 64-bit addresses.
31011
31012 However, the access values themselves are represented in 64 bits, for optimum
31013 performance and future compatibility with 64-bit code. As was
31014 the case with @code{System.Address}, the compiler will give an error message
31015 if an object or record component has a representation clause that
31016 requires the access value to fit in 32 bits. In such a situation,
31017 an explicit size clause for the access type, specifying 32 bits,
31018 will have the desired effect.
31019
31020 General access types (declared with @code{access all}) can never be
31021 32 bits, as values of such types must be able to refer to any object
31022 of the designated type,
31023 including objects residing outside the 32-bit address range.
31024 Existing Ada 83 code will not contain such type definitions,
31025 however, since general access types were introduced in Ada 95.
31026
31027 @node Unchecked conversions
31028 @subsubsection Unchecked conversions
31029
31030 @noindent
31031 In the case of an @code{Unchecked_Conversion} where the source type is a
31032 64-bit access type or the type @code{System.Address}, and the target
31033 type is a 32-bit type, the compiler will generate a warning.
31034 Even though the generated code will still perform the required
31035 conversions, it is highly recommended in these cases to use
31036 respectively a 32-bit access type or @code{System.Short_Address}
31037 as the source type.
31038
31039 @node Predefined constants
31040 @subsubsection Predefined constants
31041
31042 @noindent
31043 The following table shows the correspondence between pre-2006 versions of
31044 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31045 (``New''):
31046
31047 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31048 @item @b{Constant} @tab @b{Old} @tab @b{New}
31049 @item @code{System.Word_Size} @tab 32 @tab 64
31050 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
31051 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
31052 @item @code{System.Address_Size} @tab 32 @tab 64
31053 @end multitable
31054
31055 @noindent
31056 If you need to refer to the specific
31057 memory size of a 32-bit implementation, instead of the
31058 actual memory size, use @code{System.Short_Memory_Size}
31059 rather than @code{System.Memory_Size}.
31060 Similarly, references to @code{System.Address_Size} may need
31061 to be replaced by @code{System.Short_Address'Size}.
31062 The program @command{gnatfind} may be useful for locating
31063 references to the above constants, so that you can verify that they
31064 are still correct.
31065
31066 @node Interfacing with C
31067 @subsubsection Interfacing with C
31068
31069 @noindent
31070 In order to minimize the impact of the transition to 64-bit addresses on
31071 legacy programs, some fundamental types in the @code{Interfaces.C}
31072 package hierarchy continue to be represented in 32 bits.
31073 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31074 This eases integration with the default HP C layout choices, for example
31075 as found in the system routines in @code{DECC$SHR.EXE}.
31076 Because of this implementation choice, the type fully compatible with
31077 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31078 Depending on the context the compiler will issue a
31079 warning or an error when type @code{Address} is used, alerting the user to a
31080 potential problem. Otherwise 32-bit programs that use
31081 @code{Interfaces.C} should normally not require code modifications
31082
31083 The other issue arising with C interfacing concerns pragma @code{Convention}.
31084 For VMS 64-bit systems, there is an issue of the appropriate default size
31085 of C convention pointers in the absence of an explicit size clause. The HP
31086 C compiler can choose either 32 or 64 bits depending on compiler options.
31087 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31088 clause is given. This proves a better choice for porting 32-bit legacy
31089 applications. In order to have a 64-bit representation, it is necessary to
31090 specify a size representation clause. For example:
31091
31092 @smallexample @c ada
31093 type int_star is access Interfaces.C.int;
31094 pragma Convention(C, int_star);
31095 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
31096 @end smallexample
31097
31098 @node Experience with source compatibility
31099 @subsubsection Experience with source compatibility
31100
31101 @noindent
31102 The Security Server and STARLET on I64 provide an interesting ``test case''
31103 for source compatibility issues, since it is in such system code
31104 where assumptions about @code{Address} size might be expected to occur.
31105 Indeed, there were a small number of occasions in the Security Server
31106 file @file{jibdef.ads}
31107 where a representation clause for a record type specified
31108 32 bits for a component of type @code{Address}.
31109 All of these errors were detected by the compiler.
31110 The repair was obvious and immediate; to simply replace @code{Address} by
31111 @code{Short_Address}.
31112
31113 In the case of STARLET, there were several record types that should
31114 have had representation clauses but did not. In these record types
31115 there was an implicit assumption that an @code{Address} value occupied
31116 32 bits.
31117 These compiled without error, but their usage resulted in run-time error
31118 returns from STARLET system calls.
31119 Future GNAT technology enhancements may include a tool that detects and flags
31120 these sorts of potential source code porting problems.
31121
31122 @c ****************************************
31123 @node Taking advantage of 64 bit addressing
31124 @subsection Taking advantage of 64-bit addressing
31125
31126 @menu
31127 * Making code 64 bit clean::
31128 * Allocating memory from the 64 bit storage pool::
31129 * Restrictions on use of 64 bit objects::
31130 * Using 64 bit storage pools by default::
31131 * General access types::
31132 * STARLET and other predefined libraries::
31133 @end menu
31134
31135 @node Making code 64 bit clean
31136 @subsubsection Making code 64-bit clean
31137
31138 @noindent
31139 In order to prevent problems that may occur when (parts of) a
31140 system start using memory outside the 32-bit address range,
31141 we recommend some additional guidelines:
31142
31143 @itemize @bullet
31144 @item
31145 For imported subprograms that take parameters of the
31146 type @code{System.Address}, ensure that these subprograms can
31147 indeed handle 64-bit addresses. If not, or when in doubt,
31148 change the subprogram declaration to specify
31149 @code{System.Short_Address} instead.
31150
31151 @item
31152 Resolve all warnings related to size mismatches in
31153 unchecked conversions. Failing to do so causes
31154 erroneous execution if the source object is outside
31155 the 32-bit address space.
31156
31157 @item
31158 (optional) Explicitly use the 32-bit storage pool
31159 for access types used in a 32-bit context, or use
31160 generic access types where possible
31161 (@pxref{Restrictions on use of 64 bit objects}).
31162 @end itemize
31163
31164 @noindent
31165 If these rules are followed, the compiler will automatically insert
31166 any necessary checks to ensure that no addresses or access values
31167 passed to 32-bit code ever refer to objects outside the 32-bit
31168 address range.
31169 Any attempt to do this will raise @code{Constraint_Error}.
31170
31171 @node Allocating memory from the 64 bit storage pool
31172 @subsubsection Allocating memory from the 64-bit storage pool
31173
31174 @noindent
31175 For any access type @code{T} that potentially requires memory allocations
31176 beyond the 32-bit address space,
31177 use the following representation clause:
31178
31179 @smallexample @c ada
31180 for T'Storage_Pool use System.Pool_64;
31181 @end smallexample
31182
31183 @node Restrictions on use of 64 bit objects
31184 @subsubsection Restrictions on use of 64-bit objects
31185
31186 @noindent
31187 Taking the address of an object allocated from a 64-bit storage pool,
31188 and then passing this address to a subprogram expecting
31189 @code{System.Short_Address},
31190 or assigning it to a variable of type @code{Short_Address}, will cause
31191 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31192 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31193 no exception is raised and execution
31194 will become erroneous.
31195
31196 @node Using 64 bit storage pools by default
31197 @subsubsection Using 64-bit storage pools by default
31198
31199 @noindent
31200 In some cases it may be desirable to have the compiler allocate
31201 from 64-bit storage pools by default. This may be the case for
31202 libraries that are 64-bit clean, but may be used in both 32-bit
31203 and 64-bit contexts. For these cases the following configuration
31204 pragma may be specified:
31205
31206 @smallexample @c ada
31207 pragma Pool_64_Default;
31208 @end smallexample
31209
31210 @noindent
31211 Any code compiled in the context of this pragma will by default
31212 use the @code{System.Pool_64} storage pool. This default may be overridden
31213 for a specific access type @code{T} by the representation clause:
31214
31215 @smallexample @c ada
31216 for T'Storage_Pool use System.Pool_32;
31217 @end smallexample
31218
31219 @noindent
31220 Any object whose address may be passed to a subprogram with a
31221 @code{Short_Address} argument, or assigned to a variable of type
31222 @code{Short_Address}, needs to be allocated from this pool.
31223
31224 @node General access types
31225 @subsubsection General access types
31226
31227 @noindent
31228 Objects designated by access values from a
31229 general access type (declared with @code{access all}) are never allocated
31230 from a 64-bit storage pool. Code that uses general access types will
31231 accept objects allocated in either 32-bit or 64-bit address spaces,
31232 but never allocate objects outside the 32-bit address space.
31233 Using general access types ensures maximum compatibility with both
31234 32-bit and 64-bit code.
31235
31236 @node STARLET and other predefined libraries
31237 @subsubsection STARLET and other predefined libraries
31238
31239 @noindent
31240 All code that comes as part of GNAT is 64-bit clean, but the
31241 restrictions given in @ref{Restrictions on use of 64 bit objects},
31242 still apply. Look at the package
31243 specs to see in which contexts objects allocated
31244 in 64-bit address space are acceptable.
31245
31246 @node Technical details
31247 @subsection Technical details
31248
31249 @noindent
31250 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31251 Ada standard with respect to the type of @code{System.Address}. Previous
31252 versions of GNAT Pro have defined this type as private and implemented it as a
31253 modular type.
31254
31255 In order to allow defining @code{System.Short_Address} as a proper subtype,
31256 and to match the implicit sign extension in parameter passing,
31257 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31258 visible (i.e., non-private) integer type.
31259 Standard operations on the type, such as the binary operators ``+'', ``-'',
31260 etc., that take @code{Address} operands and return an @code{Address} result,
31261 have been hidden by declaring these
31262 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31263 ambiguities that would otherwise result from overloading.
31264 (Note that, although @code{Address} is a visible integer type,
31265 good programming practice dictates against exploiting the type's
31266 integer properties such as literals, since this will compromise
31267 code portability.)
31268
31269 Defining @code{Address} as a visible integer type helps achieve
31270 maximum compatibility for existing Ada code,
31271 without sacrificing the capabilities of the 64-bit architecture.
31272 @end ifset
31273
31274 @c ************************************************
31275 @ifset unw
31276 @node Microsoft Windows Topics
31277 @appendix Microsoft Windows Topics
31278 @cindex Windows NT
31279 @cindex Windows 95
31280 @cindex Windows 98
31281
31282 @noindent
31283 This chapter describes topics that are specific to the Microsoft Windows
31284 platforms (NT, 2000, and XP Professional).
31285
31286 @menu
31287 * Using GNAT on Windows::
31288 * Using a network installation of GNAT::
31289 * CONSOLE and WINDOWS subsystems::
31290 * Temporary Files::
31291 * Mixed-Language Programming on Windows::
31292 * Windows Calling Conventions::
31293 * Introduction to Dynamic Link Libraries (DLLs)::
31294 * Using DLLs with GNAT::
31295 * Building DLLs with GNAT::
31296 * Building DLLs with GNAT Project files::
31297 * Building DLLs with gnatdll::
31298 * GNAT and Windows Resources::
31299 * Debugging a DLL::
31300 * Setting Stack Size from gnatlink::
31301 * Setting Heap Size from gnatlink::
31302 @end menu
31303
31304 @node Using GNAT on Windows
31305 @section Using GNAT on Windows
31306
31307 @noindent
31308 One of the strengths of the GNAT technology is that its tool set
31309 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31310 @code{gdb} debugger, etc.) is used in the same way regardless of the
31311 platform.
31312
31313 On Windows this tool set is complemented by a number of Microsoft-specific
31314 tools that have been provided to facilitate interoperability with Windows
31315 when this is required. With these tools:
31316
31317 @itemize @bullet
31318
31319 @item
31320 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31321 subsystems.
31322
31323 @item
31324 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31325 relocatable and non-relocatable DLLs are supported).
31326
31327 @item
31328 You can build Ada DLLs for use in other applications. These applications
31329 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31330 relocatable and non-relocatable Ada DLLs are supported.
31331
31332 @item
31333 You can include Windows resources in your Ada application.
31334
31335 @item
31336 You can use or create COM/DCOM objects.
31337 @end itemize
31338
31339 @noindent
31340 Immediately below are listed all known general GNAT-for-Windows restrictions.
31341 Other restrictions about specific features like Windows Resources and DLLs
31342 are listed in separate sections below.
31343
31344 @itemize @bullet
31345
31346 @item
31347 It is not possible to use @code{GetLastError} and @code{SetLastError}
31348 when tasking, protected records, or exceptions are used. In these
31349 cases, in order to implement Ada semantics, the GNAT run-time system
31350 calls certain Win32 routines that set the last error variable to 0 upon
31351 success. It should be possible to use @code{GetLastError} and
31352 @code{SetLastError} when tasking, protected record, and exception
31353 features are not used, but it is not guaranteed to work.
31354
31355 @item
31356 It is not possible to link against Microsoft libraries except for
31357 import libraries. The library must be built to be compatible with
31358 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31359 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31360 not be compatible with the GNAT runtime. Even if the library is
31361 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31362
31363 @item
31364 When the compilation environment is located on FAT32 drives, users may
31365 experience recompilations of the source files that have not changed if
31366 Daylight Saving Time (DST) state has changed since the last time files
31367 were compiled. NTFS drives do not have this problem.
31368
31369 @item
31370 No components of the GNAT toolset use any entries in the Windows
31371 registry. The only entries that can be created are file associations and
31372 PATH settings, provided the user has chosen to create them at installation
31373 time, as well as some minimal book-keeping information needed to correctly
31374 uninstall or integrate different GNAT products.
31375 @end itemize
31376
31377 @node Using a network installation of GNAT
31378 @section Using a network installation of GNAT
31379
31380 @noindent
31381 Make sure the system on which GNAT is installed is accessible from the
31382 current machine, i.e., the install location is shared over the network.
31383 Shared resources are accessed on Windows by means of UNC paths, which
31384 have the format @code{\\server\sharename\path}
31385
31386 In order to use such a network installation, simply add the UNC path of the
31387 @file{bin} directory of your GNAT installation in front of your PATH. For
31388 example, if GNAT is installed in @file{\GNAT} directory of a share location
31389 called @file{c-drive} on a machine @file{LOKI}, the following command will
31390 make it available:
31391
31392 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31393
31394 Be aware that every compilation using the network installation results in the
31395 transfer of large amounts of data across the network and will likely cause
31396 serious performance penalty.
31397
31398 @node CONSOLE and WINDOWS subsystems
31399 @section CONSOLE and WINDOWS subsystems
31400 @cindex CONSOLE Subsystem
31401 @cindex WINDOWS Subsystem
31402 @cindex -mwindows
31403
31404 @noindent
31405 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31406 (which is the default subsystem) will always create a console when
31407 launching the application. This is not something desirable when the
31408 application has a Windows GUI. To get rid of this console the
31409 application must be using the @code{WINDOWS} subsystem. To do so
31410 the @option{-mwindows} linker option must be specified.
31411
31412 @smallexample
31413 $ gnatmake winprog -largs -mwindows
31414 @end smallexample
31415
31416 @node Temporary Files
31417 @section Temporary Files
31418 @cindex Temporary files
31419
31420 @noindent
31421 It is possible to control where temporary files gets created by setting
31422 the @env{TMP} environment variable. The file will be created:
31423
31424 @itemize
31425 @item Under the directory pointed to by the @env{TMP} environment variable if
31426 this directory exists.
31427
31428 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31429 set (or not pointing to a directory) and if this directory exists.
31430
31431 @item Under the current working directory otherwise.
31432 @end itemize
31433
31434 @noindent
31435 This allows you to determine exactly where the temporary
31436 file will be created. This is particularly useful in networked
31437 environments where you may not have write access to some
31438 directories.
31439
31440 @node Mixed-Language Programming on Windows
31441 @section Mixed-Language Programming on Windows
31442
31443 @noindent
31444 Developing pure Ada applications on Windows is no different than on
31445 other GNAT-supported platforms. However, when developing or porting an
31446 application that contains a mix of Ada and C/C++, the choice of your
31447 Windows C/C++ development environment conditions your overall
31448 interoperability strategy.
31449
31450 If you use @command{gcc} to compile the non-Ada part of your application,
31451 there are no Windows-specific restrictions that affect the overall
31452 interoperability with your Ada code. If you plan to use
31453 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31454 the following limitations:
31455
31456 @itemize @bullet
31457 @item
31458 You cannot link your Ada code with an object or library generated with
31459 Microsoft tools if these use the @code{.tls} section (Thread Local
31460 Storage section) since the GNAT linker does not yet support this section.
31461
31462 @item
31463 You cannot link your Ada code with an object or library generated with
31464 Microsoft tools if these use I/O routines other than those provided in
31465 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31466 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31467 libraries can cause a conflict with @code{msvcrt.dll} services. For
31468 instance Visual C++ I/O stream routines conflict with those in
31469 @code{msvcrt.dll}.
31470 @end itemize
31471
31472 @noindent
31473 If you do want to use the Microsoft tools for your non-Ada code and hit one
31474 of the above limitations, you have two choices:
31475
31476 @enumerate
31477 @item
31478 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31479 application. In this case, use the Microsoft or whatever environment to
31480 build the DLL and use GNAT to build your executable
31481 (@pxref{Using DLLs with GNAT}).
31482
31483 @item
31484 Or you can encapsulate your Ada code in a DLL to be linked with the
31485 other part of your application. In this case, use GNAT to build the DLL
31486 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31487 environment to build your executable.
31488 @end enumerate
31489
31490 @node Windows Calling Conventions
31491 @section Windows Calling Conventions
31492 @findex Stdcall
31493 @findex APIENTRY
31494
31495 @menu
31496 * C Calling Convention::
31497 * Stdcall Calling Convention::
31498 * Win32 Calling Convention::
31499 * DLL Calling Convention::
31500 @end menu
31501
31502 @noindent
31503 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31504 (callee), there are several ways to push @code{G}'s parameters on the
31505 stack and there are several possible scenarios to clean up the stack
31506 upon @code{G}'s return. A calling convention is an agreed upon software
31507 protocol whereby the responsibilities between the caller (@code{F}) and
31508 the callee (@code{G}) are clearly defined. Several calling conventions
31509 are available for Windows:
31510
31511 @itemize @bullet
31512 @item
31513 @code{C} (Microsoft defined)
31514
31515 @item
31516 @code{Stdcall} (Microsoft defined)
31517
31518 @item
31519 @code{Win32} (GNAT specific)
31520
31521 @item
31522 @code{DLL} (GNAT specific)
31523 @end itemize
31524
31525 @node C Calling Convention
31526 @subsection @code{C} Calling Convention
31527
31528 @noindent
31529 This is the default calling convention used when interfacing to C/C++
31530 routines compiled with either @command{gcc} or Microsoft Visual C++.
31531
31532 In the @code{C} calling convention subprogram parameters are pushed on the
31533 stack by the caller from right to left. The caller itself is in charge of
31534 cleaning up the stack after the call. In addition, the name of a routine
31535 with @code{C} calling convention is mangled by adding a leading underscore.
31536
31537 The name to use on the Ada side when importing (or exporting) a routine
31538 with @code{C} calling convention is the name of the routine. For
31539 instance the C function:
31540
31541 @smallexample
31542 int get_val (long);
31543 @end smallexample
31544
31545 @noindent
31546 should be imported from Ada as follows:
31547
31548 @smallexample @c ada
31549 @group
31550 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31551 pragma Import (C, Get_Val, External_Name => "get_val");
31552 @end group
31553 @end smallexample
31554
31555 @noindent
31556 Note that in this particular case the @code{External_Name} parameter could
31557 have been omitted since, when missing, this parameter is taken to be the
31558 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31559 is missing, as in the above example, this parameter is set to be the
31560 @code{External_Name} with a leading underscore.
31561
31562 When importing a variable defined in C, you should always use the @code{C}
31563 calling convention unless the object containing the variable is part of a
31564 DLL (in which case you should use the @code{Stdcall} calling
31565 convention, @pxref{Stdcall Calling Convention}).
31566
31567 @node Stdcall Calling Convention
31568 @subsection @code{Stdcall} Calling Convention
31569
31570 @noindent
31571 This convention, which was the calling convention used for Pascal
31572 programs, is used by Microsoft for all the routines in the Win32 API for
31573 efficiency reasons. It must be used to import any routine for which this
31574 convention was specified.
31575
31576 In the @code{Stdcall} calling convention subprogram parameters are pushed
31577 on the stack by the caller from right to left. The callee (and not the
31578 caller) is in charge of cleaning the stack on routine exit. In addition,
31579 the name of a routine with @code{Stdcall} calling convention is mangled by
31580 adding a leading underscore (as for the @code{C} calling convention) and a
31581 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31582 bytes) of the parameters passed to the routine.
31583
31584 The name to use on the Ada side when importing a C routine with a
31585 @code{Stdcall} calling convention is the name of the C routine. The leading
31586 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31587 the compiler. For instance the Win32 function:
31588
31589 @smallexample
31590 @b{APIENTRY} int get_val (long);
31591 @end smallexample
31592
31593 @noindent
31594 should be imported from Ada as follows:
31595
31596 @smallexample @c ada
31597 @group
31598 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31599 pragma Import (Stdcall, Get_Val);
31600 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31601 @end group
31602 @end smallexample
31603
31604 @noindent
31605 As for the @code{C} calling convention, when the @code{External_Name}
31606 parameter is missing, it is taken to be the name of the Ada entity in lower
31607 case. If instead of writing the above import pragma you write:
31608
31609 @smallexample @c ada
31610 @group
31611 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31612 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31613 @end group
31614 @end smallexample
31615
31616 @noindent
31617 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31618 of specifying the @code{External_Name} parameter you specify the
31619 @code{Link_Name} as in the following example:
31620
31621 @smallexample @c ada
31622 @group
31623 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31624 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31625 @end group
31626 @end smallexample
31627
31628 @noindent
31629 then the imported routine is @code{retrieve_val}, that is, there is no
31630 decoration at all. No leading underscore and no Stdcall suffix
31631 @code{@@}@code{@var{nn}}.
31632
31633 @noindent
31634 This is especially important as in some special cases a DLL's entry
31635 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31636 name generated for a call has it.
31637
31638 @noindent
31639 It is also possible to import variables defined in a DLL by using an
31640 import pragma for a variable. As an example, if a DLL contains a
31641 variable defined as:
31642
31643 @smallexample
31644 int my_var;
31645 @end smallexample
31646
31647 @noindent
31648 then, to access this variable from Ada you should write:
31649
31650 @smallexample @c ada
31651 @group
31652 My_Var : Interfaces.C.int;
31653 pragma Import (Stdcall, My_Var);
31654 @end group
31655 @end smallexample
31656
31657 @noindent
31658 Note that to ease building cross-platform bindings this convention
31659 will be handled as a @code{C} calling convention on non-Windows platforms.
31660
31661 @node Win32 Calling Convention
31662 @subsection @code{Win32} Calling Convention
31663
31664 @noindent
31665 This convention, which is GNAT-specific is fully equivalent to the
31666 @code{Stdcall} calling convention described above.
31667
31668 @node DLL Calling Convention
31669 @subsection @code{DLL} Calling Convention
31670
31671 @noindent
31672 This convention, which is GNAT-specific is fully equivalent to the
31673 @code{Stdcall} calling convention described above.
31674
31675 @node Introduction to Dynamic Link Libraries (DLLs)
31676 @section Introduction to Dynamic Link Libraries (DLLs)
31677 @findex DLL
31678
31679 @noindent
31680 A Dynamically Linked Library (DLL) is a library that can be shared by
31681 several applications running under Windows. A DLL can contain any number of
31682 routines and variables.
31683
31684 One advantage of DLLs is that you can change and enhance them without
31685 forcing all the applications that depend on them to be relinked or
31686 recompiled. However, you should be aware than all calls to DLL routines are
31687 slower since, as you will understand below, such calls are indirect.
31688
31689 To illustrate the remainder of this section, suppose that an application
31690 wants to use the services of a DLL @file{API.dll}. To use the services
31691 provided by @file{API.dll} you must statically link against the DLL or
31692 an import library which contains a jump table with an entry for each
31693 routine and variable exported by the DLL. In the Microsoft world this
31694 import library is called @file{API.lib}. When using GNAT this import
31695 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31696 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31697
31698 After you have linked your application with the DLL or the import library
31699 and you run your application, here is what happens:
31700
31701 @enumerate
31702 @item
31703 Your application is loaded into memory.
31704
31705 @item
31706 The DLL @file{API.dll} is mapped into the address space of your
31707 application. This means that:
31708
31709 @itemize @bullet
31710 @item
31711 The DLL will use the stack of the calling thread.
31712
31713 @item
31714 The DLL will use the virtual address space of the calling process.
31715
31716 @item
31717 The DLL will allocate memory from the virtual address space of the calling
31718 process.
31719
31720 @item
31721 Handles (pointers) can be safely exchanged between routines in the DLL
31722 routines and routines in the application using the DLL.
31723 @end itemize
31724
31725 @item
31726 The entries in the jump table (from the import library @file{libAPI.dll.a}
31727 or @file{API.lib} or automatically created when linking against a DLL)
31728 which is part of your application are initialized with the addresses
31729 of the routines and variables in @file{API.dll}.
31730
31731 @item
31732 If present in @file{API.dll}, routines @code{DllMain} or
31733 @code{DllMainCRTStartup} are invoked. These routines typically contain
31734 the initialization code needed for the well-being of the routines and
31735 variables exported by the DLL.
31736 @end enumerate
31737
31738 @noindent
31739 There is an additional point which is worth mentioning. In the Windows
31740 world there are two kind of DLLs: relocatable and non-relocatable
31741 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31742 in the target application address space. If the addresses of two
31743 non-relocatable DLLs overlap and these happen to be used by the same
31744 application, a conflict will occur and the application will run
31745 incorrectly. Hence, when possible, it is always preferable to use and
31746 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31747 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31748 User's Guide) removes the debugging symbols from the DLL but the DLL can
31749 still be relocated.
31750
31751 As a side note, an interesting difference between Microsoft DLLs and
31752 Unix shared libraries, is the fact that on most Unix systems all public
31753 routines are exported by default in a Unix shared library, while under
31754 Windows it is possible (but not required) to list exported routines in
31755 a definition file (@pxref{The Definition File}).
31756
31757 @node Using DLLs with GNAT
31758 @section Using DLLs with GNAT
31759
31760 @menu
31761 * Creating an Ada Spec for the DLL Services::
31762 * Creating an Import Library::
31763 @end menu
31764
31765 @noindent
31766 To use the services of a DLL, say @file{API.dll}, in your Ada application
31767 you must have:
31768
31769 @enumerate
31770 @item
31771 The Ada spec for the routines and/or variables you want to access in
31772 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31773 header files provided with the DLL.
31774
31775 @item
31776 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31777 mentioned an import library is a statically linked library containing the
31778 import table which will be filled at load time to point to the actual
31779 @file{API.dll} routines. Sometimes you don't have an import library for the
31780 DLL you want to use. The following sections will explain how to build
31781 one. Note that this is optional.
31782
31783 @item
31784 The actual DLL, @file{API.dll}.
31785 @end enumerate
31786
31787 @noindent
31788 Once you have all the above, to compile an Ada application that uses the
31789 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31790 you simply issue the command
31791
31792 @smallexample
31793 $ gnatmake my_ada_app -largs -lAPI
31794 @end smallexample
31795
31796 @noindent
31797 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31798 tells the GNAT linker to look first for a library named @file{API.lib}
31799 (Microsoft-style name) and if not found for a libraries named
31800 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31801 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31802 contains the following pragma
31803
31804 @smallexample @c ada
31805 pragma Linker_Options ("-lAPI");
31806 @end smallexample
31807
31808 @noindent
31809 you do not have to add @option{-largs -lAPI} at the end of the
31810 @command{gnatmake} command.
31811
31812 If any one of the items above is missing you will have to create it
31813 yourself. The following sections explain how to do so using as an
31814 example a fictitious DLL called @file{API.dll}.
31815
31816 @node Creating an Ada Spec for the DLL Services
31817 @subsection Creating an Ada Spec for the DLL Services
31818
31819 @noindent
31820 A DLL typically comes with a C/C++ header file which provides the
31821 definitions of the routines and variables exported by the DLL. The Ada
31822 equivalent of this header file is a package spec that contains definitions
31823 for the imported entities. If the DLL you intend to use does not come with
31824 an Ada spec you have to generate one such spec yourself. For example if
31825 the header file of @file{API.dll} is a file @file{api.h} containing the
31826 following two definitions:
31827
31828 @smallexample
31829 @group
31830 @cartouche
31831 int some_var;
31832 int get (char *);
31833 @end cartouche
31834 @end group
31835 @end smallexample
31836
31837 @noindent
31838 then the equivalent Ada spec could be:
31839
31840 @smallexample @c ada
31841 @group
31842 @cartouche
31843 with Interfaces.C.Strings;
31844 package API is
31845 use Interfaces;
31846
31847 Some_Var : C.int;
31848 function Get (Str : C.Strings.Chars_Ptr) return C.int;
31849
31850 private
31851 pragma Import (C, Get);
31852 pragma Import (DLL, Some_Var);
31853 end API;
31854 @end cartouche
31855 @end group
31856 @end smallexample
31857
31858 @noindent
31859 Note that a variable is
31860 @strong{always imported with a Stdcall convention}. A function
31861 can have @code{C} or @code{Stdcall} convention.
31862 (@pxref{Windows Calling Conventions}).
31863
31864 @node Creating an Import Library
31865 @subsection Creating an Import Library
31866 @cindex Import library
31867
31868 @menu
31869 * The Definition File::
31870 * GNAT-Style Import Library::
31871 * Microsoft-Style Import Library::
31872 @end menu
31873
31874 @noindent
31875 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31876 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31877 with @file{API.dll} you can skip this section. You can also skip this
31878 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31879 as in this case it is possible to link directly against the
31880 DLL. Otherwise read on.
31881
31882 @node The Definition File
31883 @subsubsection The Definition File
31884 @cindex Definition file
31885 @findex .def
31886
31887 @noindent
31888 As previously mentioned, and unlike Unix systems, the list of symbols
31889 that are exported from a DLL must be provided explicitly in Windows.
31890 The main goal of a definition file is precisely that: list the symbols
31891 exported by a DLL. A definition file (usually a file with a @code{.def}
31892 suffix) has the following structure:
31893
31894 @smallexample
31895 @group
31896 @cartouche
31897 @r{[}LIBRARY @var{name}@r{]}
31898 @r{[}DESCRIPTION @var{string}@r{]}
31899 EXPORTS
31900 @var{symbol1}
31901 @var{symbol2}
31902 @dots{}
31903 @end cartouche
31904 @end group
31905 @end smallexample
31906
31907 @table @code
31908 @item LIBRARY @var{name}
31909 This section, which is optional, gives the name of the DLL.
31910
31911 @item DESCRIPTION @var{string}
31912 This section, which is optional, gives a description string that will be
31913 embedded in the import library.
31914
31915 @item EXPORTS
31916 This section gives the list of exported symbols (procedures, functions or
31917 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31918 section of @file{API.def} looks like:
31919
31920 @smallexample
31921 @group
31922 @cartouche
31923 EXPORTS
31924 some_var
31925 get
31926 @end cartouche
31927 @end group
31928 @end smallexample
31929 @end table
31930
31931 @noindent
31932 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31933 (@pxref{Windows Calling Conventions}) for a Stdcall
31934 calling convention function in the exported symbols list.
31935
31936 @noindent
31937 There can actually be other sections in a definition file, but these
31938 sections are not relevant to the discussion at hand.
31939
31940 @node GNAT-Style Import Library
31941 @subsubsection GNAT-Style Import Library
31942
31943 @noindent
31944 To create a static import library from @file{API.dll} with the GNAT tools
31945 you should proceed as follows:
31946
31947 @enumerate
31948 @item
31949 Create the definition file @file{API.def} (@pxref{The Definition File}).
31950 For that use the @code{dll2def} tool as follows:
31951
31952 @smallexample
31953 $ dll2def API.dll > API.def
31954 @end smallexample
31955
31956 @noindent
31957 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31958 to standard output the list of entry points in the DLL. Note that if
31959 some routines in the DLL have the @code{Stdcall} convention
31960 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31961 suffix then you'll have to edit @file{api.def} to add it, and specify
31962 @option{-k} to @command{gnatdll} when creating the import library.
31963
31964 @noindent
31965 Here are some hints to find the right @code{@@}@var{nn} suffix.
31966
31967 @enumerate
31968 @item
31969 If you have the Microsoft import library (.lib), it is possible to get
31970 the right symbols by using Microsoft @code{dumpbin} tool (see the
31971 corresponding Microsoft documentation for further details).
31972
31973 @smallexample
31974 $ dumpbin /exports api.lib
31975 @end smallexample
31976
31977 @item
31978 If you have a message about a missing symbol at link time the compiler
31979 tells you what symbol is expected. You just have to go back to the
31980 definition file and add the right suffix.
31981 @end enumerate
31982
31983 @item
31984 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31985 (@pxref{Using gnatdll}) as follows:
31986
31987 @smallexample
31988 $ gnatdll -e API.def -d API.dll
31989 @end smallexample
31990
31991 @noindent
31992 @code{gnatdll} takes as input a definition file @file{API.def} and the
31993 name of the DLL containing the services listed in the definition file
31994 @file{API.dll}. The name of the static import library generated is
31995 computed from the name of the definition file as follows: if the
31996 definition file name is @var{xyz}@code{.def}, the import library name will
31997 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31998 @option{-e} could have been removed because the name of the definition
31999 file (before the ``@code{.def}'' suffix) is the same as the name of the
32000 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32001 @end enumerate
32002
32003 @node Microsoft-Style Import Library
32004 @subsubsection Microsoft-Style Import Library
32005
32006 @noindent
32007 With GNAT you can either use a GNAT-style or Microsoft-style import
32008 library. A Microsoft import library is needed only if you plan to make an
32009 Ada DLL available to applications developed with Microsoft
32010 tools (@pxref{Mixed-Language Programming on Windows}).
32011
32012 To create a Microsoft-style import library for @file{API.dll} you
32013 should proceed as follows:
32014
32015 @enumerate
32016 @item
32017 Create the definition file @file{API.def} from the DLL. For this use either
32018 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32019 tool (see the corresponding Microsoft documentation for further details).
32020
32021 @item
32022 Build the actual import library using Microsoft's @code{lib} utility:
32023
32024 @smallexample
32025 $ lib -machine:IX86 -def:API.def -out:API.lib
32026 @end smallexample
32027
32028 @noindent
32029 If you use the above command the definition file @file{API.def} must
32030 contain a line giving the name of the DLL:
32031
32032 @smallexample
32033 LIBRARY "API"
32034 @end smallexample
32035
32036 @noindent
32037 See the Microsoft documentation for further details about the usage of
32038 @code{lib}.
32039 @end enumerate
32040
32041 @node Building DLLs with GNAT
32042 @section Building DLLs with GNAT
32043 @cindex DLLs, building
32044
32045 @noindent
32046 This section explain how to build DLLs using the GNAT built-in DLL
32047 support. With the following procedure it is straight forward to build
32048 and use DLLs with GNAT.
32049
32050 @enumerate
32051
32052 @item building object files
32053
32054 The first step is to build all objects files that are to be included
32055 into the DLL. This is done by using the standard @command{gnatmake} tool.
32056
32057 @item building the DLL
32058
32059 To build the DLL you must use @command{gcc}'s @option{-shared}
32060 option. It is quite simple to use this method:
32061
32062 @smallexample
32063 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32064 @end smallexample
32065
32066 It is important to note that in this case all symbols found in the
32067 object files are automatically exported. It is possible to restrict
32068 the set of symbols to export by passing to @command{gcc} a definition
32069 file, @pxref{The Definition File}. For example:
32070
32071 @smallexample
32072 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32073 @end smallexample
32074
32075 If you use a definition file you must export the elaboration procedures
32076 for every package that required one. Elaboration procedures are named
32077 using the package name followed by "_E".
32078
32079 @item preparing DLL to be used
32080
32081 For the DLL to be used by client programs the bodies must be hidden
32082 from it and the .ali set with read-only attribute. This is very important
32083 otherwise GNAT will recompile all packages and will not actually use
32084 the code in the DLL. For example:
32085
32086 @smallexample
32087 $ mkdir apilib
32088 $ copy *.ads *.ali api.dll apilib
32089 $ attrib +R apilib\*.ali
32090 @end smallexample
32091
32092 @end enumerate
32093
32094 At this point it is possible to use the DLL by directly linking
32095 against it. Note that you must use the GNAT shared runtime when using
32096 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32097 option.
32098
32099 @smallexample
32100 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32101 @end smallexample
32102
32103 @node Building DLLs with GNAT Project files
32104 @section Building DLLs with GNAT Project files
32105 @cindex DLLs, building
32106
32107 @noindent
32108 There is nothing specific to Windows in the build process.
32109 @pxref{Library Projects}.
32110
32111 @noindent
32112 Due to a system limitation, it is not possible under Windows to create threads
32113 when inside the @code{DllMain} routine which is used for auto-initialization
32114 of shared libraries, so it is not possible to have library level tasks in SALs.
32115
32116 @node Building DLLs with gnatdll
32117 @section Building DLLs with gnatdll
32118 @cindex DLLs, building
32119
32120 @menu
32121 * Limitations When Using Ada DLLs from Ada::
32122 * Exporting Ada Entities::
32123 * Ada DLLs and Elaboration::
32124 * Ada DLLs and Finalization::
32125 * Creating a Spec for Ada DLLs::
32126 * Creating the Definition File::
32127 * Using gnatdll::
32128 @end menu
32129
32130 @noindent
32131 Note that it is preferred to use the built-in GNAT DLL support
32132 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32133 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32134
32135 This section explains how to build DLLs containing Ada code using
32136 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32137 remainder of this section.
32138
32139 The steps required to build an Ada DLL that is to be used by Ada as well as
32140 non-Ada applications are as follows:
32141
32142 @enumerate
32143 @item
32144 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32145 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32146 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32147 skip this step if you plan to use the Ada DLL only from Ada applications.
32148
32149 @item
32150 Your Ada code must export an initialization routine which calls the routine
32151 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32152 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32153 routine exported by the Ada DLL must be invoked by the clients of the DLL
32154 to initialize the DLL.
32155
32156 @item
32157 When useful, the DLL should also export a finalization routine which calls
32158 routine @code{adafinal} generated by @command{gnatbind} to perform the
32159 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32160 The finalization routine exported by the Ada DLL must be invoked by the
32161 clients of the DLL when the DLL services are no further needed.
32162
32163 @item
32164 You must provide a spec for the services exported by the Ada DLL in each
32165 of the programming languages to which you plan to make the DLL available.
32166
32167 @item
32168 You must provide a definition file listing the exported entities
32169 (@pxref{The Definition File}).
32170
32171 @item
32172 Finally you must use @code{gnatdll} to produce the DLL and the import
32173 library (@pxref{Using gnatdll}).
32174 @end enumerate
32175
32176 @noindent
32177 Note that a relocatable DLL stripped using the @code{strip}
32178 binutils tool will not be relocatable anymore. To build a DLL without
32179 debug information pass @code{-largs -s} to @code{gnatdll}. This
32180 restriction does not apply to a DLL built using a Library Project.
32181 @pxref{Library Projects}.
32182
32183 @node Limitations When Using Ada DLLs from Ada
32184 @subsection Limitations When Using Ada DLLs from Ada
32185
32186 @noindent
32187 When using Ada DLLs from Ada applications there is a limitation users
32188 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32189 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32190 each Ada DLL includes the services of the GNAT run time that are necessary
32191 to the Ada code inside the DLL. As a result, when an Ada program uses an
32192 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32193 one in the main program.
32194
32195 It is therefore not possible to exchange GNAT run-time objects between the
32196 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32197 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32198 types, etc.
32199
32200 It is completely safe to exchange plain elementary, array or record types,
32201 Windows object handles, etc.
32202
32203 @node Exporting Ada Entities
32204 @subsection Exporting Ada Entities
32205 @cindex Export table
32206
32207 @noindent
32208 Building a DLL is a way to encapsulate a set of services usable from any
32209 application. As a result, the Ada entities exported by a DLL should be
32210 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32211 any Ada name mangling. As an example here is an Ada package
32212 @code{API}, spec and body, exporting two procedures, a function, and a
32213 variable:
32214
32215 @smallexample @c ada
32216 @group
32217 @cartouche
32218 with Interfaces.C; use Interfaces;
32219 package API is
32220 Count : C.int := 0;
32221 function Factorial (Val : C.int) return C.int;
32222
32223 procedure Initialize_API;
32224 procedure Finalize_API;
32225 -- Initialization & Finalization routines. More in the next section.
32226 private
32227 pragma Export (C, Initialize_API);
32228 pragma Export (C, Finalize_API);
32229 pragma Export (C, Count);
32230 pragma Export (C, Factorial);
32231 end API;
32232 @end cartouche
32233 @end group
32234 @end smallexample
32235
32236 @smallexample @c ada
32237 @group
32238 @cartouche
32239 package body API is
32240 function Factorial (Val : C.int) return C.int is
32241 Fact : C.int := 1;
32242 begin
32243 Count := Count + 1;
32244 for K in 1 .. Val loop
32245 Fact := Fact * K;
32246 end loop;
32247 return Fact;
32248 end Factorial;
32249
32250 procedure Initialize_API is
32251 procedure Adainit;
32252 pragma Import (C, Adainit);
32253 begin
32254 Adainit;
32255 end Initialize_API;
32256
32257 procedure Finalize_API is
32258 procedure Adafinal;
32259 pragma Import (C, Adafinal);
32260 begin
32261 Adafinal;
32262 end Finalize_API;
32263 end API;
32264 @end cartouche
32265 @end group
32266 @end smallexample
32267
32268 @noindent
32269 If the Ada DLL you are building will only be used by Ada applications
32270 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32271 convention. As an example, the previous package could be written as
32272 follows:
32273
32274 @smallexample @c ada
32275 @group
32276 @cartouche
32277 package API is
32278 Count : Integer := 0;
32279 function Factorial (Val : Integer) return Integer;
32280
32281 procedure Initialize_API;
32282 procedure Finalize_API;
32283 -- Initialization and Finalization routines.
32284 end API;
32285 @end cartouche
32286 @end group
32287 @end smallexample
32288
32289 @smallexample @c ada
32290 @group
32291 @cartouche
32292 package body API is
32293 function Factorial (Val : Integer) return Integer is
32294 Fact : Integer := 1;
32295 begin
32296 Count := Count + 1;
32297 for K in 1 .. Val loop
32298 Fact := Fact * K;
32299 end loop;
32300 return Fact;
32301 end Factorial;
32302
32303 @dots{}
32304 -- The remainder of this package body is unchanged.
32305 end API;
32306 @end cartouche
32307 @end group
32308 @end smallexample
32309
32310 @noindent
32311 Note that if you do not export the Ada entities with a @code{C} or
32312 @code{Stdcall} convention you will have to provide the mangled Ada names
32313 in the definition file of the Ada DLL
32314 (@pxref{Creating the Definition File}).
32315
32316 @node Ada DLLs and Elaboration
32317 @subsection Ada DLLs and Elaboration
32318 @cindex DLLs and elaboration
32319
32320 @noindent
32321 The DLL that you are building contains your Ada code as well as all the
32322 routines in the Ada library that are needed by it. The first thing a
32323 user of your DLL must do is elaborate the Ada code
32324 (@pxref{Elaboration Order Handling in GNAT}).
32325
32326 To achieve this you must export an initialization routine
32327 (@code{Initialize_API} in the previous example), which must be invoked
32328 before using any of the DLL services. This elaboration routine must call
32329 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32330 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32331 @code{Initialize_Api} for an example. Note that the GNAT binder is
32332 automatically invoked during the DLL build process by the @code{gnatdll}
32333 tool (@pxref{Using gnatdll}).
32334
32335 When a DLL is loaded, Windows systematically invokes a routine called
32336 @code{DllMain}. It would therefore be possible to call @code{adainit}
32337 directly from @code{DllMain} without having to provide an explicit
32338 initialization routine. Unfortunately, it is not possible to call
32339 @code{adainit} from the @code{DllMain} if your program has library level
32340 tasks because access to the @code{DllMain} entry point is serialized by
32341 the system (that is, only a single thread can execute ``through'' it at a
32342 time), which means that the GNAT run time will deadlock waiting for the
32343 newly created task to complete its initialization.
32344
32345 @node Ada DLLs and Finalization
32346 @subsection Ada DLLs and Finalization
32347 @cindex DLLs and finalization
32348
32349 @noindent
32350 When the services of an Ada DLL are no longer needed, the client code should
32351 invoke the DLL finalization routine, if available. The DLL finalization
32352 routine is in charge of releasing all resources acquired by the DLL. In the
32353 case of the Ada code contained in the DLL, this is achieved by calling
32354 routine @code{adafinal} generated by the GNAT binder
32355 (@pxref{Binding with Non-Ada Main Programs}).
32356 See the body of @code{Finalize_Api} for an
32357 example. As already pointed out the GNAT binder is automatically invoked
32358 during the DLL build process by the @code{gnatdll} tool
32359 (@pxref{Using gnatdll}).
32360
32361 @node Creating a Spec for Ada DLLs
32362 @subsection Creating a Spec for Ada DLLs
32363
32364 @noindent
32365 To use the services exported by the Ada DLL from another programming
32366 language (e.g.@: C), you have to translate the specs of the exported Ada
32367 entities in that language. For instance in the case of @code{API.dll},
32368 the corresponding C header file could look like:
32369
32370 @smallexample
32371 @group
32372 @cartouche
32373 extern int *_imp__count;
32374 #define count (*_imp__count)
32375 int factorial (int);
32376 @end cartouche
32377 @end group
32378 @end smallexample
32379
32380 @noindent
32381 It is important to understand that when building an Ada DLL to be used by
32382 other Ada applications, you need two different specs for the packages
32383 contained in the DLL: one for building the DLL and the other for using
32384 the DLL. This is because the @code{DLL} calling convention is needed to
32385 use a variable defined in a DLL, but when building the DLL, the variable
32386 must have either the @code{Ada} or @code{C} calling convention. As an
32387 example consider a DLL comprising the following package @code{API}:
32388
32389 @smallexample @c ada
32390 @group
32391 @cartouche
32392 package API is
32393 Count : Integer := 0;
32394 @dots{}
32395 -- Remainder of the package omitted.
32396 end API;
32397 @end cartouche
32398 @end group
32399 @end smallexample
32400
32401 @noindent
32402 After producing a DLL containing package @code{API}, the spec that
32403 must be used to import @code{API.Count} from Ada code outside of the
32404 DLL is:
32405
32406 @smallexample @c ada
32407 @group
32408 @cartouche
32409 package API is
32410 Count : Integer;
32411 pragma Import (DLL, Count);
32412 end API;
32413 @end cartouche
32414 @end group
32415 @end smallexample
32416
32417 @node Creating the Definition File
32418 @subsection Creating the Definition File
32419
32420 @noindent
32421 The definition file is the last file needed to build the DLL. It lists
32422 the exported symbols. As an example, the definition file for a DLL
32423 containing only package @code{API} (where all the entities are exported
32424 with a @code{C} calling convention) is:
32425
32426 @smallexample
32427 @group
32428 @cartouche
32429 EXPORTS
32430 count
32431 factorial
32432 finalize_api
32433 initialize_api
32434 @end cartouche
32435 @end group
32436 @end smallexample
32437
32438 @noindent
32439 If the @code{C} calling convention is missing from package @code{API},
32440 then the definition file contains the mangled Ada names of the above
32441 entities, which in this case are:
32442
32443 @smallexample
32444 @group
32445 @cartouche
32446 EXPORTS
32447 api__count
32448 api__factorial
32449 api__finalize_api
32450 api__initialize_api
32451 @end cartouche
32452 @end group
32453 @end smallexample
32454
32455 @node Using gnatdll
32456 @subsection Using @code{gnatdll}
32457 @findex gnatdll
32458
32459 @menu
32460 * gnatdll Example::
32461 * gnatdll behind the Scenes::
32462 * Using dlltool::
32463 @end menu
32464
32465 @noindent
32466 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32467 and non-Ada sources that make up your DLL have been compiled.
32468 @code{gnatdll} is actually in charge of two distinct tasks: build the
32469 static import library for the DLL and the actual DLL. The form of the
32470 @code{gnatdll} command is
32471
32472 @smallexample
32473 @cartouche
32474 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32475 @end cartouche
32476 @end smallexample
32477
32478 @noindent
32479 where @var{list-of-files} is a list of ALI and object files. The object
32480 file list must be the exact list of objects corresponding to the non-Ada
32481 sources whose services are to be included in the DLL. The ALI file list
32482 must be the exact list of ALI files for the corresponding Ada sources
32483 whose services are to be included in the DLL. If @var{list-of-files} is
32484 missing, only the static import library is generated.
32485
32486 @noindent
32487 You may specify any of the following switches to @code{gnatdll}:
32488
32489 @table @code
32490 @item -a@ovar{address}
32491 @cindex @option{-a} (@code{gnatdll})
32492 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32493 specified the default address @var{0x11000000} will be used. By default,
32494 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32495 advise the reader to build relocatable DLL.
32496
32497 @item -b @var{address}
32498 @cindex @option{-b} (@code{gnatdll})
32499 Set the relocatable DLL base address. By default the address is
32500 @code{0x11000000}.
32501
32502 @item -bargs @var{opts}
32503 @cindex @option{-bargs} (@code{gnatdll})
32504 Binder options. Pass @var{opts} to the binder.
32505
32506 @item -d @var{dllfile}
32507 @cindex @option{-d} (@code{gnatdll})
32508 @var{dllfile} is the name of the DLL. This switch must be present for
32509 @code{gnatdll} to do anything. The name of the generated import library is
32510 obtained algorithmically from @var{dllfile} as shown in the following
32511 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32512 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32513 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32514 as shown in the following example:
32515 if @var{dllfile} is @code{xyz.dll}, the definition
32516 file used is @code{xyz.def}.
32517
32518 @item -e @var{deffile}
32519 @cindex @option{-e} (@code{gnatdll})
32520 @var{deffile} is the name of the definition file.
32521
32522 @item -g
32523 @cindex @option{-g} (@code{gnatdll})
32524 Generate debugging information. This information is stored in the object
32525 file and copied from there to the final DLL file by the linker,
32526 where it can be read by the debugger. You must use the
32527 @option{-g} switch if you plan on using the debugger or the symbolic
32528 stack traceback.
32529
32530 @item -h
32531 @cindex @option{-h} (@code{gnatdll})
32532 Help mode. Displays @code{gnatdll} switch usage information.
32533
32534 @item -Idir
32535 @cindex @option{-I} (@code{gnatdll})
32536 Direct @code{gnatdll} to search the @var{dir} directory for source and
32537 object files needed to build the DLL.
32538 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32539
32540 @item -k
32541 @cindex @option{-k} (@code{gnatdll})
32542 Removes the @code{@@}@var{nn} suffix from the import library's exported
32543 names, but keeps them for the link names. You must specify this
32544 option if you want to use a @code{Stdcall} function in a DLL for which
32545 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32546 of the Windows NT DLL for example. This option has no effect when
32547 @option{-n} option is specified.
32548
32549 @item -l @var{file}
32550 @cindex @option{-l} (@code{gnatdll})
32551 The list of ALI and object files used to build the DLL are listed in
32552 @var{file}, instead of being given in the command line. Each line in
32553 @var{file} contains the name of an ALI or object file.
32554
32555 @item -n
32556 @cindex @option{-n} (@code{gnatdll})
32557 No Import. Do not create the import library.
32558
32559 @item -q
32560 @cindex @option{-q} (@code{gnatdll})
32561 Quiet mode. Do not display unnecessary messages.
32562
32563 @item -v
32564 @cindex @option{-v} (@code{gnatdll})
32565 Verbose mode. Display extra information.
32566
32567 @item -largs @var{opts}
32568 @cindex @option{-largs} (@code{gnatdll})
32569 Linker options. Pass @var{opts} to the linker.
32570 @end table
32571
32572 @node gnatdll Example
32573 @subsubsection @code{gnatdll} Example
32574
32575 @noindent
32576 As an example the command to build a relocatable DLL from @file{api.adb}
32577 once @file{api.adb} has been compiled and @file{api.def} created is
32578
32579 @smallexample
32580 $ gnatdll -d api.dll api.ali
32581 @end smallexample
32582
32583 @noindent
32584 The above command creates two files: @file{libapi.dll.a} (the import
32585 library) and @file{api.dll} (the actual DLL). If you want to create
32586 only the DLL, just type:
32587
32588 @smallexample
32589 $ gnatdll -d api.dll -n api.ali
32590 @end smallexample
32591
32592 @noindent
32593 Alternatively if you want to create just the import library, type:
32594
32595 @smallexample
32596 $ gnatdll -d api.dll
32597 @end smallexample
32598
32599 @node gnatdll behind the Scenes
32600 @subsubsection @code{gnatdll} behind the Scenes
32601
32602 @noindent
32603 This section details the steps involved in creating a DLL. @code{gnatdll}
32604 does these steps for you. Unless you are interested in understanding what
32605 goes on behind the scenes, you should skip this section.
32606
32607 We use the previous example of a DLL containing the Ada package @code{API},
32608 to illustrate the steps necessary to build a DLL. The starting point is a
32609 set of objects that will make up the DLL and the corresponding ALI
32610 files. In the case of this example this means that @file{api.o} and
32611 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32612 the following:
32613
32614 @enumerate
32615 @item
32616 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32617 the information necessary to generate relocation information for the
32618 DLL.
32619
32620 @smallexample
32621 @group
32622 $ gnatbind -n api
32623 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32624 @end group
32625 @end smallexample
32626
32627 @noindent
32628 In addition to the base file, the @command{gnatlink} command generates an
32629 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32630 asks @command{gnatlink} to generate the routines @code{DllMain} and
32631 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32632 is loaded into memory.
32633
32634 @item
32635 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32636 export table (@file{api.exp}). The export table contains the relocation
32637 information in a form which can be used during the final link to ensure
32638 that the Windows loader is able to place the DLL anywhere in memory.
32639
32640 @smallexample
32641 @group
32642 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32643 --output-exp api.exp
32644 @end group
32645 @end smallexample
32646
32647 @item
32648 @code{gnatdll} builds the base file using the new export table. Note that
32649 @command{gnatbind} must be called once again since the binder generated file
32650 has been deleted during the previous call to @command{gnatlink}.
32651
32652 @smallexample
32653 @group
32654 $ gnatbind -n api
32655 $ gnatlink api -o api.jnk api.exp -mdll
32656 -Wl,--base-file,api.base
32657 @end group
32658 @end smallexample
32659
32660 @item
32661 @code{gnatdll} builds the new export table using the new base file and
32662 generates the DLL import library @file{libAPI.dll.a}.
32663
32664 @smallexample
32665 @group
32666 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32667 --output-exp api.exp --output-lib libAPI.a
32668 @end group
32669 @end smallexample
32670
32671 @item
32672 Finally @code{gnatdll} builds the relocatable DLL using the final export
32673 table.
32674
32675 @smallexample
32676 @group
32677 $ gnatbind -n api
32678 $ gnatlink api api.exp -o api.dll -mdll
32679 @end group
32680 @end smallexample
32681 @end enumerate
32682
32683 @node Using dlltool
32684 @subsubsection Using @code{dlltool}
32685
32686 @noindent
32687 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32688 DLLs and static import libraries. This section summarizes the most
32689 common @code{dlltool} switches. The form of the @code{dlltool} command
32690 is
32691
32692 @smallexample
32693 $ dlltool @ovar{switches}
32694 @end smallexample
32695
32696 @noindent
32697 @code{dlltool} switches include:
32698
32699 @table @option
32700 @item --base-file @var{basefile}
32701 @cindex @option{--base-file} (@command{dlltool})
32702 Read the base file @var{basefile} generated by the linker. This switch
32703 is used to create a relocatable DLL.
32704
32705 @item --def @var{deffile}
32706 @cindex @option{--def} (@command{dlltool})
32707 Read the definition file.
32708
32709 @item --dllname @var{name}
32710 @cindex @option{--dllname} (@command{dlltool})
32711 Gives the name of the DLL. This switch is used to embed the name of the
32712 DLL in the static import library generated by @code{dlltool} with switch
32713 @option{--output-lib}.
32714
32715 @item -k
32716 @cindex @option{-k} (@command{dlltool})
32717 Kill @code{@@}@var{nn} from exported names
32718 (@pxref{Windows Calling Conventions}
32719 for a discussion about @code{Stdcall}-style symbols.
32720
32721 @item --help
32722 @cindex @option{--help} (@command{dlltool})
32723 Prints the @code{dlltool} switches with a concise description.
32724
32725 @item --output-exp @var{exportfile}
32726 @cindex @option{--output-exp} (@command{dlltool})
32727 Generate an export file @var{exportfile}. The export file contains the
32728 export table (list of symbols in the DLL) and is used to create the DLL.
32729
32730 @item --output-lib @var{libfile}
32731 @cindex @option{--output-lib} (@command{dlltool})
32732 Generate a static import library @var{libfile}.
32733
32734 @item -v
32735 @cindex @option{-v} (@command{dlltool})
32736 Verbose mode.
32737
32738 @item --as @var{assembler-name}
32739 @cindex @option{--as} (@command{dlltool})
32740 Use @var{assembler-name} as the assembler. The default is @code{as}.
32741 @end table
32742
32743 @node GNAT and Windows Resources
32744 @section GNAT and Windows Resources
32745 @cindex Resources, windows
32746
32747 @menu
32748 * Building Resources::
32749 * Compiling Resources::
32750 * Using Resources::
32751 @end menu
32752
32753 @noindent
32754 Resources are an easy way to add Windows specific objects to your
32755 application. The objects that can be added as resources include:
32756
32757 @itemize @bullet
32758 @item
32759 menus
32760
32761 @item
32762 accelerators
32763
32764 @item
32765 dialog boxes
32766
32767 @item
32768 string tables
32769
32770 @item
32771 bitmaps
32772
32773 @item
32774 cursors
32775
32776 @item
32777 icons
32778
32779 @item
32780 fonts
32781 @end itemize
32782
32783 @noindent
32784 This section explains how to build, compile and use resources.
32785
32786 @node Building Resources
32787 @subsection Building Resources
32788 @cindex Resources, building
32789
32790 @noindent
32791 A resource file is an ASCII file. By convention resource files have an
32792 @file{.rc} extension.
32793 The easiest way to build a resource file is to use Microsoft tools
32794 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32795 @code{dlgedit.exe} to build dialogs.
32796 It is always possible to build an @file{.rc} file yourself by writing a
32797 resource script.
32798
32799 It is not our objective to explain how to write a resource file. A
32800 complete description of the resource script language can be found in the
32801 Microsoft documentation.
32802
32803 @node Compiling Resources
32804 @subsection Compiling Resources
32805 @findex rc
32806 @findex windres
32807 @cindex Resources, compiling
32808
32809 @noindent
32810 This section describes how to build a GNAT-compatible (COFF) object file
32811 containing the resources. This is done using the Resource Compiler
32812 @code{windres} as follows:
32813
32814 @smallexample
32815 $ windres -i myres.rc -o myres.o
32816 @end smallexample
32817
32818 @noindent
32819 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32820 file. You can specify an alternate preprocessor (usually named
32821 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32822 parameter. A list of all possible options may be obtained by entering
32823 the command @code{windres} @option{--help}.
32824
32825 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32826 to produce a @file{.res} file (binary resource file). See the
32827 corresponding Microsoft documentation for further details. In this case
32828 you need to use @code{windres} to translate the @file{.res} file to a
32829 GNAT-compatible object file as follows:
32830
32831 @smallexample
32832 $ windres -i myres.res -o myres.o
32833 @end smallexample
32834
32835 @node Using Resources
32836 @subsection Using Resources
32837 @cindex Resources, using
32838
32839 @noindent
32840 To include the resource file in your program just add the
32841 GNAT-compatible object file for the resource(s) to the linker
32842 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32843 option:
32844
32845 @smallexample
32846 $ gnatmake myprog -largs myres.o
32847 @end smallexample
32848
32849 @node Debugging a DLL
32850 @section Debugging a DLL
32851 @cindex DLL debugging
32852
32853 @menu
32854 * Program and DLL Both Built with GCC/GNAT::
32855 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32856 @end menu
32857
32858 @noindent
32859 Debugging a DLL is similar to debugging a standard program. But
32860 we have to deal with two different executable parts: the DLL and the
32861 program that uses it. We have the following four possibilities:
32862
32863 @enumerate 1
32864 @item
32865 The program and the DLL are built with @code{GCC/GNAT}.
32866 @item
32867 The program is built with foreign tools and the DLL is built with
32868 @code{GCC/GNAT}.
32869 @item
32870 The program is built with @code{GCC/GNAT} and the DLL is built with
32871 foreign tools.
32872 @item
32873 @end enumerate
32874
32875 @noindent
32876 In this section we address only cases one and two above.
32877 There is no point in trying to debug
32878 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32879 information in it. To do so you must use a debugger compatible with the
32880 tools suite used to build the DLL.
32881
32882 @node Program and DLL Both Built with GCC/GNAT
32883 @subsection Program and DLL Both Built with GCC/GNAT
32884
32885 @noindent
32886 This is the simplest case. Both the DLL and the program have @code{GDB}
32887 compatible debugging information. It is then possible to break anywhere in
32888 the process. Let's suppose here that the main procedure is named
32889 @code{ada_main} and that in the DLL there is an entry point named
32890 @code{ada_dll}.
32891
32892 @noindent
32893 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32894 program must have been built with the debugging information (see GNAT -g
32895 switch). Here are the step-by-step instructions for debugging it:
32896
32897 @enumerate 1
32898 @item Launch @code{GDB} on the main program.
32899
32900 @smallexample
32901 $ gdb -nw ada_main
32902 @end smallexample
32903
32904 @item Start the program and stop at the beginning of the main procedure
32905
32906 @smallexample
32907 (gdb) start
32908 @end smallexample
32909
32910 @noindent
32911 This step is required to be able to set a breakpoint inside the DLL. As long
32912 as the program is not run, the DLL is not loaded. This has the
32913 consequence that the DLL debugging information is also not loaded, so it is not
32914 possible to set a breakpoint in the DLL.
32915
32916 @item Set a breakpoint inside the DLL
32917
32918 @smallexample
32919 (gdb) break ada_dll
32920 (gdb) cont
32921 @end smallexample
32922
32923 @end enumerate
32924
32925 @noindent
32926 At this stage a breakpoint is set inside the DLL. From there on
32927 you can use the standard approach to debug the whole program
32928 (@pxref{Running and Debugging Ada Programs}).
32929
32930 @ignore
32931 @c This used to work, probably because the DLLs were non-relocatable
32932 @c keep this section around until the problem is sorted out.
32933
32934 To break on the @code{DllMain} routine it is not possible to follow
32935 the procedure above. At the time the program stop on @code{ada_main}
32936 the @code{DllMain} routine as already been called. Either you can use
32937 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32938
32939 @enumerate 1
32940 @item Launch @code{GDB} on the main program.
32941
32942 @smallexample
32943 $ gdb ada_main
32944 @end smallexample
32945
32946 @item Load DLL symbols
32947
32948 @smallexample
32949 (gdb) add-sym api.dll
32950 @end smallexample
32951
32952 @item Set a breakpoint inside the DLL
32953
32954 @smallexample
32955 (gdb) break ada_dll.adb:45
32956 @end smallexample
32957
32958 Note that at this point it is not possible to break using the routine symbol
32959 directly as the program is not yet running. The solution is to break
32960 on the proper line (break in @file{ada_dll.adb} line 45).
32961
32962 @item Start the program
32963
32964 @smallexample
32965 (gdb) run
32966 @end smallexample
32967
32968 @end enumerate
32969 @end ignore
32970
32971 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32972 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32973
32974 @menu
32975 * Debugging the DLL Directly::
32976 * Attaching to a Running Process::
32977 @end menu
32978
32979 @noindent
32980 In this case things are slightly more complex because it is not possible to
32981 start the main program and then break at the beginning to load the DLL and the
32982 associated DLL debugging information. It is not possible to break at the
32983 beginning of the program because there is no @code{GDB} debugging information,
32984 and therefore there is no direct way of getting initial control. This
32985 section addresses this issue by describing some methods that can be used
32986 to break somewhere in the DLL to debug it.
32987
32988 @noindent
32989 First suppose that the main procedure is named @code{main} (this is for
32990 example some C code built with Microsoft Visual C) and that there is a
32991 DLL named @code{test.dll} containing an Ada entry point named
32992 @code{ada_dll}.
32993
32994 @noindent
32995 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32996 been built with debugging information (see GNAT -g option).
32997
32998 @node Debugging the DLL Directly
32999 @subsubsection Debugging the DLL Directly
33000
33001 @enumerate 1
33002 @item
33003 Find out the executable starting address
33004
33005 @smallexample
33006 $ objdump --file-header main.exe
33007 @end smallexample
33008
33009 The starting address is reported on the last line. For example:
33010
33011 @smallexample
33012 main.exe: file format pei-i386
33013 architecture: i386, flags 0x0000010a:
33014 EXEC_P, HAS_DEBUG, D_PAGED
33015 start address 0x00401010
33016 @end smallexample
33017
33018 @item
33019 Launch the debugger on the executable.
33020
33021 @smallexample
33022 $ gdb main.exe
33023 @end smallexample
33024
33025 @item
33026 Set a breakpoint at the starting address, and launch the program.
33027
33028 @smallexample
33029 $ (gdb) break *0x00401010
33030 $ (gdb) run
33031 @end smallexample
33032
33033 The program will stop at the given address.
33034
33035 @item
33036 Set a breakpoint on a DLL subroutine.
33037
33038 @smallexample
33039 (gdb) break ada_dll.adb:45
33040 @end smallexample
33041
33042 Or if you want to break using a symbol on the DLL, you need first to
33043 select the Ada language (language used by the DLL).
33044
33045 @smallexample
33046 (gdb) set language ada
33047 (gdb) break ada_dll
33048 @end smallexample
33049
33050 @item
33051 Continue the program.
33052
33053 @smallexample
33054 (gdb) cont
33055 @end smallexample
33056
33057 @noindent
33058 This will run the program until it reaches the breakpoint that has been
33059 set. From that point you can use the standard way to debug a program
33060 as described in (@pxref{Running and Debugging Ada Programs}).
33061
33062 @end enumerate
33063
33064 @noindent
33065 It is also possible to debug the DLL by attaching to a running process.
33066
33067 @node Attaching to a Running Process
33068 @subsubsection Attaching to a Running Process
33069 @cindex DLL debugging, attach to process
33070
33071 @noindent
33072 With @code{GDB} it is always possible to debug a running process by
33073 attaching to it. It is possible to debug a DLL this way. The limitation
33074 of this approach is that the DLL must run long enough to perform the
33075 attach operation. It may be useful for instance to insert a time wasting
33076 loop in the code of the DLL to meet this criterion.
33077
33078 @enumerate 1
33079
33080 @item Launch the main program @file{main.exe}.
33081
33082 @smallexample
33083 $ main
33084 @end smallexample
33085
33086 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33087 that the process PID for @file{main.exe} is 208.
33088
33089 @item Launch gdb.
33090
33091 @smallexample
33092 $ gdb
33093 @end smallexample
33094
33095 @item Attach to the running process to be debugged.
33096
33097 @smallexample
33098 (gdb) attach 208
33099 @end smallexample
33100
33101 @item Load the process debugging information.
33102
33103 @smallexample
33104 (gdb) symbol-file main.exe
33105 @end smallexample
33106
33107 @item Break somewhere in the DLL.
33108
33109 @smallexample
33110 (gdb) break ada_dll
33111 @end smallexample
33112
33113 @item Continue process execution.
33114
33115 @smallexample
33116 (gdb) cont
33117 @end smallexample
33118
33119 @end enumerate
33120
33121 @noindent
33122 This last step will resume the process execution, and stop at
33123 the breakpoint we have set. From there you can use the standard
33124 approach to debug a program as described in
33125 (@pxref{Running and Debugging Ada Programs}).
33126
33127 @node Setting Stack Size from gnatlink
33128 @section Setting Stack Size from @command{gnatlink}
33129
33130 @noindent
33131 It is possible to specify the program stack size at link time. On modern
33132 versions of Windows, starting with XP, this is mostly useful to set the size of
33133 the main stack (environment task). The other task stacks are set with pragma
33134 Storage_Size or with the @command{gnatbind -d} command.
33135
33136 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33137 reserve size of individual tasks, the link-time stack size applies to all
33138 tasks, and pragma Storage_Size has no effect.
33139 In particular, Stack Overflow checks are made against this
33140 link-time specified size.
33141
33142 This setting can be done with
33143 @command{gnatlink} using either:
33144
33145 @itemize @bullet
33146
33147 @item using @option{-Xlinker} linker option
33148
33149 @smallexample
33150 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33151 @end smallexample
33152
33153 This sets the stack reserve size to 0x10000 bytes and the stack commit
33154 size to 0x1000 bytes.
33155
33156 @item using @option{-Wl} linker option
33157
33158 @smallexample
33159 $ gnatlink hello -Wl,--stack=0x1000000
33160 @end smallexample
33161
33162 This sets the stack reserve size to 0x1000000 bytes. Note that with
33163 @option{-Wl} option it is not possible to set the stack commit size
33164 because the coma is a separator for this option.
33165
33166 @end itemize
33167
33168 @node Setting Heap Size from gnatlink
33169 @section Setting Heap Size from @command{gnatlink}
33170
33171 @noindent
33172 Under Windows systems, it is possible to specify the program heap size from
33173 @command{gnatlink} using either:
33174
33175 @itemize @bullet
33176
33177 @item using @option{-Xlinker} linker option
33178
33179 @smallexample
33180 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33181 @end smallexample
33182
33183 This sets the heap reserve size to 0x10000 bytes and the heap commit
33184 size to 0x1000 bytes.
33185
33186 @item using @option{-Wl} linker option
33187
33188 @smallexample
33189 $ gnatlink hello -Wl,--heap=0x1000000
33190 @end smallexample
33191
33192 This sets the heap reserve size to 0x1000000 bytes. Note that with
33193 @option{-Wl} option it is not possible to set the heap commit size
33194 because the coma is a separator for this option.
33195
33196 @end itemize
33197
33198 @end ifset
33199
33200 @c **********************************
33201 @c * GNU Free Documentation License *
33202 @c **********************************
33203 @include fdl.texi
33204 @c GNU Free Documentation License
33205
33206 @node Index,,GNU Free Documentation License, Top
33207 @unnumbered Index
33208
33209 @printindex cp
33210
33211 @contents
33212 @c Put table of contents at end, otherwise it precedes the "title page" in
33213 @c the .txt version
33214 @c Edit the pdf file to move the contents to the beginning, after the title
33215 @c page
33216
33217 @bye