]> 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-2005, 2006, 2007, 2008 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c GNAT_UGN Style Guide
31 @c
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
34 @c
35 @c @chapter
36 @c @section
37 @c @subsection
38 @c @subsubsection
39 @c @subsubsubsection
40 @c
41 @c @end smallexample
42 @c @end itemize
43 @c @end enumerate
44 @c
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
60 @c
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
63 @c
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
66 @c
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c or "ali".
69 @c
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
72 @c
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
76 @c
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
79 @c Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211 --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103 Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213 procedure Hello;
1214 procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219 procedure Hello is
1220 begin
1221 Put_Line ("Hello WORLD!");
1222 end Hello;
1223
1224 procedure Goodbye is
1225 begin
1226 Put_Line ("Goodbye WORLD!");
1227 end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235 Greetings.Hello;
1236 Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs. This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear. In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}. This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503 Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568 Line : String (1..80);
1569 N : Natural;
1570 begin
1571 Put_Line("Type a line of text at each prompt; an empty line to exit");
1572 loop
1573 Put(": ");
1574 Get_Line (Line, N);
1575 Put_Line (Line (1..N) );
1576 exit when N=0;
1577 end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}. When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091 Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093 Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151 Spec_File_Name => FILE_NAME_PATTERN
2152 @r{[},Casing => CASING_SPEC@r{]}
2153 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156 Body_File_Name => FILE_NAME_PATTERN
2157 @r{[},Casing => CASING_SPEC@r{]}
2158 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161 Subunit_File_Name => FILE_NAME_PATTERN
2162 @r{[},Casing => CASING_SPEC@r{]}
2163 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231 (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233 (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259 (Spec_File_Name => "*_.ADA",
2260 Dot_Replacement => "__",
2261 Casing = Uppercase);
2262 pragma Source_File_Name
2263 (Body_File_Name => "*.ADA",
2264 Dot_Replacement => "__",
2265 Casing = Uppercase);
2266 pragma Source_File_Name
2267 (Subunit_File_Name => "*.SEP",
2268 Dot_Replacement => "__",
2269 Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada. Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555 printf ("num is %d.\n", num);
2556 return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566 return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 -- my_main.adb
2572 procedure My_Main is
2573
2574 -- Declare then export an Integer entity called num_from_Ada
2575 My_Num : Integer := 10;
2576 pragma Export (C, My_Num, "num_from_Ada");
2577
2578 -- Declare an Ada function spec for Get_Num, then use
2579 -- C function get_num for the implementation.
2580 function Get_Num return Integer;
2581 pragma Import (C, Get_Num, "get_num");
2582
2583 -- Declare an Ada procedure spec for Print_Num, then use
2584 -- C function print_num for the implementation.
2585 procedure Print_Num (Num : Integer);
2586 pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589 Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources. To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652 int a = 21, b = 7;
2653
2654 adainit();
2655
2656 /* Should print "21 + 7 = 28" */
2657 printf ("%d + %d = %d\n", a, b, add (a, b));
2658 /* Should print "21 - 7 = 14" */
2659 printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661 adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 -- unit1.ads
2667 package Unit1 is
2668 function Add (A, B : Integer) return Integer;
2669 pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 -- unit1.adb
2673 package body Unit1 is
2674 function Add (A, B : Integer) return Integer is
2675 begin
2676 return A + B;
2677 end Add;
2678 end Unit1;
2679
2680 -- unit2.ads
2681 package Unit2 is
2682 function Sub (A, B : Integer) return Integer;
2683 pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 -- unit2.adb
2687 package body Unit2 is
2688 function Sub (A, B : Integer) return Integer is
2689 begin
2690 return A - B;
2691 end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's. First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file. Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886 return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903 function builtin_sqrt (F : Float) return Float;
2904 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge. This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ 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, and currently, GNAT does
2996 not provide any help to solve the demangling problem. This problem can be
2997 addressed in two ways:
2998 @itemize @bullet
2999 @item
3000 by modifying the C++ code in order to force a C convention using
3001 the @code{extern "C"} syntax.
3002
3003 @item
3004 by figuring out the mangled name and use it as the Link_Name argument of
3005 the pragma import.
3006 @end itemize
3007
3008 @noindent
3009 Interfacing at the class level can be achieved by using the GNAT specific
3010 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3011 gnat_rm, GNAT Reference Manual}, for additional information.
3012
3013 @node Linking a Mixed C++ & Ada Program
3014 @subsection Linking a Mixed C++ & Ada Program
3015
3016 @noindent
3017 Usually the linker of the C++ development system must be used to link
3018 mixed applications because most C++ systems will resolve elaboration
3019 issues (such as calling constructors on global class instances)
3020 transparently during the link phase. GNAT has been adapted to ease the
3021 use of a foreign linker for the last phase. Three cases can be
3022 considered:
3023 @enumerate
3024
3025 @item
3026 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3027 The C++ linker can simply be called by using the C++ specific driver
3028 called @code{c++}. Note that this setup is not very common because it
3029 may involve recompiling the whole GCC tree from sources, which makes it
3030 harder to upgrade the compilation system for one language without
3031 destabilizing the other.
3032
3033 @smallexample
3034 $ c++ -c file1.C
3035 $ c++ -c file2.C
3036 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3037 @end smallexample
3038
3039 @item
3040 Using GNAT and G++ from two different GCC installations: If both
3041 compilers are on the @env{PATH}, the previous method may be used. It is
3042 important to note that environment variables such as
3043 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3044 @env{GCC_ROOT} will affect both compilers
3045 at the same time and may make one of the two compilers operate
3046 improperly if set during invocation of the wrong compiler. It is also
3047 very important that the linker uses the proper @file{libgcc.a} GCC
3048 library -- that is, the one from the C++ compiler installation. The
3049 implicit link command as suggested in the @command{gnatmake} command
3050 from the former example can be replaced by an explicit link command with
3051 the full-verbosity option in order to verify which library is used:
3052 @smallexample
3053 $ gnatbind ada_unit
3054 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3055 @end smallexample
3056 If there is a problem due to interfering environment variables, it can
3057 be worked around by using an intermediate script. The following example
3058 shows the proper script to use when GNAT has not been installed at its
3059 default location and g++ has been installed at its default location:
3060
3061 @smallexample
3062 $ cat ./my_script
3063 #!/bin/sh
3064 unset BINUTILS_ROOT
3065 unset GCC_ROOT
3066 c++ $*
3067 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3068 @end smallexample
3069
3070 @item
3071 Using a non-GNU C++ compiler: The commands previously described can be
3072 used to insure that the C++ linker is used. Nonetheless, you need to add
3073 a few more parameters to the link command line, depending on the exception
3074 mechanism used.
3075
3076 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3077 to the libgcc libraries are required:
3078
3079 @smallexample
3080 $ cat ./my_script
3081 #!/bin/sh
3082 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3083 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3084 @end smallexample
3085
3086 Where CC is the name of the non-GNU C++ compiler.
3087
3088 If the @code{zero cost} exception mechanism is used, and the platform
3089 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3090 paths to more objects are required:
3091
3092 @smallexample
3093 $ cat ./my_script
3094 #!/bin/sh
3095 CC `gcc -print-file-name=crtbegin.o` $* \
3096 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3097 `gcc -print-file-name=crtend.o`
3098 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3099 @end smallexample
3100
3101 If the @code{zero cost} exception mechanism is used, and the platform
3102 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3103 Tru64 or AIX), the simple approach described above will not work and
3104 a pre-linking phase using GNAT will be necessary.
3105
3106 @end enumerate
3107
3108 @node A Simple Example
3109 @subsection A Simple Example
3110 @noindent
3111 The following example, provided as part of the GNAT examples, shows how
3112 to achieve procedural interfacing between Ada and C++ in both
3113 directions. The C++ class A has two methods. The first method is exported
3114 to Ada by the means of an extern C wrapper function. The second method
3115 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3116 a limited record with a layout comparable to the C++ class. The Ada
3117 subprogram, in turn, calls the C++ method. So, starting from the C++
3118 main program, the process passes back and forth between the two
3119 languages.
3120
3121 @noindent
3122 Here are the compilation commands:
3123 @smallexample
3124 $ gnatmake -c simple_cpp_interface
3125 $ c++ -c cpp_main.C
3126 $ c++ -c ex7.C
3127 $ gnatbind -n simple_cpp_interface
3128 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3129 -lstdc++ ex7.o cpp_main.o
3130 @end smallexample
3131
3132 @noindent
3133 Here are the corresponding sources:
3134 @smallexample
3135
3136 //cpp_main.C
3137
3138 #include "ex7.h"
3139
3140 extern "C" @{
3141 void adainit (void);
3142 void adafinal (void);
3143 void method1 (A *t);
3144 @}
3145
3146 void method1 (A *t)
3147 @{
3148 t->method1 ();
3149 @}
3150
3151 int main ()
3152 @{
3153 A obj;
3154 adainit ();
3155 obj.method2 (3030);
3156 adafinal ();
3157 @}
3158
3159 //ex7.h
3160
3161 class Origin @{
3162 public:
3163 int o_value;
3164 @};
3165 class A : public Origin @{
3166 public:
3167 void method1 (void);
3168 void method2 (int v);
3169 A();
3170 int a_value;
3171 @};
3172
3173 //ex7.C
3174
3175 #include "ex7.h"
3176 #include <stdio.h>
3177
3178 extern "C" @{ void ada_method2 (A *t, int v);@}
3179
3180 void A::method1 (void)
3181 @{
3182 a_value = 2020;
3183 printf ("in A::method1, a_value = %d \n",a_value);
3184
3185 @}
3186
3187 void A::method2 (int v)
3188 @{
3189 ada_method2 (this, v);
3190 printf ("in A::method2, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 A::A(void)
3195 @{
3196 a_value = 1010;
3197 printf ("in A::A, a_value = %d \n",a_value);
3198 @}
3199 @end smallexample
3200
3201 @smallexample @c ada
3202 -- Ada sources
3203 package body Simple_Cpp_Interface is
3204
3205 procedure Ada_Method2 (This : in out A; V : Integer) is
3206 begin
3207 Method1 (This);
3208 This.A_Value := V;
3209 end Ada_Method2;
3210
3211 end Simple_Cpp_Interface;
3212
3213 with System;
3214 package Simple_Cpp_Interface is
3215 type A is limited
3216 record
3217 Vptr : System.Address;
3218 O_Value : Integer;
3219 A_Value : Integer;
3220 end record;
3221 pragma Convention (C, A);
3222
3223 procedure Method1 (This : in out A);
3224 pragma Import (C, Method1);
3225
3226 procedure Ada_Method2 (This : in out A; V : Integer);
3227 pragma Export (C, Ada_Method2);
3228
3229 end Simple_Cpp_Interface;
3230 @end smallexample
3231
3232 @node Interfacing with C++ constructors
3233 @subsection Interfacing with C++ constructors
3234 @noindent
3235
3236 In order to interface with C++ constructors GNAT provides the
3237 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3238 gnat_rm, GNAT Reference Manual}, for additional information).
3239 In this section we present some common uses of C++ constructors
3240 in mixed-languages programs in GNAT.
3241
3242 Let us assume that we need to interface with the following
3243 C++ class:
3244
3245 @smallexample
3246 @b{class} Root @{
3247 @b{public}:
3248 int a_value;
3249 int b_value;
3250 @b{virtual} int Get_Value ();
3251 Root(); // Default constructor
3252 Root(int v); // 1st non-default constructor
3253 Root(int v, int w); // 2nd non-default constructor
3254 @};
3255 @end smallexample
3256
3257 For this purpose we can write the following package spec (further
3258 information on how to build this spec is available in
3259 @ref{Interfacing with C++ at the Class Level} and
3260 @ref{Generating Ada Bindings for C and C++ headers}).
3261
3262 @smallexample @c ada
3263 with Interfaces.C; use Interfaces.C;
3264 package Pkg_Root is
3265 type Root is tagged limited record
3266 A_Value : int;
3267 B_Value : int;
3268 end record;
3269 pragma Import (CPP, Root);
3270
3271 function Get_Value (Obj : Root) return int;
3272 pragma Import (CPP, Get_Value);
3273
3274 function Constructor return Root'Class;
3275 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3276
3277 function Constructor (v : Integer) return Root'Class;
3278 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3279
3280 function Constructor (v, w : Integer) return Root'Class;
3281 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3282 end Pkg_Root;
3283 @end smallexample
3284
3285 On the Ada side the constructor is represented by a function (whose
3286 name is arbitrary) that returns the classwide type corresponding to
3287 the imported C++ class.
3288
3289 In a declaration of an object whose type is a class imported from C++,
3290 either the default C++ constructor is implicitly called by GNAT, or
3291 else the required C++ constructor must be explicitly called in the
3292 expression that initializes the object. For example:
3293
3294 @smallexample @c ada
3295 Obj1 : Root;
3296 Obj2 : Root := Constructor;
3297 Obj3 : Root := Constructor (v => 10);
3298 Obj4 : Root := Constructor (30, 40);
3299 @end smallexample
3300
3301 The first two declarations are equivalent: in both cases the default C++
3302 constructor is invoked (in the former case the call to the constructor is
3303 implicit, and in the latter case the call is explicit in the object
3304 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3305 that takes an integer argument, and @code{Obj4} is initialized by the
3306 non-default C++ constructor that takes two integers.
3307
3308 Let us derive the imported C++ class in the Ada side. For example:
3309
3310 @smallexample @c ada
3311 type DT is new Root with record
3312 C_Value : Natural := 2009;
3313 end record;
3314 @end smallexample
3315
3316 In this case the components DT inherited from the C++ side must be
3317 initialized by a C++ constructor, and the additional Ada components
3318 of type DT are initialized by GNAT. The initialization of such an
3319 object is done either by default, or by means of a function returning
3320 an aggregate of type DT, or by means of an extended aggregate.
3321
3322 @smallexample @c ada
3323 Obj5 : DT;
3324 Obj6 : DT := Function_Returning_DT (50);
3325 Obj7 : DT := (Constructor (30,40) with (C_Value => 50));
3326 @end smallexample
3327
3328 The declaration of @code{Obj5} invokes the default constructors: the
3329 C++ default constructor of the parent type takes care of the initialization
3330 of the components inherited from Root, and GNAT takes care of the default
3331 initialization of the additional Ada components of type DT (that is,
3332 @code{C_Value} is initialized to value 2009). The order of invocation of
3333 the constructors is consistent with the order of elaboration required by
3334 Ada and C++. That is, the constructor of the parent type is always called
3335 before the constructor of the derived type.
3336
3337 Let us now consider a record that has components whose type is imported
3338 from C++. For example:
3339
3340 @smallexample @c ada
3341 type Rec1 is limited record
3342 Data1 : Root := Constructor (10);
3343 Value : Natural := 1000;
3344 end record;
3345
3346 type Rec2 (D : Integer := 20) is limited record
3347 Rec : Rec1;
3348 Data2 : Root := Constructor (D, 30);
3349 end record;
3350 @end smallexample
3351
3352 The initialization of an object of type @code{Rec2} will call the
3353 non-default C++ constructors specified for the imported components.
3354 For example:
3355
3356 @smallexample @c ada
3357 Obj8 : Rec2 (40);
3358 @end smallexample
3359
3360 Using Ada 2005 we can use limited aggregates to initialize an object
3361 invoking C++ constructors that differ from those specified in the type
3362 declarations. For example:
3363
3364 @smallexample @c ada
3365 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3366 others => <>),
3367 others => <>);
3368 @end smallexample
3369
3370 The above declaration uses an Ada 2005 limited aggregate to
3371 initialize @code{Obj9}, and the C++ constructor that has two integer
3372 arguments is invoked to initialize the @code{Data1} component instead
3373 of the constructor specified in the declaration of type @code{Rec1}. In
3374 Ada 2005 the box in the aggregate indicates that unspecified components
3375 are initialized using the expression (if any) available in the component
3376 declaration. That is, in this case discriminant @code{D} is initialized
3377 to value @code{20}, @code{Value} is initialized to value 1000, and the
3378 non-default C++ constructor that handles two integers takes care of
3379 initializing component @code{Data2} with values @code{20,30}.
3380
3381 In Ada 2005 we can use the extended return statement to build the Ada
3382 equivalent to C++ non-default constructors. For example:
3383
3384 @smallexample @c ada
3385 function Constructor (V : Integer) return Rec2 is
3386 begin
3387 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3388 others => <>),
3389 others => <>) do
3390 -- Further actions required for construction of
3391 -- objects of type Rec2
3392 ...
3393 end record;
3394 end Constructor;
3395 @end smallexample
3396
3397 In this example the extended return statement construct is used to
3398 build in place the returned object whose components are initialized
3399 by means of a limited aggregate. Any further action associated with
3400 the constructor can be placed inside the construct.
3401
3402 @node Interfacing with C++ at the Class Level
3403 @subsection Interfacing with C++ at the Class Level
3404 @noindent
3405 In this section we demonstrate the GNAT features for interfacing with
3406 C++ by means of an example making use of Ada 2005 abstract interface
3407 types. This example consists of a classification of animals; classes
3408 have been used to model our main classification of animals, and
3409 interfaces provide support for the management of secondary
3410 classifications. We first demonstrate a case in which the types and
3411 constructors are defined on the C++ side and imported from the Ada
3412 side, and latter the reverse case.
3413
3414 The root of our derivation will be the @code{Animal} class, with a
3415 single private attribute (the @code{Age} of the animal) and two public
3416 primitives to set and get the value of this attribute.
3417
3418 @smallexample
3419 @b{class} Animal @{
3420 @b{public}:
3421 @b{virtual} void Set_Age (int New_Age);
3422 @b{virtual} int Age ();
3423 @b{private}:
3424 int Age_Count;
3425 @};
3426 @end smallexample
3427
3428 Abstract interface types are defined in C++ by means of classes with pure
3429 virtual functions and no data members. In our example we will use two
3430 interfaces that provide support for the common management of @code{Carnivore}
3431 and @code{Domestic} animals:
3432
3433 @smallexample
3434 @b{class} Carnivore @{
3435 @b{public}:
3436 @b{virtual} int Number_Of_Teeth () = 0;
3437 @};
3438
3439 @b{class} Domestic @{
3440 @b{public}:
3441 @b{virtual void} Set_Owner (char* Name) = 0;
3442 @};
3443 @end smallexample
3444
3445 Using these declarations, we can now say that a @code{Dog} is an animal that is
3446 both Carnivore and Domestic, that is:
3447
3448 @smallexample
3449 @b{class} Dog : Animal, Carnivore, Domestic @{
3450 @b{public}:
3451 @b{virtual} int Number_Of_Teeth ();
3452 @b{virtual} void Set_Owner (char* Name);
3453
3454 Dog(); // Constructor
3455 @b{private}:
3456 int Tooth_Count;
3457 char *Owner;
3458 @};
3459 @end smallexample
3460
3461 In the following examples we will assume that the previous declarations are
3462 located in a file named @code{animals.h}. The following package demonstrates
3463 how to import these C++ declarations from the Ada side:
3464
3465 @smallexample @c ada
3466 with Interfaces.C.Strings; use Interfaces.C.Strings;
3467 package Animals is
3468 type Carnivore is interface;
3469 pragma Convention (C_Plus_Plus, Carnivore);
3470 function Number_Of_Teeth (X : Carnivore)
3471 return Natural is abstract;
3472
3473 type Domestic is interface;
3474 pragma Convention (C_Plus_Plus, Set_Owner);
3475 procedure Set_Owner
3476 (X : in out Domestic;
3477 Name : Chars_Ptr) is abstract;
3478
3479 type Animal is tagged record
3480 Age : Natural := 0;
3481 end record;
3482 pragma Import (C_Plus_Plus, Animal);
3483
3484 procedure Set_Age (X : in out Animal; Age : Integer);
3485 pragma Import (C_Plus_Plus, Set_Age);
3486
3487 function Age (X : Animal) return Integer;
3488 pragma Import (C_Plus_Plus, Age);
3489
3490 type Dog is new Animal and Carnivore and Domestic with record
3491 Tooth_Count : Natural;
3492 Owner : String (1 .. 30);
3493 end record;
3494 pragma Import (C_Plus_Plus, Dog);
3495
3496 function Number_Of_Teeth (A : Dog) return Integer;
3497 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3498
3499 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3500 pragma Import (C_Plus_Plus, Set_Owner);
3501
3502 function New_Dog return Dog'Class;
3503 pragma CPP_Constructor (New_Dog);
3504 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3505 end Animals;
3506 @end smallexample
3507
3508 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3509 interfacing with these C++ classes is easy. The only requirement is that all
3510 the primitives and components must be declared exactly in the same order in
3511 the two languages.
3512
3513 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3514 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3515 the arguments to the called primitives will be the same as for C++. For the
3516 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3517 to indicate that they have been defined on the C++ side; this is required
3518 because the dispatch table associated with these tagged types will be built
3519 in the C++ side and therefore will not contain the predefined Ada primitives
3520 which Ada would otherwise expect.
3521
3522 As the reader can see there is no need to indicate the C++ mangled names
3523 associated with each subprogram because it is assumed that all the calls to
3524 these primitives will be dispatching calls. The only exception is the
3525 constructor, which must be registered with the compiler by means of
3526 @code{pragma CPP_Constructor} and needs to provide its associated C++
3527 mangled name because the Ada compiler generates direct calls to it.
3528
3529 With the above packages we can now declare objects of type Dog on the Ada side
3530 and dispatch calls to the corresponding subprograms on the C++ side. We can
3531 also extend the tagged type Dog with further fields and primitives, and
3532 override some of its C++ primitives on the Ada side. For example, here we have
3533 a type derivation defined on the Ada side that inherits all the dispatching
3534 primitives of the ancestor from the C++ side.
3535
3536 @smallexample
3537 @b{with} Animals; @b{use} Animals;
3538 @b{package} Vaccinated_Animals @b{is}
3539 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3540 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3541 @b{end} Vaccinated_Animals;
3542 @end smallexample
3543
3544 It is important to note that, because of the ABI compatibility, the programmer
3545 does not need to add any further information to indicate either the object
3546 layout or the dispatch table entry associated with each dispatching operation.
3547
3548 Now let us define all the types and constructors on the Ada side and export
3549 them to C++, using the same hierarchy of our previous example:
3550
3551 @smallexample @c ada
3552 with Interfaces.C.Strings;
3553 use Interfaces.C.Strings;
3554 package Animals is
3555 type Carnivore is interface;
3556 pragma Convention (C_Plus_Plus, Carnivore);
3557 function Number_Of_Teeth (X : Carnivore)
3558 return Natural is abstract;
3559
3560 type Domestic is interface;
3561 pragma Convention (C_Plus_Plus, Set_Owner);
3562 procedure Set_Owner
3563 (X : in out Domestic;
3564 Name : Chars_Ptr) is abstract;
3565
3566 type Animal is tagged record
3567 Age : Natural := 0;
3568 end record;
3569 pragma Convention (C_Plus_Plus, Animal);
3570
3571 procedure Set_Age (X : in out Animal; Age : Integer);
3572 pragma Export (C_Plus_Plus, Set_Age);
3573
3574 function Age (X : Animal) return Integer;
3575 pragma Export (C_Plus_Plus, Age);
3576
3577 type Dog is new Animal and Carnivore and Domestic with record
3578 Tooth_Count : Natural;
3579 Owner : String (1 .. 30);
3580 end record;
3581 pragma Convention (C_Plus_Plus, Dog);
3582
3583 function Number_Of_Teeth (A : Dog) return Integer;
3584 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3585
3586 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3587 pragma Export (C_Plus_Plus, Set_Owner);
3588
3589 function New_Dog return Dog'Class;
3590 pragma Export (C_Plus_Plus, New_Dog);
3591 end Animals;
3592 @end smallexample
3593
3594 Compared with our previous example the only difference is the use of
3595 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3596 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3597 nothing else to be done; as explained above, the only requirement is that all
3598 the primitives and components are declared in exactly the same order.
3599
3600 For completeness, let us see a brief C++ main program that uses the
3601 declarations available in @code{animals.h} (presented in our first example) to
3602 import and use the declarations from the Ada side, properly initializing and
3603 finalizing the Ada run-time system along the way:
3604
3605 @smallexample
3606 @b{#include} "animals.h"
3607 @b{#include} <iostream>
3608 @b{using namespace} std;
3609
3610 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3611 void Check_Domestic (Domestic *obj) @{@dots{}@}
3612 void Check_Animal (Animal *obj) @{@dots{}@}
3613 void Check_Dog (Dog *obj) @{@dots{}@}
3614
3615 @b{extern} "C" @{
3616 void adainit (void);
3617 void adafinal (void);
3618 Dog* new_dog ();
3619 @}
3620
3621 void test ()
3622 @{
3623 Dog *obj = new_dog(); // Ada constructor
3624 Check_Carnivore (obj); // Check secondary DT
3625 Check_Domestic (obj); // Check secondary DT
3626 Check_Animal (obj); // Check primary DT
3627 Check_Dog (obj); // Check primary DT
3628 @}
3629
3630 int main ()
3631 @{
3632 adainit (); test(); adafinal ();
3633 return 0;
3634 @}
3635 @end smallexample
3636
3637 @node Comparison between GNAT and C/C++ Compilation Models
3638 @section Comparison between GNAT and C/C++ Compilation Models
3639
3640 @noindent
3641 The GNAT model of compilation is close to the C and C++ models. You can
3642 think of Ada specs as corresponding to header files in C. As in C, you
3643 don't need to compile specs; they are compiled when they are used. The
3644 Ada @code{with} is similar in effect to the @code{#include} of a C
3645 header.
3646
3647 One notable difference is that, in Ada, you may compile specs separately
3648 to check them for semantic and syntactic accuracy. This is not always
3649 possible with C headers because they are fragments of programs that have
3650 less specific syntactic or semantic rules.
3651
3652 The other major difference is the requirement for running the binder,
3653 which performs two important functions. First, it checks for
3654 consistency. In C or C++, the only defense against assembling
3655 inconsistent programs lies outside the compiler, in a makefile, for
3656 example. The binder satisfies the Ada requirement that it be impossible
3657 to construct an inconsistent program when the compiler is used in normal
3658 mode.
3659
3660 @cindex Elaboration order control
3661 The other important function of the binder is to deal with elaboration
3662 issues. There are also elaboration issues in C++ that are handled
3663 automatically. This automatic handling has the advantage of being
3664 simpler to use, but the C++ programmer has no control over elaboration.
3665 Where @code{gnatbind} might complain there was no valid order of
3666 elaboration, a C++ compiler would simply construct a program that
3667 malfunctioned at run time.
3668 @end ifclear
3669
3670 @node Comparison between GNAT and Conventional Ada Library Models
3671 @section Comparison between GNAT and Conventional Ada Library Models
3672
3673 @noindent
3674 This section is intended for Ada programmers who have
3675 used an Ada compiler implementing the traditional Ada library
3676 model, as described in the Ada Reference Manual.
3677
3678 @cindex GNAT library
3679 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3680 source files themselves acts as the library. Compiling Ada programs does
3681 not generate any centralized information, but rather an object file and
3682 a ALI file, which are of interest only to the binder and linker.
3683 In a traditional system, the compiler reads information not only from
3684 the source file being compiled, but also from the centralized library.
3685 This means that the effect of a compilation depends on what has been
3686 previously compiled. In particular:
3687
3688 @itemize @bullet
3689 @item
3690 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3691 to the version of the unit most recently compiled into the library.
3692
3693 @item
3694 Inlining is effective only if the necessary body has already been
3695 compiled into the library.
3696
3697 @item
3698 Compiling a unit may obsolete other units in the library.
3699 @end itemize
3700
3701 @noindent
3702 In GNAT, compiling one unit never affects the compilation of any other
3703 units because the compiler reads only source files. Only changes to source
3704 files can affect the results of a compilation. In particular:
3705
3706 @itemize @bullet
3707 @item
3708 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3709 to the source version of the unit that is currently accessible to the
3710 compiler.
3711
3712 @item
3713 @cindex Inlining
3714 Inlining requires the appropriate source files for the package or
3715 subprogram bodies to be available to the compiler. Inlining is always
3716 effective, independent of the order in which units are complied.
3717
3718 @item
3719 Compiling a unit never affects any other compilations. The editing of
3720 sources may cause previous compilations to be out of date if they
3721 depended on the source file being modified.
3722 @end itemize
3723
3724 @noindent
3725 The most important result of these differences is that order of compilation
3726 is never significant in GNAT. There is no situation in which one is
3727 required to do one compilation before another. What shows up as order of
3728 compilation requirements in the traditional Ada library becomes, in
3729 GNAT, simple source dependencies; in other words, there is only a set
3730 of rules saying what source files must be present when a file is
3731 compiled.
3732
3733 @ifset vms
3734 @node Placement of temporary files
3735 @section Placement of temporary files
3736 @cindex Temporary files (user control over placement)
3737
3738 @noindent
3739 GNAT creates temporary files in the directory designated by the environment
3740 variable @env{TMPDIR}.
3741 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3742 for detailed information on how environment variables are resolved.
3743 For most users the easiest way to make use of this feature is to simply
3744 define @env{TMPDIR} as a job level logical name).
3745 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3746 for compiler temporary files, then you can include something like the
3747 following command in your @file{LOGIN.COM} file:
3748
3749 @smallexample
3750 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3751 @end smallexample
3752
3753 @noindent
3754 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3755 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3756 designated by @env{TEMP}.
3757 If none of these environment variables are defined then GNAT uses the
3758 directory designated by the logical name @code{SYS$SCRATCH:}
3759 (by default the user's home directory). If all else fails
3760 GNAT uses the current directory for temporary files.
3761 @end ifset
3762
3763 @c *************************
3764 @node Compiling Using gcc
3765 @chapter Compiling Using @command{gcc}
3766
3767 @noindent
3768 This chapter discusses how to compile Ada programs using the @command{gcc}
3769 command. It also describes the set of switches
3770 that can be used to control the behavior of the compiler.
3771 @menu
3772 * Compiling Programs::
3773 * Switches for gcc::
3774 * Search Paths and the Run-Time Library (RTL)::
3775 * Order of Compilation Issues::
3776 * Examples::
3777 @end menu
3778
3779 @node Compiling Programs
3780 @section Compiling Programs
3781
3782 @noindent
3783 The first step in creating an executable program is to compile the units
3784 of the program using the @command{gcc} command. You must compile the
3785 following files:
3786
3787 @itemize @bullet
3788 @item
3789 the body file (@file{.adb}) for a library level subprogram or generic
3790 subprogram
3791
3792 @item
3793 the spec file (@file{.ads}) for a library level package or generic
3794 package that has no body
3795
3796 @item
3797 the body file (@file{.adb}) for a library level package
3798 or generic package that has a body
3799
3800 @end itemize
3801
3802 @noindent
3803 You need @emph{not} compile the following files
3804
3805 @itemize @bullet
3806
3807 @item
3808 the spec of a library unit which has a body
3809
3810 @item
3811 subunits
3812 @end itemize
3813
3814 @noindent
3815 because they are compiled as part of compiling related units. GNAT
3816 package specs
3817 when the corresponding body is compiled, and subunits when the parent is
3818 compiled.
3819
3820 @cindex cannot generate code
3821 If you attempt to compile any of these files, you will get one of the
3822 following error messages (where @var{fff} is the name of the file you compiled):
3823
3824 @smallexample
3825 cannot generate code for file @var{fff} (package spec)
3826 to check package spec, use -gnatc
3827
3828 cannot generate code for file @var{fff} (missing subunits)
3829 to check parent unit, use -gnatc
3830
3831 cannot generate code for file @var{fff} (subprogram spec)
3832 to check subprogram spec, use -gnatc
3833
3834 cannot generate code for file @var{fff} (subunit)
3835 to check subunit, use -gnatc
3836 @end smallexample
3837
3838 @noindent
3839 As indicated by the above error messages, if you want to submit
3840 one of these files to the compiler to check for correct semantics
3841 without generating code, then use the @option{-gnatc} switch.
3842
3843 The basic command for compiling a file containing an Ada unit is
3844
3845 @smallexample
3846 $ gcc -c @ovar{switches} @file{file name}
3847 @end smallexample
3848
3849 @noindent
3850 where @var{file name} is the name of the Ada file (usually
3851 having an extension
3852 @file{.ads} for a spec or @file{.adb} for a body).
3853 @ifclear vms
3854 You specify the
3855 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3856 @end ifclear
3857 The result of a successful compilation is an object file, which has the
3858 same name as the source file but an extension of @file{.o} and an Ada
3859 Library Information (ALI) file, which also has the same name as the
3860 source file, but with @file{.ali} as the extension. GNAT creates these
3861 two output files in the current directory, but you may specify a source
3862 file in any directory using an absolute or relative path specification
3863 containing the directory information.
3864
3865 @findex gnat1
3866 @command{gcc} is actually a driver program that looks at the extensions of
3867 the file arguments and loads the appropriate compiler. For example, the
3868 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3869 These programs are in directories known to the driver program (in some
3870 configurations via environment variables you set), but need not be in
3871 your path. The @command{gcc} driver also calls the assembler and any other
3872 utilities needed to complete the generation of the required object
3873 files.
3874
3875 It is possible to supply several file names on the same @command{gcc}
3876 command. This causes @command{gcc} to call the appropriate compiler for
3877 each file. For example, the following command lists three separate
3878 files to be compiled:
3879
3880 @smallexample
3881 $ gcc -c x.adb y.adb z.c
3882 @end smallexample
3883
3884 @noindent
3885 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3886 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3887 The compiler generates three object files @file{x.o}, @file{y.o} and
3888 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3889 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3890 @ifclear vms
3891 except for
3892 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3893 @end ifclear
3894
3895 @node Switches for gcc
3896 @section Switches for @command{gcc}
3897
3898 @noindent
3899 The @command{gcc} command accepts switches that control the
3900 compilation process. These switches are fully described in this section.
3901 First we briefly list all the switches, in alphabetical order, then we
3902 describe the switches in more detail in functionally grouped sections.
3903
3904 More switches exist for GCC than those documented here, especially
3905 for specific targets. However, their use is not recommended as
3906 they may change code generation in ways that are incompatible with
3907 the Ada run-time library, or can cause inconsistencies between
3908 compilation units.
3909
3910 @menu
3911 * Output and Error Message Control::
3912 * Warning Message Control::
3913 * Debugging and Assertion Control::
3914 * Validity Checking::
3915 * Style Checking::
3916 * Run-Time Checks::
3917 * Using gcc for Syntax Checking::
3918 * Using gcc for Semantic Checking::
3919 * Compiling Different Versions of Ada::
3920 * Character Set Control::
3921 * File Naming Control::
3922 * Subprogram Inlining Control::
3923 * Auxiliary Output Control::
3924 * Debugging Control::
3925 * Exception Handling Control::
3926 * Units to Sources Mapping Files::
3927 * Integrated Preprocessing::
3928 * Code Generation Control::
3929 @ifset vms
3930 * Return Codes::
3931 @end ifset
3932 @end menu
3933
3934 @table @option
3935 @c !sort!
3936 @ifclear vms
3937 @cindex @option{-b} (@command{gcc})
3938 @item -b @var{target}
3939 Compile your program to run on @var{target}, which is the name of a
3940 system configuration. You must have a GNAT cross-compiler built if
3941 @var{target} is not the same as your host system.
3942
3943 @item -B@var{dir}
3944 @cindex @option{-B} (@command{gcc})
3945 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3946 from @var{dir} instead of the default location. Only use this switch
3947 when multiple versions of the GNAT compiler are available.
3948 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3949 GNU Compiler Collection (GCC)}, for further details. You would normally
3950 use the @option{-b} or @option{-V} switch instead.
3951
3952 @item -c
3953 @cindex @option{-c} (@command{gcc})
3954 Compile. Always use this switch when compiling Ada programs.
3955
3956 Note: for some other languages when using @command{gcc}, notably in
3957 the case of C and C++, it is possible to use
3958 use @command{gcc} without a @option{-c} switch to
3959 compile and link in one step. In the case of GNAT, you
3960 cannot use this approach, because the binder must be run
3961 and @command{gcc} cannot be used to run the GNAT binder.
3962 @end ifclear
3963
3964 @item -fno-inline
3965 @cindex @option{-fno-inline} (@command{gcc})
3966 Suppresses all back-end inlining, even if other optimization or inlining
3967 switches are set.
3968 This includes suppression of inlining that results
3969 from the use of the pragma @code{Inline_Always}.
3970 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3971 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3972 effect if this switch is present.
3973
3974 @item -fno-inline-functions
3975 @cindex @option{-fno-inline-functions} (@command{gcc})
3976 Suppresses automatic inlining of simple subprograms, which is enabled
3977 if @option{-O3} is used.
3978
3979 @item -fno-inline-small-functions
3980 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3981 Suppresses automatic inlining of small subprograms, which is enabled
3982 if @option{-O2} is used.
3983
3984 @item -fno-inline-functions-called-once
3985 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3986 Suppresses inlining of subprograms local to the unit and called once
3987 from within it, which is enabled if @option{-O1} is used.
3988
3989 @item -fno-ivopts
3990 @cindex @option{-fno-ivopts} (@command{gcc})
3991 Suppresses high-level loop induction variable optimizations, which are
3992 enabled if @option{-O1} is used. These optimizations are generally
3993 profitable but, for some specific cases of loops with numerous uses
3994 of the iteration variable that follow a common pattern, they may end
3995 up destroying the regularity that could be exploited at a lower level
3996 and thus producing inferior code.
3997
3998 @item -fno-strict-aliasing
3999 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4000 Causes the compiler to avoid assumptions regarding non-aliasing
4001 of objects of different types. See
4002 @ref{Optimization and Strict Aliasing} for details.
4003
4004 @item -fstack-check
4005 @cindex @option{-fstack-check} (@command{gcc})
4006 Activates stack checking.
4007 See @ref{Stack Overflow Checking} for details.
4008
4009 @item -fstack-usage
4010 @cindex @option{-fstack-usage} (@command{gcc})
4011 Makes the compiler output stack usage information for the program, on a
4012 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4013
4014 @item -fcallgraph-info@r{[}=su@r{]}
4015 @cindex @option{-fcallgraph-info} (@command{gcc})
4016 Makes the compiler output callgraph information for the program, on a
4017 per-file basis. The information is generated in the VCG format. It can
4018 be decorated with stack-usage per-node information.
4019
4020 @item ^-g^/DEBUG^
4021 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4022 Generate debugging information. This information is stored in the object
4023 file and copied from there to the final executable file by the linker,
4024 where it can be read by the debugger. You must use the
4025 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4026
4027 @item -gnat83
4028 @cindex @option{-gnat83} (@command{gcc})
4029 Enforce Ada 83 restrictions.
4030
4031 @item -gnat95
4032 @cindex @option{-gnat95} (@command{gcc})
4033 Enforce Ada 95 restrictions.
4034
4035 @item -gnat05
4036 @cindex @option{-gnat05} (@command{gcc})
4037 Allow full Ada 2005 features.
4038
4039 @item -gnata
4040 @cindex @option{-gnata} (@command{gcc})
4041 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4042 activated. Note that these pragmas can also be controlled using the
4043 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4044 It also activates pragmas @code{Check}, @code{Precondition}, and
4045 @code{Postcondition}. Note that these pragmas can also be controlled
4046 using the configuration pragma @code{Check_Policy}.
4047
4048 @item -gnatA
4049 @cindex @option{-gnatA} (@command{gcc})
4050 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4051 it will be ignored.
4052
4053 @item -gnatb
4054 @cindex @option{-gnatb} (@command{gcc})
4055 Generate brief messages to @file{stderr} even if verbose mode set.
4056
4057 @item -gnatB
4058 @cindex @option{-gnatB} (@command{gcc})
4059 Assume no invalid (bad) values except for 'Valid attribute use.
4060
4061 @item -gnatc
4062 @cindex @option{-gnatc} (@command{gcc})
4063 Check syntax and semantics only (no code generation attempted).
4064
4065 @item -gnatd
4066 @cindex @option{-gnatd} (@command{gcc})
4067 Specify debug options for the compiler. The string of characters after
4068 the @option{-gnatd} specify the specific debug options. The possible
4069 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4070 compiler source file @file{debug.adb} for details of the implemented
4071 debug options. Certain debug options are relevant to applications
4072 programmers, and these are documented at appropriate points in this
4073 users guide.
4074
4075 @ifclear vms
4076 @item -gnatD
4077 @cindex @option{-gnatD[nn]} (@command{gcc})
4078 @end ifclear
4079 @ifset vms
4080 @item /XDEBUG /LXDEBUG=nnn
4081 @end ifset
4082 Create expanded source files for source level debugging. This switch
4083 also suppress generation of cross-reference information
4084 (see @option{-gnatx}).
4085
4086 @item -gnatec=@var{path}
4087 @cindex @option{-gnatec} (@command{gcc})
4088 Specify a configuration pragma file
4089 @ifclear vms
4090 (the equal sign is optional)
4091 @end ifclear
4092 (@pxref{The Configuration Pragmas Files}).
4093
4094 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4095 @cindex @option{-gnateD} (@command{gcc})
4096 Defines a symbol, associated with @var{value}, for preprocessing.
4097 (@pxref{Integrated Preprocessing}).
4098
4099 @item -gnatef
4100 @cindex @option{-gnatef} (@command{gcc})
4101 Display full source path name in brief error messages.
4102
4103 @item -gnateG
4104 @cindex @option{-gnateG} (@command{gcc})
4105 Save result of preprocessing in a text file.
4106
4107 @item -gnatem=@var{path}
4108 @cindex @option{-gnatem} (@command{gcc})
4109 Specify a mapping file
4110 @ifclear vms
4111 (the equal sign is optional)
4112 @end ifclear
4113 (@pxref{Units to Sources Mapping Files}).
4114
4115 @item -gnatep=@var{file}
4116 @cindex @option{-gnatep} (@command{gcc})
4117 Specify a preprocessing data file
4118 @ifclear vms
4119 (the equal sign is optional)
4120 @end ifclear
4121 (@pxref{Integrated Preprocessing}).
4122
4123 @item -gnatE
4124 @cindex @option{-gnatE} (@command{gcc})
4125 Full dynamic elaboration checks.
4126
4127 @item -gnatf
4128 @cindex @option{-gnatf} (@command{gcc})
4129 Full errors. Multiple errors per line, all undefined references, do not
4130 attempt to suppress cascaded errors.
4131
4132 @item -gnatF
4133 @cindex @option{-gnatF} (@command{gcc})
4134 Externals names are folded to all uppercase.
4135
4136 @item ^-gnatg^/GNAT_INTERNAL^
4137 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4138 Internal GNAT implementation mode. This should not be used for
4139 applications programs, it is intended only for use by the compiler
4140 and its run-time library. For documentation, see the GNAT sources.
4141 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4142 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4143 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4144 so that all standard warnings and all standard style options are turned on.
4145 All warnings and style error messages are treated as errors.
4146
4147 @ifclear vms
4148 @item -gnatG=nn
4149 @cindex @option{-gnatG[nn]} (@command{gcc})
4150 @end ifclear
4151 @ifset vms
4152 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4153 @end ifset
4154 List generated expanded code in source form.
4155
4156 @item ^-gnath^/HELP^
4157 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4158 Output usage information. The output is written to @file{stdout}.
4159
4160 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4161 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4162 Identifier character set
4163 @ifclear vms
4164 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4165 @end ifclear
4166 For details of the possible selections for @var{c},
4167 see @ref{Character Set Control}.
4168
4169 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4170 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4171 Ignore representation clauses. When this switch is used, all
4172 representation clauses are treated as comments. This is useful
4173 when initially porting code where you want to ignore rep clause
4174 problems, and also for compiling foreign code (particularly
4175 for use with ASIS).
4176
4177 @item -gnatjnn
4178 @cindex @option{-gnatjnn} (@command{gcc})
4179 Reformat error messages to fit on nn character lines
4180
4181 @item -gnatk=@var{n}
4182 @cindex @option{-gnatk} (@command{gcc})
4183 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4184
4185 @item -gnatl
4186 @cindex @option{-gnatl} (@command{gcc})
4187 Output full source listing with embedded error messages.
4188
4189 @item -gnatL
4190 @cindex @option{-gnatL} (@command{gcc})
4191 Used in conjunction with -gnatG or -gnatD to intersperse original
4192 source lines (as comment lines with line numbers) in the expanded
4193 source output.
4194
4195 @item -gnatm=@var{n}
4196 @cindex @option{-gnatm} (@command{gcc})
4197 Limit number of detected error or warning messages to @var{n}
4198 where @var{n} is in the range 1..999999. The default setting if
4199 no switch is given is 9999. If the number of warnings reaches this
4200 limit, then a message is output and further warnings are suppressed,
4201 but the compilation is continued. If the number of error messages
4202 reaches this limit, then a message is output and the compilation
4203 is abandoned. The equal sign here is optional. A value of zero
4204 means that no limit applies.
4205
4206 @item -gnatn
4207 @cindex @option{-gnatn} (@command{gcc})
4208 Activate inlining for subprograms for which
4209 pragma @code{inline} is specified. This inlining is performed
4210 by the GCC back-end.
4211
4212 @item -gnatN
4213 @cindex @option{-gnatN} (@command{gcc})
4214 Activate front end inlining for subprograms for which
4215 pragma @code{Inline} is specified. This inlining is performed
4216 by the front end and will be visible in the
4217 @option{-gnatG} output.
4218
4219 When using a gcc-based back end (in practice this means using any version
4220 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4221 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4222 Historically front end inlining was more extensive than the gcc back end
4223 inlining, but that is no longer the case.
4224
4225 @item -gnato
4226 @cindex @option{-gnato} (@command{gcc})
4227 Enable numeric overflow checking (which is not normally enabled by
4228 default). Note that division by zero is a separate check that is not
4229 controlled by this switch (division by zero checking is on by default).
4230
4231 @item -gnatp
4232 @cindex @option{-gnatp} (@command{gcc})
4233 Suppress all checks. See @ref{Run-Time Checks} for details.
4234
4235 @item -gnatP
4236 @cindex @option{-gnatP} (@command{gcc})
4237 Enable polling. This is required on some systems (notably Windows NT) to
4238 obtain asynchronous abort and asynchronous transfer of control capability.
4239 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4240 details.
4241
4242 @item -gnatq
4243 @cindex @option{-gnatq} (@command{gcc})
4244 Don't quit. Try semantics, even if parse errors.
4245
4246 @item -gnatQ
4247 @cindex @option{-gnatQ} (@command{gcc})
4248 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4249
4250 @item -gnatr
4251 @cindex @option{-gnatr} (@command{gcc})
4252 Treat pragma Restrictions as Restriction_Warnings.
4253
4254 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4255 @cindex @option{-gnatR} (@command{gcc})
4256 Output representation information for declared types and objects.
4257
4258 @item -gnats
4259 @cindex @option{-gnats} (@command{gcc})
4260 Syntax check only.
4261
4262 @item -gnatS
4263 @cindex @option{-gnatS} (@command{gcc})
4264 Print package Standard.
4265
4266 @item -gnatt
4267 @cindex @option{-gnatt} (@command{gcc})
4268 Generate tree output file.
4269
4270 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4271 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4272 All compiler tables start at @var{nnn} times usual starting size.
4273
4274 @item -gnatu
4275 @cindex @option{-gnatu} (@command{gcc})
4276 List units for this compilation.
4277
4278 @item -gnatU
4279 @cindex @option{-gnatU} (@command{gcc})
4280 Tag all error messages with the unique string ``error:''
4281
4282 @item -gnatv
4283 @cindex @option{-gnatv} (@command{gcc})
4284 Verbose mode. Full error output with source lines to @file{stdout}.
4285
4286 @item -gnatV
4287 @cindex @option{-gnatV} (@command{gcc})
4288 Control level of validity checking. See separate section describing
4289 this feature.
4290
4291 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4292 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4293 Warning mode where
4294 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4295 the exact warnings that
4296 are enabled or disabled (@pxref{Warning Message Control}).
4297
4298 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4299 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4300 Wide character encoding method
4301 @ifclear vms
4302 (@var{e}=n/h/u/s/e/8).
4303 @end ifclear
4304 @ifset vms
4305 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4306 @end ifset
4307
4308 @item -gnatx
4309 @cindex @option{-gnatx} (@command{gcc})
4310 Suppress generation of cross-reference information.
4311
4312 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4313 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4314 Enable built-in style checks (@pxref{Style Checking}).
4315
4316 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4317 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4318 Distribution stub generation and compilation
4319 @ifclear vms
4320 (@var{m}=r/c for receiver/caller stubs).
4321 @end ifclear
4322 @ifset vms
4323 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4324 to be generated and compiled).
4325 @end ifset
4326
4327 @item ^-I^/SEARCH=^@var{dir}
4328 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4329 @cindex RTL
4330 Direct GNAT to search the @var{dir} directory for source files needed by
4331 the current compilation
4332 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4333
4334 @item ^-I-^/NOCURRENT_DIRECTORY^
4335 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4336 @cindex RTL
4337 Except for the source file named in the command line, do not look for source
4338 files in the directory containing the source file named in the command line
4339 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4340
4341 @ifclear vms
4342 @item -mbig-switch
4343 @cindex @option{-mbig-switch} (@command{gcc})
4344 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4345 This standard gcc switch causes the compiler to use larger offsets in its
4346 jump table representation for @code{case} statements.
4347 This may result in less efficient code, but is sometimes necessary
4348 (for example on HP-UX targets)
4349 @cindex HP-UX and @option{-mbig-switch} option
4350 in order to compile large and/or nested @code{case} statements.
4351
4352 @item -o @var{file}
4353 @cindex @option{-o} (@command{gcc})
4354 This switch is used in @command{gcc} to redirect the generated object file
4355 and its associated ALI file. Beware of this switch with GNAT, because it may
4356 cause the object file and ALI file to have different names which in turn
4357 may confuse the binder and the linker.
4358 @end ifclear
4359
4360 @item -nostdinc
4361 @cindex @option{-nostdinc} (@command{gcc})
4362 Inhibit the search of the default location for the GNAT Run Time
4363 Library (RTL) source files.
4364
4365 @item -nostdlib
4366 @cindex @option{-nostdlib} (@command{gcc})
4367 Inhibit the search of the default location for the GNAT Run Time
4368 Library (RTL) ALI files.
4369
4370 @ifclear vms
4371 @item -O@ovar{n}
4372 @cindex @option{-O} (@command{gcc})
4373 @var{n} controls the optimization level.
4374
4375 @table @asis
4376 @item n = 0
4377 No optimization, the default setting if no @option{-O} appears
4378
4379 @item n = 1
4380 Normal optimization, the default if you specify @option{-O} without
4381 an operand. A good compromise between code quality and compilation
4382 time.
4383
4384 @item n = 2
4385 Extensive optimization, may improve execution time, possibly at the cost of
4386 substantially increased compilation time.
4387
4388 @item n = 3
4389 Same as @option{-O2}, and also includes inline expansion for small subprograms
4390 in the same unit.
4391
4392 @item n = s
4393 Optimize space usage
4394 @end table
4395
4396 @noindent
4397 See also @ref{Optimization Levels}.
4398 @end ifclear
4399
4400 @ifset vms
4401 @item /NOOPTIMIZE
4402 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4403 Equivalent to @option{/OPTIMIZE=NONE}.
4404 This is the default behavior in the absence of an @option{/OPTIMIZE}
4405 qualifier.
4406
4407 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4408 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4409 Selects the level of optimization for your program. The supported
4410 keywords are as follows:
4411 @table @code
4412 @item ALL
4413 Perform most optimizations, including those that
4414 are expensive.
4415 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4416 without keyword options.
4417
4418 @item NONE
4419 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4420
4421 @item SOME
4422 Perform some optimizations, but omit ones that are costly.
4423
4424 @item DEVELOPMENT
4425 Same as @code{SOME}.
4426
4427 @item INLINING
4428 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4429 automatic inlining of small subprograms within a unit
4430
4431 @item UNROLL_LOOPS
4432 Try to unroll loops. This keyword may be specified together with
4433 any keyword above other than @code{NONE}. Loop unrolling
4434 usually, but not always, improves the performance of programs.
4435
4436 @item SPACE
4437 Optimize space usage
4438 @end table
4439
4440 @noindent
4441 See also @ref{Optimization Levels}.
4442 @end ifset
4443
4444 @ifclear vms
4445 @item -pass-exit-codes
4446 @cindex @option{-pass-exit-codes} (@command{gcc})
4447 Catch exit codes from the compiler and use the most meaningful as
4448 exit status.
4449 @end ifclear
4450
4451 @item --RTS=@var{rts-path}
4452 @cindex @option{--RTS} (@command{gcc})
4453 Specifies the default location of the runtime library. Same meaning as the
4454 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4455
4456 @item ^-S^/ASM^
4457 @cindex @option{^-S^/ASM^} (@command{gcc})
4458 ^Used in place of @option{-c} to^Used to^
4459 cause the assembler source file to be
4460 generated, using @file{^.s^.S^} as the extension,
4461 instead of the object file.
4462 This may be useful if you need to examine the generated assembly code.
4463
4464 @item ^-fverbose-asm^/VERBOSE_ASM^
4465 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4466 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4467 to cause the generated assembly code file to be annotated with variable
4468 names, making it significantly easier to follow.
4469
4470 @item ^-v^/VERBOSE^
4471 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4472 Show commands generated by the @command{gcc} driver. Normally used only for
4473 debugging purposes or if you need to be sure what version of the
4474 compiler you are executing.
4475
4476 @ifclear vms
4477 @item -V @var{ver}
4478 @cindex @option{-V} (@command{gcc})
4479 Execute @var{ver} version of the compiler. This is the @command{gcc}
4480 version, not the GNAT version.
4481 @end ifclear
4482
4483 @item ^-w^/NO_BACK_END_WARNINGS^
4484 @cindex @option{-w} (@command{gcc})
4485 Turn off warnings generated by the back end of the compiler. Use of
4486 this switch also causes the default for front end warnings to be set
4487 to suppress (as though @option{-gnatws} had appeared at the start of
4488 the options).
4489
4490 @end table
4491
4492 @ifclear vms
4493 @c Combining qualifiers does not work on VMS
4494 You may combine a sequence of GNAT switches into a single switch. For
4495 example, the combined switch
4496
4497 @cindex Combining GNAT switches
4498 @smallexample
4499 -gnatofi3
4500 @end smallexample
4501
4502 @noindent
4503 is equivalent to specifying the following sequence of switches:
4504
4505 @smallexample
4506 -gnato -gnatf -gnati3
4507 @end smallexample
4508 @end ifclear
4509
4510 @noindent
4511 The following restrictions apply to the combination of switches
4512 in this manner:
4513
4514 @itemize @bullet
4515 @item
4516 The switch @option{-gnatc} if combined with other switches must come
4517 first in the string.
4518
4519 @item
4520 The switch @option{-gnats} if combined with other switches must come
4521 first in the string.
4522
4523 @item
4524 The switches
4525 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4526 may not be combined with any other switches.
4527
4528 @ifclear vms
4529 @item
4530 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4531 switch), then all further characters in the switch are interpreted
4532 as style modifiers (see description of @option{-gnaty}).
4533
4534 @item
4535 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4536 switch), then all further characters in the switch are interpreted
4537 as debug flags (see description of @option{-gnatd}).
4538
4539 @item
4540 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4541 switch), then all further characters in the switch are interpreted
4542 as warning mode modifiers (see description of @option{-gnatw}).
4543
4544 @item
4545 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4546 switch), then all further characters in the switch are interpreted
4547 as validity checking options (see description of @option{-gnatV}).
4548 @end ifclear
4549 @end itemize
4550
4551 @node Output and Error Message Control
4552 @subsection Output and Error Message Control
4553 @findex stderr
4554
4555 @noindent
4556 The standard default format for error messages is called ``brief format''.
4557 Brief format messages are written to @file{stderr} (the standard error
4558 file) and have the following form:
4559
4560 @smallexample
4561 e.adb:3:04: Incorrect spelling of keyword "function"
4562 e.adb:4:20: ";" should be "is"
4563 @end smallexample
4564
4565 @noindent
4566 The first integer after the file name is the line number in the file,
4567 and the second integer is the column number within the line.
4568 @ifclear vms
4569 @code{GPS} can parse the error messages
4570 and point to the referenced character.
4571 @end ifclear
4572 The following switches provide control over the error message
4573 format:
4574
4575 @table @option
4576 @c !sort!
4577 @item -gnatv
4578 @cindex @option{-gnatv} (@command{gcc})
4579 @findex stdout
4580 @ifclear vms
4581 The v stands for verbose.
4582 @end ifclear
4583 The effect of this setting is to write long-format error
4584 messages to @file{stdout} (the standard output file.
4585 The same program compiled with the
4586 @option{-gnatv} switch would generate:
4587
4588 @smallexample
4589 @cartouche
4590 3. funcion X (Q : Integer)
4591 |
4592 >>> Incorrect spelling of keyword "function"
4593 4. return Integer;
4594 |
4595 >>> ";" should be "is"
4596 @end cartouche
4597 @end smallexample
4598
4599 @noindent
4600 The vertical bar indicates the location of the error, and the @samp{>>>}
4601 prefix can be used to search for error messages. When this switch is
4602 used the only source lines output are those with errors.
4603
4604 @item -gnatl
4605 @cindex @option{-gnatl} (@command{gcc})
4606 @ifclear vms
4607 The @code{l} stands for list.
4608 @end ifclear
4609 This switch causes a full listing of
4610 the file to be generated. In the case where a body is
4611 compiled, the corresponding spec is also listed, along
4612 with any subunits. Typical output from compiling a package
4613 body @file{p.adb} might look like:
4614
4615 @smallexample @c ada
4616 @cartouche
4617 Compiling: p.adb
4618
4619 1. package body p is
4620 2. procedure a;
4621 3. procedure a is separate;
4622 4. begin
4623 5. null
4624 |
4625 >>> missing ";"
4626
4627 6. end;
4628
4629 Compiling: p.ads
4630
4631 1. package p is
4632 2. pragma Elaborate_Body
4633 |
4634 >>> missing ";"
4635
4636 3. end p;
4637
4638 Compiling: p-a.adb
4639
4640 1. separate p
4641 |
4642 >>> missing "("
4643
4644 2. procedure a is
4645 3. begin
4646 4. null
4647 |
4648 >>> missing ";"
4649
4650 5. end;
4651 @end cartouche
4652 @end smallexample
4653
4654 @noindent
4655 @findex stderr
4656 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4657 standard output is redirected, a brief summary is written to
4658 @file{stderr} (standard error) giving the number of error messages and
4659 warning messages generated.
4660
4661 @item -^gnatl^OUTPUT_FILE^=file
4662 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4663 This has the same effect as @option{-gnatl} except that the output is
4664 written to a file instead of to standard output. If the given name
4665 @file{fname} does not start with a period, then it is the full name
4666 of the file to be written. If @file{fname} is an extension, it is
4667 appended to the name of the file being compiled. For example, if
4668 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4669 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4670
4671 @item -gnatU
4672 @cindex @option{-gnatU} (@command{gcc})
4673 This switch forces all error messages to be preceded by the unique
4674 string ``error:''. This means that error messages take a few more
4675 characters in space, but allows easy searching for and identification
4676 of error messages.
4677
4678 @item -gnatb
4679 @cindex @option{-gnatb} (@command{gcc})
4680 @ifclear vms
4681 The @code{b} stands for brief.
4682 @end ifclear
4683 This switch causes GNAT to generate the
4684 brief format error messages to @file{stderr} (the standard error
4685 file) as well as the verbose
4686 format message or full listing (which as usual is written to
4687 @file{stdout} (the standard output file).
4688
4689 @item -gnatm=@var{n}
4690 @cindex @option{-gnatm} (@command{gcc})
4691 @ifclear vms
4692 The @code{m} stands for maximum.
4693 @end ifclear
4694 @var{n} is a decimal integer in the
4695 range of 1 to 999999 and limits the number of error or warning
4696 messages to be generated. For example, using
4697 @option{-gnatm2} might yield
4698
4699 @smallexample
4700 e.adb:3:04: Incorrect spelling of keyword "function"
4701 e.adb:5:35: missing ".."
4702 fatal error: maximum number of errors detected
4703 compilation abandoned
4704 @end smallexample
4705
4706 @noindent
4707 The default setting if
4708 no switch is given is 9999. If the number of warnings reaches this
4709 limit, then a message is output and further warnings are suppressed,
4710 but the compilation is continued. If the number of error messages
4711 reaches this limit, then a message is output and the compilation
4712 is abandoned. A value of zero means that no limit applies.
4713
4714 @noindent
4715 Note that the equal sign is optional, so the switches
4716 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4717
4718 @item -gnatf
4719 @cindex @option{-gnatf} (@command{gcc})
4720 @cindex Error messages, suppressing
4721 @ifclear vms
4722 The @code{f} stands for full.
4723 @end ifclear
4724 Normally, the compiler suppresses error messages that are likely to be
4725 redundant. This switch causes all error
4726 messages to be generated. In particular, in the case of
4727 references to undefined variables. If a given variable is referenced
4728 several times, the normal format of messages is
4729 @smallexample
4730 e.adb:7:07: "V" is undefined (more references follow)
4731 @end smallexample
4732
4733 @noindent
4734 where the parenthetical comment warns that there are additional
4735 references to the variable @code{V}. Compiling the same program with the
4736 @option{-gnatf} switch yields
4737
4738 @smallexample
4739 e.adb:7:07: "V" is undefined
4740 e.adb:8:07: "V" is undefined
4741 e.adb:8:12: "V" is undefined
4742 e.adb:8:16: "V" is undefined
4743 e.adb:9:07: "V" is undefined
4744 e.adb:9:12: "V" is undefined
4745 @end smallexample
4746
4747 @noindent
4748 The @option{-gnatf} switch also generates additional information for
4749 some error messages. Some examples are:
4750
4751 @itemize @bullet
4752 @item
4753 Full details on entities not available in high integrity mode
4754 @item
4755 Details on possibly non-portable unchecked conversion
4756 @item
4757 List possible interpretations for ambiguous calls
4758 @item
4759 Additional details on incorrect parameters
4760 @end itemize
4761
4762 @item -gnatjnn
4763 @cindex @option{-gnatjnn} (@command{gcc})
4764 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4765 with continuation lines are treated as though the continuation lines were
4766 separate messages (and so a warning with two continuation lines counts as
4767 three warnings, and is listed as three separate messages).
4768
4769 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4770 messages are output in a different manner. A message and all its continuation
4771 lines are treated as a unit, and count as only one warning or message in the
4772 statistics totals. Furthermore, the message is reformatted so that no line
4773 is longer than nn characters.
4774
4775 @item -gnatq
4776 @cindex @option{-gnatq} (@command{gcc})
4777 @ifclear vms
4778 The @code{q} stands for quit (really ``don't quit'').
4779 @end ifclear
4780 In normal operation mode, the compiler first parses the program and
4781 determines if there are any syntax errors. If there are, appropriate
4782 error messages are generated and compilation is immediately terminated.
4783 This switch tells
4784 GNAT to continue with semantic analysis even if syntax errors have been
4785 found. This may enable the detection of more errors in a single run. On
4786 the other hand, the semantic analyzer is more likely to encounter some
4787 internal fatal error when given a syntactically invalid tree.
4788
4789 @item -gnatQ
4790 @cindex @option{-gnatQ} (@command{gcc})
4791 In normal operation mode, the @file{ALI} file is not generated if any
4792 illegalities are detected in the program. The use of @option{-gnatQ} forces
4793 generation of the @file{ALI} file. This file is marked as being in
4794 error, so it cannot be used for binding purposes, but it does contain
4795 reasonably complete cross-reference information, and thus may be useful
4796 for use by tools (e.g., semantic browsing tools or integrated development
4797 environments) that are driven from the @file{ALI} file. This switch
4798 implies @option{-gnatq}, since the semantic phase must be run to get a
4799 meaningful ALI file.
4800
4801 In addition, if @option{-gnatt} is also specified, then the tree file is
4802 generated even if there are illegalities. It may be useful in this case
4803 to also specify @option{-gnatq} to ensure that full semantic processing
4804 occurs. The resulting tree file can be processed by ASIS, for the purpose
4805 of providing partial information about illegal units, but if the error
4806 causes the tree to be badly malformed, then ASIS may crash during the
4807 analysis.
4808
4809 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4810 being in error, @command{gnatmake} will attempt to recompile the source when it
4811 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4812
4813 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4814 since ALI files are never generated if @option{-gnats} is set.
4815
4816 @end table
4817
4818 @node Warning Message Control
4819 @subsection Warning Message Control
4820 @cindex Warning messages
4821 @noindent
4822 In addition to error messages, which correspond to illegalities as defined
4823 in the Ada Reference Manual, the compiler detects two kinds of warning
4824 situations.
4825
4826 First, the compiler considers some constructs suspicious and generates a
4827 warning message to alert you to a possible error. Second, if the
4828 compiler detects a situation that is sure to raise an exception at
4829 run time, it generates a warning message. The following shows an example
4830 of warning messages:
4831 @smallexample
4832 e.adb:4:24: warning: creation of object may raise Storage_Error
4833 e.adb:10:17: warning: static value out of range
4834 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4835 @end smallexample
4836
4837 @noindent
4838 GNAT considers a large number of situations as appropriate
4839 for the generation of warning messages. As always, warnings are not
4840 definite indications of errors. For example, if you do an out-of-range
4841 assignment with the deliberate intention of raising a
4842 @code{Constraint_Error} exception, then the warning that may be
4843 issued does not indicate an error. Some of the situations for which GNAT
4844 issues warnings (at least some of the time) are given in the following
4845 list. This list is not complete, and new warnings are often added to
4846 subsequent versions of GNAT. The list is intended to give a general idea
4847 of the kinds of warnings that are generated.
4848
4849 @itemize @bullet
4850 @item
4851 Possible infinitely recursive calls
4852
4853 @item
4854 Out-of-range values being assigned
4855
4856 @item
4857 Possible order of elaboration problems
4858
4859 @item
4860 Assertions (pragma Assert) that are sure to fail
4861
4862 @item
4863 Unreachable code
4864
4865 @item
4866 Address clauses with possibly unaligned values, or where an attempt is
4867 made to overlay a smaller variable with a larger one.
4868
4869 @item
4870 Fixed-point type declarations with a null range
4871
4872 @item
4873 Direct_IO or Sequential_IO instantiated with a type that has access values
4874
4875 @item
4876 Variables that are never assigned a value
4877
4878 @item
4879 Variables that are referenced before being initialized
4880
4881 @item
4882 Task entries with no corresponding @code{accept} statement
4883
4884 @item
4885 Duplicate accepts for the same task entry in a @code{select}
4886
4887 @item
4888 Objects that take too much storage
4889
4890 @item
4891 Unchecked conversion between types of differing sizes
4892
4893 @item
4894 Missing @code{return} statement along some execution path in a function
4895
4896 @item
4897 Incorrect (unrecognized) pragmas
4898
4899 @item
4900 Incorrect external names
4901
4902 @item
4903 Allocation from empty storage pool
4904
4905 @item
4906 Potentially blocking operation in protected type
4907
4908 @item
4909 Suspicious parenthesization of expressions
4910
4911 @item
4912 Mismatching bounds in an aggregate
4913
4914 @item
4915 Attempt to return local value by reference
4916
4917 @item
4918 Premature instantiation of a generic body
4919
4920 @item
4921 Attempt to pack aliased components
4922
4923 @item
4924 Out of bounds array subscripts
4925
4926 @item
4927 Wrong length on string assignment
4928
4929 @item
4930 Violations of style rules if style checking is enabled
4931
4932 @item
4933 Unused @code{with} clauses
4934
4935 @item
4936 @code{Bit_Order} usage that does not have any effect
4937
4938 @item
4939 @code{Standard.Duration} used to resolve universal fixed expression
4940
4941 @item
4942 Dereference of possibly null value
4943
4944 @item
4945 Declaration that is likely to cause storage error
4946
4947 @item
4948 Internal GNAT unit @code{with}'ed by application unit
4949
4950 @item
4951 Values known to be out of range at compile time
4952
4953 @item
4954 Unreferenced labels and variables
4955
4956 @item
4957 Address overlays that could clobber memory
4958
4959 @item
4960 Unexpected initialization when address clause present
4961
4962 @item
4963 Bad alignment for address clause
4964
4965 @item
4966 Useless type conversions
4967
4968 @item
4969 Redundant assignment statements and other redundant constructs
4970
4971 @item
4972 Useless exception handlers
4973
4974 @item
4975 Accidental hiding of name by child unit
4976
4977 @item
4978 Access before elaboration detected at compile time
4979
4980 @item
4981 A range in a @code{for} loop that is known to be null or might be null
4982
4983 @end itemize
4984
4985 @noindent
4986 The following section lists compiler switches that are available
4987 to control the handling of warning messages. It is also possible
4988 to exercise much finer control over what warnings are issued and
4989 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4990 gnat_rm, GNAT Reference manual}.
4991
4992 @table @option
4993 @c !sort!
4994 @item -gnatwa
4995 @emph{Activate all optional errors.}
4996 @cindex @option{-gnatwa} (@command{gcc})
4997 This switch activates most optional warning messages, see remaining list
4998 in this section for details on optional warning messages that can be
4999 individually controlled. The warnings that are not turned on by this
5000 switch are
5001 @option{-gnatwd} (implicit dereferencing),
5002 @option{-gnatwh} (hiding),
5003 @option{-gnatwl} (elaboration warnings),
5004 @option{-gnatw.o} (warn on values set by out parameters ignored)
5005 and @option{-gnatwt} (tracking of deleted conditional code).
5006 All other optional warnings are turned on.
5007
5008 @item -gnatwA
5009 @emph{Suppress all optional errors.}
5010 @cindex @option{-gnatwA} (@command{gcc})
5011 This switch suppresses all optional warning messages, see remaining list
5012 in this section for details on optional warning messages that can be
5013 individually controlled.
5014
5015 @item -gnatw.a
5016 @emph{Activate warnings on failing assertions.}
5017 @cindex @option{-gnatw.a} (@command{gcc})
5018 @cindex Assert failures
5019 This switch activates warnings for assertions where the compiler can tell at
5020 compile time that the assertion will fail. Note that this warning is given
5021 even if assertions are disabled. The default is that such warnings are
5022 generated.
5023
5024 @item -gnatw.A
5025 @emph{Suppress warnings on failing assertions.}
5026 @cindex @option{-gnatw.A} (@command{gcc})
5027 @cindex Assert failures
5028 This switch suppresses warnings for assertions where the compiler can tell at
5029 compile time that the assertion will fail.
5030
5031 @item -gnatwb
5032 @emph{Activate warnings on bad fixed values.}
5033 @cindex @option{-gnatwb} (@command{gcc})
5034 @cindex Bad fixed values
5035 @cindex Fixed-point Small value
5036 @cindex Small value
5037 This switch activates warnings for static fixed-point expressions whose
5038 value is not an exact multiple of Small. Such values are implementation
5039 dependent, since an implementation is free to choose either of the multiples
5040 that surround the value. GNAT always chooses the closer one, but this is not
5041 required behavior, and it is better to specify a value that is an exact
5042 multiple, ensuring predictable execution. The default is that such warnings
5043 are not generated.
5044
5045 @item -gnatwB
5046 @emph{Suppress warnings on bad fixed values.}
5047 @cindex @option{-gnatwB} (@command{gcc})
5048 This switch suppresses warnings for static fixed-point expressions whose
5049 value is not an exact multiple of Small.
5050
5051 @item -gnatw.b
5052 @emph{Activate warnings on biased representation.}
5053 @cindex @option{-gnatw.b} (@command{gcc})
5054 @cindex Biased representation
5055 This switch activates warnings when a size clause, value size clause, component
5056 clause, or component size clause forces the use of biased representation for an
5057 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5058 to represent 10/11). The default is that such warnings are generated.
5059
5060 @item -gnatw.B
5061 @emph{Suppress warnings on biased representation.}
5062 @cindex @option{-gnatwB} (@command{gcc})
5063 This switch suppresses warnings for representation clauses that force the use
5064 of biased representation.
5065
5066 @item -gnatwc
5067 @emph{Activate warnings on conditionals.}
5068 @cindex @option{-gnatwc} (@command{gcc})
5069 @cindex Conditionals, constant
5070 This switch activates warnings for conditional expressions used in
5071 tests that are known to be True or False at compile time. The default
5072 is that such warnings are not generated.
5073 Note that this warning does
5074 not get issued for the use of boolean variables or constants whose
5075 values are known at compile time, since this is a standard technique
5076 for conditional compilation in Ada, and this would generate too many
5077 false positive warnings.
5078
5079 This warning option also activates a special test for comparisons using
5080 the operators ``>='' and`` <=''.
5081 If the compiler can tell that only the equality condition is possible,
5082 then it will warn that the ``>'' or ``<'' part of the test
5083 is useless and that the operator could be replaced by ``=''.
5084 An example would be comparing a @code{Natural} variable <= 0.
5085
5086 This warning option also generates warnings if
5087 one or both tests is optimized away in a membership test for integer
5088 values if the result can be determined at compile time. Range tests on
5089 enumeration types are not included, since it is common for such tests
5090 to include an end point.
5091
5092 This warning can also be turned on using @option{-gnatwa}.
5093
5094 @item -gnatwC
5095 @emph{Suppress warnings on conditionals.}
5096 @cindex @option{-gnatwC} (@command{gcc})
5097 This switch suppresses warnings for conditional expressions used in
5098 tests that are known to be True or False at compile time.
5099
5100 @item -gnatw.c
5101 @emph{Activate warnings on missing component clauses.}
5102 @cindex @option{-gnatw.c} (@command{gcc})
5103 @cindex Component clause, missing
5104 This switch activates warnings for record components where a record
5105 representation clause is present and has component clauses for the
5106 majority, but not all, of the components. A warning is given for each
5107 component for which no component clause is present.
5108
5109 This warning can also be turned on using @option{-gnatwa}.
5110
5111 @item -gnatw.C
5112 @emph{Suppress warnings on missing component clauses.}
5113 @cindex @option{-gnatwC} (@command{gcc})
5114 This switch suppresses warnings for record components that are
5115 missing a component clause in the situation described above.
5116
5117 @item -gnatwd
5118 @emph{Activate warnings on implicit dereferencing.}
5119 @cindex @option{-gnatwd} (@command{gcc})
5120 If this switch is set, then the use of a prefix of an access type
5121 in an indexed component, slice, or selected component without an
5122 explicit @code{.all} will generate a warning. With this warning
5123 enabled, access checks occur only at points where an explicit
5124 @code{.all} appears in the source code (assuming no warnings are
5125 generated as a result of this switch). The default is that such
5126 warnings are not generated.
5127 Note that @option{-gnatwa} does not affect the setting of
5128 this warning option.
5129
5130 @item -gnatwD
5131 @emph{Suppress warnings on implicit dereferencing.}
5132 @cindex @option{-gnatwD} (@command{gcc})
5133 @cindex Implicit dereferencing
5134 @cindex Dereferencing, implicit
5135 This switch suppresses warnings for implicit dereferences in
5136 indexed components, slices, and selected components.
5137
5138 @item -gnatwe
5139 @emph{Treat warnings as errors.}
5140 @cindex @option{-gnatwe} (@command{gcc})
5141 @cindex Warnings, treat as error
5142 This switch causes warning messages to be treated as errors.
5143 The warning string still appears, but the warning messages are counted
5144 as errors, and prevent the generation of an object file.
5145
5146 @item -gnatw.e
5147 @emph{Activate every optional warning}
5148 @cindex @option{-gnatw.e} (@command{gcc})
5149 @cindex Warnings, activate every optional warning
5150 This switch activates all optional warnings, including those which
5151 are not activated by @code{-gnatwa}.
5152
5153 @item -gnatwf
5154 @emph{Activate warnings on unreferenced formals.}
5155 @cindex @option{-gnatwf} (@command{gcc})
5156 @cindex Formals, unreferenced
5157 This switch causes a warning to be generated if a formal parameter
5158 is not referenced in the body of the subprogram. This warning can
5159 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5160 default is that these warnings are not generated.
5161
5162 @item -gnatwF
5163 @emph{Suppress warnings on unreferenced formals.}
5164 @cindex @option{-gnatwF} (@command{gcc})
5165 This switch suppresses warnings for unreferenced formal
5166 parameters. Note that the
5167 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5168 effect of warning on unreferenced entities other than subprogram
5169 formals.
5170
5171 @item -gnatwg
5172 @emph{Activate warnings on unrecognized pragmas.}
5173 @cindex @option{-gnatwg} (@command{gcc})
5174 @cindex Pragmas, unrecognized
5175 This switch causes a warning to be generated if an unrecognized
5176 pragma is encountered. Apart from issuing this warning, the
5177 pragma is ignored and has no effect. This warning can
5178 also be turned on using @option{-gnatwa}. The default
5179 is that such warnings are issued (satisfying the Ada Reference
5180 Manual requirement that such warnings appear).
5181
5182 @item -gnatwG
5183 @emph{Suppress warnings on unrecognized pragmas.}
5184 @cindex @option{-gnatwG} (@command{gcc})
5185 This switch suppresses warnings for unrecognized pragmas.
5186
5187 @item -gnatwh
5188 @emph{Activate warnings on hiding.}
5189 @cindex @option{-gnatwh} (@command{gcc})
5190 @cindex Hiding of Declarations
5191 This switch activates warnings on hiding declarations.
5192 A declaration is considered hiding
5193 if it is for a non-overloadable entity, and it declares an entity with the
5194 same name as some other entity that is directly or use-visible. The default
5195 is that such warnings are not generated.
5196 Note that @option{-gnatwa} does not affect the setting of this warning option.
5197
5198 @item -gnatwH
5199 @emph{Suppress warnings on hiding.}
5200 @cindex @option{-gnatwH} (@command{gcc})
5201 This switch suppresses warnings on hiding declarations.
5202
5203 @item -gnatwi
5204 @emph{Activate warnings on implementation units.}
5205 @cindex @option{-gnatwi} (@command{gcc})
5206 This switch activates warnings for a @code{with} of an internal GNAT
5207 implementation unit, defined as any unit from the @code{Ada},
5208 @code{Interfaces}, @code{GNAT},
5209 ^^@code{DEC},^ or @code{System}
5210 hierarchies that is not
5211 documented in either the Ada Reference Manual or the GNAT
5212 Programmer's Reference Manual. Such units are intended only
5213 for internal implementation purposes and should not be @code{with}'ed
5214 by user programs. The default is that such warnings are generated
5215 This warning can also be turned on using @option{-gnatwa}.
5216
5217 @item -gnatwI
5218 @emph{Disable warnings on implementation units.}
5219 @cindex @option{-gnatwI} (@command{gcc})
5220 This switch disables warnings for a @code{with} of an internal GNAT
5221 implementation unit.
5222
5223 @item -gnatwj
5224 @emph{Activate warnings on obsolescent features (Annex J).}
5225 @cindex @option{-gnatwj} (@command{gcc})
5226 @cindex Features, obsolescent
5227 @cindex Obsolescent features
5228 If this warning option is activated, then warnings are generated for
5229 calls to subprograms marked with @code{pragma Obsolescent} and
5230 for use of features in Annex J of the Ada Reference Manual. In the
5231 case of Annex J, not all features are flagged. In particular use
5232 of the renamed packages (like @code{Text_IO}) and use of package
5233 @code{ASCII} are not flagged, since these are very common and
5234 would generate many annoying positive warnings. The default is that
5235 such warnings are not generated. This warning is also turned on by
5236 the use of @option{-gnatwa}.
5237
5238 In addition to the above cases, warnings are also generated for
5239 GNAT features that have been provided in past versions but which
5240 have been superseded (typically by features in the new Ada standard).
5241 For example, @code{pragma Ravenscar} will be flagged since its
5242 function is replaced by @code{pragma Profile(Ravenscar)}.
5243
5244 Note that this warning option functions differently from the
5245 restriction @code{No_Obsolescent_Features} in two respects.
5246 First, the restriction applies only to annex J features.
5247 Second, the restriction does flag uses of package @code{ASCII}.
5248
5249 @item -gnatwJ
5250 @emph{Suppress warnings on obsolescent features (Annex J).}
5251 @cindex @option{-gnatwJ} (@command{gcc})
5252 This switch disables warnings on use of obsolescent features.
5253
5254 @item -gnatwk
5255 @emph{Activate warnings on variables that could be constants.}
5256 @cindex @option{-gnatwk} (@command{gcc})
5257 This switch activates warnings for variables that are initialized but
5258 never modified, and then could be declared constants. The default is that
5259 such warnings are not given.
5260 This warning can also be turned on using @option{-gnatwa}.
5261
5262 @item -gnatwK
5263 @emph{Suppress warnings on variables that could be constants.}
5264 @cindex @option{-gnatwK} (@command{gcc})
5265 This switch disables warnings on variables that could be declared constants.
5266
5267 @item -gnatwl
5268 @emph{Activate warnings for elaboration pragmas.}
5269 @cindex @option{-gnatwl} (@command{gcc})
5270 @cindex Elaboration, warnings
5271 This switch activates warnings on missing
5272 @code{Elaborate_All} and @code{Elaborate} pragmas.
5273 See the section in this guide on elaboration checking for details on
5274 when such pragmas should be used. In dynamic elaboration mode, this switch
5275 generations warnings about the need to add elaboration pragmas. Note however,
5276 that if you blindly follow these warnings, and add @code{Elaborate_All}
5277 warnings wherever they are recommended, you basically end up with the
5278 equivalent of the static elaboration model, which may not be what you want for
5279 legacy code for which the static model does not work.
5280
5281 For the static model, the messages generated are labeled "info:" (for
5282 information messages). They are not warnings to add elaboration pragmas,
5283 merely informational messages showing what implicit elaboration pragmas
5284 have been added, for use in analyzing elaboration circularity problems.
5285
5286 Warnings are also generated if you
5287 are using the static mode of elaboration, and a @code{pragma Elaborate}
5288 is encountered. The default is that such warnings
5289 are not generated.
5290 This warning is not automatically turned on by the use of @option{-gnatwa}.
5291
5292 @item -gnatwL
5293 @emph{Suppress warnings for elaboration pragmas.}
5294 @cindex @option{-gnatwL} (@command{gcc})
5295 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5296 See the section in this guide on elaboration checking for details on
5297 when such pragmas should be used.
5298
5299 @item -gnatwm
5300 @emph{Activate warnings on modified but unreferenced variables.}
5301 @cindex @option{-gnatwm} (@command{gcc})
5302 This switch activates warnings for variables that are assigned (using
5303 an initialization value or with one or more assignment statements) but
5304 whose value is never read. The warning is suppressed for volatile
5305 variables and also for variables that are renamings of other variables
5306 or for which an address clause is given.
5307 This warning can also be turned on using @option{-gnatwa}.
5308 The default is that these warnings are not given.
5309
5310 @item -gnatwM
5311 @emph{Disable warnings on modified but unreferenced variables.}
5312 @cindex @option{-gnatwM} (@command{gcc})
5313 This switch disables warnings for variables that are assigned or
5314 initialized, but never read.
5315
5316 @item -gnatwn
5317 @emph{Set normal warnings mode.}
5318 @cindex @option{-gnatwn} (@command{gcc})
5319 This switch sets normal warning mode, in which enabled warnings are
5320 issued and treated as warnings rather than errors. This is the default
5321 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5322 an explicit @option{-gnatws} or
5323 @option{-gnatwe}. It also cancels the effect of the
5324 implicit @option{-gnatwe} that is activated by the
5325 use of @option{-gnatg}.
5326
5327 @item -gnatwo
5328 @emph{Activate warnings on address clause overlays.}
5329 @cindex @option{-gnatwo} (@command{gcc})
5330 @cindex Address Clauses, warnings
5331 This switch activates warnings for possibly unintended initialization
5332 effects of defining address clauses that cause one variable to overlap
5333 another. The default is that such warnings are generated.
5334 This warning can also be turned on using @option{-gnatwa}.
5335
5336 @item -gnatwO
5337 @emph{Suppress warnings on address clause overlays.}
5338 @cindex @option{-gnatwO} (@command{gcc})
5339 This switch suppresses warnings on possibly unintended initialization
5340 effects of defining address clauses that cause one variable to overlap
5341 another.
5342
5343 @item -gnatw.o
5344 @emph{Activate warnings on modified but unreferenced out parameters.}
5345 @cindex @option{-gnatw.o} (@command{gcc})
5346 This switch activates warnings for variables that are modified by using
5347 them as actuals for a call to a procedure with an out mode formal, where
5348 the resulting assigned value is never read. It is applicable in the case
5349 where there is more than one out mode formal. If there is only one out
5350 mode formal, the warning is issued by default (controlled by -gnatwu).
5351 The warning is suppressed for volatile
5352 variables and also for variables that are renamings of other variables
5353 or for which an address clause is given.
5354 The default is that these warnings are not given. Note that this warning
5355 is not included in -gnatwa, it must be activated explicitly.
5356
5357 @item -gnatw.O
5358 @emph{Disable warnings on modified but unreferenced out parameters.}
5359 @cindex @option{-gnatw.O} (@command{gcc})
5360 This switch suppresses warnings for variables that are modified by using
5361 them as actuals for a call to a procedure with an out mode formal, where
5362 the resulting assigned value is never read.
5363
5364 @item -gnatwp
5365 @emph{Activate warnings on ineffective pragma Inlines.}
5366 @cindex @option{-gnatwp} (@command{gcc})
5367 @cindex Inlining, warnings
5368 This switch activates warnings for failure of front end inlining
5369 (activated by @option{-gnatN}) to inline a particular call. There are
5370 many reasons for not being able to inline a call, including most
5371 commonly that the call is too complex to inline. The default is
5372 that such warnings are not given.
5373 This warning can also be turned on using @option{-gnatwa}.
5374 Warnings on ineffective inlining by the gcc back-end can be activated
5375 separately, using the gcc switch -Winline.
5376
5377 @item -gnatwP
5378 @emph{Suppress warnings on ineffective pragma Inlines.}
5379 @cindex @option{-gnatwP} (@command{gcc})
5380 This switch suppresses warnings on ineffective pragma Inlines. If the
5381 inlining mechanism cannot inline a call, it will simply ignore the
5382 request silently.
5383
5384 @item -gnatw.p
5385 @emph{Activate warnings on parameter ordering.}
5386 @cindex @option{-gnatw.p} (@command{gcc})
5387 @cindex Parameter order, warnings
5388 This switch activates warnings for cases of suspicious parameter
5389 ordering when the list of arguments are all simple identifiers that
5390 match the names of the formals, but are in a different order. The
5391 warning is suppressed if any use of named parameter notation is used,
5392 so this is the appropriate way to suppress a false positive (and
5393 serves to emphasize that the "misordering" is deliberate). The
5394 default is
5395 that such warnings are not given.
5396 This warning can also be turned on using @option{-gnatwa}.
5397
5398 @item -gnatw.P
5399 @emph{Suppress warnings on parameter ordering.}
5400 @cindex @option{-gnatw.P} (@command{gcc})
5401 This switch suppresses warnings on cases of suspicious parameter
5402 ordering.
5403
5404 @item -gnatwq
5405 @emph{Activate warnings on questionable missing parentheses.}
5406 @cindex @option{-gnatwq} (@command{gcc})
5407 @cindex Parentheses, warnings
5408 This switch activates warnings for cases where parentheses are not used and
5409 the result is potential ambiguity from a readers point of view. For example
5410 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5411 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5412 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5413 follow the rule of always parenthesizing to make the association clear, and
5414 this warning switch warns if such parentheses are not present. The default
5415 is that these warnings are given.
5416 This warning can also be turned on using @option{-gnatwa}.
5417
5418 @item -gnatwQ
5419 @emph{Suppress warnings on questionable missing parentheses.}
5420 @cindex @option{-gnatwQ} (@command{gcc})
5421 This switch suppresses warnings for cases where the association is not
5422 clear and the use of parentheses is preferred.
5423
5424 @item -gnatwr
5425 @emph{Activate warnings on redundant constructs.}
5426 @cindex @option{-gnatwr} (@command{gcc})
5427 This switch activates warnings for redundant constructs. The following
5428 is the current list of constructs regarded as redundant:
5429
5430 @itemize @bullet
5431 @item
5432 Assignment of an item to itself.
5433 @item
5434 Type conversion that converts an expression to its own type.
5435 @item
5436 Use of the attribute @code{Base} where @code{typ'Base} is the same
5437 as @code{typ}.
5438 @item
5439 Use of pragma @code{Pack} when all components are placed by a record
5440 representation clause.
5441 @item
5442 Exception handler containing only a reraise statement (raise with no
5443 operand) which has no effect.
5444 @item
5445 Use of the operator abs on an operand that is known at compile time
5446 to be non-negative
5447 @item
5448 Comparison of boolean expressions to an explicit True value.
5449 @end itemize
5450
5451 This warning can also be turned on using @option{-gnatwa}.
5452 The default is that warnings for redundant constructs are not given.
5453
5454 @item -gnatwR
5455 @emph{Suppress warnings on redundant constructs.}
5456 @cindex @option{-gnatwR} (@command{gcc})
5457 This switch suppresses warnings for redundant constructs.
5458
5459 @item -gnatws
5460 @emph{Suppress all warnings.}
5461 @cindex @option{-gnatws} (@command{gcc})
5462 This switch completely suppresses the
5463 output of all warning messages from the GNAT front end.
5464 Note that it does not suppress warnings from the @command{gcc} back end.
5465 To suppress these back end warnings as well, use the switch @option{-w}
5466 in addition to @option{-gnatws}.
5467
5468 @item -gnatwt
5469 @emph{Activate warnings for tracking of deleted conditional code.}
5470 @cindex @option{-gnatwt} (@command{gcc})
5471 @cindex Deactivated code, warnings
5472 @cindex Deleted code, warnings
5473 This switch activates warnings for tracking of code in conditionals (IF and
5474 CASE statements) that is detected to be dead code which cannot be executed, and
5475 which is removed by the front end. This warning is off by default, and is not
5476 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5477 useful for detecting deactivated code in certified applications.
5478
5479 @item -gnatwT
5480 @emph{Suppress warnings for tracking of deleted conditional code.}
5481 @cindex @option{-gnatwT} (@command{gcc})
5482 This switch suppresses warnings for tracking of deleted conditional code.
5483
5484 @item -gnatwu
5485 @emph{Activate warnings on unused entities.}
5486 @cindex @option{-gnatwu} (@command{gcc})
5487 This switch activates warnings to be generated for entities that
5488 are declared but not referenced, and for units that are @code{with}'ed
5489 and not
5490 referenced. In the case of packages, a warning is also generated if
5491 no entities in the package are referenced. This means that if the package
5492 is referenced but the only references are in @code{use}
5493 clauses or @code{renames}
5494 declarations, a warning is still generated. A warning is also generated
5495 for a generic package that is @code{with}'ed but never instantiated.
5496 In the case where a package or subprogram body is compiled, and there
5497 is a @code{with} on the corresponding spec
5498 that is only referenced in the body,
5499 a warning is also generated, noting that the
5500 @code{with} can be moved to the body. The default is that
5501 such warnings are not generated.
5502 This switch also activates warnings on unreferenced formals
5503 (it includes the effect of @option{-gnatwf}).
5504 This warning can also be turned on using @option{-gnatwa}.
5505
5506 @item -gnatwU
5507 @emph{Suppress warnings on unused entities.}
5508 @cindex @option{-gnatwU} (@command{gcc})
5509 This switch suppresses warnings for unused entities and packages.
5510 It also turns off warnings on unreferenced formals (and thus includes
5511 the effect of @option{-gnatwF}).
5512
5513 @item -gnatwv
5514 @emph{Activate warnings on unassigned variables.}
5515 @cindex @option{-gnatwv} (@command{gcc})
5516 @cindex Unassigned variable warnings
5517 This switch activates warnings for access to variables which
5518 may not be properly initialized. The default is that
5519 such warnings are generated.
5520 This warning can also be turned on using @option{-gnatwa}.
5521
5522 @item -gnatwV
5523 @emph{Suppress warnings on unassigned variables.}
5524 @cindex @option{-gnatwV} (@command{gcc})
5525 This switch suppresses warnings for access to variables which
5526 may not be properly initialized.
5527 For variables of a composite type, the warning can also be suppressed in
5528 Ada 2005 by using a default initialization with a box. For example, if
5529 Table is an array of records whose components are only partially uninitialized,
5530 then the following code:
5531
5532 @smallexample @c ada
5533 Tab : Table := (others => <>);
5534 @end smallexample
5535
5536 will suppress warnings on subsequent statements that access components
5537 of variable Tab.
5538
5539 @item -gnatww
5540 @emph{Activate warnings on wrong low bound assumption.}
5541 @cindex @option{-gnatww} (@command{gcc})
5542 @cindex String indexing warnings
5543 This switch activates warnings for indexing an unconstrained string parameter
5544 with a literal or S'Length. This is a case where the code is assuming that the
5545 low bound is one, which is in general not true (for example when a slice is
5546 passed). The default is that such warnings are generated.
5547 This warning can also be turned on using @option{-gnatwa}.
5548
5549 @item -gnatwW
5550 @emph{Suppress warnings on wrong low bound assumption.}
5551 @cindex @option{-gnatwW} (@command{gcc})
5552 This switch suppresses warnings for indexing an unconstrained string parameter
5553 with a literal or S'Length. Note that this warning can also be suppressed
5554 in a particular case by adding an
5555 assertion that the lower bound is 1,
5556 as shown in the following example.
5557
5558 @smallexample @c ada
5559 procedure K (S : String) is
5560 pragma Assert (S'First = 1);
5561 @dots{}
5562 @end smallexample
5563
5564 @item -gnatw.w
5565 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5566 @cindex @option{-gnatw.w} (@command{gcc})
5567 @cindex Warnings Off control
5568 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5569 where either the pragma is entirely useless (because it suppresses no
5570 warnings), or it could be replaced by @code{pragma Unreferenced} or
5571 @code{pragma Unmodified}.The default is that these warnings are not given.
5572 Note that this warning is not included in -gnatwa, it must be
5573 activated explicitly.
5574
5575 @item -gnatw.W
5576 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5577 @cindex @option{-gnatw.W} (@command{gcc})
5578 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5579
5580 @item -gnatwx
5581 @emph{Activate warnings on Export/Import pragmas.}
5582 @cindex @option{-gnatwx} (@command{gcc})
5583 @cindex Export/Import pragma warnings
5584 This switch activates warnings on Export/Import pragmas when
5585 the compiler detects a possible conflict between the Ada and
5586 foreign language calling sequences. For example, the use of
5587 default parameters in a convention C procedure is dubious
5588 because the C compiler cannot supply the proper default, so
5589 a warning is issued. The default is that such warnings are
5590 generated.
5591 This warning can also be turned on using @option{-gnatwa}.
5592
5593 @item -gnatwX
5594 @emph{Suppress warnings on Export/Import pragmas.}
5595 @cindex @option{-gnatwX} (@command{gcc})
5596 This switch suppresses warnings on Export/Import pragmas.
5597 The sense of this is that you are telling the compiler that
5598 you know what you are doing in writing the pragma, and it
5599 should not complain at you.
5600
5601 @item -gnatw.x
5602 @emph{Activate warnings for No_Exception_Propagation mode.}
5603 @cindex @option{-gnatwm} (@command{gcc})
5604 This switch activates warnings for exception usage when pragma Restrictions
5605 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5606 explicit exception raises which are not covered by a local handler, and for
5607 exception handlers which do not cover a local raise. The default is that these
5608 warnings are not given.
5609
5610 @item -gnatw.X
5611 @emph{Disable warnings for No_Exception_Propagation mode.}
5612 This switch disables warnings for exception usage when pragma Restrictions
5613 (No_Exception_Propagation) is in effect.
5614
5615 @item -gnatwy
5616 @emph{Activate warnings for Ada 2005 compatibility issues.}
5617 @cindex @option{-gnatwy} (@command{gcc})
5618 @cindex Ada 2005 compatibility issues warnings
5619 For the most part Ada 2005 is upwards compatible with Ada 95,
5620 but there are some exceptions (for example the fact that
5621 @code{interface} is now a reserved word in Ada 2005). This
5622 switch activates several warnings to help in identifying
5623 and correcting such incompatibilities. The default is that
5624 these warnings are generated. Note that at one point Ada 2005
5625 was called Ada 0Y, hence the choice of character.
5626 This warning can also be turned on using @option{-gnatwa}.
5627
5628 @item -gnatwY
5629 @emph{Disable warnings for Ada 2005 compatibility issues.}
5630 @cindex @option{-gnatwY} (@command{gcc})
5631 @cindex Ada 2005 compatibility issues warnings
5632 This switch suppresses several warnings intended to help in identifying
5633 incompatibilities between Ada 95 and Ada 2005.
5634
5635 @item -gnatwz
5636 @emph{Activate warnings on unchecked conversions.}
5637 @cindex @option{-gnatwz} (@command{gcc})
5638 @cindex Unchecked_Conversion warnings
5639 This switch activates warnings for unchecked conversions
5640 where the types are known at compile time to have different
5641 sizes. The default
5642 is that such warnings are generated. Warnings are also
5643 generated for subprogram pointers with different conventions,
5644 and, on VMS only, for data pointers with different conventions.
5645 This warning can also be turned on using @option{-gnatwa}.
5646
5647 @item -gnatwZ
5648 @emph{Suppress warnings on unchecked conversions.}
5649 @cindex @option{-gnatwZ} (@command{gcc})
5650 This switch suppresses warnings for unchecked conversions
5651 where the types are known at compile time to have different
5652 sizes or conventions.
5653
5654 @item ^-Wunused^WARNINGS=UNUSED^
5655 @cindex @option{-Wunused}
5656 The warnings controlled by the @option{-gnatw} switch are generated by
5657 the front end of the compiler. The @option{GCC} back end can provide
5658 additional warnings and they are controlled by the @option{-W} switch.
5659 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5660 warnings for entities that are declared but not referenced.
5661
5662 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5663 @cindex @option{-Wuninitialized}
5664 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5665 the back end warning for uninitialized variables. This switch must be
5666 used in conjunction with an optimization level greater than zero.
5667
5668 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5669 @cindex @option{-Wall}
5670 This switch enables all the above warnings from the @option{GCC} back end.
5671 The code generator detects a number of warning situations that are missed
5672 by the @option{GNAT} front end, and this switch can be used to activate them.
5673 The use of this switch also sets the default front end warning mode to
5674 @option{-gnatwa}, that is, most front end warnings activated as well.
5675
5676 @item ^-w^/NO_BACK_END_WARNINGS^
5677 @cindex @option{-w}
5678 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5679 The use of this switch also sets the default front end warning mode to
5680 @option{-gnatws}, that is, front end warnings suppressed as well.
5681
5682 @end table
5683
5684 @noindent
5685 @ifclear vms
5686 A string of warning parameters can be used in the same parameter. For example:
5687
5688 @smallexample
5689 -gnatwaLe
5690 @end smallexample
5691
5692 @noindent
5693 will turn on all optional warnings except for elaboration pragma warnings,
5694 and also specify that warnings should be treated as errors.
5695 @end ifclear
5696 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5697
5698 @table @option
5699 @c !sort!
5700 @item -gnatwC
5701 @item -gnatwD
5702 @item -gnatwF
5703 @item -gnatwg
5704 @item -gnatwH
5705 @item -gnatwi
5706 @item -gnatwJ
5707 @item -gnatwK
5708 @item -gnatwL
5709 @item -gnatwM
5710 @item -gnatwn
5711 @item -gnatwo
5712 @item -gnatwP
5713 @item -gnatwR
5714 @item -gnatwU
5715 @item -gnatwv
5716 @item -gnatwz
5717 @item -gnatwx
5718
5719 @end table
5720
5721 @node Debugging and Assertion Control
5722 @subsection Debugging and Assertion Control
5723
5724 @table @option
5725 @item -gnata
5726 @cindex @option{-gnata} (@command{gcc})
5727 @findex Assert
5728 @findex Debug
5729 @cindex Assertions
5730
5731 @noindent
5732 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5733 are ignored. This switch, where @samp{a} stands for assert, causes
5734 @code{Assert} and @code{Debug} pragmas to be activated.
5735
5736 The pragmas have the form:
5737
5738 @smallexample
5739 @cartouche
5740 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5741 @var{static-string-expression}@r{]})
5742 @b{pragma} Debug (@var{procedure call})
5743 @end cartouche
5744 @end smallexample
5745
5746 @noindent
5747 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5748 If the result is @code{True}, the pragma has no effect (other than
5749 possible side effects from evaluating the expression). If the result is
5750 @code{False}, the exception @code{Assert_Failure} declared in the package
5751 @code{System.Assertions} is
5752 raised (passing @var{static-string-expression}, if present, as the
5753 message associated with the exception). If no string expression is
5754 given the default is a string giving the file name and line number
5755 of the pragma.
5756
5757 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5758 @code{pragma Debug} may appear within a declaration sequence, allowing
5759 debugging procedures to be called between declarations.
5760
5761 @ifset vms
5762 @item /DEBUG@r{[}=debug-level@r{]}
5763 @itemx /NODEBUG
5764 Specifies how much debugging information is to be included in
5765 the resulting object file where 'debug-level' is one of the following:
5766 @table @code
5767 @item TRACEBACK
5768 Include both debugger symbol records and traceback
5769 the object file.
5770 This is the default setting.
5771 @item ALL
5772 Include both debugger symbol records and traceback in
5773 object file.
5774 @item NONE
5775 Excludes both debugger symbol records and traceback
5776 the object file. Same as /NODEBUG.
5777 @item SYMBOLS
5778 Includes only debugger symbol records in the object
5779 file. Note that this doesn't include traceback information.
5780 @end table
5781 @end ifset
5782 @end table
5783
5784 @node Validity Checking
5785 @subsection Validity Checking
5786 @findex Validity Checking
5787
5788 @noindent
5789 The Ada Reference Manual has specific requirements for checking
5790 for invalid values. In particular, RM 13.9.1 requires that the
5791 evaluation of invalid values (for example from unchecked conversions),
5792 not result in erroneous execution. In GNAT, the result of such an
5793 evaluation in normal default mode is to either use the value
5794 unmodified, or to raise Constraint_Error in those cases where use
5795 of the unmodified value would cause erroneous execution. The cases
5796 where unmodified values might lead to erroneous execution are case
5797 statements (where a wild jump might result from an invalid value),
5798 and subscripts on the left hand side (where memory corruption could
5799 occur as a result of an invalid value).
5800
5801 The @option{-gnatB} switch tells the compiler to assume that all
5802 values are valid (that is, within their declared subtype range)
5803 except in the context of a use of the Valid attribute. This means
5804 the compiler can generate more efficient code, since the range
5805 of values is better known at compile time.
5806
5807 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5808 checking mode.
5809 @ifclear vms
5810 The @code{x} argument is a string of letters that
5811 indicate validity checks that are performed or not performed in addition
5812 to the default checks described above.
5813 @end ifclear
5814 @ifset vms
5815 The options allowed for this qualifier
5816 indicate validity checks that are performed or not performed in addition
5817 to the default checks described above.
5818 @end ifset
5819
5820 @table @option
5821 @c !sort!
5822 @item -gnatVa
5823 @emph{All validity checks.}
5824 @cindex @option{-gnatVa} (@command{gcc})
5825 All validity checks are turned on.
5826 @ifclear vms
5827 That is, @option{-gnatVa} is
5828 equivalent to @option{gnatVcdfimorst}.
5829 @end ifclear
5830
5831 @item -gnatVc
5832 @emph{Validity checks for copies.}
5833 @cindex @option{-gnatVc} (@command{gcc})
5834 The right hand side of assignments, and the initializing values of
5835 object declarations are validity checked.
5836
5837 @item -gnatVd
5838 @emph{Default (RM) validity checks.}
5839 @cindex @option{-gnatVd} (@command{gcc})
5840 Some validity checks are done by default following normal Ada semantics
5841 (RM 13.9.1 (9-11)).
5842 A check is done in case statements that the expression is within the range
5843 of the subtype. If it is not, Constraint_Error is raised.
5844 For assignments to array components, a check is done that the expression used
5845 as index is within the range. If it is not, Constraint_Error is raised.
5846 Both these validity checks may be turned off using switch @option{-gnatVD}.
5847 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5848 switch @option{-gnatVd} will leave the checks turned on.
5849 Switch @option{-gnatVD} should be used only if you are sure that all such
5850 expressions have valid values. If you use this switch and invalid values
5851 are present, then the program is erroneous, and wild jumps or memory
5852 overwriting may occur.
5853
5854 @item -gnatVe
5855 @emph{Validity checks for elementary components.}
5856 @cindex @option{-gnatVe} (@command{gcc})
5857 In the absence of this switch, assignments to record or array components are
5858 not validity checked, even if validity checks for assignments generally
5859 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5860 require valid data, but assignment of individual components does. So for
5861 example, there is a difference between copying the elements of an array with a
5862 slice assignment, compared to assigning element by element in a loop. This
5863 switch allows you to turn off validity checking for components, even when they
5864 are assigned component by component.
5865
5866 @item -gnatVf
5867 @emph{Validity checks for floating-point values.}
5868 @cindex @option{-gnatVf} (@command{gcc})
5869 In the absence of this switch, validity checking occurs only for discrete
5870 values. If @option{-gnatVf} is specified, then validity checking also applies
5871 for floating-point values, and NaNs and infinities are considered invalid,
5872 as well as out of range values for constrained types. Note that this means
5873 that standard IEEE infinity mode is not allowed. The exact contexts
5874 in which floating-point values are checked depends on the setting of other
5875 options. For example,
5876 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5877 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5878 (the order does not matter) specifies that floating-point parameters of mode
5879 @code{in} should be validity checked.
5880
5881 @item -gnatVi
5882 @emph{Validity checks for @code{in} mode parameters}
5883 @cindex @option{-gnatVi} (@command{gcc})
5884 Arguments for parameters of mode @code{in} are validity checked in function
5885 and procedure calls at the point of call.
5886
5887 @item -gnatVm
5888 @emph{Validity checks for @code{in out} mode parameters.}
5889 @cindex @option{-gnatVm} (@command{gcc})
5890 Arguments for parameters of mode @code{in out} are validity checked in
5891 procedure calls at the point of call. The @code{'m'} here stands for
5892 modify, since this concerns parameters that can be modified by the call.
5893 Note that there is no specific option to test @code{out} parameters,
5894 but any reference within the subprogram will be tested in the usual
5895 manner, and if an invalid value is copied back, any reference to it
5896 will be subject to validity checking.
5897
5898 @item -gnatVn
5899 @emph{No validity checks.}
5900 @cindex @option{-gnatVn} (@command{gcc})
5901 This switch turns off all validity checking, including the default checking
5902 for case statements and left hand side subscripts. Note that the use of
5903 the switch @option{-gnatp} suppresses all run-time checks, including
5904 validity checks, and thus implies @option{-gnatVn}. When this switch
5905 is used, it cancels any other @option{-gnatV} previously issued.
5906
5907 @item -gnatVo
5908 @emph{Validity checks for operator and attribute operands.}
5909 @cindex @option{-gnatVo} (@command{gcc})
5910 Arguments for predefined operators and attributes are validity checked.
5911 This includes all operators in package @code{Standard},
5912 the shift operators defined as intrinsic in package @code{Interfaces}
5913 and operands for attributes such as @code{Pos}. Checks are also made
5914 on individual component values for composite comparisons, and on the
5915 expressions in type conversions and qualified expressions. Checks are
5916 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5917
5918 @item -gnatVp
5919 @emph{Validity checks for parameters.}
5920 @cindex @option{-gnatVp} (@command{gcc})
5921 This controls the treatment of parameters within a subprogram (as opposed
5922 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5923 of parameters on a call. If either of these call options is used, then
5924 normally an assumption is made within a subprogram that the input arguments
5925 have been validity checking at the point of call, and do not need checking
5926 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5927 is not made, and parameters are not assumed to be valid, so their validity
5928 will be checked (or rechecked) within the subprogram.
5929
5930 @item -gnatVr
5931 @emph{Validity checks for function returns.}
5932 @cindex @option{-gnatVr} (@command{gcc})
5933 The expression in @code{return} statements in functions is validity
5934 checked.
5935
5936 @item -gnatVs
5937 @emph{Validity checks for subscripts.}
5938 @cindex @option{-gnatVs} (@command{gcc})
5939 All subscripts expressions are checked for validity, whether they appear
5940 on the right side or left side (in default mode only left side subscripts
5941 are validity checked).
5942
5943 @item -gnatVt
5944 @emph{Validity checks for tests.}
5945 @cindex @option{-gnatVt} (@command{gcc})
5946 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5947 statements are checked, as well as guard expressions in entry calls.
5948
5949 @end table
5950
5951 @noindent
5952 The @option{-gnatV} switch may be followed by
5953 ^a string of letters^a list of options^
5954 to turn on a series of validity checking options.
5955 For example,
5956 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5957 specifies that in addition to the default validity checking, copies and
5958 function return expressions are to be validity checked.
5959 In order to make it easier
5960 to specify the desired combination of effects,
5961 @ifclear vms
5962 the upper case letters @code{CDFIMORST} may
5963 be used to turn off the corresponding lower case option.
5964 @end ifclear
5965 @ifset vms
5966 the prefix @code{NO} on an option turns off the corresponding validity
5967 checking:
5968 @itemize @bullet
5969 @item @code{NOCOPIES}
5970 @item @code{NODEFAULT}
5971 @item @code{NOFLOATS}
5972 @item @code{NOIN_PARAMS}
5973 @item @code{NOMOD_PARAMS}
5974 @item @code{NOOPERANDS}
5975 @item @code{NORETURNS}
5976 @item @code{NOSUBSCRIPTS}
5977 @item @code{NOTESTS}
5978 @end itemize
5979 @end ifset
5980 Thus
5981 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5982 turns on all validity checking options except for
5983 checking of @code{@b{in out}} procedure arguments.
5984
5985 The specification of additional validity checking generates extra code (and
5986 in the case of @option{-gnatVa} the code expansion can be substantial).
5987 However, these additional checks can be very useful in detecting
5988 uninitialized variables, incorrect use of unchecked conversion, and other
5989 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5990 is useful in conjunction with the extra validity checking, since this
5991 ensures that wherever possible uninitialized variables have invalid values.
5992
5993 See also the pragma @code{Validity_Checks} which allows modification of
5994 the validity checking mode at the program source level, and also allows for
5995 temporary disabling of validity checks.
5996
5997 @node Style Checking
5998 @subsection Style Checking
5999 @findex Style checking
6000
6001 @noindent
6002 The @option{-gnaty^x^(option,option,@dots{})^} switch
6003 @cindex @option{-gnaty} (@command{gcc})
6004 causes the compiler to
6005 enforce specified style rules. A limited set of style rules has been used
6006 in writing the GNAT sources themselves. This switch allows user programs
6007 to activate all or some of these checks. If the source program fails a
6008 specified style check, an appropriate warning message is given, preceded by
6009 the character sequence ``(style)''.
6010 @ifset vms
6011 @code{(option,option,@dots{})} is a sequence of keywords
6012 @end ifset
6013 @ifclear vms
6014 The string @var{x} is a sequence of letters or digits
6015 @end ifclear
6016 indicating the particular style
6017 checks to be performed. The following checks are defined:
6018
6019 @table @option
6020 @c !sort!
6021 @item 0-9
6022 @emph{Specify indentation level.}
6023 If a digit from 1-9 appears
6024 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6025 then proper indentation is checked, with the digit indicating the
6026 indentation level required. A value of zero turns off this style check.
6027 The general style of required indentation is as specified by
6028 the examples in the Ada Reference Manual. Full line comments must be
6029 aligned with the @code{--} starting on a column that is a multiple of
6030 the alignment level, or they may be aligned the same way as the following
6031 non-blank line (this is useful when full line comments appear in the middle
6032 of a statement.
6033
6034 @item ^a^ATTRIBUTE^
6035 @emph{Check attribute casing.}
6036 Attribute names, including the case of keywords such as @code{digits}
6037 used as attributes names, must be written in mixed case, that is, the
6038 initial letter and any letter following an underscore must be uppercase.
6039 All other letters must be lowercase.
6040
6041 @item ^A^ARRAY_INDEXES^
6042 @emph{Use of array index numbers in array attributes.}
6043 When using the array attributes First, Last, Range,
6044 or Length, the index number must be omitted for one-dimensional arrays
6045 and is required for multi-dimensional arrays.
6046
6047 @item ^b^BLANKS^
6048 @emph{Blanks not allowed at statement end.}
6049 Trailing blanks are not allowed at the end of statements. The purpose of this
6050 rule, together with h (no horizontal tabs), is to enforce a canonical format
6051 for the use of blanks to separate source tokens.
6052
6053 @item ^c^COMMENTS^
6054 @emph{Check comments.}
6055 Comments must meet the following set of rules:
6056
6057 @itemize @bullet
6058
6059 @item
6060 The ``@code{--}'' that starts the column must either start in column one,
6061 or else at least one blank must precede this sequence.
6062
6063 @item
6064 Comments that follow other tokens on a line must have at least one blank
6065 following the ``@code{--}'' at the start of the comment.
6066
6067 @item
6068 Full line comments must have two blanks following the ``@code{--}'' that
6069 starts the comment, with the following exceptions.
6070
6071 @item
6072 A line consisting only of the ``@code{--}'' characters, possibly preceded
6073 by blanks is permitted.
6074
6075 @item
6076 A comment starting with ``@code{--x}'' where @code{x} is a special character
6077 is permitted.
6078 This allows proper processing of the output generated by specialized tools
6079 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6080 annotation
6081 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6082 special character is defined as being in one of the ASCII ranges
6083 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6084 Note that this usage is not permitted
6085 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6086
6087 @item
6088 A line consisting entirely of minus signs, possibly preceded by blanks, is
6089 permitted. This allows the construction of box comments where lines of minus
6090 signs are used to form the top and bottom of the box.
6091
6092 @item
6093 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6094 least one blank follows the initial ``@code{--}''. Together with the preceding
6095 rule, this allows the construction of box comments, as shown in the following
6096 example:
6097 @smallexample
6098 ---------------------------
6099 -- This is a box comment --
6100 -- with two text lines. --
6101 ---------------------------
6102 @end smallexample
6103 @end itemize
6104
6105 @item ^d^DOS_LINE_ENDINGS^
6106 @emph{Check no DOS line terminators present.}
6107 All lines must be terminated by a single ASCII.LF
6108 character (in particular the DOS line terminator sequence CR/LF is not
6109 allowed).
6110
6111 @item ^e^END^
6112 @emph{Check end/exit labels.}
6113 Optional labels on @code{end} statements ending subprograms and on
6114 @code{exit} statements exiting named loops, are required to be present.
6115
6116 @item ^f^VTABS^
6117 @emph{No form feeds or vertical tabs.}
6118 Neither form feeds nor vertical tab characters are permitted
6119 in the source text.
6120
6121 @item ^g^GNAT^
6122 @emph{GNAT style mode}
6123 The set of style check switches is set to match that used by the GNAT sources.
6124 This may be useful when developing code that is eventually intended to be
6125 incorporated into GNAT. For further details, see GNAT sources.
6126
6127 @item ^h^HTABS^
6128 @emph{No horizontal tabs.}
6129 Horizontal tab characters are not permitted in the source text.
6130 Together with the b (no blanks at end of line) check, this
6131 enforces a canonical form for the use of blanks to separate
6132 source tokens.
6133
6134 @item ^i^IF_THEN^
6135 @emph{Check if-then layout.}
6136 The keyword @code{then} must appear either on the same
6137 line as corresponding @code{if}, or on a line on its own, lined
6138 up under the @code{if} with at least one non-blank line in between
6139 containing all or part of the condition to be tested.
6140
6141 @item ^I^IN_MODE^
6142 @emph{check mode IN keywords}
6143 Mode @code{in} (the default mode) is not
6144 allowed to be given explicitly. @code{in out} is fine,
6145 but not @code{in} on its own.
6146
6147 @item ^k^KEYWORD^
6148 @emph{Check keyword casing.}
6149 All keywords must be in lower case (with the exception of keywords
6150 such as @code{digits} used as attribute names to which this check
6151 does not apply).
6152
6153 @item ^l^LAYOUT^
6154 @emph{Check layout.}
6155 Layout of statement and declaration constructs must follow the
6156 recommendations in the Ada Reference Manual, as indicated by the
6157 form of the syntax rules. For example an @code{else} keyword must
6158 be lined up with the corresponding @code{if} keyword.
6159
6160 There are two respects in which the style rule enforced by this check
6161 option are more liberal than those in the Ada Reference Manual. First
6162 in the case of record declarations, it is permissible to put the
6163 @code{record} keyword on the same line as the @code{type} keyword, and
6164 then the @code{end} in @code{end record} must line up under @code{type}.
6165 This is also permitted when the type declaration is split on two lines.
6166 For example, any of the following three layouts is acceptable:
6167
6168 @smallexample @c ada
6169 @cartouche
6170 type q is record
6171 a : integer;
6172 b : integer;
6173 end record;
6174
6175 type q is
6176 record
6177 a : integer;
6178 b : integer;
6179 end record;
6180
6181 type q is
6182 record
6183 a : integer;
6184 b : integer;
6185 end record;
6186
6187 @end cartouche
6188 @end smallexample
6189
6190 @noindent
6191 Second, in the case of a block statement, a permitted alternative
6192 is to put the block label on the same line as the @code{declare} or
6193 @code{begin} keyword, and then line the @code{end} keyword up under
6194 the block label. For example both the following are permitted:
6195
6196 @smallexample @c ada
6197 @cartouche
6198 Block : declare
6199 A : Integer := 3;
6200 begin
6201 Proc (A, A);
6202 end Block;
6203
6204 Block :
6205 declare
6206 A : Integer := 3;
6207 begin
6208 Proc (A, A);
6209 end Block;
6210 @end cartouche
6211 @end smallexample
6212
6213 @noindent
6214 The same alternative format is allowed for loops. For example, both of
6215 the following are permitted:
6216
6217 @smallexample @c ada
6218 @cartouche
6219 Clear : while J < 10 loop
6220 A (J) := 0;
6221 end loop Clear;
6222
6223 Clear :
6224 while J < 10 loop
6225 A (J) := 0;
6226 end loop Clear;
6227 @end cartouche
6228 @end smallexample
6229
6230 @item ^Lnnn^MAX_NESTING=nnn^
6231 @emph{Set maximum nesting level}
6232 The maximum level of nesting of constructs (including subprograms, loops,
6233 blocks, packages, and conditionals) may not exceed the given value
6234 @option{nnn}. A value of zero disconnects this style check.
6235
6236 @item ^m^LINE_LENGTH^
6237 @emph{Check maximum line length.}
6238 The length of source lines must not exceed 79 characters, including
6239 any trailing blanks. The value of 79 allows convenient display on an
6240 80 character wide device or window, allowing for possible special
6241 treatment of 80 character lines. Note that this count is of
6242 characters in the source text. This means that a tab character counts
6243 as one character in this count but a wide character sequence counts as
6244 a single character (however many bytes are needed in the encoding).
6245
6246 @item ^Mnnn^MAX_LENGTH=nnn^
6247 @emph{Set maximum line length.}
6248 The length of lines must not exceed the
6249 given value @option{nnn}. The maximum value that can be specified is 32767.
6250
6251 @item ^n^STANDARD_CASING^
6252 @emph{Check casing of entities in Standard.}
6253 Any identifier from Standard must be cased
6254 to match the presentation in the Ada Reference Manual (for example,
6255 @code{Integer} and @code{ASCII.NUL}).
6256
6257 @item ^N^NONE^
6258 @emph{Turn off all style checks}
6259 All style check options are turned off.
6260
6261 @item ^o^ORDERED_SUBPROGRAMS^
6262 @emph{Check order of subprogram bodies.}
6263 All subprogram bodies in a given scope
6264 (e.g.@: a package body) must be in alphabetical order. The ordering
6265 rule uses normal Ada rules for comparing strings, ignoring casing
6266 of letters, except that if there is a trailing numeric suffix, then
6267 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6268 before Junk10).
6269
6270 @item ^O^OVERRIDING_INDICATORS^
6271 @emph{Check that overriding subprograms are explicitly marked as such.}
6272 The declaration of a primitive operation of a type extension that overrides
6273 an inherited operation must carry an overriding indicator.
6274
6275 @item ^p^PRAGMA^
6276 @emph{Check pragma casing.}
6277 Pragma names must be written in mixed case, that is, the
6278 initial letter and any letter following an underscore must be uppercase.
6279 All other letters must be lowercase.
6280
6281 @item ^r^REFERENCES^
6282 @emph{Check references.}
6283 All identifier references must be cased in the same way as the
6284 corresponding declaration. No specific casing style is imposed on
6285 identifiers. The only requirement is for consistency of references
6286 with declarations.
6287
6288 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6289 @emph{Check no statements after THEN/ELSE.}
6290 No statements are allowed
6291 on the same line as a THEN or ELSE keyword following the
6292 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6293 and a special exception allows a pragma to appear after ELSE.
6294
6295 @item ^s^SPECS^
6296 @emph{Check separate specs.}
6297 Separate declarations (``specs'') are required for subprograms (a
6298 body is not allowed to serve as its own declaration). The only
6299 exception is that parameterless library level procedures are
6300 not required to have a separate declaration. This exception covers
6301 the most frequent form of main program procedures.
6302
6303 @item ^t^TOKEN^
6304 @emph{Check token spacing.}
6305 The following token spacing rules are enforced:
6306
6307 @itemize @bullet
6308
6309 @item
6310 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6311
6312 @item
6313 The token @code{=>} must be surrounded by spaces.
6314
6315 @item
6316 The token @code{<>} must be preceded by a space or a left parenthesis.
6317
6318 @item
6319 Binary operators other than @code{**} must be surrounded by spaces.
6320 There is no restriction on the layout of the @code{**} binary operator.
6321
6322 @item
6323 Colon must be surrounded by spaces.
6324
6325 @item
6326 Colon-equal (assignment, initialization) must be surrounded by spaces.
6327
6328 @item
6329 Comma must be the first non-blank character on the line, or be
6330 immediately preceded by a non-blank character, and must be followed
6331 by a space.
6332
6333 @item
6334 If the token preceding a left parenthesis ends with a letter or digit, then
6335 a space must separate the two tokens.
6336
6337 @item
6338 A right parenthesis must either be the first non-blank character on
6339 a line, or it must be preceded by a non-blank character.
6340
6341 @item
6342 A semicolon must not be preceded by a space, and must not be followed by
6343 a non-blank character.
6344
6345 @item
6346 A unary plus or minus may not be followed by a space.
6347
6348 @item
6349 A vertical bar must be surrounded by spaces.
6350 @end itemize
6351
6352 @item ^u^UNNECESSARY_BLANK_LINES^
6353 @emph{Check unnecessary blank lines.}
6354 Unnecessary blank lines are not allowed. A blank line is considered
6355 unnecessary if it appears at the end of the file, or if more than
6356 one blank line occurs in sequence.
6357
6358 @item ^x^XTRA_PARENS^
6359 @emph{Check extra parentheses.}
6360 Unnecessary extra level of parentheses (C-style) are not allowed
6361 around conditions in @code{if} statements, @code{while} statements and
6362 @code{exit} statements.
6363
6364 @item ^y^ALL_BUILTIN^
6365 @emph{Set all standard style check options}
6366 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6367 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6368 @option{-gnatyS}, @option{-gnatyLnnn},
6369 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6370
6371 @ifclear vms
6372 @item -
6373 @emph{Remove style check options}
6374 This causes any subsequent options in the string to act as canceling the
6375 corresponding style check option. To cancel maximum nesting level control,
6376 use @option{L} parameter witout any integer value after that, because any
6377 digit following @option{-} in the parameter string of the @option{-gnaty}
6378 option will be threated as canceling indentation check. The same is true
6379 for @option{M} parameter. @option{y} and @option{N} parameters are not
6380 allowed after @option{-}.
6381
6382 @item +
6383 This causes any subsequent options in the string to enable the corresponding
6384 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6385 if any.
6386 @end ifclear
6387
6388 @ifset vms
6389 @item NOxxx
6390 @emph{Removing style check options}
6391 If the name of a style check is preceded by @option{NO} then the corresponding
6392 style check is turned off. For example @option{NOCOMMENTS} turns off style
6393 checking for comments.
6394 @end ifset
6395 @end table
6396
6397 @noindent
6398 In the above rules, appearing in column one is always permitted, that is,
6399 counts as meeting either a requirement for a required preceding space,
6400 or as meeting a requirement for no preceding space.
6401
6402 Appearing at the end of a line is also always permitted, that is, counts
6403 as meeting either a requirement for a following space, or as meeting
6404 a requirement for no following space.
6405
6406 @noindent
6407 If any of these style rules is violated, a message is generated giving
6408 details on the violation. The initial characters of such messages are
6409 always ``@code{(style)}''. Note that these messages are treated as warning
6410 messages, so they normally do not prevent the generation of an object
6411 file. The @option{-gnatwe} switch can be used to treat warning messages,
6412 including style messages, as fatal errors.
6413
6414 The switch
6415 @ifclear vms
6416 @option{-gnaty} on its own (that is not
6417 followed by any letters or digits), then the effect is equivalent
6418 to the use of @option{-gnatyy}, as described above, that is all
6419 built-in standard style check options are enabled.
6420
6421 @end ifclear
6422 @ifset vms
6423 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6424 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6425 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6426 @end ifset
6427
6428
6429
6430 The switch
6431 @ifclear vms
6432 @option{-gnatyN}
6433 @end ifclear
6434 @ifset vms
6435 /STYLE_CHECKS=NONE
6436 @end ifset
6437 clears any previously set style checks.
6438
6439 @node Run-Time Checks
6440 @subsection Run-Time Checks
6441 @cindex Division by zero
6442 @cindex Access before elaboration
6443 @cindex Checks, division by zero
6444 @cindex Checks, access before elaboration
6445 @cindex Checks, stack overflow checking
6446
6447 @noindent
6448 By default, the following checks are suppressed: integer overflow
6449 checks, stack overflow checks, and checks for access before
6450 elaboration on subprogram calls. All other checks, including range
6451 checks and array bounds checks, are turned on by default. The
6452 following @command{gcc} switches refine this default behavior.
6453
6454 @table @option
6455 @c !sort!
6456 @item -gnatp
6457 @cindex @option{-gnatp} (@command{gcc})
6458 @cindex Suppressing checks
6459 @cindex Checks, suppressing
6460 @findex Suppress
6461 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6462 had been present in the source. Validity checks are also suppressed (in
6463 other words @option{-gnatp} also implies @option{-gnatVn}.
6464 Use this switch to improve the performance
6465 of the code at the expense of safety in the presence of invalid data or
6466 program bugs.
6467
6468 Note that when checks are suppressed, the compiler is allowed, but not
6469 required, to omit the checking code. If the run-time cost of the
6470 checking code is zero or near-zero, the compiler will generate it even
6471 if checks are suppressed. In particular, if the compiler can prove
6472 that a certain check will necessarily fail, it will generate code to
6473 do an unconditional ``raise'', even if checks are suppressed. The
6474 compiler warns in this case.
6475
6476 Of course, run-time checks are omitted whenever the compiler can prove
6477 that they will not fail, whether or not checks are suppressed.
6478
6479 Note that if you suppress a check that would have failed, program
6480 execution is erroneous, which means the behavior is totally
6481 unpredictable. The program might crash, or print wrong answers, or
6482 do anything else. It might even do exactly what you wanted it to do
6483 (and then it might start failing mysteriously next week or next
6484 year). The compiler will generate code based on the assumption that
6485 the condition being checked is true, which can result in disaster if
6486 that assumption is wrong.
6487
6488 @item -gnato
6489 @cindex @option{-gnato} (@command{gcc})
6490 @cindex Overflow checks
6491 @cindex Check, overflow
6492 Enables overflow checking for integer operations.
6493 This causes GNAT to generate slower and larger executable
6494 programs by adding code to check for overflow (resulting in raising
6495 @code{Constraint_Error} as required by standard Ada
6496 semantics). These overflow checks correspond to situations in which
6497 the true value of the result of an operation may be outside the base
6498 range of the result type. The following example shows the distinction:
6499
6500 @smallexample @c ada
6501 X1 : Integer := "Integer'Last";
6502 X2 : Integer range 1 .. 5 := "5";
6503 X3 : Integer := "Integer'Last";
6504 X4 : Integer range 1 .. 5 := "5";
6505 F : Float := "2.0E+20";
6506 @dots{}
6507 X1 := X1 + 1;
6508 X2 := X2 + 1;
6509 X3 := Integer (F);
6510 X4 := Integer (F);
6511 @end smallexample
6512
6513 @noindent
6514 Note that if explicit values are assigned at compile time, the
6515 compiler may be able to detect overflow at compile time, in which case
6516 no actual run-time checking code is required, and Constraint_Error
6517 will be raised unconditionally, with or without
6518 @option{-gnato}. That's why the assigned values in the above fragment
6519 are in quotes, the meaning is "assign a value not known to the
6520 compiler that happens to be equal to ...". The remaining discussion
6521 assumes that the compiler cannot detect the values at compile time.
6522
6523 Here the first addition results in a value that is outside the base range
6524 of Integer, and hence requires an overflow check for detection of the
6525 constraint error. Thus the first assignment to @code{X1} raises a
6526 @code{Constraint_Error} exception only if @option{-gnato} is set.
6527
6528 The second increment operation results in a violation of the explicit
6529 range constraint; such range checks are performed by default, and are
6530 unaffected by @option{-gnato}.
6531
6532 The two conversions of @code{F} both result in values that are outside
6533 the base range of type @code{Integer} and thus will raise
6534 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6535 The fact that the result of the second conversion is assigned to
6536 variable @code{X4} with a restricted range is irrelevant, since the problem
6537 is in the conversion, not the assignment.
6538
6539 Basically the rule is that in the default mode (@option{-gnato} not
6540 used), the generated code assures that all integer variables stay
6541 within their declared ranges, or within the base range if there is
6542 no declared range. This prevents any serious problems like indexes
6543 out of range for array operations.
6544
6545 What is not checked in default mode is an overflow that results in
6546 an in-range, but incorrect value. In the above example, the assignments
6547 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6548 range of the target variable, but the result is wrong in the sense that
6549 it is too large to be represented correctly. Typically the assignment
6550 to @code{X1} will result in wrap around to the largest negative number.
6551 The conversions of @code{F} will result in some @code{Integer} value
6552 and if that integer value is out of the @code{X4} range then the
6553 subsequent assignment would generate an exception.
6554
6555 @findex Machine_Overflows
6556 Note that the @option{-gnato} switch does not affect the code generated
6557 for any floating-point operations; it applies only to integer
6558 semantics).
6559 For floating-point, GNAT has the @code{Machine_Overflows}
6560 attribute set to @code{False} and the normal mode of operation is to
6561 generate IEEE NaN and infinite values on overflow or invalid operations
6562 (such as dividing 0.0 by 0.0).
6563
6564 The reason that we distinguish overflow checking from other kinds of
6565 range constraint checking is that a failure of an overflow check, unlike
6566 for example the failure of a range check, can result in an incorrect
6567 value, but cannot cause random memory destruction (like an out of range
6568 subscript), or a wild jump (from an out of range case value). Overflow
6569 checking is also quite expensive in time and space, since in general it
6570 requires the use of double length arithmetic.
6571
6572 Note again that @option{-gnato} is off by default, so overflow checking is
6573 not performed in default mode. This means that out of the box, with the
6574 default settings, GNAT does not do all the checks expected from the
6575 language description in the Ada Reference Manual. If you want all constraint
6576 checks to be performed, as described in this Manual, then you must
6577 explicitly use the -gnato switch either on the @command{gnatmake} or
6578 @command{gcc} command.
6579
6580 @item -gnatE
6581 @cindex @option{-gnatE} (@command{gcc})
6582 @cindex Elaboration checks
6583 @cindex Check, elaboration
6584 Enables dynamic checks for access-before-elaboration
6585 on subprogram calls and generic instantiations.
6586 Note that @option{-gnatE} is not necessary for safety, because in the
6587 default mode, GNAT ensures statically that the checks would not fail.
6588 For full details of the effect and use of this switch,
6589 @xref{Compiling Using gcc}.
6590
6591 @item -fstack-check
6592 @cindex @option{-fstack-check} (@command{gcc})
6593 @cindex Stack Overflow Checking
6594 @cindex Checks, stack overflow checking
6595 Activates stack overflow checking. For full details of the effect and use of
6596 this switch see @ref{Stack Overflow Checking}.
6597 @end table
6598
6599 @findex Unsuppress
6600 @noindent
6601 The setting of these switches only controls the default setting of the
6602 checks. You may modify them using either @code{Suppress} (to remove
6603 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6604 the program source.
6605
6606 @node Using gcc for Syntax Checking
6607 @subsection Using @command{gcc} for Syntax Checking
6608 @table @option
6609 @item -gnats
6610 @cindex @option{-gnats} (@command{gcc})
6611 @ifclear vms
6612
6613 @noindent
6614 The @code{s} stands for ``syntax''.
6615 @end ifclear
6616
6617 Run GNAT in syntax checking only mode. For
6618 example, the command
6619
6620 @smallexample
6621 $ gcc -c -gnats x.adb
6622 @end smallexample
6623
6624 @noindent
6625 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6626 series of files in a single command
6627 @ifclear vms
6628 , and can use wild cards to specify such a group of files.
6629 Note that you must specify the @option{-c} (compile
6630 only) flag in addition to the @option{-gnats} flag.
6631 @end ifclear
6632 .
6633 You may use other switches in conjunction with @option{-gnats}. In
6634 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6635 format of any generated error messages.
6636
6637 When the source file is empty or contains only empty lines and/or comments,
6638 the output is a warning:
6639
6640 @smallexample
6641 $ gcc -c -gnats -x ada toto.txt
6642 toto.txt:1:01: warning: empty file, contains no compilation units
6643 $
6644 @end smallexample
6645
6646 Otherwise, the output is simply the error messages, if any. No object file or
6647 ALI file is generated by a syntax-only compilation. Also, no units other
6648 than the one specified are accessed. For example, if a unit @code{X}
6649 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6650 check only mode does not access the source file containing unit
6651 @code{Y}.
6652
6653 @cindex Multiple units, syntax checking
6654 Normally, GNAT allows only a single unit in a source file. However, this
6655 restriction does not apply in syntax-check-only mode, and it is possible
6656 to check a file containing multiple compilation units concatenated
6657 together. This is primarily used by the @code{gnatchop} utility
6658 (@pxref{Renaming Files Using gnatchop}).
6659 @end table
6660
6661 @node Using gcc for Semantic Checking
6662 @subsection Using @command{gcc} for Semantic Checking
6663 @table @option
6664 @item -gnatc
6665 @cindex @option{-gnatc} (@command{gcc})
6666
6667 @ifclear vms
6668 @noindent
6669 The @code{c} stands for ``check''.
6670 @end ifclear
6671 Causes the compiler to operate in semantic check mode,
6672 with full checking for all illegalities specified in the
6673 Ada Reference Manual, but without generation of any object code
6674 (no object file is generated).
6675
6676 Because dependent files must be accessed, you must follow the GNAT
6677 semantic restrictions on file structuring to operate in this mode:
6678
6679 @itemize @bullet
6680 @item
6681 The needed source files must be accessible
6682 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6683
6684 @item
6685 Each file must contain only one compilation unit.
6686
6687 @item
6688 The file name and unit name must match (@pxref{File Naming Rules}).
6689 @end itemize
6690
6691 The output consists of error messages as appropriate. No object file is
6692 generated. An @file{ALI} file is generated for use in the context of
6693 cross-reference tools, but this file is marked as not being suitable
6694 for binding (since no object file is generated).
6695 The checking corresponds exactly to the notion of
6696 legality in the Ada Reference Manual.
6697
6698 Any unit can be compiled in semantics-checking-only mode, including
6699 units that would not normally be compiled (subunits,
6700 and specifications where a separate body is present).
6701 @end table
6702
6703 @node Compiling Different Versions of Ada
6704 @subsection Compiling Different Versions of Ada
6705
6706 @noindent
6707 The switches described in this section allow you to explicitly specify
6708 the version of the Ada language that your programs are written in.
6709 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6710 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6711 indicate Ada 83 compatibility mode.
6712
6713 @table @option
6714 @cindex Compatibility with Ada 83
6715
6716 @item -gnat83 (Ada 83 Compatibility Mode)
6717 @cindex @option{-gnat83} (@command{gcc})
6718 @cindex ACVC, Ada 83 tests
6719 @cindex Ada 83 mode
6720
6721 @noindent
6722 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6723 specifies that the program is to be compiled in Ada 83 mode. With
6724 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6725 semantics where this can be done easily.
6726 It is not possible to guarantee this switch does a perfect
6727 job; some subtle tests, such as are
6728 found in earlier ACVC tests (and that have been removed from the ACATS suite
6729 for Ada 95), might not compile correctly.
6730 Nevertheless, this switch may be useful in some circumstances, for example
6731 where, due to contractual reasons, existing code needs to be maintained
6732 using only Ada 83 features.
6733
6734 With few exceptions (most notably the need to use @code{<>} on
6735 @cindex Generic formal parameters
6736 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6737 reserved words, and the use of packages
6738 with optional bodies), it is not necessary to specify the
6739 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6740 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6741 a correct Ada 83 program is usually also a correct program
6742 in these later versions of the language standard.
6743 For further information, please refer to @ref{Compatibility and Porting Guide}.
6744
6745 @item -gnat95 (Ada 95 mode)
6746 @cindex @option{-gnat95} (@command{gcc})
6747 @cindex Ada 95 mode
6748
6749 @noindent
6750 This switch directs the compiler to implement the Ada 95 version of the
6751 language.
6752 Since Ada 95 is almost completely upwards
6753 compatible with Ada 83, Ada 83 programs may generally be compiled using
6754 this switch (see the description of the @option{-gnat83} switch for further
6755 information about Ada 83 mode).
6756 If an Ada 2005 program is compiled in Ada 95 mode,
6757 uses of the new Ada 2005 features will cause error
6758 messages or warnings.
6759
6760 This switch also can be used to cancel the effect of a previous
6761 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6762
6763 @item -gnat05 (Ada 2005 mode)
6764 @cindex @option{-gnat05} (@command{gcc})
6765 @cindex Ada 2005 mode
6766
6767 @noindent
6768 This switch directs the compiler to implement the Ada 2005 version of the
6769 language.
6770 Since Ada 2005 is almost completely upwards
6771 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6772 may generally be compiled using this switch (see the description of the
6773 @option{-gnat83} and @option{-gnat95} switches for further
6774 information).
6775
6776 For information about the approved ``Ada Issues'' that have been incorporated
6777 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6778 Included with GNAT releases is a file @file{features-ada0y} that describes
6779 the set of implemented Ada 2005 features.
6780 @end table
6781
6782
6783 @node Character Set Control
6784 @subsection Character Set Control
6785 @table @option
6786 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6787 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6788
6789 @noindent
6790 Normally GNAT recognizes the Latin-1 character set in source program
6791 identifiers, as described in the Ada Reference Manual.
6792 This switch causes
6793 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6794 single character ^^or word^ indicating the character set, as follows:
6795
6796 @table @code
6797 @item 1
6798 ISO 8859-1 (Latin-1) identifiers
6799
6800 @item 2
6801 ISO 8859-2 (Latin-2) letters allowed in identifiers
6802
6803 @item 3
6804 ISO 8859-3 (Latin-3) letters allowed in identifiers
6805
6806 @item 4
6807 ISO 8859-4 (Latin-4) letters allowed in identifiers
6808
6809 @item 5
6810 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6811
6812 @item 9
6813 ISO 8859-15 (Latin-9) letters allowed in identifiers
6814
6815 @item ^p^PC^
6816 IBM PC letters (code page 437) allowed in identifiers
6817
6818 @item ^8^PC850^
6819 IBM PC letters (code page 850) allowed in identifiers
6820
6821 @item ^f^FULL_UPPER^
6822 Full upper-half codes allowed in identifiers
6823
6824 @item ^n^NO_UPPER^
6825 No upper-half codes allowed in identifiers
6826
6827 @item ^w^WIDE^
6828 Wide-character codes (that is, codes greater than 255)
6829 allowed in identifiers
6830 @end table
6831
6832 @xref{Foreign Language Representation}, for full details on the
6833 implementation of these character sets.
6834
6835 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6836 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6837 Specify the method of encoding for wide characters.
6838 @var{e} is one of the following:
6839
6840 @table @code
6841
6842 @item ^h^HEX^
6843 Hex encoding (brackets coding also recognized)
6844
6845 @item ^u^UPPER^
6846 Upper half encoding (brackets encoding also recognized)
6847
6848 @item ^s^SHIFT_JIS^
6849 Shift/JIS encoding (brackets encoding also recognized)
6850
6851 @item ^e^EUC^
6852 EUC encoding (brackets encoding also recognized)
6853
6854 @item ^8^UTF8^
6855 UTF-8 encoding (brackets encoding also recognized)
6856
6857 @item ^b^BRACKETS^
6858 Brackets encoding only (default value)
6859 @end table
6860 For full details on these encoding
6861 methods see @ref{Wide Character Encodings}.
6862 Note that brackets coding is always accepted, even if one of the other
6863 options is specified, so for example @option{-gnatW8} specifies that both
6864 brackets and UTF-8 encodings will be recognized. The units that are
6865 with'ed directly or indirectly will be scanned using the specified
6866 representation scheme, and so if one of the non-brackets scheme is
6867 used, it must be used consistently throughout the program. However,
6868 since brackets encoding is always recognized, it may be conveniently
6869 used in standard libraries, allowing these libraries to be used with
6870 any of the available coding schemes.
6871 scheme.
6872
6873 If no @option{-gnatW?} parameter is present, then the default
6874 representation is normally Brackets encoding only. However, if the
6875 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6876 byte order mark or BOM for UTF-8), then these three characters are
6877 skipped and the default representation for the file is set to UTF-8.
6878
6879 Note that the wide character representation that is specified (explicitly
6880 or by default) for the main program also acts as the default encoding used
6881 for Wide_Text_IO files if not specifically overridden by a WCEM form
6882 parameter.
6883
6884 @end table
6885 @node File Naming Control
6886 @subsection File Naming Control
6887
6888 @table @option
6889 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6890 @cindex @option{-gnatk} (@command{gcc})
6891 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6892 1-999, indicates the maximum allowable length of a file name (not
6893 including the @file{.ads} or @file{.adb} extension). The default is not
6894 to enable file name krunching.
6895
6896 For the source file naming rules, @xref{File Naming Rules}.
6897 @end table
6898
6899 @node Subprogram Inlining Control
6900 @subsection Subprogram Inlining Control
6901
6902 @table @option
6903 @c !sort!
6904 @item -gnatn
6905 @cindex @option{-gnatn} (@command{gcc})
6906 @ifclear vms
6907 The @code{n} here is intended to suggest the first syllable of the
6908 word ``inline''.
6909 @end ifclear
6910 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6911 inlining to actually occur, optimization must be enabled. To enable
6912 inlining of subprograms specified by pragma @code{Inline},
6913 you must also specify this switch.
6914 In the absence of this switch, GNAT does not attempt
6915 inlining and does not need to access the bodies of
6916 subprograms for which @code{pragma Inline} is specified if they are not
6917 in the current unit.
6918
6919 If you specify this switch the compiler will access these bodies,
6920 creating an extra source dependency for the resulting object file, and
6921 where possible, the call will be inlined.
6922 For further details on when inlining is possible
6923 see @ref{Inlining of Subprograms}.
6924
6925 @item -gnatN
6926 @cindex @option{-gnatN} (@command{gcc})
6927 This switch activates front-end inlining which also
6928 generates additional dependencies.
6929
6930 When using a gcc-based back end (in practice this means using any version
6931 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6932 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6933 Historically front end inlining was more extensive than the gcc back end
6934 inlining, but that is no longer the case.
6935 @end table
6936
6937 @node Auxiliary Output Control
6938 @subsection Auxiliary Output Control
6939
6940 @table @option
6941 @item -gnatt
6942 @cindex @option{-gnatt} (@command{gcc})
6943 @cindex Writing internal trees
6944 @cindex Internal trees, writing to file
6945 Causes GNAT to write the internal tree for a unit to a file (with the
6946 extension @file{.adt}.
6947 This not normally required, but is used by separate analysis tools.
6948 Typically
6949 these tools do the necessary compilations automatically, so you should
6950 not have to specify this switch in normal operation.
6951
6952 @item -gnatu
6953 @cindex @option{-gnatu} (@command{gcc})
6954 Print a list of units required by this compilation on @file{stdout}.
6955 The listing includes all units on which the unit being compiled depends
6956 either directly or indirectly.
6957
6958 @ifclear vms
6959 @item -pass-exit-codes
6960 @cindex @option{-pass-exit-codes} (@command{gcc})
6961 If this switch is not used, the exit code returned by @command{gcc} when
6962 compiling multiple files indicates whether all source files have
6963 been successfully used to generate object files or not.
6964
6965 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6966 exit status and allows an integrated development environment to better
6967 react to a compilation failure. Those exit status are:
6968
6969 @table @asis
6970 @item 5
6971 There was an error in at least one source file.
6972 @item 3
6973 At least one source file did not generate an object file.
6974 @item 2
6975 The compiler died unexpectedly (internal error for example).
6976 @item 0
6977 An object file has been generated for every source file.
6978 @end table
6979 @end ifclear
6980 @end table
6981
6982 @node Debugging Control
6983 @subsection Debugging Control
6984
6985 @table @option
6986 @c !sort!
6987 @cindex Debugging options
6988 @ifclear vms
6989 @item -gnatd@var{x}
6990 @cindex @option{-gnatd} (@command{gcc})
6991 Activate internal debugging switches. @var{x} is a letter or digit, or
6992 string of letters or digits, which specifies the type of debugging
6993 outputs desired. Normally these are used only for internal development
6994 or system debugging purposes. You can find full documentation for these
6995 switches in the body of the @code{Debug} unit in the compiler source
6996 file @file{debug.adb}.
6997 @end ifclear
6998
6999 @item -gnatG[=nn]
7000 @cindex @option{-gnatG} (@command{gcc})
7001 This switch causes the compiler to generate auxiliary output containing
7002 a pseudo-source listing of the generated expanded code. Like most Ada
7003 compilers, GNAT works by first transforming the high level Ada code into
7004 lower level constructs. For example, tasking operations are transformed
7005 into calls to the tasking run-time routines. A unique capability of GNAT
7006 is to list this expanded code in a form very close to normal Ada source.
7007 This is very useful in understanding the implications of various Ada
7008 usage on the efficiency of the generated code. There are many cases in
7009 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7010 generate a lot of run-time code. By using @option{-gnatG} you can identify
7011 these cases, and consider whether it may be desirable to modify the coding
7012 approach to improve efficiency.
7013
7014 The optional parameter @code{nn} if present after -gnatG specifies an
7015 alternative maximum line length that overrides the normal default of 72.
7016 This value is in the range 40-999999, values less than 40 being silently
7017 reset to 40. The equal sign is optional.
7018
7019 The format of the output is very similar to standard Ada source, and is
7020 easily understood by an Ada programmer. The following special syntactic
7021 additions correspond to low level features used in the generated code that
7022 do not have any exact analogies in pure Ada source form. The following
7023 is a partial list of these special constructions. See the spec
7024 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7025
7026 If the switch @option{-gnatL} is used in conjunction with
7027 @cindex @option{-gnatL} (@command{gcc})
7028 @option{-gnatG}, then the original source lines are interspersed
7029 in the expanded source (as comment lines with the original line number).
7030
7031 @table @code
7032 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7033 Shows the storage pool being used for an allocator.
7034
7035 @item at end @var{procedure-name};
7036 Shows the finalization (cleanup) procedure for a scope.
7037
7038 @item (if @var{expr} then @var{expr} else @var{expr})
7039 Conditional expression equivalent to the @code{x?y:z} construction in C.
7040
7041 @item @var{target}^^^(@var{source})
7042 A conversion with floating-point truncation instead of rounding.
7043
7044 @item @var{target}?(@var{source})
7045 A conversion that bypasses normal Ada semantic checking. In particular
7046 enumeration types and fixed-point types are treated simply as integers.
7047
7048 @item @var{target}?^^^(@var{source})
7049 Combines the above two cases.
7050
7051 @item @var{x} #/ @var{y}
7052 @itemx @var{x} #mod @var{y}
7053 @itemx @var{x} #* @var{y}
7054 @itemx @var{x} #rem @var{y}
7055 A division or multiplication of fixed-point values which are treated as
7056 integers without any kind of scaling.
7057
7058 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7059 Shows the storage pool associated with a @code{free} statement.
7060
7061 @item [subtype or type declaration]
7062 Used to list an equivalent declaration for an internally generated
7063 type that is referenced elsewhere in the listing.
7064
7065 @item freeze @var{type-name} @ovar{actions}
7066 Shows the point at which @var{type-name} is frozen, with possible
7067 associated actions to be performed at the freeze point.
7068
7069 @item reference @var{itype}
7070 Reference (and hence definition) to internal type @var{itype}.
7071
7072 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7073 Intrinsic function call.
7074
7075 @item @var{label-name} : label
7076 Declaration of label @var{labelname}.
7077
7078 @item #$ @var{subprogram-name}
7079 An implicit call to a run-time support routine
7080 (to meet the requirement of H.3.1(9) in a
7081 convenient manner).
7082
7083 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7084 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7085 @var{expr}, but handled more efficiently).
7086
7087 @item [constraint_error]
7088 Raise the @code{Constraint_Error} exception.
7089
7090 @item @var{expression}'reference
7091 A pointer to the result of evaluating @var{expression}.
7092
7093 @item @var{target-type}!(@var{source-expression})
7094 An unchecked conversion of @var{source-expression} to @var{target-type}.
7095
7096 @item [@var{numerator}/@var{denominator}]
7097 Used to represent internal real literals (that) have no exact
7098 representation in base 2-16 (for example, the result of compile time
7099 evaluation of the expression 1.0/27.0).
7100 @end table
7101
7102 @item -gnatD[=nn]
7103 @cindex @option{-gnatD} (@command{gcc})
7104 When used in conjunction with @option{-gnatG}, this switch causes
7105 the expanded source, as described above for
7106 @option{-gnatG} to be written to files with names
7107 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7108 instead of to the standard output file. For
7109 example, if the source file name is @file{hello.adb}, then a file
7110 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7111 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7112 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7113 you to do source level debugging using the generated code which is
7114 sometimes useful for complex code, for example to find out exactly
7115 which part of a complex construction raised an exception. This switch
7116 also suppress generation of cross-reference information (see
7117 @option{-gnatx}) since otherwise the cross-reference information
7118 would refer to the @file{^.dg^.DG^} file, which would cause
7119 confusion since this is not the original source file.
7120
7121 Note that @option{-gnatD} actually implies @option{-gnatG}
7122 automatically, so it is not necessary to give both options.
7123 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7124
7125 If the switch @option{-gnatL} is used in conjunction with
7126 @cindex @option{-gnatL} (@command{gcc})
7127 @option{-gnatDG}, then the original source lines are interspersed
7128 in the expanded source (as comment lines with the original line number).
7129
7130 The optional parameter @code{nn} if present after -gnatD specifies an
7131 alternative maximum line length that overrides the normal default of 72.
7132 This value is in the range 40-999999, values less than 40 being silently
7133 reset to 40. The equal sign is optional.
7134
7135 @item -gnatr
7136 @cindex @option{-gnatr} (@command{gcc})
7137 @cindex pragma Restrictions
7138 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7139 so that violation of restrictions causes warnings rather than illegalities.
7140 This is useful during the development process when new restrictions are added
7141 or investigated. The switch also causes pragma Profile to be treated as
7142 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7143 restriction warnings rather than restrictions.
7144
7145 @ifclear vms
7146 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7147 @cindex @option{-gnatR} (@command{gcc})
7148 This switch controls output from the compiler of a listing showing
7149 representation information for declared types and objects. For
7150 @option{-gnatR0}, no information is output (equivalent to omitting
7151 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7152 so @option{-gnatR} with no parameter has the same effect), size and alignment
7153 information is listed for declared array and record types. For
7154 @option{-gnatR2}, size and alignment information is listed for all
7155 declared types and objects. Finally @option{-gnatR3} includes symbolic
7156 expressions for values that are computed at run time for
7157 variant records. These symbolic expressions have a mostly obvious
7158 format with #n being used to represent the value of the n'th
7159 discriminant. See source files @file{repinfo.ads/adb} in the
7160 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7161 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7162 the output is to a file with the name @file{^file.rep^file_REP^} where
7163 file is the name of the corresponding source file.
7164 @end ifclear
7165 @ifset vms
7166 @item /REPRESENTATION_INFO
7167 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7168 This qualifier controls output from the compiler of a listing showing
7169 representation information for declared types and objects. For
7170 @option{/REPRESENTATION_INFO=NONE}, no information is output
7171 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7172 @option{/REPRESENTATION_INFO} without option is equivalent to
7173 @option{/REPRESENTATION_INFO=ARRAYS}.
7174 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7175 information is listed for declared array and record types. For
7176 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7177 is listed for all expression information for values that are computed
7178 at run time for variant records. These symbolic expressions have a mostly
7179 obvious format with #n being used to represent the value of the n'th
7180 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7181 @code{GNAT} sources for full details on the format of
7182 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7183 If _FILE is added at the end of an option
7184 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7185 then the output is to a file with the name @file{file_REP} where
7186 file is the name of the corresponding source file.
7187 @end ifset
7188 Note that it is possible for record components to have zero size. In
7189 this case, the component clause uses an obvious extension of permitted
7190 Ada syntax, for example @code{at 0 range 0 .. -1}.
7191
7192 Representation information requires that code be generated (since it is the
7193 code generator that lays out complex data structures). If an attempt is made
7194 to output representation information when no code is generated, for example
7195 when a subunit is compiled on its own, then no information can be generated
7196 and the compiler outputs a message to this effect.
7197
7198 @item -gnatS
7199 @cindex @option{-gnatS} (@command{gcc})
7200 The use of the switch @option{-gnatS} for an
7201 Ada compilation will cause the compiler to output a
7202 representation of package Standard in a form very
7203 close to standard Ada. It is not quite possible to
7204 do this entirely in standard Ada (since new
7205 numeric base types cannot be created in standard
7206 Ada), but the output is easily
7207 readable to any Ada programmer, and is useful to
7208 determine the characteristics of target dependent
7209 types in package Standard.
7210
7211 @item -gnatx
7212 @cindex @option{-gnatx} (@command{gcc})
7213 Normally the compiler generates full cross-referencing information in
7214 the @file{ALI} file. This information is used by a number of tools,
7215 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7216 suppresses this information. This saves some space and may slightly
7217 speed up compilation, but means that these tools cannot be used.
7218 @end table
7219
7220 @node Exception Handling Control
7221 @subsection Exception Handling Control
7222
7223 @noindent
7224 GNAT uses two methods for handling exceptions at run-time. The
7225 @code{setjmp/longjmp} method saves the context when entering
7226 a frame with an exception handler. Then when an exception is
7227 raised, the context can be restored immediately, without the
7228 need for tracing stack frames. This method provides very fast
7229 exception propagation, but introduces significant overhead for
7230 the use of exception handlers, even if no exception is raised.
7231
7232 The other approach is called ``zero cost'' exception handling.
7233 With this method, the compiler builds static tables to describe
7234 the exception ranges. No dynamic code is required when entering
7235 a frame containing an exception handler. When an exception is
7236 raised, the tables are used to control a back trace of the
7237 subprogram invocation stack to locate the required exception
7238 handler. This method has considerably poorer performance for
7239 the propagation of exceptions, but there is no overhead for
7240 exception handlers if no exception is raised. Note that in this
7241 mode and in the context of mixed Ada and C/C++ programming,
7242 to propagate an exception through a C/C++ code, the C/C++ code
7243 must be compiled with the @option{-funwind-tables} GCC's
7244 option.
7245
7246 The following switches may be used to control which of the
7247 two exception handling methods is used.
7248
7249 @table @option
7250 @c !sort!
7251
7252 @item --RTS=sjlj
7253 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7254 This switch causes the setjmp/longjmp run-time (when available) to be used
7255 for exception handling. If the default
7256 mechanism for the target is zero cost exceptions, then
7257 this switch can be used to modify this default, and must be
7258 used for all units in the partition.
7259 This option is rarely used. One case in which it may be
7260 advantageous is if you have an application where exception
7261 raising is common and the overall performance of the
7262 application is improved by favoring exception propagation.
7263
7264 @item --RTS=zcx
7265 @cindex @option{--RTS=zcx} (@command{gnatmake})
7266 @cindex Zero Cost Exceptions
7267 This switch causes the zero cost approach to be used
7268 for exception handling. If this is the default mechanism for the
7269 target (see below), then this switch is unneeded. If the default
7270 mechanism for the target is setjmp/longjmp exceptions, then
7271 this switch can be used to modify this default, and must be
7272 used for all units in the partition.
7273 This option can only be used if the zero cost approach
7274 is available for the target in use, otherwise it will generate an error.
7275 @end table
7276
7277 @noindent
7278 The same option @option{--RTS} must be used both for @command{gcc}
7279 and @command{gnatbind}. Passing this option to @command{gnatmake}
7280 (@pxref{Switches for gnatmake}) will ensure the required consistency
7281 through the compilation and binding steps.
7282
7283 @node Units to Sources Mapping Files
7284 @subsection Units to Sources Mapping Files
7285
7286 @table @option
7287
7288 @item -gnatem^^=^@var{path}
7289 @cindex @option{-gnatem} (@command{gcc})
7290 A mapping file is a way to communicate to the compiler two mappings:
7291 from unit names to file names (without any directory information) and from
7292 file names to path names (with full directory information). These mappings
7293 are used by the compiler to short-circuit the path search.
7294
7295 The use of mapping files is not required for correct operation of the
7296 compiler, but mapping files can improve efficiency, particularly when
7297 sources are read over a slow network connection. In normal operation,
7298 you need not be concerned with the format or use of mapping files,
7299 and the @option{-gnatem} switch is not a switch that you would use
7300 explicitly. it is intended only for use by automatic tools such as
7301 @command{gnatmake} running under the project file facility. The
7302 description here of the format of mapping files is provided
7303 for completeness and for possible use by other tools.
7304
7305 A mapping file is a sequence of sets of three lines. In each set,
7306 the first line is the unit name, in lower case, with ``@code{%s}''
7307 appended for
7308 specs and ``@code{%b}'' appended for bodies; the second line is the
7309 file name; and the third line is the path name.
7310
7311 Example:
7312 @smallexample
7313 main%b
7314 main.2.ada
7315 /gnat/project1/sources/main.2.ada
7316 @end smallexample
7317
7318 When the switch @option{-gnatem} is specified, the compiler will create
7319 in memory the two mappings from the specified file. If there is any problem
7320 (nonexistent file, truncated file or duplicate entries), no mapping will
7321 be created.
7322
7323 Several @option{-gnatem} switches may be specified; however, only the last
7324 one on the command line will be taken into account.
7325
7326 When using a project file, @command{gnatmake} create a temporary mapping file
7327 and communicates it to the compiler using this switch.
7328
7329 @end table
7330
7331 @node Integrated Preprocessing
7332 @subsection Integrated Preprocessing
7333
7334 @noindent
7335 GNAT sources may be preprocessed immediately before compilation.
7336 In this case, the actual
7337 text of the source is not the text of the source file, but is derived from it
7338 through a process called preprocessing. Integrated preprocessing is specified
7339 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7340 indicates, through a text file, the preprocessing data to be used.
7341 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7342
7343 @noindent
7344 Note that when integrated preprocessing is used, the output from the
7345 preprocessor is not written to any external file. Instead it is passed
7346 internally to the compiler. If you need to preserve the result of
7347 preprocessing in a file, then you should use @command{gnatprep}
7348 to perform the desired preprocessing in stand-alone mode.
7349
7350 @noindent
7351 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7352 used when Integrated Preprocessing is used. The reason is that preprocessing
7353 with another Preprocessing Data file without changing the sources will
7354 not trigger recompilation without this switch.
7355
7356 @noindent
7357 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7358 always trigger recompilation for sources that are preprocessed,
7359 because @command{gnatmake} cannot compute the checksum of the source after
7360 preprocessing.
7361
7362 @noindent
7363 The actual preprocessing function is described in details in section
7364 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7365 preprocessing is triggered and parameterized.
7366
7367 @table @code
7368
7369 @item -gnatep=@var{file}
7370 @cindex @option{-gnatep} (@command{gcc})
7371 This switch indicates to the compiler the file name (without directory
7372 information) of the preprocessor data file to use. The preprocessor data file
7373 should be found in the source directories.
7374
7375 @noindent
7376 A preprocessing data file is a text file with significant lines indicating
7377 how should be preprocessed either a specific source or all sources not
7378 mentioned in other lines. A significant line is a nonempty, non-comment line.
7379 Comments are similar to Ada comments.
7380
7381 @noindent
7382 Each significant line starts with either a literal string or the character '*'.
7383 A literal string is the file name (without directory information) of the source
7384 to preprocess. A character '*' indicates the preprocessing for all the sources
7385 that are not specified explicitly on other lines (order of the lines is not
7386 significant). It is an error to have two lines with the same file name or two
7387 lines starting with the character '*'.
7388
7389 @noindent
7390 After the file name or the character '*', another optional literal string
7391 indicating the file name of the definition file to be used for preprocessing
7392 (@pxref{Form of Definitions File}). The definition files are found by the
7393 compiler in one of the source directories. In some cases, when compiling
7394 a source in a directory other than the current directory, if the definition
7395 file is in the current directory, it may be necessary to add the current
7396 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7397 the compiler would not find the definition file.
7398
7399 @noindent
7400 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7401 be found. Those ^switches^switches^ are:
7402
7403 @table @code
7404
7405 @item -b
7406 Causes both preprocessor lines and the lines deleted by
7407 preprocessing to be replaced by blank lines, preserving the line number.
7408 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7409 it cancels the effect of @option{-c}.
7410
7411 @item -c
7412 Causes both preprocessor lines and the lines deleted
7413 by preprocessing to be retained as comments marked
7414 with the special string ``@code{--! }''.
7415
7416 @item -Dsymbol=value
7417 Define or redefine a symbol, associated with value. A symbol is an Ada
7418 identifier, or an Ada reserved word, with the exception of @code{if},
7419 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7420 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7421 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7422 same name defined in a definition file.
7423
7424 @item -s
7425 Causes a sorted list of symbol names and values to be
7426 listed on the standard output file.
7427
7428 @item -u
7429 Causes undefined symbols to be treated as having the value @code{FALSE}
7430 in the context
7431 of a preprocessor test. In the absence of this option, an undefined symbol in
7432 a @code{#if} or @code{#elsif} test will be treated as an error.
7433
7434 @end table
7435
7436 @noindent
7437 Examples of valid lines in a preprocessor data file:
7438
7439 @smallexample
7440 "toto.adb" "prep.def" -u
7441 -- preprocess "toto.adb", using definition file "prep.def",
7442 -- undefined symbol are False.
7443
7444 * -c -DVERSION=V101
7445 -- preprocess all other sources without a definition file;
7446 -- suppressed lined are commented; symbol VERSION has the value V101.
7447
7448 "titi.adb" "prep2.def" -s
7449 -- preprocess "titi.adb", using definition file "prep2.def";
7450 -- list all symbols with their values.
7451 @end smallexample
7452
7453 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7454 @cindex @option{-gnateD} (@command{gcc})
7455 Define or redefine a preprocessing symbol, associated with value. If no value
7456 is given on the command line, then the value of the symbol is @code{True}.
7457 A symbol is an identifier, following normal Ada (case-insensitive)
7458 rules for its syntax, and value is any sequence (including an empty sequence)
7459 of characters from the set (letters, digits, period, underline).
7460 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7461 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7462
7463 @noindent
7464 A symbol declared with this ^switch^switch^ on the command line replaces a
7465 symbol with the same name either in a definition file or specified with a
7466 ^switch^switch^ -D in the preprocessor data file.
7467
7468 @noindent
7469 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7470
7471 @item -gnateG
7472 When integrated preprocessing is performed and the preprocessor modifies
7473 the source text, write the result of this preprocessing into a file
7474 <source>^.prep^_prep^.
7475
7476 @end table
7477
7478 @node Code Generation Control
7479 @subsection Code Generation Control
7480
7481 @noindent
7482
7483 The GCC technology provides a wide range of target dependent
7484 @option{-m} switches for controlling
7485 details of code generation with respect to different versions of
7486 architectures. This includes variations in instruction sets (e.g.@:
7487 different members of the power pc family), and different requirements
7488 for optimal arrangement of instructions (e.g.@: different members of
7489 the x86 family). The list of available @option{-m} switches may be
7490 found in the GCC documentation.
7491
7492 Use of these @option{-m} switches may in some cases result in improved
7493 code performance.
7494
7495 The GNAT Pro technology is tested and qualified without any
7496 @option{-m} switches,
7497 so generally the most reliable approach is to avoid the use of these
7498 switches. However, we generally expect most of these switches to work
7499 successfully with GNAT Pro, and many customers have reported successful
7500 use of these options.
7501
7502 Our general advice is to avoid the use of @option{-m} switches unless
7503 special needs lead to requirements in this area. In particular,
7504 there is no point in using @option{-m} switches to improve performance
7505 unless you actually see a performance improvement.
7506
7507 @ifset vms
7508 @node Return Codes
7509 @subsection Return Codes
7510 @cindex Return Codes
7511 @cindex @option{/RETURN_CODES=VMS}
7512
7513 @noindent
7514 On VMS, GNAT compiled programs return POSIX-style codes by default,
7515 e.g.@: @option{/RETURN_CODES=POSIX}.
7516
7517 To enable VMS style return codes, use GNAT BIND and LINK with the option
7518 @option{/RETURN_CODES=VMS}. For example:
7519
7520 @smallexample
7521 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7522 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7523 @end smallexample
7524
7525 @noindent
7526 Programs built with /RETURN_CODES=VMS are suitable to be called in
7527 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7528 are suitable for spawning with appropriate GNAT RTL routines.
7529
7530 @end ifset
7531
7532 @node Search Paths and the Run-Time Library (RTL)
7533 @section Search Paths and the Run-Time Library (RTL)
7534
7535 @noindent
7536 With the GNAT source-based library system, the compiler must be able to
7537 find source files for units that are needed by the unit being compiled.
7538 Search paths are used to guide this process.
7539
7540 The compiler compiles one source file whose name must be given
7541 explicitly on the command line. In other words, no searching is done
7542 for this file. To find all other source files that are needed (the most
7543 common being the specs of units), the compiler examines the following
7544 directories, in the following order:
7545
7546 @enumerate
7547 @item
7548 The directory containing the source file of the main unit being compiled
7549 (the file name on the command line).
7550
7551 @item
7552 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7553 @command{gcc} command line, in the order given.
7554
7555 @item
7556 @findex ADA_PRJ_INCLUDE_FILE
7557 Each of the directories listed in the text file whose name is given
7558 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7559
7560 @noindent
7561 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7562 driver when project files are used. It should not normally be set
7563 by other means.
7564
7565 @item
7566 @findex ADA_INCLUDE_PATH
7567 Each of the directories listed in the value of the
7568 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7569 @ifclear vms
7570 Construct this value
7571 exactly as the @env{PATH} environment variable: a list of directory
7572 names separated by colons (semicolons when working with the NT version).
7573 @end ifclear
7574 @ifset vms
7575 Normally, define this value as a logical name containing a comma separated
7576 list of directory names.
7577
7578 This variable can also be defined by means of an environment string
7579 (an argument to the HP C exec* set of functions).
7580
7581 Logical Name:
7582 @smallexample
7583 DEFINE ANOTHER_PATH FOO:[BAG]
7584 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7585 @end smallexample
7586
7587 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7588 first, followed by the standard Ada
7589 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7590 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7591 (Text_IO, Sequential_IO, etc)
7592 instead of the standard Ada packages. Thus, in order to get the standard Ada
7593 packages by default, ADA_INCLUDE_PATH must be redefined.
7594 @end ifset
7595
7596 @item
7597 The content of the @file{ada_source_path} file which is part of the GNAT
7598 installation tree and is used to store standard libraries such as the
7599 GNAT Run Time Library (RTL) source files.
7600 @ifclear vms
7601 @ref{Installing a library}
7602 @end ifclear
7603 @end enumerate
7604
7605 @noindent
7606 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7607 inhibits the use of the directory
7608 containing the source file named in the command line. You can still
7609 have this directory on your search path, but in this case it must be
7610 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7611
7612 Specifying the switch @option{-nostdinc}
7613 inhibits the search of the default location for the GNAT Run Time
7614 Library (RTL) source files.
7615
7616 The compiler outputs its object files and ALI files in the current
7617 working directory.
7618 @ifclear vms
7619 Caution: The object file can be redirected with the @option{-o} switch;
7620 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7621 so the @file{ALI} file will not go to the right place. Therefore, you should
7622 avoid using the @option{-o} switch.
7623 @end ifclear
7624
7625 @findex System.IO
7626 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7627 children make up the GNAT RTL, together with the simple @code{System.IO}
7628 package used in the @code{"Hello World"} example. The sources for these units
7629 are needed by the compiler and are kept together in one directory. Not
7630 all of the bodies are needed, but all of the sources are kept together
7631 anyway. In a normal installation, you need not specify these directory
7632 names when compiling or binding. Either the environment variables or
7633 the built-in defaults cause these files to be found.
7634
7635 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7636 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7637 consisting of child units of @code{GNAT}. This is a collection of generally
7638 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7639 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7640
7641 Besides simplifying access to the RTL, a major use of search paths is
7642 in compiling sources from multiple directories. This can make
7643 development environments much more flexible.
7644
7645 @node Order of Compilation Issues
7646 @section Order of Compilation Issues
7647
7648 @noindent
7649 If, in our earlier example, there was a spec for the @code{hello}
7650 procedure, it would be contained in the file @file{hello.ads}; yet this
7651 file would not have to be explicitly compiled. This is the result of the
7652 model we chose to implement library management. Some of the consequences
7653 of this model are as follows:
7654
7655 @itemize @bullet
7656 @item
7657 There is no point in compiling specs (except for package
7658 specs with no bodies) because these are compiled as needed by clients. If
7659 you attempt a useless compilation, you will receive an error message.
7660 It is also useless to compile subunits because they are compiled as needed
7661 by the parent.
7662
7663 @item
7664 There are no order of compilation requirements: performing a
7665 compilation never obsoletes anything. The only way you can obsolete
7666 something and require recompilations is to modify one of the
7667 source files on which it depends.
7668
7669 @item
7670 There is no library as such, apart from the ALI files
7671 (@pxref{The Ada Library Information Files}, for information on the format
7672 of these files). For now we find it convenient to create separate ALI files,
7673 but eventually the information therein may be incorporated into the object
7674 file directly.
7675
7676 @item
7677 When you compile a unit, the source files for the specs of all units
7678 that it @code{with}'s, all its subunits, and the bodies of any generics it
7679 instantiates must be available (reachable by the search-paths mechanism
7680 described above), or you will receive a fatal error message.
7681 @end itemize
7682
7683 @node Examples
7684 @section Examples
7685
7686 @noindent
7687 The following are some typical Ada compilation command line examples:
7688
7689 @table @code
7690 @item $ gcc -c xyz.adb
7691 Compile body in file @file{xyz.adb} with all default options.
7692
7693 @ifclear vms
7694 @item $ gcc -c -O2 -gnata xyz-def.adb
7695 @end ifclear
7696 @ifset vms
7697 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7698 @end ifset
7699
7700 Compile the child unit package in file @file{xyz-def.adb} with extensive
7701 optimizations, and pragma @code{Assert}/@code{Debug} statements
7702 enabled.
7703
7704 @item $ gcc -c -gnatc abc-def.adb
7705 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7706 mode.
7707 @end table
7708
7709 @node Binding Using gnatbind
7710 @chapter Binding Using @code{gnatbind}
7711 @findex gnatbind
7712
7713 @menu
7714 * Running gnatbind::
7715 * Switches for gnatbind::
7716 * Command-Line Access::
7717 * Search Paths for gnatbind::
7718 * Examples of gnatbind Usage::
7719 @end menu
7720
7721 @noindent
7722 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7723 to bind compiled GNAT objects.
7724
7725 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7726 driver (see @ref{The GNAT Driver and Project Files}).
7727
7728 The @code{gnatbind} program performs four separate functions:
7729
7730 @enumerate
7731 @item
7732 Checks that a program is consistent, in accordance with the rules in
7733 Chapter 10 of the Ada Reference Manual. In particular, error
7734 messages are generated if a program uses inconsistent versions of a
7735 given unit.
7736
7737 @item
7738 Checks that an acceptable order of elaboration exists for the program
7739 and issues an error message if it cannot find an order of elaboration
7740 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7741
7742 @item
7743 Generates a main program incorporating the given elaboration order.
7744 This program is a small Ada package (body and spec) that
7745 must be subsequently compiled
7746 using the GNAT compiler. The necessary compilation step is usually
7747 performed automatically by @command{gnatlink}. The two most important
7748 functions of this program
7749 are to call the elaboration routines of units in an appropriate order
7750 and to call the main program.
7751
7752 @item
7753 Determines the set of object files required by the given main program.
7754 This information is output in the forms of comments in the generated program,
7755 to be read by the @command{gnatlink} utility used to link the Ada application.
7756 @end enumerate
7757
7758 @node Running gnatbind
7759 @section Running @code{gnatbind}
7760
7761 @noindent
7762 The form of the @code{gnatbind} command is
7763
7764 @smallexample
7765 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7766 @end smallexample
7767
7768 @noindent
7769 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7770 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7771 package in two files whose names are
7772 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7773 For example, if given the
7774 parameter @file{hello.ali}, for a main program contained in file
7775 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7776 and @file{b~hello.adb}.
7777
7778 When doing consistency checking, the binder takes into consideration
7779 any source files it can locate. For example, if the binder determines
7780 that the given main program requires the package @code{Pack}, whose
7781 @file{.ALI}
7782 file is @file{pack.ali} and whose corresponding source spec file is
7783 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7784 (using the same search path conventions as previously described for the
7785 @command{gcc} command). If it can locate this source file, it checks that
7786 the time stamps
7787 or source checksums of the source and its references to in @file{ALI} files
7788 match. In other words, any @file{ALI} files that mentions this spec must have
7789 resulted from compiling this version of the source file (or in the case
7790 where the source checksums match, a version close enough that the
7791 difference does not matter).
7792
7793 @cindex Source files, use by binder
7794 The effect of this consistency checking, which includes source files, is
7795 that the binder ensures that the program is consistent with the latest
7796 version of the source files that can be located at bind time. Editing a
7797 source file without compiling files that depend on the source file cause
7798 error messages to be generated by the binder.
7799
7800 For example, suppose you have a main program @file{hello.adb} and a
7801 package @code{P}, from file @file{p.ads} and you perform the following
7802 steps:
7803
7804 @enumerate
7805 @item
7806 Enter @code{gcc -c hello.adb} to compile the main program.
7807
7808 @item
7809 Enter @code{gcc -c p.ads} to compile package @code{P}.
7810
7811 @item
7812 Edit file @file{p.ads}.
7813
7814 @item
7815 Enter @code{gnatbind hello}.
7816 @end enumerate
7817
7818 @noindent
7819 At this point, the file @file{p.ali} contains an out-of-date time stamp
7820 because the file @file{p.ads} has been edited. The attempt at binding
7821 fails, and the binder generates the following error messages:
7822
7823 @smallexample
7824 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7825 error: "p.ads" has been modified and must be recompiled
7826 @end smallexample
7827
7828 @noindent
7829 Now both files must be recompiled as indicated, and then the bind can
7830 succeed, generating a main program. You need not normally be concerned
7831 with the contents of this file, but for reference purposes a sample
7832 binder output file is given in @ref{Example of Binder Output File}.
7833
7834 In most normal usage, the default mode of @command{gnatbind} which is to
7835 generate the main package in Ada, as described in the previous section.
7836 In particular, this means that any Ada programmer can read and understand
7837 the generated main program. It can also be debugged just like any other
7838 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7839 @command{gnatbind} and @command{gnatlink}.
7840
7841 However for some purposes it may be convenient to generate the main
7842 program in C rather than Ada. This may for example be helpful when you
7843 are generating a mixed language program with the main program in C. The
7844 GNAT compiler itself is an example.
7845 The use of the @option{^-C^/BIND_FILE=C^} switch
7846 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7847 be generated in C (and compiled using the gnu C compiler).
7848
7849 @node Switches for gnatbind
7850 @section Switches for @command{gnatbind}
7851
7852 @noindent
7853 The following switches are available with @code{gnatbind}; details will
7854 be presented in subsequent sections.
7855
7856 @menu
7857 * Consistency-Checking Modes::
7858 * Binder Error Message Control::
7859 * Elaboration Control::
7860 * Output Control::
7861 * Binding with Non-Ada Main Programs::
7862 * Binding Programs with No Main Subprogram::
7863 @end menu
7864
7865 @table @option
7866 @c !sort!
7867
7868 @item --version
7869 @cindex @option{--version} @command{gnatbind}
7870 Display Copyright and version, then exit disregarding all other options.
7871
7872 @item --help
7873 @cindex @option{--help} @command{gnatbind}
7874 If @option{--version} was not used, display usage, then exit disregarding
7875 all other options.
7876
7877 @item -a
7878 @cindex @option{-a} @command{gnatbind}
7879 Indicates that, if supported by the platform, the adainit procedure should
7880 be treated as an initialisation routine by the linker (a constructor). This
7881 is intended to be used by the Project Manager to automatically initialize
7882 shared Stand-Alone Libraries.
7883
7884 @item ^-aO^/OBJECT_SEARCH^
7885 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7886 Specify directory to be searched for ALI files.
7887
7888 @item ^-aI^/SOURCE_SEARCH^
7889 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7890 Specify directory to be searched for source file.
7891
7892 @item ^-A^/BIND_FILE=ADA^
7893 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7894 Generate binder program in Ada (default)
7895
7896 @item ^-b^/REPORT_ERRORS=BRIEF^
7897 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7898 Generate brief messages to @file{stderr} even if verbose mode set.
7899
7900 @item ^-c^/NOOUTPUT^
7901 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7902 Check only, no generation of binder output file.
7903
7904 @item ^-C^/BIND_FILE=C^
7905 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7906 Generate binder program in C
7907
7908 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7909 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7910 This switch can be used to change the default task stack size value
7911 to a specified size @var{nn}, which is expressed in bytes by default, or
7912 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7913 with @var{m}.
7914 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7915 in effect, to completing all task specs with
7916 @smallexample @c ada
7917 pragma Storage_Size (nn);
7918 @end smallexample
7919 When they do not already have such a pragma.
7920
7921 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7922 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7923 This switch can be used to change the default secondary stack size value
7924 to a specified size @var{nn}, which is expressed in bytes by default, or
7925 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7926 with @var{m}.
7927
7928 The secondary stack is used to deal with functions that return a variable
7929 sized result, for example a function returning an unconstrained
7930 String. There are two ways in which this secondary stack is allocated.
7931
7932 For most targets, the secondary stack is growing on demand and is allocated
7933 as a chain of blocks in the heap. The -D option is not very
7934 relevant. It only give some control over the size of the allocated
7935 blocks (whose size is the minimum of the default secondary stack size value,
7936 and the actual size needed for the current allocation request).
7937
7938 For certain targets, notably VxWorks 653,
7939 the secondary stack is allocated by carving off a fixed ratio chunk of the
7940 primary task stack. The -D option is used to define the
7941 size of the environment task's secondary stack.
7942
7943 @item ^-e^/ELABORATION_DEPENDENCIES^
7944 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7945 Output complete list of elaboration-order dependencies.
7946
7947 @item ^-E^/STORE_TRACEBACKS^
7948 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7949 Store tracebacks in exception occurrences when the target supports it.
7950 This is the default with the zero cost exception mechanism.
7951 @ignore
7952 @c The following may get moved to an appendix
7953 This option is currently supported on the following targets:
7954 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7955 @end ignore
7956 See also the packages @code{GNAT.Traceback} and
7957 @code{GNAT.Traceback.Symbolic} for more information.
7958 @ifclear vms
7959 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7960 @command{gcc} option.
7961 @end ifclear
7962
7963 @item ^-F^/FORCE_ELABS_FLAGS^
7964 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7965 Force the checks of elaboration flags. @command{gnatbind} does not normally
7966 generate checks of elaboration flags for the main executable, except when
7967 a Stand-Alone Library is used. However, there are cases when this cannot be
7968 detected by gnatbind. An example is importing an interface of a Stand-Alone
7969 Library through a pragma Import and only specifying through a linker switch
7970 this Stand-Alone Library. This switch is used to guarantee that elaboration
7971 flag checks are generated.
7972
7973 @item ^-h^/HELP^
7974 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7975 Output usage (help) information
7976
7977 @item ^-I^/SEARCH^
7978 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7979 Specify directory to be searched for source and ALI files.
7980
7981 @item ^-I-^/NOCURRENT_DIRECTORY^
7982 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7983 Do not look for sources in the current directory where @code{gnatbind} was
7984 invoked, and do not look for ALI files in the directory containing the
7985 ALI file named in the @code{gnatbind} command line.
7986
7987 @item ^-l^/ORDER_OF_ELABORATION^
7988 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7989 Output chosen elaboration order.
7990
7991 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7992 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7993 Bind the units for library building. In this case the adainit and
7994 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7995 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7996 ^@var{xxx}final^@var{XXX}FINAL^.
7997 Implies ^-n^/NOCOMPILE^.
7998 @ifclear vms
7999 (@xref{GNAT and Libraries}, for more details.)
8000 @end ifclear
8001 @ifset vms
8002 On OpenVMS, these init and final procedures are exported in uppercase
8003 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8004 the init procedure will be "TOTOINIT" and the exported name of the final
8005 procedure will be "TOTOFINAL".
8006 @end ifset
8007
8008 @item ^-Mxyz^/RENAME_MAIN=xyz^
8009 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8010 Rename generated main program from main to xyz. This option is
8011 supported on cross environments only.
8012
8013 @item ^-m^/ERROR_LIMIT=^@var{n}
8014 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8015 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8016 in the range 1..999999. The default value if no switch is
8017 given is 9999. If the number of warnings reaches this limit, then a
8018 message is output and further warnings are suppressed, the bind
8019 continues in this case. If the number of errors reaches this
8020 limit, then a message is output and the bind is abandoned.
8021 A value of zero means that no limit is enforced. The equal
8022 sign is optional.
8023
8024 @ifset unw
8025 Furthermore, under Windows, the sources pointed to by the libraries path
8026 set in the registry are not searched for.
8027 @end ifset
8028
8029 @item ^-n^/NOMAIN^
8030 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8031 No main program.
8032
8033 @item -nostdinc
8034 @cindex @option{-nostdinc} (@command{gnatbind})
8035 Do not look for sources in the system default directory.
8036
8037 @item -nostdlib
8038 @cindex @option{-nostdlib} (@command{gnatbind})
8039 Do not look for library files in the system default directory.
8040
8041 @item --RTS=@var{rts-path}
8042 @cindex @option{--RTS} (@code{gnatbind})
8043 Specifies the default location of the runtime library. Same meaning as the
8044 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8045
8046 @item ^-o ^/OUTPUT=^@var{file}
8047 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8048 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8049 Note that if this option is used, then linking must be done manually,
8050 gnatlink cannot be used.
8051
8052 @item ^-O^/OBJECT_LIST^
8053 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8054 Output object list.
8055
8056 @item ^-p^/PESSIMISTIC_ELABORATION^
8057 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8058 Pessimistic (worst-case) elaboration order
8059
8060 @item ^-R^-R^
8061 @cindex @option{^-R^-R^} (@command{gnatbind})
8062 Output closure source list.
8063
8064 @item ^-s^/READ_SOURCES=ALL^
8065 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8066 Require all source files to be present.
8067
8068 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8069 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8070 Specifies the value to be used when detecting uninitialized scalar
8071 objects with pragma Initialize_Scalars.
8072 The @var{xxx} ^string specified with the switch^option^ may be either
8073 @itemize @bullet
8074 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8075 @item ``@option{^lo^LOW^}'' for the lowest possible value
8076 @item ``@option{^hi^HIGH^}'' for the highest possible value
8077 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8078 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8079 @end itemize
8080
8081 In addition, you can specify @option{-Sev} to indicate that the value is
8082 to be set at run time. In this case, the program will look for an environment
8083 @cindex GNAT_INIT_SCALARS
8084 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8085 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8086 If no environment variable is found, or if it does not have a valid value,
8087 then the default is @option{in} (invalid values).
8088
8089 @ifclear vms
8090 @item -static
8091 @cindex @option{-static} (@code{gnatbind})
8092 Link against a static GNAT run time.
8093
8094 @item -shared
8095 @cindex @option{-shared} (@code{gnatbind})
8096 Link against a shared GNAT run time when available.
8097 @end ifclear
8098
8099 @item ^-t^/NOTIME_STAMP_CHECK^
8100 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8101 Tolerate time stamp and other consistency errors
8102
8103 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8104 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8105 Set the time slice value to @var{n} milliseconds. If the system supports
8106 the specification of a specific time slice value, then the indicated value
8107 is used. If the system does not support specific time slice values, but
8108 does support some general notion of round-robin scheduling, then any
8109 nonzero value will activate round-robin scheduling.
8110
8111 A value of zero is treated specially. It turns off time
8112 slicing, and in addition, indicates to the tasking run time that the
8113 semantics should match as closely as possible the Annex D
8114 requirements of the Ada RM, and in particular sets the default
8115 scheduling policy to @code{FIFO_Within_Priorities}.
8116
8117 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8118 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8119 Enable dynamic stack usage, with @var{n} results stored and displayed
8120 at program termination. A result is generated when a task
8121 terminates. Results that can't be stored are displayed on the fly, at
8122 task termination. This option is currently not supported on Itanium
8123 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8124
8125 @item ^-v^/REPORT_ERRORS=VERBOSE^
8126 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8127 Verbose mode. Write error messages, header, summary output to
8128 @file{stdout}.
8129
8130 @ifclear vms
8131 @item -w@var{x}
8132 @cindex @option{-w} (@code{gnatbind})
8133 Warning mode (@var{x}=s/e for suppress/treat as error)
8134 @end ifclear
8135
8136 @ifset vms
8137 @item /WARNINGS=NORMAL
8138 @cindex @option{/WARNINGS} (@code{gnatbind})
8139 Normal warnings mode. Warnings are issued but ignored
8140
8141 @item /WARNINGS=SUPPRESS
8142 @cindex @option{/WARNINGS} (@code{gnatbind})
8143 All warning messages are suppressed
8144
8145 @item /WARNINGS=ERROR
8146 @cindex @option{/WARNINGS} (@code{gnatbind})
8147 Warning messages are treated as fatal errors
8148 @end ifset
8149
8150 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8151 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8152 Override default wide character encoding for standard Text_IO files.
8153
8154 @item ^-x^/READ_SOURCES=NONE^
8155 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8156 Exclude source files (check object consistency only).
8157
8158 @ifset vms
8159 @item /READ_SOURCES=AVAILABLE
8160 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8161 Default mode, in which sources are checked for consistency only if
8162 they are available.
8163 @end ifset
8164
8165 @item ^-y^/ENABLE_LEAP_SECONDS^
8166 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8167 Enable leap seconds support in @code{Ada.Calendar} and its children.
8168
8169 @item ^-z^/ZERO_MAIN^
8170 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8171 No main subprogram.
8172 @end table
8173
8174 @ifclear vms
8175 @noindent
8176 You may obtain this listing of switches by running @code{gnatbind} with
8177 no arguments.
8178 @end ifclear
8179
8180 @node Consistency-Checking Modes
8181 @subsection Consistency-Checking Modes
8182
8183 @noindent
8184 As described earlier, by default @code{gnatbind} checks
8185 that object files are consistent with one another and are consistent
8186 with any source files it can locate. The following switches control binder
8187 access to sources.
8188
8189 @table @option
8190 @c !sort!
8191 @item ^-s^/READ_SOURCES=ALL^
8192 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8193 Require source files to be present. In this mode, the binder must be
8194 able to locate all source files that are referenced, in order to check
8195 their consistency. In normal mode, if a source file cannot be located it
8196 is simply ignored. If you specify this switch, a missing source
8197 file is an error.
8198
8199 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8200 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8201 Override default wide character encoding for standard Text_IO files.
8202 Normally the default wide character encoding method used for standard
8203 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8204 the main source input (see description of switch
8205 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8206 use of this switch for the binder (which has the same set of
8207 possible arguments) overrides this default as specified.
8208
8209 @item ^-x^/READ_SOURCES=NONE^
8210 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8211 Exclude source files. In this mode, the binder only checks that ALI
8212 files are consistent with one another. Source files are not accessed.
8213 The binder runs faster in this mode, and there is still a guarantee that
8214 the resulting program is self-consistent.
8215 If a source file has been edited since it was last compiled, and you
8216 specify this switch, the binder will not detect that the object
8217 file is out of date with respect to the source file. Note that this is the
8218 mode that is automatically used by @command{gnatmake} because in this
8219 case the checking against sources has already been performed by
8220 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8221
8222 @ifset vms
8223 @item /READ_SOURCES=AVAILABLE
8224 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8225 This is the default mode in which source files are checked if they are
8226 available, and ignored if they are not available.
8227 @end ifset
8228 @end table
8229
8230 @node Binder Error Message Control
8231 @subsection Binder Error Message Control
8232
8233 @noindent
8234 The following switches provide control over the generation of error
8235 messages from the binder:
8236
8237 @table @option
8238 @c !sort!
8239 @item ^-v^/REPORT_ERRORS=VERBOSE^
8240 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8241 Verbose mode. In the normal mode, brief error messages are generated to
8242 @file{stderr}. If this switch is present, a header is written
8243 to @file{stdout} and any error messages are directed to @file{stdout}.
8244 All that is written to @file{stderr} is a brief summary message.
8245
8246 @item ^-b^/REPORT_ERRORS=BRIEF^
8247 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8248 Generate brief error messages to @file{stderr} even if verbose mode is
8249 specified. This is relevant only when used with the
8250 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8251
8252 @ifclear vms
8253 @item -m@var{n}
8254 @cindex @option{-m} (@code{gnatbind})
8255 Limits the number of error messages to @var{n}, a decimal integer in the
8256 range 1-999. The binder terminates immediately if this limit is reached.
8257
8258 @item -M@var{xxx}
8259 @cindex @option{-M} (@code{gnatbind})
8260 Renames the generated main program from @code{main} to @code{xxx}.
8261 This is useful in the case of some cross-building environments, where
8262 the actual main program is separate from the one generated
8263 by @code{gnatbind}.
8264 @end ifclear
8265
8266 @item ^-ws^/WARNINGS=SUPPRESS^
8267 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8268 @cindex Warnings
8269 Suppress all warning messages.
8270
8271 @item ^-we^/WARNINGS=ERROR^
8272 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8273 Treat any warning messages as fatal errors.
8274
8275 @ifset vms
8276 @item /WARNINGS=NORMAL
8277 Standard mode with warnings generated, but warnings do not get treated
8278 as errors.
8279 @end ifset
8280
8281 @item ^-t^/NOTIME_STAMP_CHECK^
8282 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8283 @cindex Time stamp checks, in binder
8284 @cindex Binder consistency checks
8285 @cindex Consistency checks, in binder
8286 The binder performs a number of consistency checks including:
8287
8288 @itemize @bullet
8289 @item
8290 Check that time stamps of a given source unit are consistent
8291 @item
8292 Check that checksums of a given source unit are consistent
8293 @item
8294 Check that consistent versions of @code{GNAT} were used for compilation
8295 @item
8296 Check consistency of configuration pragmas as required
8297 @end itemize
8298
8299 @noindent
8300 Normally failure of such checks, in accordance with the consistency
8301 requirements of the Ada Reference Manual, causes error messages to be
8302 generated which abort the binder and prevent the output of a binder
8303 file and subsequent link to obtain an executable.
8304
8305 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8306 into warnings, so that
8307 binding and linking can continue to completion even in the presence of such
8308 errors. The result may be a failed link (due to missing symbols), or a
8309 non-functional executable which has undefined semantics.
8310 @emph{This means that
8311 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8312 with extreme care.}
8313 @end table
8314
8315 @node Elaboration Control
8316 @subsection Elaboration Control
8317
8318 @noindent
8319 The following switches provide additional control over the elaboration
8320 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8321
8322 @table @option
8323 @item ^-p^/PESSIMISTIC_ELABORATION^
8324 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8325 Normally the binder attempts to choose an elaboration order that is
8326 likely to minimize the likelihood of an elaboration order error resulting
8327 in raising a @code{Program_Error} exception. This switch reverses the
8328 action of the binder, and requests that it deliberately choose an order
8329 that is likely to maximize the likelihood of an elaboration error.
8330 This is useful in ensuring portability and avoiding dependence on
8331 accidental fortuitous elaboration ordering.
8332
8333 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8334 switch if dynamic
8335 elaboration checking is used (@option{-gnatE} switch used for compilation).
8336 This is because in the default static elaboration mode, all necessary
8337 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8338 These implicit pragmas are still respected by the binder in
8339 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8340 safe elaboration order is assured.
8341 @end table
8342
8343 @node Output Control
8344 @subsection Output Control
8345
8346 @noindent
8347 The following switches allow additional control over the output
8348 generated by the binder.
8349
8350 @table @option
8351 @c !sort!
8352
8353 @item ^-A^/BIND_FILE=ADA^
8354 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8355 Generate binder program in Ada (default). The binder program is named
8356 @file{b~@var{mainprog}.adb} by default. This can be changed with
8357 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8358
8359 @item ^-c^/NOOUTPUT^
8360 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8361 Check only. Do not generate the binder output file. In this mode the
8362 binder performs all error checks but does not generate an output file.
8363
8364 @item ^-C^/BIND_FILE=C^
8365 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8366 Generate binder program in C. The binder program is named
8367 @file{b_@var{mainprog}.c}.
8368 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8369 option.
8370
8371 @item ^-e^/ELABORATION_DEPENDENCIES^
8372 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8373 Output complete list of elaboration-order dependencies, showing the
8374 reason for each dependency. This output can be rather extensive but may
8375 be useful in diagnosing problems with elaboration order. The output is
8376 written to @file{stdout}.
8377
8378 @item ^-h^/HELP^
8379 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8380 Output usage information. The output is written to @file{stdout}.
8381
8382 @item ^-K^/LINKER_OPTION_LIST^
8383 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8384 Output linker options to @file{stdout}. Includes library search paths,
8385 contents of pragmas Ident and Linker_Options, and libraries added
8386 by @code{gnatbind}.
8387
8388 @item ^-l^/ORDER_OF_ELABORATION^
8389 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8390 Output chosen elaboration order. The output is written to @file{stdout}.
8391
8392 @item ^-O^/OBJECT_LIST^
8393 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8394 Output full names of all the object files that must be linked to provide
8395 the Ada component of the program. The output is written to @file{stdout}.
8396 This list includes the files explicitly supplied and referenced by the user
8397 as well as implicitly referenced run-time unit files. The latter are
8398 omitted if the corresponding units reside in shared libraries. The
8399 directory names for the run-time units depend on the system configuration.
8400
8401 @item ^-o ^/OUTPUT=^@var{file}
8402 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8403 Set name of output file to @var{file} instead of the normal
8404 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8405 binder generated body filename. In C mode you would normally give
8406 @var{file} an extension of @file{.c} because it will be a C source program.
8407 Note that if this option is used, then linking must be done manually.
8408 It is not possible to use gnatlink in this case, since it cannot locate
8409 the binder file.
8410
8411 @item ^-r^/RESTRICTION_LIST^
8412 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8413 Generate list of @code{pragma Restrictions} that could be applied to
8414 the current unit. This is useful for code audit purposes, and also may
8415 be used to improve code generation in some cases.
8416
8417 @end table
8418
8419 @node Binding with Non-Ada Main Programs
8420 @subsection Binding with Non-Ada Main Programs
8421
8422 @noindent
8423 In our description so far we have assumed that the main
8424 program is in Ada, and that the task of the binder is to generate a
8425 corresponding function @code{main} that invokes this Ada main
8426 program. GNAT also supports the building of executable programs where
8427 the main program is not in Ada, but some of the called routines are
8428 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8429 The following switch is used in this situation:
8430
8431 @table @option
8432 @item ^-n^/NOMAIN^
8433 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8434 No main program. The main program is not in Ada.
8435 @end table
8436
8437 @noindent
8438 In this case, most of the functions of the binder are still required,
8439 but instead of generating a main program, the binder generates a file
8440 containing the following callable routines:
8441
8442 @table @code
8443 @item adainit
8444 @findex adainit
8445 You must call this routine to initialize the Ada part of the program by
8446 calling the necessary elaboration routines. A call to @code{adainit} is
8447 required before the first call to an Ada subprogram.
8448
8449 Note that it is assumed that the basic execution environment must be setup
8450 to be appropriate for Ada execution at the point where the first Ada
8451 subprogram is called. In particular, if the Ada code will do any
8452 floating-point operations, then the FPU must be setup in an appropriate
8453 manner. For the case of the x86, for example, full precision mode is
8454 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8455 that the FPU is in the right state.
8456
8457 @item adafinal
8458 @findex adafinal
8459 You must call this routine to perform any library-level finalization
8460 required by the Ada subprograms. A call to @code{adafinal} is required
8461 after the last call to an Ada subprogram, and before the program
8462 terminates.
8463 @end table
8464
8465 @noindent
8466 If the @option{^-n^/NOMAIN^} switch
8467 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8468 @cindex Binder, multiple input files
8469 is given, more than one ALI file may appear on
8470 the command line for @code{gnatbind}. The normal @dfn{closure}
8471 calculation is performed for each of the specified units. Calculating
8472 the closure means finding out the set of units involved by tracing
8473 @code{with} references. The reason it is necessary to be able to
8474 specify more than one ALI file is that a given program may invoke two or
8475 more quite separate groups of Ada units.
8476
8477 The binder takes the name of its output file from the last specified ALI
8478 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8479 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8480 The output is an Ada unit in source form that can
8481 be compiled with GNAT unless the -C switch is used in which case the
8482 output is a C source file, which must be compiled using the C compiler.
8483 This compilation occurs automatically as part of the @command{gnatlink}
8484 processing.
8485
8486 Currently the GNAT run time requires a FPU using 80 bits mode
8487 precision. Under targets where this is not the default it is required to
8488 call GNAT.Float_Control.Reset before using floating point numbers (this
8489 include float computation, float input and output) in the Ada code. A
8490 side effect is that this could be the wrong mode for the foreign code
8491 where floating point computation could be broken after this call.
8492
8493 @node Binding Programs with No Main Subprogram
8494 @subsection Binding Programs with No Main Subprogram
8495
8496 @noindent
8497 It is possible to have an Ada program which does not have a main
8498 subprogram. This program will call the elaboration routines of all the
8499 packages, then the finalization routines.
8500
8501 The following switch is used to bind programs organized in this manner:
8502
8503 @table @option
8504 @item ^-z^/ZERO_MAIN^
8505 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8506 Normally the binder checks that the unit name given on the command line
8507 corresponds to a suitable main subprogram. When this switch is used,
8508 a list of ALI files can be given, and the execution of the program
8509 consists of elaboration of these units in an appropriate order. Note
8510 that the default wide character encoding method for standard Text_IO
8511 files is always set to Brackets if this switch is set (you can use
8512 the binder switch
8513 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8514 @end table
8515
8516 @node Command-Line Access
8517 @section Command-Line Access
8518
8519 @noindent
8520 The package @code{Ada.Command_Line} provides access to the command-line
8521 arguments and program name. In order for this interface to operate
8522 correctly, the two variables
8523
8524 @smallexample
8525 @group
8526 int gnat_argc;
8527 char **gnat_argv;
8528 @end group
8529 @end smallexample
8530
8531 @noindent
8532 @findex gnat_argv
8533 @findex gnat_argc
8534 are declared in one of the GNAT library routines. These variables must
8535 be set from the actual @code{argc} and @code{argv} values passed to the
8536 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8537 generates the C main program to automatically set these variables.
8538 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8539 set these variables. If they are not set, the procedures in
8540 @code{Ada.Command_Line} will not be available, and any attempt to use
8541 them will raise @code{Constraint_Error}. If command line access is
8542 required, your main program must set @code{gnat_argc} and
8543 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8544 it.
8545
8546 @node Search Paths for gnatbind
8547 @section Search Paths for @code{gnatbind}
8548
8549 @noindent
8550 The binder takes the name of an ALI file as its argument and needs to
8551 locate source files as well as other ALI files to verify object consistency.
8552
8553 For source files, it follows exactly the same search rules as @command{gcc}
8554 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8555 directories searched are:
8556
8557 @enumerate
8558 @item
8559 The directory containing the ALI file named in the command line, unless
8560 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8561
8562 @item
8563 All directories specified by @option{^-I^/SEARCH^}
8564 switches on the @code{gnatbind}
8565 command line, in the order given.
8566
8567 @item
8568 @findex ADA_PRJ_OBJECTS_FILE
8569 Each of the directories listed in the text file whose name is given
8570 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8571
8572 @noindent
8573 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8574 driver when project files are used. It should not normally be set
8575 by other means.
8576
8577 @item
8578 @findex ADA_OBJECTS_PATH
8579 Each of the directories listed in the value of the
8580 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8581 @ifset unw
8582 Construct this value
8583 exactly as the @env{PATH} environment variable: a list of directory
8584 names separated by colons (semicolons when working with the NT version
8585 of GNAT).
8586 @end ifset
8587 @ifset vms
8588 Normally, define this value as a logical name containing a comma separated
8589 list of directory names.
8590
8591 This variable can also be defined by means of an environment string
8592 (an argument to the HP C exec* set of functions).
8593
8594 Logical Name:
8595 @smallexample
8596 DEFINE ANOTHER_PATH FOO:[BAG]
8597 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8598 @end smallexample
8599
8600 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8601 first, followed by the standard Ada
8602 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8603 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8604 (Text_IO, Sequential_IO, etc)
8605 instead of the standard Ada packages. Thus, in order to get the standard Ada
8606 packages by default, ADA_OBJECTS_PATH must be redefined.
8607 @end ifset
8608
8609 @item
8610 The content of the @file{ada_object_path} file which is part of the GNAT
8611 installation tree and is used to store standard libraries such as the
8612 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8613 specified.
8614 @ifclear vms
8615 @ref{Installing a library}
8616 @end ifclear
8617 @end enumerate
8618
8619 @noindent
8620 In the binder the switch @option{^-I^/SEARCH^}
8621 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8622 is used to specify both source and
8623 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8624 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8625 instead if you want to specify
8626 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8627 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8628 if you want to specify library paths
8629 only. This means that for the binder
8630 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8631 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8632 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8633 The binder generates the bind file (a C language source file) in the
8634 current working directory.
8635
8636 @findex Ada
8637 @findex System
8638 @findex Interfaces
8639 @findex GNAT
8640 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8641 children make up the GNAT Run-Time Library, together with the package
8642 GNAT and its children, which contain a set of useful additional
8643 library functions provided by GNAT. The sources for these units are
8644 needed by the compiler and are kept together in one directory. The ALI
8645 files and object files generated by compiling the RTL are needed by the
8646 binder and the linker and are kept together in one directory, typically
8647 different from the directory containing the sources. In a normal
8648 installation, you need not specify these directory names when compiling
8649 or binding. Either the environment variables or the built-in defaults
8650 cause these files to be found.
8651
8652 Besides simplifying access to the RTL, a major use of search paths is
8653 in compiling sources from multiple directories. This can make
8654 development environments much more flexible.
8655
8656 @node Examples of gnatbind Usage
8657 @section Examples of @code{gnatbind} Usage
8658
8659 @noindent
8660 This section contains a number of examples of using the GNAT binding
8661 utility @code{gnatbind}.
8662
8663 @table @code
8664 @item gnatbind hello
8665 The main program @code{Hello} (source program in @file{hello.adb}) is
8666 bound using the standard switch settings. The generated main program is
8667 @file{b~hello.adb}. This is the normal, default use of the binder.
8668
8669 @ifclear vms
8670 @item gnatbind hello -o mainprog.adb
8671 @end ifclear
8672 @ifset vms
8673 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8674 @end ifset
8675 The main program @code{Hello} (source program in @file{hello.adb}) is
8676 bound using the standard switch settings. The generated main program is
8677 @file{mainprog.adb} with the associated spec in
8678 @file{mainprog.ads}. Note that you must specify the body here not the
8679 spec, in the case where the output is in Ada. Note that if this option
8680 is used, then linking must be done manually, since gnatlink will not
8681 be able to find the generated file.
8682
8683 @ifclear vms
8684 @item gnatbind main -C -o mainprog.c -x
8685 @end ifclear
8686 @ifset vms
8687 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8688 @end ifset
8689 The main program @code{Main} (source program in
8690 @file{main.adb}) is bound, excluding source files from the
8691 consistency checking, generating
8692 the file @file{mainprog.c}.
8693
8694 @ifclear vms
8695 @item gnatbind -x main_program -C -o mainprog.c
8696 This command is exactly the same as the previous example. Switches may
8697 appear anywhere in the command line, and single letter switches may be
8698 combined into a single switch.
8699 @end ifclear
8700
8701 @ifclear vms
8702 @item gnatbind -n math dbase -C -o ada-control.c
8703 @end ifclear
8704 @ifset vms
8705 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8706 @end ifset
8707 The main program is in a language other than Ada, but calls to
8708 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8709 to @code{gnatbind} generates the file @file{ada-control.c} containing
8710 the @code{adainit} and @code{adafinal} routines to be called before and
8711 after accessing the Ada units.
8712 @end table
8713
8714 @c ------------------------------------
8715 @node Linking Using gnatlink
8716 @chapter Linking Using @command{gnatlink}
8717 @c ------------------------------------
8718 @findex gnatlink
8719
8720 @noindent
8721 This chapter discusses @command{gnatlink}, a tool that links
8722 an Ada program and builds an executable file. This utility
8723 invokes the system linker ^(via the @command{gcc} command)^^
8724 with a correct list of object files and library references.
8725 @command{gnatlink} automatically determines the list of files and
8726 references for the Ada part of a program. It uses the binder file
8727 generated by the @command{gnatbind} to determine this list.
8728
8729 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8730 driver (see @ref{The GNAT Driver and Project Files}).
8731
8732 @menu
8733 * Running gnatlink::
8734 * Switches for gnatlink::
8735 @end menu
8736
8737 @node Running gnatlink
8738 @section Running @command{gnatlink}
8739
8740 @noindent
8741 The form of the @command{gnatlink} command is
8742
8743 @smallexample
8744 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8745 @ovar{non-Ada objects} @ovar{linker options}
8746 @end smallexample
8747
8748 @noindent
8749 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8750 non-Ada objects
8751 or linker options) may be in any order, provided that no non-Ada object may
8752 be mistaken for a main @file{ALI} file.
8753 Any file name @file{F} without the @file{.ali}
8754 extension will be taken as the main @file{ALI} file if a file exists
8755 whose name is the concatenation of @file{F} and @file{.ali}.
8756
8757 @noindent
8758 @file{@var{mainprog}.ali} references the ALI file of the main program.
8759 The @file{.ali} extension of this file can be omitted. From this
8760 reference, @command{gnatlink} locates the corresponding binder file
8761 @file{b~@var{mainprog}.adb} and, using the information in this file along
8762 with the list of non-Ada objects and linker options, constructs a
8763 linker command file to create the executable.
8764
8765 The arguments other than the @command{gnatlink} switches and the main
8766 @file{ALI} file are passed to the linker uninterpreted.
8767 They typically include the names of
8768 object files for units written in other languages than Ada and any library
8769 references required to resolve references in any of these foreign language
8770 units, or in @code{Import} pragmas in any Ada units.
8771
8772 @var{linker options} is an optional list of linker specific
8773 switches.
8774 The default linker called by gnatlink is @command{gcc} which in
8775 turn calls the appropriate system linker.
8776 Standard options for the linker such as @option{-lmy_lib} or
8777 @option{-Ldir} can be added as is.
8778 For options that are not recognized by
8779 @command{gcc} as linker options, use the @command{gcc} switches
8780 @option{-Xlinker} or @option{-Wl,}.
8781 Refer to the GCC documentation for
8782 details. Here is an example showing how to generate a linker map:
8783
8784 @smallexample
8785 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8786 @end smallexample
8787
8788 Using @var{linker options} it is possible to set the program stack and
8789 heap size.
8790 @ifset unw
8791 See @ref{Setting Stack Size from gnatlink} and
8792 @ref{Setting Heap Size from gnatlink}.
8793 @end ifset
8794
8795 @command{gnatlink} determines the list of objects required by the Ada
8796 program and prepends them to the list of objects passed to the linker.
8797 @command{gnatlink} also gathers any arguments set by the use of
8798 @code{pragma Linker_Options} and adds them to the list of arguments
8799 presented to the linker.
8800
8801 @ifset vms
8802 @command{gnatlink} accepts the following types of extra files on the command
8803 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8804 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8805 handled according to their extension.
8806 @end ifset
8807
8808 @node Switches for gnatlink
8809 @section Switches for @command{gnatlink}
8810
8811 @noindent
8812 The following switches are available with the @command{gnatlink} utility:
8813
8814 @table @option
8815 @c !sort!
8816
8817 @item --version
8818 @cindex @option{--version} @command{gnatlink}
8819 Display Copyright and version, then exit disregarding all other options.
8820
8821 @item --help
8822 @cindex @option{--help} @command{gnatlink}
8823 If @option{--version} was not used, display usage, then exit disregarding
8824 all other options.
8825
8826 @item ^-A^/BIND_FILE=ADA^
8827 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8828 The binder has generated code in Ada. This is the default.
8829
8830 @item ^-C^/BIND_FILE=C^
8831 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8832 If instead of generating a file in Ada, the binder has generated one in
8833 C, then the linker needs to know about it. Use this switch to signal
8834 to @command{gnatlink} that the binder has generated C code rather than
8835 Ada code.
8836
8837 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8838 @cindex Command line length
8839 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8840 On some targets, the command line length is limited, and @command{gnatlink}
8841 will generate a separate file for the linker if the list of object files
8842 is too long.
8843 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8844 to be generated even if
8845 the limit is not exceeded. This is useful in some cases to deal with
8846 special situations where the command line length is exceeded.
8847
8848 @item ^-g^/DEBUG^
8849 @cindex Debugging information, including
8850 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8851 The option to include debugging information causes the Ada bind file (in
8852 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8853 @option{^-g^/DEBUG^}.
8854 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8855 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8856 Without @option{^-g^/DEBUG^}, the binder removes these files by
8857 default. The same procedure apply if a C bind file was generated using
8858 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8859 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8860
8861 @item ^-n^/NOCOMPILE^
8862 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8863 Do not compile the file generated by the binder. This may be used when
8864 a link is rerun with different options, but there is no need to recompile
8865 the binder file.
8866
8867 @item ^-v^/VERBOSE^
8868 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8869 Causes additional information to be output, including a full list of the
8870 included object files. This switch option is most useful when you want
8871 to see what set of object files are being used in the link step.
8872
8873 @item ^-v -v^/VERBOSE/VERBOSE^
8874 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8875 Very verbose mode. Requests that the compiler operate in verbose mode when
8876 it compiles the binder file, and that the system linker run in verbose mode.
8877
8878 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8879 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8880 @var{exec-name} specifies an alternate name for the generated
8881 executable program. If this switch is omitted, the executable has the same
8882 name as the main unit. For example, @code{gnatlink try.ali} creates
8883 an executable called @file{^try^TRY.EXE^}.
8884
8885 @ifclear vms
8886 @item -b @var{target}
8887 @cindex @option{-b} (@command{gnatlink})
8888 Compile your program to run on @var{target}, which is the name of a
8889 system configuration. You must have a GNAT cross-compiler built if
8890 @var{target} is not the same as your host system.
8891
8892 @item -B@var{dir}
8893 @cindex @option{-B} (@command{gnatlink})
8894 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8895 from @var{dir} instead of the default location. Only use this switch
8896 when multiple versions of the GNAT compiler are available.
8897 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8898 for further details. You would normally use the @option{-b} or
8899 @option{-V} switch instead.
8900
8901 @item --GCC=@var{compiler_name}
8902 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8903 Program used for compiling the binder file. The default is
8904 @command{gcc}. You need to use quotes around @var{compiler_name} if
8905 @code{compiler_name} contains spaces or other separator characters.
8906 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8907 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8908 inserted after your command name. Thus in the above example the compiler
8909 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8910 A limitation of this syntax is that the name and path name of the executable
8911 itself must not include any embedded spaces. If the compiler executable is
8912 different from the default one (gcc or <prefix>-gcc), then the back-end
8913 switches in the ALI file are not used to compile the binder generated source.
8914 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8915 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8916 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8917 is taken into account. However, all the additional switches are also taken
8918 into account. Thus,
8919 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8920 @option{--GCC="bar -x -y -z -t"}.
8921
8922 @item --LINK=@var{name}
8923 @cindex @option{--LINK=} (@command{gnatlink})
8924 @var{name} is the name of the linker to be invoked. This is especially
8925 useful in mixed language programs since languages such as C++ require
8926 their own linker to be used. When this switch is omitted, the default
8927 name for the linker is @command{gcc}. When this switch is used, the
8928 specified linker is called instead of @command{gcc} with exactly the same
8929 parameters that would have been passed to @command{gcc} so if the desired
8930 linker requires different parameters it is necessary to use a wrapper
8931 script that massages the parameters before invoking the real linker. It
8932 may be useful to control the exact invocation by using the verbose
8933 switch.
8934
8935 @end ifclear
8936
8937 @ifset vms
8938 @item /DEBUG=TRACEBACK
8939 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8940 This qualifier causes sufficient information to be included in the
8941 executable file to allow a traceback, but does not include the full
8942 symbol information needed by the debugger.
8943
8944 @item /IDENTIFICATION="<string>"
8945 @code{"<string>"} specifies the string to be stored in the image file
8946 identification field in the image header.
8947 It overrides any pragma @code{Ident} specified string.
8948
8949 @item /NOINHIBIT-EXEC
8950 Generate the executable file even if there are linker warnings.
8951
8952 @item /NOSTART_FILES
8953 Don't link in the object file containing the ``main'' transfer address.
8954 Used when linking with a foreign language main program compiled with an
8955 HP compiler.
8956
8957 @item /STATIC
8958 Prefer linking with object libraries over sharable images, even without
8959 /DEBUG.
8960 @end ifset
8961
8962 @end table
8963
8964 @node The GNAT Make Program gnatmake
8965 @chapter The GNAT Make Program @command{gnatmake}
8966 @findex gnatmake
8967
8968 @menu
8969 * Running gnatmake::
8970 * Switches for gnatmake::
8971 * Mode Switches for gnatmake::
8972 * Notes on the Command Line::
8973 * How gnatmake Works::
8974 * Examples of gnatmake Usage::
8975 @end menu
8976 @noindent
8977 A typical development cycle when working on an Ada program consists of
8978 the following steps:
8979
8980 @enumerate
8981 @item
8982 Edit some sources to fix bugs.
8983
8984 @item
8985 Add enhancements.
8986
8987 @item
8988 Compile all sources affected.
8989
8990 @item
8991 Rebind and relink.
8992
8993 @item
8994 Test.
8995 @end enumerate
8996
8997 @noindent
8998 The third step can be tricky, because not only do the modified files
8999 @cindex Dependency rules
9000 have to be compiled, but any files depending on these files must also be
9001 recompiled. The dependency rules in Ada can be quite complex, especially
9002 in the presence of overloading, @code{use} clauses, generics and inlined
9003 subprograms.
9004
9005 @command{gnatmake} automatically takes care of the third and fourth steps
9006 of this process. It determines which sources need to be compiled,
9007 compiles them, and binds and links the resulting object files.
9008
9009 Unlike some other Ada make programs, the dependencies are always
9010 accurately recomputed from the new sources. The source based approach of
9011 the GNAT compilation model makes this possible. This means that if
9012 changes to the source program cause corresponding changes in
9013 dependencies, they will always be tracked exactly correctly by
9014 @command{gnatmake}.
9015
9016 @node Running gnatmake
9017 @section Running @command{gnatmake}
9018
9019 @noindent
9020 The usual form of the @command{gnatmake} command is
9021
9022 @smallexample
9023 $ gnatmake @ovar{switches} @var{file_name}
9024 @ovar{file_names} @ovar{mode_switches}
9025 @end smallexample
9026
9027 @noindent
9028 The only required argument is one @var{file_name}, which specifies
9029 a compilation unit that is a main program. Several @var{file_names} can be
9030 specified: this will result in several executables being built.
9031 If @code{switches} are present, they can be placed before the first
9032 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9033 If @var{mode_switches} are present, they must always be placed after
9034 the last @var{file_name} and all @code{switches}.
9035
9036 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9037 extension may be omitted from the @var{file_name} arguments. However, if
9038 you are using non-standard extensions, then it is required that the
9039 extension be given. A relative or absolute directory path can be
9040 specified in a @var{file_name}, in which case, the input source file will
9041 be searched for in the specified directory only. Otherwise, the input
9042 source file will first be searched in the directory where
9043 @command{gnatmake} was invoked and if it is not found, it will be search on
9044 the source path of the compiler as described in
9045 @ref{Search Paths and the Run-Time Library (RTL)}.
9046
9047 All @command{gnatmake} output (except when you specify
9048 @option{^-M^/DEPENDENCIES_LIST^}) is to
9049 @file{stderr}. The output produced by the
9050 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9051 @file{stdout}.
9052
9053 @node Switches for gnatmake
9054 @section Switches for @command{gnatmake}
9055
9056 @noindent
9057 You may specify any of the following switches to @command{gnatmake}:
9058
9059 @table @option
9060 @c !sort!
9061
9062 @item --version
9063 @cindex @option{--version} @command{gnatmake}
9064 Display Copyright and version, then exit disregarding all other options.
9065
9066 @item --help
9067 @cindex @option{--help} @command{gnatmake}
9068 If @option{--version} was not used, display usage, then exit disregarding
9069 all other options.
9070
9071 @ifclear vms
9072 @item --GCC=@var{compiler_name}
9073 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9074 Program used for compiling. The default is `@command{gcc}'. You need to use
9075 quotes around @var{compiler_name} if @code{compiler_name} contains
9076 spaces or other separator characters. As an example @option{--GCC="foo -x
9077 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9078 compiler. A limitation of this syntax is that the name and path name of
9079 the executable itself must not include any embedded spaces. Note that
9080 switch @option{-c} is always inserted after your command name. Thus in the
9081 above example the compiler command that will be used by @command{gnatmake}
9082 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9083 used, only the last @var{compiler_name} is taken into account. However,
9084 all the additional switches are also taken into account. Thus,
9085 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9086 @option{--GCC="bar -x -y -z -t"}.
9087
9088 @item --GNATBIND=@var{binder_name}
9089 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9090 Program used for binding. The default is `@code{gnatbind}'. You need to
9091 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9092 or other separator characters. As an example @option{--GNATBIND="bar -x
9093 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9094 binder. Binder switches that are normally appended by @command{gnatmake}
9095 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9096 A limitation of this syntax is that the name and path name of the executable
9097 itself must not include any embedded spaces.
9098
9099 @item --GNATLINK=@var{linker_name}
9100 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9101 Program used for linking. The default is `@command{gnatlink}'. You need to
9102 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9103 or other separator characters. As an example @option{--GNATLINK="lan -x
9104 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9105 linker. Linker switches that are normally appended by @command{gnatmake} to
9106 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9107 A limitation of this syntax is that the name and path name of the executable
9108 itself must not include any embedded spaces.
9109
9110 @end ifclear
9111
9112 @item ^-a^/ALL_FILES^
9113 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9114 Consider all files in the make process, even the GNAT internal system
9115 files (for example, the predefined Ada library files), as well as any
9116 locked files. Locked files are files whose ALI file is write-protected.
9117 By default,
9118 @command{gnatmake} does not check these files,
9119 because the assumption is that the GNAT internal files are properly up
9120 to date, and also that any write protected ALI files have been properly
9121 installed. Note that if there is an installation problem, such that one
9122 of these files is not up to date, it will be properly caught by the
9123 binder.
9124 You may have to specify this switch if you are working on GNAT
9125 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9126 in conjunction with @option{^-f^/FORCE_COMPILE^}
9127 if you need to recompile an entire application,
9128 including run-time files, using special configuration pragmas,
9129 such as a @code{Normalize_Scalars} pragma.
9130
9131 By default
9132 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9133 internal files with
9134 @ifclear vms
9135 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9136 @end ifclear
9137 @ifset vms
9138 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9139 @end ifset
9140
9141 @item ^-b^/ACTIONS=BIND^
9142 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9143 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9144 compilation and binding, but no link.
9145 Can be combined with @option{^-l^/ACTIONS=LINK^}
9146 to do binding and linking. When not combined with
9147 @option{^-c^/ACTIONS=COMPILE^}
9148 all the units in the closure of the main program must have been previously
9149 compiled and must be up to date. The root unit specified by @var{file_name}
9150 may be given without extension, with the source extension or, if no GNAT
9151 Project File is specified, with the ALI file extension.
9152
9153 @item ^-c^/ACTIONS=COMPILE^
9154 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9155 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9156 is also specified. Do not perform linking, except if both
9157 @option{^-b^/ACTIONS=BIND^} and
9158 @option{^-l^/ACTIONS=LINK^} are also specified.
9159 If the root unit specified by @var{file_name} is not a main unit, this is the
9160 default. Otherwise @command{gnatmake} will attempt binding and linking
9161 unless all objects are up to date and the executable is more recent than
9162 the objects.
9163
9164 @item ^-C^/MAPPING^
9165 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9166 Use a temporary mapping file. A mapping file is a way to communicate to the
9167 compiler two mappings: from unit names to file names (without any directory
9168 information) and from file names to path names (with full directory
9169 information). These mappings are used by the compiler to short-circuit the path
9170 search. When @command{gnatmake} is invoked with this switch, it will create
9171 a temporary mapping file, initially populated by the project manager,
9172 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9173 Each invocation of the compiler will add the newly accessed sources to the
9174 mapping file. This will improve the source search during the next invocation
9175 of the compiler.
9176
9177 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9178 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9179 Use a specific mapping file. The file, specified as a path name (absolute or
9180 relative) by this switch, should already exist, otherwise the switch is
9181 ineffective. The specified mapping file will be communicated to the compiler.
9182 This switch is not compatible with a project file
9183 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9184 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9185
9186 @item ^-d^/DISPLAY_PROGRESS^
9187 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9188 Display progress for each source, up to date or not, as a single line
9189
9190 @smallexample
9191 completed x out of y (zz%)
9192 @end smallexample
9193
9194 If the file needs to be compiled this is displayed after the invocation of
9195 the compiler. These lines are displayed even in quiet output mode.
9196
9197 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9198 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9199 Put all object files and ALI file in directory @var{dir}.
9200 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9201 and ALI files go in the current working directory.
9202
9203 This switch cannot be used when using a project file.
9204
9205 @ifclear vms
9206 @item -eL
9207 @cindex @option{-eL} (@command{gnatmake})
9208 Follow all symbolic links when processing project files.
9209 @end ifclear
9210
9211 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9212 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9213 Output the commands for the compiler, the binder and the linker
9214 on ^standard output^SYS$OUTPUT^,
9215 instead of ^standard error^SYS$ERROR^.
9216
9217 @item ^-f^/FORCE_COMPILE^
9218 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9219 Force recompilations. Recompile all sources, even though some object
9220 files may be up to date, but don't recompile predefined or GNAT internal
9221 files or locked files (files with a write-protected ALI file),
9222 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9223
9224 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9225 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9226 When using project files, if some errors or warnings are detected during
9227 parsing and verbose mode is not in effect (no use of switch
9228 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9229 file, rather than its simple file name.
9230
9231 @item ^-g^/DEBUG^
9232 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9233 Enable debugging. This switch is simply passed to the compiler and to the
9234 linker.
9235
9236 @item ^-i^/IN_PLACE^
9237 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9238 In normal mode, @command{gnatmake} compiles all object files and ALI files
9239 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9240 then instead object files and ALI files that already exist are overwritten
9241 in place. This means that once a large project is organized into separate
9242 directories in the desired manner, then @command{gnatmake} will automatically
9243 maintain and update this organization. If no ALI files are found on the
9244 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9245 the new object and ALI files are created in the
9246 directory containing the source being compiled. If another organization
9247 is desired, where objects and sources are kept in different directories,
9248 a useful technique is to create dummy ALI files in the desired directories.
9249 When detecting such a dummy file, @command{gnatmake} will be forced to
9250 recompile the corresponding source file, and it will be put the resulting
9251 object and ALI files in the directory where it found the dummy file.
9252
9253 @item ^-j^/PROCESSES=^@var{n}
9254 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9255 @cindex Parallel make
9256 Use @var{n} processes to carry out the (re)compilations. On a
9257 multiprocessor machine compilations will occur in parallel. In the
9258 event of compilation errors, messages from various compilations might
9259 get interspersed (but @command{gnatmake} will give you the full ordered
9260 list of failing compiles at the end). If this is problematic, rerun
9261 the make process with n set to 1 to get a clean list of messages.
9262
9263 @item ^-k^/CONTINUE_ON_ERROR^
9264 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9265 Keep going. Continue as much as possible after a compilation error. To
9266 ease the programmer's task in case of compilation errors, the list of
9267 sources for which the compile fails is given when @command{gnatmake}
9268 terminates.
9269
9270 If @command{gnatmake} is invoked with several @file{file_names} and with this
9271 switch, if there are compilation errors when building an executable,
9272 @command{gnatmake} will not attempt to build the following executables.
9273
9274 @item ^-l^/ACTIONS=LINK^
9275 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9276 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9277 and linking. Linking will not be performed if combined with
9278 @option{^-c^/ACTIONS=COMPILE^}
9279 but not with @option{^-b^/ACTIONS=BIND^}.
9280 When not combined with @option{^-b^/ACTIONS=BIND^}
9281 all the units in the closure of the main program must have been previously
9282 compiled and must be up to date, and the main program needs to have been bound.
9283 The root unit specified by @var{file_name}
9284 may be given without extension, with the source extension or, if no GNAT
9285 Project File is specified, with the ALI file extension.
9286
9287 @item ^-m^/MINIMAL_RECOMPILATION^
9288 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9289 Specify that the minimum necessary amount of recompilations
9290 be performed. In this mode @command{gnatmake} ignores time
9291 stamp differences when the only
9292 modifications to a source file consist in adding/removing comments,
9293 empty lines, spaces or tabs. This means that if you have changed the
9294 comments in a source file or have simply reformatted it, using this
9295 switch will tell @command{gnatmake} not to recompile files that depend on it
9296 (provided other sources on which these files depend have undergone no
9297 semantic modifications). Note that the debugging information may be
9298 out of date with respect to the sources if the @option{-m} switch causes
9299 a compilation to be switched, so the use of this switch represents a
9300 trade-off between compilation time and accurate debugging information.
9301
9302 @item ^-M^/DEPENDENCIES_LIST^
9303 @cindex Dependencies, producing list
9304 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9305 Check if all objects are up to date. If they are, output the object
9306 dependences to @file{stdout} in a form that can be directly exploited in
9307 a @file{Makefile}. By default, each source file is prefixed with its
9308 (relative or absolute) directory name. This name is whatever you
9309 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9310 and @option{^-I^/SEARCH^} switches. If you use
9311 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9312 @option{^-q^/QUIET^}
9313 (see below), only the source file names,
9314 without relative paths, are output. If you just specify the
9315 @option{^-M^/DEPENDENCIES_LIST^}
9316 switch, dependencies of the GNAT internal system files are omitted. This
9317 is typically what you want. If you also specify
9318 the @option{^-a^/ALL_FILES^} switch,
9319 dependencies of the GNAT internal files are also listed. Note that
9320 dependencies of the objects in external Ada libraries (see switch
9321 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9322 are never reported.
9323
9324 @item ^-n^/DO_OBJECT_CHECK^
9325 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9326 Don't compile, bind, or link. Checks if all objects are up to date.
9327 If they are not, the full name of the first file that needs to be
9328 recompiled is printed.
9329 Repeated use of this option, followed by compiling the indicated source
9330 file, will eventually result in recompiling all required units.
9331
9332 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9333 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9334 Output executable name. The name of the final executable program will be
9335 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9336 name for the executable will be the name of the input file in appropriate form
9337 for an executable file on the host system.
9338
9339 This switch cannot be used when invoking @command{gnatmake} with several
9340 @file{file_names}.
9341
9342 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9343 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9344 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9345 automatically missing object directories, library directories and exec
9346 directories.
9347
9348 @item ^-P^/PROJECT_FILE=^@var{project}
9349 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9350 Use project file @var{project}. Only one such switch can be used.
9351 @xref{gnatmake and Project Files}.
9352
9353 @item ^-q^/QUIET^
9354 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9355 Quiet. When this flag is not set, the commands carried out by
9356 @command{gnatmake} are displayed.
9357
9358 @item ^-s^/SWITCH_CHECK/^
9359 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9360 Recompile if compiler switches have changed since last compilation.
9361 All compiler switches but -I and -o are taken into account in the
9362 following way:
9363 orders between different ``first letter'' switches are ignored, but
9364 orders between same switches are taken into account. For example,
9365 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9366 is equivalent to @option{-O -g}.
9367
9368 This switch is recommended when Integrated Preprocessing is used.
9369
9370 @item ^-u^/UNIQUE^
9371 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9372 Unique. Recompile at most the main files. It implies -c. Combined with
9373 -f, it is equivalent to calling the compiler directly. Note that using
9374 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9375 (@pxref{Project Files and Main Subprograms}).
9376
9377 @item ^-U^/ALL_PROJECTS^
9378 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9379 When used without a project file or with one or several mains on the command
9380 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9381 on the command line, all sources of all project files are checked and compiled
9382 if not up to date, and libraries are rebuilt, if necessary.
9383
9384 @item ^-v^/REASONS^
9385 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9386 Verbose. Display the reason for all recompilations @command{gnatmake}
9387 decides are necessary, with the highest verbosity level.
9388
9389 @item ^-vl^/LOW_VERBOSITY^
9390 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9391 Verbosity level Low. Display fewer lines than in verbosity Medium.
9392
9393 @item ^-vm^/MEDIUM_VERBOSITY^
9394 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9395 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9396
9397 @item ^-vh^/HIGH_VERBOSITY^
9398 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9399 Verbosity level High. Equivalent to ^-v^/REASONS^.
9400
9401 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9402 Indicate the verbosity of the parsing of GNAT project files.
9403 @xref{Switches Related to Project Files}.
9404
9405 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9406 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9407 Indicate that sources that are not part of any Project File may be compiled.
9408 Normally, when using Project Files, only sources that are part of a Project
9409 File may be compile. When this switch is used, a source outside of all Project
9410 Files may be compiled. The ALI file and the object file will be put in the
9411 object directory of the main Project. The compilation switches used will only
9412 be those specified on the command line. Even when
9413 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9414 command line need to be sources of a project file.
9415
9416 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9417 Indicate that external variable @var{name} has the value @var{value}.
9418 The Project Manager will use this value for occurrences of
9419 @code{external(name)} when parsing the project file.
9420 @xref{Switches Related to Project Files}.
9421
9422 @item ^-z^/NOMAIN^
9423 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9424 No main subprogram. Bind and link the program even if the unit name
9425 given on the command line is a package name. The resulting executable
9426 will execute the elaboration routines of the package and its closure,
9427 then the finalization routines.
9428
9429 @end table
9430
9431 @table @asis
9432 @item @command{gcc} @asis{switches}
9433 @ifclear vms
9434 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9435 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9436 @end ifclear
9437 @ifset vms
9438 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9439 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9440 automatically treated as a compiler switch, and passed on to all
9441 compilations that are carried out.
9442 @end ifset
9443 @end table
9444
9445 @noindent
9446 Source and library search path switches:
9447
9448 @table @option
9449 @c !sort!
9450 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9451 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9452 When looking for source files also look in directory @var{dir}.
9453 The order in which source files search is undertaken is
9454 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9455
9456 @item ^-aL^/SKIP_MISSING=^@var{dir}
9457 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9458 Consider @var{dir} as being an externally provided Ada library.
9459 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9460 files have been located in directory @var{dir}. This allows you to have
9461 missing bodies for the units in @var{dir} and to ignore out of date bodies
9462 for the same units. You still need to specify
9463 the location of the specs for these units by using the switches
9464 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9465 or @option{^-I^/SEARCH=^@var{dir}}.
9466 Note: this switch is provided for compatibility with previous versions
9467 of @command{gnatmake}. The easier method of causing standard libraries
9468 to be excluded from consideration is to write-protect the corresponding
9469 ALI files.
9470
9471 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9472 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9473 When searching for library and object files, look in directory
9474 @var{dir}. The order in which library files are searched is described in
9475 @ref{Search Paths for gnatbind}.
9476
9477 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9478 @cindex Search paths, for @command{gnatmake}
9479 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9480 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9481 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9482
9483 @item ^-I^/SEARCH=^@var{dir}
9484 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9485 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9486 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9487
9488 @item ^-I-^/NOCURRENT_DIRECTORY^
9489 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9490 @cindex Source files, suppressing search
9491 Do not look for source files in the directory containing the source
9492 file named in the command line.
9493 Do not look for ALI or object files in the directory
9494 where @command{gnatmake} was invoked.
9495
9496 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9497 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9498 @cindex Linker libraries
9499 Add directory @var{dir} to the list of directories in which the linker
9500 will search for libraries. This is equivalent to
9501 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9502 @ifclear vms
9503 Furthermore, under Windows, the sources pointed to by the libraries path
9504 set in the registry are not searched for.
9505 @end ifclear
9506
9507 @item -nostdinc
9508 @cindex @option{-nostdinc} (@command{gnatmake})
9509 Do not look for source files in the system default directory.
9510
9511 @item -nostdlib
9512 @cindex @option{-nostdlib} (@command{gnatmake})
9513 Do not look for library files in the system default directory.
9514
9515 @item --RTS=@var{rts-path}
9516 @cindex @option{--RTS} (@command{gnatmake})
9517 Specifies the default location of the runtime library. GNAT looks for the
9518 runtime
9519 in the following directories, and stops as soon as a valid runtime is found
9520 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9521 @file{ada_object_path} present):
9522
9523 @itemize @bullet
9524 @item <current directory>/$rts_path
9525
9526 @item <default-search-dir>/$rts_path
9527
9528 @item <default-search-dir>/rts-$rts_path
9529 @end itemize
9530
9531 @noindent
9532 The selected path is handled like a normal RTS path.
9533
9534 @end table
9535
9536 @node Mode Switches for gnatmake
9537 @section Mode Switches for @command{gnatmake}
9538
9539 @noindent
9540 The mode switches (referred to as @code{mode_switches}) allow the
9541 inclusion of switches that are to be passed to the compiler itself, the
9542 binder or the linker. The effect of a mode switch is to cause all
9543 subsequent switches up to the end of the switch list, or up to the next
9544 mode switch, to be interpreted as switches to be passed on to the
9545 designated component of GNAT.
9546
9547 @table @option
9548 @c !sort!
9549 @item -cargs @var{switches}
9550 @cindex @option{-cargs} (@command{gnatmake})
9551 Compiler switches. Here @var{switches} is a list of switches
9552 that are valid switches for @command{gcc}. They will be passed on to
9553 all compile steps performed by @command{gnatmake}.
9554
9555 @item -bargs @var{switches}
9556 @cindex @option{-bargs} (@command{gnatmake})
9557 Binder switches. Here @var{switches} is a list of switches
9558 that are valid switches for @code{gnatbind}. They will be passed on to
9559 all bind steps performed by @command{gnatmake}.
9560
9561 @item -largs @var{switches}
9562 @cindex @option{-largs} (@command{gnatmake})
9563 Linker switches. Here @var{switches} is a list of switches
9564 that are valid switches for @command{gnatlink}. They will be passed on to
9565 all link steps performed by @command{gnatmake}.
9566
9567 @item -margs @var{switches}
9568 @cindex @option{-margs} (@command{gnatmake})
9569 Make switches. The switches are directly interpreted by @command{gnatmake},
9570 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9571 or @option{-largs}.
9572 @end table
9573
9574 @node Notes on the Command Line
9575 @section Notes on the Command Line
9576
9577 @noindent
9578 This section contains some additional useful notes on the operation
9579 of the @command{gnatmake} command.
9580
9581 @itemize @bullet
9582 @item
9583 @cindex Recompilation, by @command{gnatmake}
9584 If @command{gnatmake} finds no ALI files, it recompiles the main program
9585 and all other units required by the main program.
9586 This means that @command{gnatmake}
9587 can be used for the initial compile, as well as during subsequent steps of
9588 the development cycle.
9589
9590 @item
9591 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9592 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9593 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9594 warning.
9595
9596 @item
9597 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9598 is used to specify both source and
9599 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9600 instead if you just want to specify
9601 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9602 if you want to specify library paths
9603 only.
9604
9605 @item
9606 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9607 This may conveniently be used to exclude standard libraries from
9608 consideration and in particular it means that the use of the
9609 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9610 unless @option{^-a^/ALL_FILES^} is also specified.
9611
9612 @item
9613 @command{gnatmake} has been designed to make the use of Ada libraries
9614 particularly convenient. Assume you have an Ada library organized
9615 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9616 of your Ada compilation units,
9617 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9618 specs of these units, but no bodies. Then to compile a unit
9619 stored in @code{main.adb}, which uses this Ada library you would just type
9620
9621 @smallexample
9622 @ifclear vms
9623 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9624 @end ifclear
9625 @ifset vms
9626 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9627 /SKIP_MISSING=@i{[OBJ_DIR]} main
9628 @end ifset
9629 @end smallexample
9630
9631 @item
9632 Using @command{gnatmake} along with the
9633 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9634 switch provides a mechanism for avoiding unnecessary recompilations. Using
9635 this switch,
9636 you can update the comments/format of your
9637 source files without having to recompile everything. Note, however, that
9638 adding or deleting lines in a source files may render its debugging
9639 info obsolete. If the file in question is a spec, the impact is rather
9640 limited, as that debugging info will only be useful during the
9641 elaboration phase of your program. For bodies the impact can be more
9642 significant. In all events, your debugger will warn you if a source file
9643 is more recent than the corresponding object, and alert you to the fact
9644 that the debugging information may be out of date.
9645 @end itemize
9646
9647 @node How gnatmake Works
9648 @section How @command{gnatmake} Works
9649
9650 @noindent
9651 Generally @command{gnatmake} automatically performs all necessary
9652 recompilations and you don't need to worry about how it works. However,
9653 it may be useful to have some basic understanding of the @command{gnatmake}
9654 approach and in particular to understand how it uses the results of
9655 previous compilations without incorrectly depending on them.
9656
9657 First a definition: an object file is considered @dfn{up to date} if the
9658 corresponding ALI file exists and if all the source files listed in the
9659 dependency section of this ALI file have time stamps matching those in
9660 the ALI file. This means that neither the source file itself nor any
9661 files that it depends on have been modified, and hence there is no need
9662 to recompile this file.
9663
9664 @command{gnatmake} works by first checking if the specified main unit is up
9665 to date. If so, no compilations are required for the main unit. If not,
9666 @command{gnatmake} compiles the main program to build a new ALI file that
9667 reflects the latest sources. Then the ALI file of the main unit is
9668 examined to find all the source files on which the main program depends,
9669 and @command{gnatmake} recursively applies the above procedure on all these
9670 files.
9671
9672 This process ensures that @command{gnatmake} only trusts the dependencies
9673 in an existing ALI file if they are known to be correct. Otherwise it
9674 always recompiles to determine a new, guaranteed accurate set of
9675 dependencies. As a result the program is compiled ``upside down'' from what may
9676 be more familiar as the required order of compilation in some other Ada
9677 systems. In particular, clients are compiled before the units on which
9678 they depend. The ability of GNAT to compile in any order is critical in
9679 allowing an order of compilation to be chosen that guarantees that
9680 @command{gnatmake} will recompute a correct set of new dependencies if
9681 necessary.
9682
9683 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9684 imported by several of the executables, it will be recompiled at most once.
9685
9686 Note: when using non-standard naming conventions
9687 (@pxref{Using Other File Names}), changing through a configuration pragmas
9688 file the version of a source and invoking @command{gnatmake} to recompile may
9689 have no effect, if the previous version of the source is still accessible
9690 by @command{gnatmake}. It may be necessary to use the switch
9691 ^-f^/FORCE_COMPILE^.
9692
9693 @node Examples of gnatmake Usage
9694 @section Examples of @command{gnatmake} Usage
9695
9696 @table @code
9697 @item gnatmake hello.adb
9698 Compile all files necessary to bind and link the main program
9699 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9700 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9701
9702 @item gnatmake main1 main2 main3
9703 Compile all files necessary to bind and link the main programs
9704 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9705 (containing unit @code{Main2}) and @file{main3.adb}
9706 (containing unit @code{Main3}) and bind and link the resulting object files
9707 to generate three executable files @file{^main1^MAIN1.EXE^},
9708 @file{^main2^MAIN2.EXE^}
9709 and @file{^main3^MAIN3.EXE^}.
9710
9711 @ifclear vms
9712 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9713 @end ifclear
9714
9715 @ifset vms
9716 @item gnatmake Main_Unit /QUIET
9717 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9718 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9719 @end ifset
9720 Compile all files necessary to bind and link the main program unit
9721 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9722 be done with optimization level 2 and the order of elaboration will be
9723 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9724 displaying commands it is executing.
9725 @end table
9726
9727 @c *************************
9728 @node Improving Performance
9729 @chapter Improving Performance
9730 @cindex Improving performance
9731
9732 @noindent
9733 This chapter presents several topics related to program performance.
9734 It first describes some of the tradeoffs that need to be considered
9735 and some of the techniques for making your program run faster.
9736 It then documents the @command{gnatelim} tool and unused subprogram/data
9737 elimination feature, which can reduce the size of program executables.
9738
9739 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9740 driver (see @ref{The GNAT Driver and Project Files}).
9741
9742 @ifnottex
9743 @menu
9744 * Performance Considerations::
9745 * Text_IO Suggestions::
9746 * Reducing Size of Ada Executables with gnatelim::
9747 * Reducing Size of Executables with unused subprogram/data elimination::
9748 @end menu
9749 @end ifnottex
9750
9751 @c *****************************
9752 @node Performance Considerations
9753 @section Performance Considerations
9754
9755 @noindent
9756 The GNAT system provides a number of options that allow a trade-off
9757 between
9758
9759 @itemize @bullet
9760 @item
9761 performance of the generated code
9762
9763 @item
9764 speed of compilation
9765
9766 @item
9767 minimization of dependences and recompilation
9768
9769 @item
9770 the degree of run-time checking.
9771 @end itemize
9772
9773 @noindent
9774 The defaults (if no options are selected) aim at improving the speed
9775 of compilation and minimizing dependences, at the expense of performance
9776 of the generated code:
9777
9778 @itemize @bullet
9779 @item
9780 no optimization
9781
9782 @item
9783 no inlining of subprogram calls
9784
9785 @item
9786 all run-time checks enabled except overflow and elaboration checks
9787 @end itemize
9788
9789 @noindent
9790 These options are suitable for most program development purposes. This
9791 chapter describes how you can modify these choices, and also provides
9792 some guidelines on debugging optimized code.
9793
9794 @menu
9795 * Controlling Run-Time Checks::
9796 * Use of Restrictions::
9797 * Optimization Levels::
9798 * Debugging Optimized Code::
9799 * Inlining of Subprograms::
9800 * Other Optimization Switches::
9801 * Optimization and Strict Aliasing::
9802
9803 @ifset vms
9804 * Coverage Analysis::
9805 @end ifset
9806 @end menu
9807
9808 @node Controlling Run-Time Checks
9809 @subsection Controlling Run-Time Checks
9810
9811 @noindent
9812 By default, GNAT generates all run-time checks, except integer overflow
9813 checks, stack overflow checks, and checks for access before elaboration on
9814 subprogram calls. The latter are not required in default mode, because all
9815 necessary checking is done at compile time.
9816 @cindex @option{-gnatp} (@command{gcc})
9817 @cindex @option{-gnato} (@command{gcc})
9818 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9819 be modified. @xref{Run-Time Checks}.
9820
9821 Our experience is that the default is suitable for most development
9822 purposes.
9823
9824 We treat integer overflow specially because these
9825 are quite expensive and in our experience are not as important as other
9826 run-time checks in the development process. Note that division by zero
9827 is not considered an overflow check, and divide by zero checks are
9828 generated where required by default.
9829
9830 Elaboration checks are off by default, and also not needed by default, since
9831 GNAT uses a static elaboration analysis approach that avoids the need for
9832 run-time checking. This manual contains a full chapter discussing the issue
9833 of elaboration checks, and if the default is not satisfactory for your use,
9834 you should read this chapter.
9835
9836 For validity checks, the minimal checks required by the Ada Reference
9837 Manual (for case statements and assignments to array elements) are on
9838 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9839 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9840 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9841 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9842 are also suppressed entirely if @option{-gnatp} is used.
9843
9844 @cindex Overflow checks
9845 @cindex Checks, overflow
9846 @findex Suppress
9847 @findex Unsuppress
9848 @cindex pragma Suppress
9849 @cindex pragma Unsuppress
9850 Note that the setting of the switches controls the default setting of
9851 the checks. They may be modified using either @code{pragma Suppress} (to
9852 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9853 checks) in the program source.
9854
9855 @node Use of Restrictions
9856 @subsection Use of Restrictions
9857
9858 @noindent
9859 The use of pragma Restrictions allows you to control which features are
9860 permitted in your program. Apart from the obvious point that if you avoid
9861 relatively expensive features like finalization (enforceable by the use
9862 of pragma Restrictions (No_Finalization), the use of this pragma does not
9863 affect the generated code in most cases.
9864
9865 One notable exception to this rule is that the possibility of task abort
9866 results in some distributed overhead, particularly if finalization or
9867 exception handlers are used. The reason is that certain sections of code
9868 have to be marked as non-abortable.
9869
9870 If you use neither the @code{abort} statement, nor asynchronous transfer
9871 of control (@code{select @dots{} then abort}), then this distributed overhead
9872 is removed, which may have a general positive effect in improving
9873 overall performance. Especially code involving frequent use of tasking
9874 constructs and controlled types will show much improved performance.
9875 The relevant restrictions pragmas are
9876
9877 @smallexample @c ada
9878 pragma Restrictions (No_Abort_Statements);
9879 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9880 @end smallexample
9881
9882 @noindent
9883 It is recommended that these restriction pragmas be used if possible. Note
9884 that this also means that you can write code without worrying about the
9885 possibility of an immediate abort at any point.
9886
9887 @node Optimization Levels
9888 @subsection Optimization Levels
9889 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9890
9891 @noindent
9892 Without any optimization ^option,^qualifier,^
9893 the compiler's goal is to reduce the cost of
9894 compilation and to make debugging produce the expected results.
9895 Statements are independent: if you stop the program with a breakpoint between
9896 statements, you can then assign a new value to any variable or change
9897 the program counter to any other statement in the subprogram and get exactly
9898 the results you would expect from the source code.
9899
9900 Turning on optimization makes the compiler attempt to improve the
9901 performance and/or code size at the expense of compilation time and
9902 possibly the ability to debug the program.
9903
9904 If you use multiple
9905 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9906 the last such option is the one that is effective.
9907
9908 @noindent
9909 The default is optimization off. This results in the fastest compile
9910 times, but GNAT makes absolutely no attempt to optimize, and the
9911 generated programs are considerably larger and slower than when
9912 optimization is enabled. You can use the
9913 @ifclear vms
9914 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9915 @option{-O2}, @option{-O3}, and @option{-Os})
9916 @end ifclear
9917 @ifset vms
9918 @code{OPTIMIZE} qualifier
9919 @end ifset
9920 to @command{gcc} to control the optimization level:
9921
9922 @table @option
9923 @item ^-O0^/OPTIMIZE=NONE^
9924 No optimization (the default);
9925 generates unoptimized code but has
9926 the fastest compilation time.
9927
9928 Note that many other compilers do fairly extensive optimization
9929 even if ``no optimization'' is specified. With gcc, it is
9930 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9931 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9932 really does mean no optimization at all. This difference between
9933 gcc and other compilers should be kept in mind when doing
9934 performance comparisons.
9935
9936 @item ^-O1^/OPTIMIZE=SOME^
9937 Moderate optimization;
9938 optimizes reasonably well but does not
9939 degrade compilation time significantly.
9940
9941 @item ^-O2^/OPTIMIZE=ALL^
9942 @ifset vms
9943 @itemx /OPTIMIZE=DEVELOPMENT
9944 @end ifset
9945 Full optimization;
9946 generates highly optimized code and has
9947 the slowest compilation time.
9948
9949 @item ^-O3^/OPTIMIZE=INLINING^
9950 Full optimization as in @option{-O2},
9951 and also attempts automatic inlining of small
9952 subprograms within a unit (@pxref{Inlining of Subprograms}).
9953
9954 @item ^-Os^/OPTIMIZE=SPACE^
9955 Optimize space usage of resulting program.
9956 @end table
9957
9958 @noindent
9959 Higher optimization levels perform more global transformations on the
9960 program and apply more expensive analysis algorithms in order to generate
9961 faster and more compact code. The price in compilation time, and the
9962 resulting improvement in execution time,
9963 both depend on the particular application and the hardware environment.
9964 You should experiment to find the best level for your application.
9965
9966 Since the precise set of optimizations done at each level will vary from
9967 release to release (and sometime from target to target), it is best to think
9968 of the optimization settings in general terms.
9969 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9970 the GNU Compiler Collection (GCC)}, for details about
9971 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9972 individually enable or disable specific optimizations.
9973
9974 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9975 been tested extensively at all optimization levels. There are some bugs
9976 which appear only with optimization turned on, but there have also been
9977 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9978 level of optimization does not improve the reliability of the code
9979 generator, which in practice is highly reliable at all optimization
9980 levels.
9981
9982 Note regarding the use of @option{-O3}: The use of this optimization level
9983 is generally discouraged with GNAT, since it often results in larger
9984 executables which run more slowly. See further discussion of this point
9985 in @ref{Inlining of Subprograms}.
9986
9987 @node Debugging Optimized Code
9988 @subsection Debugging Optimized Code
9989 @cindex Debugging optimized code
9990 @cindex Optimization and debugging
9991
9992 @noindent
9993 Although it is possible to do a reasonable amount of debugging at
9994 @ifclear vms
9995 nonzero optimization levels,
9996 the higher the level the more likely that
9997 @end ifclear
9998 @ifset vms
9999 @option{/OPTIMIZE} settings other than @code{NONE},
10000 such settings will make it more likely that
10001 @end ifset
10002 source-level constructs will have been eliminated by optimization.
10003 For example, if a loop is strength-reduced, the loop
10004 control variable may be completely eliminated and thus cannot be
10005 displayed in the debugger.
10006 This can only happen at @option{-O2} or @option{-O3}.
10007 Explicit temporary variables that you code might be eliminated at
10008 ^level^setting^ @option{-O1} or higher.
10009
10010 The use of the @option{^-g^/DEBUG^} switch,
10011 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10012 which is needed for source-level debugging,
10013 affects the size of the program executable on disk,
10014 and indeed the debugging information can be quite large.
10015 However, it has no effect on the generated code (and thus does not
10016 degrade performance)
10017
10018 Since the compiler generates debugging tables for a compilation unit before
10019 it performs optimizations, the optimizing transformations may invalidate some
10020 of the debugging data. You therefore need to anticipate certain
10021 anomalous situations that may arise while debugging optimized code.
10022 These are the most common cases:
10023
10024 @enumerate
10025 @item
10026 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10027 commands show
10028 the PC bouncing back and forth in the code. This may result from any of
10029 the following optimizations:
10030
10031 @itemize @bullet
10032 @item
10033 @i{Common subexpression elimination:} using a single instance of code for a
10034 quantity that the source computes several times. As a result you
10035 may not be able to stop on what looks like a statement.
10036
10037 @item
10038 @i{Invariant code motion:} moving an expression that does not change within a
10039 loop, to the beginning of the loop.
10040
10041 @item
10042 @i{Instruction scheduling:} moving instructions so as to
10043 overlap loads and stores (typically) with other code, or in
10044 general to move computations of values closer to their uses. Often
10045 this causes you to pass an assignment statement without the assignment
10046 happening and then later bounce back to the statement when the
10047 value is actually needed. Placing a breakpoint on a line of code
10048 and then stepping over it may, therefore, not always cause all the
10049 expected side-effects.
10050 @end itemize
10051
10052 @item
10053 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10054 two identical pieces of code are merged and the program counter suddenly
10055 jumps to a statement that is not supposed to be executed, simply because
10056 it (and the code following) translates to the same thing as the code
10057 that @emph{was} supposed to be executed. This effect is typically seen in
10058 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10059 a @code{break} in a C @code{^switch^switch^} statement.
10060
10061 @item
10062 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10063 There are various reasons for this effect:
10064
10065 @itemize @bullet
10066 @item
10067 In a subprogram prologue, a parameter may not yet have been moved to its
10068 ``home''.
10069
10070 @item
10071 A variable may be dead, and its register re-used. This is
10072 probably the most common cause.
10073
10074 @item
10075 As mentioned above, the assignment of a value to a variable may
10076 have been moved.
10077
10078 @item
10079 A variable may be eliminated entirely by value propagation or
10080 other means. In this case, GCC may incorrectly generate debugging
10081 information for the variable
10082 @end itemize
10083
10084 @noindent
10085 In general, when an unexpected value appears for a local variable or parameter
10086 you should first ascertain if that value was actually computed by
10087 your program, as opposed to being incorrectly reported by the debugger.
10088 Record fields or
10089 array elements in an object designated by an access value
10090 are generally less of a problem, once you have ascertained that the access
10091 value is sensible.
10092 Typically, this means checking variables in the preceding code and in the
10093 calling subprogram to verify that the value observed is explainable from other
10094 values (one must apply the procedure recursively to those
10095 other values); or re-running the code and stopping a little earlier
10096 (perhaps before the call) and stepping to better see how the variable obtained
10097 the value in question; or continuing to step @emph{from} the point of the
10098 strange value to see if code motion had simply moved the variable's
10099 assignments later.
10100 @end enumerate
10101
10102 @noindent
10103 In light of such anomalies, a recommended technique is to use @option{-O0}
10104 early in the software development cycle, when extensive debugging capabilities
10105 are most needed, and then move to @option{-O1} and later @option{-O2} as
10106 the debugger becomes less critical.
10107 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10108 a release management issue.
10109 @ifclear vms
10110 Note that if you use @option{-g} you can then use the @command{strip} program
10111 on the resulting executable,
10112 which removes both debugging information and global symbols.
10113 @end ifclear
10114
10115 @node Inlining of Subprograms
10116 @subsection Inlining of Subprograms
10117
10118 @noindent
10119 A call to a subprogram in the current unit is inlined if all the
10120 following conditions are met:
10121
10122 @itemize @bullet
10123 @item
10124 The optimization level is at least @option{-O1}.
10125
10126 @item
10127 The called subprogram is suitable for inlining: It must be small enough
10128 and not contain something that @command{gcc} cannot support in inlined
10129 subprograms.
10130
10131 @item
10132 @cindex pragma Inline
10133 @findex Inline
10134 Either @code{pragma Inline} applies to the subprogram, or it is local
10135 to the unit and called once from within it, or it is small and automatic
10136 inlining (optimization level @option{-O3}) is specified.
10137 @end itemize
10138
10139 @noindent
10140 Calls to subprograms in @code{with}'ed units are normally not inlined.
10141 To achieve actual inlining (that is, replacement of the call by the code
10142 in the body of the subprogram), the following conditions must all be true.
10143
10144 @itemize @bullet
10145 @item
10146 The optimization level is at least @option{-O1}.
10147
10148 @item
10149 The called subprogram is suitable for inlining: It must be small enough
10150 and not contain something that @command{gcc} cannot support in inlined
10151 subprograms.
10152
10153 @item
10154 The call appears in a body (not in a package spec).
10155
10156 @item
10157 There is a @code{pragma Inline} for the subprogram.
10158
10159 @item
10160 @cindex @option{-gnatn} (@command{gcc})
10161 The @option{^-gnatn^/INLINE^} switch
10162 is used in the @command{gcc} command line
10163 @end itemize
10164
10165 Even if all these conditions are met, it may not be possible for
10166 the compiler to inline the call, due to the length of the body,
10167 or features in the body that make it impossible for the compiler
10168 to do the inlining.
10169
10170 Note that specifying the @option{-gnatn} switch causes additional
10171 compilation dependencies. Consider the following:
10172
10173 @smallexample @c ada
10174 @cartouche
10175 package R is
10176 procedure Q;
10177 pragma Inline (Q);
10178 end R;
10179 package body R is
10180 @dots{}
10181 end R;
10182
10183 with R;
10184 procedure Main is
10185 begin
10186 @dots{}
10187 R.Q;
10188 end Main;
10189 @end cartouche
10190 @end smallexample
10191
10192 @noindent
10193 With the default behavior (no @option{-gnatn} switch specified), the
10194 compilation of the @code{Main} procedure depends only on its own source,
10195 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10196 means that editing the body of @code{R} does not require recompiling
10197 @code{Main}.
10198
10199 On the other hand, the call @code{R.Q} is not inlined under these
10200 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10201 is compiled, the call will be inlined if the body of @code{Q} is small
10202 enough, but now @code{Main} depends on the body of @code{R} in
10203 @file{r.adb} as well as on the spec. This means that if this body is edited,
10204 the main program must be recompiled. Note that this extra dependency
10205 occurs whether or not the call is in fact inlined by @command{gcc}.
10206
10207 The use of front end inlining with @option{-gnatN} generates similar
10208 additional dependencies.
10209
10210 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10211 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10212 can be used to prevent
10213 all inlining. This switch overrides all other conditions and ensures
10214 that no inlining occurs. The extra dependences resulting from
10215 @option{-gnatn} will still be active, even if
10216 this switch is used to suppress the resulting inlining actions.
10217
10218 @cindex @option{-fno-inline-functions} (@command{gcc})
10219 Note: The @option{-fno-inline-functions} switch can be used to prevent
10220 automatic inlining of small subprograms if @option{-O3} is used.
10221
10222 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10223 Note: The @option{-fno-inline-functions-called-once} switch
10224 can be used to prevent inlining of subprograms local to the unit
10225 and called once from within it if @option{-O1} is used.
10226
10227 Note regarding the use of @option{-O3}: There is no difference in inlining
10228 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10229 pragma @code{Inline} assuming the use of @option{-gnatn}
10230 or @option{-gnatN} (the switches that activate inlining). If you have used
10231 pragma @code{Inline} in appropriate cases, then it is usually much better
10232 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10233 in this case only has the effect of inlining subprograms you did not
10234 think should be inlined. We often find that the use of @option{-O3} slows
10235 down code by performing excessive inlining, leading to increased instruction
10236 cache pressure from the increased code size. So the bottom line here is
10237 that you should not automatically assume that @option{-O3} is better than
10238 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10239 it actually improves performance.
10240
10241 @node Other Optimization Switches
10242 @subsection Other Optimization Switches
10243 @cindex Optimization Switches
10244
10245 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10246 @command{gcc} optimization switches are potentially usable. These switches
10247 have not been extensively tested with GNAT but can generally be expected
10248 to work. Examples of switches in this category are
10249 @option{-funroll-loops} and
10250 the various target-specific @option{-m} options (in particular, it has been
10251 observed that @option{-march=pentium4} can significantly improve performance
10252 on appropriate machines). For full details of these switches, see
10253 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10254 the GNU Compiler Collection (GCC)}.
10255
10256 @node Optimization and Strict Aliasing
10257 @subsection Optimization and Strict Aliasing
10258 @cindex Aliasing
10259 @cindex Strict Aliasing
10260 @cindex No_Strict_Aliasing
10261
10262 @noindent
10263 The strong typing capabilities of Ada allow an optimizer to generate
10264 efficient code in situations where other languages would be forced to
10265 make worst case assumptions preventing such optimizations. Consider
10266 the following example:
10267
10268 @smallexample @c ada
10269 @cartouche
10270 procedure R is
10271 type Int1 is new Integer;
10272 type Int2 is new Integer;
10273 type Int1A is access Int1;
10274 type Int2A is access Int2;
10275 Int1V : Int1A;
10276 Int2V : Int2A;
10277 @dots{}
10278
10279 begin
10280 @dots{}
10281 for J in Data'Range loop
10282 if Data (J) = Int1V.all then
10283 Int2V.all := Int2V.all + 1;
10284 end if;
10285 end loop;
10286 @dots{}
10287 end R;
10288 @end cartouche
10289 @end smallexample
10290
10291 @noindent
10292 In this example, since the variable @code{Int1V} can only access objects
10293 of type @code{Int1}, and @code{Int2V} can only access objects of type
10294 @code{Int2}, there is no possibility that the assignment to
10295 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10296 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10297 for all iterations of the loop and avoid the extra memory reference
10298 required to dereference it each time through the loop.
10299
10300 This kind of optimization, called strict aliasing analysis, is
10301 triggered by specifying an optimization level of @option{-O2} or
10302 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10303 when access values are involved.
10304
10305 However, although this optimization is always correct in terms of
10306 the formal semantics of the Ada Reference Manual, difficulties can
10307 arise if features like @code{Unchecked_Conversion} are used to break
10308 the typing system. Consider the following complete program example:
10309
10310 @smallexample @c ada
10311 @cartouche
10312 package p1 is
10313 type int1 is new integer;
10314 type int2 is new integer;
10315 type a1 is access int1;
10316 type a2 is access int2;
10317 end p1;
10318
10319 with p1; use p1;
10320 package p2 is
10321 function to_a2 (Input : a1) return a2;
10322 end p2;
10323
10324 with Unchecked_Conversion;
10325 package body p2 is
10326 function to_a2 (Input : a1) return a2 is
10327 function to_a2u is
10328 new Unchecked_Conversion (a1, a2);
10329 begin
10330 return to_a2u (Input);
10331 end to_a2;
10332 end p2;
10333
10334 with p2; use p2;
10335 with p1; use p1;
10336 with Text_IO; use Text_IO;
10337 procedure m is
10338 v1 : a1 := new int1;
10339 v2 : a2 := to_a2 (v1);
10340 begin
10341 v1.all := 1;
10342 v2.all := 0;
10343 put_line (int1'image (v1.all));
10344 end;
10345 @end cartouche
10346 @end smallexample
10347
10348 @noindent
10349 This program prints out 0 in @option{-O0} or @option{-O1}
10350 mode, but it prints out 1 in @option{-O2} mode. That's
10351 because in strict aliasing mode, the compiler can and
10352 does assume that the assignment to @code{v2.all} could not
10353 affect the value of @code{v1.all}, since different types
10354 are involved.
10355
10356 This behavior is not a case of non-conformance with the standard, since
10357 the Ada RM specifies that an unchecked conversion where the resulting
10358 bit pattern is not a correct value of the target type can result in an
10359 abnormal value and attempting to reference an abnormal value makes the
10360 execution of a program erroneous. That's the case here since the result
10361 does not point to an object of type @code{int2}. This means that the
10362 effect is entirely unpredictable.
10363
10364 However, although that explanation may satisfy a language
10365 lawyer, in practice an applications programmer expects an
10366 unchecked conversion involving pointers to create true
10367 aliases and the behavior of printing 1 seems plain wrong.
10368 In this case, the strict aliasing optimization is unwelcome.
10369
10370 Indeed the compiler recognizes this possibility, and the
10371 unchecked conversion generates a warning:
10372
10373 @smallexample
10374 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10375 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10376 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10377 @end smallexample
10378
10379 @noindent
10380 Unfortunately the problem is recognized when compiling the body of
10381 package @code{p2}, but the actual "bad" code is generated while
10382 compiling the body of @code{m} and this latter compilation does not see
10383 the suspicious @code{Unchecked_Conversion}.
10384
10385 As implied by the warning message, there are approaches you can use to
10386 avoid the unwanted strict aliasing optimization in a case like this.
10387
10388 One possibility is to simply avoid the use of @option{-O2}, but
10389 that is a bit drastic, since it throws away a number of useful
10390 optimizations that do not involve strict aliasing assumptions.
10391
10392 A less drastic approach is to compile the program using the
10393 option @option{-fno-strict-aliasing}. Actually it is only the
10394 unit containing the dereferencing of the suspicious pointer
10395 that needs to be compiled. So in this case, if we compile
10396 unit @code{m} with this switch, then we get the expected
10397 value of zero printed. Analyzing which units might need
10398 the switch can be painful, so a more reasonable approach
10399 is to compile the entire program with options @option{-O2}
10400 and @option{-fno-strict-aliasing}. If the performance is
10401 satisfactory with this combination of options, then the
10402 advantage is that the entire issue of possible "wrong"
10403 optimization due to strict aliasing is avoided.
10404
10405 To avoid the use of compiler switches, the configuration
10406 pragma @code{No_Strict_Aliasing} with no parameters may be
10407 used to specify that for all access types, the strict
10408 aliasing optimization should be suppressed.
10409
10410 However, these approaches are still overkill, in that they causes
10411 all manipulations of all access values to be deoptimized. A more
10412 refined approach is to concentrate attention on the specific
10413 access type identified as problematic.
10414
10415 First, if a careful analysis of uses of the pointer shows
10416 that there are no possible problematic references, then
10417 the warning can be suppressed by bracketing the
10418 instantiation of @code{Unchecked_Conversion} to turn
10419 the warning off:
10420
10421 @smallexample @c ada
10422 pragma Warnings (Off);
10423 function to_a2u is
10424 new Unchecked_Conversion (a1, a2);
10425 pragma Warnings (On);
10426 @end smallexample
10427
10428 @noindent
10429 Of course that approach is not appropriate for this particular
10430 example, since indeed there is a problematic reference. In this
10431 case we can take one of two other approaches.
10432
10433 The first possibility is to move the instantiation of unchecked
10434 conversion to the unit in which the type is declared. In
10435 this example, we would move the instantiation of
10436 @code{Unchecked_Conversion} from the body of package
10437 @code{p2} to the spec of package @code{p1}. Now the
10438 warning disappears. That's because any use of the
10439 access type knows there is a suspicious unchecked
10440 conversion, and the strict aliasing optimization
10441 is automatically suppressed for the type.
10442
10443 If it is not practical to move the unchecked conversion to the same unit
10444 in which the destination access type is declared (perhaps because the
10445 source type is not visible in that unit), you may use pragma
10446 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10447 same declarative sequence as the declaration of the access type:
10448
10449 @smallexample @c ada
10450 type a2 is access int2;
10451 pragma No_Strict_Aliasing (a2);
10452 @end smallexample
10453
10454 @noindent
10455 Here again, the compiler now knows that the strict aliasing optimization
10456 should be suppressed for any reference to type @code{a2} and the
10457 expected behavior is obtained.
10458
10459 Finally, note that although the compiler can generate warnings for
10460 simple cases of unchecked conversions, there are tricker and more
10461 indirect ways of creating type incorrect aliases which the compiler
10462 cannot detect. Examples are the use of address overlays and unchecked
10463 conversions involving composite types containing access types as
10464 components. In such cases, no warnings are generated, but there can
10465 still be aliasing problems. One safe coding practice is to forbid the
10466 use of address clauses for type overlaying, and to allow unchecked
10467 conversion only for primitive types. This is not really a significant
10468 restriction since any possible desired effect can be achieved by
10469 unchecked conversion of access values.
10470
10471 The aliasing analysis done in strict aliasing mode can certainly
10472 have significant benefits. We have seen cases of large scale
10473 application code where the time is increased by up to 5% by turning
10474 this optimization off. If you have code that includes significant
10475 usage of unchecked conversion, you might want to just stick with
10476 @option{-O1} and avoid the entire issue. If you get adequate
10477 performance at this level of optimization level, that's probably
10478 the safest approach. If tests show that you really need higher
10479 levels of optimization, then you can experiment with @option{-O2}
10480 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10481 has on size and speed of the code. If you really need to use
10482 @option{-O2} with strict aliasing in effect, then you should
10483 review any uses of unchecked conversion of access types,
10484 particularly if you are getting the warnings described above.
10485
10486 @ifset vms
10487 @node Coverage Analysis
10488 @subsection Coverage Analysis
10489
10490 @noindent
10491 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10492 the user to determine the distribution of execution time across a program,
10493 @pxref{Profiling} for details of usage.
10494 @end ifset
10495
10496
10497 @node Text_IO Suggestions
10498 @section @code{Text_IO} Suggestions
10499 @cindex @code{Text_IO} and performance
10500
10501 @noindent
10502 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10503 the requirement of maintaining page and line counts. If performance
10504 is critical, a recommendation is to use @code{Stream_IO} instead of
10505 @code{Text_IO} for volume output, since this package has less overhead.
10506
10507 If @code{Text_IO} must be used, note that by default output to the standard
10508 output and standard error files is unbuffered (this provides better
10509 behavior when output statements are used for debugging, or if the
10510 progress of a program is observed by tracking the output, e.g. by
10511 using the Unix @command{tail -f} command to watch redirected output.
10512
10513 If you are generating large volumes of output with @code{Text_IO} and
10514 performance is an important factor, use a designated file instead
10515 of the standard output file, or change the standard output file to
10516 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10517
10518
10519
10520 @node Reducing Size of Ada Executables with gnatelim
10521 @section Reducing Size of Ada Executables with @code{gnatelim}
10522 @findex gnatelim
10523
10524 @noindent
10525 This section describes @command{gnatelim}, a tool which detects unused
10526 subprograms and helps the compiler to create a smaller executable for your
10527 program.
10528
10529 @menu
10530 * About gnatelim::
10531 * Running gnatelim::
10532 * Correcting the List of Eliminate Pragmas::
10533 * Making Your Executables Smaller::
10534 * Summary of the gnatelim Usage Cycle::
10535 @end menu
10536
10537 @node About gnatelim
10538 @subsection About @code{gnatelim}
10539
10540 @noindent
10541 When a program shares a set of Ada
10542 packages with other programs, it may happen that this program uses
10543 only a fraction of the subprograms defined in these packages. The code
10544 created for these unused subprograms increases the size of the executable.
10545
10546 @code{gnatelim} tracks unused subprograms in an Ada program and
10547 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10548 subprograms that are declared but never called. By placing the list of
10549 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10550 recompiling your program, you may decrease the size of its executable,
10551 because the compiler will not generate the code for 'eliminated' subprograms.
10552 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10553 information about this pragma.
10554
10555 @code{gnatelim} needs as its input data the name of the main subprogram
10556 and a bind file for a main subprogram.
10557
10558 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10559 the main subprogram. @code{gnatelim} can work with both Ada and C
10560 bind files; when both are present, it uses the Ada bind file.
10561 The following commands will build the program and create the bind file:
10562
10563 @smallexample
10564 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10565 $ gnatbind main_prog
10566 @end smallexample
10567
10568 Note that @code{gnatelim} needs neither object nor ALI files.
10569
10570 @node Running gnatelim
10571 @subsection Running @code{gnatelim}
10572
10573 @noindent
10574 @code{gnatelim} has the following command-line interface:
10575
10576 @smallexample
10577 $ gnatelim @ovar{options} name
10578 @end smallexample
10579
10580 @noindent
10581 @code{name} should be a name of a source file that contains the main subprogram
10582 of a program (partition).
10583
10584 @code{gnatelim} has the following switches:
10585
10586 @table @option
10587 @c !sort!
10588 @item ^-q^/QUIET^
10589 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10590 Quiet mode: by default @code{gnatelim} outputs to the standard error
10591 stream the number of program units left to be processed. This option turns
10592 this trace off.
10593
10594 @item ^-v^/VERBOSE^
10595 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10596 Verbose mode: @code{gnatelim} version information is printed as Ada
10597 comments to the standard output stream. Also, in addition to the number of
10598 program units left @code{gnatelim} will output the name of the current unit
10599 being processed.
10600
10601 @item ^-a^/ALL^
10602 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10603 Also look for subprograms from the GNAT run time that can be eliminated. Note
10604 that when @file{gnat.adc} is produced using this switch, the entire program
10605 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10606
10607 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10608 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10609 When looking for source files also look in directory @var{dir}. Specifying
10610 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10611 sources in the current directory.
10612
10613 @item ^-b^/BIND_FILE=^@var{bind_file}
10614 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10615 Specifies @var{bind_file} as the bind file to process. If not set, the name
10616 of the bind file is computed from the full expanded Ada name
10617 of a main subprogram.
10618
10619 @item ^-C^/CONFIG_FILE=^@var{config_file}
10620 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10621 Specifies a file @var{config_file} that contains configuration pragmas. The
10622 file must be specified with full path.
10623
10624 @item ^--GCC^/COMPILER^=@var{compiler_name}
10625 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10626 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10627 available on the path.
10628
10629 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10630 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10631 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10632 available on the path.
10633 @end table
10634
10635 @noindent
10636 @code{gnatelim} sends its output to the standard output stream, and all the
10637 tracing and debug information is sent to the standard error stream.
10638 In order to produce a proper GNAT configuration file
10639 @file{gnat.adc}, redirection must be used:
10640
10641 @smallexample
10642 @ifset vms
10643 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10644 @end ifset
10645 @ifclear vms
10646 $ gnatelim main_prog.adb > gnat.adc
10647 @end ifclear
10648 @end smallexample
10649
10650 @ifclear vms
10651 @noindent
10652 or
10653
10654 @smallexample
10655 $ gnatelim main_prog.adb >> gnat.adc
10656 @end smallexample
10657
10658 @noindent
10659 in order to append the @code{gnatelim} output to the existing contents of
10660 @file{gnat.adc}.
10661 @end ifclear
10662
10663 @node Correcting the List of Eliminate Pragmas
10664 @subsection Correcting the List of Eliminate Pragmas
10665
10666 @noindent
10667 In some rare cases @code{gnatelim} may try to eliminate
10668 subprograms that are actually called in the program. In this case, the
10669 compiler will generate an error message of the form:
10670
10671 @smallexample
10672 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10673 @end smallexample
10674
10675 @noindent
10676 You will need to manually remove the wrong @code{Eliminate} pragmas from
10677 the @file{gnat.adc} file. You should recompile your program
10678 from scratch after that, because you need a consistent @file{gnat.adc} file
10679 during the entire compilation.
10680
10681 @node Making Your Executables Smaller
10682 @subsection Making Your Executables Smaller
10683
10684 @noindent
10685 In order to get a smaller executable for your program you now have to
10686 recompile the program completely with the new @file{gnat.adc} file
10687 created by @code{gnatelim} in your current directory:
10688
10689 @smallexample
10690 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10691 @end smallexample
10692
10693 @noindent
10694 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10695 recompile everything
10696 with the set of pragmas @code{Eliminate} that you have obtained with
10697 @command{gnatelim}).
10698
10699 Be aware that the set of @code{Eliminate} pragmas is specific to each
10700 program. It is not recommended to merge sets of @code{Eliminate}
10701 pragmas created for different programs in one @file{gnat.adc} file.
10702
10703 @node Summary of the gnatelim Usage Cycle
10704 @subsection Summary of the gnatelim Usage Cycle
10705
10706 @noindent
10707 Here is a quick summary of the steps to be taken in order to reduce
10708 the size of your executables with @code{gnatelim}. You may use
10709 other GNAT options to control the optimization level,
10710 to produce the debugging information, to set search path, etc.
10711
10712 @enumerate
10713 @item
10714 Produce a bind file
10715
10716 @smallexample
10717 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10718 $ gnatbind main_prog
10719 @end smallexample
10720
10721 @item
10722 Generate a list of @code{Eliminate} pragmas
10723 @smallexample
10724 @ifset vms
10725 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10726 @end ifset
10727 @ifclear vms
10728 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10729 @end ifclear
10730 @end smallexample
10731
10732 @item
10733 Recompile the application
10734
10735 @smallexample
10736 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10737 @end smallexample
10738
10739 @end enumerate
10740
10741 @node Reducing Size of Executables with unused subprogram/data elimination
10742 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10743 @findex unused subprogram/data elimination
10744
10745 @noindent
10746 This section describes how you can eliminate unused subprograms and data from
10747 your executable just by setting options at compilation time.
10748
10749 @menu
10750 * About unused subprogram/data elimination::
10751 * Compilation options::
10752 * Example of unused subprogram/data elimination::
10753 @end menu
10754
10755 @node About unused subprogram/data elimination
10756 @subsection About unused subprogram/data elimination
10757
10758 @noindent
10759 By default, an executable contains all code and data of its composing objects
10760 (directly linked or coming from statically linked libraries), even data or code
10761 never used by this executable.
10762
10763 This feature will allow you to eliminate such unused code from your
10764 executable, making it smaller (in disk and in memory).
10765
10766 This functionality is available on all Linux platforms except for the IA-64
10767 architecture and on all cross platforms using the ELF binary file format.
10768 In both cases GNU binutils version 2.16 or later are required to enable it.
10769
10770 @node Compilation options
10771 @subsection Compilation options
10772
10773 @noindent
10774 The operation of eliminating the unused code and data from the final executable
10775 is directly performed by the linker.
10776
10777 In order to do this, it has to work with objects compiled with the
10778 following options:
10779 @option{-ffunction-sections} @option{-fdata-sections}.
10780 @cindex @option{-ffunction-sections} (@command{gcc})
10781 @cindex @option{-fdata-sections} (@command{gcc})
10782 These options are usable with C and Ada files.
10783 They will place respectively each
10784 function or data in a separate section in the resulting object file.
10785
10786 Once the objects and static libraries are created with these options, the
10787 linker can perform the dead code elimination. You can do this by setting
10788 the @option{-Wl,--gc-sections} option to gcc command or in the
10789 @option{-largs} section of @command{gnatmake}. This will perform a
10790 garbage collection of code and data never referenced.
10791
10792 If the linker performs a partial link (@option{-r} ld linker option), then you
10793 will need to provide one or several entry point using the
10794 @option{-e} / @option{--entry} ld option.
10795
10796 Note that objects compiled without the @option{-ffunction-sections} and
10797 @option{-fdata-sections} options can still be linked with the executable.
10798 However, no dead code elimination will be performed on those objects (they will
10799 be linked as is).
10800
10801 The GNAT static library is now compiled with -ffunction-sections and
10802 -fdata-sections on some platforms. This allows you to eliminate the unused code
10803 and data of the GNAT library from your executable.
10804
10805 @node Example of unused subprogram/data elimination
10806 @subsection Example of unused subprogram/data elimination
10807
10808 @noindent
10809 Here is a simple example:
10810
10811 @smallexample @c ada
10812 with Aux;
10813
10814 procedure Test is
10815 begin
10816 Aux.Used (10);
10817 end Test;
10818
10819 package Aux is
10820 Used_Data : Integer;
10821 Unused_Data : Integer;
10822
10823 procedure Used (Data : Integer);
10824 procedure Unused (Data : Integer);
10825 end Aux;
10826
10827 package body Aux is
10828 procedure Used (Data : Integer) is
10829 begin
10830 Used_Data := Data;
10831 end Used;
10832
10833 procedure Unused (Data : Integer) is
10834 begin
10835 Unused_Data := Data;
10836 end Unused;
10837 end Aux;
10838 @end smallexample
10839
10840 @noindent
10841 @code{Unused} and @code{Unused_Data} are never referenced in this code
10842 excerpt, and hence they may be safely removed from the final executable.
10843
10844 @smallexample
10845 $ gnatmake test
10846
10847 $ nm test | grep used
10848 020015f0 T aux__unused
10849 02005d88 B aux__unused_data
10850 020015cc T aux__used
10851 02005d84 B aux__used_data
10852
10853 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10854 -largs -Wl,--gc-sections
10855
10856 $ nm test | grep used
10857 02005350 T aux__used
10858 0201ffe0 B aux__used_data
10859 @end smallexample
10860
10861 @noindent
10862 It can be observed that the procedure @code{Unused} and the object
10863 @code{Unused_Data} are removed by the linker when using the
10864 appropriate options.
10865
10866 @c ********************************
10867 @node Renaming Files Using gnatchop
10868 @chapter Renaming Files Using @code{gnatchop}
10869 @findex gnatchop
10870
10871 @noindent
10872 This chapter discusses how to handle files with multiple units by using
10873 the @code{gnatchop} utility. This utility is also useful in renaming
10874 files to meet the standard GNAT default file naming conventions.
10875
10876 @menu
10877 * Handling Files with Multiple Units::
10878 * Operating gnatchop in Compilation Mode::
10879 * Command Line for gnatchop::
10880 * Switches for gnatchop::
10881 * Examples of gnatchop Usage::
10882 @end menu
10883
10884 @node Handling Files with Multiple Units
10885 @section Handling Files with Multiple Units
10886
10887 @noindent
10888 The basic compilation model of GNAT requires that a file submitted to the
10889 compiler have only one unit and there be a strict correspondence
10890 between the file name and the unit name.
10891
10892 The @code{gnatchop} utility allows both of these rules to be relaxed,
10893 allowing GNAT to process files which contain multiple compilation units
10894 and files with arbitrary file names. @code{gnatchop}
10895 reads the specified file and generates one or more output files,
10896 containing one unit per file. The unit and the file name correspond,
10897 as required by GNAT.
10898
10899 If you want to permanently restructure a set of ``foreign'' files so that
10900 they match the GNAT rules, and do the remaining development using the
10901 GNAT structure, you can simply use @command{gnatchop} once, generate the
10902 new set of files and work with them from that point on.
10903
10904 Alternatively, if you want to keep your files in the ``foreign'' format,
10905 perhaps to maintain compatibility with some other Ada compilation
10906 system, you can set up a procedure where you use @command{gnatchop} each
10907 time you compile, regarding the source files that it writes as temporary
10908 files that you throw away.
10909
10910 Note that if your file containing multiple units starts with a byte order
10911 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10912 will each start with a copy of this BOM, meaning that they can be compiled
10913 automatically in UTF-8 mode without needing to specify an explicit encoding.
10914
10915 @node Operating gnatchop in Compilation Mode
10916 @section Operating gnatchop in Compilation Mode
10917
10918 @noindent
10919 The basic function of @code{gnatchop} is to take a file with multiple units
10920 and split it into separate files. The boundary between files is reasonably
10921 clear, except for the issue of comments and pragmas. In default mode, the
10922 rule is that any pragmas between units belong to the previous unit, except
10923 that configuration pragmas always belong to the following unit. Any comments
10924 belong to the following unit. These rules
10925 almost always result in the right choice of
10926 the split point without needing to mark it explicitly and most users will
10927 find this default to be what they want. In this default mode it is incorrect to
10928 submit a file containing only configuration pragmas, or one that ends in
10929 configuration pragmas, to @code{gnatchop}.
10930
10931 However, using a special option to activate ``compilation mode'',
10932 @code{gnatchop}
10933 can perform another function, which is to provide exactly the semantics
10934 required by the RM for handling of configuration pragmas in a compilation.
10935 In the absence of configuration pragmas (at the main file level), this
10936 option has no effect, but it causes such configuration pragmas to be handled
10937 in a quite different manner.
10938
10939 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10940 only configuration pragmas, then this file is appended to the
10941 @file{gnat.adc} file in the current directory. This behavior provides
10942 the required behavior described in the RM for the actions to be taken
10943 on submitting such a file to the compiler, namely that these pragmas
10944 should apply to all subsequent compilations in the same compilation
10945 environment. Using GNAT, the current directory, possibly containing a
10946 @file{gnat.adc} file is the representation
10947 of a compilation environment. For more information on the
10948 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10949
10950 Second, in compilation mode, if @code{gnatchop}
10951 is given a file that starts with
10952 configuration pragmas, and contains one or more units, then these
10953 configuration pragmas are prepended to each of the chopped files. This
10954 behavior provides the required behavior described in the RM for the
10955 actions to be taken on compiling such a file, namely that the pragmas
10956 apply to all units in the compilation, but not to subsequently compiled
10957 units.
10958
10959 Finally, if configuration pragmas appear between units, they are appended
10960 to the previous unit. This results in the previous unit being illegal,
10961 since the compiler does not accept configuration pragmas that follow
10962 a unit. This provides the required RM behavior that forbids configuration
10963 pragmas other than those preceding the first compilation unit of a
10964 compilation.
10965
10966 For most purposes, @code{gnatchop} will be used in default mode. The
10967 compilation mode described above is used only if you need exactly
10968 accurate behavior with respect to compilations, and you have files
10969 that contain multiple units and configuration pragmas. In this
10970 circumstance the use of @code{gnatchop} with the compilation mode
10971 switch provides the required behavior, and is for example the mode
10972 in which GNAT processes the ACVC tests.
10973
10974 @node Command Line for gnatchop
10975 @section Command Line for @code{gnatchop}
10976
10977 @noindent
10978 The @code{gnatchop} command has the form:
10979
10980 @smallexample
10981 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
10982 @ovar{directory}
10983 @end smallexample
10984
10985 @noindent
10986 The only required argument is the file name of the file to be chopped.
10987 There are no restrictions on the form of this file name. The file itself
10988 contains one or more Ada units, in normal GNAT format, concatenated
10989 together. As shown, more than one file may be presented to be chopped.
10990
10991 When run in default mode, @code{gnatchop} generates one output file in
10992 the current directory for each unit in each of the files.
10993
10994 @var{directory}, if specified, gives the name of the directory to which
10995 the output files will be written. If it is not specified, all files are
10996 written to the current directory.
10997
10998 For example, given a
10999 file called @file{hellofiles} containing
11000
11001 @smallexample @c ada
11002 @group
11003 @cartouche
11004 procedure hello;
11005
11006 with Text_IO; use Text_IO;
11007 procedure hello is
11008 begin
11009 Put_Line ("Hello");
11010 end hello;
11011 @end cartouche
11012 @end group
11013 @end smallexample
11014
11015 @noindent
11016 the command
11017
11018 @smallexample
11019 $ gnatchop ^hellofiles^HELLOFILES.^
11020 @end smallexample
11021
11022 @noindent
11023 generates two files in the current directory, one called
11024 @file{hello.ads} containing the single line that is the procedure spec,
11025 and the other called @file{hello.adb} containing the remaining text. The
11026 original file is not affected. The generated files can be compiled in
11027 the normal manner.
11028
11029 @noindent
11030 When gnatchop is invoked on a file that is empty or that contains only empty
11031 lines and/or comments, gnatchop will not fail, but will not produce any
11032 new sources.
11033
11034 For example, given a
11035 file called @file{toto.txt} containing
11036
11037 @smallexample @c ada
11038 @group
11039 @cartouche
11040 -- Just a comment
11041 @end cartouche
11042 @end group
11043 @end smallexample
11044
11045 @noindent
11046 the command
11047
11048 @smallexample
11049 $ gnatchop ^toto.txt^TOT.TXT^
11050 @end smallexample
11051
11052 @noindent
11053 will not produce any new file and will result in the following warnings:
11054
11055 @smallexample
11056 toto.txt:1:01: warning: empty file, contains no compilation units
11057 no compilation units found
11058 no source files written
11059 @end smallexample
11060
11061 @node Switches for gnatchop
11062 @section Switches for @code{gnatchop}
11063
11064 @noindent
11065 @command{gnatchop} recognizes the following switches:
11066
11067 @table @option
11068 @c !sort!
11069
11070 @item --version
11071 @cindex @option{--version} @command{gnatchop}
11072 Display Copyright and version, then exit disregarding all other options.
11073
11074 @item --help
11075 @cindex @option{--help} @command{gnatchop}
11076 If @option{--version} was not used, display usage, then exit disregarding
11077 all other options.
11078
11079 @item ^-c^/COMPILATION^
11080 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11081 Causes @code{gnatchop} to operate in compilation mode, in which
11082 configuration pragmas are handled according to strict RM rules. See
11083 previous section for a full description of this mode.
11084
11085 @ifclear vms
11086 @item -gnat@var{xxx}
11087 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11088 used to parse the given file. Not all @var{xxx} options make sense,
11089 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11090 process a source file that uses Latin-2 coding for identifiers.
11091 @end ifclear
11092
11093 @item ^-h^/HELP^
11094 Causes @code{gnatchop} to generate a brief help summary to the standard
11095 output file showing usage information.
11096
11097 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11098 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11099 Limit generated file names to the specified number @code{mm}
11100 of characters.
11101 This is useful if the
11102 resulting set of files is required to be interoperable with systems
11103 which limit the length of file names.
11104 @ifset vms
11105 If no value is given, or
11106 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11107 a default of 39, suitable for OpenVMS Alpha
11108 Systems, is assumed
11109 @end ifset
11110 @ifclear vms
11111 No space is allowed between the @option{-k} and the numeric value. The numeric
11112 value may be omitted in which case a default of @option{-k8},
11113 suitable for use
11114 with DOS-like file systems, is used. If no @option{-k} switch
11115 is present then
11116 there is no limit on the length of file names.
11117 @end ifclear
11118
11119 @item ^-p^/PRESERVE^
11120 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11121 Causes the file ^modification^creation^ time stamp of the input file to be
11122 preserved and used for the time stamp of the output file(s). This may be
11123 useful for preserving coherency of time stamps in an environment where
11124 @code{gnatchop} is used as part of a standard build process.
11125
11126 @item ^-q^/QUIET^
11127 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11128 Causes output of informational messages indicating the set of generated
11129 files to be suppressed. Warnings and error messages are unaffected.
11130
11131 @item ^-r^/REFERENCE^
11132 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11133 @findex Source_Reference
11134 Generate @code{Source_Reference} pragmas. Use this switch if the output
11135 files are regarded as temporary and development is to be done in terms
11136 of the original unchopped file. This switch causes
11137 @code{Source_Reference} pragmas to be inserted into each of the
11138 generated files to refers back to the original file name and line number.
11139 The result is that all error messages refer back to the original
11140 unchopped file.
11141 In addition, the debugging information placed into the object file (when
11142 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11143 specified)
11144 also refers back to this original file so that tools like profilers and
11145 debuggers will give information in terms of the original unchopped file.
11146
11147 If the original file to be chopped itself contains
11148 a @code{Source_Reference}
11149 pragma referencing a third file, then gnatchop respects
11150 this pragma, and the generated @code{Source_Reference} pragmas
11151 in the chopped file refer to the original file, with appropriate
11152 line numbers. This is particularly useful when @code{gnatchop}
11153 is used in conjunction with @code{gnatprep} to compile files that
11154 contain preprocessing statements and multiple units.
11155
11156 @item ^-v^/VERBOSE^
11157 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11158 Causes @code{gnatchop} to operate in verbose mode. The version
11159 number and copyright notice are output, as well as exact copies of
11160 the gnat1 commands spawned to obtain the chop control information.
11161
11162 @item ^-w^/OVERWRITE^
11163 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11164 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11165 fatal error if there is already a file with the same name as a
11166 file it would otherwise output, in other words if the files to be
11167 chopped contain duplicated units. This switch bypasses this
11168 check, and causes all but the last instance of such duplicated
11169 units to be skipped.
11170
11171 @ifclear vms
11172 @item --GCC=@var{xxxx}
11173 @cindex @option{--GCC=} (@code{gnatchop})
11174 Specify the path of the GNAT parser to be used. When this switch is used,
11175 no attempt is made to add the prefix to the GNAT parser executable.
11176 @end ifclear
11177 @end table
11178
11179 @node Examples of gnatchop Usage
11180 @section Examples of @code{gnatchop} Usage
11181
11182 @table @code
11183 @ifset vms
11184 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11185 @end ifset
11186 @ifclear vms
11187 @item gnatchop -w hello_s.ada prerelease/files
11188 @end ifclear
11189
11190 Chops the source file @file{hello_s.ada}. The output files will be
11191 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11192 overwriting any
11193 files with matching names in that directory (no files in the current
11194 directory are modified).
11195
11196 @item gnatchop ^archive^ARCHIVE.^
11197 Chops the source file @file{^archive^ARCHIVE.^}
11198 into the current directory. One
11199 useful application of @code{gnatchop} is in sending sets of sources
11200 around, for example in email messages. The required sources are simply
11201 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11202 command), and then
11203 @command{gnatchop} is used at the other end to reconstitute the original
11204 file names.
11205
11206 @item gnatchop file1 file2 file3 direc
11207 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11208 the resulting files in the directory @file{direc}. Note that if any units
11209 occur more than once anywhere within this set of files, an error message
11210 is generated, and no files are written. To override this check, use the
11211 @option{^-w^/OVERWRITE^} switch,
11212 in which case the last occurrence in the last file will
11213 be the one that is output, and earlier duplicate occurrences for a given
11214 unit will be skipped.
11215 @end table
11216
11217 @node Configuration Pragmas
11218 @chapter Configuration Pragmas
11219 @cindex Configuration pragmas
11220 @cindex Pragmas, configuration
11221
11222 @noindent
11223 Configuration pragmas include those pragmas described as
11224 such in the Ada Reference Manual, as well as
11225 implementation-dependent pragmas that are configuration pragmas.
11226 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11227 for details on these additional GNAT-specific configuration pragmas.
11228 Most notably, the pragma @code{Source_File_Name}, which allows
11229 specifying non-default names for source files, is a configuration
11230 pragma. The following is a complete list of configuration pragmas
11231 recognized by GNAT:
11232
11233 @smallexample
11234 Ada_83
11235 Ada_95
11236 Ada_05
11237 Ada_2005
11238 Assertion_Policy
11239 C_Pass_By_Copy
11240 Check_Name
11241 Check_Policy
11242 Compile_Time_Error
11243 Compile_Time_Warning
11244 Compiler_Unit
11245 Component_Alignment
11246 Debug_Policy
11247 Detect_Blocking
11248 Discard_Names
11249 Elaboration_Checks
11250 Eliminate
11251 Extend_System
11252 External_Name_Casing
11253 Fast_Math
11254 Favor_Top_Level
11255 Float_Representation
11256 Implicit_Packing
11257 Initialize_Scalars
11258 Interrupt_State
11259 License
11260 Locking_Policy
11261 Long_Float
11262 No_Run_Time
11263 No_Strict_Aliasing
11264 Normalize_Scalars
11265 Optimize_Alignment
11266 Persistent_BSS
11267 Polling
11268 Priority_Specific_Dispatching
11269 Profile
11270 Profile_Warnings
11271 Propagate_Exceptions
11272 Queuing_Policy
11273 Ravenscar
11274 Restricted_Run_Time
11275 Restrictions
11276 Restrictions_Warnings
11277 Reviewable
11278 Source_File_Name
11279 Source_File_Name_Project
11280 Style_Checks
11281 Suppress
11282 Suppress_Exception_Locations
11283 Task_Dispatching_Policy
11284 Universal_Data
11285 Unsuppress
11286 Use_VADS_Size
11287 Validity_Checks
11288 Warnings
11289 Wide_Character_Encoding
11290
11291 @end smallexample
11292
11293 @menu
11294 * Handling of Configuration Pragmas::
11295 * The Configuration Pragmas Files::
11296 @end menu
11297
11298 @node Handling of Configuration Pragmas
11299 @section Handling of Configuration Pragmas
11300
11301 Configuration pragmas may either appear at the start of a compilation
11302 unit, in which case they apply only to that unit, or they may apply to
11303 all compilations performed in a given compilation environment.
11304
11305 GNAT also provides the @code{gnatchop} utility to provide an automatic
11306 way to handle configuration pragmas following the semantics for
11307 compilations (that is, files with multiple units), described in the RM.
11308 See @ref{Operating gnatchop in Compilation Mode} for details.
11309 However, for most purposes, it will be more convenient to edit the
11310 @file{gnat.adc} file that contains configuration pragmas directly,
11311 as described in the following section.
11312
11313 @node The Configuration Pragmas Files
11314 @section The Configuration Pragmas Files
11315 @cindex @file{gnat.adc}
11316
11317 @noindent
11318 In GNAT a compilation environment is defined by the current
11319 directory at the time that a compile command is given. This current
11320 directory is searched for a file whose name is @file{gnat.adc}. If
11321 this file is present, it is expected to contain one or more
11322 configuration pragmas that will be applied to the current compilation.
11323 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11324 considered.
11325
11326 Configuration pragmas may be entered into the @file{gnat.adc} file
11327 either by running @code{gnatchop} on a source file that consists only of
11328 configuration pragmas, or more conveniently by
11329 direct editing of the @file{gnat.adc} file, which is a standard format
11330 source file.
11331
11332 In addition to @file{gnat.adc}, additional files containing configuration
11333 pragmas may be applied to the current compilation using the switch
11334 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11335 contains only configuration pragmas. These configuration pragmas are
11336 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11337 is present and switch @option{-gnatA} is not used).
11338
11339 It is allowed to specify several switches @option{-gnatec}, all of which
11340 will be taken into account.
11341
11342 If you are using project file, a separate mechanism is provided using
11343 project attributes, see @ref{Specifying Configuration Pragmas} for more
11344 details.
11345
11346 @ifset vms
11347 Of special interest to GNAT OpenVMS Alpha is the following
11348 configuration pragma:
11349
11350 @smallexample @c ada
11351 @cartouche
11352 pragma Extend_System (Aux_DEC);
11353 @end cartouche
11354 @end smallexample
11355
11356 @noindent
11357 In the presence of this pragma, GNAT adds to the definition of the
11358 predefined package SYSTEM all the additional types and subprograms that are
11359 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11360 @end ifset
11361
11362 @node Handling Arbitrary File Naming Conventions Using gnatname
11363 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11364 @cindex Arbitrary File Naming Conventions
11365
11366 @menu
11367 * Arbitrary File Naming Conventions::
11368 * Running gnatname::
11369 * Switches for gnatname::
11370 * Examples of gnatname Usage::
11371 @end menu
11372
11373 @node Arbitrary File Naming Conventions
11374 @section Arbitrary File Naming Conventions
11375
11376 @noindent
11377 The GNAT compiler must be able to know the source file name of a compilation
11378 unit. When using the standard GNAT default file naming conventions
11379 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11380 does not need additional information.
11381
11382 @noindent
11383 When the source file names do not follow the standard GNAT default file naming
11384 conventions, the GNAT compiler must be given additional information through
11385 a configuration pragmas file (@pxref{Configuration Pragmas})
11386 or a project file.
11387 When the non-standard file naming conventions are well-defined,
11388 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11389 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11390 if the file naming conventions are irregular or arbitrary, a number
11391 of pragma @code{Source_File_Name} for individual compilation units
11392 must be defined.
11393 To help maintain the correspondence between compilation unit names and
11394 source file names within the compiler,
11395 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11396 set of files.
11397
11398 @node Running gnatname
11399 @section Running @code{gnatname}
11400
11401 @noindent
11402 The usual form of the @code{gnatname} command is
11403
11404 @smallexample
11405 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11406 @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11407 @end smallexample
11408
11409 @noindent
11410 All of the arguments are optional. If invoked without any argument,
11411 @code{gnatname} will display its usage.
11412
11413 @noindent
11414 When used with at least one naming pattern, @code{gnatname} will attempt to
11415 find all the compilation units in files that follow at least one of the
11416 naming patterns. To find these compilation units,
11417 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11418 regular files.
11419
11420 @noindent
11421 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11422 Each Naming Pattern is enclosed between double quotes.
11423 A Naming Pattern is a regular expression similar to the wildcard patterns
11424 used in file names by the Unix shells or the DOS prompt.
11425
11426 @noindent
11427 @code{gnatname} may be called with several sections of directories/patterns.
11428 Sections are separated by switch @code{--and}. In each section, there must be
11429 at least one pattern. If no directory is specified in a section, the current
11430 directory (or the project directory is @code{-P} is used) is implied.
11431 The options other that the directory switches and the patterns apply globally
11432 even if they are in different sections.
11433
11434 @noindent
11435 Examples of Naming Patterns are
11436
11437 @smallexample
11438 "*.[12].ada"
11439 "*.ad[sb]*"
11440 "body_*" "spec_*"
11441 @end smallexample
11442
11443 @noindent
11444 For a more complete description of the syntax of Naming Patterns,
11445 see the second kind of regular expressions described in @file{g-regexp.ads}
11446 (the ``Glob'' regular expressions).
11447
11448 @noindent
11449 When invoked with no switch @code{-P}, @code{gnatname} will create a
11450 configuration pragmas file @file{gnat.adc} in the current working directory,
11451 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11452 unit.
11453
11454 @node Switches for gnatname
11455 @section Switches for @code{gnatname}
11456
11457 @noindent
11458 Switches for @code{gnatname} must precede any specified Naming Pattern.
11459
11460 @noindent
11461 You may specify any of the following switches to @code{gnatname}:
11462
11463 @table @option
11464 @c !sort!
11465
11466 @item --version
11467 @cindex @option{--version} @command{gnatname}
11468 Display Copyright and version, then exit disregarding all other options.
11469
11470 @item --help
11471 @cindex @option{--help} @command{gnatname}
11472 If @option{--version} was not used, display usage, then exit disregarding
11473 all other options.
11474
11475 @item --and
11476 Start another section of directories/patterns.
11477
11478 @item ^-c^/CONFIG_FILE=^@file{file}
11479 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11480 Create a configuration pragmas file @file{file} (instead of the default
11481 @file{gnat.adc}).
11482 @ifclear vms
11483 There may be zero, one or more space between @option{-c} and
11484 @file{file}.
11485 @end ifclear
11486 @file{file} may include directory information. @file{file} must be
11487 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11488 When a switch @option{^-c^/CONFIG_FILE^} is
11489 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11490
11491 @item ^-d^/SOURCE_DIRS=^@file{dir}
11492 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11493 Look for source files in directory @file{dir}. There may be zero, one or more
11494 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11495 When a switch @option{^-d^/SOURCE_DIRS^}
11496 is specified, the current working directory will not be searched for source
11497 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11498 or @option{^-D^/DIR_FILES^} switch.
11499 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11500 If @file{dir} is a relative path, it is relative to the directory of
11501 the configuration pragmas file specified with switch
11502 @option{^-c^/CONFIG_FILE^},
11503 or to the directory of the project file specified with switch
11504 @option{^-P^/PROJECT_FILE^} or,
11505 if neither switch @option{^-c^/CONFIG_FILE^}
11506 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11507 current working directory. The directory
11508 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11509
11510 @item ^-D^/DIRS_FILE=^@file{file}
11511 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11512 Look for source files in all directories listed in text file @file{file}.
11513 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11514 and @file{file}.
11515 @file{file} must be an existing, readable text file.
11516 Each nonempty line in @file{file} must be a directory.
11517 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11518 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11519 @file{file}.
11520
11521 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11522 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11523 Foreign patterns. Using this switch, it is possible to add sources of languages
11524 other than Ada to the list of sources of a project file.
11525 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11526 For example,
11527 @smallexample
11528 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11529 @end smallexample
11530 @noindent
11531 will look for Ada units in all files with the @file{.ada} extension,
11532 and will add to the list of file for project @file{prj.gpr} the C files
11533 with extension @file{.^c^C^}.
11534
11535 @item ^-h^/HELP^
11536 @cindex @option{^-h^/HELP^} (@code{gnatname})
11537 Output usage (help) information. The output is written to @file{stdout}.
11538
11539 @item ^-P^/PROJECT_FILE=^@file{proj}
11540 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11541 Create or update project file @file{proj}. There may be zero, one or more space
11542 between @option{-P} and @file{proj}. @file{proj} may include directory
11543 information. @file{proj} must be writable.
11544 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11545 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11546 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11547
11548 @item ^-v^/VERBOSE^
11549 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11550 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11551 This includes name of the file written, the name of the directories to search
11552 and, for each file in those directories whose name matches at least one of
11553 the Naming Patterns, an indication of whether the file contains a unit,
11554 and if so the name of the unit.
11555
11556 @item ^-v -v^/VERBOSE /VERBOSE^
11557 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11558 Very Verbose mode. In addition to the output produced in verbose mode,
11559 for each file in the searched directories whose name matches none of
11560 the Naming Patterns, an indication is given that there is no match.
11561
11562 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11563 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11564 Excluded patterns. Using this switch, it is possible to exclude some files
11565 that would match the name patterns. For example,
11566 @smallexample
11567 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11568 @end smallexample
11569 @noindent
11570 will look for Ada units in all files with the @file{.ada} extension,
11571 except those whose names end with @file{_nt.ada}.
11572
11573 @end table
11574
11575 @node Examples of gnatname Usage
11576 @section Examples of @code{gnatname} Usage
11577
11578 @ifset vms
11579 @smallexample
11580 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11581 @end smallexample
11582 @end ifset
11583
11584 @ifclear vms
11585 @smallexample
11586 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11587 @end smallexample
11588 @end ifclear
11589
11590 @noindent
11591 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11592 and be writable. In addition, the directory
11593 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11594 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11595
11596 @ifclear vms
11597 Note the optional spaces after @option{-c} and @option{-d}.
11598 @end ifclear
11599
11600 @smallexample
11601 @ifclear vms
11602 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11603 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11604 @end ifclear
11605 @ifset vms
11606 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11607 /EXCLUDED_PATTERN=*_nt_body.ada
11608 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11609 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11610 @end ifset
11611 @end smallexample
11612
11613 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11614 even in conjunction with one or several switches
11615 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11616 are used in this example.
11617
11618 @c *****************************************
11619 @c * G N A T P r o j e c t M a n a g e r *
11620 @c *****************************************
11621 @node GNAT Project Manager
11622 @chapter GNAT Project Manager
11623
11624 @menu
11625 * Introduction::
11626 * Examples of Project Files::
11627 * Project File Syntax::
11628 * Objects and Sources in Project Files::
11629 * Importing Projects::
11630 * Project Extension::
11631 * Project Hierarchy Extension::
11632 * External References in Project Files::
11633 * Packages in Project Files::
11634 * Variables from Imported Projects::
11635 * Naming Schemes::
11636 * Library Projects::
11637 * Stand-alone Library Projects::
11638 * Switches Related to Project Files::
11639 * Tools Supporting Project Files::
11640 * An Extended Example::
11641 * Project File Complete Syntax::
11642 @end menu
11643
11644 @c ****************
11645 @c * Introduction *
11646 @c ****************
11647
11648 @node Introduction
11649 @section Introduction
11650
11651 @noindent
11652 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11653 you to manage complex builds involving a number of source files, directories,
11654 and compilation options for different system configurations. In particular,
11655 project files allow you to specify:
11656 @itemize @bullet
11657 @item
11658 The directory or set of directories containing the source files, and/or the
11659 names of the specific source files themselves
11660 @item
11661 The directory in which the compiler's output
11662 (@file{ALI} files, object files, tree files) is to be placed
11663 @item
11664 The directory in which the executable programs is to be placed
11665 @item
11666 ^Switch^Switch^ settings for any of the project-enabled tools
11667 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11668 @code{gnatfind}); you can apply these settings either globally or to individual
11669 compilation units.
11670 @item
11671 The source files containing the main subprogram(s) to be built
11672 @item
11673 The source programming language(s) (currently Ada and/or C)
11674 @item
11675 Source file naming conventions; you can specify these either globally or for
11676 individual compilation units
11677 @end itemize
11678
11679 @menu
11680 * Project Files::
11681 @end menu
11682
11683 @node Project Files
11684 @subsection Project Files
11685
11686 @noindent
11687 Project files are written in a syntax close to that of Ada, using familiar
11688 notions such as packages, context clauses, declarations, default values,
11689 assignments, and inheritance. Finally, project files can be built
11690 hierarchically from other project files, simplifying complex system
11691 integration and project reuse.
11692
11693 A @dfn{project} is a specific set of values for various compilation properties.
11694 The settings for a given project are described by means of
11695 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11696 Property values in project files are either strings or lists of strings.
11697 Properties that are not explicitly set receive default values. A project
11698 file may interrogate the values of @dfn{external variables} (user-defined
11699 command-line switches or environment variables), and it may specify property
11700 settings conditionally, based on the value of such variables.
11701
11702 In simple cases, a project's source files depend only on other source files
11703 in the same project, or on the predefined libraries. (@emph{Dependence} is
11704 used in
11705 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11706 the Project Manager also allows more sophisticated arrangements,
11707 where the source files in one project depend on source files in other
11708 projects:
11709 @itemize @bullet
11710 @item
11711 One project can @emph{import} other projects containing needed source files.
11712 @item
11713 You can organize GNAT projects in a hierarchy: a @emph{child} project
11714 can extend a @emph{parent} project, inheriting the parent's source files and
11715 optionally overriding any of them with alternative versions
11716 @end itemize
11717
11718 @noindent
11719 More generally, the Project Manager lets you structure large development
11720 efforts into hierarchical subsystems, where build decisions are delegated
11721 to the subsystem level, and thus different compilation environments
11722 (^switch^switch^ settings) used for different subsystems.
11723
11724 The Project Manager is invoked through the
11725 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11726 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11727 @ifclear vms
11728 There may be zero, one or more spaces between @option{-P} and
11729 @option{@emph{projectfile}}.
11730 @end ifclear
11731 If you want to define (on the command line) an external variable that is
11732 queried by the project file, you must use the
11733 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11734 The Project Manager parses and interprets the project file, and drives the
11735 invoked tool based on the project settings.
11736
11737 The Project Manager supports a wide range of development strategies,
11738 for systems of all sizes. Here are some typical practices that are
11739 easily handled:
11740 @itemize @bullet
11741 @item
11742 Using a common set of source files, but generating object files in different
11743 directories via different ^switch^switch^ settings
11744 @item
11745 Using a mostly-shared set of source files, but with different versions of
11746 some unit or units
11747 @end itemize
11748
11749 @noindent
11750 The destination of an executable can be controlled inside a project file
11751 using the @option{^-o^-o^}
11752 ^switch^switch^.
11753 In the absence of such a ^switch^switch^ either inside
11754 the project file or on the command line, any executable files generated by
11755 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11756 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11757 in the object directory of the project.
11758
11759 You can use project files to achieve some of the effects of a source
11760 versioning system (for example, defining separate projects for
11761 the different sets of sources that comprise different releases) but the
11762 Project Manager is independent of any source configuration management tools
11763 that might be used by the developers.
11764
11765 The next section introduces the main features of GNAT's project facility
11766 through a sequence of examples; subsequent sections will present the syntax
11767 and semantics in more detail. A more formal description of the project
11768 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11769 Reference Manual}.
11770
11771 @c *****************************
11772 @c * Examples of Project Files *
11773 @c *****************************
11774
11775 @node Examples of Project Files
11776 @section Examples of Project Files
11777 @noindent
11778 This section illustrates some of the typical uses of project files and
11779 explains their basic structure and behavior.
11780
11781 @menu
11782 * Common Sources with Different ^Switches^Switches^ and Directories::
11783 * Using External Variables::
11784 * Importing Other Projects::
11785 * Extending a Project::
11786 @end menu
11787
11788 @node Common Sources with Different ^Switches^Switches^ and Directories
11789 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11790
11791 @menu
11792 * Source Files::
11793 * Specifying the Object Directory::
11794 * Specifying the Exec Directory::
11795 * Project File Packages::
11796 * Specifying ^Switch^Switch^ Settings::
11797 * Main Subprograms::
11798 * Executable File Names::
11799 * Source File Naming Conventions::
11800 * Source Language(s)::
11801 @end menu
11802
11803 @noindent
11804 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11805 @file{proc.adb} are in the @file{/common} directory. The file
11806 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11807 package @code{Pack}. We want to compile these source files under two sets
11808 of ^switches^switches^:
11809 @itemize @bullet
11810 @item
11811 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11812 and the @option{^-gnata^-gnata^},
11813 @option{^-gnato^-gnato^},
11814 and @option{^-gnatE^-gnatE^} switches to the
11815 compiler; the compiler's output is to appear in @file{/common/debug}
11816 @item
11817 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11818 to the compiler; the compiler's output is to appear in @file{/common/release}
11819 @end itemize
11820
11821 @noindent
11822 The GNAT project files shown below, respectively @file{debug.gpr} and
11823 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11824
11825 Schematically:
11826 @smallexample
11827 @group
11828 ^/common^[COMMON]^
11829 debug.gpr
11830 release.gpr
11831 pack.ads
11832 pack.adb
11833 proc.adb
11834 @end group
11835 @group
11836 ^/common/debug^[COMMON.DEBUG]^
11837 proc.ali, proc.o
11838 pack.ali, pack.o
11839 @end group
11840 @group
11841 ^/common/release^[COMMON.RELEASE]^
11842 proc.ali, proc.o
11843 pack.ali, pack.o
11844 @end group
11845 @end smallexample
11846 Here are the corresponding project files:
11847
11848 @smallexample @c projectfile
11849 @group
11850 project Debug is
11851 for Object_Dir use "debug";
11852 for Main use ("proc");
11853
11854 package Builder is
11855 for ^Default_Switches^Default_Switches^ ("Ada")
11856 use ("^-g^-g^");
11857 for Executable ("proc.adb") use "proc1";
11858 end Builder;
11859 @end group
11860
11861 @group
11862 package Compiler is
11863 for ^Default_Switches^Default_Switches^ ("Ada")
11864 use ("-fstack-check",
11865 "^-gnata^-gnata^",
11866 "^-gnato^-gnato^",
11867 "^-gnatE^-gnatE^");
11868 end Compiler;
11869 end Debug;
11870 @end group
11871 @end smallexample
11872
11873 @smallexample @c projectfile
11874 @group
11875 project Release is
11876 for Object_Dir use "release";
11877 for Exec_Dir use ".";
11878 for Main use ("proc");
11879
11880 package Compiler is
11881 for ^Default_Switches^Default_Switches^ ("Ada")
11882 use ("^-O2^-O2^");
11883 end Compiler;
11884 end Release;
11885 @end group
11886 @end smallexample
11887
11888 @noindent
11889 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11890 insensitive), and analogously the project defined by @file{release.gpr} is
11891 @code{"Release"}. For consistency the file should have the same name as the
11892 project, and the project file's extension should be @code{"gpr"}. These
11893 conventions are not required, but a warning is issued if they are not followed.
11894
11895 If the current directory is @file{^/temp^[TEMP]^}, then the command
11896 @smallexample
11897 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11898 @end smallexample
11899
11900 @noindent
11901 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11902 as well as the @code{^proc1^PROC1.EXE^} executable,
11903 using the ^switch^switch^ settings defined in the project file.
11904
11905 Likewise, the command
11906 @smallexample
11907 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11908 @end smallexample
11909
11910 @noindent
11911 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11912 and the @code{^proc^PROC.EXE^}
11913 executable in @file{^/common^[COMMON]^},
11914 using the ^switch^switch^ settings from the project file.
11915
11916 @node Source Files
11917 @unnumberedsubsubsec Source Files
11918
11919 @noindent
11920 If a project file does not explicitly specify a set of source directories or
11921 a set of source files, then by default the project's source files are the
11922 Ada source files in the project file directory. Thus @file{pack.ads},
11923 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11924
11925 @node Specifying the Object Directory
11926 @unnumberedsubsubsec Specifying the Object Directory
11927
11928 @noindent
11929 Several project properties are modeled by Ada-style @emph{attributes};
11930 a property is defined by supplying the equivalent of an Ada attribute
11931 definition clause in the project file.
11932 A project's object directory is another such a property; the corresponding
11933 attribute is @code{Object_Dir}, and its value is also a string expression,
11934 specified either as absolute or relative. In the later case,
11935 it is relative to the project file directory. Thus the compiler's
11936 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11937 (for the @code{Debug} project)
11938 and to @file{^/common/release^[COMMON.RELEASE]^}
11939 (for the @code{Release} project).
11940 If @code{Object_Dir} is not specified, then the default is the project file
11941 directory itself.
11942
11943 @node Specifying the Exec Directory
11944 @unnumberedsubsubsec Specifying the Exec Directory
11945
11946 @noindent
11947 A project's exec directory is another property; the corresponding
11948 attribute is @code{Exec_Dir}, and its value is also a string expression,
11949 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11950 then the default is the object directory (which may also be the project file
11951 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11952 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11953 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11954 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11955
11956 @node Project File Packages
11957 @unnumberedsubsubsec Project File Packages
11958
11959 @noindent
11960 A GNAT tool that is integrated with the Project Manager is modeled by a
11961 corresponding package in the project file. In the example above,
11962 The @code{Debug} project defines the packages @code{Builder}
11963 (for @command{gnatmake}) and @code{Compiler};
11964 the @code{Release} project defines only the @code{Compiler} package.
11965
11966 The Ada-like package syntax is not to be taken literally. Although packages in
11967 project files bear a surface resemblance to packages in Ada source code, the
11968 notation is simply a way to convey a grouping of properties for a named
11969 entity. Indeed, the package names permitted in project files are restricted
11970 to a predefined set, corresponding to the project-aware tools, and the contents
11971 of packages are limited to a small set of constructs.
11972 The packages in the example above contain attribute definitions.
11973
11974 @node Specifying ^Switch^Switch^ Settings
11975 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11976
11977 @noindent
11978 ^Switch^Switch^ settings for a project-aware tool can be specified through
11979 attributes in the package that corresponds to the tool.
11980 The example above illustrates one of the relevant attributes,
11981 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11982 in both project files.
11983 Unlike simple attributes like @code{Source_Dirs},
11984 @code{^Default_Switches^Default_Switches^} is
11985 known as an @emph{associative array}. When you define this attribute, you must
11986 supply an ``index'' (a literal string), and the effect of the attribute
11987 definition is to set the value of the array at the specified index.
11988 For the @code{^Default_Switches^Default_Switches^} attribute,
11989 the index is a programming language (in our case, Ada),
11990 and the value specified (after @code{use}) must be a list
11991 of string expressions.
11992
11993 The attributes permitted in project files are restricted to a predefined set.
11994 Some may appear at project level, others in packages.
11995 For any attribute that is an associative array, the index must always be a
11996 literal string, but the restrictions on this string (e.g., a file name or a
11997 language name) depend on the individual attribute.
11998 Also depending on the attribute, its specified value will need to be either a
11999 string or a string list.
12000
12001 In the @code{Debug} project, we set the switches for two tools,
12002 @command{gnatmake} and the compiler, and thus we include the two corresponding
12003 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12004 attribute with index @code{"Ada"}.
12005 Note that the package corresponding to
12006 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
12007 similar, but only includes the @code{Compiler} package.
12008
12009 In project @code{Debug} above, the ^switches^switches^ starting with
12010 @option{-gnat} that are specified in package @code{Compiler}
12011 could have been placed in package @code{Builder}, since @command{gnatmake}
12012 transmits all such ^switches^switches^ to the compiler.
12013
12014 @node Main Subprograms
12015 @unnumberedsubsubsec Main Subprograms
12016
12017 @noindent
12018 One of the specifiable properties of a project is a list of files that contain
12019 main subprograms. This property is captured in the @code{Main} attribute,
12020 whose value is a list of strings. If a project defines the @code{Main}
12021 attribute, it is not necessary to identify the main subprogram(s) when
12022 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12023
12024 @node Executable File Names
12025 @unnumberedsubsubsec Executable File Names
12026
12027 @noindent
12028 By default, the executable file name corresponding to a main source is
12029 deduced from the main source file name. Through the attributes
12030 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12031 it is possible to change this default.
12032 In project @code{Debug} above, the executable file name
12033 for main source @file{^proc.adb^PROC.ADB^} is
12034 @file{^proc1^PROC1.EXE^}.
12035 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12036 of the executable files, when no attribute @code{Executable} applies:
12037 its value replace the platform-specific executable suffix.
12038 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12039 specify a non-default executable file name when several mains are built at once
12040 in a single @command{gnatmake} command.
12041
12042 @node Source File Naming Conventions
12043 @unnumberedsubsubsec Source File Naming Conventions
12044
12045 @noindent
12046 Since the project files above do not specify any source file naming
12047 conventions, the GNAT defaults are used. The mechanism for defining source
12048 file naming conventions -- a package named @code{Naming} --
12049 is described below (@pxref{Naming Schemes}).
12050
12051 @node Source Language(s)
12052 @unnumberedsubsubsec Source Language(s)
12053
12054 @noindent
12055 Since the project files do not specify a @code{Languages} attribute, by
12056 default the GNAT tools assume that the language of the project file is Ada.
12057 More generally, a project can comprise source files
12058 in Ada, C, and/or other languages.
12059
12060 @node Using External Variables
12061 @subsection Using External Variables
12062
12063 @noindent
12064 Instead of supplying different project files for debug and release, we can
12065 define a single project file that queries an external variable (set either
12066 on the command line or via an ^environment variable^logical name^) in order to
12067 conditionally define the appropriate settings. Again, assume that the
12068 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12069 located in directory @file{^/common^[COMMON]^}. The following project file,
12070 @file{build.gpr}, queries the external variable named @code{STYLE} and
12071 defines an object directory and ^switch^switch^ settings based on whether
12072 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12073 the default is @code{"deb"}.
12074
12075 @smallexample @c projectfile
12076 @group
12077 project Build is
12078 for Main use ("proc");
12079
12080 type Style_Type is ("deb", "rel");
12081 Style : Style_Type := external ("STYLE", "deb");
12082
12083 case Style is
12084 when "deb" =>
12085 for Object_Dir use "debug";
12086
12087 when "rel" =>
12088 for Object_Dir use "release";
12089 for Exec_Dir use ".";
12090 end case;
12091 @end group
12092
12093 @group
12094 package Builder is
12095
12096 case Style is
12097 when "deb" =>
12098 for ^Default_Switches^Default_Switches^ ("Ada")
12099 use ("^-g^-g^");
12100 for Executable ("proc") use "proc1";
12101 when others =>
12102 null;
12103 end case;
12104
12105 end Builder;
12106 @end group
12107
12108 @group
12109 package Compiler is
12110
12111 case Style is
12112 when "deb" =>
12113 for ^Default_Switches^Default_Switches^ ("Ada")
12114 use ("^-gnata^-gnata^",
12115 "^-gnato^-gnato^",
12116 "^-gnatE^-gnatE^");
12117
12118 when "rel" =>
12119 for ^Default_Switches^Default_Switches^ ("Ada")
12120 use ("^-O2^-O2^");
12121 end case;
12122
12123 end Compiler;
12124
12125 end Build;
12126 @end group
12127 @end smallexample
12128
12129 @noindent
12130 @code{Style_Type} is an example of a @emph{string type}, which is the project
12131 file analog of an Ada enumeration type but whose components are string literals
12132 rather than identifiers. @code{Style} is declared as a variable of this type.
12133
12134 The form @code{external("STYLE", "deb")} is known as an
12135 @emph{external reference}; its first argument is the name of an
12136 @emph{external variable}, and the second argument is a default value to be
12137 used if the external variable doesn't exist. You can define an external
12138 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12139 or you can use ^an environment variable^a logical name^
12140 as an external variable.
12141
12142 Each @code{case} construct is expanded by the Project Manager based on the
12143 value of @code{Style}. Thus the command
12144 @ifclear vms
12145 @smallexample
12146 gnatmake -P/common/build.gpr -XSTYLE=deb
12147 @end smallexample
12148 @end ifclear
12149
12150 @ifset vms
12151 @smallexample
12152 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12153 @end smallexample
12154 @end ifset
12155
12156 @noindent
12157 is equivalent to the @command{gnatmake} invocation using the project file
12158 @file{debug.gpr} in the earlier example. So is the command
12159 @smallexample
12160 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12161 @end smallexample
12162
12163 @noindent
12164 since @code{"deb"} is the default for @code{STYLE}.
12165
12166 Analogously,
12167
12168 @ifclear vms
12169 @smallexample
12170 gnatmake -P/common/build.gpr -XSTYLE=rel
12171 @end smallexample
12172 @end ifclear
12173
12174 @ifset vms
12175 @smallexample
12176 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12177 @end smallexample
12178 @end ifset
12179
12180 @noindent
12181 is equivalent to the @command{gnatmake} invocation using the project file
12182 @file{release.gpr} in the earlier example.
12183
12184 @node Importing Other Projects
12185 @subsection Importing Other Projects
12186 @cindex @code{ADA_PROJECT_PATH}
12187
12188 @noindent
12189 A compilation unit in a source file in one project may depend on compilation
12190 units in source files in other projects. To compile this unit under
12191 control of a project file, the
12192 dependent project must @emph{import} the projects containing the needed source
12193 files.
12194 This effect is obtained using syntax similar to an Ada @code{with} clause,
12195 but where @code{with}ed entities are strings that denote project files.
12196
12197 As an example, suppose that the two projects @code{GUI_Proj} and
12198 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12199 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12200 and @file{^/comm^[COMM]^}, respectively.
12201 Suppose that the source files for @code{GUI_Proj} are
12202 @file{gui.ads} and @file{gui.adb}, and that the source files for
12203 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12204 files is located in its respective project file directory. Schematically:
12205
12206 @smallexample
12207 @group
12208 ^/gui^[GUI]^
12209 gui_proj.gpr
12210 gui.ads
12211 gui.adb
12212 @end group
12213
12214 @group
12215 ^/comm^[COMM]^
12216 comm_proj.gpr
12217 comm.ads
12218 comm.adb
12219 @end group
12220 @end smallexample
12221
12222 @noindent
12223 We want to develop an application in directory @file{^/app^[APP]^} that
12224 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12225 the corresponding project files (e.g.@: the ^switch^switch^ settings
12226 and object directory).
12227 Skeletal code for a main procedure might be something like the following:
12228
12229 @smallexample @c ada
12230 @group
12231 with GUI, Comm;
12232 procedure App_Main is
12233 @dots{}
12234 begin
12235 @dots{}
12236 end App_Main;
12237 @end group
12238 @end smallexample
12239
12240 @noindent
12241 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12242 effect:
12243
12244 @smallexample @c projectfile
12245 @group
12246 with "/gui/gui_proj", "/comm/comm_proj";
12247 project App_Proj is
12248 for Main use ("app_main");
12249 end App_Proj;
12250 @end group
12251 @end smallexample
12252
12253 @noindent
12254 Building an executable is achieved through the command:
12255 @smallexample
12256 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12257 @end smallexample
12258 @noindent
12259 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12260 in the directory where @file{app_proj.gpr} resides.
12261
12262 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12263 (as illustrated above) the @code{with} clause can omit the extension.
12264
12265 Our example specified an absolute path for each imported project file.
12266 Alternatively, the directory name of an imported object can be omitted
12267 if either
12268 @itemize @bullet
12269 @item
12270 The imported project file is in the same directory as the importing project
12271 file, or
12272 @item
12273 You have defined ^an environment variable^a logical name^
12274 that includes the directory containing
12275 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12276 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12277 directory names separated by colons (semicolons on Windows).
12278 @end itemize
12279
12280 @noindent
12281 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12282 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12283 as follows:
12284
12285 @smallexample @c projectfile
12286 @group
12287 with "gui_proj", "comm_proj";
12288 project App_Proj is
12289 for Main use ("app_main");
12290 end App_Proj;
12291 @end group
12292 @end smallexample
12293
12294 @noindent
12295 Importing other projects can create ambiguities.
12296 For example, the same unit might be present in different imported projects, or
12297 it might be present in both the importing project and in an imported project.
12298 Both of these conditions are errors. Note that in the current version of
12299 the Project Manager, it is illegal to have an ambiguous unit even if the
12300 unit is never referenced by the importing project. This restriction may be
12301 relaxed in a future release.
12302
12303 @node Extending a Project
12304 @subsection Extending a Project
12305
12306 @noindent
12307 In large software systems it is common to have multiple
12308 implementations of a common interface; in Ada terms, multiple versions of a
12309 package body for the same spec. For example, one implementation
12310 might be safe for use in tasking programs, while another might only be used
12311 in sequential applications. This can be modeled in GNAT using the concept
12312 of @emph{project extension}. If one project (the ``child'') @emph{extends}
12313 another project (the ``parent'') then by default all source files of the
12314 parent project are inherited by the child, but the child project can
12315 override any of the parent's source files with new versions, and can also
12316 add new files. This facility is the project analog of a type extension in
12317 Object-Oriented Programming. Project hierarchies are permitted (a child
12318 project may be the parent of yet another project), and a project that
12319 inherits one project can also import other projects.
12320
12321 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12322 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12323 @file{pack.adb}, and @file{proc.adb}:
12324
12325 @smallexample
12326 @group
12327 ^/seq^[SEQ]^
12328 pack.ads
12329 pack.adb
12330 proc.adb
12331 seq_proj.gpr
12332 @end group
12333 @end smallexample
12334
12335 @noindent
12336 Note that the project file can simply be empty (that is, no attribute or
12337 package is defined):
12338
12339 @smallexample @c projectfile
12340 @group
12341 project Seq_Proj is
12342 end Seq_Proj;
12343 @end group
12344 @end smallexample
12345
12346 @noindent
12347 implying that its source files are all the Ada source files in the project
12348 directory.
12349
12350 Suppose we want to supply an alternate version of @file{pack.adb}, in
12351 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12352 @file{pack.ads} and @file{proc.adb}. We can define a project
12353 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12354
12355 @smallexample
12356 @group
12357 ^/tasking^[TASKING]^
12358 pack.adb
12359 tasking_proj.gpr
12360 @end group
12361
12362 @group
12363 project Tasking_Proj extends "/seq/seq_proj" is
12364 end Tasking_Proj;
12365 @end group
12366 @end smallexample
12367
12368 @noindent
12369 The version of @file{pack.adb} used in a build depends on which project file
12370 is specified.
12371
12372 Note that we could have obtained the desired behavior using project import
12373 rather than project inheritance; a @code{base} project would contain the
12374 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12375 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12376 would import @code{base} and add a different version of @file{pack.adb}. The
12377 choice depends on whether other sources in the original project need to be
12378 overridden. If they do, then project extension is necessary, otherwise,
12379 importing is sufficient.
12380
12381 @noindent
12382 In a project file that extends another project file, it is possible to
12383 indicate that an inherited source is not part of the sources of the extending
12384 project. This is necessary sometimes when a package spec has been overloaded
12385 and no longer requires a body: in this case, it is necessary to indicate that
12386 the inherited body is not part of the sources of the project, otherwise there
12387 will be a compilation error when compiling the spec.
12388
12389 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12390 Its value is a string list: a list of file names. It is also possible to use
12391 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12392 the file name of a text file containing a list of file names, one per line.
12393
12394 @smallexample @c @projectfile
12395 project B extends "a" is
12396 for Source_Files use ("pkg.ads");
12397 -- New spec of Pkg does not need a completion
12398 for Excluded_Source_Files use ("pkg.adb");
12399 end B;
12400 @end smallexample
12401
12402 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12403 is still needed: if it is possible to build using @command{gnatmake} when such
12404 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12405 it is possible to remove the source completely from a system that includes
12406 project P.
12407
12408 @c ***********************
12409 @c * Project File Syntax *
12410 @c ***********************
12411
12412 @node Project File Syntax
12413 @section Project File Syntax
12414
12415 @menu
12416 * Basic Syntax::
12417 * Qualified Projects::
12418 * Packages::
12419 * Expressions::
12420 * String Types::
12421 * Variables::
12422 * Attributes::
12423 * Associative Array Attributes::
12424 * case Constructions::
12425 @end menu
12426
12427 @noindent
12428 This section describes the structure of project files.
12429
12430 A project may be an @emph{independent project}, entirely defined by a single
12431 project file. Any Ada source file in an independent project depends only
12432 on the predefined library and other Ada source files in the same project.
12433
12434 @noindent
12435 A project may also @dfn{depend on} other projects, in either or both of
12436 the following ways:
12437 @itemize @bullet
12438 @item It may import any number of projects
12439 @item It may extend at most one other project
12440 @end itemize
12441
12442 @noindent
12443 The dependence relation is a directed acyclic graph (the subgraph reflecting
12444 the ``extends'' relation is a tree).
12445
12446 A project's @dfn{immediate sources} are the source files directly defined by
12447 that project, either implicitly by residing in the project file's directory,
12448 or explicitly through any of the source-related attributes described below.
12449 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12450 of @var{proj} together with the immediate sources (unless overridden) of any
12451 project on which @var{proj} depends (either directly or indirectly).
12452
12453 @node Basic Syntax
12454 @subsection Basic Syntax
12455
12456 @noindent
12457 As seen in the earlier examples, project files have an Ada-like syntax.
12458 The minimal project file is:
12459 @smallexample @c projectfile
12460 @group
12461 project Empty is
12462
12463 end Empty;
12464 @end group
12465 @end smallexample
12466
12467 @noindent
12468 The identifier @code{Empty} is the name of the project.
12469 This project name must be present after the reserved
12470 word @code{end} at the end of the project file, followed by a semi-colon.
12471
12472 Any name in a project file, such as the project name or a variable name,
12473 has the same syntax as an Ada identifier.
12474
12475 The reserved words of project files are the Ada 95 reserved words plus
12476 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
12477 reserved words currently used in project file syntax are:
12478
12479 @itemize @bullet
12480 @item
12481 @code{all}
12482 @item
12483 @code{at}
12484 @item
12485 @code{case}
12486 @item
12487 @code{end}
12488 @item
12489 @code{for}
12490 @item
12491 @code{is}
12492 @item
12493 @code{limited}
12494 @item
12495 @code{null}
12496 @item
12497 @code{others}
12498 @item
12499 @code{package}
12500 @item
12501 @code{renames}
12502 @item
12503 @code{type}
12504 @item
12505 @code{use}
12506 @item
12507 @code{when}
12508 @item
12509 @code{with}
12510 @end itemize
12511
12512 @noindent
12513 Comments in project files have the same syntax as in Ada, two consecutive
12514 hyphens through the end of the line.
12515
12516 @node Qualified Projects
12517 @subsection Qualified Projects
12518
12519 @noindent
12520 Before the reserved @code{project}, there may be one or two "qualifiers", that
12521 is identifiers or other reserved words, to qualify the project.
12522
12523 The current list of qualifiers is:
12524
12525 @itemize @bullet
12526 @item
12527 @code{abstract}: qualify a project with no sources. An abstract project must
12528 have a declaration specifying that there are no sources in the project, and,
12529 if it extends another project, the project it extends must also be a qualified
12530 abstract project.
12531
12532 @item
12533 @code{standard}: a standard project is a non library project with sources.
12534
12535 @item
12536 @code{aggregate}: for future extension
12537
12538 @item
12539 @code{aggregate library}: for future extension
12540
12541 @item
12542 @code{library}: a library project must declare both attributes
12543 @code{Library_Name} and @code{Library_Dir}.
12544
12545 @item
12546 @code{configuration}: a configuration project cannot be in a project tree.
12547 @end itemize
12548
12549 @node Packages
12550 @subsection Packages
12551
12552 @noindent
12553 A project file may contain @emph{packages}. The name of a package must be one
12554 of the identifiers from the following list. A package
12555 with a given name may only appear once in a project file. Package names are
12556 case insensitive. The following package names are legal:
12557
12558 @itemize @bullet
12559 @item
12560 @code{Naming}
12561 @item
12562 @code{Builder}
12563 @item
12564 @code{Compiler}
12565 @item
12566 @code{Binder}
12567 @item
12568 @code{Linker}
12569 @item
12570 @code{Finder}
12571 @item
12572 @code{Cross_Reference}
12573 @item
12574 @code{Eliminate}
12575 @item
12576 @code{Pretty_Printer}
12577 @item
12578 @code{Metrics}
12579 @item
12580 @code{gnatls}
12581 @item
12582 @code{gnatstub}
12583 @item
12584 @code{IDE}
12585 @item
12586 @code{Language_Processing}
12587 @end itemize
12588
12589 @noindent
12590 In its simplest form, a package may be empty:
12591
12592 @smallexample @c projectfile
12593 @group
12594 project Simple is
12595 package Builder is
12596 end Builder;
12597 end Simple;
12598 @end group
12599 @end smallexample
12600
12601 @noindent
12602 A package may contain @emph{attribute declarations},
12603 @emph{variable declarations} and @emph{case constructions}, as will be
12604 described below.
12605
12606 When there is ambiguity between a project name and a package name,
12607 the name always designates the project. To avoid possible confusion, it is
12608 always a good idea to avoid naming a project with one of the
12609 names allowed for packages or any name that starts with @code{gnat}.
12610
12611 @node Expressions
12612 @subsection Expressions
12613
12614 @noindent
12615 An @emph{expression} is either a @emph{string expression} or a
12616 @emph{string list expression}.
12617
12618 A @emph{string expression} is either a @emph{simple string expression} or a
12619 @emph{compound string expression}.
12620
12621 A @emph{simple string expression} is one of the following:
12622 @itemize @bullet
12623 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12624 @item A string-valued variable reference (@pxref{Variables})
12625 @item A string-valued attribute reference (@pxref{Attributes})
12626 @item An external reference (@pxref{External References in Project Files})
12627 @end itemize
12628
12629 @noindent
12630 A @emph{compound string expression} is a concatenation of string expressions,
12631 using the operator @code{"&"}
12632 @smallexample
12633 Path & "/" & File_Name & ".ads"
12634 @end smallexample
12635
12636 @noindent
12637 A @emph{string list expression} is either a
12638 @emph{simple string list expression} or a
12639 @emph{compound string list expression}.
12640
12641 A @emph{simple string list expression} is one of the following:
12642 @itemize @bullet
12643 @item A parenthesized list of zero or more string expressions,
12644 separated by commas
12645 @smallexample
12646 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12647 Empty_List := ();
12648 @end smallexample
12649 @item A string list-valued variable reference
12650 @item A string list-valued attribute reference
12651 @end itemize
12652
12653 @noindent
12654 A @emph{compound string list expression} is the concatenation (using
12655 @code{"&"}) of a simple string list expression and an expression. Note that
12656 each term in a compound string list expression, except the first, may be
12657 either a string expression or a string list expression.
12658
12659 @smallexample @c projectfile
12660 @group
12661 File_Name_List := () & File_Name; -- One string in this list
12662 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12663 -- Two strings
12664 Big_List := File_Name_List & Extended_File_Name_List;
12665 -- Concatenation of two string lists: three strings
12666 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12667 -- Illegal: must start with a string list
12668 @end group
12669 @end smallexample
12670
12671 @node String Types
12672 @subsection String Types
12673
12674 @noindent
12675 A @emph{string type declaration} introduces a discrete set of string literals.
12676 If a string variable is declared to have this type, its value
12677 is restricted to the given set of literals.
12678
12679 Here is an example of a string type declaration:
12680
12681 @smallexample @c projectfile
12682 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12683 @end smallexample
12684
12685 @noindent
12686 Variables of a string type are called @emph{typed variables}; all other
12687 variables are called @emph{untyped variables}. Typed variables are
12688 particularly useful in @code{case} constructions, to support conditional
12689 attribute declarations.
12690 (@pxref{case Constructions}).
12691
12692 The string literals in the list are case sensitive and must all be different.
12693 They may include any graphic characters allowed in Ada, including spaces.
12694
12695 A string type may only be declared at the project level, not inside a package.
12696
12697 A string type may be referenced by its name if it has been declared in the same
12698 project file, or by an expanded name whose prefix is the name of the project
12699 in which it is declared.
12700
12701 @node Variables
12702 @subsection Variables
12703
12704 @noindent
12705 A variable may be declared at the project file level, or within a package.
12706 Here are some examples of variable declarations:
12707
12708 @smallexample @c projectfile
12709 @group
12710 This_OS : OS := external ("OS"); -- a typed variable declaration
12711 That_OS := "GNU/Linux"; -- an untyped variable declaration
12712 @end group
12713 @end smallexample
12714
12715 @noindent
12716 The syntax of a @emph{typed variable declaration} is identical to the Ada
12717 syntax for an object declaration. By contrast, the syntax of an untyped
12718 variable declaration is identical to an Ada assignment statement. In fact,
12719 variable declarations in project files have some of the characteristics of
12720 an assignment, in that successive declarations for the same variable are
12721 allowed. Untyped variable declarations do establish the expected kind of the
12722 variable (string or string list), and successive declarations for it must
12723 respect the initial kind.
12724
12725 @noindent
12726 A string variable declaration (typed or untyped) declares a variable
12727 whose value is a string. This variable may be used as a string expression.
12728 @smallexample @c projectfile
12729 File_Name := "readme.txt";
12730 Saved_File_Name := File_Name & ".saved";
12731 @end smallexample
12732
12733 @noindent
12734 A string list variable declaration declares a variable whose value is a list
12735 of strings. The list may contain any number (zero or more) of strings.
12736
12737 @smallexample @c projectfile
12738 Empty_List := ();
12739 List_With_One_Element := ("^-gnaty^-gnaty^");
12740 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12741 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12742 "pack2.ada", "util_.ada", "util.ada");
12743 @end smallexample
12744
12745 @noindent
12746 The same typed variable may not be declared more than once at project level,
12747 and it may not be declared more than once in any package; it is in effect
12748 a constant.
12749
12750 The same untyped variable may be declared several times. Declarations are
12751 elaborated in the order in which they appear, so the new value replaces
12752 the old one, and any subsequent reference to the variable uses the new value.
12753 However, as noted above, if a variable has been declared as a string, all
12754 subsequent
12755 declarations must give it a string value. Similarly, if a variable has
12756 been declared as a string list, all subsequent declarations
12757 must give it a string list value.
12758
12759 A @emph{variable reference} may take several forms:
12760
12761 @itemize @bullet
12762 @item The simple variable name, for a variable in the current package (if any)
12763 or in the current project
12764 @item An expanded name, whose prefix is a context name.
12765 @end itemize
12766
12767 @noindent
12768 A @emph{context} may be one of the following:
12769
12770 @itemize @bullet
12771 @item The name of an existing package in the current project
12772 @item The name of an imported project of the current project
12773 @item The name of an ancestor project (i.e., a project extended by the current
12774 project, either directly or indirectly)
12775 @item An expanded name whose prefix is an imported/parent project name, and
12776 whose selector is a package name in that project.
12777 @end itemize
12778
12779 @noindent
12780 A variable reference may be used in an expression.
12781
12782 @node Attributes
12783 @subsection Attributes
12784
12785 @noindent
12786 A project (and its packages) may have @emph{attributes} that define
12787 the project's properties. Some attributes have values that are strings;
12788 others have values that are string lists.
12789
12790 There are two categories of attributes: @emph{simple attributes}
12791 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12792
12793 Legal project attribute names, and attribute names for each legal package are
12794 listed below. Attributes names are case-insensitive.
12795
12796 The following attributes are defined on projects (all are simple attributes):
12797
12798 @multitable @columnfractions .4 .3
12799 @item @emph{Attribute Name}
12800 @tab @emph{Value}
12801 @item @code{Source_Files}
12802 @tab string list
12803 @item @code{Source_Dirs}
12804 @tab string list
12805 @item @code{Source_List_File}
12806 @tab string
12807 @item @code{Object_Dir}
12808 @tab string
12809 @item @code{Exec_Dir}
12810 @tab string
12811 @item @code{Excluded_Source_Dirs}
12812 @tab string list
12813 @item @code{Excluded_Source_Files}
12814 @tab string list
12815 @item @code{Excluded_Source_List_File}
12816 @tab string
12817 @item @code{Languages}
12818 @tab string list
12819 @item @code{Main}
12820 @tab string list
12821 @item @code{Library_Dir}
12822 @tab string
12823 @item @code{Library_Name}
12824 @tab string
12825 @item @code{Library_Kind}
12826 @tab string
12827 @item @code{Library_Version}
12828 @tab string
12829 @item @code{Library_Interface}
12830 @tab string
12831 @item @code{Library_Auto_Init}
12832 @tab string
12833 @item @code{Library_Options}
12834 @tab string list
12835 @item @code{Library_Src_Dir}
12836 @tab string
12837 @item @code{Library_ALI_Dir}
12838 @tab string
12839 @item @code{Library_GCC}
12840 @tab string
12841 @item @code{Library_Symbol_File}
12842 @tab string
12843 @item @code{Library_Symbol_Policy}
12844 @tab string
12845 @item @code{Library_Reference_Symbol_File}
12846 @tab string
12847 @item @code{Externally_Built}
12848 @tab string
12849 @end multitable
12850
12851 @noindent
12852 The following attributes are defined for package @code{Naming}
12853 (@pxref{Naming Schemes}):
12854
12855 @multitable @columnfractions .4 .2 .2 .2
12856 @item Attribute Name @tab Category @tab Index @tab Value
12857 @item @code{Spec_Suffix}
12858 @tab associative array
12859 @tab language name
12860 @tab string
12861 @item @code{Body_Suffix}
12862 @tab associative array
12863 @tab language name
12864 @tab string
12865 @item @code{Separate_Suffix}
12866 @tab simple attribute
12867 @tab n/a
12868 @tab string
12869 @item @code{Casing}
12870 @tab simple attribute
12871 @tab n/a
12872 @tab string
12873 @item @code{Dot_Replacement}
12874 @tab simple attribute
12875 @tab n/a
12876 @tab string
12877 @item @code{Spec}
12878 @tab associative array
12879 @tab Ada unit name
12880 @tab string
12881 @item @code{Body}
12882 @tab associative array
12883 @tab Ada unit name
12884 @tab string
12885 @item @code{Specification_Exceptions}
12886 @tab associative array
12887 @tab language name
12888 @tab string list
12889 @item @code{Implementation_Exceptions}
12890 @tab associative array
12891 @tab language name
12892 @tab string list
12893 @end multitable
12894
12895 @noindent
12896 The following attributes are defined for packages @code{Builder},
12897 @code{Compiler}, @code{Binder},
12898 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12899 (@pxref{^Switches^Switches^ and Project Files}).
12900
12901 @multitable @columnfractions .4 .2 .2 .2
12902 @item Attribute Name @tab Category @tab Index @tab Value
12903 @item @code{^Default_Switches^Default_Switches^}
12904 @tab associative array
12905 @tab language name
12906 @tab string list
12907 @item @code{^Switches^Switches^}
12908 @tab associative array
12909 @tab file name
12910 @tab string list
12911 @end multitable
12912
12913 @noindent
12914 In addition, package @code{Compiler} has a single string attribute
12915 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12916 string attribute @code{Global_Configuration_Pragmas}.
12917
12918 @noindent
12919 Each simple attribute has a default value: the empty string (for string-valued
12920 attributes) and the empty list (for string list-valued attributes).
12921
12922 An attribute declaration defines a new value for an attribute.
12923
12924 Examples of simple attribute declarations:
12925
12926 @smallexample @c projectfile
12927 for Object_Dir use "objects";
12928 for Source_Dirs use ("units", "test/drivers");
12929 @end smallexample
12930
12931 @noindent
12932 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12933 attribute definition clause in Ada.
12934
12935 Attributes references may be appear in expressions.
12936 The general form for such a reference is @code{<entity>'<attribute>}:
12937 Associative array attributes are functions. Associative
12938 array attribute references must have an argument that is a string literal.
12939
12940 Examples are:
12941
12942 @smallexample @c projectfile
12943 project'Object_Dir
12944 Naming'Dot_Replacement
12945 Imported_Project'Source_Dirs
12946 Imported_Project.Naming'Casing
12947 Builder'^Default_Switches^Default_Switches^("Ada")
12948 @end smallexample
12949
12950 @noindent
12951 The prefix of an attribute may be:
12952 @itemize @bullet
12953 @item @code{project} for an attribute of the current project
12954 @item The name of an existing package of the current project
12955 @item The name of an imported project
12956 @item The name of a parent project that is extended by the current project
12957 @item An expanded name whose prefix is imported/parent project name,
12958 and whose selector is a package name
12959 @end itemize
12960
12961 @noindent
12962 Example:
12963 @smallexample @c projectfile
12964 @group
12965 project Prj is
12966 for Source_Dirs use project'Source_Dirs & "units";
12967 for Source_Dirs use project'Source_Dirs & "test/drivers"
12968 end Prj;
12969 @end group
12970 @end smallexample
12971
12972 @noindent
12973 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12974 has the default value: an empty string list. After this declaration,
12975 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12976 After the second attribute declaration @code{Source_Dirs} is a string list of
12977 two elements: @code{"units"} and @code{"test/drivers"}.
12978
12979 Note: this example is for illustration only. In practice,
12980 the project file would contain only one attribute declaration:
12981
12982 @smallexample @c projectfile
12983 for Source_Dirs use ("units", "test/drivers");
12984 @end smallexample
12985
12986 @node Associative Array Attributes
12987 @subsection Associative Array Attributes
12988
12989 @noindent
12990 Some attributes are defined as @emph{associative arrays}. An associative
12991 array may be regarded as a function that takes a string as a parameter
12992 and delivers a string or string list value as its result.
12993
12994 Here are some examples of single associative array attribute associations:
12995
12996 @smallexample @c projectfile
12997 for Body ("main") use "Main.ada";
12998 for ^Switches^Switches^ ("main.ada")
12999 use ("^-v^-v^",
13000 "^-gnatv^-gnatv^");
13001 for ^Switches^Switches^ ("main.ada")
13002 use Builder'^Switches^Switches^ ("main.ada")
13003 & "^-g^-g^";
13004 @end smallexample
13005
13006 @noindent
13007 Like untyped variables and simple attributes, associative array attributes
13008 may be declared several times. Each declaration supplies a new value for the
13009 attribute, and replaces the previous setting.
13010
13011 @noindent
13012 An associative array attribute may be declared as a full associative array
13013 declaration, with the value of the same attribute in an imported or extended
13014 project.
13015
13016 @smallexample @c projectfile
13017 package Builder is
13018 for Default_Switches use Default.Builder'Default_Switches;
13019 end Builder;
13020 @end smallexample
13021
13022 @noindent
13023 In this example, @code{Default} must be either a project imported by the
13024 current project, or the project that the current project extends. If the
13025 attribute is in a package (in this case, in package @code{Builder}), the same
13026 package needs to be specified.
13027
13028 @noindent
13029 A full associative array declaration replaces any other declaration for the
13030 attribute, including other full associative array declaration. Single
13031 associative array associations may be declare after a full associative
13032 declaration, modifying the value for a single association of the attribute.
13033
13034 @node case Constructions
13035 @subsection @code{case} Constructions
13036
13037 @noindent
13038 A @code{case} construction is used in a project file to effect conditional
13039 behavior.
13040 Here is a typical example:
13041
13042 @smallexample @c projectfile
13043 @group
13044 project MyProj is
13045 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13046
13047 OS : OS_Type := external ("OS", "GNU/Linux");
13048 @end group
13049
13050 @group
13051 package Compiler is
13052 case OS is
13053 when "GNU/Linux" | "Unix" =>
13054 for ^Default_Switches^Default_Switches^ ("Ada")
13055 use ("^-gnath^-gnath^");
13056 when "NT" =>
13057 for ^Default_Switches^Default_Switches^ ("Ada")
13058 use ("^-gnatP^-gnatP^");
13059 when others =>
13060 end case;
13061 end Compiler;
13062 end MyProj;
13063 @end group
13064 @end smallexample
13065
13066 @noindent
13067 The syntax of a @code{case} construction is based on the Ada case statement
13068 (although there is no @code{null} construction for empty alternatives).
13069
13070 The case expression must be a typed string variable.
13071 Each alternative comprises the reserved word @code{when}, either a list of
13072 literal strings separated by the @code{"|"} character or the reserved word
13073 @code{others}, and the @code{"=>"} token.
13074 Each literal string must belong to the string type that is the type of the
13075 case variable.
13076 An @code{others} alternative, if present, must occur last.
13077
13078 After each @code{=>}, there are zero or more constructions. The only
13079 constructions allowed in a case construction are other case constructions,
13080 attribute declarations and variable declarations. String type declarations and
13081 package declarations are not allowed. Variable declarations are restricted to
13082 variables that have already been declared before the case construction.
13083
13084 The value of the case variable is often given by an external reference
13085 (@pxref{External References in Project Files}).
13086
13087 @c ****************************************
13088 @c * Objects and Sources in Project Files *
13089 @c ****************************************
13090
13091 @node Objects and Sources in Project Files
13092 @section Objects and Sources in Project Files
13093
13094 @menu
13095 * Object Directory::
13096 * Exec Directory::
13097 * Source Directories::
13098 * Source File Names::
13099 @end menu
13100
13101 @noindent
13102 Each project has exactly one object directory and one or more source
13103 directories. The source directories must contain at least one source file,
13104 unless the project file explicitly specifies that no source files are present
13105 (@pxref{Source File Names}).
13106
13107 @node Object Directory
13108 @subsection Object Directory
13109
13110 @noindent
13111 The object directory for a project is the directory containing the compiler's
13112 output (such as @file{ALI} files and object files) for the project's immediate
13113 sources.
13114
13115 The object directory is given by the value of the attribute @code{Object_Dir}
13116 in the project file.
13117
13118 @smallexample @c projectfile
13119 for Object_Dir use "objects";
13120 @end smallexample
13121
13122 @noindent
13123 The attribute @code{Object_Dir} has a string value, the path name of the object
13124 directory. The path name may be absolute or relative to the directory of the
13125 project file. This directory must already exist, and be readable and writable.
13126
13127 By default, when the attribute @code{Object_Dir} is not given an explicit value
13128 or when its value is the empty string, the object directory is the same as the
13129 directory containing the project file.
13130
13131 @node Exec Directory
13132 @subsection Exec Directory
13133
13134 @noindent
13135 The exec directory for a project is the directory containing the executables
13136 for the project's main subprograms.
13137
13138 The exec directory is given by the value of the attribute @code{Exec_Dir}
13139 in the project file.
13140
13141 @smallexample @c projectfile
13142 for Exec_Dir use "executables";
13143 @end smallexample
13144
13145 @noindent
13146 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13147 directory. The path name may be absolute or relative to the directory of the
13148 project file. This directory must already exist, and be writable.
13149
13150 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13151 or when its value is the empty string, the exec directory is the same as the
13152 object directory of the project file.
13153
13154 @node Source Directories
13155 @subsection Source Directories
13156
13157 @noindent
13158 The source directories of a project are specified by the project file
13159 attribute @code{Source_Dirs}.
13160
13161 This attribute's value is a string list. If the attribute is not given an
13162 explicit value, then there is only one source directory, the one where the
13163 project file resides.
13164
13165 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13166 as in
13167
13168 @smallexample @c projectfile
13169 for Source_Dirs use ();
13170 @end smallexample
13171
13172 @noindent
13173 indicates that the project contains no source files.
13174
13175 Otherwise, each string in the string list designates one or more
13176 source directories.
13177
13178 @smallexample @c projectfile
13179 for Source_Dirs use ("sources", "test/drivers");
13180 @end smallexample
13181
13182 @noindent
13183 If a string in the list ends with @code{"/**"}, then the directory whose path
13184 name precedes the two asterisks, as well as all its subdirectories
13185 (recursively), are source directories.
13186
13187 @smallexample @c projectfile
13188 for Source_Dirs use ("/system/sources/**");
13189 @end smallexample
13190
13191 @noindent
13192 Here the directory @code{/system/sources} and all of its subdirectories
13193 (recursively) are source directories.
13194
13195 To specify that the source directories are the directory of the project file
13196 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13197 @smallexample @c projectfile
13198 for Source_Dirs use ("./**");
13199 @end smallexample
13200
13201 @noindent
13202 Each of the source directories must exist and be readable.
13203
13204 @node Source File Names
13205 @subsection Source File Names
13206
13207 @noindent
13208 In a project that contains source files, their names may be specified by the
13209 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13210 (a string). Source file names never include any directory information.
13211
13212 If the attribute @code{Source_Files} is given an explicit value, then each
13213 element of the list is a source file name.
13214
13215 @smallexample @c projectfile
13216 for Source_Files use ("main.adb");
13217 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13218 @end smallexample
13219
13220 @noindent
13221 If the attribute @code{Source_Files} is not given an explicit value,
13222 but the attribute @code{Source_List_File} is given a string value,
13223 then the source file names are contained in the text file whose path name
13224 (absolute or relative to the directory of the project file) is the
13225 value of the attribute @code{Source_List_File}.
13226
13227 Each line in the file that is not empty or is not a comment
13228 contains a source file name.
13229
13230 @smallexample @c projectfile
13231 for Source_List_File use "source_list.txt";
13232 @end smallexample
13233
13234 @noindent
13235 By default, if neither the attribute @code{Source_Files} nor the attribute
13236 @code{Source_List_File} is given an explicit value, then each file in the
13237 source directories that conforms to the project's naming scheme
13238 (@pxref{Naming Schemes}) is an immediate source of the project.
13239
13240 A warning is issued if both attributes @code{Source_Files} and
13241 @code{Source_List_File} are given explicit values. In this case, the attribute
13242 @code{Source_Files} prevails.
13243
13244 Each source file name must be the name of one existing source file
13245 in one of the source directories.
13246
13247 A @code{Source_Files} attribute whose value is an empty list
13248 indicates that there are no source files in the project.
13249
13250 If the order of the source directories is known statically, that is if
13251 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13252 be several files with the same source file name. In this case, only the file
13253 in the first directory is considered as an immediate source of the project
13254 file. If the order of the source directories is not known statically, it is
13255 an error to have several files with the same source file name.
13256
13257 Projects can be specified to have no Ada source
13258 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13259 list, or the @code{"Ada"} may be absent from @code{Languages}:
13260
13261 @smallexample @c projectfile
13262 for Source_Dirs use ();
13263 for Source_Files use ();
13264 for Languages use ("C", "C++");
13265 @end smallexample
13266
13267 @noindent
13268 Otherwise, a project must contain at least one immediate source.
13269
13270 Projects with no source files are useful as template packages
13271 (@pxref{Packages in Project Files}) for other projects; in particular to
13272 define a package @code{Naming} (@pxref{Naming Schemes}).
13273
13274 @c ****************************
13275 @c * Importing Projects *
13276 @c ****************************
13277
13278 @node Importing Projects
13279 @section Importing Projects
13280 @cindex @code{ADA_PROJECT_PATH}
13281
13282 @noindent
13283 An immediate source of a project P may depend on source files that
13284 are neither immediate sources of P nor in the predefined library.
13285 To get this effect, P must @emph{import} the projects that contain the needed
13286 source files.
13287
13288 @smallexample @c projectfile
13289 @group
13290 with "project1", "utilities.gpr";
13291 with "/namings/apex.gpr";
13292 project Main is
13293 @dots{}
13294 @end group
13295 @end smallexample
13296
13297 @noindent
13298 As can be seen in this example, the syntax for importing projects is similar
13299 to the syntax for importing compilation units in Ada. However, project files
13300 use literal strings instead of names, and the @code{with} clause identifies
13301 project files rather than packages.
13302
13303 Each literal string is the file name or path name (absolute or relative) of a
13304 project file. If a string corresponds to a file name, with no path or a
13305 relative path, then its location is determined by the @emph{project path}. The
13306 latter can be queried using @code{gnatls -v}. It contains:
13307
13308 @itemize @bullet
13309 @item
13310 In first position, the directory containing the current project file.
13311 @item
13312 In last position, the default project directory. This default project directory
13313 is part of the GNAT installation and is the standard place to install project
13314 files giving access to standard support libraries.
13315 @ifclear vms
13316 @ref{Installing a library}
13317 @end ifclear
13318
13319 @item
13320 In between, all the directories referenced in the
13321 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13322 @end itemize
13323
13324 @noindent
13325 If a relative pathname is used, as in
13326
13327 @smallexample @c projectfile
13328 with "tests/proj";
13329 @end smallexample
13330
13331 @noindent
13332 then the full path for the project is constructed by concatenating this
13333 relative path to those in the project path, in order, until a matching file is
13334 found. Any symbolic link will be fully resolved in the directory of the
13335 importing project file before the imported project file is examined.
13336
13337 If the @code{with}'ed project file name does not have an extension,
13338 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13339 then the file name as specified in the @code{with} clause (no extension) will
13340 be used. In the above example, if a file @code{project1.gpr} is found, then it
13341 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13342 then it will be used; if neither file exists, this is an error.
13343
13344 A warning is issued if the name of the project file does not match the
13345 name of the project; this check is case insensitive.
13346
13347 Any source file that is an immediate source of the imported project can be
13348 used by the immediate sources of the importing project, transitively. Thus
13349 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13350 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13351 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13352 because if and when @code{B} ceases to import @code{C}, some sources in
13353 @code{A} will no longer compile.
13354
13355 A side effect of this capability is that normally cyclic dependencies are not
13356 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13357 is not allowed to import @code{A}. However, there are cases when cyclic
13358 dependencies would be beneficial. For these cases, another form of import
13359 between projects exists, the @code{limited with}: a project @code{A} that
13360 imports a project @code{B} with a straight @code{with} may also be imported,
13361 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13362 to @code{A} include at least one @code{limited with}.
13363
13364 @smallexample @c 0projectfile
13365 with "../b/b.gpr";
13366 with "../c/c.gpr";
13367 project A is
13368 end A;
13369
13370 limited with "../a/a.gpr";
13371 project B is
13372 end B;
13373
13374 with "../d/d.gpr";
13375 project C is
13376 end C;
13377
13378 limited with "../a/a.gpr";
13379 project D is
13380 end D;
13381 @end smallexample
13382
13383 @noindent
13384 In the above legal example, there are two project cycles:
13385 @itemize @bullet
13386 @item A-> B-> A
13387 @item A -> C -> D -> A
13388 @end itemize
13389
13390 @noindent
13391 In each of these cycle there is one @code{limited with}: import of @code{A}
13392 from @code{B} and import of @code{A} from @code{D}.
13393
13394 The difference between straight @code{with} and @code{limited with} is that
13395 the name of a project imported with a @code{limited with} cannot be used in the
13396 project that imports it. In particular, its packages cannot be renamed and
13397 its variables cannot be referred to.
13398
13399 An exception to the above rules for @code{limited with} is that for the main
13400 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13401 @code{limited with} is equivalent to a straight @code{with}. For example,
13402 in the example above, projects @code{B} and @code{D} could not be main
13403 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13404 each have a @code{limited with} that is the only one in a cycle of importing
13405 projects.
13406
13407 @c *********************
13408 @c * Project Extension *
13409 @c *********************
13410
13411 @node Project Extension
13412 @section Project Extension
13413
13414 @noindent
13415 During development of a large system, it is sometimes necessary to use
13416 modified versions of some of the source files, without changing the original
13417 sources. This can be achieved through the @emph{project extension} facility.
13418
13419 @smallexample @c projectfile
13420 project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13421 @end smallexample
13422
13423 @noindent
13424 A project extension declaration introduces an extending project
13425 (the @emph{child}) and a project being extended (the @emph{parent}).
13426
13427 By default, a child project inherits all the sources of its parent.
13428 However, inherited sources can be overridden: a unit in a parent is hidden
13429 by a unit of the same name in the child.
13430
13431 Inherited sources are considered to be sources (but not immediate sources)
13432 of the child project; see @ref{Project File Syntax}.
13433
13434 An inherited source file retains any switches specified in the parent project.
13435
13436 For example if the project @code{Utilities} contains the spec and the
13437 body of an Ada package @code{Util_IO}, then the project
13438 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13439 The original body of @code{Util_IO} will not be considered in program builds.
13440 However, the package spec will still be found in the project
13441 @code{Utilities}.
13442
13443 A child project can have only one parent, except when it is qualified as
13444 abstract. But it may import any number of other projects.
13445
13446 A project is not allowed to import directly or indirectly at the same time a
13447 child project and any of its ancestors.
13448
13449 @c *******************************
13450 @c * Project Hierarchy Extension *
13451 @c *******************************
13452
13453 @node Project Hierarchy Extension
13454 @section Project Hierarchy Extension
13455
13456 @noindent
13457 When extending a large system spanning multiple projects, it is often
13458 inconvenient to extend every project in the hierarchy that is impacted by a
13459 small change introduced. In such cases, it is possible to create a virtual
13460 extension of entire hierarchy using @code{extends all} relationship.
13461
13462 When the project is extended using @code{extends all} inheritance, all projects
13463 that are imported by it, both directly and indirectly, are considered virtually
13464 extended. That is, the Project Manager creates "virtual projects"
13465 that extend every project in the hierarchy; all these virtual projects have
13466 no sources of their own and have as object directory the object directory of
13467 the root of "extending all" project.
13468
13469 It is possible to explicitly extend one or more projects in the hierarchy
13470 in order to modify the sources. These extending projects must be imported by
13471 the "extending all" project, which will replace the corresponding virtual
13472 projects with the explicit ones.
13473
13474 When building such a project hierarchy extension, the Project Manager will
13475 ensure that both modified sources and sources in virtual extending projects
13476 that depend on them, are recompiled.
13477
13478 By means of example, consider the following hierarchy of projects.
13479
13480 @enumerate
13481 @item
13482 project A, containing package P1
13483 @item
13484 project B importing A and containing package P2 which depends on P1
13485 @item
13486 project C importing B and containing package P3 which depends on P2
13487 @end enumerate
13488
13489 @noindent
13490 We want to modify packages P1 and P3.
13491
13492 This project hierarchy will need to be extended as follows:
13493
13494 @enumerate
13495 @item
13496 Create project A1 that extends A, placing modified P1 there:
13497
13498 @smallexample @c 0projectfile
13499 project A1 extends "(@dots{})/A" is
13500 end A1;
13501 @end smallexample
13502
13503 @item
13504 Create project C1 that "extends all" C and imports A1, placing modified
13505 P3 there:
13506
13507 @smallexample @c 0projectfile
13508 with "(@dots{})/A1";
13509 project C1 extends all "(@dots{})/C" is
13510 end C1;
13511 @end smallexample
13512 @end enumerate
13513
13514 When you build project C1, your entire modified project space will be
13515 recompiled, including the virtual project B1 that has been impacted by the
13516 "extending all" inheritance of project C.
13517
13518 Note that if a Library Project in the hierarchy is virtually extended,
13519 the virtual project that extends the Library Project is not a Library Project.
13520
13521 @c ****************************************
13522 @c * External References in Project Files *
13523 @c ****************************************
13524
13525 @node External References in Project Files
13526 @section External References in Project Files
13527
13528 @noindent
13529 A project file may contain references to external variables; such references
13530 are called @emph{external references}.
13531
13532 An external variable is either defined as part of the environment (an
13533 environment variable in Unix, for example) or else specified on the command
13534 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13535 If both, then the command line value is used.
13536
13537 The value of an external reference is obtained by means of the built-in
13538 function @code{external}, which returns a string value.
13539 This function has two forms:
13540 @itemize @bullet
13541 @item @code{external (external_variable_name)}
13542 @item @code{external (external_variable_name, default_value)}
13543 @end itemize
13544
13545 @noindent
13546 Each parameter must be a string literal. For example:
13547
13548 @smallexample @c projectfile
13549 external ("USER")
13550 external ("OS", "GNU/Linux")
13551 @end smallexample
13552
13553 @noindent
13554 In the form with one parameter, the function returns the value of
13555 the external variable given as parameter. If this name is not present in the
13556 environment, the function returns an empty string.
13557
13558 In the form with two string parameters, the second argument is
13559 the value returned when the variable given as the first argument is not
13560 present in the environment. In the example above, if @code{"OS"} is not
13561 the name of ^an environment variable^a logical name^ and is not passed on
13562 the command line, then the returned value is @code{"GNU/Linux"}.
13563
13564 An external reference may be part of a string expression or of a string
13565 list expression, and can therefore appear in a variable declaration or
13566 an attribute declaration.
13567
13568 @smallexample @c projectfile
13569 @group
13570 type Mode_Type is ("Debug", "Release");
13571 Mode : Mode_Type := external ("MODE");
13572 case Mode is
13573 when "Debug" =>
13574 @dots{}
13575 @end group
13576 @end smallexample
13577
13578 @c *****************************
13579 @c * Packages in Project Files *
13580 @c *****************************
13581
13582 @node Packages in Project Files
13583 @section Packages in Project Files
13584
13585 @noindent
13586 A @emph{package} defines the settings for project-aware tools within a
13587 project.
13588 For each such tool one can declare a package; the names for these
13589 packages are preset (@pxref{Packages}).
13590 A package may contain variable declarations, attribute declarations, and case
13591 constructions.
13592
13593 @smallexample @c projectfile
13594 @group
13595 project Proj is
13596 package Builder is -- used by gnatmake
13597 for ^Default_Switches^Default_Switches^ ("Ada")
13598 use ("^-v^-v^",
13599 "^-g^-g^");
13600 end Builder;
13601 end Proj;
13602 @end group
13603 @end smallexample
13604
13605 @noindent
13606 The syntax of package declarations mimics that of package in Ada.
13607
13608 Most of the packages have an attribute
13609 @code{^Default_Switches^Default_Switches^}.
13610 This attribute is an associative array, and its value is a string list.
13611 The index of the associative array is the name of a programming language (case
13612 insensitive). This attribute indicates the ^switch^switch^
13613 or ^switches^switches^ to be used
13614 with the corresponding tool.
13615
13616 Some packages also have another attribute, @code{^Switches^Switches^},
13617 an associative array whose value is a string list.
13618 The index is the name of a source file.
13619 This attribute indicates the ^switch^switch^
13620 or ^switches^switches^ to be used by the corresponding
13621 tool when dealing with this specific file.
13622
13623 Further information on these ^switch^switch^-related attributes is found in
13624 @ref{^Switches^Switches^ and Project Files}.
13625
13626 A package may be declared as a @emph{renaming} of another package; e.g., from
13627 the project file for an imported project.
13628
13629 @smallexample @c projectfile
13630 @group
13631 with "/global/apex.gpr";
13632 project Example is
13633 package Naming renames Apex.Naming;
13634 @dots{}
13635 end Example;
13636 @end group
13637 @end smallexample
13638
13639 @noindent
13640 Packages that are renamed in other project files often come from project files
13641 that have no sources: they are just used as templates. Any modification in the
13642 template will be reflected automatically in all the project files that rename
13643 a package from the template.
13644
13645 In addition to the tool-oriented packages, you can also declare a package
13646 named @code{Naming} to establish specialized source file naming conventions
13647 (@pxref{Naming Schemes}).
13648
13649 @c ************************************
13650 @c * Variables from Imported Projects *
13651 @c ************************************
13652
13653 @node Variables from Imported Projects
13654 @section Variables from Imported Projects
13655
13656 @noindent
13657 An attribute or variable defined in an imported or parent project can
13658 be used in expressions in the importing / extending project.
13659 Such an attribute or variable is denoted by an expanded name whose prefix
13660 is either the name of the project or the expanded name of a package within
13661 a project.
13662
13663 @smallexample @c projectfile
13664 @group
13665 with "imported";
13666 project Main extends "base" is
13667 Var1 := Imported.Var;
13668 Var2 := Base.Var & ".new";
13669 @end group
13670
13671 @group
13672 package Builder is
13673 for ^Default_Switches^Default_Switches^ ("Ada")
13674 use Imported.Builder'Ada_^Switches^Switches^ &
13675 "^-gnatg^-gnatg^" &
13676 "^-v^-v^";
13677 end Builder;
13678 @end group
13679
13680 @group
13681 package Compiler is
13682 for ^Default_Switches^Default_Switches^ ("Ada")
13683 use Base.Compiler'Ada_^Switches^Switches^;
13684 end Compiler;
13685 end Main;
13686 @end group
13687 @end smallexample
13688
13689 @noindent
13690 In this example:
13691
13692 @itemize @bullet
13693 @item
13694 The value of @code{Var1} is a copy of the variable @code{Var} defined
13695 in the project file @file{"imported.gpr"}
13696 @item
13697 the value of @code{Var2} is a copy of the value of variable @code{Var}
13698 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13699 @item
13700 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13701 @code{Builder} is a string list that includes in its value a copy of the value
13702 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13703 in project file @file{imported.gpr} plus two new elements:
13704 @option{"^-gnatg^-gnatg^"}
13705 and @option{"^-v^-v^"};
13706 @item
13707 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13708 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13709 defined in the @code{Compiler} package in project file @file{base.gpr},
13710 the project being extended.
13711 @end itemize
13712
13713 @c ******************
13714 @c * Naming Schemes *
13715 @c ******************
13716
13717 @node Naming Schemes
13718 @section Naming Schemes
13719
13720 @noindent
13721 Sometimes an Ada software system is ported from a foreign compilation
13722 environment to GNAT, and the file names do not use the default GNAT
13723 conventions. Instead of changing all the file names (which for a variety
13724 of reasons might not be possible), you can define the relevant file
13725 naming scheme in the @code{Naming} package in your project file.
13726
13727 @noindent
13728 Note that the use of pragmas described in
13729 @ref{Alternative File Naming Schemes} by mean of a configuration
13730 pragmas file is not supported when using project files. You must use
13731 the features described in this paragraph. You can however use specify
13732 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13733
13734 @ifclear vms
13735 For example, the following
13736 package models the Apex file naming rules:
13737
13738 @smallexample @c projectfile
13739 @group
13740 package Naming is
13741 for Casing use "lowercase";
13742 for Dot_Replacement use ".";
13743 for Spec_Suffix ("Ada") use ".1.ada";
13744 for Body_Suffix ("Ada") use ".2.ada";
13745 end Naming;
13746 @end group
13747 @end smallexample
13748 @end ifclear
13749
13750 @ifset vms
13751 For example, the following package models the HP Ada file naming rules:
13752
13753 @smallexample @c projectfile
13754 @group
13755 package Naming is
13756 for Casing use "lowercase";
13757 for Dot_Replacement use "__";
13758 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13759 for Body_Suffix ("Ada") use ".^ada^ada^";
13760 end Naming;
13761 @end group
13762 @end smallexample
13763
13764 @noindent
13765 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13766 names in lower case)
13767 @end ifset
13768
13769 @noindent
13770 You can define the following attributes in package @code{Naming}:
13771
13772 @table @code
13773
13774 @item @code{Casing}
13775 This must be a string with one of the three values @code{"lowercase"},
13776 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13777
13778 @noindent
13779 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13780
13781 @item @code{Dot_Replacement}
13782 This must be a string whose value satisfies the following conditions:
13783
13784 @itemize @bullet
13785 @item It must not be empty
13786 @item It cannot start or end with an alphanumeric character
13787 @item It cannot be a single underscore
13788 @item It cannot start with an underscore followed by an alphanumeric
13789 @item It cannot contain a dot @code{'.'} except if the entire string
13790 is @code{"."}
13791 @end itemize
13792
13793 @noindent
13794 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13795
13796 @item @code{Spec_Suffix}
13797 This is an associative array (indexed by the programming language name, case
13798 insensitive) whose value is a string that must satisfy the following
13799 conditions:
13800
13801 @itemize @bullet
13802 @item It must not be empty
13803 @item It must include at least one dot
13804 @end itemize
13805 @noindent
13806 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13807 @code{"^.ads^.ADS^"}.
13808
13809 @item @code{Body_Suffix}
13810 This is an associative array (indexed by the programming language name, case
13811 insensitive) whose value is a string that must satisfy the following
13812 conditions:
13813
13814 @itemize @bullet
13815 @item It must not be empty
13816 @item It must include at least one dot
13817 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13818 @end itemize
13819 @noindent
13820 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13821 same string, then a file name that ends with the longest of these two suffixes
13822 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13823 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13824
13825 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13826 @code{"^.adb^.ADB^"}.
13827
13828 @item @code{Separate_Suffix}
13829 This must be a string whose value satisfies the same conditions as
13830 @code{Body_Suffix}. The same "longest suffix" rules apply.
13831
13832 @noindent
13833 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13834 value as @code{Body_Suffix ("Ada")}.
13835
13836 @item @code{Spec}
13837 @noindent
13838 You can use the associative array attribute @code{Spec} to define
13839 the source file name for an individual Ada compilation unit's spec. The array
13840 index must be a string literal that identifies the Ada unit (case insensitive).
13841 The value of this attribute must be a string that identifies the file that
13842 contains this unit's spec (case sensitive or insensitive depending on the
13843 operating system).
13844
13845 @smallexample @c projectfile
13846 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13847 @end smallexample
13848
13849 When the source file contains several units, you can indicate at what
13850 position the unit occurs in the file, with the following. The first unit
13851 in the file has index 1
13852
13853 @smallexample @c projectfile
13854 for Body ("top") use "foo.a" at 1;
13855 for Body ("foo") use "foo.a" at 2;
13856 @end smallexample
13857
13858 @item @code{Body}
13859
13860 You can use the associative array attribute @code{Body} to
13861 define the source file name for an individual Ada compilation unit's body
13862 (possibly a subunit). The array index must be a string literal that identifies
13863 the Ada unit (case insensitive). The value of this attribute must be a string
13864 that identifies the file that contains this unit's body or subunit (case
13865 sensitive or insensitive depending on the operating system).
13866
13867 @smallexample @c projectfile
13868 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13869 @end smallexample
13870 @end table
13871
13872 @c ********************
13873 @c * Library Projects *
13874 @c ********************
13875
13876 @node Library Projects
13877 @section Library Projects
13878
13879 @noindent
13880 @emph{Library projects} are projects whose object code is placed in a library.
13881 (Note that this facility is not yet supported on all platforms).
13882
13883 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13884 single archive, which might either be a shared or a static library. This
13885 library can later on be linked with multiple executables, potentially
13886 reducing their sizes.
13887
13888 If your project file specifies languages other than Ada, but you are still
13889 using @code{gnatmake} to compile and link, the latter will not try to
13890 compile your sources other than Ada (you should use @code{gprbuild} if that
13891 is your intent). However, @code{gnatmake} will automatically link all object
13892 files found in the object directory, whether or not they were compiled from
13893 an Ada source file. This specific behavior only applies when multiple
13894 languages are specified.
13895
13896 To create a library project, you need to define in its project file
13897 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13898 Additionally, you may define other library-related attributes such as
13899 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13900 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13901
13902 The @code{Library_Name} attribute has a string value. There is no restriction
13903 on the name of a library. It is the responsibility of the developer to
13904 choose a name that will be accepted by the platform. It is recommended to
13905 choose names that could be Ada identifiers; such names are almost guaranteed
13906 to be acceptable on all platforms.
13907
13908 The @code{Library_Dir} attribute has a string value that designates the path
13909 (absolute or relative) of the directory where the library will reside.
13910 It must designate an existing directory, and this directory must be writable,
13911 different from the project's object directory and from any source directory
13912 in the project tree.
13913
13914 If both @code{Library_Name} and @code{Library_Dir} are specified and
13915 are legal, then the project file defines a library project. The optional
13916 library-related attributes are checked only for such project files.
13917
13918 The @code{Library_Kind} attribute has a string value that must be one of the
13919 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13920 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13921 attribute is not specified, the library is a static library, that is
13922 an archive of object files that can be potentially linked into a
13923 static executable. Otherwise, the library may be dynamic or
13924 relocatable, that is a library that is loaded only at the start of execution.
13925
13926 If you need to build both a static and a dynamic library, you should use two
13927 different object directories, since in some cases some extra code needs to
13928 be generated for the latter. For such cases, it is recommended to either use
13929 two different project files, or a single one which uses external variables
13930 to indicate what kind of library should be build.
13931
13932 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13933 directory where the ALI files of the library will be copied. When it is
13934 not specified, the ALI files are copied to the directory specified in
13935 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13936 must be writable and different from the project's object directory and from
13937 any source directory in the project tree.
13938
13939 The @code{Library_Version} attribute has a string value whose interpretation
13940 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13941 used only for dynamic/relocatable libraries as the internal name of the
13942 library (the @code{"soname"}). If the library file name (built from the
13943 @code{Library_Name}) is different from the @code{Library_Version}, then the
13944 library file will be a symbolic link to the actual file whose name will be
13945 @code{Library_Version}.
13946
13947 Example (on Unix):
13948
13949 @smallexample @c projectfile
13950 @group
13951 project Plib is
13952
13953 Version := "1";
13954
13955 for Library_Dir use "lib_dir";
13956 for Library_Name use "dummy";
13957 for Library_Kind use "relocatable";
13958 for Library_Version use "libdummy.so." & Version;
13959
13960 end Plib;
13961 @end group
13962 @end smallexample
13963
13964 @noindent
13965 Directory @file{lib_dir} will contain the internal library file whose name
13966 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13967 @file{libdummy.so.1}.
13968
13969 When @command{gnatmake} detects that a project file
13970 is a library project file, it will check all immediate sources of the project
13971 and rebuild the library if any of the sources have been recompiled.
13972
13973 Standard project files can import library project files. In such cases,
13974 the libraries will only be rebuilt if some of its sources are recompiled
13975 because they are in the closure of some other source in an importing project.
13976 Sources of the library project files that are not in such a closure will
13977 not be checked, unless the full library is checked, because one of its sources
13978 needs to be recompiled.
13979
13980 For instance, assume the project file @code{A} imports the library project file
13981 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13982 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13983 @file{l2.ads}, @file{l2.adb}.
13984
13985 If @file{l1.adb} has been modified, then the library associated with @code{L}
13986 will be rebuilt when compiling all the immediate sources of @code{A} only
13987 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13988 @code{"with L1;"}.
13989
13990 To be sure that all the sources in the library associated with @code{L} are
13991 up to date, and that all the sources of project @code{A} are also up to date,
13992 the following two commands needs to be used:
13993
13994 @smallexample
13995 gnatmake -Pl.gpr
13996 gnatmake -Pa.gpr
13997 @end smallexample
13998
13999 When a library is built or rebuilt, an attempt is made first to delete all
14000 files in the library directory.
14001 All @file{ALI} files will also be copied from the object directory to the
14002 library directory. To build executables, @command{gnatmake} will use the
14003 library rather than the individual object files.
14004
14005 @ifclear vms
14006 It is also possible to create library project files for third-party libraries
14007 that are precompiled and cannot be compiled locally thanks to the
14008 @code{externally_built} attribute. (See @ref{Installing a library}).
14009 @end ifclear
14010
14011 @c *******************************
14012 @c * Stand-alone Library Projects *
14013 @c *******************************
14014
14015 @node Stand-alone Library Projects
14016 @section Stand-alone Library Projects
14017
14018 @noindent
14019 A Stand-alone Library is a library that contains the necessary code to
14020 elaborate the Ada units that are included in the library. A Stand-alone
14021 Library is suitable to be used in an executable when the main is not
14022 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14023 subprogram.
14024
14025 A Stand-alone Library Project is a Library Project where the library is
14026 a Stand-alone Library.
14027
14028 To be a Stand-alone Library Project, in addition to the two attributes
14029 that make a project a Library Project (@code{Library_Name} and
14030 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14031 @code{Library_Interface} must be defined.
14032
14033 @smallexample @c projectfile
14034 @group
14035 for Library_Dir use "lib_dir";
14036 for Library_Name use "dummy";
14037 for Library_Interface use ("int1", "int1.child");
14038 @end group
14039 @end smallexample
14040
14041 Attribute @code{Library_Interface} has a nonempty string list value,
14042 each string in the list designating a unit contained in an immediate source
14043 of the project file.
14044
14045 When a Stand-alone Library is built, first the binder is invoked to build
14046 a package whose name depends on the library name
14047 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14048 This binder-generated package includes initialization and
14049 finalization procedures whose
14050 names depend on the library name (dummyinit and dummyfinal in the example
14051 above). The object corresponding to this package is included in the library.
14052
14053 A dynamic or relocatable Stand-alone Library is automatically initialized
14054 if automatic initialization of Stand-alone Libraries is supported on the
14055 platform and if attribute @code{Library_Auto_Init} is not specified or
14056 is specified with the value "true". A static Stand-alone Library is never
14057 automatically initialized.
14058
14059 Single string attribute @code{Library_Auto_Init} may be specified with only
14060 two possible values: "false" or "true" (case-insensitive). Specifying
14061 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14062 initialization of dynamic or relocatable libraries.
14063
14064 When a non-automatically initialized Stand-alone Library is used
14065 in an executable, its initialization procedure must be called before
14066 any service of the library is used.
14067 When the main subprogram is in Ada, it may mean that the initialization
14068 procedure has to be called during elaboration of another package.
14069
14070 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14071 (those that are listed in attribute @code{Library_Interface}) are copied to
14072 the Library Directory. As a consequence, only the Interface Units may be
14073 imported from Ada units outside of the library. If other units are imported,
14074 the binding phase will fail.
14075
14076 When a Stand-Alone Library is bound, the switches that are specified in
14077 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14078 used in the call to @command{gnatbind}.
14079
14080 The string list attribute @code{Library_Options} may be used to specified
14081 additional switches to the call to @command{gcc} to link the library.
14082
14083 The attribute @code{Library_Src_Dir}, may be specified for a
14084 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14085 single string value. Its value must be the path (absolute or relative to the
14086 project directory) of an existing directory. This directory cannot be the
14087 object directory or one of the source directories, but it can be the same as
14088 the library directory. The sources of the Interface
14089 Units of the library, necessary to an Ada client of the library, will be
14090 copied to the designated directory, called Interface Copy directory.
14091 These sources includes the specs of the Interface Units, but they may also
14092 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14093 are used, or when there is a generic units in the spec. Before the sources
14094 are copied to the Interface Copy directory, an attempt is made to delete all
14095 files in the Interface Copy directory.
14096
14097 @c *************************************
14098 @c * Switches Related to Project Files *
14099 @c *************************************
14100 @node Switches Related to Project Files
14101 @section Switches Related to Project Files
14102
14103 @noindent
14104 The following switches are used by GNAT tools that support project files:
14105
14106 @table @option
14107
14108 @item ^-P^/PROJECT_FILE=^@var{project}
14109 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14110 Indicates the name of a project file. This project file will be parsed with
14111 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14112 if any, and using the external references indicated
14113 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14114 @ifclear vms
14115 There may zero, one or more spaces between @option{-P} and @var{project}.
14116 @end ifclear
14117
14118 @noindent
14119 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14120
14121 @noindent
14122 Since the Project Manager parses the project file only after all the switches
14123 on the command line are checked, the order of the switches
14124 @option{^-P^/PROJECT_FILE^},
14125 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14126 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14127
14128 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14129 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14130 Indicates that external variable @var{name} has the value @var{value}.
14131 The Project Manager will use this value for occurrences of
14132 @code{external(name)} when parsing the project file.
14133
14134 @ifclear vms
14135 @noindent
14136 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14137 put between quotes.
14138 @smallexample
14139 -XOS=NT
14140 -X"user=John Doe"
14141 @end smallexample
14142 @end ifclear
14143
14144 @noindent
14145 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14146 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14147 @var{name}, only the last one is used.
14148
14149 @noindent
14150 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14151 takes precedence over the value of the same name in the environment.
14152
14153 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14154 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14155 Indicates the verbosity of the parsing of GNAT project files.
14156
14157 @ifclear vms
14158 @option{-vP0} means Default;
14159 @option{-vP1} means Medium;
14160 @option{-vP2} means High.
14161 @end ifclear
14162
14163 @ifset vms
14164 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14165 HIGH.
14166 @end ifset
14167
14168 @noindent
14169 The default is ^Default^DEFAULT^: no output for syntactically correct
14170 project files.
14171 @noindent
14172 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14173 only the last one is used.
14174
14175 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14176 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14177 Add directory <dir> at the beginning of the project search path, in order,
14178 after the current working directory.
14179
14180 @ifclear vms
14181 @item -eL
14182 @cindex @option{-eL} (any project-aware tool)
14183 Follow all symbolic links when processing project files.
14184 @end ifclear
14185
14186 @item ^--subdirs^/SUBDIRS^=<subdir>
14187 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14188 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14189 directories (except the source directories) are the subdirectories <subdir>
14190 of the directories specified in the project files. This applies in particular
14191 to object directories, library directories and exec directories. If the
14192 subdirectories do not exist, they are created automatically.
14193
14194 @end table
14195
14196 @c **********************************
14197 @c * Tools Supporting Project Files *
14198 @c **********************************
14199
14200 @node Tools Supporting Project Files
14201 @section Tools Supporting Project Files
14202
14203 @menu
14204 * gnatmake and Project Files::
14205 * The GNAT Driver and Project Files::
14206 @end menu
14207
14208 @node gnatmake and Project Files
14209 @subsection gnatmake and Project Files
14210
14211 @noindent
14212 This section covers several topics related to @command{gnatmake} and
14213 project files: defining ^switches^switches^ for @command{gnatmake}
14214 and for the tools that it invokes; specifying configuration pragmas;
14215 the use of the @code{Main} attribute; building and rebuilding library project
14216 files.
14217
14218 @menu
14219 * ^Switches^Switches^ and Project Files::
14220 * Specifying Configuration Pragmas::
14221 * Project Files and Main Subprograms::
14222 * Library Project Files::
14223 @end menu
14224
14225 @node ^Switches^Switches^ and Project Files
14226 @subsubsection ^Switches^Switches^ and Project Files
14227
14228 @ifset vms
14229 It is not currently possible to specify VMS style qualifiers in the project
14230 files; only Unix style ^switches^switches^ may be specified.
14231 @end ifset
14232
14233 @noindent
14234 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14235 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14236 attribute, a @code{^Switches^Switches^} attribute, or both;
14237 as their names imply, these ^switch^switch^-related
14238 attributes affect the ^switches^switches^ that are used for each of these GNAT
14239 components when
14240 @command{gnatmake} is invoked. As will be explained below, these
14241 component-specific ^switches^switches^ precede
14242 the ^switches^switches^ provided on the @command{gnatmake} command line.
14243
14244 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14245 array indexed by language name (case insensitive) whose value is a string list.
14246 For example:
14247
14248 @smallexample @c projectfile
14249 @group
14250 package Compiler is
14251 for ^Default_Switches^Default_Switches^ ("Ada")
14252 use ("^-gnaty^-gnaty^",
14253 "^-v^-v^");
14254 end Compiler;
14255 @end group
14256 @end smallexample
14257
14258 @noindent
14259 The @code{^Switches^Switches^} attribute is also an associative array,
14260 indexed by a file name (which may or may not be case sensitive, depending
14261 on the operating system) whose value is a string list. For example:
14262
14263 @smallexample @c projectfile
14264 @group
14265 package Builder is
14266 for ^Switches^Switches^ ("main1.adb")
14267 use ("^-O2^-O2^");
14268 for ^Switches^Switches^ ("main2.adb")
14269 use ("^-g^-g^");
14270 end Builder;
14271 @end group
14272 @end smallexample
14273
14274 @noindent
14275 For the @code{Builder} package, the file names must designate source files
14276 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
14277 file names must designate @file{ALI} or source files for main subprograms.
14278 In each case just the file name without an explicit extension is acceptable.
14279
14280 For each tool used in a program build (@command{gnatmake}, the compiler, the
14281 binder, and the linker), the corresponding package @dfn{contributes} a set of
14282 ^switches^switches^ for each file on which the tool is invoked, based on the
14283 ^switch^switch^-related attributes defined in the package.
14284 In particular, the ^switches^switches^
14285 that each of these packages contributes for a given file @var{f} comprise:
14286
14287 @itemize @bullet
14288 @item
14289 the value of attribute @code{^Switches^Switches^ (@var{f})},
14290 if it is specified in the package for the given file,
14291 @item
14292 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14293 if it is specified in the package.
14294 @end itemize
14295
14296 @noindent
14297 If neither of these attributes is defined in the package, then the package does
14298 not contribute any ^switches^switches^ for the given file.
14299
14300 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14301 two sets, in the following order: those contributed for the file
14302 by the @code{Builder} package;
14303 and the switches passed on the command line.
14304
14305 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14306 the ^switches^switches^ passed to the tool comprise three sets,
14307 in the following order:
14308
14309 @enumerate
14310 @item
14311 the applicable ^switches^switches^ contributed for the file
14312 by the @code{Builder} package in the project file supplied on the command line;
14313
14314 @item
14315 those contributed for the file by the package (in the relevant project file --
14316 see below) corresponding to the tool; and
14317
14318 @item
14319 the applicable switches passed on the command line.
14320 @end enumerate
14321
14322 @noindent
14323 The term @emph{applicable ^switches^switches^} reflects the fact that
14324 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14325 tools, depending on the individual ^switch^switch^.
14326
14327 @command{gnatmake} may invoke the compiler on source files from different
14328 projects. The Project Manager will use the appropriate project file to
14329 determine the @code{Compiler} package for each source file being compiled.
14330 Likewise for the @code{Binder} and @code{Linker} packages.
14331
14332 As an example, consider the following package in a project file:
14333
14334 @smallexample @c projectfile
14335 @group
14336 project Proj1 is
14337 package Compiler is
14338 for ^Default_Switches^Default_Switches^ ("Ada")
14339 use ("^-g^-g^");
14340 for ^Switches^Switches^ ("a.adb")
14341 use ("^-O1^-O1^");
14342 for ^Switches^Switches^ ("b.adb")
14343 use ("^-O2^-O2^",
14344 "^-gnaty^-gnaty^");
14345 end Compiler;
14346 end Proj1;
14347 @end group
14348 @end smallexample
14349
14350 @noindent
14351 If @command{gnatmake} is invoked with this project file, and it needs to
14352 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14353 @file{a.adb} will be compiled with the ^switch^switch^
14354 @option{^-O1^-O1^},
14355 @file{b.adb} with ^switches^switches^
14356 @option{^-O2^-O2^}
14357 and @option{^-gnaty^-gnaty^},
14358 and @file{c.adb} with @option{^-g^-g^}.
14359
14360 The following example illustrates the ordering of the ^switches^switches^
14361 contributed by different packages:
14362
14363 @smallexample @c projectfile
14364 @group
14365 project Proj2 is
14366 package Builder is
14367 for ^Switches^Switches^ ("main.adb")
14368 use ("^-g^-g^",
14369 "^-O1^-)1^",
14370 "^-f^-f^");
14371 end Builder;
14372 @end group
14373
14374 @group
14375 package Compiler is
14376 for ^Switches^Switches^ ("main.adb")
14377 use ("^-O2^-O2^");
14378 end Compiler;
14379 end Proj2;
14380 @end group
14381 @end smallexample
14382
14383 @noindent
14384 If you issue the command:
14385
14386 @smallexample
14387 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14388 @end smallexample
14389
14390 @noindent
14391 then the compiler will be invoked on @file{main.adb} with the following
14392 sequence of ^switches^switches^
14393
14394 @smallexample
14395 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14396 @end smallexample
14397
14398 with the last @option{^-O^-O^}
14399 ^switch^switch^ having precedence over the earlier ones;
14400 several other ^switches^switches^
14401 (such as @option{^-c^-c^}) are added implicitly.
14402
14403 The ^switches^switches^
14404 @option{^-g^-g^}
14405 and @option{^-O1^-O1^} are contributed by package
14406 @code{Builder}, @option{^-O2^-O2^} is contributed
14407 by the package @code{Compiler}
14408 and @option{^-O0^-O0^} comes from the command line.
14409
14410 The @option{^-g^-g^}
14411 ^switch^switch^ will also be passed in the invocation of
14412 @command{Gnatlink.}
14413
14414 A final example illustrates switch contributions from packages in different
14415 project files:
14416
14417 @smallexample @c projectfile
14418 @group
14419 project Proj3 is
14420 for Source_Files use ("pack.ads", "pack.adb");
14421 package Compiler is
14422 for ^Default_Switches^Default_Switches^ ("Ada")
14423 use ("^-gnata^-gnata^");
14424 end Compiler;
14425 end Proj3;
14426 @end group
14427
14428 @group
14429 with "Proj3";
14430 project Proj4 is
14431 for Source_Files use ("foo_main.adb", "bar_main.adb");
14432 package Builder is
14433 for ^Switches^Switches^ ("foo_main.adb")
14434 use ("^-s^-s^",
14435 "^-g^-g^");
14436 end Builder;
14437 end Proj4;
14438 @end group
14439
14440 @group
14441 -- Ada source file:
14442 with Pack;
14443 procedure Foo_Main is
14444 @dots{}
14445 end Foo_Main;
14446 @end group
14447 @end smallexample
14448
14449 If the command is
14450 @smallexample
14451 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14452 @end smallexample
14453
14454 @noindent
14455 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14456 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14457 @option{^-gnato^-gnato^} (passed on the command line).
14458 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14459 are @option{^-g^-g^} from @code{Proj4.Builder},
14460 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14461 and @option{^-gnato^-gnato^} from the command line.
14462
14463 @noindent
14464 When using @command{gnatmake} with project files, some ^switches^switches^ or
14465 arguments may be expressed as relative paths. As the working directory where
14466 compilation occurs may change, these relative paths are converted to absolute
14467 paths. For the ^switches^switches^ found in a project file, the relative paths
14468 are relative to the project file directory, for the switches on the command
14469 line, they are relative to the directory where @command{gnatmake} is invoked.
14470 The ^switches^switches^ for which this occurs are:
14471 ^-I^-I^,
14472 ^-A^-A^,
14473 ^-L^-L^,
14474 ^-aO^-aO^,
14475 ^-aL^-aL^,
14476 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14477 ^switch^switch^
14478 ^-o^-o^, object files specified in package @code{Linker} or after
14479 -largs on the command line). The exception to this rule is the ^switch^switch^
14480 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14481
14482 @node Specifying Configuration Pragmas
14483 @subsubsection Specifying Configuration Pragmas
14484
14485 When using @command{gnatmake} with project files, if there exists a file
14486 @file{gnat.adc} that contains configuration pragmas, this file will be
14487 ignored.
14488
14489 Configuration pragmas can be defined by means of the following attributes in
14490 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14491 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14492
14493 Both these attributes are single string attributes. Their values is the path
14494 name of a file containing configuration pragmas. If a path name is relative,
14495 then it is relative to the project directory of the project file where the
14496 attribute is defined.
14497
14498 When compiling a source, the configuration pragmas used are, in order,
14499 those listed in the file designated by attribute
14500 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14501 project file, if it is specified, and those listed in the file designated by
14502 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14503 the project file of the source, if it exists.
14504
14505 @node Project Files and Main Subprograms
14506 @subsubsection Project Files and Main Subprograms
14507
14508 @noindent
14509 When using a project file, you can invoke @command{gnatmake}
14510 with one or several main subprograms, by specifying their source files on the
14511 command line.
14512
14513 @smallexample
14514 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14515 @end smallexample
14516
14517 @noindent
14518 Each of these needs to be a source file of the same project, except
14519 when the switch ^-u^/UNIQUE^ is used.
14520
14521 @noindent
14522 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14523 same project, one of the project in the tree rooted at the project specified
14524 on the command line. The package @code{Builder} of this common project, the
14525 "main project" is the one that is considered by @command{gnatmake}.
14526
14527 @noindent
14528 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14529 imported directly or indirectly by the project specified on the command line.
14530 Note that if such a source file is not part of the project specified on the
14531 command line, the ^switches^switches^ found in package @code{Builder} of the
14532 project specified on the command line, if any, that are transmitted
14533 to the compiler will still be used, not those found in the project file of
14534 the source file.
14535
14536 @noindent
14537 When using a project file, you can also invoke @command{gnatmake} without
14538 explicitly specifying any main, and the effect depends on whether you have
14539 defined the @code{Main} attribute. This attribute has a string list value,
14540 where each element in the list is the name of a source file (the file
14541 extension is optional) that contains a unit that can be a main subprogram.
14542
14543 If the @code{Main} attribute is defined in a project file as a non-empty
14544 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14545 line, then invoking @command{gnatmake} with this project file but without any
14546 main on the command line is equivalent to invoking @command{gnatmake} with all
14547 the file names in the @code{Main} attribute on the command line.
14548
14549 Example:
14550 @smallexample @c projectfile
14551 @group
14552 project Prj is
14553 for Main use ("main1", "main2", "main3");
14554 end Prj;
14555 @end group
14556 @end smallexample
14557
14558 @noindent
14559 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14560 is equivalent to
14561 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14562
14563 When the project attribute @code{Main} is not specified, or is specified
14564 as an empty string list, or when the switch @option{-u} is used on the command
14565 line, then invoking @command{gnatmake} with no main on the command line will
14566 result in all immediate sources of the project file being checked, and
14567 potentially recompiled. Depending on the presence of the switch @option{-u},
14568 sources from other project files on which the immediate sources of the main
14569 project file depend are also checked and potentially recompiled. In other
14570 words, the @option{-u} switch is applied to all of the immediate sources of the
14571 main project file.
14572
14573 When no main is specified on the command line and attribute @code{Main} exists
14574 and includes several mains, or when several mains are specified on the
14575 command line, the default ^switches^switches^ in package @code{Builder} will
14576 be used for all mains, even if there are specific ^switches^switches^
14577 specified for one or several mains.
14578
14579 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14580 the specific ^switches^switches^ for each main, if they are specified.
14581
14582 @node Library Project Files
14583 @subsubsection Library Project Files
14584
14585 @noindent
14586 When @command{gnatmake} is invoked with a main project file that is a library
14587 project file, it is not allowed to specify one or more mains on the command
14588 line.
14589
14590 @noindent
14591 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14592 ^-l^/ACTION=LINK^ have special meanings.
14593
14594 @itemize @bullet
14595 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14596 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14597 library.
14598
14599 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14600 to @command{gnatmake} that the binder generated file should be compiled
14601 (in the case of a stand-alone library) and that the library should be built.
14602
14603 @end itemize
14604
14605 @node The GNAT Driver and Project Files
14606 @subsection The GNAT Driver and Project Files
14607
14608 @noindent
14609 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14610 can benefit from project files:
14611 @command{^gnatbind^gnatbind^},
14612 @command{^gnatcheck^gnatcheck^}),
14613 @command{^gnatclean^gnatclean^}),
14614 @command{^gnatelim^gnatelim^},
14615 @command{^gnatfind^gnatfind^},
14616 @command{^gnatlink^gnatlink^},
14617 @command{^gnatls^gnatls^},
14618 @command{^gnatmetric^gnatmetric^},
14619 @command{^gnatpp^gnatpp^},
14620 @command{^gnatstub^gnatstub^},
14621 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14622 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14623 They must be invoked through the @command{gnat} driver.
14624
14625 The @command{gnat} driver is a wrapper that accepts a number of commands and
14626 calls the corresponding tool. It was designed initially for VMS platforms (to
14627 convert VMS qualifiers to Unix-style switches), but it is now available on all
14628 GNAT platforms.
14629
14630 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14631 (case insensitive):
14632
14633 @itemize @bullet
14634 @item
14635 BIND to invoke @command{^gnatbind^gnatbind^}
14636 @item
14637 CHOP to invoke @command{^gnatchop^gnatchop^}
14638 @item
14639 CLEAN to invoke @command{^gnatclean^gnatclean^}
14640 @item
14641 COMP or COMPILE to invoke the compiler
14642 @item
14643 ELIM to invoke @command{^gnatelim^gnatelim^}
14644 @item
14645 FIND to invoke @command{^gnatfind^gnatfind^}
14646 @item
14647 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14648 @item
14649 LINK to invoke @command{^gnatlink^gnatlink^}
14650 @item
14651 LS or LIST to invoke @command{^gnatls^gnatls^}
14652 @item
14653 MAKE to invoke @command{^gnatmake^gnatmake^}
14654 @item
14655 NAME to invoke @command{^gnatname^gnatname^}
14656 @item
14657 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14658 @item
14659 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14660 @item
14661 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14662 @item
14663 STUB to invoke @command{^gnatstub^gnatstub^}
14664 @item
14665 XREF to invoke @command{^gnatxref^gnatxref^}
14666 @end itemize
14667
14668 @noindent
14669 (note that the compiler is invoked using the command
14670 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14671
14672 @noindent
14673 On non-VMS platforms, between @command{gnat} and the command, two
14674 special switches may be used:
14675
14676 @itemize @bullet
14677 @item
14678 @command{-v} to display the invocation of the tool.
14679 @item
14680 @command{-dn} to prevent the @command{gnat} driver from removing
14681 the temporary files it has created. These temporary files are
14682 configuration files and temporary file list files.
14683 @end itemize
14684
14685 @noindent
14686 The command may be followed by switches and arguments for the invoked
14687 tool.
14688
14689 @smallexample
14690 gnat bind -C main.ali
14691 gnat ls -a main
14692 gnat chop foo.txt
14693 @end smallexample
14694
14695 @noindent
14696 Switches may also be put in text files, one switch per line, and the text
14697 files may be specified with their path name preceded by '@@'.
14698
14699 @smallexample
14700 gnat bind @@args.txt main.ali
14701 @end smallexample
14702
14703 @noindent
14704 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14705 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14706 (@option{^-P^/PROJECT_FILE^},
14707 @option{^-X^/EXTERNAL_REFERENCE^} and
14708 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14709 the switches of the invoking tool.
14710
14711 @noindent
14712 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14713 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14714 the immediate sources of the specified project file.
14715
14716 @noindent
14717 When GNAT METRIC is used with a project file, but with no source
14718 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14719 with all the immediate sources of the specified project file and with
14720 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14721 of the project.
14722
14723 @noindent
14724 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14725 a project file, no source is specified on the command line and
14726 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14727 the underlying tool (^gnatpp^gnatpp^ or
14728 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14729 not only for the immediate sources of the main project.
14730 @ifclear vms
14731 (-U stands for Universal or Union of the project files of the project tree)
14732 @end ifclear
14733
14734 @noindent
14735 For each of the following commands, there is optionally a corresponding
14736 package in the main project.
14737
14738 @itemize @bullet
14739 @item
14740 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14741
14742 @item
14743 package @code{Check} for command CHECK (invoking
14744 @code{^gnatcheck^gnatcheck^})
14745
14746 @item
14747 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14748
14749 @item
14750 package @code{Cross_Reference} for command XREF (invoking
14751 @code{^gnatxref^gnatxref^})
14752
14753 @item
14754 package @code{Eliminate} for command ELIM (invoking
14755 @code{^gnatelim^gnatelim^})
14756
14757 @item
14758 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14759
14760 @item
14761 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14762
14763 @item
14764 package @code{Gnatstub} for command STUB
14765 (invoking @code{^gnatstub^gnatstub^})
14766
14767 @item
14768 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14769
14770 @item
14771 package @code{Metrics} for command METRIC
14772 (invoking @code{^gnatmetric^gnatmetric^})
14773
14774 @item
14775 package @code{Pretty_Printer} for command PP or PRETTY
14776 (invoking @code{^gnatpp^gnatpp^})
14777
14778 @end itemize
14779
14780 @noindent
14781 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14782 a simple variable with a string list value. It contains ^switches^switches^
14783 for the invocation of @code{^gnatls^gnatls^}.
14784
14785 @smallexample @c projectfile
14786 @group
14787 project Proj1 is
14788 package gnatls is
14789 for ^Switches^Switches^
14790 use ("^-a^-a^",
14791 "^-v^-v^");
14792 end gnatls;
14793 end Proj1;
14794 @end group
14795 @end smallexample
14796
14797 @noindent
14798 All other packages have two attribute @code{^Switches^Switches^} and
14799 @code{^Default_Switches^Default_Switches^}.
14800
14801 @noindent
14802 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14803 source file name, that has a string list value: the ^switches^switches^ to be
14804 used when the tool corresponding to the package is invoked for the specific
14805 source file.
14806
14807 @noindent
14808 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14809 indexed by the programming language that has a string list value.
14810 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14811 ^switches^switches^ for the invocation of the tool corresponding
14812 to the package, except if a specific @code{^Switches^Switches^} attribute
14813 is specified for the source file.
14814
14815 @smallexample @c projectfile
14816 @group
14817 project Proj is
14818
14819 for Source_Dirs use ("./**");
14820
14821 package gnatls is
14822 for ^Switches^Switches^ use
14823 ("^-a^-a^",
14824 "^-v^-v^");
14825 end gnatls;
14826 @end group
14827 @group
14828
14829 package Compiler is
14830 for ^Default_Switches^Default_Switches^ ("Ada")
14831 use ("^-gnatv^-gnatv^",
14832 "^-gnatwa^-gnatwa^");
14833 end Binder;
14834 @end group
14835 @group
14836
14837 package Binder is
14838 for ^Default_Switches^Default_Switches^ ("Ada")
14839 use ("^-C^-C^",
14840 "^-e^-e^");
14841 end Binder;
14842 @end group
14843 @group
14844
14845 package Linker is
14846 for ^Default_Switches^Default_Switches^ ("Ada")
14847 use ("^-C^-C^");
14848 for ^Switches^Switches^ ("main.adb")
14849 use ("^-C^-C^",
14850 "^-v^-v^",
14851 "^-v^-v^");
14852 end Linker;
14853 @end group
14854 @group
14855
14856 package Finder is
14857 for ^Default_Switches^Default_Switches^ ("Ada")
14858 use ("^-a^-a^",
14859 "^-f^-f^");
14860 end Finder;
14861 @end group
14862 @group
14863
14864 package Cross_Reference is
14865 for ^Default_Switches^Default_Switches^ ("Ada")
14866 use ("^-a^-a^",
14867 "^-f^-f^",
14868 "^-d^-d^",
14869 "^-u^-u^");
14870 end Cross_Reference;
14871 end Proj;
14872 @end group
14873 @end smallexample
14874
14875 @noindent
14876 With the above project file, commands such as
14877
14878 @smallexample
14879 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14880 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14881 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14882 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14883 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14884 @end smallexample
14885
14886 @noindent
14887 will set up the environment properly and invoke the tool with the switches
14888 found in the package corresponding to the tool:
14889 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14890 except @code{^Switches^Switches^ ("main.adb")}
14891 for @code{^gnatlink^gnatlink^}.
14892 It is also possible to invoke some of the tools,
14893 @code{^gnatcheck^gnatcheck^}),
14894 @code{^gnatmetric^gnatmetric^}),
14895 and @code{^gnatpp^gnatpp^})
14896 on a set of project units thanks to the combination of the switches
14897 @option{-P}, @option{-U} and possibly the main unit when one is interested
14898 in its closure. For instance,
14899 @smallexample
14900 gnat metric -Pproj
14901 @end smallexample
14902 will compute the metrics for all the immediate units of project
14903 @code{proj}.
14904 @smallexample
14905 gnat metric -Pproj -U
14906 @end smallexample
14907 will compute the metrics for all the units of the closure of projects
14908 rooted at @code{proj}.
14909 @smallexample
14910 gnat metric -Pproj -U main_unit
14911 @end smallexample
14912 will compute the metrics for the closure of units rooted at
14913 @code{main_unit}. This last possibility relies implicitly
14914 on @command{gnatbind}'s option @option{-R}.
14915
14916 @c **********************
14917 @node An Extended Example
14918 @section An Extended Example
14919
14920 @noindent
14921 Suppose that we have two programs, @var{prog1} and @var{prog2},
14922 whose sources are in corresponding directories. We would like
14923 to build them with a single @command{gnatmake} command, and we want to place
14924 their object files into @file{build} subdirectories of the source directories.
14925 Furthermore, we want to have to have two separate subdirectories
14926 in @file{build} -- @file{release} and @file{debug} -- which will contain
14927 the object files compiled with different set of compilation flags.
14928
14929 In other words, we have the following structure:
14930
14931 @smallexample
14932 @group
14933 main
14934 |- prog1
14935 | |- build
14936 | | debug
14937 | | release
14938 |- prog2
14939 |- build
14940 | debug
14941 | release
14942 @end group
14943 @end smallexample
14944
14945 @noindent
14946 Here are the project files that we must place in a directory @file{main}
14947 to maintain this structure:
14948
14949 @enumerate
14950
14951 @item We create a @code{Common} project with a package @code{Compiler} that
14952 specifies the compilation ^switches^switches^:
14953
14954 @smallexample
14955 File "common.gpr":
14956 @group
14957 @b{project} Common @b{is}
14958
14959 @b{for} Source_Dirs @b{use} (); -- No source files
14960 @end group
14961
14962 @group
14963 @b{type} Build_Type @b{is} ("release", "debug");
14964 Build : Build_Type := External ("BUILD", "debug");
14965 @end group
14966 @group
14967 @b{package} Compiler @b{is}
14968 @b{case} Build @b{is}
14969 @b{when} "release" =>
14970 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14971 @b{use} ("^-O2^-O2^");
14972 @b{when} "debug" =>
14973 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14974 @b{use} ("^-g^-g^");
14975 @b{end case};
14976 @b{end} Compiler;
14977
14978 @b{end} Common;
14979 @end group
14980 @end smallexample
14981
14982 @item We create separate projects for the two programs:
14983
14984 @smallexample
14985 @group
14986 File "prog1.gpr":
14987
14988 @b{with} "common";
14989 @b{project} Prog1 @b{is}
14990
14991 @b{for} Source_Dirs @b{use} ("prog1");
14992 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14993
14994 @b{package} Compiler @b{renames} Common.Compiler;
14995
14996 @b{end} Prog1;
14997 @end group
14998 @end smallexample
14999
15000 @smallexample
15001 @group
15002 File "prog2.gpr":
15003
15004 @b{with} "common";
15005 @b{project} Prog2 @b{is}
15006
15007 @b{for} Source_Dirs @b{use} ("prog2");
15008 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
15009
15010 @b{package} Compiler @b{renames} Common.Compiler;
15011
15012 @end group
15013 @b{end} Prog2;
15014 @end smallexample
15015
15016 @item We create a wrapping project @code{Main}:
15017
15018 @smallexample
15019 @group
15020 File "main.gpr":
15021
15022 @b{with} "common";
15023 @b{with} "prog1";
15024 @b{with} "prog2";
15025 @b{project} Main @b{is}
15026
15027 @b{package} Compiler @b{renames} Common.Compiler;
15028
15029 @b{end} Main;
15030 @end group
15031 @end smallexample
15032
15033 @item Finally we need to create a dummy procedure that @code{with}s (either
15034 explicitly or implicitly) all the sources of our two programs.
15035
15036 @end enumerate
15037
15038 @noindent
15039 Now we can build the programs using the command
15040
15041 @smallexample
15042 gnatmake ^-P^/PROJECT_FILE=^main dummy
15043 @end smallexample
15044
15045 @noindent
15046 for the Debug mode, or
15047
15048 @ifclear vms
15049 @smallexample
15050 gnatmake -Pmain -XBUILD=release
15051 @end smallexample
15052 @end ifclear
15053
15054 @ifset vms
15055 @smallexample
15056 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15057 @end smallexample
15058 @end ifset
15059
15060 @noindent
15061 for the Release mode.
15062
15063 @c ********************************
15064 @c * Project File Complete Syntax *
15065 @c ********************************
15066
15067 @node Project File Complete Syntax
15068 @section Project File Complete Syntax
15069
15070 @smallexample
15071 project ::=
15072 context_clause project_declaration
15073
15074 context_clause ::=
15075 @{with_clause@}
15076
15077 with_clause ::=
15078 @b{with} path_name @{ , path_name @} ;
15079
15080 path_name ::=
15081 string_literal
15082
15083 project_declaration ::=
15084 simple_project_declaration | project_extension
15085
15086 simple_project_declaration ::=
15087 @b{project} <project_>simple_name @b{is}
15088 @{declarative_item@}
15089 @b{end} <project_>simple_name;
15090
15091 project_extension ::=
15092 @b{project} <project_>simple_name @b{extends} path_name @b{is}
15093 @{declarative_item@}
15094 @b{end} <project_>simple_name;
15095
15096 declarative_item ::=
15097 package_declaration |
15098 typed_string_declaration |
15099 other_declarative_item
15100
15101 package_declaration ::=
15102 package_spec | package_renaming
15103
15104 package_spec ::=
15105 @b{package} package_identifier @b{is}
15106 @{simple_declarative_item@}
15107 @b{end} package_identifier ;
15108
15109 package_identifier ::=
15110 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15111 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
15112 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
15113
15114 package_renaming ::==
15115 @b{package} package_identifier @b{renames}
15116 <project_>simple_name.package_identifier ;
15117
15118 typed_string_declaration ::=
15119 @b{type} <typed_string_>_simple_name @b{is}
15120 ( string_literal @{, string_literal@} );
15121
15122 other_declarative_item ::=
15123 attribute_declaration |
15124 typed_variable_declaration |
15125 variable_declaration |
15126 case_construction
15127
15128 attribute_declaration ::=
15129 full_associative_array_declaration |
15130 @b{for} attribute_designator @b{use} expression ;
15131
15132 full_associative_array_declaration ::=
15133 @b{for} <associative_array_attribute_>simple_name @b{use}
15134 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15135
15136 attribute_designator ::=
15137 <simple_attribute_>simple_name |
15138 <associative_array_attribute_>simple_name ( string_literal )
15139
15140 typed_variable_declaration ::=
15141 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
15142
15143 variable_declaration ::=
15144 <variable_>simple_name := expression;
15145
15146 expression ::=
15147 term @{& term@}
15148
15149 term ::=
15150 literal_string |
15151 string_list |
15152 <variable_>name |
15153 external_value |
15154 attribute_reference
15155
15156 string_literal ::=
15157 (same as Ada)
15158
15159 string_list ::=
15160 ( <string_>expression @{ , <string_>expression @} )
15161
15162 external_value ::=
15163 @b{external} ( string_literal [, string_literal] )
15164
15165 attribute_reference ::=
15166 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15167
15168 attribute_prefix ::=
15169 @b{project} |
15170 <project_>simple_name | package_identifier |
15171 <project_>simple_name . package_identifier
15172
15173 case_construction ::=
15174 @b{case} <typed_variable_>name @b{is}
15175 @{case_item@}
15176 @b{end case} ;
15177
15178 case_item ::=
15179 @b{when} discrete_choice_list =>
15180 @{case_construction | attribute_declaration@}
15181
15182 discrete_choice_list ::=
15183 string_literal @{| string_literal@} |
15184 @b{others}
15185
15186 name ::=
15187 simple_name @{. simple_name@}
15188
15189 simple_name ::=
15190 identifier (same as Ada)
15191
15192 @end smallexample
15193
15194 @node The Cross-Referencing Tools gnatxref and gnatfind
15195 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15196 @findex gnatxref
15197 @findex gnatfind
15198
15199 @noindent
15200 The compiler generates cross-referencing information (unless
15201 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15202 This information indicates where in the source each entity is declared and
15203 referenced. Note that entities in package Standard are not included, but
15204 entities in all other predefined units are included in the output.
15205
15206 Before using any of these two tools, you need to compile successfully your
15207 application, so that GNAT gets a chance to generate the cross-referencing
15208 information.
15209
15210 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15211 information to provide the user with the capability to easily locate the
15212 declaration and references to an entity. These tools are quite similar,
15213 the difference being that @code{gnatfind} is intended for locating
15214 definitions and/or references to a specified entity or entities, whereas
15215 @code{gnatxref} is oriented to generating a full report of all
15216 cross-references.
15217
15218 To use these tools, you must not compile your application using the
15219 @option{-gnatx} switch on the @command{gnatmake} command line
15220 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15221 information will not be generated.
15222
15223 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15224 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15225
15226 @menu
15227 * gnatxref Switches::
15228 * gnatfind Switches::
15229 * Project Files for gnatxref and gnatfind::
15230 * Regular Expressions in gnatfind and gnatxref::
15231 * Examples of gnatxref Usage::
15232 * Examples of gnatfind Usage::
15233 @end menu
15234
15235 @node gnatxref Switches
15236 @section @code{gnatxref} Switches
15237
15238 @noindent
15239 The command invocation for @code{gnatxref} is:
15240 @smallexample
15241 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15242 @end smallexample
15243
15244 @noindent
15245 where
15246
15247 @table @var
15248 @item sourcefile1
15249 @itemx sourcefile2
15250 identifies the source files for which a report is to be generated. The
15251 ``with''ed units will be processed too. You must provide at least one file.
15252
15253 These file names are considered to be regular expressions, so for instance
15254 specifying @file{source*.adb} is the same as giving every file in the current
15255 directory whose name starts with @file{source} and whose extension is
15256 @file{adb}.
15257
15258 You shouldn't specify any directory name, just base names. @command{gnatxref}
15259 and @command{gnatfind} will be able to locate these files by themselves using
15260 the source path. If you specify directories, no result is produced.
15261
15262 @end table
15263
15264 @noindent
15265 The switches can be:
15266 @table @option
15267 @c !sort!
15268 @item --version
15269 @cindex @option{--version} @command{gnatxref}
15270 Display Copyright and version, then exit disregarding all other options.
15271
15272 @item --help
15273 @cindex @option{--help} @command{gnatxref}
15274 If @option{--version} was not used, display usage, then exit disregarding
15275 all other options.
15276
15277 @item ^-a^/ALL_FILES^
15278 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15279 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15280 the read-only files found in the library search path. Otherwise, these files
15281 will be ignored. This option can be used to protect Gnat sources or your own
15282 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15283 much faster, and their output much smaller. Read-only here refers to access
15284 or permissions status in the file system for the current user.
15285
15286 @item -aIDIR
15287 @cindex @option{-aIDIR} (@command{gnatxref})
15288 When looking for source files also look in directory DIR. The order in which
15289 source file search is undertaken is the same as for @command{gnatmake}.
15290
15291 @item -aODIR
15292 @cindex @option{-aODIR} (@command{gnatxref})
15293 When searching for library and object files, look in directory
15294 DIR. The order in which library files are searched is the same as for
15295 @command{gnatmake}.
15296
15297 @item -nostdinc
15298 @cindex @option{-nostdinc} (@command{gnatxref})
15299 Do not look for sources in the system default directory.
15300
15301 @item -nostdlib
15302 @cindex @option{-nostdlib} (@command{gnatxref})
15303 Do not look for library files in the system default directory.
15304
15305 @item --RTS=@var{rts-path}
15306 @cindex @option{--RTS} (@command{gnatxref})
15307 Specifies the default location of the runtime library. Same meaning as the
15308 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15309
15310 @item ^-d^/DERIVED_TYPES^
15311 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15312 If this switch is set @code{gnatxref} will output the parent type
15313 reference for each matching derived types.
15314
15315 @item ^-f^/FULL_PATHNAME^
15316 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15317 If this switch is set, the output file names will be preceded by their
15318 directory (if the file was found in the search path). If this switch is
15319 not set, the directory will not be printed.
15320
15321 @item ^-g^/IGNORE_LOCALS^
15322 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15323 If this switch is set, information is output only for library-level
15324 entities, ignoring local entities. The use of this switch may accelerate
15325 @code{gnatfind} and @code{gnatxref}.
15326
15327 @item -IDIR
15328 @cindex @option{-IDIR} (@command{gnatxref})
15329 Equivalent to @samp{-aODIR -aIDIR}.
15330
15331 @item -pFILE
15332 @cindex @option{-pFILE} (@command{gnatxref})
15333 Specify a project file to use @xref{Project Files}.
15334 If you need to use the @file{.gpr}
15335 project files, you should use gnatxref through the GNAT driver
15336 (@command{gnat xref -Pproject}).
15337
15338 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15339 project file in the current directory.
15340
15341 If a project file is either specified or found by the tools, then the content
15342 of the source directory and object directory lines are added as if they
15343 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15344 and @samp{^-aO^OBJECT_SEARCH^}.
15345 @item ^-u^/UNUSED^
15346 Output only unused symbols. This may be really useful if you give your
15347 main compilation unit on the command line, as @code{gnatxref} will then
15348 display every unused entity and 'with'ed package.
15349
15350 @ifclear vms
15351 @item -v
15352 Instead of producing the default output, @code{gnatxref} will generate a
15353 @file{tags} file that can be used by vi. For examples how to use this
15354 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15355 to the standard output, thus you will have to redirect it to a file.
15356 @end ifclear
15357
15358 @end table
15359
15360 @noindent
15361 All these switches may be in any order on the command line, and may even
15362 appear after the file names. They need not be separated by spaces, thus
15363 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15364 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15365
15366 @node gnatfind Switches
15367 @section @code{gnatfind} Switches
15368
15369 @noindent
15370 The command line for @code{gnatfind} is:
15371
15372 @smallexample
15373 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15374 @r{[}@var{file1} @var{file2} @dots{}]
15375 @end smallexample
15376
15377 @noindent
15378 where
15379
15380 @table @var
15381 @item pattern
15382 An entity will be output only if it matches the regular expression found
15383 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15384
15385 Omitting the pattern is equivalent to specifying @samp{*}, which
15386 will match any entity. Note that if you do not provide a pattern, you
15387 have to provide both a sourcefile and a line.
15388
15389 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15390 for matching purposes. At the current time there is no support for
15391 8-bit codes other than Latin-1, or for wide characters in identifiers.
15392
15393 @item sourcefile
15394 @code{gnatfind} will look for references, bodies or declarations
15395 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15396 and column @var{column}. See @ref{Examples of gnatfind Usage}
15397 for syntax examples.
15398
15399 @item line
15400 is a decimal integer identifying the line number containing
15401 the reference to the entity (or entities) to be located.
15402
15403 @item column
15404 is a decimal integer identifying the exact location on the
15405 line of the first character of the identifier for the
15406 entity reference. Columns are numbered from 1.
15407
15408 @item file1 file2 @dots{}
15409 The search will be restricted to these source files. If none are given, then
15410 the search will be done for every library file in the search path.
15411 These file must appear only after the pattern or sourcefile.
15412
15413 These file names are considered to be regular expressions, so for instance
15414 specifying @file{source*.adb} is the same as giving every file in the current
15415 directory whose name starts with @file{source} and whose extension is
15416 @file{adb}.
15417
15418 The location of the spec of the entity will always be displayed, even if it
15419 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
15420 occurrences of the entity in the separate units of the ones given on the
15421 command line will also be displayed.
15422
15423 Note that if you specify at least one file in this part, @code{gnatfind} may
15424 sometimes not be able to find the body of the subprograms.
15425
15426 @end table
15427
15428 @noindent
15429 At least one of 'sourcefile' or 'pattern' has to be present on
15430 the command line.
15431
15432 The following switches are available:
15433 @table @option
15434 @c !sort!
15435
15436 @cindex @option{--version} @command{gnatfind}
15437 Display Copyright and version, then exit disregarding all other options.
15438
15439 @item --help
15440 @cindex @option{--help} @command{gnatfind}
15441 If @option{--version} was not used, display usage, then exit disregarding
15442 all other options.
15443
15444 @item ^-a^/ALL_FILES^
15445 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15446 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15447 the read-only files found in the library search path. Otherwise, these files
15448 will be ignored. This option can be used to protect Gnat sources or your own
15449 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15450 much faster, and their output much smaller. Read-only here refers to access
15451 or permission status in the file system for the current user.
15452
15453 @item -aIDIR
15454 @cindex @option{-aIDIR} (@command{gnatfind})
15455 When looking for source files also look in directory DIR. The order in which
15456 source file search is undertaken is the same as for @command{gnatmake}.
15457
15458 @item -aODIR
15459 @cindex @option{-aODIR} (@command{gnatfind})
15460 When searching for library and object files, look in directory
15461 DIR. The order in which library files are searched is the same as for
15462 @command{gnatmake}.
15463
15464 @item -nostdinc
15465 @cindex @option{-nostdinc} (@command{gnatfind})
15466 Do not look for sources in the system default directory.
15467
15468 @item -nostdlib
15469 @cindex @option{-nostdlib} (@command{gnatfind})
15470 Do not look for library files in the system default directory.
15471
15472 @item --RTS=@var{rts-path}
15473 @cindex @option{--RTS} (@command{gnatfind})
15474 Specifies the default location of the runtime library. Same meaning as the
15475 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15476
15477 @item ^-d^/DERIVED_TYPE_INFORMATION^
15478 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15479 If this switch is set, then @code{gnatfind} will output the parent type
15480 reference for each matching derived types.
15481
15482 @item ^-e^/EXPRESSIONS^
15483 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15484 By default, @code{gnatfind} accept the simple regular expression set for
15485 @samp{pattern}. If this switch is set, then the pattern will be
15486 considered as full Unix-style regular expression.
15487
15488 @item ^-f^/FULL_PATHNAME^
15489 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15490 If this switch is set, the output file names will be preceded by their
15491 directory (if the file was found in the search path). If this switch is
15492 not set, the directory will not be printed.
15493
15494 @item ^-g^/IGNORE_LOCALS^
15495 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15496 If this switch is set, information is output only for library-level
15497 entities, ignoring local entities. The use of this switch may accelerate
15498 @code{gnatfind} and @code{gnatxref}.
15499
15500 @item -IDIR
15501 @cindex @option{-IDIR} (@command{gnatfind})
15502 Equivalent to @samp{-aODIR -aIDIR}.
15503
15504 @item -pFILE
15505 @cindex @option{-pFILE} (@command{gnatfind})
15506 Specify a project file (@pxref{Project Files}) to use.
15507 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15508 project file in the current directory.
15509
15510 If a project file is either specified or found by the tools, then the content
15511 of the source directory and object directory lines are added as if they
15512 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15513 @samp{^-aO^/OBJECT_SEARCH^}.
15514
15515 @item ^-r^/REFERENCES^
15516 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15517 By default, @code{gnatfind} will output only the information about the
15518 declaration, body or type completion of the entities. If this switch is
15519 set, the @code{gnatfind} will locate every reference to the entities in
15520 the files specified on the command line (or in every file in the search
15521 path if no file is given on the command line).
15522
15523 @item ^-s^/PRINT_LINES^
15524 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15525 If this switch is set, then @code{gnatfind} will output the content
15526 of the Ada source file lines were the entity was found.
15527
15528 @item ^-t^/TYPE_HIERARCHY^
15529 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15530 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15531 the specified type. It act like -d option but recursively from parent
15532 type to parent type. When this switch is set it is not possible to
15533 specify more than one file.
15534
15535 @end table
15536
15537 @noindent
15538 All these switches may be in any order on the command line, and may even
15539 appear after the file names. They need not be separated by spaces, thus
15540 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15541 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15542
15543 As stated previously, gnatfind will search in every directory in the
15544 search path. You can force it to look only in the current directory if
15545 you specify @code{*} at the end of the command line.
15546
15547 @node Project Files for gnatxref and gnatfind
15548 @section Project Files for @command{gnatxref} and @command{gnatfind}
15549
15550 @noindent
15551 Project files allow a programmer to specify how to compile its
15552 application, where to find sources, etc. These files are used
15553 @ifclear vms
15554 primarily by GPS, but they can also be used
15555 @end ifclear
15556 by the two tools
15557 @code{gnatxref} and @code{gnatfind}.
15558
15559 A project file name must end with @file{.gpr}. If a single one is
15560 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15561 extract the information from it. If multiple project files are found, none of
15562 them is read, and you have to use the @samp{-p} switch to specify the one
15563 you want to use.
15564
15565 The following lines can be included, even though most of them have default
15566 values which can be used in most cases.
15567 The lines can be entered in any order in the file.
15568 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15569 each line. If you have multiple instances, only the last one is taken into
15570 account.
15571
15572 @table @code
15573 @item src_dir=DIR
15574 [default: @code{"^./^[]^"}]
15575 specifies a directory where to look for source files. Multiple @code{src_dir}
15576 lines can be specified and they will be searched in the order they
15577 are specified.
15578
15579 @item obj_dir=DIR
15580 [default: @code{"^./^[]^"}]
15581 specifies a directory where to look for object and library files. Multiple
15582 @code{obj_dir} lines can be specified, and they will be searched in the order
15583 they are specified
15584
15585 @item comp_opt=SWITCHES
15586 [default: @code{""}]
15587 creates a variable which can be referred to subsequently by using
15588 the @code{$@{comp_opt@}} notation. This is intended to store the default
15589 switches given to @command{gnatmake} and @command{gcc}.
15590
15591 @item bind_opt=SWITCHES
15592 [default: @code{""}]
15593 creates a variable which can be referred to subsequently by using
15594 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15595 switches given to @command{gnatbind}.
15596
15597 @item link_opt=SWITCHES
15598 [default: @code{""}]
15599 creates a variable which can be referred to subsequently by using
15600 the @samp{$@{link_opt@}} notation. This is intended to store the default
15601 switches given to @command{gnatlink}.
15602
15603 @item main=EXECUTABLE
15604 [default: @code{""}]
15605 specifies the name of the executable for the application. This variable can
15606 be referred to in the following lines by using the @samp{$@{main@}} notation.
15607
15608 @ifset vms
15609 @item comp_cmd=COMMAND
15610 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15611 @end ifset
15612 @ifclear vms
15613 @item comp_cmd=COMMAND
15614 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15615 @end ifclear
15616 specifies the command used to compile a single file in the application.
15617
15618 @ifset vms
15619 @item make_cmd=COMMAND
15620 [default: @code{"GNAT MAKE $@{main@}
15621 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15622 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15623 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15624 @end ifset
15625 @ifclear vms
15626 @item make_cmd=COMMAND
15627 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15628 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15629 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15630 @end ifclear
15631 specifies the command used to recompile the whole application.
15632
15633 @item run_cmd=COMMAND
15634 [default: @code{"$@{main@}"}]
15635 specifies the command used to run the application.
15636
15637 @item debug_cmd=COMMAND
15638 [default: @code{"gdb $@{main@}"}]
15639 specifies the command used to debug the application
15640
15641 @end table
15642
15643 @noindent
15644 @command{gnatxref} and @command{gnatfind} only take into account the
15645 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15646
15647 @node Regular Expressions in gnatfind and gnatxref
15648 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15649
15650 @noindent
15651 As specified in the section about @command{gnatfind}, the pattern can be a
15652 regular expression. Actually, there are to set of regular expressions
15653 which are recognized by the program:
15654
15655 @table @code
15656 @item globbing patterns
15657 These are the most usual regular expression. They are the same that you
15658 generally used in a Unix shell command line, or in a DOS session.
15659
15660 Here is a more formal grammar:
15661 @smallexample
15662 @group
15663 @iftex
15664 @leftskip=.5cm
15665 @end iftex
15666 regexp ::= term
15667 term ::= elmt -- matches elmt
15668 term ::= elmt elmt -- concatenation (elmt then elmt)
15669 term ::= * -- any string of 0 or more characters
15670 term ::= ? -- matches any character
15671 term ::= [char @{char@}] -- matches any character listed
15672 term ::= [char - char] -- matches any character in range
15673 @end group
15674 @end smallexample
15675
15676 @item full regular expression
15677 The second set of regular expressions is much more powerful. This is the
15678 type of regular expressions recognized by utilities such a @file{grep}.
15679
15680 The following is the form of a regular expression, expressed in Ada
15681 reference manual style BNF is as follows
15682
15683 @smallexample
15684 @iftex
15685 @leftskip=.5cm
15686 @end iftex
15687 @group
15688 regexp ::= term @{| term@} -- alternation (term or term @dots{})
15689
15690 term ::= item @{item@} -- concatenation (item then item)
15691
15692 item ::= elmt -- match elmt
15693 item ::= elmt * -- zero or more elmt's
15694 item ::= elmt + -- one or more elmt's
15695 item ::= elmt ? -- matches elmt or nothing
15696 @end group
15697 @group
15698 elmt ::= nschar -- matches given character
15699 elmt ::= [nschar @{nschar@}] -- matches any character listed
15700 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15701 elmt ::= [char - char] -- matches chars in given range
15702 elmt ::= \ char -- matches given character
15703 elmt ::= . -- matches any single character
15704 elmt ::= ( regexp ) -- parens used for grouping
15705
15706 char ::= any character, including special characters
15707 nschar ::= any character except ()[].*+?^^^
15708 @end group
15709 @end smallexample
15710
15711 Following are a few examples:
15712
15713 @table @samp
15714 @item abcde|fghi
15715 will match any of the two strings @samp{abcde} and @samp{fghi},
15716
15717 @item abc*d
15718 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15719 @samp{abcccd}, and so on,
15720
15721 @item [a-z]+
15722 will match any string which has only lowercase characters in it (and at
15723 least one character.
15724
15725 @end table
15726 @end table
15727
15728 @node Examples of gnatxref Usage
15729 @section Examples of @code{gnatxref} Usage
15730
15731 @subsection General Usage
15732
15733 @noindent
15734 For the following examples, we will consider the following units:
15735
15736 @smallexample @c ada
15737 @group
15738 @cartouche
15739 main.ads:
15740 1: with Bar;
15741 2: package Main is
15742 3: procedure Foo (B : in Integer);
15743 4: C : Integer;
15744 5: private
15745 6: D : Integer;
15746 7: end Main;
15747
15748 main.adb:
15749 1: package body Main is
15750 2: procedure Foo (B : in Integer) is
15751 3: begin
15752 4: C := B;
15753 5: D := B;
15754 6: Bar.Print (B);
15755 7: Bar.Print (C);
15756 8: end Foo;
15757 9: end Main;
15758
15759 bar.ads:
15760 1: package Bar is
15761 2: procedure Print (B : Integer);
15762 3: end bar;
15763 @end cartouche
15764 @end group
15765 @end smallexample
15766
15767 @table @code
15768
15769 @noindent
15770 The first thing to do is to recompile your application (for instance, in
15771 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15772 the cross-referencing information.
15773 You can then issue any of the following commands:
15774
15775 @item gnatxref main.adb
15776 @code{gnatxref} generates cross-reference information for main.adb
15777 and every unit 'with'ed by main.adb.
15778
15779 The output would be:
15780 @smallexample
15781 @iftex
15782 @leftskip=0cm
15783 @end iftex
15784 B Type: Integer
15785 Decl: bar.ads 2:22
15786 B Type: Integer
15787 Decl: main.ads 3:20
15788 Body: main.adb 2:20
15789 Ref: main.adb 4:13 5:13 6:19
15790 Bar Type: Unit
15791 Decl: bar.ads 1:9
15792 Ref: main.adb 6:8 7:8
15793 main.ads 1:6
15794 C Type: Integer
15795 Decl: main.ads 4:5
15796 Modi: main.adb 4:8
15797 Ref: main.adb 7:19
15798 D Type: Integer
15799 Decl: main.ads 6:5
15800 Modi: main.adb 5:8
15801 Foo Type: Unit
15802 Decl: main.ads 3:15
15803 Body: main.adb 2:15
15804 Main Type: Unit
15805 Decl: main.ads 2:9
15806 Body: main.adb 1:14
15807 Print Type: Unit
15808 Decl: bar.ads 2:15
15809 Ref: main.adb 6:12 7:12
15810 @end smallexample
15811
15812 @noindent
15813 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15814 its body is in main.adb, line 1, column 14 and is not referenced any where.
15815
15816 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15817 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15818
15819 @item gnatxref package1.adb package2.ads
15820 @code{gnatxref} will generates cross-reference information for
15821 package1.adb, package2.ads and any other package 'with'ed by any
15822 of these.
15823
15824 @end table
15825
15826 @ifclear vms
15827 @subsection Using gnatxref with vi
15828
15829 @code{gnatxref} can generate a tags file output, which can be used
15830 directly from @command{vi}. Note that the standard version of @command{vi}
15831 will not work properly with overloaded symbols. Consider using another
15832 free implementation of @command{vi}, such as @command{vim}.
15833
15834 @smallexample
15835 $ gnatxref -v gnatfind.adb > tags
15836 @end smallexample
15837
15838 @noindent
15839 will generate the tags file for @code{gnatfind} itself (if the sources
15840 are in the search path!).
15841
15842 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15843 (replacing @var{entity} by whatever you are looking for), and vi will
15844 display a new file with the corresponding declaration of entity.
15845 @end ifclear
15846
15847 @node Examples of gnatfind Usage
15848 @section Examples of @code{gnatfind} Usage
15849
15850 @table @code
15851
15852 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15853 Find declarations for all entities xyz referenced at least once in
15854 main.adb. The references are search in every library file in the search
15855 path.
15856
15857 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15858 switch is set)
15859
15860 The output will look like:
15861 @smallexample
15862 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15863 ^directory/^[directory]^main.adb:24:10: xyz <= body
15864 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15865 @end smallexample
15866
15867 @noindent
15868 that is to say, one of the entities xyz found in main.adb is declared at
15869 line 12 of main.ads (and its body is in main.adb), and another one is
15870 declared at line 45 of foo.ads
15871
15872 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15873 This is the same command as the previous one, instead @code{gnatfind} will
15874 display the content of the Ada source file lines.
15875
15876 The output will look like:
15877
15878 @smallexample
15879 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15880 procedure xyz;
15881 ^directory/^[directory]^main.adb:24:10: xyz <= body
15882 procedure xyz is
15883 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15884 xyz : Integer;
15885 @end smallexample
15886
15887 @noindent
15888 This can make it easier to find exactly the location your are looking
15889 for.
15890
15891 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15892 Find references to all entities containing an x that are
15893 referenced on line 123 of main.ads.
15894 The references will be searched only in main.ads and foo.adb.
15895
15896 @item gnatfind main.ads:123
15897 Find declarations and bodies for all entities that are referenced on
15898 line 123 of main.ads.
15899
15900 This is the same as @code{gnatfind "*":main.adb:123}.
15901
15902 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15903 Find the declaration for the entity referenced at column 45 in
15904 line 123 of file main.adb in directory mydir. Note that it
15905 is usual to omit the identifier name when the column is given,
15906 since the column position identifies a unique reference.
15907
15908 The column has to be the beginning of the identifier, and should not
15909 point to any character in the middle of the identifier.
15910
15911 @end table
15912
15913 @c *********************************
15914 @node The GNAT Pretty-Printer gnatpp
15915 @chapter The GNAT Pretty-Printer @command{gnatpp}
15916 @findex gnatpp
15917 @cindex Pretty-Printer
15918
15919 @noindent
15920 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15921 for source reformatting / pretty-printing.
15922 It takes an Ada source file as input and generates a reformatted
15923 version as output.
15924 You can specify various style directives via switches; e.g.,
15925 identifier case conventions, rules of indentation, and comment layout.
15926
15927 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15928 tree for the input source and thus requires the input to be syntactically and
15929 semantically legal.
15930 If this condition is not met, @command{gnatpp} will terminate with an
15931 error message; no output file will be generated.
15932
15933 If the source files presented to @command{gnatpp} contain
15934 preprocessing directives, then the output file will
15935 correspond to the generated source after all
15936 preprocessing is carried out. There is no way
15937 using @command{gnatpp} to obtain pretty printed files that
15938 include the preprocessing directives.
15939
15940 If the compilation unit
15941 contained in the input source depends semantically upon units located
15942 outside the current directory, you have to provide the source search path
15943 when invoking @command{gnatpp}, if these units are contained in files with
15944 names that do not follow the GNAT file naming rules, you have to provide
15945 the configuration file describing the corresponding naming scheme;
15946 see the description of the @command{gnatpp}
15947 switches below. Another possibility is to use a project file and to
15948 call @command{gnatpp} through the @command{gnat} driver
15949
15950 The @command{gnatpp} command has the form
15951
15952 @smallexample
15953 $ gnatpp @ovar{switches} @var{filename}
15954 @end smallexample
15955
15956 @noindent
15957 where
15958 @itemize @bullet
15959 @item
15960 @var{switches} is an optional sequence of switches defining such properties as
15961 the formatting rules, the source search path, and the destination for the
15962 output source file
15963
15964 @item
15965 @var{filename} is the name (including the extension) of the source file to
15966 reformat; ``wildcards'' or several file names on the same gnatpp command are
15967 allowed. The file name may contain path information; it does not have to
15968 follow the GNAT file naming rules
15969 @end itemize
15970
15971 @menu
15972 * Switches for gnatpp::
15973 * Formatting Rules::
15974 @end menu
15975
15976 @node Switches for gnatpp
15977 @section Switches for @command{gnatpp}
15978
15979 @noindent
15980 The following subsections describe the various switches accepted by
15981 @command{gnatpp}, organized by category.
15982
15983 @ifclear vms
15984 You specify a switch by supplying a name and generally also a value.
15985 In many cases the values for a switch with a given name are incompatible with
15986 each other
15987 (for example the switch that controls the casing of a reserved word may have
15988 exactly one value: upper case, lower case, or
15989 mixed case) and thus exactly one such switch can be in effect for an
15990 invocation of @command{gnatpp}.
15991 If more than one is supplied, the last one is used.
15992 However, some values for the same switch are mutually compatible.
15993 You may supply several such switches to @command{gnatpp}, but then
15994 each must be specified in full, with both the name and the value.
15995 Abbreviated forms (the name appearing once, followed by each value) are
15996 not permitted.
15997 For example, to set
15998 the alignment of the assignment delimiter both in declarations and in
15999 assignment statements, you must write @option{-A2A3}
16000 (or @option{-A2 -A3}), but not @option{-A23}.
16001 @end ifclear
16002
16003 @ifset vms
16004 In many cases the set of options for a given qualifier are incompatible with
16005 each other (for example the qualifier that controls the casing of a reserved
16006 word may have exactly one option, which specifies either upper case, lower
16007 case, or mixed case), and thus exactly one such option can be in effect for
16008 an invocation of @command{gnatpp}.
16009 If more than one is supplied, the last one is used.
16010 However, some qualifiers have options that are mutually compatible,
16011 and then you may then supply several such options when invoking
16012 @command{gnatpp}.
16013 @end ifset
16014
16015 In most cases, it is obvious whether or not the
16016 ^values for a switch with a given name^options for a given qualifier^
16017 are compatible with each other.
16018 When the semantics might not be evident, the summaries below explicitly
16019 indicate the effect.
16020
16021 @menu
16022 * Alignment Control::
16023 * Casing Control::
16024 * Construct Layout Control::
16025 * General Text Layout Control::
16026 * Other Formatting Options::
16027 * Setting the Source Search Path::
16028 * Output File Control::
16029 * Other gnatpp Switches::
16030 @end menu
16031
16032 @node Alignment Control
16033 @subsection Alignment Control
16034 @cindex Alignment control in @command{gnatpp}
16035
16036 @noindent
16037 Programs can be easier to read if certain constructs are vertically aligned.
16038 By default all alignments are set ON.
16039 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16040 OFF, and then use one or more of the other
16041 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16042 to activate alignment for specific constructs.
16043
16044 @table @option
16045 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16046
16047 @ifset vms
16048 @item /ALIGN=ON
16049 Set all alignments to ON
16050 @end ifset
16051
16052 @item ^-A0^/ALIGN=OFF^
16053 Set all alignments to OFF
16054
16055 @item ^-A1^/ALIGN=COLONS^
16056 Align @code{:} in declarations
16057
16058 @item ^-A2^/ALIGN=DECLARATIONS^
16059 Align @code{:=} in initializations in declarations
16060
16061 @item ^-A3^/ALIGN=STATEMENTS^
16062 Align @code{:=} in assignment statements
16063
16064 @item ^-A4^/ALIGN=ARROWS^
16065 Align @code{=>} in associations
16066
16067 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16068 Align @code{at} keywords in the component clauses in record
16069 representation clauses
16070 @end table
16071
16072 @noindent
16073 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16074 is allowed.
16075
16076 @node Casing Control
16077 @subsection Casing Control
16078 @cindex Casing control in @command{gnatpp}
16079
16080 @noindent
16081 @command{gnatpp} allows you to specify the casing for reserved words,
16082 pragma names, attribute designators and identifiers.
16083 For identifiers you may define a
16084 general rule for name casing but also override this rule
16085 via a set of dictionary files.
16086
16087 Three types of casing are supported: lower case, upper case, and mixed case.
16088 Lower and upper case are self-explanatory (but since some letters in
16089 Latin1 and other GNAT-supported character sets
16090 exist only in lower-case form, an upper case conversion will have no
16091 effect on them.)
16092 ``Mixed case'' means that the first letter, and also each letter immediately
16093 following an underscore, are converted to their uppercase forms;
16094 all the other letters are converted to their lowercase forms.
16095
16096 @table @option
16097 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16098 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16099 Attribute designators are lower case
16100
16101 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16102 Attribute designators are upper case
16103
16104 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16105 Attribute designators are mixed case (this is the default)
16106
16107 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16108 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16109 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16110 lower case (this is the default)
16111
16112 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16113 Keywords are upper case
16114
16115 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16116 @item ^-nD^/NAME_CASING=AS_DECLARED^
16117 Name casing for defining occurrences are as they appear in the source file
16118 (this is the default)
16119
16120 @item ^-nU^/NAME_CASING=UPPER_CASE^
16121 Names are in upper case
16122
16123 @item ^-nL^/NAME_CASING=LOWER_CASE^
16124 Names are in lower case
16125
16126 @item ^-nM^/NAME_CASING=MIXED_CASE^
16127 Names are in mixed case
16128
16129 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16130 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16131 Pragma names are lower case
16132
16133 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16134 Pragma names are upper case
16135
16136 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16137 Pragma names are mixed case (this is the default)
16138
16139 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16140 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16141 Use @var{file} as a @emph{dictionary file} that defines
16142 the casing for a set of specified names,
16143 thereby overriding the effect on these names by
16144 any explicit or implicit
16145 ^-n^/NAME_CASING^ switch.
16146 To supply more than one dictionary file,
16147 use ^several @option{-D} switches^a list of files as options^.
16148
16149 @noindent
16150 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16151 to define the casing for the Ada predefined names and
16152 the names declared in the GNAT libraries.
16153
16154 @item ^-D-^/SPECIFIC_CASING^
16155 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16156 Do not use the default dictionary file;
16157 instead, use the casing
16158 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16159 dictionary file(s)
16160 @end table
16161
16162 @noindent
16163 The structure of a dictionary file, and details on the conventions
16164 used in the default dictionary file, are defined in @ref{Name Casing}.
16165
16166 The @option{^-D-^/SPECIFIC_CASING^} and
16167 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16168 compatible.
16169
16170 @node Construct Layout Control
16171 @subsection Construct Layout Control
16172 @cindex Layout control in @command{gnatpp}
16173
16174 @noindent
16175 This group of @command{gnatpp} switches controls the layout of comments and
16176 complex syntactic constructs. See @ref{Formatting Comments} for details
16177 on their effect.
16178
16179 @table @option
16180 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16181 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16182 All the comments remain unchanged
16183
16184 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16185 GNAT-style comment line indentation (this is the default).
16186
16187 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16188 Reference-manual comment line indentation.
16189
16190 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16191 GNAT-style comment beginning
16192
16193 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16194 Reformat comment blocks
16195
16196 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16197 Keep unchanged special form comments
16198
16199 Reformat comment blocks
16200
16201 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16202 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16203 GNAT-style layout (this is the default)
16204
16205 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16206 Compact layout
16207
16208 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16209 Uncompact layout
16210
16211 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16212 @item ^-N^/NOTABS^
16213 All the VT characters are removed from the comment text. All the HT characters
16214 are expanded with the sequences of space characters to get to the next tab
16215 stops.
16216
16217 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16218 @item ^--no-separate-is^/NO_SEPARATE_IS^
16219 Do not place the keyword @code{is} on a separate line in a subprogram body in
16220 case if the spec occupies more then one line.
16221
16222 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16223 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16224 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16225 keyword @code{then} in IF statements on a separate line.
16226
16227 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16228 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16229 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16230 keyword @code{then} in IF statements on a separate line. This option is
16231 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16232
16233 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16234 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16235 Start each USE clause in a context clause from a separate line.
16236
16237 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16238 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16239 Use a separate line for a loop or block statement name, but do not use an extra
16240 indentation level for the statement itself.
16241
16242 @end table
16243
16244 @ifclear vms
16245 @noindent
16246 The @option{-c1} and @option{-c2} switches are incompatible.
16247 The @option{-c3} and @option{-c4} switches are compatible with each other and
16248 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16249 the other comment formatting switches.
16250
16251 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16252 @end ifclear
16253
16254 @ifset vms
16255 @noindent
16256 For the @option{/COMMENTS_LAYOUT} qualifier:
16257 @itemize @bullet
16258 @item
16259 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16260 @item
16261 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16262 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16263 @end itemize
16264
16265 @noindent
16266 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16267 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16268 @end ifset
16269
16270 @node General Text Layout Control
16271 @subsection General Text Layout Control
16272
16273 @noindent
16274 These switches allow control over line length and indentation.
16275
16276 @table @option
16277 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16278 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16279 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16280
16281 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16282 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16283 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16284
16285 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16286 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16287 Indentation level for continuation lines (relative to the line being
16288 continued), @var{nnn} from 1@dots{}9.
16289 The default
16290 value is one less then the (normal) indentation level, unless the
16291 indentation is set to 1 (in which case the default value for continuation
16292 line indentation is also 1)
16293 @end table
16294
16295 @node Other Formatting Options
16296 @subsection Other Formatting Options
16297
16298 @noindent
16299 These switches control the inclusion of missing end/exit labels, and
16300 the indentation level in @b{case} statements.
16301
16302 @table @option
16303 @item ^-e^/NO_MISSED_LABELS^
16304 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16305 Do not insert missing end/exit labels. An end label is the name of
16306 a construct that may optionally be repeated at the end of the
16307 construct's declaration;
16308 e.g., the names of packages, subprograms, and tasks.
16309 An exit label is the name of a loop that may appear as target
16310 of an exit statement within the loop.
16311 By default, @command{gnatpp} inserts these end/exit labels when
16312 they are absent from the original source. This option suppresses such
16313 insertion, so that the formatted source reflects the original.
16314
16315 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16316 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16317 Insert a Form Feed character after a pragma Page.
16318
16319 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16320 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16321 Do not use an additional indentation level for @b{case} alternatives
16322 and variants if there are @var{nnn} or more (the default
16323 value is 10).
16324 If @var{nnn} is 0, an additional indentation level is
16325 used for @b{case} alternatives and variants regardless of their number.
16326 @end table
16327
16328 @node Setting the Source Search Path
16329 @subsection Setting the Source Search Path
16330
16331 @noindent
16332 To define the search path for the input source file, @command{gnatpp}
16333 uses the same switches as the GNAT compiler, with the same effects.
16334
16335 @table @option
16336 @item ^-I^/SEARCH=^@var{dir}
16337 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16338 The same as the corresponding gcc switch
16339
16340 @item ^-I-^/NOCURRENT_DIRECTORY^
16341 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16342 The same as the corresponding gcc switch
16343
16344 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16345 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16346 The same as the corresponding gcc switch
16347
16348 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16349 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16350 The same as the corresponding gcc switch
16351
16352 @end table
16353
16354 @node Output File Control
16355 @subsection Output File Control
16356
16357 @noindent
16358 By default the output is sent to the file whose name is obtained by appending
16359 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16360 (if the file with this name already exists, it is unconditionally overwritten).
16361 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16362 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16363 as output file.
16364 The output may be redirected by the following switches:
16365
16366 @table @option
16367 @item ^-pipe^/STANDARD_OUTPUT^
16368 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16369 Send the output to @code{Standard_Output}
16370
16371 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16372 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16373 Write the output into @var{output_file}.
16374 If @var{output_file} already exists, @command{gnatpp} terminates without
16375 reading or processing the input file.
16376
16377 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16378 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16379 Write the output into @var{output_file}, overwriting the existing file
16380 (if one is present).
16381
16382 @item ^-r^/REPLACE^
16383 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16384 Replace the input source file with the reformatted output, and copy the
16385 original input source into the file whose name is obtained by appending the
16386 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16387 If a file with this name already exists, @command{gnatpp} terminates without
16388 reading or processing the input file.
16389
16390 @item ^-rf^/OVERRIDING_REPLACE^
16391 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16392 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16393 already exists, it is overwritten.
16394
16395 @item ^-rnb^/REPLACE_NO_BACKUP^
16396 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16397 Replace the input source file with the reformatted output without
16398 creating any backup copy of the input source.
16399
16400 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16401 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16402 Specifies the format of the reformatted output file. The @var{xxx}
16403 ^string specified with the switch^option^ may be either
16404 @itemize @bullet
16405 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16406 @item ``@option{^crlf^CRLF^}''
16407 the same as @option{^crlf^CRLF^}
16408 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16409 @item ``@option{^lf^LF^}''
16410 the same as @option{^unix^UNIX^}
16411 @end itemize
16412
16413 @item ^-W^/RESULT_ENCODING=^@var{e}
16414 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16415 Specify the wide character encoding method used to write the code in the
16416 result file
16417 @var{e} is one of the following:
16418
16419 @itemize @bullet
16420
16421 @item ^h^HEX^
16422 Hex encoding
16423
16424 @item ^u^UPPER^
16425 Upper half encoding
16426
16427 @item ^s^SHIFT_JIS^
16428 Shift/JIS encoding
16429
16430 @item ^e^EUC^
16431 EUC encoding
16432
16433 @item ^8^UTF8^
16434 UTF-8 encoding
16435
16436 @item ^b^BRACKETS^
16437 Brackets encoding (default value)
16438 @end itemize
16439
16440 @end table
16441
16442 @noindent
16443 Options @option{^-pipe^/STANDARD_OUTPUT^},
16444 @option{^-o^/OUTPUT^} and
16445 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16446 contains only one file to reformat.
16447 Option
16448 @option{^--eol^/END_OF_LINE^}
16449 and
16450 @option{^-W^/RESULT_ENCODING^}
16451 cannot be used together
16452 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16453
16454 @node Other gnatpp Switches
16455 @subsection Other @code{gnatpp} Switches
16456
16457 @noindent
16458 The additional @command{gnatpp} switches are defined in this subsection.
16459
16460 @table @option
16461 @item ^-files @var{filename}^/FILES=@var{output_file}^
16462 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16463 Take the argument source files from the specified file. This file should be an
16464 ordinary textual file containing file names separated by spaces or
16465 line breaks. You can use this switch more then once in the same call to
16466 @command{gnatpp}. You also can combine this switch with explicit list of
16467 files.
16468
16469 @item ^-v^/VERBOSE^
16470 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16471 Verbose mode;
16472 @command{gnatpp} generates version information and then
16473 a trace of the actions it takes to produce or obtain the ASIS tree.
16474
16475 @item ^-w^/WARNINGS^
16476 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16477 Warning mode;
16478 @command{gnatpp} generates a warning whenever it cannot provide
16479 a required layout in the result source.
16480 @end table
16481
16482 @node Formatting Rules
16483 @section Formatting Rules
16484
16485 @noindent
16486 The following subsections show how @command{gnatpp} treats ``white space'',
16487 comments, program layout, and name casing.
16488 They provide the detailed descriptions of the switches shown above.
16489
16490 @menu
16491 * White Space and Empty Lines::
16492 * Formatting Comments::
16493 * Construct Layout::
16494 * Name Casing::
16495 @end menu
16496
16497 @node White Space and Empty Lines
16498 @subsection White Space and Empty Lines
16499
16500 @noindent
16501 @command{gnatpp} does not have an option to control space characters.
16502 It will add or remove spaces according to the style illustrated by the
16503 examples in the @cite{Ada Reference Manual}.
16504
16505 The only format effectors
16506 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16507 that will appear in the output file are platform-specific line breaks,
16508 and also format effectors within (but not at the end of) comments.
16509 In particular, each horizontal tab character that is not inside
16510 a comment will be treated as a space and thus will appear in the
16511 output file as zero or more spaces depending on
16512 the reformatting of the line in which it appears.
16513 The only exception is a Form Feed character, which is inserted after a
16514 pragma @code{Page} when @option{-ff} is set.
16515
16516 The output file will contain no lines with trailing ``white space'' (spaces,
16517 format effectors).
16518
16519 Empty lines in the original source are preserved
16520 only if they separate declarations or statements.
16521 In such contexts, a
16522 sequence of two or more empty lines is replaced by exactly one empty line.
16523 Note that a blank line will be removed if it separates two ``comment blocks''
16524 (a comment block is a sequence of whole-line comments).
16525 In order to preserve a visual separation between comment blocks, use an
16526 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16527 Likewise, if for some reason you wish to have a sequence of empty lines,
16528 use a sequence of empty comments instead.
16529
16530 @node Formatting Comments
16531 @subsection Formatting Comments
16532
16533 @noindent
16534 Comments in Ada code are of two kinds:
16535 @itemize @bullet
16536 @item
16537 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16538 ``white space'') on a line
16539
16540 @item
16541 an @emph{end-of-line comment}, which follows some other Ada lexical element
16542 on the same line.
16543 @end itemize
16544
16545 @noindent
16546 The indentation of a whole-line comment is that of either
16547 the preceding or following line in
16548 the formatted source, depending on switch settings as will be described below.
16549
16550 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16551 between the end of the preceding Ada lexical element and the beginning
16552 of the comment as appear in the original source,
16553 unless either the comment has to be split to
16554 satisfy the line length limitation, or else the next line contains a
16555 whole line comment that is considered a continuation of this end-of-line
16556 comment (because it starts at the same position).
16557 In the latter two
16558 cases, the start of the end-of-line comment is moved right to the nearest
16559 multiple of the indentation level.
16560 This may result in a ``line overflow'' (the right-shifted comment extending
16561 beyond the maximum line length), in which case the comment is split as
16562 described below.
16563
16564 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16565 (GNAT-style comment line indentation)
16566 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16567 (reference-manual comment line indentation).
16568 With reference-manual style, a whole-line comment is indented as if it
16569 were a declaration or statement at the same place
16570 (i.e., according to the indentation of the preceding line(s)).
16571 With GNAT style, a whole-line comment that is immediately followed by an
16572 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16573 word @b{begin}, is indented based on the construct that follows it.
16574
16575 For example:
16576 @smallexample @c ada
16577 @cartouche
16578 if A then
16579 null;
16580 -- some comment
16581 else
16582 null;
16583 end if;
16584 @end cartouche
16585 @end smallexample
16586
16587 @noindent
16588 Reference-manual indentation produces:
16589
16590 @smallexample @c ada
16591 @cartouche
16592 if A then
16593 null;
16594 -- some comment
16595 else
16596 null;
16597 end if;
16598 @end cartouche
16599 @end smallexample
16600
16601 @noindent
16602 while GNAT-style indentation produces:
16603
16604 @smallexample @c ada
16605 @cartouche
16606 if A then
16607 null;
16608 -- some comment
16609 else
16610 null;
16611 end if;
16612 @end cartouche
16613 @end smallexample
16614
16615 @noindent
16616 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16617 (GNAT style comment beginning) has the following
16618 effect:
16619
16620 @itemize @bullet
16621 @item
16622 For each whole-line comment that does not end with two hyphens,
16623 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16624 to ensure that there are at least two spaces between these hyphens and the
16625 first non-blank character of the comment.
16626 @end itemize
16627
16628 @noindent
16629 For an end-of-line comment, if in the original source the next line is a
16630 whole-line comment that starts at the same position
16631 as the end-of-line comment,
16632 then the whole-line comment (and all whole-line comments
16633 that follow it and that start at the same position)
16634 will start at this position in the output file.
16635
16636 @noindent
16637 That is, if in the original source we have:
16638
16639 @smallexample @c ada
16640 @cartouche
16641 begin
16642 A := B + C; -- B must be in the range Low1..High1
16643 -- C must be in the range Low2..High2
16644 --B+C will be in the range Low1+Low2..High1+High2
16645 X := X + 1;
16646 @end cartouche
16647 @end smallexample
16648
16649 @noindent
16650 Then in the formatted source we get
16651
16652 @smallexample @c ada
16653 @cartouche
16654 begin
16655 A := B + C; -- B must be in the range Low1..High1
16656 -- C must be in the range Low2..High2
16657 -- B+C will be in the range Low1+Low2..High1+High2
16658 X := X + 1;
16659 @end cartouche
16660 @end smallexample
16661
16662 @noindent
16663 A comment that exceeds the line length limit will be split.
16664 Unless switch
16665 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16666 the line belongs to a reformattable block, splitting the line generates a
16667 @command{gnatpp} warning.
16668 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16669 comments may be reformatted in typical
16670 word processor style (that is, moving words between lines and putting as
16671 many words in a line as possible).
16672
16673 @noindent
16674 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16675 that has a special format (that is, a character that is neither a letter nor digit
16676 not white space nor line break immediately following the leading @code{--} of
16677 the comment) should be without any change moved from the argument source
16678 into reformatted source. This switch allows to preserve comments that are used
16679 as a special marks in the code (e.g.@: SPARK annotation).
16680
16681 @node Construct Layout
16682 @subsection Construct Layout
16683
16684 @noindent
16685 In several cases the suggested layout in the Ada Reference Manual includes
16686 an extra level of indentation that many programmers prefer to avoid. The
16687 affected cases include:
16688
16689 @itemize @bullet
16690
16691 @item Record type declaration (RM 3.8)
16692
16693 @item Record representation clause (RM 13.5.1)
16694
16695 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16696
16697 @item Block statement in case if a block has a statement identifier (RM 5.6)
16698 @end itemize
16699
16700 @noindent
16701 In compact mode (when GNAT style layout or compact layout is set),
16702 the pretty printer uses one level of indentation instead
16703 of two. This is achieved in the record definition and record representation
16704 clause cases by putting the @code{record} keyword on the same line as the
16705 start of the declaration or representation clause, and in the block and loop
16706 case by putting the block or loop header on the same line as the statement
16707 identifier.
16708
16709 @noindent
16710 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16711 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16712 layout on the one hand, and uncompact layout
16713 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16714 can be illustrated by the following examples:
16715
16716 @iftex
16717 @cartouche
16718 @multitable @columnfractions .5 .5
16719 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16720
16721 @item
16722 @smallexample @c ada
16723 type q is record
16724 a : integer;
16725 b : integer;
16726 end record;
16727 @end smallexample
16728 @tab
16729 @smallexample @c ada
16730 type q is
16731 record
16732 a : integer;
16733 b : integer;
16734 end record;
16735 @end smallexample
16736
16737 @item
16738 @smallexample @c ada
16739 for q use record
16740 a at 0 range 0 .. 31;
16741 b at 4 range 0 .. 31;
16742 end record;
16743 @end smallexample
16744 @tab
16745 @smallexample @c ada
16746 for q use
16747 record
16748 a at 0 range 0 .. 31;
16749 b at 4 range 0 .. 31;
16750 end record;
16751 @end smallexample
16752
16753 @item
16754 @smallexample @c ada
16755 Block : declare
16756 A : Integer := 3;
16757 begin
16758 Proc (A, A);
16759 end Block;
16760 @end smallexample
16761 @tab
16762 @smallexample @c ada
16763 Block :
16764 declare
16765 A : Integer := 3;
16766 begin
16767 Proc (A, A);
16768 end Block;
16769 @end smallexample
16770
16771 @item
16772 @smallexample @c ada
16773 Clear : for J in 1 .. 10 loop
16774 A (J) := 0;
16775 end loop Clear;
16776 @end smallexample
16777 @tab
16778 @smallexample @c ada
16779 Clear :
16780 for J in 1 .. 10 loop
16781 A (J) := 0;
16782 end loop Clear;
16783 @end smallexample
16784 @end multitable
16785 @end cartouche
16786 @end iftex
16787
16788 @ifnottex
16789 @smallexample
16790 @cartouche
16791 GNAT style, compact layout Uncompact layout
16792
16793 type q is record type q is
16794 a : integer; record
16795 b : integer; a : integer;
16796 end record; b : integer;
16797 end record;
16798
16799 for q use record for q use
16800 a at 0 range 0 .. 31; record
16801 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16802 end record; b at 4 range 0 .. 31;
16803 end record;
16804
16805 Block : declare Block :
16806 A : Integer := 3; declare
16807 begin A : Integer := 3;
16808 Proc (A, A); begin
16809 end Block; Proc (A, A);
16810 end Block;
16811
16812 Clear : for J in 1 .. 10 loop Clear :
16813 A (J) := 0; for J in 1 .. 10 loop
16814 end loop Clear; A (J) := 0;
16815 end loop Clear;
16816 @end cartouche
16817 @end smallexample
16818 @end ifnottex
16819
16820 @noindent
16821 A further difference between GNAT style layout and compact layout is that
16822 GNAT style layout inserts empty lines as separation for
16823 compound statements, return statements and bodies.
16824
16825 Note that the layout specified by
16826 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16827 for named block and loop statements overrides the layout defined by these
16828 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16829 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16830 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16831
16832 @node Name Casing
16833 @subsection Name Casing
16834
16835 @noindent
16836 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16837 the same casing as the corresponding defining identifier.
16838
16839 You control the casing for defining occurrences via the
16840 @option{^-n^/NAME_CASING^} switch.
16841 @ifclear vms
16842 With @option{-nD} (``as declared'', which is the default),
16843 @end ifclear
16844 @ifset vms
16845 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16846 @end ifset
16847 defining occurrences appear exactly as in the source file
16848 where they are declared.
16849 The other ^values for this switch^options for this qualifier^ ---
16850 @option{^-nU^UPPER_CASE^},
16851 @option{^-nL^LOWER_CASE^},
16852 @option{^-nM^MIXED_CASE^} ---
16853 result in
16854 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16855 If @command{gnatpp} changes the casing of a defining
16856 occurrence, it analogously changes the casing of all the
16857 usage occurrences of this name.
16858
16859 If the defining occurrence of a name is not in the source compilation unit
16860 currently being processed by @command{gnatpp}, the casing of each reference to
16861 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16862 switch (subject to the dictionary file mechanism described below).
16863 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16864 had affected the
16865 casing for the defining occurrence of the name.
16866
16867 Some names may need to be spelled with casing conventions that are not
16868 covered by the upper-, lower-, and mixed-case transformations.
16869 You can arrange correct casing by placing such names in a
16870 @emph{dictionary file},
16871 and then supplying a @option{^-D^/DICTIONARY^} switch.
16872 The casing of names from dictionary files overrides
16873 any @option{^-n^/NAME_CASING^} switch.
16874
16875 To handle the casing of Ada predefined names and the names from GNAT libraries,
16876 @command{gnatpp} assumes a default dictionary file.
16877 The name of each predefined entity is spelled with the same casing as is used
16878 for the entity in the @cite{Ada Reference Manual}.
16879 The name of each entity in the GNAT libraries is spelled with the same casing
16880 as is used in the declaration of that entity.
16881
16882 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16883 default dictionary file.
16884 Instead, the casing for predefined and GNAT-defined names will be established
16885 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16886 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16887 will appear as just shown,
16888 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16889 To ensure that even such names are rendered in uppercase,
16890 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16891 (or else, less conveniently, place these names in upper case in a dictionary
16892 file).
16893
16894 A dictionary file is
16895 a plain text file; each line in this file can be either a blank line
16896 (containing only space characters and ASCII.HT characters), an Ada comment
16897 line, or the specification of exactly one @emph{casing schema}.
16898
16899 A casing schema is a string that has the following syntax:
16900
16901 @smallexample
16902 @cartouche
16903 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16904
16905 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16906 @end cartouche
16907 @end smallexample
16908
16909 @noindent
16910 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16911 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16912
16913 The casing schema string can be followed by white space and/or an Ada-style
16914 comment; any amount of white space is allowed before the string.
16915
16916 If a dictionary file is passed as
16917 @ifclear vms
16918 the value of a @option{-D@var{file}} switch
16919 @end ifclear
16920 @ifset vms
16921 an option to the @option{/DICTIONARY} qualifier
16922 @end ifset
16923 then for every
16924 simple name and every identifier, @command{gnatpp} checks if the dictionary
16925 defines the casing for the name or for some of its parts (the term ``subword''
16926 is used below to denote the part of a name which is delimited by ``_'' or by
16927 the beginning or end of the word and which does not contain any ``_'' inside):
16928
16929 @itemize @bullet
16930 @item
16931 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16932 the casing defined by the dictionary; no subwords are checked for this word
16933
16934 @item
16935 for every subword @command{gnatpp} checks if the dictionary contains the
16936 corresponding string of the form @code{*@var{simple_identifier}*},
16937 and if it does, the casing of this @var{simple_identifier} is used
16938 for this subword
16939
16940 @item
16941 if the whole name does not contain any ``_'' inside, and if for this name
16942 the dictionary contains two entries - one of the form @var{identifier},
16943 and another - of the form *@var{simple_identifier}*, then the first one
16944 is applied to define the casing of this name
16945
16946 @item
16947 if more than one dictionary file is passed as @command{gnatpp} switches, each
16948 dictionary adds new casing exceptions and overrides all the existing casing
16949 exceptions set by the previous dictionaries
16950
16951 @item
16952 when @command{gnatpp} checks if the word or subword is in the dictionary,
16953 this check is not case sensitive
16954 @end itemize
16955
16956 @noindent
16957 For example, suppose we have the following source to reformat:
16958
16959 @smallexample @c ada
16960 @cartouche
16961 procedure test is
16962 name1 : integer := 1;
16963 name4_name3_name2 : integer := 2;
16964 name2_name3_name4 : Boolean;
16965 name1_var : Float;
16966 begin
16967 name2_name3_name4 := name4_name3_name2 > name1;
16968 end;
16969 @end cartouche
16970 @end smallexample
16971
16972 @noindent
16973 And suppose we have two dictionaries:
16974
16975 @smallexample
16976 @cartouche
16977 @i{dict1:}
16978 NAME1
16979 *NaMe3*
16980 *Name1*
16981 @end cartouche
16982
16983 @cartouche
16984 @i{dict2:}
16985 *NAME3*
16986 @end cartouche
16987 @end smallexample
16988
16989 @noindent
16990 If @command{gnatpp} is called with the following switches:
16991
16992 @smallexample
16993 @ifclear vms
16994 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16995 @end ifclear
16996 @ifset vms
16997 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16998 @end ifset
16999 @end smallexample
17000
17001 @noindent
17002 then we will get the following name casing in the @command{gnatpp} output:
17003
17004 @smallexample @c ada
17005 @cartouche
17006 procedure Test is
17007 NAME1 : Integer := 1;
17008 Name4_NAME3_Name2 : Integer := 2;
17009 Name2_NAME3_Name4 : Boolean;
17010 Name1_Var : Float;
17011 begin
17012 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17013 end Test;
17014 @end cartouche
17015 @end smallexample
17016
17017 @c *********************************
17018 @node The GNAT Metric Tool gnatmetric
17019 @chapter The GNAT Metric Tool @command{gnatmetric}
17020 @findex gnatmetric
17021 @cindex Metric tool
17022
17023 @noindent
17024 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17025 for computing various program metrics.
17026 It takes an Ada source file as input and generates a file containing the
17027 metrics data as output. Various switches control which
17028 metrics are computed and output.
17029
17030 @command{gnatmetric} generates and uses the ASIS
17031 tree for the input source and thus requires the input to be syntactically and
17032 semantically legal.
17033 If this condition is not met, @command{gnatmetric} will generate
17034 an error message; no metric information for this file will be
17035 computed and reported.
17036
17037 If the compilation unit contained in the input source depends semantically
17038 upon units in files located outside the current directory, you have to provide
17039 the source search path when invoking @command{gnatmetric}.
17040 If it depends semantically upon units that are contained
17041 in files with names that do not follow the GNAT file naming rules, you have to
17042 provide the configuration file describing the corresponding naming scheme (see
17043 the description of the @command{gnatmetric} switches below.)
17044 Alternatively, you may use a project file and invoke @command{gnatmetric}
17045 through the @command{gnat} driver.
17046
17047 The @command{gnatmetric} command has the form
17048
17049 @smallexample
17050 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17051 @end smallexample
17052
17053 @noindent
17054 where
17055 @itemize @bullet
17056 @item
17057 @var{switches} specify the metrics to compute and define the destination for
17058 the output
17059
17060 @item
17061 Each @var{filename} is the name (including the extension) of a source
17062 file to process. ``Wildcards'' are allowed, and
17063 the file name may contain path information.
17064 If no @var{filename} is supplied, then the @var{switches} list must contain
17065 at least one
17066 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17067 Including both a @option{-files} switch and one or more
17068 @var{filename} arguments is permitted.
17069
17070 @item
17071 @samp{-cargs @var{gcc_switches}} is a list of switches for
17072 @command{gcc}. They will be passed on to all compiler invocations made by
17073 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17074 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17075 and use the @option{-gnatec} switch to set the configuration file.
17076 @end itemize
17077
17078 @menu
17079 * Switches for gnatmetric::
17080 @end menu
17081
17082 @node Switches for gnatmetric
17083 @section Switches for @command{gnatmetric}
17084
17085 @noindent
17086 The following subsections describe the various switches accepted by
17087 @command{gnatmetric}, organized by category.
17088
17089 @menu
17090 * Output Files Control::
17091 * Disable Metrics For Local Units::
17092 * Specifying a set of metrics to compute::
17093 * Other gnatmetric Switches::
17094 * Generate project-wide metrics::
17095 @end menu
17096
17097 @node Output Files Control
17098 @subsection Output File Control
17099 @cindex Output file control in @command{gnatmetric}
17100
17101 @noindent
17102 @command{gnatmetric} has two output formats. It can generate a
17103 textual (human-readable) form, and also XML. By default only textual
17104 output is generated.
17105
17106 When generating the output in textual form, @command{gnatmetric} creates
17107 for each Ada source file a corresponding text file
17108 containing the computed metrics, except for the case when the set of metrics
17109 specified by gnatmetric parameters consists only of metrics that are computed
17110 for the whole set of analyzed sources, but not for each Ada source.
17111 By default, this file is placed in the same directory as where the source
17112 file is located, and its name is obtained
17113 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17114 input file.
17115
17116 All the output information generated in XML format is placed in a single
17117 file. By default this file is placed in the current directory and has the
17118 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17119
17120 Some of the computed metrics are summed over the units passed to
17121 @command{gnatmetric}; for example, the total number of lines of code.
17122 By default this information is sent to @file{stdout}, but a file
17123 can be specified with the @option{-og} switch.
17124
17125 The following switches control the @command{gnatmetric} output:
17126
17127 @table @option
17128 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17129 @item ^-x^/XML^
17130 Generate the XML output
17131
17132 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17133 @item ^-nt^/NO_TEXT^
17134 Do not generate the output in text form (implies @option{^-x^/XML^})
17135
17136 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17137 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17138 Put textual files with detailed metrics into @var{output_dir}
17139
17140 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17141 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17142 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17143 in the name of the output file.
17144
17145 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17146 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17147 Put global metrics into @var{file_name}
17148
17149 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17150 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17151 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17152
17153 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17154 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17155 Use ``short'' source file names in the output. (The @command{gnatmetric}
17156 output includes the name(s) of the Ada source file(s) from which the metrics
17157 are computed. By default each name includes the absolute path. The
17158 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17159 to exclude all directory information from the file names that are output.)
17160
17161 @end table
17162
17163 @node Disable Metrics For Local Units
17164 @subsection Disable Metrics For Local Units
17165 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17166
17167 @noindent
17168 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17169 one compilation
17170 unit per one source file. It computes line metrics for the whole source
17171 file, and it also computes syntax
17172 and complexity metrics for the file's outermost unit.
17173
17174 By default, @command{gnatmetric} will also compute all metrics for certain
17175 kinds of locally declared program units:
17176
17177 @itemize @bullet
17178 @item
17179 subprogram (and generic subprogram) bodies;
17180
17181 @item
17182 package (and generic package) specs and bodies;
17183
17184 @item
17185 task object and type specifications and bodies;
17186
17187 @item
17188 protected object and type specifications and bodies.
17189 @end itemize
17190
17191 @noindent
17192 These kinds of entities will be referred to as
17193 @emph{eligible local program units}, or simply @emph{eligible local units},
17194 @cindex Eligible local unit (for @command{gnatmetric})
17195 in the discussion below.
17196
17197 Note that a subprogram declaration, generic instantiation,
17198 or renaming declaration only receives metrics
17199 computation when it appear as the outermost entity
17200 in a source file.
17201
17202 Suppression of metrics computation for eligible local units can be
17203 obtained via the following switch:
17204
17205 @table @option
17206 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17207 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17208 Do not compute detailed metrics for eligible local program units
17209
17210 @end table
17211
17212 @node Specifying a set of metrics to compute
17213 @subsection Specifying a set of metrics to compute
17214
17215 @noindent
17216 By default all the metrics are computed and reported. The switches
17217 described in this subsection allow you to control, on an individual
17218 basis, whether metrics are computed and
17219 reported. If at least one positive metric
17220 switch is specified (that is, a switch that defines that a given
17221 metric or set of metrics is to be computed), then only
17222 explicitly specified metrics are reported.
17223
17224 @menu
17225 * Line Metrics Control::
17226 * Syntax Metrics Control::
17227 * Complexity Metrics Control::
17228 * Object-Oriented Metrics Control::
17229 @end menu
17230
17231 @node Line Metrics Control
17232 @subsubsection Line Metrics Control
17233 @cindex Line metrics control in @command{gnatmetric}
17234
17235 @noindent
17236 For any (legal) source file, and for each of its
17237 eligible local program units, @command{gnatmetric} computes the following
17238 metrics:
17239
17240 @itemize @bullet
17241 @item
17242 the total number of lines;
17243
17244 @item
17245 the total number of code lines (i.e., non-blank lines that are not comments)
17246
17247 @item
17248 the number of comment lines
17249
17250 @item
17251 the number of code lines containing end-of-line comments;
17252
17253 @item
17254 the comment percentage: the ratio between the number of lines that contain
17255 comments and the number of all non-blank lines, expressed as a percentage;
17256
17257 @item
17258 the number of empty lines and lines containing only space characters and/or
17259 format effectors (blank lines)
17260
17261 @item
17262 the average number of code lines in subprogram bodies, task bodies, entry
17263 bodies and statement sequences in package bodies (this metric is only computed
17264 across the whole set of the analyzed units)
17265
17266 @end itemize
17267
17268 @noindent
17269 @command{gnatmetric} sums the values of the line metrics for all the
17270 files being processed and then generates the cumulative results. The tool
17271 also computes for all the files being processed the average number of code
17272 lines in bodies.
17273
17274 You can use the following switches to select the specific line metrics
17275 to be computed and reported.
17276
17277 @table @option
17278 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17279
17280 @ifclear vms
17281 @cindex @option{--no-lines@var{x}}
17282 @end ifclear
17283
17284 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17285 Report all the line metrics
17286
17287 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17288 Do not report any of line metrics
17289
17290 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17291 Report the number of all lines
17292
17293 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17294 Do not report the number of all lines
17295
17296 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17297 Report the number of code lines
17298
17299 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17300 Do not report the number of code lines
17301
17302 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17303 Report the number of comment lines
17304
17305 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17306 Do not report the number of comment lines
17307
17308 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17309 Report the number of code lines containing
17310 end-of-line comments
17311
17312 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17313 Do not report the number of code lines containing
17314 end-of-line comments
17315
17316 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17317 Report the comment percentage in the program text
17318
17319 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17320 Do not report the comment percentage in the program text
17321
17322 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17323 Report the number of blank lines
17324
17325 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17326 Do not report the number of blank lines
17327
17328 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17329 Report the average number of code lines in subprogram bodies, task bodies,
17330 entry bodies and statement sequences in package bodies. The metric is computed
17331 and reported for the whole set of processed Ada sources only.
17332
17333 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17334 Do not report the average number of code lines in subprogram bodies,
17335 task bodies, entry bodies and statement sequences in package bodies.
17336
17337 @end table
17338
17339 @node Syntax Metrics Control
17340 @subsubsection Syntax Metrics Control
17341 @cindex Syntax metrics control in @command{gnatmetric}
17342
17343 @noindent
17344 @command{gnatmetric} computes various syntactic metrics for the
17345 outermost unit and for each eligible local unit:
17346
17347 @table @emph
17348 @item LSLOC (``Logical Source Lines Of Code'')
17349 The total number of declarations and the total number of statements
17350
17351 @item Maximal static nesting level of inner program units
17352 According to
17353 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17354 package, a task unit, a protected unit, a
17355 protected entry, a generic unit, or an explicitly declared subprogram other
17356 than an enumeration literal.''
17357
17358 @item Maximal nesting level of composite syntactic constructs
17359 This corresponds to the notion of the
17360 maximum nesting level in the GNAT built-in style checks
17361 (@pxref{Style Checking})
17362 @end table
17363
17364 @noindent
17365 For the outermost unit in the file, @command{gnatmetric} additionally computes
17366 the following metrics:
17367
17368 @table @emph
17369 @item Public subprograms
17370 This metric is computed for package specs. It is the
17371 number of subprograms and generic subprograms declared in the visible
17372 part (including the visible part of nested packages, protected objects, and
17373 protected types).
17374
17375 @item All subprograms
17376 This metric is computed for bodies and subunits. The
17377 metric is equal to a total number of subprogram bodies in the compilation
17378 unit.
17379 Neither generic instantiations nor renamings-as-a-body nor body stubs
17380 are counted. Any subprogram body is counted, independently of its nesting
17381 level and enclosing constructs. Generic bodies and bodies of protected
17382 subprograms are counted in the same way as ``usual'' subprogram bodies.
17383
17384 @item Public types
17385 This metric is computed for package specs and
17386 generic package declarations. It is the total number of types
17387 that can be referenced from outside this compilation unit, plus the
17388 number of types from all the visible parts of all the visible generic
17389 packages. Generic formal types are not counted. Only types, not subtypes,
17390 are included.
17391
17392 @noindent
17393 Along with the total number of public types, the following
17394 types are counted and reported separately:
17395
17396 @itemize @bullet
17397 @item
17398 Abstract types
17399
17400 @item
17401 Root tagged types (abstract, non-abstract, private, non-private). Type
17402 extensions are @emph{not} counted
17403
17404 @item
17405 Private types (including private extensions)
17406
17407 @item
17408 Task types
17409
17410 @item
17411 Protected types
17412
17413 @end itemize
17414
17415 @item All types
17416 This metric is computed for any compilation unit. It is equal to the total
17417 number of the declarations of different types given in the compilation unit.
17418 The private and the corresponding full type declaration are counted as one
17419 type declaration. Incomplete type declarations and generic formal types
17420 are not counted.
17421 No distinction is made among different kinds of types (abstract,
17422 private etc.); the total number of types is computed and reported.
17423
17424 @end table
17425
17426 @noindent
17427 By default, all the syntax metrics are computed and reported. You can use the
17428 following switches to select specific syntax metrics.
17429
17430 @table @option
17431
17432 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17433
17434 @ifclear vms
17435 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17436 @end ifclear
17437
17438 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17439 Report all the syntax metrics
17440
17441 @item ^--no-syntax-all^/ALL_OFF^
17442 Do not report any of syntax metrics
17443
17444 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17445 Report the total number of declarations
17446
17447 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17448 Do not report the total number of declarations
17449
17450 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17451 Report the total number of statements
17452
17453 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17454 Do not report the total number of statements
17455
17456 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17457 Report the number of public subprograms in a compilation unit
17458
17459 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17460 Do not report the number of public subprograms in a compilation unit
17461
17462 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17463 Report the number of all the subprograms in a compilation unit
17464
17465 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17466 Do not report the number of all the subprograms in a compilation unit
17467
17468 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17469 Report the number of public types in a compilation unit
17470
17471 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17472 Do not report the number of public types in a compilation unit
17473
17474 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17475 Report the number of all the types in a compilation unit
17476
17477 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17478 Do not report the number of all the types in a compilation unit
17479
17480 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17481 Report the maximal program unit nesting level
17482
17483 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17484 Do not report the maximal program unit nesting level
17485
17486 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17487 Report the maximal construct nesting level
17488
17489 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17490 Do not report the maximal construct nesting level
17491
17492 @end table
17493
17494 @node Complexity Metrics Control
17495 @subsubsection Complexity Metrics Control
17496 @cindex Complexity metrics control in @command{gnatmetric}
17497
17498 @noindent
17499 For a program unit that is an executable body (a subprogram body (including
17500 generic bodies), task body, entry body or a package body containing
17501 its own statement sequence) @command{gnatmetric} computes the following
17502 complexity metrics:
17503
17504 @itemize @bullet
17505 @item
17506 McCabe cyclomatic complexity;
17507
17508 @item
17509 McCabe essential complexity;
17510
17511 @item
17512 maximal loop nesting level
17513
17514 @end itemize
17515
17516 @noindent
17517 The McCabe complexity metrics are defined
17518 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17519
17520 According to McCabe, both control statements and short-circuit control forms
17521 should be taken into account when computing cyclomatic complexity. For each
17522 body, we compute three metric values:
17523
17524 @itemize @bullet
17525 @item
17526 the complexity introduced by control
17527 statements only, without taking into account short-circuit forms,
17528
17529 @item
17530 the complexity introduced by short-circuit control forms only, and
17531
17532 @item
17533 the total
17534 cyclomatic complexity, which is the sum of these two values.
17535 @end itemize
17536
17537 @noindent
17538 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17539 the code in the exception handlers and in all the nested program units.
17540
17541 By default, all the complexity metrics are computed and reported.
17542 For more fine-grained control you can use
17543 the following switches:
17544
17545 @table @option
17546 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17547
17548 @ifclear vms
17549 @cindex @option{--no-complexity@var{x}}
17550 @end ifclear
17551
17552 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17553 Report all the complexity metrics
17554
17555 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17556 Do not report any of complexity metrics
17557
17558 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17559 Report the McCabe Cyclomatic Complexity
17560
17561 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17562 Do not report the McCabe Cyclomatic Complexity
17563
17564 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17565 Report the Essential Complexity
17566
17567 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17568 Do not report the Essential Complexity
17569
17570 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17571 Report maximal loop nesting level
17572
17573 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17574 Do not report maximal loop nesting level
17575
17576 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17577 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17578 task bodies, entry bodies and statement sequences in package bodies.
17579 The metric is computed and reported for whole set of processed Ada sources
17580 only.
17581
17582 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17583 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17584 bodies, task bodies, entry bodies and statement sequences in package bodies
17585
17586 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17587 @item ^-ne^/NO_EXITS_AS_GOTOS^
17588 Do not consider @code{exit} statements as @code{goto}s when
17589 computing Essential Complexity
17590
17591 @end table
17592
17593
17594 @node Object-Oriented Metrics Control
17595 @subsubsection Object-Oriented Metrics Control
17596 @cindex Object-Oriented metrics control in @command{gnatmetric}
17597
17598 @noindent
17599 @cindex Coupling metrics (in in @command{gnatmetric})
17600 Coupling metrics are object-oriented metrics that measure the
17601 dependencies between a given class (or a group of classes) and the
17602 ``external world'' (that is, the other classes in the program). In this
17603 subsection the term ``class'' is used in its
17604 traditional object-oriented programming sense
17605 (an instantiable module that contains data and/or method members).
17606 A @emph{category} (of classes)
17607 is a group of closely related classes that are reused and/or
17608 modified together.
17609
17610 A class @code{K}'s @emph{efferent coupling} is the number of classes
17611 that @code{K} depends upon.
17612 A category's efferent coupling is the number of classes outside the
17613 category that the classes inside the category depend upon.
17614
17615 A class @code{K}'s @emph{afferent coupling} is the number of classes
17616 that depend upon @code{K}.
17617 A category's afferent coupling is the number of classes outside the
17618 category that depend on classes belonging to the category.
17619
17620 Ada's implementation of the object-oriented paradigm does not use the
17621 traditional class notion, so the definition of the coupling
17622 metrics for Ada maps the class and class category notions
17623 onto Ada constructs.
17624
17625 For the coupling metrics, several kinds of modules -- a library package,
17626 a library generic package, and a library generic package instantiation --
17627 that define a tagged type or an interface type are
17628 considered to be a class. A category consists of a library package (or
17629 a library generic package) that defines a tagged or an interface type,
17630 together with all its descendant (generic) packages that define tagged
17631 or interface types. For any package counted as a class,
17632 its body (if any) is considered
17633 together with its spec when counting the dependencies. For dependencies
17634 between classes, the Ada semantic dependencies are considered.
17635 For coupling metrics, only dependencies on units that are considered as
17636 classes, are considered.
17637
17638 When computing coupling metrics, @command{gnatmetric} counts only
17639 dependencies between units that are arguments of the gnatmetric call.
17640 Coupling metrics are program-wide (or project-wide) metrics, so to
17641 get a valid result, you should call @command{gnatmetric} for
17642 the whole set of sources that make up your program. It can be done
17643 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17644 option (see See @ref{The GNAT Driver and Project Files} for details.
17645
17646 By default, all the coupling metrics are disabled. You can use the following
17647 switches to specify the coupling metrics to be computed and reported:
17648
17649 @table @option
17650
17651 @ifclear vms
17652 @cindex @option{--package@var{x}} (@command{gnatmetric})
17653 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17654 @cindex @option{--category@var{x}} (@command{gnatmetric})
17655 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17656 @end ifclear
17657
17658 @ifset vms
17659 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17660 @end ifset
17661
17662 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17663 Report all the coupling metrics
17664
17665 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17666 Do not report any of metrics
17667
17668 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17669 Report package efferent coupling
17670
17671 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17672 Do not report package efferent coupling
17673
17674 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17675 Report package afferent coupling
17676
17677 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17678 Do not report package afferent coupling
17679
17680 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17681 Report category efferent coupling
17682
17683 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17684 Do not report category efferent coupling
17685
17686 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17687 Report category afferent coupling
17688
17689 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17690 Do not report category afferent coupling
17691
17692 @end table
17693
17694 @node Other gnatmetric Switches
17695 @subsection Other @code{gnatmetric} Switches
17696
17697 @noindent
17698 Additional @command{gnatmetric} switches are as follows:
17699
17700 @table @option
17701 @item ^-files @var{filename}^/FILES=@var{filename}^
17702 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17703 Take the argument source files from the specified file. This file should be an
17704 ordinary text file containing file names separated by spaces or
17705 line breaks. You can use this switch more then once in the same call to
17706 @command{gnatmetric}. You also can combine this switch with
17707 an explicit list of files.
17708
17709 @item ^-v^/VERBOSE^
17710 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17711 Verbose mode;
17712 @command{gnatmetric} generates version information and then
17713 a trace of sources being processed.
17714
17715 @item ^-dv^/DEBUG_OUTPUT^
17716 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17717 Debug mode;
17718 @command{gnatmetric} generates various messages useful to understand what
17719 happens during the metrics computation
17720
17721 @item ^-q^/QUIET^
17722 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17723 Quiet mode.
17724 @end table
17725
17726 @node Generate project-wide metrics
17727 @subsection Generate project-wide metrics
17728
17729 In order to compute metrics on all units of a given project, you can use
17730 the @command{gnat} driver along with the @option{-P} option:
17731 @smallexample
17732 gnat metric -Pproj
17733 @end smallexample
17734
17735 @noindent
17736 If the project @code{proj} depends upon other projects, you can compute
17737 the metrics on the project closure using the @option{-U} option:
17738 @smallexample
17739 gnat metric -Pproj -U
17740 @end smallexample
17741
17742 @noindent
17743 Finally, if not all the units are relevant to a particular main
17744 program in the project closure, you can generate metrics for the set
17745 of units needed to create a given main program (unit closure) using
17746 the @option{-U} option followed by the name of the main unit:
17747 @smallexample
17748 gnat metric -Pproj -U main
17749 @end smallexample
17750
17751
17752 @c ***********************************
17753 @node File Name Krunching Using gnatkr
17754 @chapter File Name Krunching Using @code{gnatkr}
17755 @findex gnatkr
17756
17757 @noindent
17758 This chapter discusses the method used by the compiler to shorten
17759 the default file names chosen for Ada units so that they do not
17760 exceed the maximum length permitted. It also describes the
17761 @code{gnatkr} utility that can be used to determine the result of
17762 applying this shortening.
17763 @menu
17764 * About gnatkr::
17765 * Using gnatkr::
17766 * Krunching Method::
17767 * Examples of gnatkr Usage::
17768 @end menu
17769
17770 @node About gnatkr
17771 @section About @code{gnatkr}
17772
17773 @noindent
17774 The default file naming rule in GNAT
17775 is that the file name must be derived from
17776 the unit name. The exact default rule is as follows:
17777 @itemize @bullet
17778 @item
17779 Take the unit name and replace all dots by hyphens.
17780 @item
17781 If such a replacement occurs in the
17782 second character position of a name, and the first character is
17783 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17784 then replace the dot by the character
17785 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17786 instead of a minus.
17787 @end itemize
17788 The reason for this exception is to avoid clashes
17789 with the standard names for children of System, Ada, Interfaces,
17790 and GNAT, which use the prefixes
17791 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17792 respectively.
17793
17794 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17795 switch of the compiler activates a ``krunching''
17796 circuit that limits file names to nn characters (where nn is a decimal
17797 integer). For example, using OpenVMS,
17798 where the maximum file name length is
17799 39, the value of nn is usually set to 39, but if you want to generate
17800 a set of files that would be usable if ported to a system with some
17801 different maximum file length, then a different value can be specified.
17802 The default value of 39 for OpenVMS need not be specified.
17803
17804 The @code{gnatkr} utility can be used to determine the krunched name for
17805 a given file, when krunched to a specified maximum length.
17806
17807 @node Using gnatkr
17808 @section Using @code{gnatkr}
17809
17810 @noindent
17811 The @code{gnatkr} command has the form
17812
17813 @ifclear vms
17814 @smallexample
17815 $ gnatkr @var{name} @ovar{length}
17816 @end smallexample
17817 @end ifclear
17818
17819 @ifset vms
17820 @smallexample
17821 $ gnatkr @var{name} /COUNT=nn
17822 @end smallexample
17823 @end ifset
17824
17825 @noindent
17826 @var{name} is the uncrunched file name, derived from the name of the unit
17827 in the standard manner described in the previous section (i.e., in particular
17828 all dots are replaced by hyphens). The file name may or may not have an
17829 extension (defined as a suffix of the form period followed by arbitrary
17830 characters other than period). If an extension is present then it will
17831 be preserved in the output. For example, when krunching @file{hellofile.ads}
17832 to eight characters, the result will be hellofil.ads.
17833
17834 Note: for compatibility with previous versions of @code{gnatkr} dots may
17835 appear in the name instead of hyphens, but the last dot will always be
17836 taken as the start of an extension. So if @code{gnatkr} is given an argument
17837 such as @file{Hello.World.adb} it will be treated exactly as if the first
17838 period had been a hyphen, and for example krunching to eight characters
17839 gives the result @file{hellworl.adb}.
17840
17841 Note that the result is always all lower case (except on OpenVMS where it is
17842 all upper case). Characters of the other case are folded as required.
17843
17844 @var{length} represents the length of the krunched name. The default
17845 when no argument is given is ^8^39^ characters. A length of zero stands for
17846 unlimited, in other words do not chop except for system files where the
17847 implied crunching length is always eight characters.
17848
17849 @noindent
17850 The output is the krunched name. The output has an extension only if the
17851 original argument was a file name with an extension.
17852
17853 @node Krunching Method
17854 @section Krunching Method
17855
17856 @noindent
17857 The initial file name is determined by the name of the unit that the file
17858 contains. The name is formed by taking the full expanded name of the
17859 unit and replacing the separating dots with hyphens and
17860 using ^lowercase^uppercase^
17861 for all letters, except that a hyphen in the second character position is
17862 replaced by a ^tilde^dollar sign^ if the first character is
17863 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17864 The extension is @code{.ads} for a
17865 spec and @code{.adb} for a body.
17866 Krunching does not affect the extension, but the file name is shortened to
17867 the specified length by following these rules:
17868
17869 @itemize @bullet
17870 @item
17871 The name is divided into segments separated by hyphens, tildes or
17872 underscores and all hyphens, tildes, and underscores are
17873 eliminated. If this leaves the name short enough, we are done.
17874
17875 @item
17876 If the name is too long, the longest segment is located (left-most
17877 if there are two of equal length), and shortened by dropping
17878 its last character. This is repeated until the name is short enough.
17879
17880 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17881 to fit the name into 8 characters as required by some operating systems.
17882
17883 @smallexample
17884 our-strings-wide_fixed 22
17885 our strings wide fixed 19
17886 our string wide fixed 18
17887 our strin wide fixed 17
17888 our stri wide fixed 16
17889 our stri wide fixe 15
17890 our str wide fixe 14
17891 our str wid fixe 13
17892 our str wid fix 12
17893 ou str wid fix 11
17894 ou st wid fix 10
17895 ou st wi fix 9
17896 ou st wi fi 8
17897 Final file name: oustwifi.adb
17898 @end smallexample
17899
17900 @item
17901 The file names for all predefined units are always krunched to eight
17902 characters. The krunching of these predefined units uses the following
17903 special prefix replacements:
17904
17905 @table @file
17906 @item ada-
17907 replaced by @file{^a^A^-}
17908
17909 @item gnat-
17910 replaced by @file{^g^G^-}
17911
17912 @item interfaces-
17913 replaced by @file{^i^I^-}
17914
17915 @item system-
17916 replaced by @file{^s^S^-}
17917 @end table
17918
17919 These system files have a hyphen in the second character position. That
17920 is why normal user files replace such a character with a
17921 ^tilde^dollar sign^, to
17922 avoid confusion with system file names.
17923
17924 As an example of this special rule, consider
17925 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17926
17927 @smallexample
17928 ada-strings-wide_fixed 22
17929 a- strings wide fixed 18
17930 a- string wide fixed 17
17931 a- strin wide fixed 16
17932 a- stri wide fixed 15
17933 a- stri wide fixe 14
17934 a- str wide fixe 13
17935 a- str wid fixe 12
17936 a- str wid fix 11
17937 a- st wid fix 10
17938 a- st wi fix 9
17939 a- st wi fi 8
17940 Final file name: a-stwifi.adb
17941 @end smallexample
17942 @end itemize
17943
17944 Of course no file shortening algorithm can guarantee uniqueness over all
17945 possible unit names, and if file name krunching is used then it is your
17946 responsibility to ensure that no name clashes occur. The utility
17947 program @code{gnatkr} is supplied for conveniently determining the
17948 krunched name of a file.
17949
17950 @node Examples of gnatkr Usage
17951 @section Examples of @code{gnatkr} Usage
17952
17953 @smallexample
17954 @iftex
17955 @leftskip=0cm
17956 @end iftex
17957 @ifclear vms
17958 $ gnatkr very_long_unit_name.ads --> velounna.ads
17959 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17960 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17961 $ gnatkr grandparent-parent-child --> grparchi
17962 @end ifclear
17963 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17964 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17965 @end smallexample
17966
17967 @node Preprocessing Using gnatprep
17968 @chapter Preprocessing Using @code{gnatprep}
17969 @findex gnatprep
17970
17971 @noindent
17972 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17973 preprocessing.
17974 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17975 special GNAT features.
17976 For further discussion of conditional compilation in general, see
17977 @ref{Conditional Compilation}.
17978
17979 @menu
17980 * Preprocessing Symbols::
17981 * Using gnatprep::
17982 * Switches for gnatprep::
17983 * Form of Definitions File::
17984 * Form of Input Text for gnatprep::
17985 @end menu
17986
17987 @node Preprocessing Symbols
17988 @section Preprocessing Symbols
17989
17990 @noindent
17991 Preprocessing symbols are defined in definition files and referred to in
17992 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17993 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17994 all characters need to be in the ASCII set (no accented letters).
17995
17996 @node Using gnatprep
17997 @section Using @code{gnatprep}
17998
17999 @noindent
18000 To call @code{gnatprep} use
18001
18002 @smallexample
18003 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18004 @end smallexample
18005
18006 @noindent
18007 where
18008 @table @var
18009 @item switches
18010 is an optional sequence of switches as described in the next section.
18011
18012 @item infile
18013 is the full name of the input file, which is an Ada source
18014 file containing preprocessor directives.
18015
18016 @item outfile
18017 is the full name of the output file, which is an Ada source
18018 in standard Ada form. When used with GNAT, this file name will
18019 normally have an ads or adb suffix.
18020
18021 @item deffile
18022 is the full name of a text file containing definitions of
18023 preprocessing symbols to be referenced by the preprocessor. This argument is
18024 optional, and can be replaced by the use of the @option{-D} switch.
18025
18026 @end table
18027
18028 @node Switches for gnatprep
18029 @section Switches for @code{gnatprep}
18030
18031 @table @option
18032 @c !sort!
18033
18034 @item ^-b^/BLANK_LINES^
18035 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18036 Causes both preprocessor lines and the lines deleted by
18037 preprocessing to be replaced by blank lines in the output source file,
18038 preserving line numbers in the output file.
18039
18040 @item ^-c^/COMMENTS^
18041 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18042 Causes both preprocessor lines and the lines deleted
18043 by preprocessing to be retained in the output source as comments marked
18044 with the special string @code{"--! "}. This option will result in line numbers
18045 being preserved in the output file.
18046
18047 @item ^-C^/REPLACE_IN_COMMENTS^
18048 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18049 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18050 If this option is specified, then comments are scanned and any $symbol
18051 substitutions performed as in program text. This is particularly useful
18052 when structured comments are used (e.g., when writing programs in the
18053 SPARK dialect of Ada). Note that this switch is not available when
18054 doing integrated preprocessing (it would be useless in this context
18055 since comments are ignored by the compiler in any case).
18056
18057 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18058 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18059 Defines a new preprocessing symbol, associated with value. If no value is given
18060 on the command line, then symbol is considered to be @code{True}. This switch
18061 can be used in place of a definition file.
18062
18063 @ifset vms
18064 @item /REMOVE
18065 @cindex @option{/REMOVE} (@command{gnatprep})
18066 This is the default setting which causes lines deleted by preprocessing
18067 to be entirely removed from the output file.
18068 @end ifset
18069
18070 @item ^-r^/REFERENCE^
18071 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18072 Causes a @code{Source_Reference} pragma to be generated that
18073 references the original input file, so that error messages will use
18074 the file name of this original file. The use of this switch implies
18075 that preprocessor lines are not to be removed from the file, so its
18076 use will force @option{^-b^/BLANK_LINES^} mode if
18077 @option{^-c^/COMMENTS^}
18078 has not been specified explicitly.
18079
18080 Note that if the file to be preprocessed contains multiple units, then
18081 it will be necessary to @code{gnatchop} the output file from
18082 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18083 in the preprocessed file, it will be respected by
18084 @code{gnatchop ^-r^/REFERENCE^}
18085 so that the final chopped files will correctly refer to the original
18086 input source file for @code{gnatprep}.
18087
18088 @item ^-s^/SYMBOLS^
18089 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18090 Causes a sorted list of symbol names and values to be
18091 listed on the standard output file.
18092
18093 @item ^-u^/UNDEFINED^
18094 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18095 Causes undefined symbols to be treated as having the value FALSE in the context
18096 of a preprocessor test. In the absence of this option, an undefined symbol in
18097 a @code{#if} or @code{#elsif} test will be treated as an error.
18098
18099 @end table
18100
18101 @ifclear vms
18102 @noindent
18103 Note: if neither @option{-b} nor @option{-c} is present,
18104 then preprocessor lines and
18105 deleted lines are completely removed from the output, unless -r is
18106 specified, in which case -b is assumed.
18107 @end ifclear
18108
18109 @node Form of Definitions File
18110 @section Form of Definitions File
18111
18112 @noindent
18113 The definitions file contains lines of the form
18114
18115 @smallexample
18116 symbol := value
18117 @end smallexample
18118
18119 @noindent
18120 where symbol is a preprocessing symbol, and value is one of the following:
18121
18122 @itemize @bullet
18123 @item
18124 Empty, corresponding to a null substitution
18125 @item
18126 A string literal using normal Ada syntax
18127 @item
18128 Any sequence of characters from the set
18129 (letters, digits, period, underline).
18130 @end itemize
18131
18132 @noindent
18133 Comment lines may also appear in the definitions file, starting with
18134 the usual @code{--},
18135 and comments may be added to the definitions lines.
18136
18137 @node Form of Input Text for gnatprep
18138 @section Form of Input Text for @code{gnatprep}
18139
18140 @noindent
18141 The input text may contain preprocessor conditional inclusion lines,
18142 as well as general symbol substitution sequences.
18143
18144 The preprocessor conditional inclusion commands have the form
18145
18146 @smallexample
18147 @group
18148 @cartouche
18149 #if @i{expression} @r{[}then@r{]}
18150 lines
18151 #elsif @i{expression} @r{[}then@r{]}
18152 lines
18153 #elsif @i{expression} @r{[}then@r{]}
18154 lines
18155 @dots{}
18156 #else
18157 lines
18158 #end if;
18159 @end cartouche
18160 @end group
18161 @end smallexample
18162
18163 @noindent
18164 In this example, @i{expression} is defined by the following grammar:
18165 @smallexample
18166 @i{expression} ::= <symbol>
18167 @i{expression} ::= <symbol> = "<value>"
18168 @i{expression} ::= <symbol> = <symbol>
18169 @i{expression} ::= <symbol> 'Defined
18170 @i{expression} ::= not @i{expression}
18171 @i{expression} ::= @i{expression} and @i{expression}
18172 @i{expression} ::= @i{expression} or @i{expression}
18173 @i{expression} ::= @i{expression} and then @i{expression}
18174 @i{expression} ::= @i{expression} or else @i{expression}
18175 @i{expression} ::= ( @i{expression} )
18176 @end smallexample
18177
18178 The following restriction exists: it is not allowed to have "and" or "or"
18179 following "not" in the same expression without parentheses. For example, this
18180 is not allowed:
18181
18182 @smallexample
18183 not X or Y
18184 @end smallexample
18185
18186 This should be one of the following:
18187
18188 @smallexample
18189 (not X) or Y
18190 not (X or Y)
18191 @end smallexample
18192
18193 @noindent
18194 For the first test (@i{expression} ::= <symbol>) the symbol must have
18195 either the value true or false, that is to say the right-hand of the
18196 symbol definition must be one of the (case-insensitive) literals
18197 @code{True} or @code{False}. If the value is true, then the
18198 corresponding lines are included, and if the value is false, they are
18199 excluded.
18200
18201 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18202 the symbol has been defined in the definition file or by a @option{-D}
18203 switch on the command line. Otherwise, the test is false.
18204
18205 The equality tests are case insensitive, as are all the preprocessor lines.
18206
18207 If the symbol referenced is not defined in the symbol definitions file,
18208 then the effect depends on whether or not switch @option{-u}
18209 is specified. If so, then the symbol is treated as if it had the value
18210 false and the test fails. If this switch is not specified, then
18211 it is an error to reference an undefined symbol. It is also an error to
18212 reference a symbol that is defined with a value other than @code{True}
18213 or @code{False}.
18214
18215 The use of the @code{not} operator inverts the sense of this logical test.
18216 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18217 operators, without parentheses. For example, "if not X or Y then" is not
18218 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18219
18220 The @code{then} keyword is optional as shown
18221
18222 The @code{#} must be the first non-blank character on a line, but
18223 otherwise the format is free form. Spaces or tabs may appear between
18224 the @code{#} and the keyword. The keywords and the symbols are case
18225 insensitive as in normal Ada code. Comments may be used on a
18226 preprocessor line, but other than that, no other tokens may appear on a
18227 preprocessor line. Any number of @code{elsif} clauses can be present,
18228 including none at all. The @code{else} is optional, as in Ada.
18229
18230 The @code{#} marking the start of a preprocessor line must be the first
18231 non-blank character on the line, i.e., it must be preceded only by
18232 spaces or horizontal tabs.
18233
18234 Symbol substitution outside of preprocessor lines is obtained by using
18235 the sequence
18236
18237 @smallexample
18238 $symbol
18239 @end smallexample
18240
18241 @noindent
18242 anywhere within a source line, except in a comment or within a
18243 string literal. The identifier
18244 following the @code{$} must match one of the symbols defined in the symbol
18245 definition file, and the result is to substitute the value of the
18246 symbol in place of @code{$symbol} in the output file.
18247
18248 Note that although the substitution of strings within a string literal
18249 is not possible, it is possible to have a symbol whose defined value is
18250 a string literal. So instead of setting XYZ to @code{hello} and writing:
18251
18252 @smallexample
18253 Header : String := "$XYZ";
18254 @end smallexample
18255
18256 @noindent
18257 you should set XYZ to @code{"hello"} and write:
18258
18259 @smallexample
18260 Header : String := $XYZ;
18261 @end smallexample
18262
18263 @noindent
18264 and then the substitution will occur as desired.
18265
18266 @ifset vms
18267 @node The GNAT Run-Time Library Builder gnatlbr
18268 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18269 @findex gnatlbr
18270 @cindex Library builder
18271
18272 @noindent
18273 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18274 supplied configuration pragmas.
18275
18276 @menu
18277 * Running gnatlbr::
18278 * Switches for gnatlbr::
18279 * Examples of gnatlbr Usage::
18280 @end menu
18281
18282 @node Running gnatlbr
18283 @section Running @code{gnatlbr}
18284
18285 @noindent
18286 The @code{gnatlbr} command has the form
18287
18288 @smallexample
18289 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18290 @end smallexample
18291
18292 @node Switches for gnatlbr
18293 @section Switches for @code{gnatlbr}
18294
18295 @noindent
18296 @code{gnatlbr} recognizes the following switches:
18297
18298 @table @option
18299 @c !sort!
18300 @item /CREATE=directory
18301 @cindex @code{/CREATE} (@code{gnatlbr})
18302 Create the new run-time library in the specified directory.
18303
18304 @item /SET=directory
18305 @cindex @code{/SET} (@code{gnatlbr})
18306 Make the library in the specified directory the current run-time library.
18307
18308 @item /DELETE=directory
18309 @cindex @code{/DELETE} (@code{gnatlbr})
18310 Delete the run-time library in the specified directory.
18311
18312 @item /CONFIG=file
18313 @cindex @code{/CONFIG} (@code{gnatlbr})
18314 With /CREATE: Use the configuration pragmas in the specified file when
18315 building the library.
18316
18317 With /SET: Use the configuration pragmas in the specified file when
18318 compiling.
18319
18320 @end table
18321
18322 @node Examples of gnatlbr Usage
18323 @section Example of @code{gnatlbr} Usage
18324
18325 @smallexample
18326 Contents of VAXFLOAT.ADC:
18327 pragma Float_Representation (VAX_Float);
18328
18329 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18330
18331 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18332
18333 @end smallexample
18334 @end ifset
18335
18336 @node The GNAT Library Browser gnatls
18337 @chapter The GNAT Library Browser @code{gnatls}
18338 @findex gnatls
18339 @cindex Library browser
18340
18341 @noindent
18342 @code{gnatls} is a tool that outputs information about compiled
18343 units. It gives the relationship between objects, unit names and source
18344 files. It can also be used to check the source dependencies of a unit
18345 as well as various characteristics.
18346
18347 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18348 driver (see @ref{The GNAT Driver and Project Files}).
18349
18350 @menu
18351 * Running gnatls::
18352 * Switches for gnatls::
18353 * Examples of gnatls Usage::
18354 @end menu
18355
18356 @node Running gnatls
18357 @section Running @code{gnatls}
18358
18359 @noindent
18360 The @code{gnatls} command has the form
18361
18362 @smallexample
18363 $ gnatls switches @var{object_or_ali_file}
18364 @end smallexample
18365
18366 @noindent
18367 The main argument is the list of object or @file{ali} files
18368 (@pxref{The Ada Library Information Files})
18369 for which information is requested.
18370
18371 In normal mode, without additional option, @code{gnatls} produces a
18372 four-column listing. Each line represents information for a specific
18373 object. The first column gives the full path of the object, the second
18374 column gives the name of the principal unit in this object, the third
18375 column gives the status of the source and the fourth column gives the
18376 full path of the source representing this unit.
18377 Here is a simple example of use:
18378
18379 @smallexample
18380 $ gnatls *.o
18381 ^./^[]^demo1.o demo1 DIF demo1.adb
18382 ^./^[]^demo2.o demo2 OK demo2.adb
18383 ^./^[]^hello.o h1 OK hello.adb
18384 ^./^[]^instr-child.o instr.child MOK instr-child.adb
18385 ^./^[]^instr.o instr OK instr.adb
18386 ^./^[]^tef.o tef DIF tef.adb
18387 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
18388 ^./^[]^tgef.o tgef DIF tgef.adb
18389 @end smallexample
18390
18391 @noindent
18392 The first line can be interpreted as follows: the main unit which is
18393 contained in
18394 object file @file{demo1.o} is demo1, whose main source is in
18395 @file{demo1.adb}. Furthermore, the version of the source used for the
18396 compilation of demo1 has been modified (DIF). Each source file has a status
18397 qualifier which can be:
18398
18399 @table @code
18400 @item OK (unchanged)
18401 The version of the source file used for the compilation of the
18402 specified unit corresponds exactly to the actual source file.
18403
18404 @item MOK (slightly modified)
18405 The version of the source file used for the compilation of the
18406 specified unit differs from the actual source file but not enough to
18407 require recompilation. If you use gnatmake with the qualifier
18408 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18409 MOK will not be recompiled.
18410
18411 @item DIF (modified)
18412 No version of the source found on the path corresponds to the source
18413 used to build this object.
18414
18415 @item ??? (file not found)
18416 No source file was found for this unit.
18417
18418 @item HID (hidden, unchanged version not first on PATH)
18419 The version of the source that corresponds exactly to the source used
18420 for compilation has been found on the path but it is hidden by another
18421 version of the same source that has been modified.
18422
18423 @end table
18424
18425 @node Switches for gnatls
18426 @section Switches for @code{gnatls}
18427
18428 @noindent
18429 @code{gnatls} recognizes the following switches:
18430
18431 @table @option
18432 @c !sort!
18433 @cindex @option{--version} @command{gnatls}
18434 Display Copyright and version, then exit disregarding all other options.
18435
18436 @item --help
18437 @cindex @option{--help} @command{gnatls}
18438 If @option{--version} was not used, display usage, then exit disregarding
18439 all other options.
18440
18441 @item ^-a^/ALL_UNITS^
18442 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18443 Consider all units, including those of the predefined Ada library.
18444 Especially useful with @option{^-d^/DEPENDENCIES^}.
18445
18446 @item ^-d^/DEPENDENCIES^
18447 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18448 List sources from which specified units depend on.
18449
18450 @item ^-h^/OUTPUT=OPTIONS^
18451 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18452 Output the list of options.
18453
18454 @item ^-o^/OUTPUT=OBJECTS^
18455 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18456 Only output information about object files.
18457
18458 @item ^-s^/OUTPUT=SOURCES^
18459 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18460 Only output information about source files.
18461
18462 @item ^-u^/OUTPUT=UNITS^
18463 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18464 Only output information about compilation units.
18465
18466 @item ^-files^/FILES^=@var{file}
18467 @cindex @option{^-files^/FILES^} (@code{gnatls})
18468 Take as arguments the files listed in text file @var{file}.
18469 Text file @var{file} may contain empty lines that are ignored.
18470 Each nonempty line should contain the name of an existing file.
18471 Several such switches may be specified simultaneously.
18472
18473 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18474 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18475 @itemx ^-I^/SEARCH=^@var{dir}
18476 @itemx ^-I-^/NOCURRENT_DIRECTORY^
18477 @itemx -nostdinc
18478 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18479 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18480 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18481 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18482 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18483 flags (@pxref{Switches for gnatmake}).
18484
18485 @item --RTS=@var{rts-path}
18486 @cindex @option{--RTS} (@code{gnatls})
18487 Specifies the default location of the runtime library. Same meaning as the
18488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18489
18490 @item ^-v^/OUTPUT=VERBOSE^
18491 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18492 Verbose mode. Output the complete source, object and project paths. Do not use
18493 the default column layout but instead use long format giving as much as
18494 information possible on each requested units, including special
18495 characteristics such as:
18496
18497 @table @code
18498 @item Preelaborable
18499 The unit is preelaborable in the Ada sense.
18500
18501 @item No_Elab_Code
18502 No elaboration code has been produced by the compiler for this unit.
18503
18504 @item Pure
18505 The unit is pure in the Ada sense.
18506
18507 @item Elaborate_Body
18508 The unit contains a pragma Elaborate_Body.
18509
18510 @item Remote_Types
18511 The unit contains a pragma Remote_Types.
18512
18513 @item Shared_Passive
18514 The unit contains a pragma Shared_Passive.
18515
18516 @item Predefined
18517 This unit is part of the predefined environment and cannot be modified
18518 by the user.
18519
18520 @item Remote_Call_Interface
18521 The unit contains a pragma Remote_Call_Interface.
18522
18523 @end table
18524
18525 @end table
18526
18527 @node Examples of gnatls Usage
18528 @section Example of @code{gnatls} Usage
18529 @ifclear vms
18530
18531 @noindent
18532 Example of using the verbose switch. Note how the source and
18533 object paths are affected by the -I switch.
18534
18535 @smallexample
18536 $ gnatls -v -I.. demo1.o
18537
18538 GNATLS 5.03w (20041123-34)
18539 Copyright 1997-2004 Free Software Foundation, Inc.
18540
18541 Source Search Path:
18542 <Current_Directory>
18543 ../
18544 /home/comar/local/adainclude/
18545
18546 Object Search Path:
18547 <Current_Directory>
18548 ../
18549 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18550
18551 Project Search Path:
18552 <Current_Directory>
18553 /home/comar/local/lib/gnat/
18554
18555 ./demo1.o
18556 Unit =>
18557 Name => demo1
18558 Kind => subprogram body
18559 Flags => No_Elab_Code
18560 Source => demo1.adb modified
18561 @end smallexample
18562
18563 @noindent
18564 The following is an example of use of the dependency list.
18565 Note the use of the -s switch
18566 which gives a straight list of source files. This can be useful for
18567 building specialized scripts.
18568
18569 @smallexample
18570 $ gnatls -d demo2.o
18571 ./demo2.o demo2 OK demo2.adb
18572 OK gen_list.ads
18573 OK gen_list.adb
18574 OK instr.ads
18575 OK instr-child.ads
18576
18577 $ gnatls -d -s -a demo1.o
18578 demo1.adb
18579 /home/comar/local/adainclude/ada.ads
18580 /home/comar/local/adainclude/a-finali.ads
18581 /home/comar/local/adainclude/a-filico.ads
18582 /home/comar/local/adainclude/a-stream.ads
18583 /home/comar/local/adainclude/a-tags.ads
18584 gen_list.ads
18585 gen_list.adb
18586 /home/comar/local/adainclude/gnat.ads
18587 /home/comar/local/adainclude/g-io.ads
18588 instr.ads
18589 /home/comar/local/adainclude/system.ads
18590 /home/comar/local/adainclude/s-exctab.ads
18591 /home/comar/local/adainclude/s-finimp.ads
18592 /home/comar/local/adainclude/s-finroo.ads
18593 /home/comar/local/adainclude/s-secsta.ads
18594 /home/comar/local/adainclude/s-stalib.ads
18595 /home/comar/local/adainclude/s-stoele.ads
18596 /home/comar/local/adainclude/s-stratt.ads
18597 /home/comar/local/adainclude/s-tasoli.ads
18598 /home/comar/local/adainclude/s-unstyp.ads
18599 /home/comar/local/adainclude/unchconv.ads
18600 @end smallexample
18601 @end ifclear
18602
18603 @ifset vms
18604 @smallexample
18605 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18606
18607 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18608 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18609 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18610 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18611 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18612 demo1.adb
18613 gen_list.ads
18614 gen_list.adb
18615 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18616 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18617 instr.ads
18618 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18619 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18620 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18621 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18622 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18623 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18624 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18625 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18626 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18627 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18628 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18629 @end smallexample
18630 @end ifset
18631
18632 @node Cleaning Up Using gnatclean
18633 @chapter Cleaning Up Using @code{gnatclean}
18634 @findex gnatclean
18635 @cindex Cleaning tool
18636
18637 @noindent
18638 @code{gnatclean} is a tool that allows the deletion of files produced by the
18639 compiler, binder and linker, including ALI files, object files, tree files,
18640 expanded source files, library files, interface copy source files, binder
18641 generated files and executable files.
18642
18643 @menu
18644 * Running gnatclean::
18645 * Switches for gnatclean::
18646 @c * Examples of gnatclean Usage::
18647 @end menu
18648
18649 @node Running gnatclean
18650 @section Running @code{gnatclean}
18651
18652 @noindent
18653 The @code{gnatclean} command has the form:
18654
18655 @smallexample
18656 $ gnatclean switches @var{names}
18657 @end smallexample
18658
18659 @noindent
18660 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18661 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18662 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18663
18664 @noindent
18665 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18666 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18667 the linker. In informative-only mode, specified by switch
18668 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18669 normal mode is listed, but no file is actually deleted.
18670
18671 @node Switches for gnatclean
18672 @section Switches for @code{gnatclean}
18673
18674 @noindent
18675 @code{gnatclean} recognizes the following switches:
18676
18677 @table @option
18678 @c !sort!
18679 @cindex @option{--version} @command{gnatclean}
18680 Display Copyright and version, then exit disregarding all other options.
18681
18682 @item --help
18683 @cindex @option{--help} @command{gnatclean}
18684 If @option{--version} was not used, display usage, then exit disregarding
18685 all other options.
18686
18687 @item ^-c^/COMPILER_FILES_ONLY^
18688 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18689 Only attempt to delete the files produced by the compiler, not those produced
18690 by the binder or the linker. The files that are not to be deleted are library
18691 files, interface copy files, binder generated files and executable files.
18692
18693 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18694 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18695 Indicate that ALI and object files should normally be found in directory
18696 @var{dir}.
18697
18698 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18699 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18700 When using project files, if some errors or warnings are detected during
18701 parsing and verbose mode is not in effect (no use of switch
18702 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18703 file, rather than its simple file name.
18704
18705 @item ^-h^/HELP^
18706 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18707 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18708
18709 @item ^-n^/NODELETE^
18710 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18711 Informative-only mode. Do not delete any files. Output the list of the files
18712 that would have been deleted if this switch was not specified.
18713
18714 @item ^-P^/PROJECT_FILE=^@var{project}
18715 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18716 Use project file @var{project}. Only one such switch can be used.
18717 When cleaning a project file, the files produced by the compilation of the
18718 immediate sources or inherited sources of the project files are to be
18719 deleted. This is not depending on the presence or not of executable names
18720 on the command line.
18721
18722 @item ^-q^/QUIET^
18723 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18724 Quiet output. If there are no errors, do not output anything, except in
18725 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18726 (switch ^-n^/NODELETE^).
18727
18728 @item ^-r^/RECURSIVE^
18729 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18730 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18731 clean all imported and extended project files, recursively. If this switch
18732 is not specified, only the files related to the main project file are to be
18733 deleted. This switch has no effect if no project file is specified.
18734
18735 @item ^-v^/VERBOSE^
18736 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18737 Verbose mode.
18738
18739 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18740 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18741 Indicates the verbosity of the parsing of GNAT project files.
18742 @xref{Switches Related to Project Files}.
18743
18744 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18745 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18746 Indicates that external variable @var{name} has the value @var{value}.
18747 The Project Manager will use this value for occurrences of
18748 @code{external(name)} when parsing the project file.
18749 @xref{Switches Related to Project Files}.
18750
18751 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18752 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18753 When searching for ALI and object files, look in directory
18754 @var{dir}.
18755
18756 @item ^-I^/SEARCH=^@var{dir}
18757 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18758 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18759
18760 @item ^-I-^/NOCURRENT_DIRECTORY^
18761 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18762 @cindex Source files, suppressing search
18763 Do not look for ALI or object files in the directory
18764 where @code{gnatclean} was invoked.
18765
18766 @end table
18767
18768 @c @node Examples of gnatclean Usage
18769 @c @section Examples of @code{gnatclean} Usage
18770
18771 @ifclear vms
18772 @node GNAT and Libraries
18773 @chapter GNAT and Libraries
18774 @cindex Library, building, installing, using
18775
18776 @noindent
18777 This chapter describes how to build and use libraries with GNAT, and also shows
18778 how to recompile the GNAT run-time library. You should be familiar with the
18779 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18780 chapter.
18781
18782 @menu
18783 * Introduction to Libraries in GNAT::
18784 * General Ada Libraries::
18785 * Stand-alone Ada Libraries::
18786 * Rebuilding the GNAT Run-Time Library::
18787 @end menu
18788
18789 @node Introduction to Libraries in GNAT
18790 @section Introduction to Libraries in GNAT
18791
18792 @noindent
18793 A library is, conceptually, a collection of objects which does not have its
18794 own main thread of execution, but rather provides certain services to the
18795 applications that use it. A library can be either statically linked with the
18796 application, in which case its code is directly included in the application,
18797 or, on platforms that support it, be dynamically linked, in which case
18798 its code is shared by all applications making use of this library.
18799
18800 GNAT supports both types of libraries.
18801 In the static case, the compiled code can be provided in different ways. The
18802 simplest approach is to provide directly the set of objects resulting from
18803 compilation of the library source files. Alternatively, you can group the
18804 objects into an archive using whatever commands are provided by the operating
18805 system. For the latter case, the objects are grouped into a shared library.
18806
18807 In the GNAT environment, a library has three types of components:
18808 @itemize @bullet
18809 @item
18810 Source files.
18811 @item
18812 @file{ALI} files.
18813 @xref{The Ada Library Information Files}.
18814 @item
18815 Object files, an archive or a shared library.
18816 @end itemize
18817
18818 @noindent
18819 A GNAT library may expose all its source files, which is useful for
18820 documentation purposes. Alternatively, it may expose only the units needed by
18821 an external user to make use of the library. That is to say, the specs
18822 reflecting the library services along with all the units needed to compile
18823 those specs, which can include generic bodies or any body implementing an
18824 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18825 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18826
18827 All compilation units comprising an application, including those in a library,
18828 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18829 computes the elaboration order from the @file{ALI} files and this is why they
18830 constitute a mandatory part of GNAT libraries. Except in the case of
18831 @emph{stand-alone libraries}, where a specific library elaboration routine is
18832 produced independently of the application(s) using the library.
18833
18834 @node General Ada Libraries
18835 @section General Ada Libraries
18836
18837 @menu
18838 * Building a library::
18839 * Installing a library::
18840 * Using a library::
18841 @end menu
18842
18843 @node Building a library
18844 @subsection Building a library
18845
18846 @noindent
18847 The easiest way to build a library is to use the Project Manager,
18848 which supports a special type of project called a @emph{Library Project}
18849 (@pxref{Library Projects}).
18850
18851 A project is considered a library project, when two project-level attributes
18852 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18853 control different aspects of library configuration, additional optional
18854 project-level attributes can be specified:
18855 @table @code
18856 @item Library_Kind
18857 This attribute controls whether the library is to be static or dynamic
18858
18859 @item Library_Version
18860 This attribute specifies the library version; this value is used
18861 during dynamic linking of shared libraries to determine if the currently
18862 installed versions of the binaries are compatible.
18863
18864 @item Library_Options
18865 @item Library_GCC
18866 These attributes specify additional low-level options to be used during
18867 library generation, and redefine the actual application used to generate
18868 library.
18869 @end table
18870
18871 @noindent
18872 The GNAT Project Manager takes full care of the library maintenance task,
18873 including recompilation of the source files for which objects do not exist
18874 or are not up to date, assembly of the library archive, and installation of
18875 the library (i.e., copying associated source, object and @file{ALI} files
18876 to the specified location).
18877
18878 Here is a simple library project file:
18879 @smallexample @c ada
18880 project My_Lib is
18881 for Source_Dirs use ("src1", "src2");
18882 for Object_Dir use "obj";
18883 for Library_Name use "mylib";
18884 for Library_Dir use "lib";
18885 for Library_Kind use "dynamic";
18886 end My_lib;
18887 @end smallexample
18888
18889 @noindent
18890 and the compilation command to build and install the library:
18891
18892 @smallexample @c ada
18893 $ gnatmake -Pmy_lib
18894 @end smallexample
18895
18896 @noindent
18897 It is not entirely trivial to perform manually all the steps required to
18898 produce a library. We recommend that you use the GNAT Project Manager
18899 for this task. In special cases where this is not desired, the necessary
18900 steps are discussed below.
18901
18902 There are various possibilities for compiling the units that make up the
18903 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18904 with a conventional script. For simple libraries, it is also possible to create
18905 a dummy main program which depends upon all the packages that comprise the
18906 interface of the library. This dummy main program can then be given to
18907 @command{gnatmake}, which will ensure that all necessary objects are built.
18908
18909 After this task is accomplished, you should follow the standard procedure
18910 of the underlying operating system to produce the static or shared library.
18911
18912 Here is an example of such a dummy program:
18913 @smallexample @c ada
18914 @group
18915 with My_Lib.Service1;
18916 with My_Lib.Service2;
18917 with My_Lib.Service3;
18918 procedure My_Lib_Dummy is
18919 begin
18920 null;
18921 end;
18922 @end group
18923 @end smallexample
18924
18925 @noindent
18926 Here are the generic commands that will build an archive or a shared library.
18927
18928 @smallexample
18929 # compiling the library
18930 $ gnatmake -c my_lib_dummy.adb
18931
18932 # we don't need the dummy object itself
18933 $ rm my_lib_dummy.o my_lib_dummy.ali
18934
18935 # create an archive with the remaining objects
18936 $ ar rc libmy_lib.a *.o
18937 # some systems may require "ranlib" to be run as well
18938
18939 # or create a shared library
18940 $ gcc -shared -o libmy_lib.so *.o
18941 # some systems may require the code to have been compiled with -fPIC
18942
18943 # remove the object files that are now in the library
18944 $ rm *.o
18945
18946 # Make the ALI files read-only so that gnatmake will not try to
18947 # regenerate the objects that are in the library
18948 $ chmod -w *.ali
18949 @end smallexample
18950
18951 @noindent
18952 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18953 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18954 be accessed by the directive @option{-l@var{xxx}} at link time.
18955
18956 @node Installing a library
18957 @subsection Installing a library
18958 @cindex @code{ADA_PROJECT_PATH}
18959
18960 @noindent
18961 If you use project files, library installation is part of the library build
18962 process. Thus no further action is needed in order to make use of the
18963 libraries that are built as part of the general application build. A usable
18964 version of the library is installed in the directory specified by the
18965 @code{Library_Dir} attribute of the library project file.
18966
18967 You may want to install a library in a context different from where the library
18968 is built. This situation arises with third party suppliers, who may want
18969 to distribute a library in binary form where the user is not expected to be
18970 able to recompile the library. The simplest option in this case is to provide
18971 a project file slightly different from the one used to build the library, by
18972 using the @code{externally_built} attribute. For instance, the project
18973 file used to build the library in the previous section can be changed into the
18974 following one when the library is installed:
18975
18976 @smallexample @c projectfile
18977 project My_Lib is
18978 for Source_Dirs use ("src1", "src2");
18979 for Library_Name use "mylib";
18980 for Library_Dir use "lib";
18981 for Library_Kind use "dynamic";
18982 for Externally_Built use "true";
18983 end My_lib;
18984 @end smallexample
18985
18986 @noindent
18987 This project file assumes that the directories @file{src1},
18988 @file{src2}, and @file{lib} exist in
18989 the directory containing the project file. The @code{externally_built}
18990 attribute makes it clear to the GNAT builder that it should not attempt to
18991 recompile any of the units from this library. It allows the library provider to
18992 restrict the source set to the minimum necessary for clients to make use of the
18993 library as described in the first section of this chapter. It is the
18994 responsibility of the library provider to install the necessary sources, ALI
18995 files and libraries in the directories mentioned in the project file. For
18996 convenience, the user's library project file should be installed in a location
18997 that will be searched automatically by the GNAT
18998 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18999 environment variable (@pxref{Importing Projects}), and also the default GNAT
19000 library location that can be queried with @command{gnatls -v} and is usually of
19001 the form $gnat_install_root/lib/gnat.
19002
19003 When project files are not an option, it is also possible, but not recommended,
19004 to install the library so that the sources needed to use the library are on the
19005 Ada source path and the ALI files & libraries be on the Ada Object path (see
19006 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19007 administrator can place general-purpose libraries in the default compiler
19008 paths, by specifying the libraries' location in the configuration files
19009 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19010 must be located in the GNAT installation tree at the same place as the gcc spec
19011 file. The location of the gcc spec file can be determined as follows:
19012 @smallexample
19013 $ gcc -v
19014 @end smallexample
19015
19016 @noindent
19017 The configuration files mentioned above have a simple format: each line
19018 must contain one unique directory name.
19019 Those names are added to the corresponding path
19020 in their order of appearance in the file. The names can be either absolute
19021 or relative; in the latter case, they are relative to where theses files
19022 are located.
19023
19024 The files @file{ada_source_path} and @file{ada_object_path} might not be
19025 present in a
19026 GNAT installation, in which case, GNAT will look for its run-time library in
19027 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19028 objects and @file{ALI} files). When the files exist, the compiler does not
19029 look in @file{adainclude} and @file{adalib}, and thus the
19030 @file{ada_source_path} file
19031 must contain the location for the GNAT run-time sources (which can simply
19032 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19033 contain the location for the GNAT run-time objects (which can simply
19034 be @file{adalib}).
19035
19036 You can also specify a new default path to the run-time library at compilation
19037 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19038 the run-time library you want your program to be compiled with. This switch is
19039 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19040 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19041
19042 It is possible to install a library before or after the standard GNAT
19043 library, by reordering the lines in the configuration files. In general, a
19044 library must be installed before the GNAT library if it redefines
19045 any part of it.
19046
19047 @node Using a library
19048 @subsection Using a library
19049
19050 @noindent Once again, the project facility greatly simplifies the use of
19051 libraries. In this context, using a library is just a matter of adding a
19052 @code{with} clause in the user project. For instance, to make use of the
19053 library @code{My_Lib} shown in examples in earlier sections, you can
19054 write:
19055
19056 @smallexample @c projectfile
19057 with "my_lib";
19058 project My_Proj is
19059 @dots{}
19060 end My_Proj;
19061 @end smallexample
19062
19063 Even if you have a third-party, non-Ada library, you can still use GNAT's
19064 Project Manager facility to provide a wrapper for it. For example, the
19065 following project, when @code{with}ed by your main project, will link with the
19066 third-party library @file{liba.a}:
19067
19068 @smallexample @c projectfile
19069 @group
19070 project Liba is
19071 for Externally_Built use "true";
19072 for Source_Files use ();
19073 for Library_Dir use "lib";
19074 for Library_Name use "a";
19075 for Library_Kind use "static";
19076 end Liba;
19077 @end group
19078 @end smallexample
19079 This is an alternative to the use of @code{pragma Linker_Options}. It is
19080 especially interesting in the context of systems with several interdependent
19081 static libraries where finding a proper linker order is not easy and best be
19082 left to the tools having visibility over project dependence information.
19083
19084 @noindent
19085 In order to use an Ada library manually, you need to make sure that this
19086 library is on both your source and object path
19087 (see @ref{Search Paths and the Run-Time Library (RTL)}
19088 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19089 in an archive or a shared library, you need to specify the desired
19090 library at link time.
19091
19092 For example, you can use the library @file{mylib} installed in
19093 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19094
19095 @smallexample
19096 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19097 -largs -lmy_lib
19098 @end smallexample
19099
19100 @noindent
19101 This can be expressed more simply:
19102 @smallexample
19103 $ gnatmake my_appl
19104 @end smallexample
19105 @noindent
19106 when the following conditions are met:
19107 @itemize @bullet
19108 @item
19109 @file{/dir/my_lib_src} has been added by the user to the environment
19110 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19111 @file{ada_source_path}
19112 @item
19113 @file{/dir/my_lib_obj} has been added by the user to the environment
19114 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19115 @file{ada_object_path}
19116 @item
19117 a pragma @code{Linker_Options} has been added to one of the sources.
19118 For example:
19119
19120 @smallexample @c ada
19121 pragma Linker_Options ("-lmy_lib");
19122 @end smallexample
19123 @end itemize
19124
19125 @node Stand-alone Ada Libraries
19126 @section Stand-alone Ada Libraries
19127 @cindex Stand-alone library, building, using
19128
19129 @menu
19130 * Introduction to Stand-alone Libraries::
19131 * Building a Stand-alone Library::
19132 * Creating a Stand-alone Library to be used in a non-Ada context::
19133 * Restrictions in Stand-alone Libraries::
19134 @end menu
19135
19136 @node Introduction to Stand-alone Libraries
19137 @subsection Introduction to Stand-alone Libraries
19138
19139 @noindent
19140 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19141 necessary code to
19142 elaborate the Ada units that are included in the library. In contrast with
19143 an ordinary library, which consists of all sources, objects and @file{ALI}
19144 files of the
19145 library, a SAL may specify a restricted subset of compilation units
19146 to serve as a library interface. In this case, the fully
19147 self-sufficient set of files will normally consist of an objects
19148 archive, the sources of interface units' specs, and the @file{ALI}
19149 files of interface units.
19150 If an interface spec contains a generic unit or an inlined subprogram,
19151 the body's
19152 source must also be provided; if the units that must be provided in the source
19153 form depend on other units, the source and @file{ALI} files of those must
19154 also be provided.
19155
19156 The main purpose of a SAL is to minimize the recompilation overhead of client
19157 applications when a new version of the library is installed. Specifically,
19158 if the interface sources have not changed, client applications do not need to
19159 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19160 version, controlled by @code{Library_Version} attribute, is not changed,
19161 then the clients do not need to be relinked.
19162
19163 SALs also allow the library providers to minimize the amount of library source
19164 text exposed to the clients. Such ``information hiding'' might be useful or
19165 necessary for various reasons.
19166
19167 Stand-alone libraries are also well suited to be used in an executable whose
19168 main routine is not written in Ada.
19169
19170 @node Building a Stand-alone Library
19171 @subsection Building a Stand-alone Library
19172
19173 @noindent
19174 GNAT's Project facility provides a simple way of building and installing
19175 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19176 To be a Stand-alone Library Project, in addition to the two attributes
19177 that make a project a Library Project (@code{Library_Name} and
19178 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19179 @code{Library_Interface} must be defined. For example:
19180
19181 @smallexample @c projectfile
19182 @group
19183 for Library_Dir use "lib_dir";
19184 for Library_Name use "dummy";
19185 for Library_Interface use ("int1", "int1.child");
19186 @end group
19187 @end smallexample
19188
19189 @noindent
19190 Attribute @code{Library_Interface} has a non-empty string list value,
19191 each string in the list designating a unit contained in an immediate source
19192 of the project file.
19193
19194 When a Stand-alone Library is built, first the binder is invoked to build
19195 a package whose name depends on the library name
19196 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19197 This binder-generated package includes initialization and
19198 finalization procedures whose
19199 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19200 in the example
19201 above). The object corresponding to this package is included in the library.
19202
19203 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19204 calling of these procedures if a static SAL is built, or if a shared SAL
19205 is built
19206 with the project-level attribute @code{Library_Auto_Init} set to
19207 @code{"false"}.
19208
19209 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19210 (those that are listed in attribute @code{Library_Interface}) are copied to
19211 the Library Directory. As a consequence, only the Interface Units may be
19212 imported from Ada units outside of the library. If other units are imported,
19213 the binding phase will fail.
19214
19215 The attribute @code{Library_Src_Dir} may be specified for a
19216 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19217 single string value. Its value must be the path (absolute or relative to the
19218 project directory) of an existing directory. This directory cannot be the
19219 object directory or one of the source directories, but it can be the same as
19220 the library directory. The sources of the Interface
19221 Units of the library that are needed by an Ada client of the library will be
19222 copied to the designated directory, called the Interface Copy directory.
19223 These sources include the specs of the Interface Units, but they may also
19224 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19225 are used, or when there is a generic unit in the spec. Before the sources
19226 are copied to the Interface Copy directory, an attempt is made to delete all
19227 files in the Interface Copy directory.
19228
19229 Building stand-alone libraries by hand is somewhat tedious, but for those
19230 occasions when it is necessary here are the steps that you need to perform:
19231 @itemize @bullet
19232 @item
19233 Compile all library sources.
19234
19235 @item
19236 Invoke the binder with the switch @option{-n} (No Ada main program),
19237 with all the @file{ALI} files of the interfaces, and
19238 with the switch @option{-L} to give specific names to the @code{init}
19239 and @code{final} procedures. For example:
19240 @smallexample
19241 gnatbind -n int1.ali int2.ali -Lsal1
19242 @end smallexample
19243
19244 @item
19245 Compile the binder generated file:
19246 @smallexample
19247 gcc -c b~int2.adb
19248 @end smallexample
19249
19250 @item
19251 Link the dynamic library with all the necessary object files,
19252 indicating to the linker the names of the @code{init} (and possibly
19253 @code{final}) procedures for automatic initialization (and finalization).
19254 The built library should be placed in a directory different from
19255 the object directory.
19256
19257 @item
19258 Copy the @code{ALI} files of the interface to the library directory,
19259 add in this copy an indication that it is an interface to a SAL
19260 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19261 with letter ``P'') and make the modified copy of the @file{ALI} file
19262 read-only.
19263 @end itemize
19264
19265 @noindent
19266 Using SALs is not different from using other libraries
19267 (see @ref{Using a library}).
19268
19269 @node Creating a Stand-alone Library to be used in a non-Ada context
19270 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19271
19272 @noindent
19273 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19274 a non-Ada context.
19275
19276 The only extra step required is to ensure that library interface subprograms
19277 are compatible with the main program, by means of @code{pragma Export}
19278 or @code{pragma Convention}.
19279
19280 Here is an example of simple library interface for use with C main program:
19281
19282 @smallexample @c ada
19283 package Interface is
19284
19285 procedure Do_Something;
19286 pragma Export (C, Do_Something, "do_something");
19287
19288 procedure Do_Something_Else;
19289 pragma Export (C, Do_Something_Else, "do_something_else");
19290
19291 end Interface;
19292 @end smallexample
19293
19294 @noindent
19295 On the foreign language side, you must provide a ``foreign'' view of the
19296 library interface; remember that it should contain elaboration routines in
19297 addition to interface subprograms.
19298
19299 The example below shows the content of @code{mylib_interface.h} (note
19300 that there is no rule for the naming of this file, any name can be used)
19301 @smallexample
19302 /* the library elaboration procedure */
19303 extern void mylibinit (void);
19304
19305 /* the library finalization procedure */
19306 extern void mylibfinal (void);
19307
19308 /* the interface exported by the library */
19309 extern void do_something (void);
19310 extern void do_something_else (void);
19311 @end smallexample
19312
19313 @noindent
19314 Libraries built as explained above can be used from any program, provided
19315 that the elaboration procedures (named @code{mylibinit} in the previous
19316 example) are called before the library services are used. Any number of
19317 libraries can be used simultaneously, as long as the elaboration
19318 procedure of each library is called.
19319
19320 Below is an example of a C program that uses the @code{mylib} library.
19321
19322 @smallexample
19323 #include "mylib_interface.h"
19324
19325 int
19326 main (void)
19327 @{
19328 /* First, elaborate the library before using it */
19329 mylibinit ();
19330
19331 /* Main program, using the library exported entities */
19332 do_something ();
19333 do_something_else ();
19334
19335 /* Library finalization at the end of the program */
19336 mylibfinal ();
19337 return 0;
19338 @}
19339 @end smallexample
19340
19341 @noindent
19342 Note that invoking any library finalization procedure generated by
19343 @code{gnatbind} shuts down the Ada run-time environment.
19344 Consequently, the
19345 finalization of all Ada libraries must be performed at the end of the program.
19346 No call to these libraries or to the Ada run-time library should be made
19347 after the finalization phase.
19348
19349 @node Restrictions in Stand-alone Libraries
19350 @subsection Restrictions in Stand-alone Libraries
19351
19352 @noindent
19353 The pragmas listed below should be used with caution inside libraries,
19354 as they can create incompatibilities with other Ada libraries:
19355 @itemize @bullet
19356 @item pragma @code{Locking_Policy}
19357 @item pragma @code{Queuing_Policy}
19358 @item pragma @code{Task_Dispatching_Policy}
19359 @item pragma @code{Unreserve_All_Interrupts}
19360 @end itemize
19361
19362 @noindent
19363 When using a library that contains such pragmas, the user must make sure
19364 that all libraries use the same pragmas with the same values. Otherwise,
19365 @code{Program_Error} will
19366 be raised during the elaboration of the conflicting
19367 libraries. The usage of these pragmas and its consequences for the user
19368 should therefore be well documented.
19369
19370 Similarly, the traceback in the exception occurrence mechanism should be
19371 enabled or disabled in a consistent manner across all libraries.
19372 Otherwise, Program_Error will be raised during the elaboration of the
19373 conflicting libraries.
19374
19375 If the @code{Version} or @code{Body_Version}
19376 attributes are used inside a library, then you need to
19377 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19378 libraries, so that version identifiers can be properly computed.
19379 In practice these attributes are rarely used, so this is unlikely
19380 to be a consideration.
19381
19382 @node Rebuilding the GNAT Run-Time Library
19383 @section Rebuilding the GNAT Run-Time Library
19384 @cindex GNAT Run-Time Library, rebuilding
19385 @cindex Building the GNAT Run-Time Library
19386 @cindex Rebuilding the GNAT Run-Time Library
19387 @cindex Run-Time Library, rebuilding
19388
19389 @noindent
19390 It may be useful to recompile the GNAT library in various contexts, the
19391 most important one being the use of partition-wide configuration pragmas
19392 such as @code{Normalize_Scalars}. A special Makefile called
19393 @code{Makefile.adalib} is provided to that effect and can be found in
19394 the directory containing the GNAT library. The location of this
19395 directory depends on the way the GNAT environment has been installed and can
19396 be determined by means of the command:
19397
19398 @smallexample
19399 $ gnatls -v
19400 @end smallexample
19401
19402 @noindent
19403 The last entry in the object search path usually contains the
19404 gnat library. This Makefile contains its own documentation and in
19405 particular the set of instructions needed to rebuild a new library and
19406 to use it.
19407
19408 @node Using the GNU make Utility
19409 @chapter Using the GNU @code{make} Utility
19410 @findex make
19411
19412 @noindent
19413 This chapter offers some examples of makefiles that solve specific
19414 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19415 make, make, GNU @code{make}}), nor does it try to replace the
19416 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19417
19418 All the examples in this section are specific to the GNU version of
19419 make. Although @command{make} is a standard utility, and the basic language
19420 is the same, these examples use some advanced features found only in
19421 @code{GNU make}.
19422
19423 @menu
19424 * Using gnatmake in a Makefile::
19425 * Automatically Creating a List of Directories::
19426 * Generating the Command Line Switches::
19427 * Overcoming Command Line Length Limits::
19428 @end menu
19429
19430 @node Using gnatmake in a Makefile
19431 @section Using gnatmake in a Makefile
19432 @findex makefile
19433 @cindex GNU make
19434
19435 @noindent
19436 Complex project organizations can be handled in a very powerful way by
19437 using GNU make combined with gnatmake. For instance, here is a Makefile
19438 which allows you to build each subsystem of a big project into a separate
19439 shared library. Such a makefile allows you to significantly reduce the link
19440 time of very big applications while maintaining full coherence at
19441 each step of the build process.
19442
19443 The list of dependencies are handled automatically by
19444 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19445 the appropriate directories.
19446
19447 Note that you should also read the example on how to automatically
19448 create the list of directories
19449 (@pxref{Automatically Creating a List of Directories})
19450 which might help you in case your project has a lot of subdirectories.
19451
19452 @smallexample
19453 @iftex
19454 @leftskip=0cm
19455 @font@heightrm=cmr8
19456 @heightrm
19457 @end iftex
19458 ## This Makefile is intended to be used with the following directory
19459 ## configuration:
19460 ## - The sources are split into a series of csc (computer software components)
19461 ## Each of these csc is put in its own directory.
19462 ## Their name are referenced by the directory names.
19463 ## They will be compiled into shared library (although this would also work
19464 ## with static libraries
19465 ## - The main program (and possibly other packages that do not belong to any
19466 ## csc is put in the top level directory (where the Makefile is).
19467 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
19468 ## \_ second_csc (sources) __ lib (will contain the library)
19469 ## \_ @dots{}
19470 ## Although this Makefile is build for shared library, it is easy to modify
19471 ## to build partial link objects instead (modify the lines with -shared and
19472 ## gnatlink below)
19473 ##
19474 ## With this makefile, you can change any file in the system or add any new
19475 ## file, and everything will be recompiled correctly (only the relevant shared
19476 ## objects will be recompiled, and the main program will be re-linked).
19477
19478 # The list of computer software component for your project. This might be
19479 # generated automatically.
19480 CSC_LIST=aa bb cc
19481
19482 # Name of the main program (no extension)
19483 MAIN=main
19484
19485 # If we need to build objects with -fPIC, uncomment the following line
19486 #NEED_FPIC=-fPIC
19487
19488 # The following variable should give the directory containing libgnat.so
19489 # You can get this directory through 'gnatls -v'. This is usually the last
19490 # directory in the Object_Path.
19491 GLIB=@dots{}
19492
19493 # The directories for the libraries
19494 # (This macro expands the list of CSC to the list of shared libraries, you
19495 # could simply use the expanded form:
19496 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19497 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19498
19499 $@{MAIN@}: objects $@{LIB_DIR@}
19500 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19501 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19502
19503 objects::
19504 # recompile the sources
19505 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19506
19507 # Note: In a future version of GNAT, the following commands will be simplified
19508 # by a new tool, gnatmlib
19509 $@{LIB_DIR@}:
19510 mkdir -p $@{dir $@@ @}
19511 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19512 cd $@{dir $@@ @} && cp -f ../*.ali .
19513
19514 # The dependencies for the modules
19515 # Note that we have to force the expansion of *.o, since in some cases
19516 # make won't be able to do it itself.
19517 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19518 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19519 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19520
19521 # Make sure all of the shared libraries are in the path before starting the
19522 # program
19523 run::
19524 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19525
19526 clean::
19527 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19528 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19529 $@{RM@} $@{CSC_LIST:%=%/*.o@}
19530 $@{RM@} *.o *.ali $@{MAIN@}
19531 @end smallexample
19532
19533 @node Automatically Creating a List of Directories
19534 @section Automatically Creating a List of Directories
19535
19536 @noindent
19537 In most makefiles, you will have to specify a list of directories, and
19538 store it in a variable. For small projects, it is often easier to
19539 specify each of them by hand, since you then have full control over what
19540 is the proper order for these directories, which ones should be
19541 included.
19542
19543 However, in larger projects, which might involve hundreds of
19544 subdirectories, it might be more convenient to generate this list
19545 automatically.
19546
19547 The example below presents two methods. The first one, although less
19548 general, gives you more control over the list. It involves wildcard
19549 characters, that are automatically expanded by @command{make}. Its
19550 shortcoming is that you need to explicitly specify some of the
19551 organization of your project, such as for instance the directory tree
19552 depth, whether some directories are found in a separate tree, @enddots{}
19553
19554 The second method is the most general one. It requires an external
19555 program, called @command{find}, which is standard on all Unix systems. All
19556 the directories found under a given root directory will be added to the
19557 list.
19558
19559 @smallexample
19560 @iftex
19561 @leftskip=0cm
19562 @font@heightrm=cmr8
19563 @heightrm
19564 @end iftex
19565 # The examples below are based on the following directory hierarchy:
19566 # All the directories can contain any number of files
19567 # ROOT_DIRECTORY -> a -> aa -> aaa
19568 # -> ab
19569 # -> ac
19570 # -> b -> ba -> baa
19571 # -> bb
19572 # -> bc
19573 # This Makefile creates a variable called DIRS, that can be reused any time
19574 # you need this list (see the other examples in this section)
19575
19576 # The root of your project's directory hierarchy
19577 ROOT_DIRECTORY=.
19578
19579 ####
19580 # First method: specify explicitly the list of directories
19581 # This allows you to specify any subset of all the directories you need.
19582 ####
19583
19584 DIRS := a/aa/ a/ab/ b/ba/
19585
19586 ####
19587 # Second method: use wildcards
19588 # Note that the argument(s) to wildcard below should end with a '/'.
19589 # Since wildcards also return file names, we have to filter them out
19590 # to avoid duplicate directory names.
19591 # We thus use make's @code{dir} and @code{sort} functions.
19592 # It sets DIRs to the following value (note that the directories aaa and baa
19593 # are not given, unless you change the arguments to wildcard).
19594 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19595 ####
19596
19597 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19598 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19599
19600 ####
19601 # Third method: use an external program
19602 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19603 # This is the most complete command: it sets DIRs to the following value:
19604 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19605 ####
19606
19607 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19608
19609 @end smallexample
19610
19611 @node Generating the Command Line Switches
19612 @section Generating the Command Line Switches
19613
19614 @noindent
19615 Once you have created the list of directories as explained in the
19616 previous section (@pxref{Automatically Creating a List of Directories}),
19617 you can easily generate the command line arguments to pass to gnatmake.
19618
19619 For the sake of completeness, this example assumes that the source path
19620 is not the same as the object path, and that you have two separate lists
19621 of directories.
19622
19623 @smallexample
19624 # see "Automatically creating a list of directories" to create
19625 # these variables
19626 SOURCE_DIRS=
19627 OBJECT_DIRS=
19628
19629 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19630 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19631
19632 all:
19633 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19634 @end smallexample
19635
19636 @node Overcoming Command Line Length Limits
19637 @section Overcoming Command Line Length Limits
19638
19639 @noindent
19640 One problem that might be encountered on big projects is that many
19641 operating systems limit the length of the command line. It is thus hard to give
19642 gnatmake the list of source and object directories.
19643
19644 This example shows how you can set up environment variables, which will
19645 make @command{gnatmake} behave exactly as if the directories had been
19646 specified on the command line, but have a much higher length limit (or
19647 even none on most systems).
19648
19649 It assumes that you have created a list of directories in your Makefile,
19650 using one of the methods presented in
19651 @ref{Automatically Creating a List of Directories}.
19652 For the sake of completeness, we assume that the object
19653 path (where the ALI files are found) is different from the sources patch.
19654
19655 Note a small trick in the Makefile below: for efficiency reasons, we
19656 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19657 expanded immediately by @code{make}. This way we overcome the standard
19658 make behavior which is to expand the variables only when they are
19659 actually used.
19660
19661 On Windows, if you are using the standard Windows command shell, you must
19662 replace colons with semicolons in the assignments to these variables.
19663
19664 @smallexample
19665 @iftex
19666 @leftskip=0cm
19667 @font@heightrm=cmr8
19668 @heightrm
19669 @end iftex
19670 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19671 # This is the same thing as putting the -I arguments on the command line.
19672 # (the equivalent of using -aI on the command line would be to define
19673 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19674 # You can of course have different values for these variables.
19675 #
19676 # Note also that we need to keep the previous values of these variables, since
19677 # they might have been set before running 'make' to specify where the GNAT
19678 # library is installed.
19679
19680 # see "Automatically creating a list of directories" to create these
19681 # variables
19682 SOURCE_DIRS=
19683 OBJECT_DIRS=
19684
19685 empty:=
19686 space:=$@{empty@} $@{empty@}
19687 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19688 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19689 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19690 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19691 export ADA_INCLUDE_PATH
19692 export ADA_OBJECT_PATH
19693
19694 all:
19695 gnatmake main_unit
19696 @end smallexample
19697 @end ifclear
19698
19699 @node Memory Management Issues
19700 @chapter Memory Management Issues
19701
19702 @noindent
19703 This chapter describes some useful memory pools provided in the GNAT library
19704 and in particular the GNAT Debug Pool facility, which can be used to detect
19705 incorrect uses of access values (including ``dangling references'').
19706 @ifclear vms
19707 It also describes the @command{gnatmem} tool, which can be used to track down
19708 ``memory leaks''.
19709 @end ifclear
19710
19711 @menu
19712 * Some Useful Memory Pools::
19713 * The GNAT Debug Pool Facility::
19714 @ifclear vms
19715 * The gnatmem Tool::
19716 @end ifclear
19717 @end menu
19718
19719 @node Some Useful Memory Pools
19720 @section Some Useful Memory Pools
19721 @findex Memory Pool
19722 @cindex storage, pool
19723
19724 @noindent
19725 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19726 storage pool. Allocations use the standard system call @code{malloc} while
19727 deallocations use the standard system call @code{free}. No reclamation is
19728 performed when the pool goes out of scope. For performance reasons, the
19729 standard default Ada allocators/deallocators do not use any explicit storage
19730 pools but if they did, they could use this storage pool without any change in
19731 behavior. That is why this storage pool is used when the user
19732 manages to make the default implicit allocator explicit as in this example:
19733 @smallexample @c ada
19734 type T1 is access Something;
19735 -- no Storage pool is defined for T2
19736 type T2 is access Something_Else;
19737 for T2'Storage_Pool use T1'Storage_Pool;
19738 -- the above is equivalent to
19739 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19740 @end smallexample
19741
19742 @noindent
19743 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19744 pool. The allocation strategy is similar to @code{Pool_Local}'s
19745 except that the all
19746 storage allocated with this pool is reclaimed when the pool object goes out of
19747 scope. This pool provides a explicit mechanism similar to the implicit one
19748 provided by several Ada 83 compilers for allocations performed through a local
19749 access type and whose purpose was to reclaim memory when exiting the
19750 scope of a given local access. As an example, the following program does not
19751 leak memory even though it does not perform explicit deallocation:
19752
19753 @smallexample @c ada
19754 with System.Pool_Local;
19755 procedure Pooloc1 is
19756 procedure Internal is
19757 type A is access Integer;
19758 X : System.Pool_Local.Unbounded_Reclaim_Pool;
19759 for A'Storage_Pool use X;
19760 v : A;
19761 begin
19762 for I in 1 .. 50 loop
19763 v := new Integer;
19764 end loop;
19765 end Internal;
19766 begin
19767 for I in 1 .. 100 loop
19768 Internal;
19769 end loop;
19770 end Pooloc1;
19771 @end smallexample
19772
19773 @noindent
19774 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19775 @code{Storage_Size} is specified for an access type.
19776 The whole storage for the pool is
19777 allocated at once, usually on the stack at the point where the access type is
19778 elaborated. It is automatically reclaimed when exiting the scope where the
19779 access type is defined. This package is not intended to be used directly by the
19780 user and it is implicitly used for each such declaration:
19781
19782 @smallexample @c ada
19783 type T1 is access Something;
19784 for T1'Storage_Size use 10_000;
19785 @end smallexample
19786
19787 @node The GNAT Debug Pool Facility
19788 @section The GNAT Debug Pool Facility
19789 @findex Debug Pool
19790 @cindex storage, pool, memory corruption
19791
19792 @noindent
19793 The use of unchecked deallocation and unchecked conversion can easily
19794 lead to incorrect memory references. The problems generated by such
19795 references are usually difficult to tackle because the symptoms can be
19796 very remote from the origin of the problem. In such cases, it is
19797 very helpful to detect the problem as early as possible. This is the
19798 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19799
19800 In order to use the GNAT specific debugging pool, the user must
19801 associate a debug pool object with each of the access types that may be
19802 related to suspected memory problems. See Ada Reference Manual 13.11.
19803 @smallexample @c ada
19804 type Ptr is access Some_Type;
19805 Pool : GNAT.Debug_Pools.Debug_Pool;
19806 for Ptr'Storage_Pool use Pool;
19807 @end smallexample
19808
19809 @noindent
19810 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19811 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19812 allow the user to redefine allocation and deallocation strategies. They
19813 also provide a checkpoint for each dereference, through the use of
19814 the primitive operation @code{Dereference} which is implicitly called at
19815 each dereference of an access value.
19816
19817 Once an access type has been associated with a debug pool, operations on
19818 values of the type may raise four distinct exceptions,
19819 which correspond to four potential kinds of memory corruption:
19820 @itemize @bullet
19821 @item
19822 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19823 @item
19824 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19825 @item
19826 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19827 @item
19828 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19829 @end itemize
19830
19831 @noindent
19832 For types associated with a Debug_Pool, dynamic allocation is performed using
19833 the standard GNAT allocation routine. References to all allocated chunks of
19834 memory are kept in an internal dictionary. Several deallocation strategies are
19835 provided, whereupon the user can choose to release the memory to the system,
19836 keep it allocated for further invalid access checks, or fill it with an easily
19837 recognizable pattern for debug sessions. The memory pattern is the old IBM
19838 hexadecimal convention: @code{16#DEADBEEF#}.
19839
19840 See the documentation in the file g-debpoo.ads for more information on the
19841 various strategies.
19842
19843 Upon each dereference, a check is made that the access value denotes a
19844 properly allocated memory location. Here is a complete example of use of
19845 @code{Debug_Pools}, that includes typical instances of memory corruption:
19846 @smallexample @c ada
19847 @iftex
19848 @leftskip=0cm
19849 @end iftex
19850 with Gnat.Io; use Gnat.Io;
19851 with Unchecked_Deallocation;
19852 with Unchecked_Conversion;
19853 with GNAT.Debug_Pools;
19854 with System.Storage_Elements;
19855 with Ada.Exceptions; use Ada.Exceptions;
19856 procedure Debug_Pool_Test is
19857
19858 type T is access Integer;
19859 type U is access all T;
19860
19861 P : GNAT.Debug_Pools.Debug_Pool;
19862 for T'Storage_Pool use P;
19863
19864 procedure Free is new Unchecked_Deallocation (Integer, T);
19865 function UC is new Unchecked_Conversion (U, T);
19866 A, B : aliased T;
19867
19868 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19869
19870 begin
19871 Info (P);
19872 A := new Integer;
19873 B := new Integer;
19874 B := A;
19875 Info (P);
19876 Free (A);
19877 begin
19878 Put_Line (Integer'Image(B.all));
19879 exception
19880 when E : others => Put_Line ("raised: " & Exception_Name (E));
19881 end;
19882 begin
19883 Free (B);
19884 exception
19885 when E : others => Put_Line ("raised: " & Exception_Name (E));
19886 end;
19887 B := UC(A'Access);
19888 begin
19889 Put_Line (Integer'Image(B.all));
19890 exception
19891 when E : others => Put_Line ("raised: " & Exception_Name (E));
19892 end;
19893 begin
19894 Free (B);
19895 exception
19896 when E : others => Put_Line ("raised: " & Exception_Name (E));
19897 end;
19898 Info (P);
19899 end Debug_Pool_Test;
19900 @end smallexample
19901
19902 @noindent
19903 The debug pool mechanism provides the following precise diagnostics on the
19904 execution of this erroneous program:
19905 @smallexample
19906 Debug Pool info:
19907 Total allocated bytes : 0
19908 Total deallocated bytes : 0
19909 Current Water Mark: 0
19910 High Water Mark: 0
19911
19912 Debug Pool info:
19913 Total allocated bytes : 8
19914 Total deallocated bytes : 0
19915 Current Water Mark: 8
19916 High Water Mark: 8
19917
19918 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19919 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19920 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19921 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19922 Debug Pool info:
19923 Total allocated bytes : 8
19924 Total deallocated bytes : 4
19925 Current Water Mark: 4
19926 High Water Mark: 8
19927 @end smallexample
19928
19929 @ifclear vms
19930 @node The gnatmem Tool
19931 @section The @command{gnatmem} Tool
19932 @findex gnatmem
19933
19934 @noindent
19935 The @code{gnatmem} utility monitors dynamic allocation and
19936 deallocation activity in a program, and displays information about
19937 incorrect deallocations and possible sources of memory leaks.
19938 It is designed to work in association with a static runtime library
19939 only and in this context provides three types of information:
19940 @itemize @bullet
19941 @item
19942 General information concerning memory management, such as the total
19943 number of allocations and deallocations, the amount of allocated
19944 memory and the high water mark, i.e.@: the largest amount of allocated
19945 memory in the course of program execution.
19946
19947 @item
19948 Backtraces for all incorrect deallocations, that is to say deallocations
19949 which do not correspond to a valid allocation.
19950
19951 @item
19952 Information on each allocation that is potentially the origin of a memory
19953 leak.
19954 @end itemize
19955
19956 @menu
19957 * Running gnatmem::
19958 * Switches for gnatmem::
19959 * Example of gnatmem Usage::
19960 @end menu
19961
19962 @node Running gnatmem
19963 @subsection Running @code{gnatmem}
19964
19965 @noindent
19966 @code{gnatmem} makes use of the output created by the special version of
19967 allocation and deallocation routines that record call information. This
19968 allows to obtain accurate dynamic memory usage history at a minimal cost to
19969 the execution speed. Note however, that @code{gnatmem} is not supported on
19970 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19971 Solaris and Windows NT/2000/XP (x86).
19972
19973 @noindent
19974 The @code{gnatmem} command has the form
19975
19976 @smallexample
19977 $ gnatmem @ovar{switches} user_program
19978 @end smallexample
19979
19980 @noindent
19981 The program must have been linked with the instrumented version of the
19982 allocation and deallocation routines. This is done by linking with the
19983 @file{libgmem.a} library. For correct symbolic backtrace information,
19984 the user program should be compiled with debugging options
19985 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19986
19987 @smallexample
19988 $ gnatmake -g my_program -largs -lgmem
19989 @end smallexample
19990
19991 @noindent
19992 As library @file{libgmem.a} contains an alternate body for package
19993 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19994 when an executable is linked with library @file{libgmem.a}. It is then not
19995 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19996
19997 @noindent
19998 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19999 This file contains information about all allocations and deallocations
20000 performed by the program. It is produced by the instrumented allocations and
20001 deallocations routines and will be used by @code{gnatmem}.
20002
20003 In order to produce symbolic backtrace information for allocations and
20004 deallocations performed by the GNAT run-time library, you need to use a
20005 version of that library that has been compiled with the @option{-g} switch
20006 (see @ref{Rebuilding the GNAT Run-Time Library}).
20007
20008 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20009 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20010 @option{-i} switch, gnatmem will assume that this file can be found in the
20011 current directory. For example, after you have executed @file{my_program},
20012 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20013
20014 @smallexample
20015 $ gnatmem my_program
20016 @end smallexample
20017
20018 @noindent
20019 This will produce the output with the following format:
20020
20021 *************** debut cc
20022 @smallexample
20023 $ gnatmem my_program
20024
20025 Global information
20026 ------------------
20027 Total number of allocations : 45
20028 Total number of deallocations : 6
20029 Final Water Mark (non freed mem) : 11.29 Kilobytes
20030 High Water Mark : 11.40 Kilobytes
20031
20032 .
20033 .
20034 .
20035 Allocation Root # 2
20036 -------------------
20037 Number of non freed allocations : 11
20038 Final Water Mark (non freed mem) : 1.16 Kilobytes
20039 High Water Mark : 1.27 Kilobytes
20040 Backtrace :
20041 my_program.adb:23 my_program.alloc
20042 .
20043 .
20044 .
20045 @end smallexample
20046
20047 The first block of output gives general information. In this case, the
20048 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20049 Unchecked_Deallocation routine occurred.
20050
20051 @noindent
20052 Subsequent paragraphs display information on all allocation roots.
20053 An allocation root is a specific point in the execution of the program
20054 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20055 construct. This root is represented by an execution backtrace (or subprogram
20056 call stack). By default the backtrace depth for allocations roots is 1, so
20057 that a root corresponds exactly to a source location. The backtrace can
20058 be made deeper, to make the root more specific.
20059
20060 @node Switches for gnatmem
20061 @subsection Switches for @code{gnatmem}
20062
20063 @noindent
20064 @code{gnatmem} recognizes the following switches:
20065
20066 @table @option
20067
20068 @item -q
20069 @cindex @option{-q} (@code{gnatmem})
20070 Quiet. Gives the minimum output needed to identify the origin of the
20071 memory leaks. Omits statistical information.
20072
20073 @item @var{N}
20074 @cindex @var{N} (@code{gnatmem})
20075 N is an integer literal (usually between 1 and 10) which controls the
20076 depth of the backtraces defining allocation root. The default value for
20077 N is 1. The deeper the backtrace, the more precise the localization of
20078 the root. Note that the total number of roots can depend on this
20079 parameter. This parameter must be specified @emph{before} the name of the
20080 executable to be analyzed, to avoid ambiguity.
20081
20082 @item -b n
20083 @cindex @option{-b} (@code{gnatmem})
20084 This switch has the same effect as just depth parameter.
20085
20086 @item -i @var{file}
20087 @cindex @option{-i} (@code{gnatmem})
20088 Do the @code{gnatmem} processing starting from @file{file}, rather than
20089 @file{gmem.out} in the current directory.
20090
20091 @item -m n
20092 @cindex @option{-m} (@code{gnatmem})
20093 This switch causes @code{gnatmem} to mask the allocation roots that have less
20094 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20095 examine even the roots that didn't result in leaks.
20096
20097 @item -s order
20098 @cindex @option{-s} (@code{gnatmem})
20099 This switch causes @code{gnatmem} to sort the allocation roots according to the
20100 specified order of sort criteria, each identified by a single letter. The
20101 currently supported criteria are @code{n, h, w} standing respectively for
20102 number of unfreed allocations, high watermark, and final watermark
20103 corresponding to a specific root. The default order is @code{nwh}.
20104
20105 @end table
20106
20107 @node Example of gnatmem Usage
20108 @subsection Example of @code{gnatmem} Usage
20109
20110 @noindent
20111 The following example shows the use of @code{gnatmem}
20112 on a simple memory-leaking program.
20113 Suppose that we have the following Ada program:
20114
20115 @smallexample @c ada
20116 @group
20117 @cartouche
20118 with Unchecked_Deallocation;
20119 procedure Test_Gm is
20120
20121 type T is array (1..1000) of Integer;
20122 type Ptr is access T;
20123 procedure Free is new Unchecked_Deallocation (T, Ptr);
20124 A : Ptr;
20125
20126 procedure My_Alloc is
20127 begin
20128 A := new T;
20129 end My_Alloc;
20130
20131 procedure My_DeAlloc is
20132 B : Ptr := A;
20133 begin
20134 Free (B);
20135 end My_DeAlloc;
20136
20137 begin
20138 My_Alloc;
20139 for I in 1 .. 5 loop
20140 for J in I .. 5 loop
20141 My_Alloc;
20142 end loop;
20143 My_Dealloc;
20144 end loop;
20145 end;
20146 @end cartouche
20147 @end group
20148 @end smallexample
20149
20150 @noindent
20151 The program needs to be compiled with debugging option and linked with
20152 @code{gmem} library:
20153
20154 @smallexample
20155 $ gnatmake -g test_gm -largs -lgmem
20156 @end smallexample
20157
20158 @noindent
20159 Then we execute the program as usual:
20160
20161 @smallexample
20162 $ test_gm
20163 @end smallexample
20164
20165 @noindent
20166 Then @code{gnatmem} is invoked simply with
20167 @smallexample
20168 $ gnatmem test_gm
20169 @end smallexample
20170
20171 @noindent
20172 which produces the following output (result may vary on different platforms):
20173
20174 @smallexample
20175 Global information
20176 ------------------
20177 Total number of allocations : 18
20178 Total number of deallocations : 5
20179 Final Water Mark (non freed mem) : 53.00 Kilobytes
20180 High Water Mark : 56.90 Kilobytes
20181
20182 Allocation Root # 1
20183 -------------------
20184 Number of non freed allocations : 11
20185 Final Water Mark (non freed mem) : 42.97 Kilobytes
20186 High Water Mark : 46.88 Kilobytes
20187 Backtrace :
20188 test_gm.adb:11 test_gm.my_alloc
20189
20190 Allocation Root # 2
20191 -------------------
20192 Number of non freed allocations : 1
20193 Final Water Mark (non freed mem) : 10.02 Kilobytes
20194 High Water Mark : 10.02 Kilobytes
20195 Backtrace :
20196 s-secsta.adb:81 system.secondary_stack.ss_init
20197
20198 Allocation Root # 3
20199 -------------------
20200 Number of non freed allocations : 1
20201 Final Water Mark (non freed mem) : 12 Bytes
20202 High Water Mark : 12 Bytes
20203 Backtrace :
20204 s-secsta.adb:181 system.secondary_stack.ss_init
20205 @end smallexample
20206
20207 @noindent
20208 Note that the GNAT run time contains itself a certain number of
20209 allocations that have no corresponding deallocation,
20210 as shown here for root #2 and root
20211 #3. This is a normal behavior when the number of non-freed allocations
20212 is one, it allocates dynamic data structures that the run time needs for
20213 the complete lifetime of the program. Note also that there is only one
20214 allocation root in the user program with a single line back trace:
20215 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20216 program shows that 'My_Alloc' is called at 2 different points in the
20217 source (line 21 and line 24). If those two allocation roots need to be
20218 distinguished, the backtrace depth parameter can be used:
20219
20220 @smallexample
20221 $ gnatmem 3 test_gm
20222 @end smallexample
20223
20224 @noindent
20225 which will give the following output:
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 : 10
20238 Final Water Mark (non freed mem) : 39.06 Kilobytes
20239 High Water Mark : 42.97 Kilobytes
20240 Backtrace :
20241 test_gm.adb:11 test_gm.my_alloc
20242 test_gm.adb:24 test_gm
20243 b_test_gm.c:52 main
20244
20245 Allocation Root # 2
20246 -------------------
20247 Number of non freed allocations : 1
20248 Final Water Mark (non freed mem) : 10.02 Kilobytes
20249 High Water Mark : 10.02 Kilobytes
20250 Backtrace :
20251 s-secsta.adb:81 system.secondary_stack.ss_init
20252 s-secsta.adb:283 <system__secondary_stack___elabb>
20253 b_test_gm.c:33 adainit
20254
20255 Allocation Root # 3
20256 -------------------
20257 Number of non freed allocations : 1
20258 Final Water Mark (non freed mem) : 3.91 Kilobytes
20259 High Water Mark : 3.91 Kilobytes
20260 Backtrace :
20261 test_gm.adb:11 test_gm.my_alloc
20262 test_gm.adb:21 test_gm
20263 b_test_gm.c:52 main
20264
20265 Allocation Root # 4
20266 -------------------
20267 Number of non freed allocations : 1
20268 Final Water Mark (non freed mem) : 12 Bytes
20269 High Water Mark : 12 Bytes
20270 Backtrace :
20271 s-secsta.adb:181 system.secondary_stack.ss_init
20272 s-secsta.adb:283 <system__secondary_stack___elabb>
20273 b_test_gm.c:33 adainit
20274 @end smallexample
20275
20276 @noindent
20277 The allocation root #1 of the first example has been split in 2 roots #1
20278 and #3 thanks to the more precise associated backtrace.
20279
20280 @end ifclear
20281
20282 @node Stack Related Facilities
20283 @chapter Stack Related Facilities
20284
20285 @noindent
20286 This chapter describes some useful tools associated with stack
20287 checking and analysis. In
20288 particular, it deals with dynamic and static stack usage measurements.
20289
20290 @menu
20291 * Stack Overflow Checking::
20292 * Static Stack Usage Analysis::
20293 * Dynamic Stack Usage Analysis::
20294 @end menu
20295
20296 @node Stack Overflow Checking
20297 @section Stack Overflow Checking
20298 @cindex Stack Overflow Checking
20299 @cindex -fstack-check
20300
20301 @noindent
20302 For most operating systems, @command{gcc} does not perform stack overflow
20303 checking by default. This means that if the main environment task or
20304 some other task exceeds the available stack space, then unpredictable
20305 behavior will occur. Most native systems offer some level of protection by
20306 adding a guard page at the end of each task stack. This mechanism is usually
20307 not enough for dealing properly with stack overflow situations because
20308 a large local variable could ``jump'' above the guard page.
20309 Furthermore, when the
20310 guard page is hit, there may not be any space left on the stack for executing
20311 the exception propagation code. Enabling stack checking avoids
20312 such situations.
20313
20314 To activate stack checking, compile all units with the gcc option
20315 @option{-fstack-check}. For example:
20316
20317 @smallexample
20318 gcc -c -fstack-check package1.adb
20319 @end smallexample
20320
20321 @noindent
20322 Units compiled with this option will generate extra instructions to check
20323 that any use of the stack (for procedure calls or for declaring local
20324 variables in declare blocks) does not exceed the available stack space.
20325 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20326
20327 For declared tasks, the stack size is controlled by the size
20328 given in an applicable @code{Storage_Size} pragma or by the value specified
20329 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20330 the default size as defined in the GNAT runtime otherwise.
20331
20332 For the environment task, the stack size depends on
20333 system defaults and is unknown to the compiler. Stack checking
20334 may still work correctly if a fixed
20335 size stack is allocated, but this cannot be guaranteed.
20336 @ifclear vms
20337 To ensure that a clean exception is signalled for stack
20338 overflow, set the environment variable
20339 @env{GNAT_STACK_LIMIT} to indicate the maximum
20340 stack area that can be used, as in:
20341 @cindex GNAT_STACK_LIMIT
20342
20343 @smallexample
20344 SET GNAT_STACK_LIMIT 1600
20345 @end smallexample
20346
20347 @noindent
20348 The limit is given in kilobytes, so the above declaration would
20349 set the stack limit of the environment task to 1.6 megabytes.
20350 Note that the only purpose of this usage is to limit the amount
20351 of stack used by the environment task. If it is necessary to
20352 increase the amount of stack for the environment task, then this
20353 is an operating systems issue, and must be addressed with the
20354 appropriate operating systems commands.
20355 @end ifclear
20356 @ifset vms
20357 To have a fixed size stack in the environment task, the stack must be put
20358 in the P0 address space and its size specified. Use these switches to
20359 create a p0 image:
20360
20361 @smallexample
20362 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20363 @end smallexample
20364
20365 @noindent
20366 The quotes are required to keep case. The number after @samp{STACK=} is the
20367 size of the environmental task stack in pagelets (512 bytes). In this example
20368 the stack size is about 2 megabytes.
20369
20370 @noindent
20371 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20372 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
20373 more details about the @option{/p0image} qualifier and the @option{stack}
20374 option.
20375 @end ifset
20376
20377 @node Static Stack Usage Analysis
20378 @section Static Stack Usage Analysis
20379 @cindex Static Stack Usage Analysis
20380 @cindex -fstack-usage
20381
20382 @noindent
20383 A unit compiled with @option{-fstack-usage} will generate an extra file
20384 that specifies
20385 the maximum amount of stack used, on a per-function basis.
20386 The file has the same
20387 basename as the target object file with a @file{.su} extension.
20388 Each line of this file is made up of three fields:
20389
20390 @itemize
20391 @item
20392 The name of the function.
20393 @item
20394 A number of bytes.
20395 @item
20396 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20397 @end itemize
20398
20399 The second field corresponds to the size of the known part of the function
20400 frame.
20401
20402 The qualifier @code{static} means that the function frame size
20403 is purely static.
20404 It usually means that all local variables have a static size.
20405 In this case, the second field is a reliable measure of the function stack
20406 utilization.
20407
20408 The qualifier @code{dynamic} means that the function frame size is not static.
20409 It happens mainly when some local variables have a dynamic size. When this
20410 qualifier appears alone, the second field is not a reliable measure
20411 of the function stack analysis. When it is qualified with @code{bounded}, it
20412 means that the second field is a reliable maximum of the function stack
20413 utilization.
20414
20415 @node Dynamic Stack Usage Analysis
20416 @section Dynamic Stack Usage Analysis
20417
20418 @noindent
20419 It is possible to measure the maximum amount of stack used by a task, by
20420 adding a switch to @command{gnatbind}, as:
20421
20422 @smallexample
20423 $ gnatbind -u0 file
20424 @end smallexample
20425
20426 @noindent
20427 With this option, at each task termination, its stack usage is output on
20428 @file{stderr}.
20429 It is not always convenient to output the stack usage when the program
20430 is still running. Hence, it is possible to delay this output until program
20431 termination. for a given number of tasks specified as the argument of the
20432 @option{-u} option. For instance:
20433
20434 @smallexample
20435 $ gnatbind -u100 file
20436 @end smallexample
20437
20438 @noindent
20439 will buffer the stack usage information of the first 100 tasks to terminate and
20440 output this info at program termination. Results are displayed in four
20441 columns:
20442
20443 @noindent
20444 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20445
20446 @noindent
20447 where:
20448
20449 @table @emph
20450 @item Index
20451 is a number associated with each task.
20452
20453 @item Task Name
20454 is the name of the task analyzed.
20455
20456 @item Stack Size
20457 is the maximum size for the stack.
20458
20459 @item Stack Usage
20460 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20461 is not entirely analyzed, and it's not possible to know exactly how
20462 much has actually been used. The report thus contains the theoretical stack usage
20463 (Value) and the possible variation (Variation) around this value.
20464
20465 @end table
20466
20467 @noindent
20468 The environment task stack, e.g., the stack that contains the main unit, is
20469 only processed when the environment variable GNAT_STACK_LIMIT is set.
20470
20471
20472 @c *********************************
20473 @c * GNATCHECK *
20474 @c *********************************
20475 @node Verifying Properties Using gnatcheck
20476 @chapter Verifying Properties Using @command{gnatcheck}
20477 @findex gnatcheck
20478 @cindex @command{gnatcheck}
20479
20480 @noindent
20481 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20482 of Ada source files according to a given set of semantic rules.
20483 @cindex ASIS
20484
20485 In order to check compliance with a given rule, @command{gnatcheck} has to
20486 semantically analyze the Ada sources.
20487 Therefore, checks can only be performed on
20488 legal Ada units. Moreover, when a unit depends semantically upon units located
20489 outside the current directory, the source search path has to be provided when
20490 calling @command{gnatcheck}, either through a specified project file or
20491 through @command{gnatcheck} switches as described below.
20492
20493 A number of rules are predefined in @command{gnatcheck} and are described
20494 later in this chapter.
20495 You can also add new rules, by modifying the @command{gnatcheck} code and
20496 rebuilding the tool. In order to add a simple rule making some local checks,
20497 a small amount of straightforward ASIS-based programming is usually needed.
20498
20499 Project support for @command{gnatcheck} is provided by the GNAT
20500 driver (see @ref{The GNAT Driver and Project Files}).
20501
20502 Invoking @command{gnatcheck} on the command line has the form:
20503
20504 @smallexample
20505 $ gnatcheck @ovar{switches} @{@var{filename}@}
20506 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20507 @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20508 @end smallexample
20509
20510 @noindent
20511 where
20512 @itemize @bullet
20513 @item
20514 @var{switches} specify the general tool options
20515
20516 @item
20517 Each @var{filename} is the name (including the extension) of a source
20518 file to process. ``Wildcards'' are allowed, and
20519 the file name may contain path information.
20520
20521 @item
20522 Each @var{arg_list_filename} is the name (including the extension) of a text
20523 file containing the names of the source files to process, separated by spaces
20524 or line breaks.
20525
20526 @item
20527 @var{gcc_switches} is a list of switches for
20528 @command{gcc}. They will be passed on to all compiler invocations made by
20529 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20530 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20531 and use the @option{-gnatec} switch to set the configuration file.
20532
20533 @item
20534 @var{rule_options} is a list of options for controlling a set of
20535 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20536 @end itemize
20537
20538 @noindent
20539 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20540
20541 @menu
20542 * Format of the Report File::
20543 * General gnatcheck Switches::
20544 * gnatcheck Rule Options::
20545 * Adding the Results of Compiler Checks to gnatcheck Output::
20546 * Project-Wide Checks::
20547 * Predefined Rules::
20548 @end menu
20549
20550 @node Format of the Report File
20551 @section Format of the Report File
20552 @cindex Report file (for @code{gnatcheck})
20553
20554 @noindent
20555 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20556 rule violations.
20557 It also creates a text file that
20558 contains the complete report of the last gnatcheck run. By default this file is
20559 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20560 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20561 location of the report file. This report contains:
20562 @itemize @bullet
20563 @item a list of the Ada source files being checked,
20564 @item a list of enabled and disabled rules,
20565 @item a list of the diagnostic messages, ordered in three different ways
20566 and collected in three separate
20567 sections. Section 1 contains the raw list of diagnostic messages. It
20568 corresponds to the output going to @file{stdout}. Section 2 contains
20569 messages ordered by rules.
20570 Section 3 contains messages ordered by source files.
20571 @end itemize
20572
20573 @node General gnatcheck Switches
20574 @section General @command{gnatcheck} Switches
20575
20576 @noindent
20577 The following switches control the general @command{gnatcheck} behavior
20578
20579 @table @option
20580 @c !sort!
20581 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20582 @item ^-a^/ALL^
20583 Process all units including those with read-only ALI files such as
20584 those from GNAT Run-Time library.
20585
20586 @ifclear vms
20587 @ignore
20588 @cindex @option{-d} (@command{gnatcheck})
20589 @item -d
20590 Debug mode
20591 @end ignore
20592
20593 @cindex @option{-dd} (@command{gnatcheck})
20594 @item -dd
20595 Progress indicator mode (for use in GPS)
20596 @end ifclear
20597
20598 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20599 @item ^-h^/HELP^
20600 List the predefined and user-defined rules. For more details see
20601 @ref{Predefined Rules}.
20602
20603 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20604 @item ^-l^/LOCS^
20605 Use full source locations references in the report file. For a construct from
20606 a generic instantiation a full source location is a chain from the location
20607 of this construct in the generic unit to the place where this unit is
20608 instantiated.
20609
20610 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20611 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20612 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20613 the default value is 500. Zero means that there is no limitation on
20614 the number of diagnostic messages to be printed into Stdout.
20615
20616 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20617 @item ^-q^/QUIET^
20618 Quiet mode. All the diagnoses about rule violations are placed in the
20619 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20620
20621 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20622 @item ^-s^/SHORT^
20623 Short format of the report file (no version information, no list of applied
20624 rules, no list of checked sources is included)
20625
20626 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20627 @item ^-s1^/COMPILER_STYLE^
20628 Include the compiler-style section in the report file
20629
20630 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20631 @item ^-s2^/BY_RULES^
20632 Include the section containing diagnoses ordered by rules in the report file
20633
20634 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20635 @item ^-s3^/BY_FILES_BY_RULES^
20636 Include the section containing diagnoses ordered by files and then by rules
20637 in the report file
20638
20639 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20640 @item ^-v^/VERBOSE^
20641 Verbose mode; @command{gnatcheck} generates version information and then
20642 a trace of sources being processed.
20643
20644
20645 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20646 @item ^-o ^/OUTPUT=^@var{report_file}
20647 Set name of report file file to @var{report_file} .
20648
20649 @end table
20650
20651 @noindent
20652 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20653 @option{^-s2^/BY_RULES^} or
20654 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20655 then the @command{gnatcheck} report file will only contain sections
20656 explicitly denoted by these options.
20657
20658 @node gnatcheck Rule Options
20659 @section @command{gnatcheck} Rule Options
20660
20661 @noindent
20662 The following options control the processing performed by
20663 @command{gnatcheck}.
20664
20665 @table @option
20666 @cindex @option{+ALL} (@command{gnatcheck})
20667 @item +ALL
20668 Turn all the rule checks ON.
20669
20670 @cindex @option{-ALL} (@command{gnatcheck})
20671 @item -ALL
20672 Turn all the rule checks OFF.
20673
20674 @cindex @option{+R} (@command{gnatcheck})
20675 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20676 Turn on the check for a specified rule with the specified parameter, if any.
20677 @var{rule_id} must be the identifier of one of the currently implemented rules
20678 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20679 are not case-sensitive. The @var{param} item must
20680 be a string representing a valid parameter(s) for the specified rule.
20681 If it contains any space characters then this string must be enclosed in
20682 quotation marks.
20683
20684 @cindex @option{-R} (@command{gnatcheck})
20685 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20686 Turn off the check for a specified rule with the specified parameter, if any.
20687
20688 @cindex @option{-from} (@command{gnatcheck})
20689 @item -from=@var{rule_option_filename}
20690 Read the rule options from the text file @var{rule_option_filename}, referred as
20691 ``rule file'' below.
20692
20693 @end table
20694
20695 @noindent
20696 The default behavior is that all the rule checks are disabled.
20697
20698 A rule file is a text file containing a set of rule options.
20699 @cindex Rule file (for @code{gnatcheck})
20700 The file may contain empty lines and Ada-style comments (comment
20701 lines and end-of-line comments). The rule file has free format; that is,
20702 you do not have to start a new rule option on a new line.
20703
20704 A rule file may contain other @option{-from=@var{rule_option_filename}}
20705 options, each such option being replaced with the content of the
20706 corresponding rule file during the rule files processing. In case a
20707 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20708 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20709 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20710 the processing of rule files is interrupted and a part of their content
20711 is ignored.
20712
20713
20714 @node Adding the Results of Compiler Checks to gnatcheck Output
20715 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20716
20717 @noindent
20718 The @command{gnatcheck} tool can include in the generated diagnostic messages
20719 and in
20720 the report file the results of the checks performed by the compiler. Though
20721 disabled by default, this effect may be obtained by using @option{+R} with
20722 the following rule identifiers and parameters:
20723
20724 @table @option
20725 @item Restrictions
20726 To record restrictions violations (that are performed by the compiler if the
20727 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20728 use the rule named
20729 @code{Restrictions} with the same parameters as pragma
20730 @code{Restrictions} or @code{Restriction_Warnings}.
20731
20732 @item Style_Checks
20733 To record compiler style checks(@pxref{Style Checking}), use the rule named
20734 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20735 which enables all the standard style checks that corresponds to @option{-gnatyy}
20736 GNAT style check option, or a string that has exactly the same
20737 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20738 @code{Style_Checks} (for further information about this pragma,
20739 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20740
20741 @item Warnings
20742 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20743 named @code{Warnings} with a parameter that is a valid
20744 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20745 (for further information about this pragma, @pxref{Pragma Warnings,,,
20746 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20747 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20748 all the specific warnings, but not suppresses the warning mode,
20749 and 'e' parameter, corresponding to @option{-gnatwe} that means
20750 "treat warnings as errors", does not have any effect.
20751
20752 @end table
20753
20754 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20755 option with the corresponding restriction name as a parameter. @code{-R} is
20756 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20757 warnings and style checks, use the corresponding warning and style options.
20758
20759 @node Project-Wide Checks
20760 @section Project-Wide Checks
20761 @cindex Project-wide checks (for @command{gnatcheck})
20762
20763 @noindent
20764 In order to perform checks on all units of a given project, you can use
20765 the GNAT driver along with the @option{-P} option:
20766 @smallexample
20767 gnat check -Pproj -rules -from=my_rules
20768 @end smallexample
20769
20770 @noindent
20771 If the project @code{proj} depends upon other projects, you can perform
20772 checks on the project closure using the @option{-U} option:
20773 @smallexample
20774 gnat check -Pproj -U -rules -from=my_rules
20775 @end smallexample
20776
20777 @noindent
20778 Finally, if not all the units are relevant to a particular main
20779 program in the project closure, you can perform checks for the set
20780 of units needed to create a given main program (unit closure) using
20781 the @option{-U} option followed by the name of the main unit:
20782 @smallexample
20783 gnat check -Pproj -U main -rules -from=my_rules
20784 @end smallexample
20785
20786
20787 @node Predefined Rules
20788 @section Predefined Rules
20789 @cindex Predefined rules (for @command{gnatcheck})
20790
20791 @ignore
20792 @c (Jan 2007) Since the global rules are still under development and are not
20793 @c documented, there is no point in explaining the difference between
20794 @c global and local rules
20795 @noindent
20796 A rule in @command{gnatcheck} is either local or global.
20797 A @emph{local rule} is a rule that applies to a well-defined section
20798 of a program and that can be checked by analyzing only this section.
20799 A @emph{global rule} requires analysis of some global properties of the
20800 whole program (mostly related to the program call graph).
20801 As of @value{NOW}, the implementation of global rules should be
20802 considered to be at a preliminary stage. You can use the
20803 @option{+GLOBAL} option to enable all the global rules, and the
20804 @option{-GLOBAL} rule option to disable all the global rules.
20805
20806 All the global rules in the list below are
20807 so indicated by marking them ``GLOBAL''.
20808 This +GLOBAL and -GLOBAL options are not
20809 included in the list of gnatcheck options above, because at the moment they
20810 are considered as a temporary debug options.
20811
20812 @command{gnatcheck} performs rule checks for generic
20813 instances only for global rules. This limitation may be relaxed in a later
20814 release.
20815 @end ignore
20816
20817 @noindent
20818 The following subsections document the rules implemented in
20819 @command{gnatcheck}.
20820 The subsection title is the same as the rule identifier, which may be
20821 used as a parameter of the @option{+R} or @option{-R} options.
20822
20823
20824 @menu
20825 * Abstract_Type_Declarations::
20826 * Anonymous_Arrays::
20827 * Anonymous_Subtypes::
20828 * Blocks::
20829 * Boolean_Relational_Operators::
20830 @ignore
20831 * Ceiling_Violations::
20832 @end ignore
20833 * Controlled_Type_Declarations::
20834 * Declarations_In_Blocks::
20835 * Default_Parameters::
20836 * Discriminated_Records::
20837 * Enumeration_Ranges_In_CASE_Statements::
20838 * Exceptions_As_Control_Flow::
20839 * EXIT_Statements_With_No_Loop_Name::
20840 * Expanded_Loop_Exit_Names::
20841 * Explicit_Full_Discrete_Ranges::
20842 * Float_Equality_Checks::
20843 * Forbidden_Pragmas::
20844 * Function_Style_Procedures::
20845 * Generics_In_Subprograms::
20846 * GOTO_Statements::
20847 * Implicit_IN_Mode_Parameters::
20848 * Implicit_SMALL_For_Fixed_Point_Types::
20849 * Improperly_Located_Instantiations::
20850 * Improper_Returns::
20851 * Library_Level_Subprograms::
20852 * Local_Packages::
20853 @ignore
20854 * Improperly_Called_Protected_Entries::
20855 @end ignore
20856 * Metrics::
20857 * Misnamed_Identifiers::
20858 * Multiple_Entries_In_Protected_Definitions::
20859 * Name_Clashes::
20860 * Non_Qualified_Aggregates::
20861 * Non_Short_Circuit_Operators::
20862 * Non_SPARK_Attributes::
20863 * Non_Tagged_Derived_Types::
20864 * Non_Visible_Exceptions::
20865 * Numeric_Literals::
20866 * OTHERS_In_Aggregates::
20867 * OTHERS_In_CASE_Statements::
20868 * OTHERS_In_Exception_Handlers::
20869 * Outer_Loop_Exits::
20870 * Overloaded_Operators::
20871 * Overly_Nested_Control_Structures::
20872 * Parameters_Out_Of_Order::
20873 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20874 * Positional_Actuals_For_Defaulted_Parameters::
20875 * Positional_Components::
20876 * Positional_Generic_Parameters::
20877 * Positional_Parameters::
20878 * Predefined_Numeric_Types::
20879 * Raising_External_Exceptions::
20880 * Raising_Predefined_Exceptions::
20881 * Separate_Numeric_Error_Handlers::
20882 @ignore
20883 * Recursion::
20884 * Side_Effect_Functions::
20885 @end ignore
20886 * Slices::
20887 * Unassigned_OUT_Parameters::
20888 * Uncommented_BEGIN_In_Package_Bodies::
20889 * Unconstrained_Array_Returns::
20890 * Universal_Ranges::
20891 * Unnamed_Blocks_And_Loops::
20892 @ignore
20893 * Unused_Subprograms::
20894 @end ignore
20895 * USE_PACKAGE_Clauses::
20896 * Volatile_Objects_Without_Address_Clauses::
20897 @end menu
20898
20899
20900 @node Abstract_Type_Declarations
20901 @subsection @code{Abstract_Type_Declarations}
20902 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20903
20904 @noindent
20905 Flag all declarations of abstract types. For an abstract private
20906 type, both the private and full type declarations are flagged.
20907
20908 This rule has no parameters.
20909
20910
20911 @node Anonymous_Arrays
20912 @subsection @code{Anonymous_Arrays}
20913 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20914
20915 @noindent
20916 Flag all anonymous array type definitions (by Ada semantics these can only
20917 occur in object declarations).
20918
20919 This rule has no parameters.
20920
20921 @node Anonymous_Subtypes
20922 @subsection @code{Anonymous_Subtypes}
20923 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20924
20925 @noindent
20926 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20927 any instance of a subtype indication with a constraint, other than one
20928 that occurs immediately within a subtype declaration. Any use of a range
20929 other than as a constraint used immediately within a subtype declaration
20930 is considered as an anonymous subtype.
20931
20932 An effect of this rule is that @code{for} loops such as the following are
20933 flagged (since @code{1..N} is formally a ``range''):
20934
20935 @smallexample @c ada
20936 for I in 1 .. N loop
20937 @dots{}
20938 end loop;
20939 @end smallexample
20940
20941 @noindent
20942 Declaring an explicit subtype solves the problem:
20943
20944 @smallexample @c ada
20945 subtype S is Integer range 1..N;
20946 @dots{}
20947 for I in S loop
20948 @dots{}
20949 end loop;
20950 @end smallexample
20951
20952 @noindent
20953 This rule has no parameters.
20954
20955 @node Blocks
20956 @subsection @code{Blocks}
20957 @cindex @code{Blocks} rule (for @command{gnatcheck})
20958
20959 @noindent
20960 Flag each block statement.
20961
20962 This rule has no parameters.
20963
20964 @node Boolean_Relational_Operators
20965 @subsection @code{Boolean_Relational_Operators}
20966 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20967
20968 @noindent
20969 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20970 ``>='', ``='' and ``/='') for the predefined Boolean type.
20971 (This rule is useful in enforcing the SPARK language restrictions.)
20972
20973 Calls to predefined relational operators of any type derived from
20974 @code{Standard.Boolean} are not detected. Calls to user-defined functions
20975 with these designators, and uses of operators that are renamings
20976 of the predefined relational operators for @code{Standard.Boolean},
20977 are likewise not detected.
20978
20979 This rule has no parameters.
20980
20981 @ignore
20982 @node Ceiling_Violations
20983 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20984 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20985
20986 @noindent
20987 Flag invocations of a protected operation by a task whose priority exceeds
20988 the protected object's ceiling.
20989
20990 As of @value{NOW}, this rule has the following limitations:
20991
20992 @itemize @bullet
20993
20994 @item
20995 We consider only pragmas Priority and Interrupt_Priority as means to define
20996 a task/protected operation priority. We do not consider the effect of using
20997 Ada.Dynamic_Priorities.Set_Priority procedure;
20998
20999 @item
21000 We consider only base task priorities, and no priority inheritance. That is,
21001 we do not make a difference between calls issued during task activation and
21002 execution of the sequence of statements from task body;
21003
21004 @item
21005 Any situation when the priority of protected operation caller is set by a
21006 dynamic expression (that is, the corresponding Priority or
21007 Interrupt_Priority pragma has a non-static expression as an argument) we
21008 treat as a priority inconsistency (and, therefore, detect this situation).
21009 @end itemize
21010
21011 @noindent
21012 At the moment the notion of the main subprogram is not implemented in
21013 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21014 if this subprogram can be a main subprogram of a partition) changes the
21015 priority of an environment task. So if we have more then one such pragma in
21016 the set of processed sources, the pragma that is processed last, defines the
21017 priority of an environment task.
21018
21019 This rule has no parameters.
21020 @end ignore
21021
21022 @node Controlled_Type_Declarations
21023 @subsection @code{Controlled_Type_Declarations}
21024 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21025
21026 @noindent
21027 Flag all declarations of controlled types. A declaration of a private type
21028 is flagged if its full declaration declares a controlled type. A declaration
21029 of a derived type is flagged if its ancestor type is controlled. Subtype
21030 declarations are not checked. A declaration of a type that itself is not a
21031 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21032 component is not checked.
21033
21034 This rule has no parameters.
21035
21036
21037
21038 @node Declarations_In_Blocks
21039 @subsection @code{Declarations_In_Blocks}
21040 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21041
21042 @noindent
21043 Flag all block statements containing local declarations. A @code{declare}
21044 block with an empty @i{declarative_part} or with a @i{declarative part}
21045 containing only pragmas and/or @code{use} clauses is not flagged.
21046
21047 This rule has no parameters.
21048
21049
21050 @node Default_Parameters
21051 @subsection @code{Default_Parameters}
21052 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21053
21054 @noindent
21055 Flag all default expressions for subprogram parameters. Parameter
21056 declarations of formal and generic subprograms are also checked.
21057
21058 This rule has no parameters.
21059
21060
21061 @node Discriminated_Records
21062 @subsection @code{Discriminated_Records}
21063 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21064
21065 @noindent
21066 Flag all declarations of record types with discriminants. Only the
21067 declarations of record and record extension types are checked. Incomplete,
21068 formal, private, derived and private extension type declarations are not
21069 checked. Task and protected type declarations also are not checked.
21070
21071 This rule has no parameters.
21072
21073
21074 @node Enumeration_Ranges_In_CASE_Statements
21075 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21076 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21077
21078 @noindent
21079 Flag each use of a range of enumeration literals as a choice in a
21080 @code{case} statement.
21081 All forms for specifying a range (explicit ranges
21082 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21083 An enumeration range is
21084 flagged even if contains exactly one enumeration value or no values at all. A
21085 type derived from an enumeration type is considered as an enumeration type.
21086
21087 This rule helps prevent maintenance problems arising from adding an
21088 enumeration value to a type and having it implicitly handled by an existing
21089 @code{case} statement with an enumeration range that includes the new literal.
21090
21091 This rule has no parameters.
21092
21093
21094 @node Exceptions_As_Control_Flow
21095 @subsection @code{Exceptions_As_Control_Flow}
21096 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21097
21098 @noindent
21099 Flag each place where an exception is explicitly raised and handled in the
21100 same subprogram body. A @code{raise} statement in an exception handler,
21101 package body, task body or entry body is not flagged.
21102
21103 The rule has no parameters.
21104
21105 @node EXIT_Statements_With_No_Loop_Name
21106 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21107 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21108
21109 @noindent
21110 Flag each @code{exit} statement that does not specify the name of the loop
21111 being exited.
21112
21113 The rule has no parameters.
21114
21115
21116 @node Expanded_Loop_Exit_Names
21117 @subsection @code{Expanded_Loop_Exit_Names}
21118 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21119
21120 @noindent
21121 Flag all expanded loop names in @code{exit} statements.
21122
21123 This rule has no parameters.
21124
21125 @node Explicit_Full_Discrete_Ranges
21126 @subsection @code{Explicit_Full_Discrete_Ranges}
21127 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21128
21129 @noindent
21130 Flag each discrete range that has the form @code{A'First .. A'Last}.
21131
21132 This rule has no parameters.
21133
21134 @node Float_Equality_Checks
21135 @subsection @code{Float_Equality_Checks}
21136 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21137
21138 @noindent
21139 Flag all calls to the predefined equality operations for floating-point types.
21140 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21141 User-defined equality operations are not flagged, nor are ``@code{=}''
21142 and ``@code{/=}'' operations for fixed-point types.
21143
21144 This rule has no parameters.
21145
21146
21147 @node Forbidden_Pragmas
21148 @subsection @code{Forbidden_Pragmas}
21149 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21150
21151 @noindent
21152 Flag each use of the specified pragmas. The pragmas to be detected
21153 are named in the rule's parameters.
21154
21155 This rule has the following parameters:
21156
21157 @itemize @bullet
21158 @item For the @option{+R} option
21159
21160 @table @asis
21161 @item @emph{Pragma_Name}
21162 Adds the specified pragma to the set of pragmas to be
21163 checked and sets the checks for all the specified pragmas
21164 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21165 does not correspond to any pragma name defined in the Ada
21166 standard or to the name of a GNAT-specific pragma defined
21167 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21168 Manual}, it is treated as the name of unknown pragma.
21169
21170 @item @code{GNAT}
21171 All the GNAT-specific pragmas are detected; this sets
21172 the checks for all the specified pragmas ON.
21173
21174 @item @code{ALL}
21175 All pragmas are detected; this sets the rule ON.
21176 @end table
21177
21178 @item For the @option{-R} option
21179 @table @asis
21180 @item @emph{Pragma_Name}
21181 Removes the specified pragma from the set of pragmas to be
21182 checked without affecting checks for
21183 other pragmas. @emph{Pragma_Name} is treated as a name
21184 of a pragma. If it does not correspond to any pragma
21185 defined in the Ada standard or to any name defined in
21186 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21187 this option is treated as turning OFF detection of all unknown pragmas.
21188
21189 @item GNAT
21190 Turn OFF detection of all GNAT-specific pragmas
21191
21192 @item ALL
21193 Clear the list of the pragmas to be detected and
21194 turn the rule OFF.
21195 @end table
21196 @end itemize
21197
21198 @noindent
21199 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21200 the syntax of an Ada identifier and therefore can not be considered
21201 as a pragma name, a diagnostic message is generated and the corresponding
21202 parameter is ignored.
21203
21204 When more then one parameter is given in the same rule option, the parameters
21205 must be separated by a comma.
21206
21207 If more then one option for this rule is specified for the @command{gnatcheck}
21208 call, a new option overrides the previous one(s).
21209
21210 The @option{+R} option with no parameters turns the rule ON with the set of
21211 pragmas to be detected defined by the previous rule options.
21212 (By default this set is empty, so if the only option specified for the rule is
21213 @option{+RForbidden_Pragmas} (with
21214 no parameter), then the rule is enabled, but it does not detect anything).
21215 The @option{-R} option with no parameter turns the rule OFF, but it does not
21216 affect the set of pragmas to be detected.
21217
21218
21219
21220
21221 @node Function_Style_Procedures
21222 @subsection @code{Function_Style_Procedures}
21223 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21224
21225 @noindent
21226 Flag each procedure that can be rewritten as a function. A procedure can be
21227 converted into a function if it has exactly one parameter of mode @code{out}
21228 and no parameters of mode @code{in out}. Procedure declarations,
21229 formal procedure declarations, and generic procedure declarations are always
21230 checked. Procedure
21231 bodies and body stubs are flagged only if they do not have corresponding
21232 separate declarations. Procedure renamings and procedure instantiations are
21233 not flagged.
21234
21235 If a procedure can be rewritten as a function, but its @code{out} parameter is
21236 of a limited type, it is not flagged.
21237
21238 Protected procedures are not flagged. Null procedures also are not flagged.
21239
21240 This rule has no parameters.
21241
21242
21243 @node Generics_In_Subprograms
21244 @subsection @code{Generics_In_Subprograms}
21245 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21246
21247 @noindent
21248 Flag each declaration of a generic unit in a subprogram. Generic
21249 declarations in the bodies of generic subprograms are also flagged.
21250 A generic unit nested in another generic unit is not flagged.
21251 If a generic unit is
21252 declared in a local package that is declared in a subprogram body, the
21253 generic unit is flagged.
21254
21255 This rule has no parameters.
21256
21257
21258 @node GOTO_Statements
21259 @subsection @code{GOTO_Statements}
21260 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21261
21262 @noindent
21263 Flag each occurrence of a @code{goto} statement.
21264
21265 This rule has no parameters.
21266
21267
21268 @node Implicit_IN_Mode_Parameters
21269 @subsection @code{Implicit_IN_Mode_Parameters}
21270 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21271
21272 @noindent
21273 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21274 Note that @code{access} parameters, although they technically behave
21275 like @code{in} parameters, are not flagged.
21276
21277 This rule has no parameters.
21278
21279
21280 @node Implicit_SMALL_For_Fixed_Point_Types
21281 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21282 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21283
21284 @noindent
21285 Flag each fixed point type declaration that lacks an explicit
21286 representation clause to define its @code{'Small} value.
21287 Since @code{'Small} can be defined only for ordinary fixed point types,
21288 decimal fixed point type declarations are not checked.
21289
21290 This rule has no parameters.
21291
21292
21293 @node Improperly_Located_Instantiations
21294 @subsection @code{Improperly_Located_Instantiations}
21295 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21296
21297 @noindent
21298 Flag all generic instantiations in library-level package specs
21299 (including library generic packages) and in all subprogram bodies.
21300
21301 Instantiations in task and entry bodies are not flagged. Instantiations in the
21302 bodies of protected subprograms are flagged.
21303
21304 This rule has no parameters.
21305
21306
21307
21308 @node Improper_Returns
21309 @subsection @code{Improper_Returns}
21310 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21311
21312 @noindent
21313 Flag each explicit @code{return} statement in procedures, and
21314 multiple @code{return} statements in functions.
21315 Diagnostic messages are generated for all @code{return} statements
21316 in a procedure (thus each procedure must be written so that it
21317 returns implicitly at the end of its statement part),
21318 and for all @code{return} statements in a function after the first one.
21319 This rule supports the stylistic convention that each subprogram
21320 should have no more than one point of normal return.
21321
21322 This rule has no parameters.
21323
21324
21325 @node Library_Level_Subprograms
21326 @subsection @code{Library_Level_Subprograms}
21327 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21328
21329 @noindent
21330 Flag all library-level subprograms (including generic subprogram instantiations).
21331
21332 This rule has no parameters.
21333
21334
21335 @node Local_Packages
21336 @subsection @code{Local_Packages}
21337 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21338
21339 @noindent
21340 Flag all local packages declared in package and generic package
21341 specs.
21342 Local packages in bodies are not flagged.
21343
21344 This rule has no parameters.
21345
21346 @ignore
21347 @node Improperly_Called_Protected_Entries
21348 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21349 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21350
21351 @noindent
21352 Flag each protected entry that can be called from more than one task.
21353
21354 This rule has no parameters.
21355 @end ignore
21356
21357 @node Metrics
21358 @subsection @code{Metrics}
21359 @cindex @code{Metrics} rule (for @command{gnatcheck})
21360
21361 @noindent
21362 There is a set of checks based on computing a metric value and comparing the
21363 result with the specified upper (or lower, depending on a specific metric)
21364 value specified for a given metric. A construct is flagged if a given metric
21365 is applicable (can be computed) for it and the computed value is greater
21366 then (lover then) the specified upper (lower) bound.
21367
21368 The name of any metric-based rule consists of the prefix @code{Metrics_}
21369 followed by the name of the corresponding metric (see the table below).
21370 For @option{+R} option, each metric-based rule has a numeric parameter
21371 specifying the bound (integer or real, depending on a metric), @option{-R}
21372 option for metric rules does not have a parameter.
21373
21374 The following table shows the metric names for that the corresponding
21375 metrics-based checks are supported by gnatcheck, including the
21376 constraint that must be satisfied by the bound that is specified for the check
21377 and what bound - upper (U) or lower (L) - should be specified.
21378
21379 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21380 @ifnothtml
21381 @headitem Check Name @tab Description @tab Bounds Value
21382 @end ifnothtml
21383 @ifhtml
21384 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21385 @end ifhtml
21386 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21387 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21388 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21389 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21390 @end multitable
21391
21392 @noindent
21393 The meaning and the computed values for all these metrics are exactly
21394 the same as for the corresponding metrics in @command{gnatmetric}.
21395
21396 @emph{Example:} the rule
21397 @smallexample
21398 +RMetrics_Cyclomatic_Complexity : 7
21399 @end smallexample
21400 @noindent
21401 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21402
21403 To turn OFF the check for cyclomatic complexity metric, use the following option:
21404 @smallexample
21405 -RMetrics_Cyclomatic_Complexity
21406 @end smallexample
21407
21408 @node Misnamed_Identifiers
21409 @subsection @code{Misnamed_Identifiers}
21410 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21411
21412 @noindent
21413 Flag the declaration of each identifier that does not have a suffix
21414 corresponding to the kind of entity being declared.
21415 The following declarations are checked:
21416
21417 @itemize @bullet
21418 @item
21419 type declarations
21420
21421 @item
21422 constant declarations (but not number declarations)
21423
21424 @item
21425 package renaming declarations (but not generic package renaming
21426 declarations)
21427 @end itemize
21428
21429 @noindent
21430 This rule may have parameters. When used without parameters, the rule enforces
21431 the following checks:
21432
21433 @itemize @bullet
21434 @item
21435 type-defining names end with @code{_T}, unless the type is an access type,
21436 in which case the suffix must be @code{_A}
21437 @item
21438 constant names end with @code{_C}
21439 @item
21440 names defining package renamings end with @code{_R}
21441 @end itemize
21442
21443 @noindent
21444 For a private or incomplete type declaration the following checks are
21445 made for the defining name suffix:
21446
21447 @itemize @bullet
21448 @item
21449 For an incomplete type declaration: if the corresponding full type
21450 declaration is available, the defining identifier from the full type
21451 declaration is checked, but the defining identifier from the incomplete type
21452 declaration is not; otherwise the defining identifier from the incomplete
21453 type declaration is checked against the suffix specified for type
21454 declarations.
21455
21456 @item
21457 For a private type declaration (including private extensions), the defining
21458 identifier from the private type declaration is checked against the type
21459 suffix (even if the corresponding full declaration is an access type
21460 declaration), and the defining identifier from the corresponding full type
21461 declaration is not checked.
21462 @end itemize
21463
21464 @noindent
21465 For a deferred constant, the defining name in the corresponding full constant
21466 declaration is not checked.
21467
21468 Defining names of formal types are not checked.
21469
21470 The rule may have the following parameters:
21471
21472 @itemize @bullet
21473 @item
21474 For the @option{+R} option:
21475 @table @code
21476 @item Default
21477 Sets the default listed above for all the names to be checked.
21478
21479 @item Type_Suffix=@emph{string}
21480 Specifies the suffix for a type name.
21481
21482 @item Access_Suffix=@emph{string}
21483 Specifies the suffix for an access type name. If
21484 this parameter is set, it overrides for access
21485 types the suffix set by the @code{Type_Suffix} parameter.
21486
21487 @item Constant_Suffix=@emph{string}
21488 Specifies the suffix for a constant name.
21489
21490 @item Renaming_Suffix=@emph{string}
21491 Specifies the suffix for a package renaming name.
21492 @end table
21493
21494 @item
21495 For the @option{-R} option:
21496 @table @code
21497 @item All_Suffixes
21498 Remove all the suffixes specified for the
21499 identifier suffix checks, whether by default or
21500 as specified by other rule parameters. All the
21501 checks for this rule are disabled as a result.
21502
21503 @item Type_Suffix
21504 Removes the suffix specified for types. This
21505 disables checks for types but does not disable
21506 any other checks for this rule (including the
21507 check for access type names if @code{Access_Suffix} is
21508 set).
21509
21510 @item Access_Suffix
21511 Removes the suffix specified for access types.
21512 This disables checks for access type names but
21513 does not disable any other checks for this rule.
21514 If @code{Type_Suffix} is set, access type names are
21515 checked as ordinary type names.
21516
21517 @item Constant_Suffix
21518 Removes the suffix specified for constants. This
21519 disables checks for constant names but does not
21520 disable any other checks for this rule.
21521
21522 @item Renaming_Suffix
21523 Removes the suffix specified for package
21524 renamings. This disables checks for package
21525 renamings but does not disable any other checks
21526 for this rule.
21527 @end table
21528 @end itemize
21529
21530 @noindent
21531 If more than one parameter is used, parameters must be separated by commas.
21532
21533 If more than one option is specified for the @command{gnatcheck} invocation,
21534 a new option overrides the previous one(s).
21535
21536 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21537 checks for all the
21538 name suffixes specified by previous options used for this rule.
21539
21540 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21541 all the checks but keeps
21542 all the suffixes specified by previous options used for this rule.
21543
21544 The @emph{string} value must be a valid suffix for an Ada identifier (after
21545 trimming all the leading and trailing space characters, if any).
21546 Parameters are not case sensitive, except the @emph{string} part.
21547
21548 If any error is detected in a rule parameter, the parameter is ignored.
21549 In such a case the options that are set for the rule are not
21550 specified.
21551
21552
21553
21554 @node Multiple_Entries_In_Protected_Definitions
21555 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21556 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21557
21558 @noindent
21559 Flag each protected definition (i.e., each protected object/type declaration)
21560 that defines more than one entry.
21561 Diagnostic messages are generated for all the entry declarations
21562 except the first one. An entry family is counted as one entry. Entries from
21563 the private part of the protected definition are also checked.
21564
21565 This rule has no parameters.
21566
21567 @node Name_Clashes
21568 @subsection @code{Name_Clashes}
21569 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21570
21571 @noindent
21572 Check that certain names are not used as defining identifiers. To activate
21573 this rule, you need to supply a reference to the dictionary file(s) as a rule
21574 parameter(s) (more then one dictionary file can be specified). If no
21575 dictionary file is set, this rule will not cause anything to be flagged.
21576 Only defining occurrences, not references, are checked.
21577 The check is not case-sensitive.
21578
21579 This rule is enabled by default, but without setting any corresponding
21580 dictionary file(s); thus the default effect is to do no checks.
21581
21582 A dictionary file is a plain text file. The maximum line length for this file
21583 is 1024 characters. If the line is longer then this limit, extra characters
21584 are ignored.
21585
21586 Each line can be either an empty line, a comment line, or a line containing
21587 a list of identifiers separated by space or HT characters.
21588 A comment is an Ada-style comment (from @code{--} to end-of-line).
21589 Identifiers must follow the Ada syntax for identifiers.
21590 A line containing one or more identifiers may end with a comment.
21591
21592 @node Non_Qualified_Aggregates
21593 @subsection @code{Non_Qualified_Aggregates}
21594 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21595
21596 @noindent
21597 Flag each non-qualified aggregate.
21598 A non-qualified aggregate is an
21599 aggregate that is not the expression of a qualified expression. A
21600 string literal is not considered an aggregate, but an array
21601 aggregate of a string type is considered as a normal aggregate.
21602 Aggregates of anonymous array types are not flagged.
21603
21604 This rule has no parameters.
21605
21606
21607 @node Non_Short_Circuit_Operators
21608 @subsection @code{Non_Short_Circuit_Operators}
21609 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21610
21611 @noindent
21612 Flag all calls to predefined @code{and} and @code{or} operators for
21613 any boolean type. Calls to
21614 user-defined @code{and} and @code{or} and to operators defined by renaming
21615 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21616 operators for modular types or boolean array types are not flagged.
21617
21618 This rule has no parameters.
21619
21620
21621
21622 @node Non_SPARK_Attributes
21623 @subsection @code{Non_SPARK_Attributes}
21624 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21625
21626 @noindent
21627 The SPARK language defines the following subset of Ada 95 attribute
21628 designators as those that can be used in SPARK programs. The use of
21629 any other attribute is flagged.
21630
21631 @itemize @bullet
21632 @item @code{'Adjacent}
21633 @item @code{'Aft}
21634 @item @code{'Base}
21635 @item @code{'Ceiling}
21636 @item @code{'Component_Size}
21637 @item @code{'Compose}
21638 @item @code{'Copy_Sign}
21639 @item @code{'Delta}
21640 @item @code{'Denorm}
21641 @item @code{'Digits}
21642 @item @code{'Exponent}
21643 @item @code{'First}
21644 @item @code{'Floor}
21645 @item @code{'Fore}
21646 @item @code{'Fraction}
21647 @item @code{'Last}
21648 @item @code{'Leading_Part}
21649 @item @code{'Length}
21650 @item @code{'Machine}
21651 @item @code{'Machine_Emax}
21652 @item @code{'Machine_Emin}
21653 @item @code{'Machine_Mantissa}
21654 @item @code{'Machine_Overflows}
21655 @item @code{'Machine_Radix}
21656 @item @code{'Machine_Rounds}
21657 @item @code{'Max}
21658 @item @code{'Min}
21659 @item @code{'Model}
21660 @item @code{'Model_Emin}
21661 @item @code{'Model_Epsilon}
21662 @item @code{'Model_Mantissa}
21663 @item @code{'Model_Small}
21664 @item @code{'Modulus}
21665 @item @code{'Pos}
21666 @item @code{'Pred}
21667 @item @code{'Range}
21668 @item @code{'Remainder}
21669 @item @code{'Rounding}
21670 @item @code{'Safe_First}
21671 @item @code{'Safe_Last}
21672 @item @code{'Scaling}
21673 @item @code{'Signed_Zeros}
21674 @item @code{'Size}
21675 @item @code{'Small}
21676 @item @code{'Succ}
21677 @item @code{'Truncation}
21678 @item @code{'Unbiased_Rounding}
21679 @item @code{'Val}
21680 @item @code{'Valid}
21681 @end itemize
21682
21683 @noindent
21684 This rule has no parameters.
21685
21686
21687 @node Non_Tagged_Derived_Types
21688 @subsection @code{Non_Tagged_Derived_Types}
21689 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21690
21691 @noindent
21692 Flag all derived type declarations that do not have a record extension part.
21693
21694 This rule has no parameters.
21695
21696
21697
21698 @node Non_Visible_Exceptions
21699 @subsection @code{Non_Visible_Exceptions}
21700 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21701
21702 @noindent
21703 Flag constructs leading to the possibility of propagating an exception
21704 out of the scope in which the exception is declared.
21705 Two cases are detected:
21706
21707 @itemize @bullet
21708 @item
21709 An exception declaration in a subprogram body, task body or block
21710 statement is flagged if the body or statement does not contain a handler for
21711 that exception or a handler with an @code{others} choice.
21712
21713 @item
21714 A @code{raise} statement in an exception handler of a subprogram body,
21715 task body or block statement is flagged if it (re)raises a locally
21716 declared exception. This may occur under the following circumstances:
21717 @itemize @minus
21718 @item
21719 it explicitly raises a locally declared exception, or
21720 @item
21721 it does not specify an exception name (i.e., it is simply @code{raise;})
21722 and the enclosing handler contains a locally declared exception in its
21723 exception choices.
21724 @end itemize
21725 @end itemize
21726
21727 @noindent
21728 Renamings of local exceptions are not flagged.
21729
21730 This rule has no parameters.
21731
21732
21733 @node Numeric_Literals
21734 @subsection @code{Numeric_Literals}
21735 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21736
21737 @noindent
21738 Flag each use of a numeric literal in an index expression, and in any
21739 circumstance except for the following:
21740
21741 @itemize @bullet
21742 @item
21743 a literal occurring in the initialization expression for a constant
21744 declaration or a named number declaration, or
21745
21746 @item
21747 an integer literal that is less than or equal to a value
21748 specified by the @option{N} rule parameter.
21749 @end itemize
21750
21751 @noindent
21752 This rule may have the following parameters for the @option{+R} option:
21753
21754 @table @asis
21755 @item @emph{N}
21756 @emph{N} is an integer literal used as the maximal value that is not flagged
21757 (i.e., integer literals not exceeding this value are allowed)
21758
21759 @item @code{ALL}
21760 All integer literals are flagged
21761 @end table
21762
21763 @noindent
21764 If no parameters are set, the maximum unflagged value is 1.
21765
21766 The last specified check limit (or the fact that there is no limit at
21767 all) is used when multiple @option{+R} options appear.
21768
21769 The @option{-R} option for this rule has no parameters.
21770 It disables the rule but retains the last specified maximum unflagged value.
21771 If the @option{+R} option subsequently appears, this value is used as the
21772 threshold for the check.
21773
21774
21775 @node OTHERS_In_Aggregates
21776 @subsection @code{OTHERS_In_Aggregates}
21777 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21778
21779 @noindent
21780 Flag each use of an @code{others} choice in extension aggregates.
21781 In record and array aggregates, an @code{others} choice is flagged unless
21782 it is used to refer to all components, or to all but one component.
21783
21784 If, in case of a named array aggregate, there are two associations, one
21785 with an @code{others} choice and another with a discrete range, the
21786 @code{others} choice is flagged even if the discrete range specifies
21787 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21788
21789 This rule has no parameters.
21790
21791 @node OTHERS_In_CASE_Statements
21792 @subsection @code{OTHERS_In_CASE_Statements}
21793 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21794
21795 @noindent
21796 Flag any use of an @code{others} choice in a @code{case} statement.
21797
21798 This rule has no parameters.
21799
21800 @node OTHERS_In_Exception_Handlers
21801 @subsection @code{OTHERS_In_Exception_Handlers}
21802 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21803
21804 @noindent
21805 Flag any use of an @code{others} choice in an exception handler.
21806
21807 This rule has no parameters.
21808
21809
21810 @node Outer_Loop_Exits
21811 @subsection @code{Outer_Loop_Exits}
21812 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21813
21814 @noindent
21815 Flag each @code{exit} statement containing a loop name that is not the name
21816 of the immediately enclosing @code{loop} statement.
21817
21818 This rule has no parameters.
21819
21820
21821 @node Overloaded_Operators
21822 @subsection @code{Overloaded_Operators}
21823 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21824
21825 @noindent
21826 Flag each function declaration that overloads an operator symbol.
21827 A function body is checked only if the body does not have a
21828 separate spec. Formal functions are also checked. For a
21829 renaming declaration, only renaming-as-declaration is checked
21830
21831 This rule has no parameters.
21832
21833
21834 @node Overly_Nested_Control_Structures
21835 @subsection @code{Overly_Nested_Control_Structures}
21836 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21837
21838 @noindent
21839 Flag each control structure whose nesting level exceeds the value provided
21840 in the rule parameter.
21841
21842 The control structures checked are the following:
21843
21844 @itemize @bullet
21845 @item @code{if} statement
21846 @item @code{case} statement
21847 @item @code{loop} statement
21848 @item Selective accept statement
21849 @item Timed entry call statement
21850 @item Conditional entry call
21851 @item Asynchronous select statement
21852 @end itemize
21853
21854 @noindent
21855 The rule has the following parameter for the @option{+R} option:
21856
21857 @table @emph
21858 @item N
21859 Positive integer specifying the maximal control structure nesting
21860 level that is not flagged
21861 @end table
21862
21863 @noindent
21864 If the parameter for the @option{+R} option is not specified or
21865 if it is not a positive integer, @option{+R} option is ignored.
21866
21867 If more then one option is specified for the gnatcheck call, the later option and
21868 new parameter override the previous one(s).
21869
21870
21871 @node Parameters_Out_Of_Order
21872 @subsection @code{Parameters_Out_Of_Order}
21873 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21874
21875 @noindent
21876 Flag each subprogram and entry declaration whose formal parameters are not
21877 ordered according to the following scheme:
21878
21879 @itemize @bullet
21880
21881 @item @code{in} and @code{access} parameters first,
21882 then @code{in out} parameters,
21883 and then @code{out} parameters;
21884
21885 @item for @code{in} mode, parameters with default initialization expressions
21886 occur last
21887 @end itemize
21888
21889 @noindent
21890 Only the first violation of the described order is flagged.
21891
21892 The following constructs are checked:
21893
21894 @itemize @bullet
21895 @item subprogram declarations (including null procedures);
21896 @item generic subprogram declarations;
21897 @item formal subprogram declarations;
21898 @item entry declarations;
21899 @item subprogram bodies and subprogram body stubs that do not
21900 have separate specifications
21901 @end itemize
21902
21903 @noindent
21904 Subprogram renamings are not checked.
21905
21906 This rule has no parameters.
21907
21908
21909 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21910 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21911 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21912
21913 @noindent
21914 Flag each generic actual parameter corresponding to a generic formal
21915 parameter with a default initialization, if positional notation is used.
21916
21917 This rule has no parameters.
21918
21919 @node Positional_Actuals_For_Defaulted_Parameters
21920 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21921 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21922
21923 @noindent
21924 Flag each actual parameter to a subprogram or entry call where the
21925 corresponding formal parameter has a default expression, if positional
21926 notation is used.
21927
21928 This rule has no parameters.
21929
21930 @node Positional_Components
21931 @subsection @code{Positional_Components}
21932 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21933
21934 @noindent
21935 Flag each array, record and extension aggregate that includes positional
21936 notation.
21937
21938 This rule has no parameters.
21939
21940
21941 @node Positional_Generic_Parameters
21942 @subsection @code{Positional_Generic_Parameters}
21943 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21944
21945 @noindent
21946 Flag each instantiation using positional parameter notation.
21947
21948 This rule has no parameters.
21949
21950
21951 @node Positional_Parameters
21952 @subsection @code{Positional_Parameters}
21953 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21954
21955 @noindent
21956 Flag each subprogram or entry call using positional parameter notation,
21957 except for the following:
21958
21959 @itemize @bullet
21960 @item
21961 Invocations of prefix or infix operators are not flagged
21962 @item
21963 If the called subprogram or entry has only one formal parameter,
21964 the call is not flagged;
21965 @item
21966 If a subprogram call uses the @emph{Object.Operation} notation, then
21967 @itemize @minus
21968 @item
21969 the first parameter (that is, @emph{Object}) is not flagged;
21970 @item
21971 if the called subprogram has only two parameters, the second parameter
21972 of the call is not flagged;
21973 @end itemize
21974 @end itemize
21975
21976 @noindent
21977 This rule has no parameters.
21978
21979
21980
21981
21982 @node Predefined_Numeric_Types
21983 @subsection @code{Predefined_Numeric_Types}
21984 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21985
21986 @noindent
21987 Flag each explicit use of the name of any numeric type or subtype defined
21988 in package @code{Standard}.
21989
21990 The rationale for this rule is to detect when the
21991 program may depend on platform-specific characteristics of the implementation
21992 of the predefined numeric types. Note that this rule is over-pessimistic;
21993 for example, a program that uses @code{String} indexing
21994 likely needs a variable of type @code{Integer}.
21995 Another example is the flagging of predefined numeric types with explicit
21996 constraints:
21997
21998 @smallexample @c ada
21999 subtype My_Integer is Integer range Left .. Right;
22000 Vy_Var : My_Integer;
22001 @end smallexample
22002
22003 @noindent
22004 This rule detects only numeric types and subtypes defined in
22005 @code{Standard}. The use of numeric types and subtypes defined in other
22006 predefined packages (such as @code{System.Any_Priority} or
22007 @code{Ada.Text_IO.Count}) is not flagged
22008
22009 This rule has no parameters.
22010
22011
22012
22013 @node Raising_External_Exceptions
22014 @subsection @code{Raising_External_Exceptions}
22015 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22016
22017 @noindent
22018 Flag any @code{raise} statement, in a program unit declared in a library
22019 package or in a generic library package, for an exception that is
22020 neither a predefined exception nor an exception that is also declared (or
22021 renamed) in the visible part of the package.
22022
22023 This rule has no parameters.
22024
22025
22026
22027 @node Raising_Predefined_Exceptions
22028 @subsection @code{Raising_Predefined_Exceptions}
22029 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22030
22031 @noindent
22032 Flag each @code{raise} statement that raises a predefined exception
22033 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22034 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22035
22036 This rule has no parameters.
22037
22038 @node Separate_Numeric_Error_Handlers
22039 @subsection @code{Separate_Numeric_Error_Handlers}
22040 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22041
22042 @noindent
22043 Flags each exception handler that contains a choice for
22044 the predefined @code{Constraint_Error} exception, but does not contain
22045 the choice for the predefined @code{Numeric_Error} exception, or
22046 that contains the choice for @code{Numeric_Error}, but does not contain the
22047 choice for @code{Constraint_Error}.
22048
22049 This rule has no parameters.
22050
22051 @ignore
22052 @node Recursion
22053 @subsection @code{Recursion} (under construction, GLOBAL)
22054 @cindex @code{Recursion} rule (for @command{gnatcheck})
22055
22056 @noindent
22057 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22058 calls, of recursive subprograms are detected.
22059
22060 This rule has no parameters.
22061 @end ignore
22062
22063 @ignore
22064 @node Side_Effect_Functions
22065 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22066 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22067
22068 @noindent
22069 Flag functions with side effects.
22070
22071 We define a side effect as changing any data object that is not local for the
22072 body of this function.
22073
22074 At the moment, we do NOT consider a side effect any input-output operations
22075 (changing a state or a content of any file).
22076
22077 We do not consider protected functions for this rule (???)
22078
22079 There are the following sources of side effect:
22080
22081 @enumerate
22082 @item Explicit (or direct) side-effect:
22083
22084 @itemize @bullet
22085 @item
22086 direct assignment to a non-local variable;
22087
22088 @item
22089 direct call to an entity that is known to change some data object that is
22090 not local for the body of this function (Note, that if F1 calls F2 and F2
22091 does have a side effect, this does not automatically mean that F1 also
22092 have a side effect, because it may be the case that F2 is declared in
22093 F1's body and it changes some data object that is global for F2, but
22094 local for F1);
22095 @end itemize
22096
22097 @item Indirect side-effect:
22098 @itemize @bullet
22099 @item
22100 Subprogram calls implicitly issued by:
22101 @itemize @bullet
22102 @item
22103 computing initialization expressions from type declarations as a part
22104 of object elaboration or allocator evaluation;
22105 @item
22106 computing implicit parameters of subprogram or entry calls or generic
22107 instantiations;
22108 @end itemize
22109
22110 @item
22111 activation of a task that change some non-local data object (directly or
22112 indirectly);
22113
22114 @item
22115 elaboration code of a package that is a result of a package instantiation;
22116
22117 @item
22118 controlled objects;
22119 @end itemize
22120
22121 @item Situations when we can suspect a side-effect, but the full static check
22122 is either impossible or too hard:
22123 @itemize @bullet
22124 @item
22125 assignment to access variables or to the objects pointed by access
22126 variables;
22127
22128 @item
22129 call to a subprogram pointed by access-to-subprogram value
22130
22131 @item
22132 dispatching calls;
22133 @end itemize
22134 @end enumerate
22135
22136 @noindent
22137 This rule has no parameters.
22138 @end ignore
22139
22140 @node Slices
22141 @subsection @code{Slices}
22142 @cindex @code{Slices} rule (for @command{gnatcheck})
22143
22144 @noindent
22145 Flag all uses of array slicing
22146
22147 This rule has no parameters.
22148
22149
22150 @node Unassigned_OUT_Parameters
22151 @subsection @code{Unassigned_OUT_Parameters}
22152 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22153
22154 @noindent
22155 Flags procedures' @code{out} parameters that are not assigned, and
22156 identifies the contexts in which the assignments are missing.
22157
22158 An @code{out} parameter is flagged in the statements in the procedure
22159 body's handled sequence of statements (before the procedure body's
22160 @code{exception} part, if any) if this sequence of statements contains
22161 no assignments to the parameter.
22162
22163 An @code{out} parameter is flagged in an exception handler in the exception
22164 part of the procedure body's handled sequence of statements if the handler
22165 contains no assignment to the parameter.
22166
22167 Bodies of generic procedures are also considered.
22168
22169 The following are treated as assignments to an @code{out} parameter:
22170
22171 @itemize @bullet
22172 @item
22173 an assignment statement, with the parameter or some component as the target;
22174
22175 @item
22176 passing the parameter (or one of its components) as an @code{out} or
22177 @code{in out} parameter.
22178 @end itemize
22179
22180 @noindent
22181 This rule does not have any parameters.
22182
22183
22184
22185 @node Uncommented_BEGIN_In_Package_Bodies
22186 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22187 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22188
22189 @noindent
22190 Flags each package body with declarations and a statement part that does not
22191 include a trailing comment on the line containing the @code{begin} keyword;
22192 this trailing comment needs to specify the package name and nothing else.
22193 The @code{begin} is not flagged if the package body does not
22194 contain any declarations.
22195
22196 If the @code{begin} keyword is placed on the
22197 same line as the last declaration or the first statement, it is flagged
22198 independently of whether the line contains a trailing comment. The
22199 diagnostic message is attached to the line containing the first statement.
22200
22201 This rule has no parameters.
22202
22203
22204 @node Unconstrained_Array_Returns
22205 @subsection @code{Unconstrained_Array_Returns}
22206 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22207
22208 @noindent
22209 Flag each function returning an unconstrained array. Function declarations,
22210 function bodies (and body stubs) having no separate specifications,
22211 and generic function instantiations are checked.
22212 Generic function declarations, function calls and function renamings are
22213 not checked.
22214
22215 This rule has no parameters.
22216
22217 @node Universal_Ranges
22218 @subsection @code{Universal_Ranges}
22219 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22220
22221 @noindent
22222 Flag discrete ranges that are a part of an index constraint, constrained
22223 array definition, or @code{for}-loop parameter specification, and whose bounds
22224 are both of type @i{universal_integer}. Ranges that have at least one
22225 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22226 or an expression of non-universal type) are not flagged.
22227
22228 This rule has no parameters.
22229
22230
22231 @node Unnamed_Blocks_And_Loops
22232 @subsection @code{Unnamed_Blocks_And_Loops}
22233 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22234
22235 @noindent
22236 Flag each unnamed block statement and loop statement.
22237
22238 The rule has no parameters.
22239
22240
22241
22242 @ignore
22243 @node Unused_Subprograms
22244 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22245 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22246
22247 @noindent
22248 Flag all unused subprograms.
22249
22250 This rule has no parameters.
22251 @end ignore
22252
22253
22254
22255
22256 @node USE_PACKAGE_Clauses
22257 @subsection @code{USE_PACKAGE_Clauses}
22258 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22259
22260 @noindent
22261 Flag all @code{use} clauses for packages; @code{use type} clauses are
22262 not flagged.
22263
22264 This rule has no parameters.
22265
22266
22267
22268 @node Volatile_Objects_Without_Address_Clauses
22269 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22270 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22271
22272 @noindent
22273 Flag each volatile object that does not have an address clause.
22274
22275 The following check is made: if the pragma @code{Volatile} is applied to a
22276 data object or to its type, then an address clause must
22277 be supplied for this object.
22278
22279 This rule does not check the components of data objects,
22280 array components that are volatile as a result of the pragma
22281 @code{Volatile_Components}, or objects that are volatile because
22282 they are atomic as a result of pragmas @code{Atomic} or
22283 @code{Atomic_Components}.
22284
22285 Only variable declarations, and not constant declarations, are checked.
22286
22287 This rule has no parameters.
22288
22289
22290 @c *********************************
22291 @node Creating Sample Bodies Using gnatstub
22292 @chapter Creating Sample Bodies Using @command{gnatstub}
22293 @findex gnatstub
22294
22295 @noindent
22296 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22297 for library unit declarations.
22298
22299 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22300 driver (see @ref{The GNAT Driver and Project Files}).
22301
22302 To create a body stub, @command{gnatstub} has to compile the library
22303 unit declaration. Therefore, bodies can be created only for legal
22304 library units. Moreover, if a library unit depends semantically upon
22305 units located outside the current directory, you have to provide
22306 the source search path when calling @command{gnatstub}, see the description
22307 of @command{gnatstub} switches below.
22308
22309 By default, all the program unit body stubs generated by @code{gnatstub}
22310 raise the predefined @code{Program_Error} exception, which will catch
22311 accidental calls of generated stubs. This behavior can be changed with
22312 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22313
22314 @menu
22315 * Running gnatstub::
22316 * Switches for gnatstub::
22317 @end menu
22318
22319 @node Running gnatstub
22320 @section Running @command{gnatstub}
22321
22322 @noindent
22323 @command{gnatstub} has the command-line interface of the form
22324
22325 @smallexample
22326 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22327 @end smallexample
22328
22329 @noindent
22330 where
22331 @table @var
22332 @item filename
22333 is the name of the source file that contains a library unit declaration
22334 for which a body must be created. The file name may contain the path
22335 information.
22336 The file name does not have to follow the GNAT file name conventions. If the
22337 name
22338 does not follow GNAT file naming conventions, the name of the body file must
22339 be provided
22340 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22341 If the file name follows the GNAT file naming
22342 conventions and the name of the body file is not provided,
22343 @command{gnatstub}
22344 creates the name
22345 of the body file from the argument file name by replacing the @file{.ads}
22346 suffix
22347 with the @file{.adb} suffix.
22348
22349 @item directory
22350 indicates the directory in which the body stub is to be placed (the default
22351 is the
22352 current directory)
22353
22354 @item switches
22355 is an optional sequence of switches as described in the next section
22356 @end table
22357
22358 @node Switches for gnatstub
22359 @section Switches for @command{gnatstub}
22360
22361 @table @option
22362 @c !sort!
22363
22364 @item ^-f^/FULL^
22365 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22366 If the destination directory already contains a file with the name of the
22367 body file
22368 for the argument spec file, replace it with the generated body stub.
22369
22370 @item ^-hs^/HEADER=SPEC^
22371 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22372 Put the comment header (i.e., all the comments preceding the
22373 compilation unit) from the source of the library unit declaration
22374 into the body stub.
22375
22376 @item ^-hg^/HEADER=GENERAL^
22377 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22378 Put a sample comment header into the body stub.
22379
22380 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22381 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22382 Use the content of the file as the comment header for a generated body stub.
22383
22384 @ifclear vms
22385 @item -IDIR
22386 @cindex @option{-IDIR} (@command{gnatstub})
22387 @itemx -I-
22388 @cindex @option{-I-} (@command{gnatstub})
22389 @end ifclear
22390 @ifset vms
22391 @item /NOCURRENT_DIRECTORY
22392 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22393 @end ifset
22394 ^These switches have ^This switch has^ the same meaning as in calls to
22395 @command{gcc}.
22396 ^They define ^It defines ^ the source search path in the call to
22397 @command{gcc} issued
22398 by @command{gnatstub} to compile an argument source file.
22399
22400 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22401 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22402 This switch has the same meaning as in calls to @command{gcc}.
22403 It defines the additional configuration file to be passed to the call to
22404 @command{gcc} issued
22405 by @command{gnatstub} to compile an argument source file.
22406
22407 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22408 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22409 (@var{n} is a non-negative integer). Set the maximum line length in the
22410 body stub to @var{n}; the default is 79. The maximum value that can be
22411 specified is 32767. Note that in the special case of configuration
22412 pragma files, the maximum is always 32767 regardless of whether or
22413 not this switch appears.
22414
22415 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22416 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22417 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22418 the generated body sample to @var{n}.
22419 The default indentation is 3.
22420
22421 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22422 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22423 Order local bodies alphabetically. (By default local bodies are ordered
22424 in the same way as the corresponding local specs in the argument spec file.)
22425
22426 @item ^-i^/INDENTATION=^@var{n}
22427 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22428 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22429
22430 @item ^-k^/TREE_FILE=SAVE^
22431 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22432 Do not remove the tree file (i.e., the snapshot of the compiler internal
22433 structures used by @command{gnatstub}) after creating the body stub.
22434
22435 @item ^-l^/LINE_LENGTH=^@var{n}
22436 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22437 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22438
22439 @item ^--no-exception^/NO_EXCEPTION^
22440 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22441 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22442 This is not always possible for function stubs.
22443
22444 @item ^-o ^/BODY=^@var{body-name}
22445 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22446 Body file name. This should be set if the argument file name does not
22447 follow
22448 the GNAT file naming
22449 conventions. If this switch is omitted the default name for the body will be
22450 obtained
22451 from the argument file name according to the GNAT file naming conventions.
22452
22453 @item ^-q^/QUIET^
22454 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22455 Quiet mode: do not generate a confirmation when a body is
22456 successfully created, and do not generate a message when a body is not
22457 required for an
22458 argument unit.
22459
22460 @item ^-r^/TREE_FILE=REUSE^
22461 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22462 Reuse the tree file (if it exists) instead of creating it. Instead of
22463 creating the tree file for the library unit declaration, @command{gnatstub}
22464 tries to find it in the current directory and use it for creating
22465 a body. If the tree file is not found, no body is created. This option
22466 also implies @option{^-k^/SAVE^}, whether or not
22467 the latter is set explicitly.
22468
22469 @item ^-t^/TREE_FILE=OVERWRITE^
22470 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22471 Overwrite the existing tree file. If the current directory already
22472 contains the file which, according to the GNAT file naming rules should
22473 be considered as a tree file for the argument source file,
22474 @command{gnatstub}
22475 will refuse to create the tree file needed to create a sample body
22476 unless this option is set.
22477
22478 @item ^-v^/VERBOSE^
22479 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22480 Verbose mode: generate version information.
22481
22482 @end table
22483
22484 @c *********************************
22485 @node Generating Ada Bindings for C and C++ headers
22486 @chapter Generating Ada Bindings for C and C++ headers
22487 @findex binding
22488
22489 @noindent
22490 GNAT now comes with a new experimental binding generator for C and C++
22491 headers which is intended to do 95% of the tedious work of generating
22492 Ada specs from C or C++ header files. Note that this still is a work in
22493 progress, not designed to generate 100% correct Ada specs.
22494
22495 The code generated is using the Ada 2005 syntax, which makes it
22496 easier to interface with other languages than previous versions of Ada.
22497
22498 @menu
22499 * Running the binding generator::
22500 * Generating bindings for C++ headers::
22501 * Switches::
22502 @end menu
22503
22504 @node Running the binding generator
22505 @section Running the binding generator
22506
22507 @noindent
22508 The binding generator is part of the @command{gcc} compiler and can be
22509 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22510 spec files for the header files specified on the command line, and all
22511 header files needed by these files transitivitely. For example:
22512
22513 @smallexample
22514 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22515 $ gcc -c -gnat05 *.ads
22516 @end smallexample
22517
22518 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22519 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22520 correspond to the files @file{/usr/include/time.h},
22521 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22522 mode these Ada specs.
22523
22524 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22525 and will attempt to generate corresponding Ada comments.
22526
22527 If you want to generate a single Ada file and not the transitive closure, you
22528 can use instead the @option{-fdump-ada-spec-slim} switch.
22529
22530 Note that we recommend when possible to use the @command{g++} driver to
22531 generate bindings, even for most C headers, since this will in general
22532 generate better Ada specs. For generating bindings for C++ headers, it is
22533 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22534 is equivalent in this case. If @command{g++} cannot work on your C headers
22535 because of incompatibilities between C and C++, then you can fallback to
22536 @command{gcc} instead.
22537
22538 For an example of better bindings generated from the C++ front-end,
22539 the name of the parameters (when available) are actually ignored by the C
22540 front-end. Consider the following C header:
22541
22542 @smallexample
22543 extern void foo (int variable);
22544 @end smallexample
22545
22546 with the C front-end, @code{variable} is ignored, and the above is handled as:
22547
22548 @smallexample
22549 extern void foo (int);
22550 @end smallexample
22551
22552 generating a generic:
22553
22554 @smallexample
22555 procedure foo (param1 : int);
22556 @end smallexample
22557
22558 with the C++ front-end, the name is available, and we generate:
22559
22560 @smallexample
22561 procedure foo (variable : int);
22562 @end smallexample
22563
22564 In some cases, the generated bindings will be more complete or more meaningful
22565 when defining some macros, which you can do via the @option{-D} switch. This
22566 is for example the case with @file{Xlib.h} under GNU/Linux:
22567
22568 @smallexample
22569 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22570 @end smallexample
22571
22572 The above will generate more complete bindings than a straight call without
22573 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22574
22575 In other cases, it is not possible to parse a header file in a stand alone
22576 manner, because other include files need to be included first. In this
22577 case, the solution is to create a small header file including the needed
22578 @code{#include} and possible @code{#define} directives. For example, to
22579 generate Ada bindings for @file{readline/readline.h}, you need to first
22580 include @file{stdio.h}, so you can create a file with the following two
22581 lines in e.g. @file{readline1.h}:
22582
22583 @smallexample
22584 #include <stdio.h>
22585 #include <readline/readline.h>
22586 @end smallexample
22587
22588 and then generate Ada bindings from this file:
22589
22590 @smallexample
22591 $ g++ -c -fdump-ada-spec readline1.h
22592 @end smallexample
22593
22594 @node Generating bindings for C++ headers
22595 @section Generating bindings for C++ headers
22596
22597 @noindent
22598 Generating bindings for C++ headers is done using the same options, always
22599 with the @command{g++} compiler.
22600
22601 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22602 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22603 multiple inheritance of abstract classes will be mapped to Ada interfaces
22604 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22605 information on interfacing to C++).
22606
22607 For example, given the following C++ header file:
22608
22609 @smallexample
22610 @group
22611 @cartouche
22612 class Carnivore @{
22613 public:
22614 virtual int Number_Of_Teeth () = 0;
22615 @};
22616
22617 class Domestic @{
22618 public:
22619 virtual void Set_Owner (char* Name) = 0;
22620 @};
22621
22622 class Animal @{
22623 public:
22624 int Age_Count;
22625 virtual void Set_Age (int New_Age);
22626 @};
22627
22628 class Dog : Animal, Carnivore, Domestic @{
22629 public:
22630 int Tooth_Count;
22631 char *Owner;
22632
22633 virtual int Number_Of_Teeth ();
22634 virtual void Set_Owner (char* Name);
22635
22636 Dog();
22637 @};
22638 @end cartouche
22639 @end group
22640 @end smallexample
22641
22642 The corresponding Ada code is generated:
22643
22644 @smallexample @c ada
22645 @group
22646 @cartouche
22647 package Class_Carnivore is
22648 type Carnivore is limited interface;
22649 pragma Import (CPP, Carnivore);
22650
22651 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22652 end;
22653 use Class_Carnivore;
22654
22655 package Class_Domestic is
22656 type Domestic is limited interface;
22657 pragma Import (CPP, Domestic);
22658
22659 procedure Set_Owner
22660 (this : access Domestic;
22661 Name : Interfaces.C.Strings.chars_ptr) is abstract;
22662 end;
22663 use Class_Domestic;
22664
22665 package Class_Animal is
22666 type Animal is tagged limited record
22667 Age_Count : aliased int;
22668 end record;
22669 pragma Import (CPP, Animal);
22670
22671 procedure Set_Age (this : access Animal; New_Age : int);
22672 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22673 end;
22674 use Class_Animal;
22675
22676 package Class_Dog is
22677 type Dog is new Animal and Carnivore and Domestic with record
22678 Tooth_Count : aliased int;
22679 Owner : Interfaces.C.Strings.chars_ptr;
22680 end record;
22681 pragma Import (CPP, Dog);
22682
22683 function Number_Of_Teeth (this : access Dog) return int;
22684 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22685
22686 procedure Set_Owner
22687 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22688 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22689
22690 function New_Dog return Dog'Class;
22691 pragma CPP_Constructor (New_Dog);
22692 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22693 end;
22694 use Class_Dog;
22695 @end cartouche
22696 @end group
22697 @end smallexample
22698
22699 @node Switches
22700 @section Switches
22701
22702 @table @option
22703 @item -fdump-ada-spec
22704 @cindex @option{-fdump-ada-spec} (@command{gcc})
22705 Generate Ada spec files for the given header files transitively (including
22706 all header files that these headers depend upon).
22707
22708 @item -fdump-ada-spec-slim
22709 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22710 Generate Ada spec files for the header files specified on the command line
22711 only.
22712
22713 @item -C
22714 @cindex @option{-C} (@command{gcc})
22715 Extract comments from headers and generate Ada comments in the Ada spec files.
22716 @end table
22717
22718 @node Other Utility Programs
22719 @chapter Other Utility Programs
22720
22721 @noindent
22722 This chapter discusses some other utility programs available in the Ada
22723 environment.
22724
22725 @menu
22726 * Using Other Utility Programs with GNAT::
22727 * The External Symbol Naming Scheme of GNAT::
22728 * Converting Ada Files to html with gnathtml::
22729 * Installing gnathtml::
22730 @ifset vms
22731 * LSE::
22732 * Profiling::
22733 @end ifset
22734 @end menu
22735
22736 @node Using Other Utility Programs with GNAT
22737 @section Using Other Utility Programs with GNAT
22738
22739 @noindent
22740 The object files generated by GNAT are in standard system format and in
22741 particular the debugging information uses this format. This means
22742 programs generated by GNAT can be used with existing utilities that
22743 depend on these formats.
22744
22745 @ifclear vms
22746 In general, any utility program that works with C will also often work with
22747 Ada programs generated by GNAT. This includes software utilities such as
22748 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22749 as Purify.
22750 @end ifclear
22751
22752 @node The External Symbol Naming Scheme of GNAT
22753 @section The External Symbol Naming Scheme of GNAT
22754
22755 @noindent
22756 In order to interpret the output from GNAT, when using tools that are
22757 originally intended for use with other languages, it is useful to
22758 understand the conventions used to generate link names from the Ada
22759 entity names.
22760
22761 All link names are in all lowercase letters. With the exception of library
22762 procedure names, the mechanism used is simply to use the full expanded
22763 Ada name with dots replaced by double underscores. For example, suppose
22764 we have the following package spec:
22765
22766 @smallexample @c ada
22767 @group
22768 @cartouche
22769 package QRS is
22770 MN : Integer;
22771 end QRS;
22772 @end cartouche
22773 @end group
22774 @end smallexample
22775
22776 @noindent
22777 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22778 the corresponding link name is @code{qrs__mn}.
22779 @findex Export
22780 Of course if a @code{pragma Export} is used this may be overridden:
22781
22782 @smallexample @c ada
22783 @group
22784 @cartouche
22785 package Exports is
22786 Var1 : Integer;
22787 pragma Export (Var1, C, External_Name => "var1_name");
22788 Var2 : Integer;
22789 pragma Export (Var2, C, Link_Name => "var2_link_name");
22790 end Exports;
22791 @end cartouche
22792 @end group
22793 @end smallexample
22794
22795 @noindent
22796 In this case, the link name for @var{Var1} is whatever link name the
22797 C compiler would assign for the C function @var{var1_name}. This typically
22798 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22799 system conventions, but other possibilities exist. The link name for
22800 @var{Var2} is @var{var2_link_name}, and this is not operating system
22801 dependent.
22802
22803 @findex _main
22804 One exception occurs for library level procedures. A potential ambiguity
22805 arises between the required name @code{_main} for the C main program,
22806 and the name we would otherwise assign to an Ada library level procedure
22807 called @code{Main} (which might well not be the main program).
22808
22809 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22810 names. So if we have a library level procedure such as
22811
22812 @smallexample @c ada
22813 @group
22814 @cartouche
22815 procedure Hello (S : String);
22816 @end cartouche
22817 @end group
22818 @end smallexample
22819
22820 @noindent
22821 the external name of this procedure will be @var{_ada_hello}.
22822
22823
22824 @node Converting Ada Files to html with gnathtml
22825 @section Converting Ada Files to HTML with @code{gnathtml}
22826
22827 @noindent
22828 This @code{Perl} script allows Ada source files to be browsed using
22829 standard Web browsers. For installation procedure, see the section
22830 @xref{Installing gnathtml}.
22831
22832 Ada reserved keywords are highlighted in a bold font and Ada comments in
22833 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22834 switch to suppress the generation of cross-referencing information, user
22835 defined variables and types will appear in a different color; you will
22836 be able to click on any identifier and go to its declaration.
22837
22838 The command line is as follow:
22839 @smallexample
22840 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22841 @end smallexample
22842
22843 @noindent
22844 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22845 an html file for every ada file, and a global file called @file{index.htm}.
22846 This file is an index of every identifier defined in the files.
22847
22848 The available ^switches^options^ are the following ones:
22849
22850 @table @option
22851 @item -83
22852 @cindex @option{-83} (@code{gnathtml})
22853 Only the Ada 83 subset of keywords will be highlighted.
22854
22855 @item -cc @var{color}
22856 @cindex @option{-cc} (@code{gnathtml})
22857 This option allows you to change the color used for comments. The default
22858 value is green. The color argument can be any name accepted by html.
22859
22860 @item -d
22861 @cindex @option{-d} (@code{gnathtml})
22862 If the Ada files depend on some other files (for instance through
22863 @code{with} clauses, the latter files will also be converted to html.
22864 Only the files in the user project will be converted to html, not the files
22865 in the run-time library itself.
22866
22867 @item -D
22868 @cindex @option{-D} (@code{gnathtml})
22869 This command is the same as @option{-d} above, but @command{gnathtml} will
22870 also look for files in the run-time library, and generate html files for them.
22871
22872 @item -ext @var{extension}
22873 @cindex @option{-ext} (@code{gnathtml})
22874 This option allows you to change the extension of the generated HTML files.
22875 If you do not specify an extension, it will default to @file{htm}.
22876
22877 @item -f
22878 @cindex @option{-f} (@code{gnathtml})
22879 By default, gnathtml will generate html links only for global entities
22880 ('with'ed units, global variables and types,@dots{}). If you specify
22881 @option{-f} on the command line, then links will be generated for local
22882 entities too.
22883
22884 @item -l @var{number}
22885 @cindex @option{-l} (@code{gnathtml})
22886 If this ^switch^option^ is provided and @var{number} is not 0, then
22887 @code{gnathtml} will number the html files every @var{number} line.
22888
22889 @item -I @var{dir}
22890 @cindex @option{-I} (@code{gnathtml})
22891 Specify a directory to search for library files (@file{.ALI} files) and
22892 source files. You can provide several -I switches on the command line,
22893 and the directories will be parsed in the order of the command line.
22894
22895 @item -o @var{dir}
22896 @cindex @option{-o} (@code{gnathtml})
22897 Specify the output directory for html files. By default, gnathtml will
22898 saved the generated html files in a subdirectory named @file{html/}.
22899
22900 @item -p @var{file}
22901 @cindex @option{-p} (@code{gnathtml})
22902 If you are using Emacs and the most recent Emacs Ada mode, which provides
22903 a full Integrated Development Environment for compiling, checking,
22904 running and debugging applications, you may use @file{.gpr} files
22905 to give the directories where Emacs can find sources and object files.
22906
22907 Using this ^switch^option^, you can tell gnathtml to use these files.
22908 This allows you to get an html version of your application, even if it
22909 is spread over multiple directories.
22910
22911 @item -sc @var{color}
22912 @cindex @option{-sc} (@code{gnathtml})
22913 This ^switch^option^ allows you to change the color used for symbol
22914 definitions.
22915 The default value is red. The color argument can be any name accepted by html.
22916
22917 @item -t @var{file}
22918 @cindex @option{-t} (@code{gnathtml})
22919 This ^switch^option^ provides the name of a file. This file contains a list of
22920 file names to be converted, and the effect is exactly as though they had
22921 appeared explicitly on the command line. This
22922 is the recommended way to work around the command line length limit on some
22923 systems.
22924
22925 @end table
22926
22927 @node Installing gnathtml
22928 @section Installing @code{gnathtml}
22929
22930 @noindent
22931 @code{Perl} needs to be installed on your machine to run this script.
22932 @code{Perl} is freely available for almost every architecture and
22933 Operating System via the Internet.
22934
22935 On Unix systems, you may want to modify the first line of the script
22936 @code{gnathtml}, to explicitly tell the Operating system where Perl
22937 is. The syntax of this line is:
22938 @smallexample
22939 #!full_path_name_to_perl
22940 @end smallexample
22941
22942 @noindent
22943 Alternatively, you may run the script using the following command line:
22944
22945 @smallexample
22946 $ perl gnathtml.pl @ovar{switches} @var{files}
22947 @end smallexample
22948
22949 @ifset vms
22950 @node LSE
22951 @section LSE
22952 @findex LSE
22953
22954 @noindent
22955 The GNAT distribution provides an Ada 95 template for the HP Language
22956 Sensitive Editor (LSE), a component of DECset. In order to
22957 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22958
22959 @node Profiling
22960 @section Profiling
22961 @findex PCA
22962
22963 @noindent
22964 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22965 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22966 the collection phase with the /DEBUG qualifier.
22967
22968 @smallexample
22969 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22970 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22971 $ RUN/DEBUG <PROGRAM_NAME>
22972 @end smallexample
22973 @noindent
22974 @end ifset
22975
22976 @ifclear vms
22977 @c ******************************
22978 @node Code Coverage and Profiling
22979 @chapter Code Coverage and Profiling
22980 @cindex Code Coverage
22981 @cindex Profiling
22982
22983 @noindent
22984 This chapter describes how to use @code{gcov} - coverage testing tool - and
22985 @code{gprof} - profiler tool - on your Ada programs.
22986
22987 @menu
22988 * Code Coverage of Ada Programs using gcov::
22989 * Profiling an Ada Program using gprof::
22990 @end menu
22991
22992 @node Code Coverage of Ada Programs using gcov
22993 @section Code Coverage of Ada Programs using gcov
22994 @cindex gcov
22995 @cindex -fprofile-arcs
22996 @cindex -ftest-coverage
22997 @cindex -coverage
22998 @cindex Code Coverage
22999
23000 @noindent
23001 @code{gcov} is a test coverage program: it analyzes the execution of a given
23002 program on selected tests, to help you determine the portions of the program
23003 that are still untested.
23004
23005 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23006 User's Guide. You can refer to this documentation for a more complete
23007 description.
23008
23009 This chapter provides a quick startup guide, and
23010 details some Gnat-specific features.
23011
23012 @menu
23013 * Quick startup guide::
23014 * Gnat specifics::
23015 @end menu
23016
23017 @node Quick startup guide
23018 @subsection Quick startup guide
23019
23020 In order to perform coverage analysis of a program using @code{gcov}, 3
23021 steps are needed:
23022
23023 @itemize @bullet
23024 @item
23025 Code instrumentation during the compilation process
23026 @item
23027 Execution of the instrumented program
23028 @item
23029 Execution of the @code{gcov} tool to generate the result.
23030 @end itemize
23031
23032 The code instrumentation needed by gcov is created at the object level:
23033 The source code is not modified in any way, because the instrumentation code is
23034 inserted by gcc during the compilation process. To compile your code with code
23035 coverage activated, you need to recompile your whole project using the
23036 switches
23037 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23038 @code{-fprofile-arcs}.
23039
23040 @smallexample
23041 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23042 -largs -fprofile-arcs
23043 @end smallexample
23044
23045 This compilation process will create @file{.gcno} files together with
23046 the usual object files.
23047
23048 Once the program is compiled with coverage instrumentation, you can
23049 run it as many times as needed - on portions of a test suite for
23050 example. The first execution will produce @file{.gcda} files at the
23051 same location as the @file{.gcno} files. The following executions
23052 will update those files, so that a cumulative result of the covered
23053 portions of the program is generated.
23054
23055 Finally, you need to call the @code{gcov} tool. The different options of
23056 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23057
23058 This will create annotated source files with a @file{.gcov} extension:
23059 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23060
23061 @node Gnat specifics
23062 @subsection Gnat specifics
23063
23064 Because Ada semantics, portions of the source code may be shared among
23065 several object files. This is the case for example when generics are
23066 involved, when inlining is active or when declarations generate initialisation
23067 calls. In order to take
23068 into account this shared code, you need to call @code{gcov} on all
23069 source files of the tested program at once.
23070
23071 The list of source files might exceed the system's maximum command line
23072 length. In order to bypass this limitation, a new mechanism has been
23073 implemented in @code{gcov}: you can now list all your project's files into a
23074 text file, and provide this file to gcov as a parameter, preceded by a @@
23075 (e.g. @samp{gcov @@mysrclist.txt}).
23076
23077 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23078 not supported as there can be unresolved symbols during the final link.
23079
23080 @node Profiling an Ada Program using gprof
23081 @section Profiling an Ada Program using gprof
23082 @cindex gprof
23083 @cindex -pg
23084 @cindex Profiling
23085
23086 @noindent
23087 This section is not meant to be an exhaustive documentation of @code{gprof}.
23088 Full documentation for it can be found in the GNU Profiler User's Guide
23089 documentation that is part of this GNAT distribution.
23090
23091 Profiling a program helps determine the parts of a program that are executed
23092 most often, and are therefore the most time-consuming.
23093
23094 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23095 better handle Ada programs and multitasking.
23096 It is currently supported on the following platforms
23097 @itemize @bullet
23098 @item
23099 linux x86/x86_64
23100 @item
23101 solaris sparc/sparc64/x86
23102 @item
23103 windows x86
23104 @end itemize
23105
23106 @noindent
23107 In order to profile a program using @code{gprof}, 3 steps are needed:
23108
23109 @itemize @bullet
23110 @item
23111 Code instrumentation, requiring a full recompilation of the project with the
23112 proper switches.
23113 @item
23114 Execution of the program under the analysis conditions, i.e. with the desired
23115 input.
23116 @item
23117 Analysis of the results using the @code{gprof} tool.
23118 @end itemize
23119
23120 @noindent
23121 The following sections detail the different steps, and indicate how
23122 to interpret the results:
23123 @menu
23124 * Compilation for profiling::
23125 * Program execution::
23126 * Running gprof::
23127 * Interpretation of profiling results::
23128 @end menu
23129
23130 @node Compilation for profiling
23131 @subsection Compilation for profiling
23132 @cindex -pg
23133 @cindex Profiling
23134
23135 In order to profile a program the first step is to tell the compiler
23136 to generate the necessary profiling information. The compiler switch to be used
23137 is @code{-pg}, which must be added to other compilation switches. This
23138 switch needs to be specified both during compilation and link stages, and can
23139 be specified once when using gnatmake:
23140
23141 @smallexample
23142 gnatmake -f -pg -P my_project
23143 @end smallexample
23144
23145 @noindent
23146 Note that only the objects that were compiled with the @samp{-pg} switch will be
23147 profiled; if you need to profile your whole project, use the
23148 @samp{-f} gnatmake switch to force full recompilation.
23149
23150 @node Program execution
23151 @subsection Program execution
23152
23153 @noindent
23154 Once the program has been compiled for profiling, you can run it as usual.
23155
23156 The only constraint imposed by profiling is that the program must terminate
23157 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23158 properly analyzed.
23159
23160 Once the program completes execution, a data file called @file{gmon.out} is
23161 generated in the directory where the program was launched from. If this file
23162 already exists, it will be overwritten.
23163
23164 @node Running gprof
23165 @subsection Running gprof
23166
23167 @noindent
23168 The @code{gprof} tool is called as follow:
23169
23170 @smallexample
23171 gprof my_prog gmon.out
23172 @end smallexample
23173
23174 @noindent
23175 or simpler:
23176
23177 @smallexample
23178 gprof my_prog
23179 @end smallexample
23180
23181 @noindent
23182 The complete form of the gprof command line is the following:
23183
23184 @smallexample
23185 gprof [^switches^options^] [executable [data-file]]
23186 @end smallexample
23187
23188 @noindent
23189 @code{gprof} supports numerous ^switch^options^. The order of these
23190 ^switch^options^ does not matter. The full list of options can be found in
23191 the GNU Profiler User's Guide documentation that comes with this documentation.
23192
23193 The following is the subset of those switches that is most relevant:
23194
23195 @table @option
23196
23197 @item --demangle[=@var{style}]
23198 @itemx --no-demangle
23199 @cindex @option{--demangle} (@code{gprof})
23200 These options control whether symbol names should be demangled when
23201 printing output. The default is to demangle C++ symbols. The
23202 @code{--no-demangle} option may be used to turn off demangling. Different
23203 compilers have different mangling styles. The optional demangling style
23204 argument can be used to choose an appropriate demangling style for your
23205 compiler, in particular Ada symbols generated by GNAT can be demangled using
23206 @code{--demangle=gnat}.
23207
23208 @item -e @var{function_name}
23209 @cindex @option{-e} (@code{gprof})
23210 The @samp{-e @var{function}} option tells @code{gprof} not to print
23211 information about the function @var{function_name} (and its
23212 children@dots{}) in the call graph. The function will still be listed
23213 as a child of any functions that call it, but its index number will be
23214 shown as @samp{[not printed]}. More than one @samp{-e} option may be
23215 given; only one @var{function_name} may be indicated with each @samp{-e}
23216 option.
23217
23218 @item -E @var{function_name}
23219 @cindex @option{-E} (@code{gprof})
23220 The @code{-E @var{function}} option works like the @code{-e} option, but
23221 execution time spent in the function (and children who were not called from
23222 anywhere else), will not be used to compute the percentages-of-time for
23223 the call graph. More than one @samp{-E} option may be given; only one
23224 @var{function_name} may be indicated with each @samp{-E} option.
23225
23226 @item -f @var{function_name}
23227 @cindex @option{-f} (@code{gprof})
23228 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23229 call graph to the function @var{function_name} and its children (and
23230 their children@dots{}). More than one @samp{-f} option may be given;
23231 only one @var{function_name} may be indicated with each @samp{-f}
23232 option.
23233
23234 @item -F @var{function_name}
23235 @cindex @option{-F} (@code{gprof})
23236 The @samp{-F @var{function}} option works like the @code{-f} option, but
23237 only time spent in the function and its children (and their
23238 children@dots{}) will be used to determine total-time and
23239 percentages-of-time for the call graph. More than one @samp{-F} option
23240 may be given; only one @var{function_name} may be indicated with each
23241 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
23242
23243 @end table
23244
23245 @node Interpretation of profiling results
23246 @subsection Interpretation of profiling results
23247
23248 @noindent
23249
23250 The results of the profiling analysis are represented by two arrays: the
23251 'flat profile' and the 'call graph'. Full documentation of those outputs
23252 can be found in the GNU Profiler User's Guide.
23253
23254 The flat profile shows the time spent in each function of the program, and how
23255 many time it has been called. This allows you to locate easily the most
23256 time-consuming functions.
23257
23258 The call graph shows, for each subprogram, the subprograms that call it,
23259 and the subprograms that it calls. It also provides an estimate of the time
23260 spent in each of those callers/called subprograms.
23261 @end ifclear
23262
23263 @c ******************************
23264 @node Running and Debugging Ada Programs
23265 @chapter Running and Debugging Ada Programs
23266 @cindex Debugging
23267
23268 @noindent
23269 This chapter discusses how to debug Ada programs.
23270 @ifset vms
23271 It applies to GNAT on the Alpha OpenVMS platform;
23272 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23273 since HP has implemented Ada support in the OpenVMS debugger on I64.
23274 @end ifset
23275
23276 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23277
23278 @enumerate
23279 @item
23280 The illegality may be a violation of the static semantics of Ada. In
23281 that case GNAT diagnoses the constructs in the program that are illegal.
23282 It is then a straightforward matter for the user to modify those parts of
23283 the program.
23284
23285 @item
23286 The illegality may be a violation of the dynamic semantics of Ada. In
23287 that case the program compiles and executes, but may generate incorrect
23288 results, or may terminate abnormally with some exception.
23289
23290 @item
23291 When presented with a program that contains convoluted errors, GNAT
23292 itself may terminate abnormally without providing full diagnostics on
23293 the incorrect user program.
23294 @end enumerate
23295
23296 @menu
23297 * The GNAT Debugger GDB::
23298 * Running GDB::
23299 * Introduction to GDB Commands::
23300 * Using Ada Expressions::
23301 * Calling User-Defined Subprograms::
23302 * Using the Next Command in a Function::
23303 * Ada Exceptions::
23304 * Ada Tasks::
23305 * Debugging Generic Units::
23306 * GNAT Abnormal Termination or Failure to Terminate::
23307 * Naming Conventions for GNAT Source Files::
23308 * Getting Internal Debugging Information::
23309 * Stack Traceback::
23310 @end menu
23311
23312 @cindex Debugger
23313 @findex gdb
23314
23315 @node The GNAT Debugger GDB
23316 @section The GNAT Debugger GDB
23317
23318 @noindent
23319 @code{GDB} is a general purpose, platform-independent debugger that
23320 can be used to debug mixed-language programs compiled with @command{gcc},
23321 and in particular is capable of debugging Ada programs compiled with
23322 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23323 complex Ada data structures.
23324
23325 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23326 @ifset vms
23327 located in the GNU:[DOCS] directory,
23328 @end ifset
23329 for full details on the usage of @code{GDB}, including a section on
23330 its usage on programs. This manual should be consulted for full
23331 details. The section that follows is a brief introduction to the
23332 philosophy and use of @code{GDB}.
23333
23334 When GNAT programs are compiled, the compiler optionally writes debugging
23335 information into the generated object file, including information on
23336 line numbers, and on declared types and variables. This information is
23337 separate from the generated code. It makes the object files considerably
23338 larger, but it does not add to the size of the actual executable that
23339 will be loaded into memory, and has no impact on run-time performance. The
23340 generation of debug information is triggered by the use of the
23341 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23342 used to carry out the compilations. It is important to emphasize that
23343 the use of these options does not change the generated code.
23344
23345 The debugging information is written in standard system formats that
23346 are used by many tools, including debuggers and profilers. The format
23347 of the information is typically designed to describe C types and
23348 semantics, but GNAT implements a translation scheme which allows full
23349 details about Ada types and variables to be encoded into these
23350 standard C formats. Details of this encoding scheme may be found in
23351 the file exp_dbug.ads in the GNAT source distribution. However, the
23352 details of this encoding are, in general, of no interest to a user,
23353 since @code{GDB} automatically performs the necessary decoding.
23354
23355 When a program is bound and linked, the debugging information is
23356 collected from the object files, and stored in the executable image of
23357 the program. Again, this process significantly increases the size of
23358 the generated executable file, but it does not increase the size of
23359 the executable program itself. Furthermore, if this program is run in
23360 the normal manner, it runs exactly as if the debug information were
23361 not present, and takes no more actual memory.
23362
23363 However, if the program is run under control of @code{GDB}, the
23364 debugger is activated. The image of the program is loaded, at which
23365 point it is ready to run. If a run command is given, then the program
23366 will run exactly as it would have if @code{GDB} were not present. This
23367 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
23368 entirely non-intrusive until a breakpoint is encountered. If no
23369 breakpoint is ever hit, the program will run exactly as it would if no
23370 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23371 the debugging information and can respond to user commands to inspect
23372 variables, and more generally to report on the state of execution.
23373
23374 @c **************
23375 @node Running GDB
23376 @section Running GDB
23377
23378 @noindent
23379 This section describes how to initiate the debugger.
23380 @c The above sentence is really just filler, but it was otherwise
23381 @c clumsy to get the first paragraph nonindented given the conditional
23382 @c nature of the description
23383
23384 @ifclear vms
23385 The debugger can be launched from a @code{GPS} menu or
23386 directly from the command line. The description below covers the latter use.
23387 All the commands shown can be used in the @code{GPS} debug console window,
23388 but there are usually more GUI-based ways to achieve the same effect.
23389 @end ifclear
23390
23391 The command to run @code{GDB} is
23392
23393 @smallexample
23394 $ ^gdb program^GDB PROGRAM^
23395 @end smallexample
23396
23397 @noindent
23398 where @code{^program^PROGRAM^} is the name of the executable file. This
23399 activates the debugger and results in a prompt for debugger commands.
23400 The simplest command is simply @code{run}, which causes the program to run
23401 exactly as if the debugger were not present. The following section
23402 describes some of the additional commands that can be given to @code{GDB}.
23403
23404 @c *******************************
23405 @node Introduction to GDB Commands
23406 @section Introduction to GDB Commands
23407
23408 @noindent
23409 @code{GDB} contains a large repertoire of commands. @xref{Top,,
23410 Debugging with GDB, gdb, Debugging with GDB},
23411 @ifset vms
23412 located in the GNU:[DOCS] directory,
23413 @end ifset
23414 for extensive documentation on the use
23415 of these commands, together with examples of their use. Furthermore,
23416 the command @command{help} invoked from within GDB activates a simple help
23417 facility which summarizes the available commands and their options.
23418 In this section we summarize a few of the most commonly
23419 used commands to give an idea of what @code{GDB} is about. You should create
23420 a simple program with debugging information and experiment with the use of
23421 these @code{GDB} commands on the program as you read through the
23422 following section.
23423
23424 @table @code
23425 @item set args @var{arguments}
23426 The @var{arguments} list above is a list of arguments to be passed to
23427 the program on a subsequent run command, just as though the arguments
23428 had been entered on a normal invocation of the program. The @code{set args}
23429 command is not needed if the program does not require arguments.
23430
23431 @item run
23432 The @code{run} command causes execution of the program to start from
23433 the beginning. If the program is already running, that is to say if
23434 you are currently positioned at a breakpoint, then a prompt will ask
23435 for confirmation that you want to abandon the current execution and
23436 restart.
23437
23438 @item breakpoint @var{location}
23439 The breakpoint command sets a breakpoint, that is to say a point at which
23440 execution will halt and @code{GDB} will await further
23441 commands. @var{location} is
23442 either a line number within a file, given in the format @code{file:linenumber},
23443 or it is the name of a subprogram. If you request that a breakpoint be set on
23444 a subprogram that is overloaded, a prompt will ask you to specify on which of
23445 those subprograms you want to breakpoint. You can also
23446 specify that all of them should be breakpointed. If the program is run
23447 and execution encounters the breakpoint, then the program
23448 stops and @code{GDB} signals that the breakpoint was encountered by
23449 printing the line of code before which the program is halted.
23450
23451 @item breakpoint exception @var{name}
23452 A special form of the breakpoint command which breakpoints whenever
23453 exception @var{name} is raised.
23454 If @var{name} is omitted,
23455 then a breakpoint will occur when any exception is raised.
23456
23457 @item print @var{expression}
23458 This will print the value of the given expression. Most simple
23459 Ada expression formats are properly handled by @code{GDB}, so the expression
23460 can contain function calls, variables, operators, and attribute references.
23461
23462 @item continue
23463 Continues execution following a breakpoint, until the next breakpoint or the
23464 termination of the program.
23465
23466 @item step
23467 Executes a single line after a breakpoint. If the next statement
23468 is a subprogram call, execution continues into (the first statement of)
23469 the called subprogram.
23470
23471 @item next
23472 Executes a single line. If this line is a subprogram call, executes and
23473 returns from the call.
23474
23475 @item list
23476 Lists a few lines around the current source location. In practice, it
23477 is usually more convenient to have a separate edit window open with the
23478 relevant source file displayed. Successive applications of this command
23479 print subsequent lines. The command can be given an argument which is a
23480 line number, in which case it displays a few lines around the specified one.
23481
23482 @item backtrace
23483 Displays a backtrace of the call chain. This command is typically
23484 used after a breakpoint has occurred, to examine the sequence of calls that
23485 leads to the current breakpoint. The display includes one line for each
23486 activation record (frame) corresponding to an active subprogram.
23487
23488 @item up
23489 At a breakpoint, @code{GDB} can display the values of variables local
23490 to the current frame. The command @code{up} can be used to
23491 examine the contents of other active frames, by moving the focus up
23492 the stack, that is to say from callee to caller, one frame at a time.
23493
23494 @item down
23495 Moves the focus of @code{GDB} down from the frame currently being
23496 examined to the frame of its callee (the reverse of the previous command),
23497
23498 @item frame @var{n}
23499 Inspect the frame with the given number. The value 0 denotes the frame
23500 of the current breakpoint, that is to say the top of the call stack.
23501
23502 @end table
23503
23504 @noindent
23505 The above list is a very short introduction to the commands that
23506 @code{GDB} provides. Important additional capabilities, including conditional
23507 breakpoints, the ability to execute command sequences on a breakpoint,
23508 the ability to debug at the machine instruction level and many other
23509 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23510 Debugging with GDB}. Note that most commands can be abbreviated
23511 (for example, c for continue, bt for backtrace).
23512
23513 @node Using Ada Expressions
23514 @section Using Ada Expressions
23515 @cindex Ada expressions
23516
23517 @noindent
23518 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23519 extensions. The philosophy behind the design of this subset is
23520
23521 @itemize @bullet
23522 @item
23523 That @code{GDB} should provide basic literals and access to operations for
23524 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23525 leaving more sophisticated computations to subprograms written into the
23526 program (which therefore may be called from @code{GDB}).
23527
23528 @item
23529 That type safety and strict adherence to Ada language restrictions
23530 are not particularly important to the @code{GDB} user.
23531
23532 @item
23533 That brevity is important to the @code{GDB} user.
23534 @end itemize
23535
23536 @noindent
23537 Thus, for brevity, the debugger acts as if there were
23538 implicit @code{with} and @code{use} clauses in effect for all user-written
23539 packages, thus making it unnecessary to fully qualify most names with
23540 their packages, regardless of context. Where this causes ambiguity,
23541 @code{GDB} asks the user's intent.
23542
23543 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23544 GDB, gdb, Debugging with GDB}.
23545
23546 @node Calling User-Defined Subprograms
23547 @section Calling User-Defined Subprograms
23548
23549 @noindent
23550 An important capability of @code{GDB} is the ability to call user-defined
23551 subprograms while debugging. This is achieved simply by entering
23552 a subprogram call statement in the form:
23553
23554 @smallexample
23555 call subprogram-name (parameters)
23556 @end smallexample
23557
23558 @noindent
23559 The keyword @code{call} can be omitted in the normal case where the
23560 @code{subprogram-name} does not coincide with any of the predefined
23561 @code{GDB} commands.
23562
23563 The effect is to invoke the given subprogram, passing it the
23564 list of parameters that is supplied. The parameters can be expressions and
23565 can include variables from the program being debugged. The
23566 subprogram must be defined
23567 at the library level within your program, and @code{GDB} will call the
23568 subprogram within the environment of your program execution (which
23569 means that the subprogram is free to access or even modify variables
23570 within your program).
23571
23572 The most important use of this facility is in allowing the inclusion of
23573 debugging routines that are tailored to particular data structures
23574 in your program. Such debugging routines can be written to provide a suitably
23575 high-level description of an abstract type, rather than a low-level dump
23576 of its physical layout. After all, the standard
23577 @code{GDB print} command only knows the physical layout of your
23578 types, not their abstract meaning. Debugging routines can provide information
23579 at the desired semantic level and are thus enormously useful.
23580
23581 For example, when debugging GNAT itself, it is crucial to have access to
23582 the contents of the tree nodes used to represent the program internally.
23583 But tree nodes are represented simply by an integer value (which in turn
23584 is an index into a table of nodes).
23585 Using the @code{print} command on a tree node would simply print this integer
23586 value, which is not very useful. But the PN routine (defined in file
23587 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23588 a useful high level representation of the tree node, which includes the
23589 syntactic category of the node, its position in the source, the integers
23590 that denote descendant nodes and parent node, as well as varied
23591 semantic information. To study this example in more detail, you might want to
23592 look at the body of the PN procedure in the stated file.
23593
23594 @node Using the Next Command in a Function
23595 @section Using the Next Command in a Function
23596
23597 @noindent
23598 When you use the @code{next} command in a function, the current source
23599 location will advance to the next statement as usual. A special case
23600 arises in the case of a @code{return} statement.
23601
23602 Part of the code for a return statement is the ``epilog'' of the function.
23603 This is the code that returns to the caller. There is only one copy of
23604 this epilog code, and it is typically associated with the last return
23605 statement in the function if there is more than one return. In some
23606 implementations, this epilog is associated with the first statement
23607 of the function.
23608
23609 The result is that if you use the @code{next} command from a return
23610 statement that is not the last return statement of the function you
23611 may see a strange apparent jump to the last return statement or to
23612 the start of the function. You should simply ignore this odd jump.
23613 The value returned is always that from the first return statement
23614 that was stepped through.
23615
23616 @node Ada Exceptions
23617 @section Breaking on Ada Exceptions
23618 @cindex Exceptions
23619
23620 @noindent
23621 You can set breakpoints that trip when your program raises
23622 selected exceptions.
23623
23624 @table @code
23625 @item break exception
23626 Set a breakpoint that trips whenever (any task in the) program raises
23627 any exception.
23628
23629 @item break exception @var{name}
23630 Set a breakpoint that trips whenever (any task in the) program raises
23631 the exception @var{name}.
23632
23633 @item break exception unhandled
23634 Set a breakpoint that trips whenever (any task in the) program raises an
23635 exception for which there is no handler.
23636
23637 @item info exceptions
23638 @itemx info exceptions @var{regexp}
23639 The @code{info exceptions} command permits the user to examine all defined
23640 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23641 argument, prints out only those exceptions whose name matches @var{regexp}.
23642 @end table
23643
23644 @node Ada Tasks
23645 @section Ada Tasks
23646 @cindex Tasks
23647
23648 @noindent
23649 @code{GDB} allows the following task-related commands:
23650
23651 @table @code
23652 @item info tasks
23653 This command shows a list of current Ada tasks, as in the following example:
23654
23655 @smallexample
23656 @iftex
23657 @leftskip=0cm
23658 @end iftex
23659 (gdb) info tasks
23660 ID TID P-ID Thread Pri State Name
23661 1 8088000 0 807e000 15 Child Activation Wait main_task
23662 2 80a4000 1 80ae000 15 Accept/Select Wait b
23663 3 809a800 1 80a4800 15 Child Activation Wait a
23664 * 4 80ae800 3 80b8000 15 Running c
23665 @end smallexample
23666
23667 @noindent
23668 In this listing, the asterisk before the first task indicates it to be the
23669 currently running task. The first column lists the task ID that is used
23670 to refer to tasks in the following commands.
23671
23672 @item break @var{linespec} task @var{taskid}
23673 @itemx break @var{linespec} task @var{taskid} if @dots{}
23674 @cindex Breakpoints and tasks
23675 These commands are like the @code{break @dots{} thread @dots{}}.
23676 @var{linespec} specifies source lines.
23677
23678 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23679 to specify that you only want @code{GDB} to stop the program when a
23680 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23681 numeric task identifiers assigned by @code{GDB}, shown in the first
23682 column of the @samp{info tasks} display.
23683
23684 If you do not specify @samp{task @var{taskid}} when you set a
23685 breakpoint, the breakpoint applies to @emph{all} tasks of your
23686 program.
23687
23688 You can use the @code{task} qualifier on conditional breakpoints as
23689 well; in this case, place @samp{task @var{taskid}} before the
23690 breakpoint condition (before the @code{if}).
23691
23692 @item task @var{taskno}
23693 @cindex Task switching
23694
23695 This command allows to switch to the task referred by @var{taskno}. In
23696 particular, This allows to browse the backtrace of the specified
23697 task. It is advised to switch back to the original task before
23698 continuing execution otherwise the scheduling of the program may be
23699 perturbed.
23700 @end table
23701
23702 @noindent
23703 For more detailed information on the tasking support,
23704 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23705
23706 @node Debugging Generic Units
23707 @section Debugging Generic Units
23708 @cindex Debugging Generic Units
23709 @cindex Generics
23710
23711 @noindent
23712 GNAT always uses code expansion for generic instantiation. This means that
23713 each time an instantiation occurs, a complete copy of the original code is
23714 made, with appropriate substitutions of formals by actuals.
23715
23716 It is not possible to refer to the original generic entities in
23717 @code{GDB}, but it is always possible to debug a particular instance of
23718 a generic, by using the appropriate expanded names. For example, if we have
23719
23720 @smallexample @c ada
23721 @group
23722 @cartouche
23723 procedure g is
23724
23725 generic package k is
23726 procedure kp (v1 : in out integer);
23727 end k;
23728
23729 package body k is
23730 procedure kp (v1 : in out integer) is
23731 begin
23732 v1 := v1 + 1;
23733 end kp;
23734 end k;
23735
23736 package k1 is new k;
23737 package k2 is new k;
23738
23739 var : integer := 1;
23740
23741 begin
23742 k1.kp (var);
23743 k2.kp (var);
23744 k1.kp (var);
23745 k2.kp (var);
23746 end;
23747 @end cartouche
23748 @end group
23749 @end smallexample
23750
23751 @noindent
23752 Then to break on a call to procedure kp in the k2 instance, simply
23753 use the command:
23754
23755 @smallexample
23756 (gdb) break g.k2.kp
23757 @end smallexample
23758
23759 @noindent
23760 When the breakpoint occurs, you can step through the code of the
23761 instance in the normal manner and examine the values of local variables, as for
23762 other units.
23763
23764 @node GNAT Abnormal Termination or Failure to Terminate
23765 @section GNAT Abnormal Termination or Failure to Terminate
23766 @cindex GNAT Abnormal Termination or Failure to Terminate
23767
23768 @noindent
23769 When presented with programs that contain serious errors in syntax
23770 or semantics,
23771 GNAT may on rare occasions experience problems in operation, such
23772 as aborting with a
23773 segmentation fault or illegal memory access, raising an internal
23774 exception, terminating abnormally, or failing to terminate at all.
23775 In such cases, you can activate
23776 various features of GNAT that can help you pinpoint the construct in your
23777 program that is the likely source of the problem.
23778
23779 The following strategies are presented in increasing order of
23780 difficulty, corresponding to your experience in using GNAT and your
23781 familiarity with compiler internals.
23782
23783 @enumerate
23784 @item
23785 Run @command{gcc} with the @option{-gnatf}. This first
23786 switch causes all errors on a given line to be reported. In its absence,
23787 only the first error on a line is displayed.
23788
23789 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23790 are encountered, rather than after compilation is terminated. If GNAT
23791 terminates prematurely or goes into an infinite loop, the last error
23792 message displayed may help to pinpoint the culprit.
23793
23794 @item
23795 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23796 mode, @command{gcc} produces ongoing information about the progress of the
23797 compilation and provides the name of each procedure as code is
23798 generated. This switch allows you to find which Ada procedure was being
23799 compiled when it encountered a code generation problem.
23800
23801 @item
23802 @cindex @option{-gnatdc} switch
23803 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23804 switch that does for the front-end what @option{^-v^VERBOSE^} does
23805 for the back end. The system prints the name of each unit,
23806 either a compilation unit or nested unit, as it is being analyzed.
23807 @item
23808 Finally, you can start
23809 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23810 front-end of GNAT, and can be run independently (normally it is just
23811 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23812 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23813 @code{where} command is the first line of attack; the variable
23814 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23815 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23816 which the execution stopped, and @code{input_file name} indicates the name of
23817 the source file.
23818 @end enumerate
23819
23820 @node Naming Conventions for GNAT Source Files
23821 @section Naming Conventions for GNAT Source Files
23822
23823 @noindent
23824 In order to examine the workings of the GNAT system, the following
23825 brief description of its organization may be helpful:
23826
23827 @itemize @bullet
23828 @item
23829 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23830
23831 @item
23832 All files prefixed with @file{^par^PAR^} are components of the parser. The
23833 numbers correspond to chapters of the Ada Reference Manual. For example,
23834 parsing of select statements can be found in @file{par-ch9.adb}.
23835
23836 @item
23837 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23838 numbers correspond to chapters of the Ada standard. For example, all
23839 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23840 addition, some features of the language require sufficient special processing
23841 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23842 dynamic dispatching, etc.
23843
23844 @item
23845 All files prefixed with @file{^exp^EXP^} perform normalization and
23846 expansion of the intermediate representation (abstract syntax tree, or AST).
23847 these files use the same numbering scheme as the parser and semantics files.
23848 For example, the construction of record initialization procedures is done in
23849 @file{exp_ch3.adb}.
23850
23851 @item
23852 The files prefixed with @file{^bind^BIND^} implement the binder, which
23853 verifies the consistency of the compilation, determines an order of
23854 elaboration, and generates the bind file.
23855
23856 @item
23857 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23858 data structures used by the front-end.
23859
23860 @item
23861 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23862 the abstract syntax tree as produced by the parser.
23863
23864 @item
23865 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23866 all entities, computed during semantic analysis.
23867
23868 @item
23869 Library management issues are dealt with in files with prefix
23870 @file{^lib^LIB^}.
23871
23872 @item
23873 @findex Ada
23874 @cindex Annex A
23875 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23876 defined in Annex A.
23877
23878 @item
23879 @findex Interfaces
23880 @cindex Annex B
23881 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23882 defined in Annex B.
23883
23884 @item
23885 @findex System
23886 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23887 both language-defined children and GNAT run-time routines.
23888
23889 @item
23890 @findex GNAT
23891 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23892 general-purpose packages, fully documented in their specs. All
23893 the other @file{.c} files are modifications of common @command{gcc} files.
23894 @end itemize
23895
23896 @node Getting Internal Debugging Information
23897 @section Getting Internal Debugging Information
23898
23899 @noindent
23900 Most compilers have internal debugging switches and modes. GNAT
23901 does also, except GNAT internal debugging switches and modes are not
23902 secret. A summary and full description of all the compiler and binder
23903 debug flags are in the file @file{debug.adb}. You must obtain the
23904 sources of the compiler to see the full detailed effects of these flags.
23905
23906 The switches that print the source of the program (reconstructed from
23907 the internal tree) are of general interest for user programs, as are the
23908 options to print
23909 the full internal tree, and the entity table (the symbol table
23910 information). The reconstructed source provides a readable version of the
23911 program after the front-end has completed analysis and expansion,
23912 and is useful when studying the performance of specific constructs.
23913 For example, constraint checks are indicated, complex aggregates
23914 are replaced with loops and assignments, and tasking primitives
23915 are replaced with run-time calls.
23916
23917 @node Stack Traceback
23918 @section Stack Traceback
23919 @cindex traceback
23920 @cindex stack traceback
23921 @cindex stack unwinding
23922
23923 @noindent
23924 Traceback is a mechanism to display the sequence of subprogram calls that
23925 leads to a specified execution point in a program. Often (but not always)
23926 the execution point is an instruction at which an exception has been raised.
23927 This mechanism is also known as @i{stack unwinding} because it obtains
23928 its information by scanning the run-time stack and recovering the activation
23929 records of all active subprograms. Stack unwinding is one of the most
23930 important tools for program debugging.
23931
23932 The first entry stored in traceback corresponds to the deepest calling level,
23933 that is to say the subprogram currently executing the instruction
23934 from which we want to obtain the traceback.
23935
23936 Note that there is no runtime performance penalty when stack traceback
23937 is enabled, and no exception is raised during program execution.
23938
23939 @menu
23940 * Non-Symbolic Traceback::
23941 * Symbolic Traceback::
23942 @end menu
23943
23944 @node Non-Symbolic Traceback
23945 @subsection Non-Symbolic Traceback
23946 @cindex traceback, non-symbolic
23947
23948 @noindent
23949 Note: this feature is not supported on all platforms. See
23950 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23951 platforms.
23952
23953 @menu
23954 * Tracebacks From an Unhandled Exception::
23955 * Tracebacks From Exception Occurrences (non-symbolic)::
23956 * Tracebacks From Anywhere in a Program (non-symbolic)::
23957 @end menu
23958
23959 @node Tracebacks From an Unhandled Exception
23960 @subsubsection Tracebacks From an Unhandled Exception
23961
23962 @noindent
23963 A runtime non-symbolic traceback is a list of addresses of call instructions.
23964 To enable this feature you must use the @option{-E}
23965 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23966 of exception information. You can retrieve this information using the
23967 @code{addr2line} tool.
23968
23969 Here is a simple example:
23970
23971 @smallexample @c ada
23972 @cartouche
23973 procedure STB is
23974
23975 procedure P1 is
23976 begin
23977 raise Constraint_Error;
23978 end P1;
23979
23980 procedure P2 is
23981 begin
23982 P1;
23983 end P2;
23984
23985 begin
23986 P2;
23987 end STB;
23988 @end cartouche
23989 @end smallexample
23990
23991 @smallexample
23992 $ gnatmake stb -bargs -E
23993 $ stb
23994
23995 Execution terminated by unhandled exception
23996 Exception name: CONSTRAINT_ERROR
23997 Message: stb.adb:5
23998 Call stack traceback locations:
23999 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24000 @end smallexample
24001
24002 @noindent
24003 As we see the traceback lists a sequence of addresses for the unhandled
24004 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24005 guess that this exception come from procedure P1. To translate these
24006 addresses into the source lines where the calls appear, the
24007 @code{addr2line} tool, described below, is invaluable. The use of this tool
24008 requires the program to be compiled with debug information.
24009
24010 @smallexample
24011 $ gnatmake -g stb -bargs -E
24012 $ stb
24013
24014 Execution terminated by unhandled exception
24015 Exception name: CONSTRAINT_ERROR
24016 Message: stb.adb:5
24017 Call stack traceback locations:
24018 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24019
24020 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24021 0x4011f1 0x77e892a4
24022
24023 00401373 at d:/stb/stb.adb:5
24024 0040138B at d:/stb/stb.adb:10
24025 0040139C at d:/stb/stb.adb:14
24026 00401335 at d:/stb/b~stb.adb:104
24027 004011C4 at /build/@dots{}/crt1.c:200
24028 004011F1 at /build/@dots{}/crt1.c:222
24029 77E892A4 in ?? at ??:0
24030 @end smallexample
24031
24032 @noindent
24033 The @code{addr2line} tool has several other useful options:
24034
24035 @table @code
24036 @item --functions
24037 to get the function name corresponding to any location
24038
24039 @item --demangle=gnat
24040 to use the gnat decoding mode for the function names. Note that
24041 for binutils version 2.9.x the option is simply @option{--demangle}.
24042 @end table
24043
24044 @smallexample
24045 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24046 0x40139c 0x401335 0x4011c4 0x4011f1
24047
24048 00401373 in stb.p1 at d:/stb/stb.adb:5
24049 0040138B in stb.p2 at d:/stb/stb.adb:10
24050 0040139C in stb at d:/stb/stb.adb:14
24051 00401335 in main at d:/stb/b~stb.adb:104
24052 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24053 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24054 @end smallexample
24055
24056 @noindent
24057 From this traceback we can see that the exception was raised in
24058 @file{stb.adb} at line 5, which was reached from a procedure call in
24059 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24060 which contains the call to the main program.
24061 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24062 and the output will vary from platform to platform.
24063
24064 It is also possible to use @code{GDB} with these traceback addresses to debug
24065 the program. For example, we can break at a given code location, as reported
24066 in the stack traceback:
24067
24068 @smallexample
24069 $ gdb -nw stb
24070 @ifclear vms
24071 @noindent
24072 Furthermore, this feature is not implemented inside Windows DLL. Only
24073 the non-symbolic traceback is reported in this case.
24074 @end ifclear
24075
24076 (gdb) break *0x401373
24077 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24078 @end smallexample
24079
24080 @noindent
24081 It is important to note that the stack traceback addresses
24082 do not change when debug information is included. This is particularly useful
24083 because it makes it possible to release software without debug information (to
24084 minimize object size), get a field report that includes a stack traceback
24085 whenever an internal bug occurs, and then be able to retrieve the sequence
24086 of calls with the same program compiled with debug information.
24087
24088 @node Tracebacks From Exception Occurrences (non-symbolic)
24089 @subsubsection Tracebacks From Exception Occurrences
24090
24091 @noindent
24092 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24093 The stack traceback is attached to the exception information string, and can
24094 be retrieved in an exception handler within the Ada program, by means of the
24095 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24096
24097 @smallexample @c ada
24098 with Ada.Text_IO;
24099 with Ada.Exceptions;
24100
24101 procedure STB is
24102
24103 use Ada;
24104 use Ada.Exceptions;
24105
24106 procedure P1 is
24107 K : Positive := 1;
24108 begin
24109 K := K - 1;
24110 exception
24111 when E : others =>
24112 Text_IO.Put_Line (Exception_Information (E));
24113 end P1;
24114
24115 procedure P2 is
24116 begin
24117 P1;
24118 end P2;
24119
24120 begin
24121 P2;
24122 end STB;
24123 @end smallexample
24124
24125 @noindent
24126 This program will output:
24127
24128 @smallexample
24129 $ stb
24130
24131 Exception name: CONSTRAINT_ERROR
24132 Message: stb.adb:12
24133 Call stack traceback locations:
24134 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24135 @end smallexample
24136
24137 @node Tracebacks From Anywhere in a Program (non-symbolic)
24138 @subsubsection Tracebacks From Anywhere in a Program
24139
24140 @noindent
24141 It is also possible to retrieve a stack traceback from anywhere in a
24142 program. For this you need to
24143 use the @code{GNAT.Traceback} API. This package includes a procedure called
24144 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24145 display procedures described below. It is not necessary to use the
24146 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24147 is invoked explicitly.
24148
24149 @noindent
24150 In the following example we compute a traceback at a specific location in
24151 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24152 convert addresses to strings:
24153
24154 @smallexample @c ada
24155 with Ada.Text_IO;
24156 with GNAT.Traceback;
24157 with GNAT.Debug_Utilities;
24158
24159 procedure STB is
24160
24161 use Ada;
24162 use GNAT;
24163 use GNAT.Traceback;
24164
24165 procedure P1 is
24166 TB : Tracebacks_Array (1 .. 10);
24167 -- We are asking for a maximum of 10 stack frames.
24168 Len : Natural;
24169 -- Len will receive the actual number of stack frames returned.
24170 begin
24171 Call_Chain (TB, Len);
24172
24173 Text_IO.Put ("In STB.P1 : ");
24174
24175 for K in 1 .. Len loop
24176 Text_IO.Put (Debug_Utilities.Image (TB (K)));
24177 Text_IO.Put (' ');
24178 end loop;
24179
24180 Text_IO.New_Line;
24181 end P1;
24182
24183 procedure P2 is
24184 begin
24185 P1;
24186 end P2;
24187
24188 begin
24189 P2;
24190 end STB;
24191 @end smallexample
24192
24193 @smallexample
24194 $ gnatmake -g stb
24195 $ stb
24196
24197 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24198 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24199 @end smallexample
24200
24201 @noindent
24202 You can then get further information by invoking the @code{addr2line}
24203 tool as described earlier (note that the hexadecimal addresses
24204 need to be specified in C format, with a leading ``0x'').
24205
24206 @node Symbolic Traceback
24207 @subsection Symbolic Traceback
24208 @cindex traceback, symbolic
24209
24210 @noindent
24211 A symbolic traceback is a stack traceback in which procedure names are
24212 associated with each code location.
24213
24214 @noindent
24215 Note that this feature is not supported on all platforms. See
24216 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24217 list of currently supported platforms.
24218
24219 @noindent
24220 Note that the symbolic traceback requires that the program be compiled
24221 with debug information. If it is not compiled with debug information
24222 only the non-symbolic information will be valid.
24223
24224 @menu
24225 * Tracebacks From Exception Occurrences (symbolic)::
24226 * Tracebacks From Anywhere in a Program (symbolic)::
24227 @end menu
24228
24229 @node Tracebacks From Exception Occurrences (symbolic)
24230 @subsubsection Tracebacks From Exception Occurrences
24231
24232 @smallexample @c ada
24233 with Ada.Text_IO;
24234 with GNAT.Traceback.Symbolic;
24235
24236 procedure STB is
24237
24238 procedure P1 is
24239 begin
24240 raise Constraint_Error;
24241 end P1;
24242
24243 procedure P2 is
24244 begin
24245 P1;
24246 end P2;
24247
24248 procedure P3 is
24249 begin
24250 P2;
24251 end P3;
24252
24253 begin
24254 P3;
24255 exception
24256 when E : others =>
24257 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24258 end STB;
24259 @end smallexample
24260
24261 @smallexample
24262 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24263 $ stb
24264
24265 0040149F in stb.p1 at stb.adb:8
24266 004014B7 in stb.p2 at stb.adb:13
24267 004014CF in stb.p3 at stb.adb:18
24268 004015DD in ada.stb at stb.adb:22
24269 00401461 in main at b~stb.adb:168
24270 004011C4 in __mingw_CRTStartup at crt1.c:200
24271 004011F1 in mainCRTStartup at crt1.c:222
24272 77E892A4 in ?? at ??:0
24273 @end smallexample
24274
24275 @noindent
24276 In the above example the ``.\'' syntax in the @command{gnatmake} command
24277 is currently required by @command{addr2line} for files that are in
24278 the current working directory.
24279 Moreover, the exact sequence of linker options may vary from platform
24280 to platform.
24281 The above @option{-largs} section is for Windows platforms. By contrast,
24282 under Unix there is no need for the @option{-largs} section.
24283 Differences across platforms are due to details of linker implementation.
24284
24285 @node Tracebacks From Anywhere in a Program (symbolic)
24286 @subsubsection Tracebacks From Anywhere in a Program
24287
24288 @noindent
24289 It is possible to get a symbolic stack traceback
24290 from anywhere in a program, just as for non-symbolic tracebacks.
24291 The first step is to obtain a non-symbolic
24292 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24293 information. Here is an example:
24294
24295 @smallexample @c ada
24296 with Ada.Text_IO;
24297 with GNAT.Traceback;
24298 with GNAT.Traceback.Symbolic;
24299
24300 procedure STB is
24301
24302 use Ada;
24303 use GNAT.Traceback;
24304 use GNAT.Traceback.Symbolic;
24305
24306 procedure P1 is
24307 TB : Tracebacks_Array (1 .. 10);
24308 -- We are asking for a maximum of 10 stack frames.
24309 Len : Natural;
24310 -- Len will receive the actual number of stack frames returned.
24311 begin
24312 Call_Chain (TB, Len);
24313 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24314 end P1;
24315
24316 procedure P2 is
24317 begin
24318 P1;
24319 end P2;
24320
24321 begin
24322 P2;
24323 end STB;
24324 @end smallexample
24325
24326 @c ******************************
24327 @ifset vms
24328 @node Compatibility with HP Ada
24329 @chapter Compatibility with HP Ada
24330 @cindex Compatibility
24331
24332 @noindent
24333 @cindex DEC Ada
24334 @cindex HP Ada
24335 @cindex Compatibility between GNAT and HP Ada
24336 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24337 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24338 GNAT is highly compatible
24339 with HP Ada, and it should generally be straightforward to port code
24340 from the HP Ada environment to GNAT. However, there are a few language
24341 and implementation differences of which the user must be aware. These
24342 differences are discussed in this chapter. In
24343 addition, the operating environment and command structure for the
24344 compiler are different, and these differences are also discussed.
24345
24346 For further details on these and other compatibility issues,
24347 see Appendix E of the HP publication
24348 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24349
24350 Except where otherwise indicated, the description of GNAT for OpenVMS
24351 applies to both the Alpha and I64 platforms.
24352
24353 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24354 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24355
24356 The discussion in this chapter addresses specifically the implementation
24357 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24358 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24359 GNAT always follows the Alpha implementation.
24360
24361 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24362 attributes are recognized, although only a subset of them can sensibly
24363 be implemented. The description of pragmas in
24364 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24365 indicates whether or not they are applicable to non-VMS systems.
24366
24367 @menu
24368 * Ada Language Compatibility::
24369 * Differences in the Definition of Package System::
24370 * Language-Related Features::
24371 * The Package STANDARD::
24372 * The Package SYSTEM::
24373 * Tasking and Task-Related Features::
24374 * Pragmas and Pragma-Related Features::
24375 * Library of Predefined Units::
24376 * Bindings::
24377 * Main Program Definition::
24378 * Implementation-Defined Attributes::
24379 * Compiler and Run-Time Interfacing::
24380 * Program Compilation and Library Management::
24381 * Input-Output::
24382 * Implementation Limits::
24383 * Tools and Utilities::
24384 @end menu
24385
24386 @node Ada Language Compatibility
24387 @section Ada Language Compatibility
24388
24389 @noindent
24390 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24391 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24392 with Ada 83, and therefore Ada 83 programs will compile
24393 and run under GNAT with
24394 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24395 provides details on specific incompatibilities.
24396
24397 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24398 as well as the pragma @code{ADA_83}, to force the compiler to
24399 operate in Ada 83 mode. This mode does not guarantee complete
24400 conformance to Ada 83, but in practice is sufficient to
24401 eliminate most sources of incompatibilities.
24402 In particular, it eliminates the recognition of the
24403 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24404 in Ada 83 programs is legal, and handles the cases of packages
24405 with optional bodies, and generics that instantiate unconstrained
24406 types without the use of @code{(<>)}.
24407
24408 @node Differences in the Definition of Package System
24409 @section Differences in the Definition of Package @code{System}
24410
24411 @noindent
24412 An Ada compiler is allowed to add
24413 implementation-dependent declarations to package @code{System}.
24414 In normal mode,
24415 GNAT does not take advantage of this permission, and the version of
24416 @code{System} provided by GNAT exactly matches that defined in the Ada
24417 Reference Manual.
24418
24419 However, HP Ada adds an extensive set of declarations to package
24420 @code{System},
24421 as fully documented in the HP Ada manuals. To minimize changes required
24422 for programs that make use of these extensions, GNAT provides the pragma
24423 @code{Extend_System} for extending the definition of package System. By using:
24424 @cindex pragma @code{Extend_System}
24425 @cindex @code{Extend_System} pragma
24426
24427 @smallexample @c ada
24428 @group
24429 @cartouche
24430 pragma Extend_System (Aux_DEC);
24431 @end cartouche
24432 @end group
24433 @end smallexample
24434
24435 @noindent
24436 the set of definitions in @code{System} is extended to include those in
24437 package @code{System.Aux_DEC}.
24438 @cindex @code{System.Aux_DEC} package
24439 @cindex @code{Aux_DEC} package (child of @code{System})
24440 These definitions are incorporated directly into package @code{System},
24441 as though they had been declared there. For a
24442 list of the declarations added, see the spec of this package,
24443 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24444 @cindex @file{s-auxdec.ads} file
24445 The pragma @code{Extend_System} is a configuration pragma, which means that
24446 it can be placed in the file @file{gnat.adc}, so that it will automatically
24447 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24448 for further details.
24449
24450 An alternative approach that avoids the use of the non-standard
24451 @code{Extend_System} pragma is to add a context clause to the unit that
24452 references these facilities:
24453
24454 @smallexample @c ada
24455 @cartouche
24456 with System.Aux_DEC;
24457 use System.Aux_DEC;
24458 @end cartouche
24459 @end smallexample
24460
24461 @noindent
24462 The effect is not quite semantically identical to incorporating
24463 the declarations directly into package @code{System},
24464 but most programs will not notice a difference
24465 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24466 to reference the entities directly in package @code{System}.
24467 For units containing such references,
24468 the prefixes must either be removed, or the pragma @code{Extend_System}
24469 must be used.
24470
24471 @node Language-Related Features
24472 @section Language-Related Features
24473
24474 @noindent
24475 The following sections highlight differences in types,
24476 representations of types, operations, alignment, and
24477 related topics.
24478
24479 @menu
24480 * Integer Types and Representations::
24481 * Floating-Point Types and Representations::
24482 * Pragmas Float_Representation and Long_Float::
24483 * Fixed-Point Types and Representations::
24484 * Record and Array Component Alignment::
24485 * Address Clauses::
24486 * Other Representation Clauses::
24487 @end menu
24488
24489 @node Integer Types and Representations
24490 @subsection Integer Types and Representations
24491
24492 @noindent
24493 The set of predefined integer types is identical in HP Ada and GNAT.
24494 Furthermore the representation of these integer types is also identical,
24495 including the capability of size clauses forcing biased representation.
24496
24497 In addition,
24498 HP Ada for OpenVMS Alpha systems has defined the
24499 following additional integer types in package @code{System}:
24500
24501 @itemize @bullet
24502
24503 @item
24504 @code{INTEGER_8}
24505
24506 @item
24507 @code{INTEGER_16}
24508
24509 @item
24510 @code{INTEGER_32}
24511
24512 @item
24513 @code{INTEGER_64}
24514
24515 @item
24516 @code{LARGEST_INTEGER}
24517 @end itemize
24518
24519 @noindent
24520 In GNAT, the first four of these types may be obtained from the
24521 standard Ada package @code{Interfaces}.
24522 Alternatively, by use of the pragma @code{Extend_System}, identical
24523 declarations can be referenced directly in package @code{System}.
24524 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24525
24526 @node Floating-Point Types and Representations
24527 @subsection Floating-Point Types and Representations
24528 @cindex Floating-Point types
24529
24530 @noindent
24531 The set of predefined floating-point types is identical in HP Ada and GNAT.
24532 Furthermore the representation of these floating-point
24533 types is also identical. One important difference is that the default
24534 representation for HP Ada is @code{VAX_Float}, but the default representation
24535 for GNAT is IEEE.
24536
24537 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24538 pragma @code{Float_Representation} as described in the HP Ada
24539 documentation.
24540 For example, the declarations:
24541
24542 @smallexample @c ada
24543 @cartouche
24544 type F_Float is digits 6;
24545 pragma Float_Representation (VAX_Float, F_Float);
24546 @end cartouche
24547 @end smallexample
24548
24549 @noindent
24550 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24551 format.
24552 This set of declarations actually appears in @code{System.Aux_DEC},
24553 which contains
24554 the full set of additional floating-point declarations provided in
24555 the HP Ada version of package @code{System}.
24556 This and similar declarations may be accessed in a user program
24557 by using pragma @code{Extend_System}. The use of this
24558 pragma, and the related pragma @code{Long_Float} is described in further
24559 detail in the following section.
24560
24561 @node Pragmas Float_Representation and Long_Float
24562 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24563
24564 @noindent
24565 HP Ada provides the pragma @code{Float_Representation}, which
24566 acts as a program library switch to allow control over
24567 the internal representation chosen for the predefined
24568 floating-point types declared in the package @code{Standard}.
24569 The format of this pragma is as follows:
24570
24571 @smallexample @c ada
24572 @cartouche
24573 pragma Float_Representation(VAX_Float | IEEE_Float);
24574 @end cartouche
24575 @end smallexample
24576
24577 @noindent
24578 This pragma controls the representation of floating-point
24579 types as follows:
24580
24581 @itemize @bullet
24582 @item
24583 @code{VAX_Float} specifies that floating-point
24584 types are represented by default with the VAX system hardware types
24585 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24586 Note that the @code{H-floating}
24587 type was available only on VAX systems, and is not available
24588 in either HP Ada or GNAT.
24589
24590 @item
24591 @code{IEEE_Float} specifies that floating-point
24592 types are represented by default with the IEEE single and
24593 double floating-point types.
24594 @end itemize
24595
24596 @noindent
24597 GNAT provides an identical implementation of the pragma
24598 @code{Float_Representation}, except that it functions as a
24599 configuration pragma. Note that the
24600 notion of configuration pragma corresponds closely to the
24601 HP Ada notion of a program library switch.
24602
24603 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24604 which is different
24605 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24606 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24607 advisable to change the format of numbers passed to standard library
24608 routines, and if necessary explicit type conversions may be needed.
24609
24610 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24611 efficient, and (given that it conforms to an international standard)
24612 potentially more portable.
24613 The situation in which @code{VAX_Float} may be useful is in interfacing
24614 to existing code and data that expect the use of @code{VAX_Float}.
24615 In such a situation use the predefined @code{VAX_Float}
24616 types in package @code{System}, as extended by
24617 @code{Extend_System}. For example, use @code{System.F_Float}
24618 to specify the 32-bit @code{F-Float} format.
24619
24620 @noindent
24621 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24622 to allow control over the internal representation chosen
24623 for the predefined type @code{Long_Float} and for floating-point
24624 type declarations with digits specified in the range 7 .. 15.
24625 The format of this pragma is as follows:
24626
24627 @smallexample @c ada
24628 @cartouche
24629 pragma Long_Float (D_FLOAT | G_FLOAT);
24630 @end cartouche
24631 @end smallexample
24632
24633 @node Fixed-Point Types and Representations
24634 @subsection Fixed-Point Types and Representations
24635
24636 @noindent
24637 On HP Ada for OpenVMS Alpha systems, rounding is
24638 away from zero for both positive and negative numbers.
24639 Therefore, @code{+0.5} rounds to @code{1},
24640 and @code{-0.5} rounds to @code{-1}.
24641
24642 On GNAT the results of operations
24643 on fixed-point types are in accordance with the Ada
24644 rules. In particular, results of operations on decimal
24645 fixed-point types are truncated.
24646
24647 @node Record and Array Component Alignment
24648 @subsection Record and Array Component Alignment
24649
24650 @noindent
24651 On HP Ada for OpenVMS Alpha, all non-composite components
24652 are aligned on natural boundaries. For example, 1-byte
24653 components are aligned on byte boundaries, 2-byte
24654 components on 2-byte boundaries, 4-byte components on 4-byte
24655 byte boundaries, and so on. The OpenVMS Alpha hardware
24656 runs more efficiently with naturally aligned data.
24657
24658 On GNAT, alignment rules are compatible
24659 with HP Ada for OpenVMS Alpha.
24660
24661 @node Address Clauses
24662 @subsection Address Clauses
24663
24664 @noindent
24665 In HP Ada and GNAT, address clauses are supported for
24666 objects and imported subprograms.
24667 The predefined type @code{System.Address} is a private type
24668 in both compilers on Alpha OpenVMS, with the same representation
24669 (it is simply a machine pointer). Addition, subtraction, and comparison
24670 operations are available in the standard Ada package
24671 @code{System.Storage_Elements}, or in package @code{System}
24672 if it is extended to include @code{System.Aux_DEC} using a
24673 pragma @code{Extend_System} as previously described.
24674
24675 Note that code that @code{with}'s both this extended package @code{System}
24676 and the package @code{System.Storage_Elements} should not @code{use}
24677 both packages, or ambiguities will result. In general it is better
24678 not to mix these two sets of facilities. The Ada package was
24679 designed specifically to provide the kind of features that HP Ada
24680 adds directly to package @code{System}.
24681
24682 The type @code{System.Address} is a 64-bit integer type in GNAT for
24683 I64 OpenVMS. For more information,
24684 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24685
24686 GNAT is compatible with HP Ada in its handling of address
24687 clauses, except for some limitations in
24688 the form of address clauses for composite objects with
24689 initialization. Such address clauses are easily replaced
24690 by the use of an explicitly-defined constant as described
24691 in the Ada Reference Manual (13.1(22)). For example, the sequence
24692 of declarations:
24693
24694 @smallexample @c ada
24695 @cartouche
24696 X, Y : Integer := Init_Func;
24697 Q : String (X .. Y) := "abc";
24698 @dots{}
24699 for Q'Address use Compute_Address;
24700 @end cartouche
24701 @end smallexample
24702
24703 @noindent
24704 will be rejected by GNAT, since the address cannot be computed at the time
24705 that @code{Q} is declared. To achieve the intended effect, write instead:
24706
24707 @smallexample @c ada
24708 @group
24709 @cartouche
24710 X, Y : Integer := Init_Func;
24711 Q_Address : constant Address := Compute_Address;
24712 Q : String (X .. Y) := "abc";
24713 @dots{}
24714 for Q'Address use Q_Address;
24715 @end cartouche
24716 @end group
24717 @end smallexample
24718
24719 @noindent
24720 which will be accepted by GNAT (and other Ada compilers), and is also
24721 compatible with Ada 83. A fuller description of the restrictions
24722 on address specifications is found in @ref{Top, GNAT Reference Manual,
24723 About This Guide, gnat_rm, GNAT Reference Manual}.
24724
24725 @node Other Representation Clauses
24726 @subsection Other Representation Clauses
24727
24728 @noindent
24729 GNAT implements in a compatible manner all the representation
24730 clauses supported by HP Ada. In addition, GNAT
24731 implements the representation clause forms that were introduced in Ada 95,
24732 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24733
24734 @node The Package STANDARD
24735 @section The Package @code{STANDARD}
24736
24737 @noindent
24738 The package @code{STANDARD}, as implemented by HP Ada, is fully
24739 described in the @cite{Ada Reference Manual} and in the
24740 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24741 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24742
24743 In addition, HP Ada supports the Latin-1 character set in
24744 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24745 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24746 the type @code{WIDE_CHARACTER}.
24747
24748 The floating-point types supported by GNAT are those
24749 supported by HP Ada, but the defaults are different, and are controlled by
24750 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24751
24752 @node The Package SYSTEM
24753 @section The Package @code{SYSTEM}
24754
24755 @noindent
24756 HP Ada provides a specific version of the package
24757 @code{SYSTEM} for each platform on which the language is implemented.
24758 For the complete spec of the package @code{SYSTEM}, see
24759 Appendix F of the @cite{HP Ada Language Reference Manual}.
24760
24761 On HP Ada, the package @code{SYSTEM} includes the following conversion
24762 functions:
24763 @itemize @bullet
24764 @item @code{TO_ADDRESS(INTEGER)}
24765
24766 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24767
24768 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24769
24770 @item @code{TO_INTEGER(ADDRESS)}
24771
24772 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24773
24774 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24775 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24776 @end itemize
24777
24778 @noindent
24779 By default, GNAT supplies a version of @code{SYSTEM} that matches
24780 the definition given in the @cite{Ada Reference Manual}.
24781 This
24782 is a subset of the HP system definitions, which is as
24783 close as possible to the original definitions. The only difference
24784 is that the definition of @code{SYSTEM_NAME} is different:
24785
24786 @smallexample @c ada
24787 @cartouche
24788 type Name is (SYSTEM_NAME_GNAT);
24789 System_Name : constant Name := SYSTEM_NAME_GNAT;
24790 @end cartouche
24791 @end smallexample
24792
24793 @noindent
24794 Also, GNAT adds the Ada declarations for
24795 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24796
24797 However, the use of the following pragma causes GNAT
24798 to extend the definition of package @code{SYSTEM} so that it
24799 encompasses the full set of HP-specific extensions,
24800 including the functions listed above:
24801
24802 @smallexample @c ada
24803 @cartouche
24804 pragma Extend_System (Aux_DEC);
24805 @end cartouche
24806 @end smallexample
24807
24808 @noindent
24809 The pragma @code{Extend_System} is a configuration pragma that
24810 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24811 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24812
24813 HP Ada does not allow the recompilation of the package
24814 @code{SYSTEM}. Instead HP Ada provides several pragmas
24815 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24816 to modify values in the package @code{SYSTEM}.
24817 On OpenVMS Alpha systems, the pragma
24818 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24819 its single argument.
24820
24821 GNAT does permit the recompilation of package @code{SYSTEM} using
24822 the special switch @option{-gnatg}, and this switch can be used if
24823 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24824 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24825 or @code{MEMORY_SIZE} by any other means.
24826
24827 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24828 enumeration literal @code{SYSTEM_NAME_GNAT}.
24829
24830 The definitions provided by the use of
24831
24832 @smallexample @c ada
24833 pragma Extend_System (AUX_Dec);
24834 @end smallexample
24835
24836 @noindent
24837 are virtually identical to those provided by the HP Ada 83 package
24838 @code{SYSTEM}. One important difference is that the name of the
24839 @code{TO_ADDRESS}
24840 function for type @code{UNSIGNED_LONGWORD} is changed to
24841 @code{TO_ADDRESS_LONG}.
24842 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24843 discussion of why this change was necessary.
24844
24845 @noindent
24846 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24847 is in fact
24848 an extension to Ada 83 not strictly compatible with the reference manual.
24849 GNAT, in order to be exactly compatible with the standard,
24850 does not provide this capability. In HP Ada 83, the
24851 point of this definition is to deal with a call like:
24852
24853 @smallexample @c ada
24854 TO_ADDRESS (16#12777#);
24855 @end smallexample
24856
24857 @noindent
24858 Normally, according to Ada 83 semantics, one would expect this to be
24859 ambiguous, since it matches both the @code{INTEGER} and
24860 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24861 However, in HP Ada 83, there is no ambiguity, since the
24862 definition using @i{universal_integer} takes precedence.
24863
24864 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24865 it is
24866 not possible to be 100% compatible. Since there are many programs using
24867 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24868 GNAT was
24869 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24870 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24871
24872 @smallexample @c ada
24873 function To_Address (X : Integer) return Address;
24874 pragma Pure_Function (To_Address);
24875
24876 function To_Address_Long (X : Unsigned_Longword) return Address;
24877 pragma Pure_Function (To_Address_Long);
24878 @end smallexample
24879
24880 @noindent
24881 This means that programs using @code{TO_ADDRESS} for
24882 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24883
24884 @node Tasking and Task-Related Features
24885 @section Tasking and Task-Related Features
24886
24887 @noindent
24888 This section compares the treatment of tasking in GNAT
24889 and in HP Ada for OpenVMS Alpha.
24890 The GNAT description applies to both Alpha and I64 OpenVMS.
24891 For detailed information on tasking in
24892 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24893 relevant run-time reference manual.
24894
24895 @menu
24896 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24897 * Assigning Task IDs::
24898 * Task IDs and Delays::
24899 * Task-Related Pragmas::
24900 * Scheduling and Task Priority::
24901 * The Task Stack::
24902 * External Interrupts::
24903 @end menu
24904
24905 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24906 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24907
24908 @noindent
24909 On OpenVMS Alpha systems, each Ada task (except a passive
24910 task) is implemented as a single stream of execution
24911 that is created and managed by the kernel. On these
24912 systems, HP Ada tasking support is based on DECthreads,
24913 an implementation of the POSIX standard for threads.
24914
24915 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24916 code that calls DECthreads routines can be used together.
24917 The interaction between Ada tasks and DECthreads routines
24918 can have some benefits. For example when on OpenVMS Alpha,
24919 HP Ada can call C code that is already threaded.
24920
24921 GNAT uses the facilities of DECthreads,
24922 and Ada tasks are mapped to threads.
24923
24924 @node Assigning Task IDs
24925 @subsection Assigning Task IDs
24926
24927 @noindent
24928 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24929 the environment task that executes the main program. On
24930 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24931 that have been created but are not yet activated.
24932
24933 On OpenVMS Alpha systems, task IDs are assigned at
24934 activation. On GNAT systems, task IDs are also assigned at
24935 task creation but do not have the same form or values as
24936 task ID values in HP Ada. There is no null task, and the
24937 environment task does not have a specific task ID value.
24938
24939 @node Task IDs and Delays
24940 @subsection Task IDs and Delays
24941
24942 @noindent
24943 On OpenVMS Alpha systems, tasking delays are implemented
24944 using Timer System Services. The Task ID is used for the
24945 identification of the timer request (the @code{REQIDT} parameter).
24946 If Timers are used in the application take care not to use
24947 @code{0} for the identification, because cancelling such a timer
24948 will cancel all timers and may lead to unpredictable results.
24949
24950 @node Task-Related Pragmas
24951 @subsection Task-Related Pragmas
24952
24953 @noindent
24954 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24955 specification of the size of the guard area for a task
24956 stack. (The guard area forms an area of memory that has no
24957 read or write access and thus helps in the detection of
24958 stack overflow.) On OpenVMS Alpha systems, if the pragma
24959 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24960 area is created. In the absence of a pragma @code{TASK_STORAGE},
24961 a default guard area is created.
24962
24963 GNAT supplies the following task-related pragmas:
24964
24965 @itemize @bullet
24966 @item @code{TASK_INFO}
24967
24968 This pragma appears within a task definition and
24969 applies to the task in which it appears. The argument
24970 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24971
24972 @item @code{TASK_STORAGE}
24973
24974 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24975 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24976 @code{SUPPRESS}, and @code{VOLATILE}.
24977 @end itemize
24978 @node Scheduling and Task Priority
24979 @subsection Scheduling and Task Priority
24980
24981 @noindent
24982 HP Ada implements the Ada language requirement that
24983 when two tasks are eligible for execution and they have
24984 different priorities, the lower priority task does not
24985 execute while the higher priority task is waiting. The HP
24986 Ada Run-Time Library keeps a task running until either the
24987 task is suspended or a higher priority task becomes ready.
24988
24989 On OpenVMS Alpha systems, the default strategy is round-
24990 robin with preemption. Tasks of equal priority take turns
24991 at the processor. A task is run for a certain period of
24992 time and then placed at the tail of the ready queue for
24993 its priority level.
24994
24995 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24996 which can be used to enable or disable round-robin
24997 scheduling of tasks with the same priority.
24998 See the relevant HP Ada run-time reference manual for
24999 information on using the pragmas to control HP Ada task
25000 scheduling.
25001
25002 GNAT follows the scheduling rules of Annex D (Real-Time
25003 Annex) of the @cite{Ada Reference Manual}. In general, this
25004 scheduling strategy is fully compatible with HP Ada
25005 although it provides some additional constraints (as
25006 fully documented in Annex D).
25007 GNAT implements time slicing control in a manner compatible with
25008 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25009 are identical to the HP Ada 83 pragma of the same name.
25010 Note that it is not possible to mix GNAT tasking and
25011 HP Ada 83 tasking in the same program, since the two run-time
25012 libraries are not compatible.
25013
25014 @node The Task Stack
25015 @subsection The Task Stack
25016
25017 @noindent
25018 In HP Ada, a task stack is allocated each time a
25019 non-passive task is activated. As soon as the task is
25020 terminated, the storage for the task stack is deallocated.
25021 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25022 a default stack size is used. Also, regardless of the size
25023 specified, some additional space is allocated for task
25024 management purposes. On OpenVMS Alpha systems, at least
25025 one page is allocated.
25026
25027 GNAT handles task stacks in a similar manner. In accordance with
25028 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25029 an alternative method for controlling the task stack size.
25030 The specification of the attribute @code{T'STORAGE_SIZE} is also
25031 supported in a manner compatible with HP Ada.
25032
25033 @node External Interrupts
25034 @subsection External Interrupts
25035
25036 @noindent
25037 On HP Ada, external interrupts can be associated with task entries.
25038 GNAT is compatible with HP Ada in its handling of external interrupts.
25039
25040 @node Pragmas and Pragma-Related Features
25041 @section Pragmas and Pragma-Related Features
25042
25043 @noindent
25044 Both HP Ada and GNAT supply all language-defined pragmas
25045 as specified by the Ada 83 standard. GNAT also supplies all
25046 language-defined pragmas introduced by Ada 95 and Ada 2005.
25047 In addition, GNAT implements the implementation-defined pragmas
25048 from HP Ada 83.
25049
25050 @itemize @bullet
25051 @item @code{AST_ENTRY}
25052
25053 @item @code{COMMON_OBJECT}
25054
25055 @item @code{COMPONENT_ALIGNMENT}
25056
25057 @item @code{EXPORT_EXCEPTION}
25058
25059 @item @code{EXPORT_FUNCTION}
25060
25061 @item @code{EXPORT_OBJECT}
25062
25063 @item @code{EXPORT_PROCEDURE}
25064
25065 @item @code{EXPORT_VALUED_PROCEDURE}
25066
25067 @item @code{FLOAT_REPRESENTATION}
25068
25069 @item @code{IDENT}
25070
25071 @item @code{IMPORT_EXCEPTION}
25072
25073 @item @code{IMPORT_FUNCTION}
25074
25075 @item @code{IMPORT_OBJECT}
25076
25077 @item @code{IMPORT_PROCEDURE}
25078
25079 @item @code{IMPORT_VALUED_PROCEDURE}
25080
25081 @item @code{INLINE_GENERIC}
25082
25083 @item @code{INTERFACE_NAME}
25084
25085 @item @code{LONG_FLOAT}
25086
25087 @item @code{MAIN_STORAGE}
25088
25089 @item @code{PASSIVE}
25090
25091 @item @code{PSECT_OBJECT}
25092
25093 @item @code{SHARE_GENERIC}
25094
25095 @item @code{SUPPRESS_ALL}
25096
25097 @item @code{TASK_STORAGE}
25098
25099 @item @code{TIME_SLICE}
25100
25101 @item @code{TITLE}
25102 @end itemize
25103
25104 @noindent
25105 These pragmas are all fully implemented, with the exception of @code{TITLE},
25106 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25107 recognized, but which have no
25108 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25109 use of Ada protected objects. In GNAT, all generics are inlined.
25110
25111 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25112 a separate subprogram specification which must appear before the
25113 subprogram body.
25114
25115 GNAT also supplies a number of implementation-defined pragmas as follows:
25116 @itemize @bullet
25117 @item @code{ABORT_DEFER}
25118
25119 @item @code{ADA_83}
25120
25121 @item @code{ADA_95}
25122
25123 @item @code{ADA_05}
25124
25125 @item @code{ANNOTATE}
25126
25127 @item @code{ASSERT}
25128
25129 @item @code{C_PASS_BY_COPY}
25130
25131 @item @code{CPP_CLASS}
25132
25133 @item @code{CPP_CONSTRUCTOR}
25134
25135 @item @code{CPP_DESTRUCTOR}
25136
25137 @item @code{DEBUG}
25138
25139 @item @code{EXTEND_SYSTEM}
25140
25141 @item @code{LINKER_ALIAS}
25142
25143 @item @code{LINKER_SECTION}
25144
25145 @item @code{MACHINE_ATTRIBUTE}
25146
25147 @item @code{NO_RETURN}
25148
25149 @item @code{PURE_FUNCTION}
25150
25151 @item @code{SOURCE_FILE_NAME}
25152
25153 @item @code{SOURCE_REFERENCE}
25154
25155 @item @code{TASK_INFO}
25156
25157 @item @code{UNCHECKED_UNION}
25158
25159 @item @code{UNIMPLEMENTED_UNIT}
25160
25161 @item @code{UNIVERSAL_DATA}
25162
25163 @item @code{UNSUPPRESS}
25164
25165 @item @code{WARNINGS}
25166
25167 @item @code{WEAK_EXTERNAL}
25168 @end itemize
25169
25170 @noindent
25171 For full details on these GNAT implementation-defined pragmas,
25172 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25173 Manual}.
25174
25175 @menu
25176 * Restrictions on the Pragma INLINE::
25177 * Restrictions on the Pragma INTERFACE::
25178 * Restrictions on the Pragma SYSTEM_NAME::
25179 @end menu
25180
25181 @node Restrictions on the Pragma INLINE
25182 @subsection Restrictions on Pragma @code{INLINE}
25183
25184 @noindent
25185 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25186 @itemize @bullet
25187 @item Parameters cannot have a task type.
25188
25189 @item Function results cannot be task types, unconstrained
25190 array types, or unconstrained types with discriminants.
25191
25192 @item Bodies cannot declare the following:
25193 @itemize @bullet
25194 @item Subprogram body or stub (imported subprogram is allowed)
25195
25196 @item Tasks
25197
25198 @item Generic declarations
25199
25200 @item Instantiations
25201
25202 @item Exceptions
25203
25204 @item Access types (types derived from access types allowed)
25205
25206 @item Array or record types
25207
25208 @item Dependent tasks
25209
25210 @item Direct recursive calls of subprogram or containing
25211 subprogram, directly or via a renaming
25212
25213 @end itemize
25214 @end itemize
25215
25216 @noindent
25217 In GNAT, the only restriction on pragma @code{INLINE} is that the
25218 body must occur before the call if both are in the same
25219 unit, and the size must be appropriately small. There are
25220 no other specific restrictions which cause subprograms to
25221 be incapable of being inlined.
25222
25223 @node Restrictions on the Pragma INTERFACE
25224 @subsection Restrictions on Pragma @code{INTERFACE}
25225
25226 @noindent
25227 The following restrictions on pragma @code{INTERFACE}
25228 are enforced by both HP Ada and GNAT:
25229 @itemize @bullet
25230 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
25231 Default is the default on OpenVMS Alpha systems.
25232
25233 @item Parameter passing: Language specifies default
25234 mechanisms but can be overridden with an @code{EXPORT} pragma.
25235
25236 @itemize @bullet
25237 @item Ada: Use internal Ada rules.
25238
25239 @item Bliss, C: Parameters must be mode @code{in}; cannot be
25240 record or task type. Result cannot be a string, an
25241 array, or a record.
25242
25243 @item Fortran: Parameters cannot have a task type. Result cannot
25244 be a string, an array, or a record.
25245 @end itemize
25246 @end itemize
25247
25248 @noindent
25249 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25250 record parameters for all languages.
25251
25252 @node Restrictions on the Pragma SYSTEM_NAME
25253 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
25254
25255 @noindent
25256 For HP Ada for OpenVMS Alpha, the enumeration literal
25257 for the type @code{NAME} is @code{OPENVMS_AXP}.
25258 In GNAT, the enumeration
25259 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25260
25261 @node Library of Predefined Units
25262 @section Library of Predefined Units
25263
25264 @noindent
25265 A library of predefined units is provided as part of the
25266 HP Ada and GNAT implementations. HP Ada does not provide
25267 the package @code{MACHINE_CODE} but instead recommends importing
25268 assembler code.
25269
25270 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25271 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25272 version.
25273 The HP Ada Predefined Library units are modified to remove post-Ada 83
25274 incompatibilities and to make them interoperable with GNAT
25275 (@pxref{Changes to DECLIB}, for details).
25276 The units are located in the @file{DECLIB} directory.
25277
25278 The GNAT RTL is contained in
25279 the @file{ADALIB} directory, and
25280 the default search path is set up to find @code{DECLIB} units in preference
25281 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25282 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25283
25284 @menu
25285 * Changes to DECLIB::
25286 @end menu
25287
25288 @node Changes to DECLIB
25289 @subsection Changes to @code{DECLIB}
25290
25291 @noindent
25292 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25293 compatibility are minor and include the following:
25294
25295 @itemize @bullet
25296 @item Adjusting the location of pragmas and record representation
25297 clauses to obey Ada 95 (and thus Ada 2005) rules
25298
25299 @item Adding the proper notation to generic formal parameters
25300 that take unconstrained types in instantiation
25301
25302 @item Adding pragma @code{ELABORATE_BODY} to package specs
25303 that have package bodies not otherwise allowed
25304
25305 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25306 ``@code{PROTECTD}''.
25307 Currently these are found only in the @code{STARLET} package spec.
25308
25309 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25310 where the address size is constrained to 32 bits.
25311 @end itemize
25312
25313 @noindent
25314 None of the above changes is visible to users.
25315
25316 @node Bindings
25317 @section Bindings
25318
25319 @noindent
25320 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25321 @itemize @bullet
25322
25323 @item Command Language Interpreter (CLI interface)
25324
25325 @item DECtalk Run-Time Library (DTK interface)
25326
25327 @item Librarian utility routines (LBR interface)
25328
25329 @item General Purpose Run-Time Library (LIB interface)
25330
25331 @item Math Run-Time Library (MTH interface)
25332
25333 @item National Character Set Run-Time Library (NCS interface)
25334
25335 @item Compiled Code Support Run-Time Library (OTS interface)
25336
25337 @item Parallel Processing Run-Time Library (PPL interface)
25338
25339 @item Screen Management Run-Time Library (SMG interface)
25340
25341 @item Sort Run-Time Library (SOR interface)
25342
25343 @item String Run-Time Library (STR interface)
25344
25345 @item STARLET System Library
25346 @findex Starlet
25347
25348 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
25349
25350 @item X Windows Toolkit (XT interface)
25351
25352 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
25353 @end itemize
25354
25355 @noindent
25356 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25357 directory, on both the Alpha and I64 OpenVMS platforms.
25358
25359 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25360 in the
25361 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25362 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25363 @code{Xt}, and @code{X_Lib}
25364 causing the default X/Motif sharable image libraries to be linked in. This
25365 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25366 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25367
25368 It may be necessary to edit these options files to update or correct the
25369 library names if, for example, the newer X/Motif bindings from
25370 @file{ADA$EXAMPLES}
25371 had been (previous to installing GNAT) copied and renamed to supersede the
25372 default @file{ADA$PREDEFINED} versions.
25373
25374 @menu
25375 * Shared Libraries and Options Files::
25376 * Interfaces to C::
25377 @end menu
25378
25379 @node Shared Libraries and Options Files
25380 @subsection Shared Libraries and Options Files
25381
25382 @noindent
25383 When using the HP Ada
25384 predefined X and Motif bindings, the linking with their sharable images is
25385 done automatically by @command{GNAT LINK}.
25386 When using other X and Motif bindings, you need
25387 to add the corresponding sharable images to the command line for
25388 @code{GNAT LINK}. When linking with shared libraries, or with
25389 @file{.OPT} files, you must
25390 also add them to the command line for @command{GNAT LINK}.
25391
25392 A shared library to be used with GNAT is built in the same way as other
25393 libraries under VMS. The VMS Link command can be used in standard fashion.
25394
25395 @node Interfaces to C
25396 @subsection Interfaces to C
25397
25398 @noindent
25399 HP Ada
25400 provides the following Ada types and operations:
25401
25402 @itemize @bullet
25403 @item C types package (@code{C_TYPES})
25404
25405 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25406
25407 @item Other_types (@code{SHORT_INT})
25408 @end itemize
25409
25410 @noindent
25411 Interfacing to C with GNAT, you can use the above approach
25412 described for HP Ada or the facilities of Annex B of
25413 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25414 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25415 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25416
25417 The @option{-gnatF} qualifier forces default and explicit
25418 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25419 to be uppercased for compatibility with the default behavior
25420 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25421
25422 @node Main Program Definition
25423 @section Main Program Definition
25424
25425 @noindent
25426 The following section discusses differences in the
25427 definition of main programs on HP Ada and GNAT.
25428 On HP Ada, main programs are defined to meet the
25429 following conditions:
25430 @itemize @bullet
25431 @item Procedure with no formal parameters (returns @code{0} upon
25432 normal completion)
25433
25434 @item Procedure with no formal parameters (returns @code{42} when
25435 an unhandled exception is raised)
25436
25437 @item Function with no formal parameters whose returned value
25438 is of a discrete type
25439
25440 @item Procedure with one @code{out} formal of a discrete type for
25441 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25442
25443 @end itemize
25444
25445 @noindent
25446 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25447 a main function or main procedure returns a discrete
25448 value whose size is less than 64 bits (32 on VAX systems),
25449 the value is zero- or sign-extended as appropriate.
25450 On GNAT, main programs are defined as follows:
25451 @itemize @bullet
25452 @item Must be a non-generic, parameterless subprogram that
25453 is either a procedure or function returning an Ada
25454 @code{STANDARD.INTEGER} (the predefined type)
25455
25456 @item Cannot be a generic subprogram or an instantiation of a
25457 generic subprogram
25458 @end itemize
25459
25460 @node Implementation-Defined Attributes
25461 @section Implementation-Defined Attributes
25462
25463 @noindent
25464 GNAT provides all HP Ada implementation-defined
25465 attributes.
25466
25467 @node Compiler and Run-Time Interfacing
25468 @section Compiler and Run-Time Interfacing
25469
25470 @noindent
25471 HP Ada provides the following qualifiers to pass options to the linker
25472 (ACS LINK):
25473 @itemize @bullet
25474 @item @option{/WAIT} and @option{/SUBMIT}
25475
25476 @item @option{/COMMAND}
25477
25478 @item @option{/@r{[}NO@r{]}MAP}
25479
25480 @item @option{/OUTPUT=@var{file-spec}}
25481
25482 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25483 @end itemize
25484
25485 @noindent
25486 To pass options to the linker, GNAT provides the following
25487 switches:
25488
25489 @itemize @bullet
25490 @item @option{/EXECUTABLE=@var{exec-name}}
25491
25492 @item @option{/VERBOSE}
25493
25494 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25495 @end itemize
25496
25497 @noindent
25498 For more information on these switches, see
25499 @ref{Switches for gnatlink}.
25500 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25501 to control optimization. HP Ada also supplies the
25502 following pragmas:
25503 @itemize @bullet
25504 @item @code{OPTIMIZE}
25505
25506 @item @code{INLINE}
25507
25508 @item @code{INLINE_GENERIC}
25509
25510 @item @code{SUPPRESS_ALL}
25511
25512 @item @code{PASSIVE}
25513 @end itemize
25514
25515 @noindent
25516 In GNAT, optimization is controlled strictly by command
25517 line parameters, as described in the corresponding section of this guide.
25518 The HP pragmas for control of optimization are
25519 recognized but ignored.
25520
25521 Note that in GNAT, the default is optimization off, whereas in HP Ada
25522 the default is that optimization is turned on.
25523
25524 @node Program Compilation and Library Management
25525 @section Program Compilation and Library Management
25526
25527 @noindent
25528 HP Ada and GNAT provide a comparable set of commands to
25529 build programs. HP Ada also provides a program library,
25530 which is a concept that does not exist on GNAT. Instead,
25531 GNAT provides directories of sources that are compiled as
25532 needed.
25533
25534 The following table summarizes
25535 the HP Ada commands and provides
25536 equivalent GNAT commands. In this table, some GNAT
25537 equivalents reflect the fact that GNAT does not use the
25538 concept of a program library. Instead, it uses a model
25539 in which collections of source and object files are used
25540 in a manner consistent with other languages like C and
25541 Fortran. Therefore, standard system file commands are used
25542 to manipulate these elements. Those GNAT commands are marked with
25543 an asterisk.
25544 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25545
25546 @need 1500
25547 @multitable @columnfractions .35 .65
25548
25549 @item @emph{HP Ada Command}
25550 @tab @emph{GNAT Equivalent / Description}
25551
25552 @item @command{ADA}
25553 @tab @command{GNAT COMPILE}@*
25554 Invokes the compiler to compile one or more Ada source files.
25555
25556 @item @command{ACS ATTACH}@*
25557 @tab [No equivalent]@*
25558 Switches control of terminal from current process running the program
25559 library manager.
25560
25561 @item @command{ACS CHECK}
25562 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25563 Forms the execution closure of one
25564 or more compiled units and checks completeness and currency.
25565
25566 @item @command{ACS COMPILE}
25567 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25568 Forms the execution closure of one or
25569 more specified units, checks completeness and currency,
25570 identifies units that have revised source files, compiles same,
25571 and recompiles units that are or will become obsolete.
25572 Also completes incomplete generic instantiations.
25573
25574 @item @command{ACS COPY FOREIGN}
25575 @tab Copy (*)@*
25576 Copies a foreign object file into the program library as a
25577 library unit body.
25578
25579 @item @command{ACS COPY UNIT}
25580 @tab Copy (*)@*
25581 Copies a compiled unit from one program library to another.
25582
25583 @item @command{ACS CREATE LIBRARY}
25584 @tab Create /directory (*)@*
25585 Creates a program library.
25586
25587 @item @command{ACS CREATE SUBLIBRARY}
25588 @tab Create /directory (*)@*
25589 Creates a program sublibrary.
25590
25591 @item @command{ACS DELETE LIBRARY}
25592 @tab @*
25593 Deletes a program library and its contents.
25594
25595 @item @command{ACS DELETE SUBLIBRARY}
25596 @tab @*
25597 Deletes a program sublibrary and its contents.
25598
25599 @item @command{ACS DELETE UNIT}
25600 @tab Delete file (*)@*
25601 On OpenVMS systems, deletes one or more compiled units from
25602 the current program library.
25603
25604 @item @command{ACS DIRECTORY}
25605 @tab Directory (*)@*
25606 On OpenVMS systems, lists units contained in the current
25607 program library.
25608
25609 @item @command{ACS ENTER FOREIGN}
25610 @tab Copy (*)@*
25611 Allows the import of a foreign body as an Ada library
25612 spec and enters a reference to a pointer.
25613
25614 @item @command{ACS ENTER UNIT}
25615 @tab Copy (*)@*
25616 Enters a reference (pointer) from the current program library to
25617 a unit compiled into another program library.
25618
25619 @item @command{ACS EXIT}
25620 @tab [No equivalent]@*
25621 Exits from the program library manager.
25622
25623 @item @command{ACS EXPORT}
25624 @tab Copy (*)@*
25625 Creates an object file that contains system-specific object code
25626 for one or more units. With GNAT, object files can simply be copied
25627 into the desired directory.
25628
25629 @item @command{ACS EXTRACT SOURCE}
25630 @tab Copy (*)@*
25631 Allows access to the copied source file for each Ada compilation unit
25632
25633 @item @command{ACS HELP}
25634 @tab @command{HELP GNAT}@*
25635 Provides online help.
25636
25637 @item @command{ACS LINK}
25638 @tab @command{GNAT LINK}@*
25639 Links an object file containing Ada units into an executable file.
25640
25641 @item @command{ACS LOAD}
25642 @tab Copy (*)@*
25643 Loads (partially compiles) Ada units into the program library.
25644 Allows loading a program from a collection of files into a library
25645 without knowing the relationship among units.
25646
25647 @item @command{ACS MERGE}
25648 @tab Copy (*)@*
25649 Merges into the current program library, one or more units from
25650 another library where they were modified.
25651
25652 @item @command{ACS RECOMPILE}
25653 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25654 Recompiles from external or copied source files any obsolete
25655 unit in the closure. Also, completes any incomplete generic
25656 instantiations.
25657
25658 @item @command{ACS REENTER}
25659 @tab @command{GNAT MAKE}@*
25660 Reenters current references to units compiled after last entered
25661 with the @command{ACS ENTER UNIT} command.
25662
25663 @item @command{ACS SET LIBRARY}
25664 @tab Set default (*)@*
25665 Defines a program library to be the compilation context as well
25666 as the target library for compiler output and commands in general.
25667
25668 @item @command{ACS SET PRAGMA}
25669 @tab Edit @file{gnat.adc} (*)@*
25670 Redefines specified values of the library characteristics
25671 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25672 and @code{Float_Representation}.
25673
25674 @item @command{ACS SET SOURCE}
25675 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25676 Defines the source file search list for the @command{ACS COMPILE} command.
25677
25678 @item @command{ACS SHOW LIBRARY}
25679 @tab Directory (*)@*
25680 Lists information about one or more program libraries.
25681
25682 @item @command{ACS SHOW PROGRAM}
25683 @tab [No equivalent]@*
25684 Lists information about the execution closure of one or
25685 more units in the program library.
25686
25687 @item @command{ACS SHOW SOURCE}
25688 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25689 Shows the source file search used when compiling units.
25690
25691 @item @command{ACS SHOW VERSION}
25692 @tab Compile with @option{VERBOSE} option
25693 Displays the version number of the compiler and program library
25694 manager used.
25695
25696 @item @command{ACS SPAWN}
25697 @tab [No equivalent]@*
25698 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25699 command).
25700
25701 @item @command{ACS VERIFY}
25702 @tab [No equivalent]@*
25703 Performs a series of consistency checks on a program library to
25704 determine whether the library structure and library files are in
25705 valid form.
25706 @end multitable
25707
25708 @noindent
25709
25710 @node Input-Output
25711 @section Input-Output
25712
25713 @noindent
25714 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25715 Management Services (RMS) to perform operations on
25716 external files.
25717
25718 @noindent
25719 HP Ada and GNAT predefine an identical set of input-
25720 output packages. To make the use of the
25721 generic @code{TEXT_IO} operations more convenient, HP Ada
25722 provides predefined library packages that instantiate the
25723 integer and floating-point operations for the predefined
25724 integer and floating-point types as shown in the following table.
25725
25726 @multitable @columnfractions .45 .55
25727 @item @emph{Package Name} @tab Instantiation
25728
25729 @item @code{INTEGER_TEXT_IO}
25730 @tab @code{INTEGER_IO(INTEGER)}
25731
25732 @item @code{SHORT_INTEGER_TEXT_IO}
25733 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25734
25735 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25736 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25737
25738 @item @code{FLOAT_TEXT_IO}
25739 @tab @code{FLOAT_IO(FLOAT)}
25740
25741 @item @code{LONG_FLOAT_TEXT_IO}
25742 @tab @code{FLOAT_IO(LONG_FLOAT)}
25743 @end multitable
25744
25745 @noindent
25746 The HP Ada predefined packages and their operations
25747 are implemented using OpenVMS Alpha files and input-output
25748 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25749 Familiarity with the following is recommended:
25750 @itemize @bullet
25751 @item RMS file organizations and access methods
25752
25753 @item OpenVMS file specifications and directories
25754
25755 @item OpenVMS File Definition Language (FDL)
25756 @end itemize
25757
25758 @noindent
25759 GNAT provides I/O facilities that are completely
25760 compatible with HP Ada. The distribution includes the
25761 standard HP Ada versions of all I/O packages, operating
25762 in a manner compatible with HP Ada. In particular, the
25763 following packages are by default the HP Ada (Ada 83)
25764 versions of these packages rather than the renamings
25765 suggested in Annex J of the Ada Reference Manual:
25766 @itemize @bullet
25767 @item @code{TEXT_IO}
25768
25769 @item @code{SEQUENTIAL_IO}
25770
25771 @item @code{DIRECT_IO}
25772 @end itemize
25773
25774 @noindent
25775 The use of the standard child package syntax (for
25776 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25777 packages.
25778 GNAT provides HP-compatible predefined instantiations
25779 of the @code{TEXT_IO} packages, and also
25780 provides the standard predefined instantiations required
25781 by the @cite{Ada Reference Manual}.
25782
25783 For further information on how GNAT interfaces to the file
25784 system or how I/O is implemented in programs written in
25785 mixed languages, see @ref{Implementation of the Standard I/O,,,
25786 gnat_rm, GNAT Reference Manual}.
25787 This chapter covers the following:
25788 @itemize @bullet
25789 @item Standard I/O packages
25790
25791 @item @code{FORM} strings
25792
25793 @item @code{ADA.DIRECT_IO}
25794
25795 @item @code{ADA.SEQUENTIAL_IO}
25796
25797 @item @code{ADA.TEXT_IO}
25798
25799 @item Stream pointer positioning
25800
25801 @item Reading and writing non-regular files
25802
25803 @item @code{GET_IMMEDIATE}
25804
25805 @item Treating @code{TEXT_IO} files as streams
25806
25807 @item Shared files
25808
25809 @item Open modes
25810 @end itemize
25811
25812 @node Implementation Limits
25813 @section Implementation Limits
25814
25815 @noindent
25816 The following table lists implementation limits for HP Ada
25817 and GNAT systems.
25818 @multitable @columnfractions .60 .20 .20
25819 @sp 1
25820 @item @emph{Compilation Parameter}
25821 @tab @emph{HP Ada}
25822 @tab @emph{GNAT}
25823 @sp 1
25824
25825 @item In a subprogram or entry declaration, maximum number of
25826 formal parameters that are of an unconstrained record type
25827 @tab 32
25828 @tab No set limit
25829 @sp 1
25830
25831 @item Maximum identifier length (number of characters)
25832 @tab 255
25833 @tab 32766
25834 @sp 1
25835
25836 @item Maximum number of characters in a source line
25837 @tab 255
25838 @tab 32766
25839 @sp 1
25840
25841 @item Maximum collection size (number of bytes)
25842 @tab 2**31-1
25843 @tab 2**31-1
25844 @sp 1
25845
25846 @item Maximum number of discriminants for a record type
25847 @tab 245
25848 @tab No set limit
25849 @sp 1
25850
25851 @item Maximum number of formal parameters in an entry or
25852 subprogram declaration
25853 @tab 246
25854 @tab No set limit
25855 @sp 1
25856
25857 @item Maximum number of dimensions in an array type
25858 @tab 255
25859 @tab No set limit
25860 @sp 1
25861
25862 @item Maximum number of library units and subunits in a compilation.
25863 @tab 4095
25864 @tab No set limit
25865 @sp 1
25866
25867 @item Maximum number of library units and subunits in an execution.
25868 @tab 16383
25869 @tab No set limit
25870 @sp 1
25871
25872 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25873 or @code{PSECT_OBJECT}
25874 @tab 32757
25875 @tab No set limit
25876 @sp 1
25877
25878 @item Maximum number of enumeration literals in an enumeration type
25879 definition
25880 @tab 65535
25881 @tab No set limit
25882 @sp 1
25883
25884 @item Maximum number of lines in a source file
25885 @tab 65534
25886 @tab No set limit
25887 @sp 1
25888
25889 @item Maximum number of bits in any object
25890 @tab 2**31-1
25891 @tab 2**31-1
25892 @sp 1
25893
25894 @item Maximum size of the static portion of a stack frame (approximate)
25895 @tab 2**31-1
25896 @tab 2**31-1
25897 @end multitable
25898
25899 @node Tools and Utilities
25900 @section Tools and Utilities
25901
25902 @noindent
25903 The following table lists some of the OpenVMS development tools
25904 available for HP Ada, and the corresponding tools for
25905 use with @value{EDITION} on Alpha and I64 platforms.
25906 Aside from the debugger, all the OpenVMS tools identified are part
25907 of the DECset package.
25908
25909 @iftex
25910 @c Specify table in TeX since Texinfo does a poor job
25911 @tex
25912 \smallskip
25913 \smallskip
25914 \settabs\+Language-Sensitive Editor\quad
25915 &Product with HP Ada\quad
25916 &\cr
25917 \+\it Tool
25918 &\it Product with HP Ada
25919 & \it Product with GNAT Pro\cr
25920 \smallskip
25921 \+Code Management System
25922 &HP CMS
25923 & HP CMS\cr
25924 \smallskip
25925 \+Language-Sensitive Editor
25926 &HP LSE
25927 & emacs or HP LSE (Alpha)\cr
25928 \+
25929 &
25930 & HP LSE (I64)\cr
25931 \smallskip
25932 \+Debugger
25933 &OpenVMS Debug
25934 & gdb (Alpha),\cr
25935 \+
25936 &
25937 & OpenVMS Debug (I64)\cr
25938 \smallskip
25939 \+Source Code Analyzer /
25940 &HP SCA
25941 & GNAT XREF\cr
25942 \+Cross Referencer
25943 &
25944 &\cr
25945 \smallskip
25946 \+Test Manager
25947 &HP Digital Test
25948 & HP DTM\cr
25949 \+
25950 &Manager (DTM)
25951 &\cr
25952 \smallskip
25953 \+Performance and
25954 & HP PCA
25955 & HP PCA\cr
25956 \+Coverage Analyzer
25957 &
25958 &\cr
25959 \smallskip
25960 \+Module Management
25961 & HP MMS
25962 & Not applicable\cr
25963 \+ System
25964 &
25965 &\cr
25966 \smallskip
25967 \smallskip
25968 @end tex
25969 @end iftex
25970
25971 @ifnottex
25972 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
25973 @c the TeX version above for the printed version
25974 @flushleft
25975 @c @multitable @columnfractions .3 .4 .4
25976 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25977 @item @i{Tool}
25978 @tab @i{Tool with HP Ada}
25979 @tab @i{Tool with @value{EDITION}}
25980 @item Code Management@*System
25981 @tab HP CMS
25982 @tab HP CMS
25983 @item Language-Sensitive@*Editor
25984 @tab HP LSE
25985 @tab emacs or HP LSE (Alpha)
25986 @item
25987 @tab
25988 @tab HP LSE (I64)
25989 @item Debugger
25990 @tab OpenVMS Debug
25991 @tab gdb (Alpha),
25992 @item
25993 @tab
25994 @tab OpenVMS Debug (I64)
25995 @item Source Code Analyzer /@*Cross Referencer
25996 @tab HP SCA
25997 @tab GNAT XREF
25998 @item Test Manager
25999 @tab HP Digital Test@*Manager (DTM)
26000 @tab HP DTM
26001 @item Performance and@*Coverage Analyzer
26002 @tab HP PCA
26003 @tab HP PCA
26004 @item Module Management@*System
26005 @tab HP MMS
26006 @tab Not applicable
26007 @end multitable
26008 @end flushleft
26009 @end ifnottex
26010
26011 @end ifset
26012
26013 @c **************************************
26014 @node Platform-Specific Information for the Run-Time Libraries
26015 @appendix Platform-Specific Information for the Run-Time Libraries
26016 @cindex Tasking and threads libraries
26017 @cindex Threads libraries and tasking
26018 @cindex Run-time libraries (platform-specific information)
26019
26020 @noindent
26021 The GNAT run-time implementation may vary with respect to both the
26022 underlying threads library and the exception handling scheme.
26023 For threads support, one or more of the following are supplied:
26024 @itemize @bullet
26025 @item @b{native threads library}, a binding to the thread package from
26026 the underlying operating system
26027
26028 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26029 POSIX thread package
26030 @end itemize
26031
26032 @noindent
26033 For exception handling, either or both of two models are supplied:
26034 @itemize @bullet
26035 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26036 Most programs should experience a substantial speed improvement by
26037 being compiled with a ZCX run-time.
26038 This is especially true for
26039 tasking applications or applications with many exception handlers.}
26040 @cindex Zero-Cost Exceptions
26041 @cindex ZCX (Zero-Cost Exceptions)
26042 which uses binder-generated tables that
26043 are interrogated at run time to locate a handler
26044
26045 @item @b{setjmp / longjmp} (``SJLJ''),
26046 @cindex setjmp/longjmp Exception Model
26047 @cindex SJLJ (setjmp/longjmp Exception Model)
26048 which uses dynamically-set data to establish
26049 the set of handlers
26050 @end itemize
26051
26052 @noindent
26053 This appendix summarizes which combinations of threads and exception support
26054 are supplied on various GNAT platforms.
26055 It then shows how to select a particular library either
26056 permanently or temporarily,
26057 explains the properties of (and tradeoffs among) the various threads
26058 libraries, and provides some additional
26059 information about several specific platforms.
26060
26061 @menu
26062 * Summary of Run-Time Configurations::
26063 * Specifying a Run-Time Library::
26064 * Choosing the Scheduling Policy::
26065 * Solaris-Specific Considerations::
26066 * Linux-Specific Considerations::
26067 * AIX-Specific Considerations::
26068 * Irix-Specific Considerations::
26069 * RTX-Specific Considerations::
26070 @end menu
26071
26072 @node Summary of Run-Time Configurations
26073 @section Summary of Run-Time Configurations
26074
26075 @multitable @columnfractions .30 .70
26076 @item @b{alpha-openvms}
26077 @item @code{@ @ }@i{rts-native (default)}
26078 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26079 @item @code{@ @ @ @ }Exceptions @tab ZCX
26080 @*
26081 @item @b{alpha-tru64}
26082 @item @code{@ @ }@i{rts-native (default)}
26083 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26084 @item @code{@ @ @ @ }Exceptions @tab ZCX
26085 @*
26086 @item @code{@ @ }@i{rts-sjlj}
26087 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
26088 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26089 @*
26090 @item @b{ia64-hp_linux}
26091 @item @code{@ @ }@i{rts-native (default)}
26092 @item @code{@ @ @ @ }Tasking @tab pthread library
26093 @item @code{@ @ @ @ }Exceptions @tab ZCX
26094 @*
26095 @item @b{ia64-hpux}
26096 @item @code{@ @ }@i{rts-native (default)}
26097 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26098 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26099 @*
26100 @item @b{ia64-openvms}
26101 @item @code{@ @ }@i{rts-native (default)}
26102 @item @code{@ @ @ @ }Tasking @tab native VMS threads
26103 @item @code{@ @ @ @ }Exceptions @tab ZCX
26104 @*
26105 @item @b{ia64-sgi_linux}
26106 @item @code{@ @ }@i{rts-native (default)}
26107 @item @code{@ @ @ @ }Tasking @tab pthread library
26108 @item @code{@ @ @ @ }Exceptions @tab ZCX
26109 @*
26110 @item @b{mips-irix}
26111 @item @code{@ @ }@i{rts-native (default)}
26112 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
26113 @item @code{@ @ @ @ }Exceptions @tab ZCX
26114 @*
26115 @item @b{pa-hpux}
26116 @item @code{@ @ }@i{rts-native (default)}
26117 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26118 @item @code{@ @ @ @ }Exceptions @tab ZCX
26119 @*
26120 @item @code{@ @ }@i{rts-sjlj}
26121 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
26122 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26123 @*
26124 @item @b{ppc-aix}
26125 @item @code{@ @ }@i{rts-native (default)}
26126 @item @code{@ @ @ @ }Tasking @tab native AIX threads
26127 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26128 @*
26129 @item @b{ppc-darwin}
26130 @item @code{@ @ }@i{rts-native (default)}
26131 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
26132 @item @code{@ @ @ @ }Exceptions @tab ZCX
26133 @*
26134 @item @b{sparc-solaris} @tab
26135 @item @code{@ @ }@i{rts-native (default)}
26136 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26137 @item @code{@ @ @ @ }Exceptions @tab ZCX
26138 @*
26139 @item @code{@ @ }@i{rts-pthread}
26140 @item @code{@ @ @ @ }Tasking @tab pthread library
26141 @item @code{@ @ @ @ }Exceptions @tab ZCX
26142 @*
26143 @item @code{@ @ }@i{rts-sjlj}
26144 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26145 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26146 @*
26147 @item @b{sparc64-solaris} @tab
26148 @item @code{@ @ }@i{rts-native (default)}
26149 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
26150 @item @code{@ @ @ @ }Exceptions @tab ZCX
26151 @*
26152 @item @b{x86-linux}
26153 @item @code{@ @ }@i{rts-native (default)}
26154 @item @code{@ @ @ @ }Tasking @tab pthread library
26155 @item @code{@ @ @ @ }Exceptions @tab ZCX
26156 @*
26157 @item @code{@ @ }@i{rts-sjlj}
26158 @item @code{@ @ @ @ }Tasking @tab pthread library
26159 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26160 @*
26161 @item @b{x86-lynx}
26162 @item @code{@ @ }@i{rts-native (default)}
26163 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
26164 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26165 @*
26166 @item @b{x86-solaris}
26167 @item @code{@ @ }@i{rts-native (default)}
26168 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
26169 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26170 @*
26171 @item @b{x86-windows}
26172 @item @code{@ @ }@i{rts-native (default)}
26173 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26174 @item @code{@ @ @ @ }Exceptions @tab ZCX
26175 @*
26176 @item @code{@ @ }@i{rts-sjlj (default)}
26177 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
26178 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26179 @*
26180 @item @b{x86-windows-rtx}
26181 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26182 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
26183 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26184 @*
26185 @item @code{@ @ }@i{rts-rtx-w32}
26186 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
26187 @item @code{@ @ @ @ }Exceptions @tab ZCX
26188 @*
26189 @item @b{x86_64-linux}
26190 @item @code{@ @ }@i{rts-native (default)}
26191 @item @code{@ @ @ @ }Tasking @tab pthread library
26192 @item @code{@ @ @ @ }Exceptions @tab ZCX
26193 @*
26194 @item @code{@ @ }@i{rts-sjlj}
26195 @item @code{@ @ @ @ }Tasking @tab pthread library
26196 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26197 @*
26198 @end multitable
26199
26200 @node Specifying a Run-Time Library
26201 @section Specifying a Run-Time Library
26202
26203 @noindent
26204 The @file{adainclude} subdirectory containing the sources of the GNAT
26205 run-time library, and the @file{adalib} subdirectory containing the
26206 @file{ALI} files and the static and/or shared GNAT library, are located
26207 in the gcc target-dependent area:
26208
26209 @smallexample
26210 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26211 @end smallexample
26212
26213 @noindent
26214 As indicated above, on some platforms several run-time libraries are supplied.
26215 These libraries are installed in the target dependent area and
26216 contain a complete source and binary subdirectory. The detailed description
26217 below explains the differences between the different libraries in terms of
26218 their thread support.
26219
26220 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26221 This default run time is selected by the means of soft links.
26222 For example on x86-linux:
26223
26224 @smallexample
26225 @group
26226 $(target-dir)
26227 |
26228 +--- adainclude----------+
26229 | |
26230 +--- adalib-----------+ |
26231 | | |
26232 +--- rts-native | |
26233 | | | |
26234 | +--- adainclude <---+
26235 | | |
26236 | +--- adalib <----+
26237 |
26238 +--- rts-sjlj
26239 |
26240 +--- adainclude
26241 |
26242 +--- adalib
26243 @end group
26244 @end smallexample
26245
26246 @noindent
26247 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26248 these soft links can be modified with the following commands:
26249
26250 @smallexample
26251 $ cd $target
26252 $ rm -f adainclude adalib
26253 $ ln -s rts-sjlj/adainclude adainclude
26254 $ ln -s rts-sjlj/adalib adalib
26255 @end smallexample
26256
26257 @noindent
26258 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26259 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26260 @file{$target/ada_object_path}.
26261
26262 Selecting another run-time library temporarily can be
26263 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26264 @cindex @option{--RTS} option
26265
26266 @node Choosing the Scheduling Policy
26267 @section Choosing the Scheduling Policy
26268
26269 @noindent
26270 When using a POSIX threads implementation, you have a choice of several
26271 scheduling policies: @code{SCHED_FIFO},
26272 @cindex @code{SCHED_FIFO} scheduling policy
26273 @code{SCHED_RR}
26274 @cindex @code{SCHED_RR} scheduling policy
26275 and @code{SCHED_OTHER}.
26276 @cindex @code{SCHED_OTHER} scheduling policy
26277 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26278 or @code{SCHED_RR} requires special (e.g., root) privileges.
26279
26280 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26281 @code{SCHED_FIFO},
26282 @cindex @code{SCHED_FIFO} scheduling policy
26283 you can use one of the following:
26284
26285 @itemize @bullet
26286 @item
26287 @code{pragma Time_Slice (0.0)}
26288 @cindex pragma Time_Slice
26289 @item
26290 the corresponding binder option @option{-T0}
26291 @cindex @option{-T0} option
26292 @item
26293 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26294 @cindex pragma Task_Dispatching_Policy
26295 @end itemize
26296
26297 @noindent
26298 To specify @code{SCHED_RR},
26299 @cindex @code{SCHED_RR} scheduling policy
26300 you should use @code{pragma Time_Slice} with a
26301 value greater than @code{0.0}, or else use the corresponding @option{-T}
26302 binder option.
26303
26304 @node Solaris-Specific Considerations
26305 @section Solaris-Specific Considerations
26306 @cindex Solaris Sparc threads libraries
26307
26308 @noindent
26309 This section addresses some topics related to the various threads libraries
26310 on Sparc Solaris.
26311
26312 @menu
26313 * Solaris Threads Issues::
26314 @end menu
26315
26316 @node Solaris Threads Issues
26317 @subsection Solaris Threads Issues
26318
26319 @noindent
26320 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26321 library based on POSIX threads --- @emph{rts-pthread}.
26322 @cindex rts-pthread threads library
26323 This run-time library has the advantage of being mostly shared across all
26324 POSIX-compliant thread implementations, and it also provides under
26325 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26326 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26327 and @code{PTHREAD_PRIO_PROTECT}
26328 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26329 semantics that can be selected using the predefined pragma
26330 @code{Locking_Policy}
26331 @cindex pragma Locking_Policy (under rts-pthread)
26332 with respectively
26333 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26334 @cindex @code{Inheritance_Locking} (under rts-pthread)
26335 @cindex @code{Ceiling_Locking} (under rts-pthread)
26336
26337 As explained above, the native run-time library is based on the Solaris thread
26338 library (@code{libthread}) and is the default library.
26339
26340 When the Solaris threads library is used (this is the default), programs
26341 compiled with GNAT can automatically take advantage of
26342 and can thus execute on multiple processors.
26343 The user can alternatively specify a processor on which the program should run
26344 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26345 is made by
26346 setting the environment variable @env{GNAT_PROCESSOR}
26347 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26348 to one of the following:
26349
26350 @table @code
26351 @item -2
26352 Use the default configuration (run the program on all
26353 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26354 unset
26355
26356 @item -1
26357 Let the run-time implementation choose one processor and run the program on
26358 that processor
26359
26360 @item 0 .. Last_Proc
26361 Run the program on the specified processor.
26362 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26363 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26364 @end table
26365
26366 @node Linux-Specific Considerations
26367 @section Linux-Specific Considerations
26368 @cindex Linux threads libraries
26369
26370 @noindent
26371 On GNU/Linux without NPTL support (usually system with GNU C Library
26372 older than 2.3), the signal model is not POSIX compliant, which means
26373 that to send a signal to the process, you need to send the signal to all
26374 threads, e.g.@: by using @code{killpg()}.
26375
26376 @node AIX-Specific Considerations
26377 @section AIX-Specific Considerations
26378 @cindex AIX resolver library
26379
26380 @noindent
26381 On AIX, the resolver library initializes some internal structure on
26382 the first call to @code{get*by*} functions, which are used to implement
26383 @code{GNAT.Sockets.Get_Host_By_Name} and
26384 @code{GNAT.Sockets.Get_Host_By_Address}.
26385 If such initialization occurs within an Ada task, and the stack size for
26386 the task is the default size, a stack overflow may occur.
26387
26388 To avoid this overflow, the user should either ensure that the first call
26389 to @code{GNAT.Sockets.Get_Host_By_Name} or
26390 @code{GNAT.Sockets.Get_Host_By_Addrss}
26391 occurs in the environment task, or use @code{pragma Storage_Size} to
26392 specify a sufficiently large size for the stack of the task that contains
26393 this call.
26394
26395 @node Irix-Specific Considerations
26396 @section Irix-Specific Considerations
26397 @cindex Irix libraries
26398
26399 @noindent
26400 The GCC support libraries coming with the Irix compiler have moved to
26401 their canonical place with respect to the general Irix ABI related
26402 conventions. Running applications built with the default shared GNAT
26403 run-time now requires the LD_LIBRARY_PATH environment variable to
26404 include this location. A possible way to achieve this is to issue the
26405 following command line on a bash prompt:
26406
26407 @smallexample
26408 @group
26409 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26410 @end group
26411 @end smallexample
26412
26413 @node RTX-Specific Considerations
26414 @section RTX-Specific Considerations
26415 @cindex RTX libraries
26416
26417 @noindent
26418 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26419 API. Applications can be built to work in two different modes:
26420
26421 @itemize @bullet
26422 @item
26423 Windows executables that run in Ring 3 to utilize memory protection
26424 (@emph{rts-rtx-w32}).
26425
26426 @item
26427 Real-time subsystem (RTSS) executables that run in Ring 0, where
26428 performance can be optimized with RTSS applications taking precedent
26429 over all Windows applications (@emph{rts-rtx-rtss}).
26430
26431 @end itemize
26432
26433 @c *******************************
26434 @node Example of Binder Output File
26435 @appendix Example of Binder Output File
26436
26437 @noindent
26438 This Appendix displays the source code for @command{gnatbind}'s output
26439 file generated for a simple ``Hello World'' program.
26440 Comments have been added for clarification purposes.
26441
26442 @smallexample @c adanocomment
26443 @iftex
26444 @leftskip=0cm
26445 @end iftex
26446 -- The package is called Ada_Main unless this name is actually used
26447 -- as a unit name in the partition, in which case some other unique
26448 -- name is used.
26449
26450 with System;
26451 package ada_main is
26452
26453 Elab_Final_Code : Integer;
26454 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26455
26456 -- The main program saves the parameters (argument count,
26457 -- argument values, environment pointer) in global variables
26458 -- for later access by other units including
26459 -- Ada.Command_Line.
26460
26461 gnat_argc : Integer;
26462 gnat_argv : System.Address;
26463 gnat_envp : System.Address;
26464
26465 -- The actual variables are stored in a library routine. This
26466 -- is useful for some shared library situations, where there
26467 -- are problems if variables are not in the library.
26468
26469 pragma Import (C, gnat_argc);
26470 pragma Import (C, gnat_argv);
26471 pragma Import (C, gnat_envp);
26472
26473 -- The exit status is similarly an external location
26474
26475 gnat_exit_status : Integer;
26476 pragma Import (C, gnat_exit_status);
26477
26478 GNAT_Version : constant String :=
26479 "GNAT Version: 6.0.0w (20061115)";
26480 pragma Export (C, GNAT_Version, "__gnat_version");
26481
26482 -- This is the generated adafinal routine that performs
26483 -- finalization at the end of execution. In the case where
26484 -- Ada is the main program, this main program makes a call
26485 -- to adafinal at program termination.
26486
26487 procedure adafinal;
26488 pragma Export (C, adafinal, "adafinal");
26489
26490 -- This is the generated adainit routine that performs
26491 -- initialization at the start of execution. In the case
26492 -- where Ada is the main program, this main program makes
26493 -- a call to adainit at program startup.
26494
26495 procedure adainit;
26496 pragma Export (C, adainit, "adainit");
26497
26498 -- This routine is called at the start of execution. It is
26499 -- a dummy routine that is used by the debugger to breakpoint
26500 -- at the start of execution.
26501
26502 procedure Break_Start;
26503 pragma Import (C, Break_Start, "__gnat_break_start");
26504
26505 -- This is the actual generated main program (it would be
26506 -- suppressed if the no main program switch were used). As
26507 -- required by standard system conventions, this program has
26508 -- the external name main.
26509
26510 function main
26511 (argc : Integer;
26512 argv : System.Address;
26513 envp : System.Address)
26514 return Integer;
26515 pragma Export (C, main, "main");
26516
26517 -- The following set of constants give the version
26518 -- identification values for every unit in the bound
26519 -- partition. This identification is computed from all
26520 -- dependent semantic units, and corresponds to the
26521 -- string that would be returned by use of the
26522 -- Body_Version or Version attributes.
26523
26524 type Version_32 is mod 2 ** 32;
26525 u00001 : constant Version_32 := 16#7880BEB3#;
26526 u00002 : constant Version_32 := 16#0D24CBD0#;
26527 u00003 : constant Version_32 := 16#3283DBEB#;
26528 u00004 : constant Version_32 := 16#2359F9ED#;
26529 u00005 : constant Version_32 := 16#664FB847#;
26530 u00006 : constant Version_32 := 16#68E803DF#;
26531 u00007 : constant Version_32 := 16#5572E604#;
26532 u00008 : constant Version_32 := 16#46B173D8#;
26533 u00009 : constant Version_32 := 16#156A40CF#;
26534 u00010 : constant Version_32 := 16#033DABE0#;
26535 u00011 : constant Version_32 := 16#6AB38FEA#;
26536 u00012 : constant Version_32 := 16#22B6217D#;
26537 u00013 : constant Version_32 := 16#68A22947#;
26538 u00014 : constant Version_32 := 16#18CC4A56#;
26539 u00015 : constant Version_32 := 16#08258E1B#;
26540 u00016 : constant Version_32 := 16#367D5222#;
26541 u00017 : constant Version_32 := 16#20C9ECA4#;
26542 u00018 : constant Version_32 := 16#50D32CB6#;
26543 u00019 : constant Version_32 := 16#39A8BB77#;
26544 u00020 : constant Version_32 := 16#5CF8FA2B#;
26545 u00021 : constant Version_32 := 16#2F1EB794#;
26546 u00022 : constant Version_32 := 16#31AB6444#;
26547 u00023 : constant Version_32 := 16#1574B6E9#;
26548 u00024 : constant Version_32 := 16#5109C189#;
26549 u00025 : constant Version_32 := 16#56D770CD#;
26550 u00026 : constant Version_32 := 16#02F9DE3D#;
26551 u00027 : constant Version_32 := 16#08AB6B2C#;
26552 u00028 : constant Version_32 := 16#3FA37670#;
26553 u00029 : constant Version_32 := 16#476457A0#;
26554 u00030 : constant Version_32 := 16#731E1B6E#;
26555 u00031 : constant Version_32 := 16#23C2E789#;
26556 u00032 : constant Version_32 := 16#0F1BD6A1#;
26557 u00033 : constant Version_32 := 16#7C25DE96#;
26558 u00034 : constant Version_32 := 16#39ADFFA2#;
26559 u00035 : constant Version_32 := 16#571DE3E7#;
26560 u00036 : constant Version_32 := 16#5EB646AB#;
26561 u00037 : constant Version_32 := 16#4249379B#;
26562 u00038 : constant Version_32 := 16#0357E00A#;
26563 u00039 : constant Version_32 := 16#3784FB72#;
26564 u00040 : constant Version_32 := 16#2E723019#;
26565 u00041 : constant Version_32 := 16#623358EA#;
26566 u00042 : constant Version_32 := 16#107F9465#;
26567 u00043 : constant Version_32 := 16#6843F68A#;
26568 u00044 : constant Version_32 := 16#63305874#;
26569 u00045 : constant Version_32 := 16#31E56CE1#;
26570 u00046 : constant Version_32 := 16#02917970#;
26571 u00047 : constant Version_32 := 16#6CCBA70E#;
26572 u00048 : constant Version_32 := 16#41CD4204#;
26573 u00049 : constant Version_32 := 16#572E3F58#;
26574 u00050 : constant Version_32 := 16#20729FF5#;
26575 u00051 : constant Version_32 := 16#1D4F93E8#;
26576 u00052 : constant Version_32 := 16#30B2EC3D#;
26577 u00053 : constant Version_32 := 16#34054F96#;
26578 u00054 : constant Version_32 := 16#5A199860#;
26579 u00055 : constant Version_32 := 16#0E7F912B#;
26580 u00056 : constant Version_32 := 16#5760634A#;
26581 u00057 : constant Version_32 := 16#5D851835#;
26582
26583 -- The following Export pragmas export the version numbers
26584 -- with symbolic names ending in B (for body) or S
26585 -- (for spec) so that they can be located in a link. The
26586 -- information provided here is sufficient to track down
26587 -- the exact versions of units used in a given build.
26588
26589 pragma Export (C, u00001, "helloB");
26590 pragma Export (C, u00002, "system__standard_libraryB");
26591 pragma Export (C, u00003, "system__standard_libraryS");
26592 pragma Export (C, u00004, "adaS");
26593 pragma Export (C, u00005, "ada__text_ioB");
26594 pragma Export (C, u00006, "ada__text_ioS");
26595 pragma Export (C, u00007, "ada__exceptionsB");
26596 pragma Export (C, u00008, "ada__exceptionsS");
26597 pragma Export (C, u00009, "gnatS");
26598 pragma Export (C, u00010, "gnat__heap_sort_aB");
26599 pragma Export (C, u00011, "gnat__heap_sort_aS");
26600 pragma Export (C, u00012, "systemS");
26601 pragma Export (C, u00013, "system__exception_tableB");
26602 pragma Export (C, u00014, "system__exception_tableS");
26603 pragma Export (C, u00015, "gnat__htableB");
26604 pragma Export (C, u00016, "gnat__htableS");
26605 pragma Export (C, u00017, "system__exceptionsS");
26606 pragma Export (C, u00018, "system__machine_state_operationsB");
26607 pragma Export (C, u00019, "system__machine_state_operationsS");
26608 pragma Export (C, u00020, "system__machine_codeS");
26609 pragma Export (C, u00021, "system__storage_elementsB");
26610 pragma Export (C, u00022, "system__storage_elementsS");
26611 pragma Export (C, u00023, "system__secondary_stackB");
26612 pragma Export (C, u00024, "system__secondary_stackS");
26613 pragma Export (C, u00025, "system__parametersB");
26614 pragma Export (C, u00026, "system__parametersS");
26615 pragma Export (C, u00027, "system__soft_linksB");
26616 pragma Export (C, u00028, "system__soft_linksS");
26617 pragma Export (C, u00029, "system__stack_checkingB");
26618 pragma Export (C, u00030, "system__stack_checkingS");
26619 pragma Export (C, u00031, "system__tracebackB");
26620 pragma Export (C, u00032, "system__tracebackS");
26621 pragma Export (C, u00033, "ada__streamsS");
26622 pragma Export (C, u00034, "ada__tagsB");
26623 pragma Export (C, u00035, "ada__tagsS");
26624 pragma Export (C, u00036, "system__string_opsB");
26625 pragma Export (C, u00037, "system__string_opsS");
26626 pragma Export (C, u00038, "interfacesS");
26627 pragma Export (C, u00039, "interfaces__c_streamsB");
26628 pragma Export (C, u00040, "interfaces__c_streamsS");
26629 pragma Export (C, u00041, "system__file_ioB");
26630 pragma Export (C, u00042, "system__file_ioS");
26631 pragma Export (C, u00043, "ada__finalizationB");
26632 pragma Export (C, u00044, "ada__finalizationS");
26633 pragma Export (C, u00045, "system__finalization_rootB");
26634 pragma Export (C, u00046, "system__finalization_rootS");
26635 pragma Export (C, u00047, "system__finalization_implementationB");
26636 pragma Export (C, u00048, "system__finalization_implementationS");
26637 pragma Export (C, u00049, "system__string_ops_concat_3B");
26638 pragma Export (C, u00050, "system__string_ops_concat_3S");
26639 pragma Export (C, u00051, "system__stream_attributesB");
26640 pragma Export (C, u00052, "system__stream_attributesS");
26641 pragma Export (C, u00053, "ada__io_exceptionsS");
26642 pragma Export (C, u00054, "system__unsigned_typesS");
26643 pragma Export (C, u00055, "system__file_control_blockS");
26644 pragma Export (C, u00056, "ada__finalization__list_controllerB");
26645 pragma Export (C, u00057, "ada__finalization__list_controllerS");
26646
26647 -- BEGIN ELABORATION ORDER
26648 -- ada (spec)
26649 -- gnat (spec)
26650 -- gnat.heap_sort_a (spec)
26651 -- gnat.heap_sort_a (body)
26652 -- gnat.htable (spec)
26653 -- gnat.htable (body)
26654 -- interfaces (spec)
26655 -- system (spec)
26656 -- system.machine_code (spec)
26657 -- system.parameters (spec)
26658 -- system.parameters (body)
26659 -- interfaces.c_streams (spec)
26660 -- interfaces.c_streams (body)
26661 -- system.standard_library (spec)
26662 -- ada.exceptions (spec)
26663 -- system.exception_table (spec)
26664 -- system.exception_table (body)
26665 -- ada.io_exceptions (spec)
26666 -- system.exceptions (spec)
26667 -- system.storage_elements (spec)
26668 -- system.storage_elements (body)
26669 -- system.machine_state_operations (spec)
26670 -- system.machine_state_operations (body)
26671 -- system.secondary_stack (spec)
26672 -- system.stack_checking (spec)
26673 -- system.soft_links (spec)
26674 -- system.soft_links (body)
26675 -- system.stack_checking (body)
26676 -- system.secondary_stack (body)
26677 -- system.standard_library (body)
26678 -- system.string_ops (spec)
26679 -- system.string_ops (body)
26680 -- ada.tags (spec)
26681 -- ada.tags (body)
26682 -- ada.streams (spec)
26683 -- system.finalization_root (spec)
26684 -- system.finalization_root (body)
26685 -- system.string_ops_concat_3 (spec)
26686 -- system.string_ops_concat_3 (body)
26687 -- system.traceback (spec)
26688 -- system.traceback (body)
26689 -- ada.exceptions (body)
26690 -- system.unsigned_types (spec)
26691 -- system.stream_attributes (spec)
26692 -- system.stream_attributes (body)
26693 -- system.finalization_implementation (spec)
26694 -- system.finalization_implementation (body)
26695 -- ada.finalization (spec)
26696 -- ada.finalization (body)
26697 -- ada.finalization.list_controller (spec)
26698 -- ada.finalization.list_controller (body)
26699 -- system.file_control_block (spec)
26700 -- system.file_io (spec)
26701 -- system.file_io (body)
26702 -- ada.text_io (spec)
26703 -- ada.text_io (body)
26704 -- hello (body)
26705 -- END ELABORATION ORDER
26706
26707 end ada_main;
26708
26709 -- The following source file name pragmas allow the generated file
26710 -- names to be unique for different main programs. They are needed
26711 -- since the package name will always be Ada_Main.
26712
26713 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26714 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26715
26716 -- Generated package body for Ada_Main starts here
26717
26718 package body ada_main is
26719
26720 -- The actual finalization is performed by calling the
26721 -- library routine in System.Standard_Library.Adafinal
26722
26723 procedure Do_Finalize;
26724 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26725
26726 -------------
26727 -- adainit --
26728 -------------
26729
26730 @findex adainit
26731 procedure adainit is
26732
26733 -- These booleans are set to True once the associated unit has
26734 -- been elaborated. It is also used to avoid elaborating the
26735 -- same unit twice.
26736
26737 E040 : Boolean;
26738 pragma Import (Ada, E040, "interfaces__c_streams_E");
26739
26740 E008 : Boolean;
26741 pragma Import (Ada, E008, "ada__exceptions_E");
26742
26743 E014 : Boolean;
26744 pragma Import (Ada, E014, "system__exception_table_E");
26745
26746 E053 : Boolean;
26747 pragma Import (Ada, E053, "ada__io_exceptions_E");
26748
26749 E017 : Boolean;
26750 pragma Import (Ada, E017, "system__exceptions_E");
26751
26752 E024 : Boolean;
26753 pragma Import (Ada, E024, "system__secondary_stack_E");
26754
26755 E030 : Boolean;
26756 pragma Import (Ada, E030, "system__stack_checking_E");
26757
26758 E028 : Boolean;
26759 pragma Import (Ada, E028, "system__soft_links_E");
26760
26761 E035 : Boolean;
26762 pragma Import (Ada, E035, "ada__tags_E");
26763
26764 E033 : Boolean;
26765 pragma Import (Ada, E033, "ada__streams_E");
26766
26767 E046 : Boolean;
26768 pragma Import (Ada, E046, "system__finalization_root_E");
26769
26770 E048 : Boolean;
26771 pragma Import (Ada, E048, "system__finalization_implementation_E");
26772
26773 E044 : Boolean;
26774 pragma Import (Ada, E044, "ada__finalization_E");
26775
26776 E057 : Boolean;
26777 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26778
26779 E055 : Boolean;
26780 pragma Import (Ada, E055, "system__file_control_block_E");
26781
26782 E042 : Boolean;
26783 pragma Import (Ada, E042, "system__file_io_E");
26784
26785 E006 : Boolean;
26786 pragma Import (Ada, E006, "ada__text_io_E");
26787
26788 -- Set_Globals is a library routine that stores away the
26789 -- value of the indicated set of global values in global
26790 -- variables within the library.
26791
26792 procedure Set_Globals
26793 (Main_Priority : Integer;
26794 Time_Slice_Value : Integer;
26795 WC_Encoding : Character;
26796 Locking_Policy : Character;
26797 Queuing_Policy : Character;
26798 Task_Dispatching_Policy : Character;
26799 Adafinal : System.Address;
26800 Unreserve_All_Interrupts : Integer;
26801 Exception_Tracebacks : Integer);
26802 @findex __gnat_set_globals
26803 pragma Import (C, Set_Globals, "__gnat_set_globals");
26804
26805 -- SDP_Table_Build is a library routine used to build the
26806 -- exception tables. See unit Ada.Exceptions in files
26807 -- a-except.ads/adb for full details of how zero cost
26808 -- exception handling works. This procedure, the call to
26809 -- it, and the two following tables are all omitted if the
26810 -- build is in longjmp/setjmp exception mode.
26811
26812 @findex SDP_Table_Build
26813 @findex Zero Cost Exceptions
26814 procedure SDP_Table_Build
26815 (SDP_Addresses : System.Address;
26816 SDP_Count : Natural;
26817 Elab_Addresses : System.Address;
26818 Elab_Addr_Count : Natural);
26819 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26820
26821 -- Table of Unit_Exception_Table addresses. Used for zero
26822 -- cost exception handling to build the top level table.
26823
26824 ST : aliased constant array (1 .. 23) of System.Address := (
26825 Hello'UET_Address,
26826 Ada.Text_Io'UET_Address,
26827 Ada.Exceptions'UET_Address,
26828 Gnat.Heap_Sort_A'UET_Address,
26829 System.Exception_Table'UET_Address,
26830 System.Machine_State_Operations'UET_Address,
26831 System.Secondary_Stack'UET_Address,
26832 System.Parameters'UET_Address,
26833 System.Soft_Links'UET_Address,
26834 System.Stack_Checking'UET_Address,
26835 System.Traceback'UET_Address,
26836 Ada.Streams'UET_Address,
26837 Ada.Tags'UET_Address,
26838 System.String_Ops'UET_Address,
26839 Interfaces.C_Streams'UET_Address,
26840 System.File_Io'UET_Address,
26841 Ada.Finalization'UET_Address,
26842 System.Finalization_Root'UET_Address,
26843 System.Finalization_Implementation'UET_Address,
26844 System.String_Ops_Concat_3'UET_Address,
26845 System.Stream_Attributes'UET_Address,
26846 System.File_Control_Block'UET_Address,
26847 Ada.Finalization.List_Controller'UET_Address);
26848
26849 -- Table of addresses of elaboration routines. Used for
26850 -- zero cost exception handling to make sure these
26851 -- addresses are included in the top level procedure
26852 -- address table.
26853
26854 EA : aliased constant array (1 .. 23) of System.Address := (
26855 adainit'Code_Address,
26856 Do_Finalize'Code_Address,
26857 Ada.Exceptions'Elab_Spec'Address,
26858 System.Exceptions'Elab_Spec'Address,
26859 Interfaces.C_Streams'Elab_Spec'Address,
26860 System.Exception_Table'Elab_Body'Address,
26861 Ada.Io_Exceptions'Elab_Spec'Address,
26862 System.Stack_Checking'Elab_Spec'Address,
26863 System.Soft_Links'Elab_Body'Address,
26864 System.Secondary_Stack'Elab_Body'Address,
26865 Ada.Tags'Elab_Spec'Address,
26866 Ada.Tags'Elab_Body'Address,
26867 Ada.Streams'Elab_Spec'Address,
26868 System.Finalization_Root'Elab_Spec'Address,
26869 Ada.Exceptions'Elab_Body'Address,
26870 System.Finalization_Implementation'Elab_Spec'Address,
26871 System.Finalization_Implementation'Elab_Body'Address,
26872 Ada.Finalization'Elab_Spec'Address,
26873 Ada.Finalization.List_Controller'Elab_Spec'Address,
26874 System.File_Control_Block'Elab_Spec'Address,
26875 System.File_Io'Elab_Body'Address,
26876 Ada.Text_Io'Elab_Spec'Address,
26877 Ada.Text_Io'Elab_Body'Address);
26878
26879 -- Start of processing for adainit
26880
26881 begin
26882
26883 -- Call SDP_Table_Build to build the top level procedure
26884 -- table for zero cost exception handling (omitted in
26885 -- longjmp/setjmp mode).
26886
26887 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26888
26889 -- Call Set_Globals to record various information for
26890 -- this partition. The values are derived by the binder
26891 -- from information stored in the ali files by the compiler.
26892
26893 @findex __gnat_set_globals
26894 Set_Globals
26895 (Main_Priority => -1,
26896 -- Priority of main program, -1 if no pragma Priority used
26897
26898 Time_Slice_Value => -1,
26899 -- Time slice from Time_Slice pragma, -1 if none used
26900
26901 WC_Encoding => 'b',
26902 -- Wide_Character encoding used, default is brackets
26903
26904 Locking_Policy => ' ',
26905 -- Locking_Policy used, default of space means not
26906 -- specified, otherwise it is the first character of
26907 -- the policy name.
26908
26909 Queuing_Policy => ' ',
26910 -- Queuing_Policy used, default of space means not
26911 -- specified, otherwise it is the first character of
26912 -- the policy name.
26913
26914 Task_Dispatching_Policy => ' ',
26915 -- Task_Dispatching_Policy used, default of space means
26916 -- not specified, otherwise first character of the
26917 -- policy name.
26918
26919 Adafinal => System.Null_Address,
26920 -- Address of Adafinal routine, not used anymore
26921
26922 Unreserve_All_Interrupts => 0,
26923 -- Set true if pragma Unreserve_All_Interrupts was used
26924
26925 Exception_Tracebacks => 0);
26926 -- Indicates if exception tracebacks are enabled
26927
26928 Elab_Final_Code := 1;
26929
26930 -- Now we have the elaboration calls for all units in the partition.
26931 -- The Elab_Spec and Elab_Body attributes generate references to the
26932 -- implicit elaboration procedures generated by the compiler for
26933 -- each unit that requires elaboration.
26934
26935 if not E040 then
26936 Interfaces.C_Streams'Elab_Spec;
26937 end if;
26938 E040 := True;
26939 if not E008 then
26940 Ada.Exceptions'Elab_Spec;
26941 end if;
26942 if not E014 then
26943 System.Exception_Table'Elab_Body;
26944 E014 := True;
26945 end if;
26946 if not E053 then
26947 Ada.Io_Exceptions'Elab_Spec;
26948 E053 := True;
26949 end if;
26950 if not E017 then
26951 System.Exceptions'Elab_Spec;
26952 E017 := True;
26953 end if;
26954 if not E030 then
26955 System.Stack_Checking'Elab_Spec;
26956 end if;
26957 if not E028 then
26958 System.Soft_Links'Elab_Body;
26959 E028 := True;
26960 end if;
26961 E030 := True;
26962 if not E024 then
26963 System.Secondary_Stack'Elab_Body;
26964 E024 := True;
26965 end if;
26966 if not E035 then
26967 Ada.Tags'Elab_Spec;
26968 end if;
26969 if not E035 then
26970 Ada.Tags'Elab_Body;
26971 E035 := True;
26972 end if;
26973 if not E033 then
26974 Ada.Streams'Elab_Spec;
26975 E033 := True;
26976 end if;
26977 if not E046 then
26978 System.Finalization_Root'Elab_Spec;
26979 end if;
26980 E046 := True;
26981 if not E008 then
26982 Ada.Exceptions'Elab_Body;
26983 E008 := True;
26984 end if;
26985 if not E048 then
26986 System.Finalization_Implementation'Elab_Spec;
26987 end if;
26988 if not E048 then
26989 System.Finalization_Implementation'Elab_Body;
26990 E048 := True;
26991 end if;
26992 if not E044 then
26993 Ada.Finalization'Elab_Spec;
26994 end if;
26995 E044 := True;
26996 if not E057 then
26997 Ada.Finalization.List_Controller'Elab_Spec;
26998 end if;
26999 E057 := True;
27000 if not E055 then
27001 System.File_Control_Block'Elab_Spec;
27002 E055 := True;
27003 end if;
27004 if not E042 then
27005 System.File_Io'Elab_Body;
27006 E042 := True;
27007 end if;
27008 if not E006 then
27009 Ada.Text_Io'Elab_Spec;
27010 end if;
27011 if not E006 then
27012 Ada.Text_Io'Elab_Body;
27013 E006 := True;
27014 end if;
27015
27016 Elab_Final_Code := 0;
27017 end adainit;
27018
27019 --------------
27020 -- adafinal --
27021 --------------
27022
27023 @findex adafinal
27024 procedure adafinal is
27025 begin
27026 Do_Finalize;
27027 end adafinal;
27028
27029 ----------
27030 -- main --
27031 ----------
27032
27033 -- main is actually a function, as in the ANSI C standard,
27034 -- defined to return the exit status. The three parameters
27035 -- are the argument count, argument values and environment
27036 -- pointer.
27037
27038 @findex Main Program
27039 function main
27040 (argc : Integer;
27041 argv : System.Address;
27042 envp : System.Address)
27043 return Integer
27044 is
27045 -- The initialize routine performs low level system
27046 -- initialization using a standard library routine which
27047 -- sets up signal handling and performs any other
27048 -- required setup. The routine can be found in file
27049 -- a-init.c.
27050
27051 @findex __gnat_initialize
27052 procedure initialize;
27053 pragma Import (C, initialize, "__gnat_initialize");
27054
27055 -- The finalize routine performs low level system
27056 -- finalization using a standard library routine. The
27057 -- routine is found in file a-final.c and in the standard
27058 -- distribution is a dummy routine that does nothing, so
27059 -- really this is a hook for special user finalization.
27060
27061 @findex __gnat_finalize
27062 procedure finalize;
27063 pragma Import (C, finalize, "__gnat_finalize");
27064
27065 -- We get to the main program of the partition by using
27066 -- pragma Import because if we try to with the unit and
27067 -- call it Ada style, then not only do we waste time
27068 -- recompiling it, but also, we don't really know the right
27069 -- switches (e.g.@: identifier character set) to be used
27070 -- to compile it.
27071
27072 procedure Ada_Main_Program;
27073 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27074
27075 -- Start of processing for main
27076
27077 begin
27078 -- Save global variables
27079
27080 gnat_argc := argc;
27081 gnat_argv := argv;
27082 gnat_envp := envp;
27083
27084 -- Call low level system initialization
27085
27086 Initialize;
27087
27088 -- Call our generated Ada initialization routine
27089
27090 adainit;
27091
27092 -- This is the point at which we want the debugger to get
27093 -- control
27094
27095 Break_Start;
27096
27097 -- Now we call the main program of the partition
27098
27099 Ada_Main_Program;
27100
27101 -- Perform Ada finalization
27102
27103 adafinal;
27104
27105 -- Perform low level system finalization
27106
27107 Finalize;
27108
27109 -- Return the proper exit status
27110 return (gnat_exit_status);
27111 end;
27112
27113 -- This section is entirely comments, so it has no effect on the
27114 -- compilation of the Ada_Main package. It provides the list of
27115 -- object files and linker options, as well as some standard
27116 -- libraries needed for the link. The gnatlink utility parses
27117 -- this b~hello.adb file to read these comment lines to generate
27118 -- the appropriate command line arguments for the call to the
27119 -- system linker. The BEGIN/END lines are used for sentinels for
27120 -- this parsing operation.
27121
27122 -- The exact file names will of course depend on the environment,
27123 -- host/target and location of files on the host system.
27124
27125 @findex Object file list
27126 -- BEGIN Object file/option list
27127 -- ./hello.o
27128 -- -L./
27129 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27130 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27131 -- END Object file/option list
27132
27133 end ada_main;
27134 @end smallexample
27135
27136 @noindent
27137 The Ada code in the above example is exactly what is generated by the
27138 binder. We have added comments to more clearly indicate the function
27139 of each part of the generated @code{Ada_Main} package.
27140
27141 The code is standard Ada in all respects, and can be processed by any
27142 tools that handle Ada. In particular, it is possible to use the debugger
27143 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27144 suppose that for reasons that you do not understand, your program is crashing
27145 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27146 you can place a breakpoint on the call:
27147
27148 @smallexample @c ada
27149 Ada.Text_Io'Elab_Body;
27150 @end smallexample
27151
27152 @noindent
27153 and trace the elaboration routine for this package to find out where
27154 the problem might be (more usually of course you would be debugging
27155 elaboration code in your own application).
27156
27157 @node Elaboration Order Handling in GNAT
27158 @appendix Elaboration Order Handling in GNAT
27159 @cindex Order of elaboration
27160 @cindex Elaboration control
27161
27162 @menu
27163 * Elaboration Code::
27164 * Checking the Elaboration Order::
27165 * Controlling the Elaboration Order::
27166 * Controlling Elaboration in GNAT - Internal Calls::
27167 * Controlling Elaboration in GNAT - External Calls::
27168 * Default Behavior in GNAT - Ensuring Safety::
27169 * Treatment of Pragma Elaborate::
27170 * Elaboration Issues for Library Tasks::
27171 * Mixing Elaboration Models::
27172 * What to Do If the Default Elaboration Behavior Fails::
27173 * Elaboration for Access-to-Subprogram Values::
27174 * Summary of Procedures for Elaboration Control::
27175 * Other Elaboration Order Considerations::
27176 @end menu
27177
27178 @noindent
27179 This chapter describes the handling of elaboration code in Ada and
27180 in GNAT, and discusses how the order of elaboration of program units can
27181 be controlled in GNAT, either automatically or with explicit programming
27182 features.
27183
27184 @node Elaboration Code
27185 @section Elaboration Code
27186
27187 @noindent
27188 Ada provides rather general mechanisms for executing code at elaboration
27189 time, that is to say before the main program starts executing. Such code arises
27190 in three contexts:
27191
27192 @table @asis
27193 @item Initializers for variables.
27194 Variables declared at the library level, in package specs or bodies, can
27195 require initialization that is performed at elaboration time, as in:
27196 @smallexample @c ada
27197 @cartouche
27198 Sqrt_Half : Float := Sqrt (0.5);
27199 @end cartouche
27200 @end smallexample
27201
27202 @item Package initialization code
27203 Code in a @code{BEGIN-END} section at the outer level of a package body is
27204 executed as part of the package body elaboration code.
27205
27206 @item Library level task allocators
27207 Tasks that are declared using task allocators at the library level
27208 start executing immediately and hence can execute at elaboration time.
27209 @end table
27210
27211 @noindent
27212 Subprogram calls are possible in any of these contexts, which means that
27213 any arbitrary part of the program may be executed as part of the elaboration
27214 code. It is even possible to write a program which does all its work at
27215 elaboration time, with a null main program, although stylistically this
27216 would usually be considered an inappropriate way to structure
27217 a program.
27218
27219 An important concern arises in the context of elaboration code:
27220 we have to be sure that it is executed in an appropriate order. What we
27221 have is a series of elaboration code sections, potentially one section
27222 for each unit in the program. It is important that these execute
27223 in the correct order. Correctness here means that, taking the above
27224 example of the declaration of @code{Sqrt_Half},
27225 if some other piece of
27226 elaboration code references @code{Sqrt_Half},
27227 then it must run after the
27228 section of elaboration code that contains the declaration of
27229 @code{Sqrt_Half}.
27230
27231 There would never be any order of elaboration problem if we made a rule
27232 that whenever you @code{with} a unit, you must elaborate both the spec and body
27233 of that unit before elaborating the unit doing the @code{with}'ing:
27234
27235 @smallexample @c ada
27236 @group
27237 @cartouche
27238 with Unit_1;
27239 package Unit_2 is @dots{}
27240 @end cartouche
27241 @end group
27242 @end smallexample
27243
27244 @noindent
27245 would require that both the body and spec of @code{Unit_1} be elaborated
27246 before the spec of @code{Unit_2}. However, a rule like that would be far too
27247 restrictive. In particular, it would make it impossible to have routines
27248 in separate packages that were mutually recursive.
27249
27250 You might think that a clever enough compiler could look at the actual
27251 elaboration code and determine an appropriate correct order of elaboration,
27252 but in the general case, this is not possible. Consider the following
27253 example.
27254
27255 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27256 that references
27257 the variable @code{Sqrt_1}, which is declared in the elaboration code
27258 of the body of @code{Unit_1}:
27259
27260 @smallexample @c ada
27261 @cartouche
27262 Sqrt_1 : Float := Sqrt (0.1);
27263 @end cartouche
27264 @end smallexample
27265
27266 @noindent
27267 The elaboration code of the body of @code{Unit_1} also contains:
27268
27269 @smallexample @c ada
27270 @group
27271 @cartouche
27272 if expression_1 = 1 then
27273 Q := Unit_2.Func_2;
27274 end if;
27275 @end cartouche
27276 @end group
27277 @end smallexample
27278
27279 @noindent
27280 @code{Unit_2} is exactly parallel,
27281 it has a procedure @code{Func_2} that references
27282 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27283 the body @code{Unit_2}:
27284
27285 @smallexample @c ada
27286 @cartouche
27287 Sqrt_2 : Float := Sqrt (0.1);
27288 @end cartouche
27289 @end smallexample
27290
27291 @noindent
27292 The elaboration code of the body of @code{Unit_2} also contains:
27293
27294 @smallexample @c ada
27295 @group
27296 @cartouche
27297 if expression_2 = 2 then
27298 Q := Unit_1.Func_1;
27299 end if;
27300 @end cartouche
27301 @end group
27302 @end smallexample
27303
27304 @noindent
27305 Now the question is, which of the following orders of elaboration is
27306 acceptable:
27307
27308 @smallexample
27309 @group
27310 Spec of Unit_1
27311 Spec of Unit_2
27312 Body of Unit_1
27313 Body of Unit_2
27314 @end group
27315 @end smallexample
27316
27317 @noindent
27318 or
27319
27320 @smallexample
27321 @group
27322 Spec of Unit_2
27323 Spec of Unit_1
27324 Body of Unit_2
27325 Body of Unit_1
27326 @end group
27327 @end smallexample
27328
27329 @noindent
27330 If you carefully analyze the flow here, you will see that you cannot tell
27331 at compile time the answer to this question.
27332 If @code{expression_1} is not equal to 1,
27333 and @code{expression_2} is not equal to 2,
27334 then either order is acceptable, because neither of the function calls is
27335 executed. If both tests evaluate to true, then neither order is acceptable
27336 and in fact there is no correct order.
27337
27338 If one of the two expressions is true, and the other is false, then one
27339 of the above orders is correct, and the other is incorrect. For example,
27340 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27341 then the call to @code{Func_1}
27342 will occur, but not the call to @code{Func_2.}
27343 This means that it is essential
27344 to elaborate the body of @code{Unit_1} before
27345 the body of @code{Unit_2}, so the first
27346 order of elaboration is correct and the second is wrong.
27347
27348 By making @code{expression_1} and @code{expression_2}
27349 depend on input data, or perhaps
27350 the time of day, we can make it impossible for the compiler or binder
27351 to figure out which of these expressions will be true, and hence it
27352 is impossible to guarantee a safe order of elaboration at run time.
27353
27354 @node Checking the Elaboration Order
27355 @section Checking the Elaboration Order
27356
27357 @noindent
27358 In some languages that involve the same kind of elaboration problems,
27359 e.g.@: Java and C++, the programmer is expected to worry about these
27360 ordering problems himself, and it is common to
27361 write a program in which an incorrect elaboration order gives
27362 surprising results, because it references variables before they
27363 are initialized.
27364 Ada is designed to be a safe language, and a programmer-beware approach is
27365 clearly not sufficient. Consequently, the language provides three lines
27366 of defense:
27367
27368 @table @asis
27369 @item Standard rules
27370 Some standard rules restrict the possible choice of elaboration
27371 order. In particular, if you @code{with} a unit, then its spec is always
27372 elaborated before the unit doing the @code{with}. Similarly, a parent
27373 spec is always elaborated before the child spec, and finally
27374 a spec is always elaborated before its corresponding body.
27375
27376 @item Dynamic elaboration checks
27377 @cindex Elaboration checks
27378 @cindex Checks, elaboration
27379 Dynamic checks are made at run time, so that if some entity is accessed
27380 before it is elaborated (typically by means of a subprogram call)
27381 then the exception (@code{Program_Error}) is raised.
27382
27383 @item Elaboration control
27384 Facilities are provided for the programmer to specify the desired order
27385 of elaboration.
27386 @end table
27387
27388 Let's look at these facilities in more detail. First, the rules for
27389 dynamic checking. One possible rule would be simply to say that the
27390 exception is raised if you access a variable which has not yet been
27391 elaborated. The trouble with this approach is that it could require
27392 expensive checks on every variable reference. Instead Ada has two
27393 rules which are a little more restrictive, but easier to check, and
27394 easier to state:
27395
27396 @table @asis
27397 @item Restrictions on calls
27398 A subprogram can only be called at elaboration time if its body
27399 has been elaborated. The rules for elaboration given above guarantee
27400 that the spec of the subprogram has been elaborated before the
27401 call, but not the body. If this rule is violated, then the
27402 exception @code{Program_Error} is raised.
27403
27404 @item Restrictions on instantiations
27405 A generic unit can only be instantiated if the body of the generic
27406 unit has been elaborated. Again, the rules for elaboration given above
27407 guarantee that the spec of the generic unit has been elaborated
27408 before the instantiation, but not the body. If this rule is
27409 violated, then the exception @code{Program_Error} is raised.
27410 @end table
27411
27412 @noindent
27413 The idea is that if the body has been elaborated, then any variables
27414 it references must have been elaborated; by checking for the body being
27415 elaborated we guarantee that none of its references causes any
27416 trouble. As we noted above, this is a little too restrictive, because a
27417 subprogram that has no non-local references in its body may in fact be safe
27418 to call. However, it really would be unsafe to rely on this, because
27419 it would mean that the caller was aware of details of the implementation
27420 in the body. This goes against the basic tenets of Ada.
27421
27422 A plausible implementation can be described as follows.
27423 A Boolean variable is associated with each subprogram
27424 and each generic unit. This variable is initialized to False, and is set to
27425 True at the point body is elaborated. Every call or instantiation checks the
27426 variable, and raises @code{Program_Error} if the variable is False.
27427
27428 Note that one might think that it would be good enough to have one Boolean
27429 variable for each package, but that would not deal with cases of trying
27430 to call a body in the same package as the call
27431 that has not been elaborated yet.
27432 Of course a compiler may be able to do enough analysis to optimize away
27433 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27434 does such optimizations, but still the easiest conceptual model is to
27435 think of there being one variable per subprogram.
27436
27437 @node Controlling the Elaboration Order
27438 @section Controlling the Elaboration Order
27439
27440 @noindent
27441 In the previous section we discussed the rules in Ada which ensure
27442 that @code{Program_Error} is raised if an incorrect elaboration order is
27443 chosen. This prevents erroneous executions, but we need mechanisms to
27444 specify a correct execution and avoid the exception altogether.
27445 To achieve this, Ada provides a number of features for controlling
27446 the order of elaboration. We discuss these features in this section.
27447
27448 First, there are several ways of indicating to the compiler that a given
27449 unit has no elaboration problems:
27450
27451 @table @asis
27452 @item packages that do not require a body
27453 A library package that does not require a body does not permit
27454 a body (this rule was introduced in Ada 95).
27455 Thus if we have a such a package, as in:
27456
27457 @smallexample @c ada
27458 @group
27459 @cartouche
27460 package Definitions is
27461 generic
27462 type m is new integer;
27463 package Subp is
27464 type a is array (1 .. 10) of m;
27465 type b is array (1 .. 20) of m;
27466 end Subp;
27467 end Definitions;
27468 @end cartouche
27469 @end group
27470 @end smallexample
27471
27472 @noindent
27473 A package that @code{with}'s @code{Definitions} may safely instantiate
27474 @code{Definitions.Subp} because the compiler can determine that there
27475 definitely is no package body to worry about in this case
27476
27477 @item pragma Pure
27478 @cindex pragma Pure
27479 @findex Pure
27480 Places sufficient restrictions on a unit to guarantee that
27481 no call to any subprogram in the unit can result in an
27482 elaboration problem. This means that the compiler does not need
27483 to worry about the point of elaboration of such units, and in
27484 particular, does not need to check any calls to any subprograms
27485 in this unit.
27486
27487 @item pragma Preelaborate
27488 @findex Preelaborate
27489 @cindex pragma Preelaborate
27490 This pragma places slightly less stringent restrictions on a unit than
27491 does pragma Pure,
27492 but these restrictions are still sufficient to ensure that there
27493 are no elaboration problems with any calls to the unit.
27494
27495 @item pragma Elaborate_Body
27496 @findex Elaborate_Body
27497 @cindex pragma Elaborate_Body
27498 This pragma requires that the body of a unit be elaborated immediately
27499 after its spec. Suppose a unit @code{A} has such a pragma,
27500 and unit @code{B} does
27501 a @code{with} of unit @code{A}. Recall that the standard rules require
27502 the spec of unit @code{A}
27503 to be elaborated before the @code{with}'ing unit; given the pragma in
27504 @code{A}, we also know that the body of @code{A}
27505 will be elaborated before @code{B}, so
27506 that calls to @code{A} are safe and do not need a check.
27507 @end table
27508
27509 @noindent
27510 Note that,
27511 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27512 the use of
27513 @code{Elaborate_Body} does not guarantee that the program is
27514 free of elaboration problems, because it may not be possible
27515 to satisfy the requested elaboration order.
27516 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27517 If a programmer
27518 marks @code{Unit_1} as @code{Elaborate_Body},
27519 and not @code{Unit_2,} then the order of
27520 elaboration will be:
27521
27522 @smallexample
27523 @group
27524 Spec of Unit_2
27525 Spec of Unit_1
27526 Body of Unit_1
27527 Body of Unit_2
27528 @end group
27529 @end smallexample
27530
27531 @noindent
27532 Now that means that the call to @code{Func_1} in @code{Unit_2}
27533 need not be checked,
27534 it must be safe. But the call to @code{Func_2} in
27535 @code{Unit_1} may still fail if
27536 @code{Expression_1} is equal to 1,
27537 and the programmer must still take
27538 responsibility for this not being the case.
27539
27540 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27541 eliminated, except for calls entirely within a body, which are
27542 in any case fully under programmer control. However, using the pragma
27543 everywhere is not always possible.
27544 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27545 we marked both of them as having pragma @code{Elaborate_Body}, then
27546 clearly there would be no possible elaboration order.
27547
27548 The above pragmas allow a server to guarantee safe use by clients, and
27549 clearly this is the preferable approach. Consequently a good rule
27550 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27551 and if this is not possible,
27552 mark them as @code{Elaborate_Body} if possible.
27553 As we have seen, there are situations where neither of these
27554 three pragmas can be used.
27555 So we also provide methods for clients to control the
27556 order of elaboration of the servers on which they depend:
27557
27558 @table @asis
27559 @item pragma Elaborate (unit)
27560 @findex Elaborate
27561 @cindex pragma Elaborate
27562 This pragma is placed in the context clause, after a @code{with} clause,
27563 and it requires that the body of the named unit be elaborated before
27564 the unit in which the pragma occurs. The idea is to use this pragma
27565 if the current unit calls at elaboration time, directly or indirectly,
27566 some subprogram in the named unit.
27567
27568 @item pragma Elaborate_All (unit)
27569 @findex Elaborate_All
27570 @cindex pragma Elaborate_All
27571 This is a stronger version of the Elaborate pragma. Consider the
27572 following example:
27573
27574 @smallexample
27575 Unit A @code{with}'s unit B and calls B.Func in elab code
27576 Unit B @code{with}'s unit C, and B.Func calls C.Func
27577 @end smallexample
27578
27579 @noindent
27580 Now if we put a pragma @code{Elaborate (B)}
27581 in unit @code{A}, this ensures that the
27582 body of @code{B} is elaborated before the call, but not the
27583 body of @code{C}, so
27584 the call to @code{C.Func} could still cause @code{Program_Error} to
27585 be raised.
27586
27587 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27588 not only that the body of the named unit be elaborated before the
27589 unit doing the @code{with}, but also the bodies of all units that the
27590 named unit uses, following @code{with} links transitively. For example,
27591 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27592 then it requires
27593 not only that the body of @code{B} be elaborated before @code{A},
27594 but also the
27595 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27596 @end table
27597
27598 @noindent
27599 We are now in a position to give a usage rule in Ada for avoiding
27600 elaboration problems, at least if dynamic dispatching and access to
27601 subprogram values are not used. We will handle these cases separately
27602 later.
27603
27604 The rule is simple. If a unit has elaboration code that can directly or
27605 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27606 a generic package in a @code{with}'ed unit,
27607 then if the @code{with}'ed unit does not have
27608 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27609 a pragma @code{Elaborate_All}
27610 for the @code{with}'ed unit. By following this rule a client is
27611 assured that calls can be made without risk of an exception.
27612
27613 For generic subprogram instantiations, the rule can be relaxed to
27614 require only a pragma @code{Elaborate} since elaborating the body
27615 of a subprogram cannot cause any transitive elaboration (we are
27616 not calling the subprogram in this case, just elaborating its
27617 declaration).
27618
27619 If this rule is not followed, then a program may be in one of four
27620 states:
27621
27622 @table @asis
27623 @item No order exists
27624 No order of elaboration exists which follows the rules, taking into
27625 account any @code{Elaborate}, @code{Elaborate_All},
27626 or @code{Elaborate_Body} pragmas. In
27627 this case, an Ada compiler must diagnose the situation at bind
27628 time, and refuse to build an executable program.
27629
27630 @item One or more orders exist, all incorrect
27631 One or more acceptable elaboration orders exist, and all of them
27632 generate an elaboration order problem. In this case, the binder
27633 can build an executable program, but @code{Program_Error} will be raised
27634 when the program is run.
27635
27636 @item Several orders exist, some right, some incorrect
27637 One or more acceptable elaboration orders exists, and some of them
27638 work, and some do not. The programmer has not controlled
27639 the order of elaboration, so the binder may or may not pick one of
27640 the correct orders, and the program may or may not raise an
27641 exception when it is run. This is the worst case, because it means
27642 that the program may fail when moved to another compiler, or even
27643 another version of the same compiler.
27644
27645 @item One or more orders exists, all correct
27646 One ore more acceptable elaboration orders exist, and all of them
27647 work. In this case the program runs successfully. This state of
27648 affairs can be guaranteed by following the rule we gave above, but
27649 may be true even if the rule is not followed.
27650 @end table
27651
27652 @noindent
27653 Note that one additional advantage of following our rules on the use
27654 of @code{Elaborate} and @code{Elaborate_All}
27655 is that the program continues to stay in the ideal (all orders OK) state
27656 even if maintenance
27657 changes some bodies of some units. Conversely, if a program that does
27658 not follow this rule happens to be safe at some point, this state of affairs
27659 may deteriorate silently as a result of maintenance changes.
27660
27661 You may have noticed that the above discussion did not mention
27662 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27663 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27664 code in the body makes calls to some other unit, so it is still necessary
27665 to use @code{Elaborate_All} on such units.
27666
27667 @node Controlling Elaboration in GNAT - Internal Calls
27668 @section Controlling Elaboration in GNAT - Internal Calls
27669
27670 @noindent
27671 In the case of internal calls, i.e., calls within a single package, the
27672 programmer has full control over the order of elaboration, and it is up
27673 to the programmer to elaborate declarations in an appropriate order. For
27674 example writing:
27675
27676 @smallexample @c ada
27677 @group
27678 @cartouche
27679 function One return Float;
27680
27681 Q : Float := One;
27682
27683 function One return Float is
27684 begin
27685 return 1.0;
27686 end One;
27687 @end cartouche
27688 @end group
27689 @end smallexample
27690
27691 @noindent
27692 will obviously raise @code{Program_Error} at run time, because function
27693 One will be called before its body is elaborated. In this case GNAT will
27694 generate a warning that the call will raise @code{Program_Error}:
27695
27696 @smallexample
27697 @group
27698 @cartouche
27699 1. procedure y is
27700 2. function One return Float;
27701 3.
27702 4. Q : Float := One;
27703 |
27704 >>> warning: cannot call "One" before body is elaborated
27705 >>> warning: Program_Error will be raised at run time
27706
27707 5.
27708 6. function One return Float is
27709 7. begin
27710 8. return 1.0;
27711 9. end One;
27712 10.
27713 11. begin
27714 12. null;
27715 13. end;
27716 @end cartouche
27717 @end group
27718 @end smallexample
27719
27720 @noindent
27721 Note that in this particular case, it is likely that the call is safe, because
27722 the function @code{One} does not access any global variables.
27723 Nevertheless in Ada, we do not want the validity of the check to depend on
27724 the contents of the body (think about the separate compilation case), so this
27725 is still wrong, as we discussed in the previous sections.
27726
27727 The error is easily corrected by rearranging the declarations so that the
27728 body of @code{One} appears before the declaration containing the call
27729 (note that in Ada 95 and Ada 2005,
27730 declarations can appear in any order, so there is no restriction that
27731 would prevent this reordering, and if we write:
27732
27733 @smallexample @c ada
27734 @group
27735 @cartouche
27736 function One return Float;
27737
27738 function One return Float is
27739 begin
27740 return 1.0;
27741 end One;
27742
27743 Q : Float := One;
27744 @end cartouche
27745 @end group
27746 @end smallexample
27747
27748 @noindent
27749 then all is well, no warning is generated, and no
27750 @code{Program_Error} exception
27751 will be raised.
27752 Things are more complicated when a chain of subprograms is executed:
27753
27754 @smallexample @c ada
27755 @group
27756 @cartouche
27757 function A return Integer;
27758 function B return Integer;
27759 function C return Integer;
27760
27761 function B return Integer is begin return A; end;
27762 function C return Integer is begin return B; end;
27763
27764 X : Integer := C;
27765
27766 function A return Integer is begin return 1; end;
27767 @end cartouche
27768 @end group
27769 @end smallexample
27770
27771 @noindent
27772 Now the call to @code{C}
27773 at elaboration time in the declaration of @code{X} is correct, because
27774 the body of @code{C} is already elaborated,
27775 and the call to @code{B} within the body of
27776 @code{C} is correct, but the call
27777 to @code{A} within the body of @code{B} is incorrect, because the body
27778 of @code{A} has not been elaborated, so @code{Program_Error}
27779 will be raised on the call to @code{A}.
27780 In this case GNAT will generate a
27781 warning that @code{Program_Error} may be
27782 raised at the point of the call. Let's look at the warning:
27783
27784 @smallexample
27785 @group
27786 @cartouche
27787 1. procedure x is
27788 2. function A return Integer;
27789 3. function B return Integer;
27790 4. function C return Integer;
27791 5.
27792 6. function B return Integer is begin return A; end;
27793 |
27794 >>> warning: call to "A" before body is elaborated may
27795 raise Program_Error
27796 >>> warning: "B" called at line 7
27797 >>> warning: "C" called at line 9
27798
27799 7. function C return Integer is begin return B; end;
27800 8.
27801 9. X : Integer := C;
27802 10.
27803 11. function A return Integer is begin return 1; end;
27804 12.
27805 13. begin
27806 14. null;
27807 15. end;
27808 @end cartouche
27809 @end group
27810 @end smallexample
27811
27812 @noindent
27813 Note that the message here says ``may raise'', instead of the direct case,
27814 where the message says ``will be raised''. That's because whether
27815 @code{A} is
27816 actually called depends in general on run-time flow of control.
27817 For example, if the body of @code{B} said
27818
27819 @smallexample @c ada
27820 @group
27821 @cartouche
27822 function B return Integer is
27823 begin
27824 if some-condition-depending-on-input-data then
27825 return A;
27826 else
27827 return 1;
27828 end if;
27829 end B;
27830 @end cartouche
27831 @end group
27832 @end smallexample
27833
27834 @noindent
27835 then we could not know until run time whether the incorrect call to A would
27836 actually occur, so @code{Program_Error} might
27837 or might not be raised. It is possible for a compiler to
27838 do a better job of analyzing bodies, to
27839 determine whether or not @code{Program_Error}
27840 might be raised, but it certainly
27841 couldn't do a perfect job (that would require solving the halting problem
27842 and is provably impossible), and because this is a warning anyway, it does
27843 not seem worth the effort to do the analysis. Cases in which it
27844 would be relevant are rare.
27845
27846 In practice, warnings of either of the forms given
27847 above will usually correspond to
27848 real errors, and should be examined carefully and eliminated.
27849 In the rare case where a warning is bogus, it can be suppressed by any of
27850 the following methods:
27851
27852 @itemize @bullet
27853 @item
27854 Compile with the @option{-gnatws} switch set
27855
27856 @item
27857 Suppress @code{Elaboration_Check} for the called subprogram
27858
27859 @item
27860 Use pragma @code{Warnings_Off} to turn warnings off for the call
27861 @end itemize
27862
27863 @noindent
27864 For the internal elaboration check case,
27865 GNAT by default generates the
27866 necessary run-time checks to ensure
27867 that @code{Program_Error} is raised if any
27868 call fails an elaboration check. Of course this can only happen if a
27869 warning has been issued as described above. The use of pragma
27870 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27871 some of these checks, meaning that it may be possible (but is not
27872 guaranteed) for a program to be able to call a subprogram whose body
27873 is not yet elaborated, without raising a @code{Program_Error} exception.
27874
27875 @node Controlling Elaboration in GNAT - External Calls
27876 @section Controlling Elaboration in GNAT - External Calls
27877
27878 @noindent
27879 The previous section discussed the case in which the execution of a
27880 particular thread of elaboration code occurred entirely within a
27881 single unit. This is the easy case to handle, because a programmer
27882 has direct and total control over the order of elaboration, and
27883 furthermore, checks need only be generated in cases which are rare
27884 and which the compiler can easily detect.
27885 The situation is more complex when separate compilation is taken into account.
27886 Consider the following:
27887
27888 @smallexample @c ada
27889 @cartouche
27890 @group
27891 package Math is
27892 function Sqrt (Arg : Float) return Float;
27893 end Math;
27894
27895 package body Math is
27896 function Sqrt (Arg : Float) return Float is
27897 begin
27898 @dots{}
27899 end Sqrt;
27900 end Math;
27901 @end group
27902 @group
27903 with Math;
27904 package Stuff is
27905 X : Float := Math.Sqrt (0.5);
27906 end Stuff;
27907
27908 with Stuff;
27909 procedure Main is
27910 begin
27911 @dots{}
27912 end Main;
27913 @end group
27914 @end cartouche
27915 @end smallexample
27916
27917 @noindent
27918 where @code{Main} is the main program. When this program is executed, the
27919 elaboration code must first be executed, and one of the jobs of the
27920 binder is to determine the order in which the units of a program are
27921 to be elaborated. In this case we have four units: the spec and body
27922 of @code{Math},
27923 the spec of @code{Stuff} and the body of @code{Main}).
27924 In what order should the four separate sections of elaboration code
27925 be executed?
27926
27927 There are some restrictions in the order of elaboration that the binder
27928 can choose. In particular, if unit U has a @code{with}
27929 for a package @code{X}, then you
27930 are assured that the spec of @code{X}
27931 is elaborated before U , but you are
27932 not assured that the body of @code{X}
27933 is elaborated before U.
27934 This means that in the above case, the binder is allowed to choose the
27935 order:
27936
27937 @smallexample
27938 spec of Math
27939 spec of Stuff
27940 body of Math
27941 body of Main
27942 @end smallexample
27943
27944 @noindent
27945 but that's not good, because now the call to @code{Math.Sqrt}
27946 that happens during
27947 the elaboration of the @code{Stuff}
27948 spec happens before the body of @code{Math.Sqrt} is
27949 elaborated, and hence causes @code{Program_Error} exception to be raised.
27950 At first glance, one might say that the binder is misbehaving, because
27951 obviously you want to elaborate the body of something you @code{with}
27952 first, but
27953 that is not a general rule that can be followed in all cases. Consider
27954
27955 @smallexample @c ada
27956 @group
27957 @cartouche
27958 package X is @dots{}
27959
27960 package Y is @dots{}
27961
27962 with X;
27963 package body Y is @dots{}
27964
27965 with Y;
27966 package body X is @dots{}
27967 @end cartouche
27968 @end group
27969 @end smallexample
27970
27971 @noindent
27972 This is a common arrangement, and, apart from the order of elaboration
27973 problems that might arise in connection with elaboration code, this works fine.
27974 A rule that says that you must first elaborate the body of anything you
27975 @code{with} cannot work in this case:
27976 the body of @code{X} @code{with}'s @code{Y},
27977 which means you would have to
27978 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27979 which means
27980 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27981 loop that cannot be broken.
27982
27983 It is true that the binder can in many cases guess an order of elaboration
27984 that is unlikely to cause a @code{Program_Error}
27985 exception to be raised, and it tries to do so (in the
27986 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27987 by default
27988 elaborate the body of @code{Math} right after its spec, so all will be well).
27989
27990 However, a program that blindly relies on the binder to be helpful can
27991 get into trouble, as we discussed in the previous sections, so
27992 GNAT
27993 provides a number of facilities for assisting the programmer in
27994 developing programs that are robust with respect to elaboration order.
27995
27996 @node Default Behavior in GNAT - Ensuring Safety
27997 @section Default Behavior in GNAT - Ensuring Safety
27998
27999 @noindent
28000 The default behavior in GNAT ensures elaboration safety. In its
28001 default mode GNAT implements the
28002 rule we previously described as the right approach. Let's restate it:
28003
28004 @itemize
28005 @item
28006 @emph{If a unit has elaboration code that can directly or indirectly make a
28007 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28008 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28009 does not have pragma @code{Pure} or
28010 @code{Preelaborate}, then the client should have an
28011 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28012
28013 @emph{In the case of instantiating a generic subprogram, it is always
28014 sufficient to have only an @code{Elaborate} pragma for the
28015 @code{with}'ed unit.}
28016 @end itemize
28017
28018 @noindent
28019 By following this rule a client is assured that calls and instantiations
28020 can be made without risk of an exception.
28021
28022 In this mode GNAT traces all calls that are potentially made from
28023 elaboration code, and puts in any missing implicit @code{Elaborate}
28024 and @code{Elaborate_All} pragmas.
28025 The advantage of this approach is that no elaboration problems
28026 are possible if the binder can find an elaboration order that is
28027 consistent with these implicit @code{Elaborate} and
28028 @code{Elaborate_All} pragmas. The
28029 disadvantage of this approach is that no such order may exist.
28030
28031 If the binder does not generate any diagnostics, then it means that it has
28032 found an elaboration order that is guaranteed to be safe. However, the binder
28033 may still be relying on implicitly generated @code{Elaborate} and
28034 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28035 guaranteed.
28036
28037 If it is important to guarantee portability, then the compilations should
28038 use the
28039 @option{-gnatwl}
28040 (warn on elaboration problems) switch. This will cause warning messages
28041 to be generated indicating the missing @code{Elaborate} and
28042 @code{Elaborate_All} pragmas.
28043 Consider the following source program:
28044
28045 @smallexample @c ada
28046 @group
28047 @cartouche
28048 with k;
28049 package j is
28050 m : integer := k.r;
28051 end;
28052 @end cartouche
28053 @end group
28054 @end smallexample
28055
28056 @noindent
28057 where it is clear that there
28058 should be a pragma @code{Elaborate_All}
28059 for unit @code{k}. An implicit pragma will be generated, and it is
28060 likely that the binder will be able to honor it. However, if you want
28061 to port this program to some other Ada compiler than GNAT.
28062 it is safer to include the pragma explicitly in the source. If this
28063 unit is compiled with the
28064 @option{-gnatwl}
28065 switch, then the compiler outputs a warning:
28066
28067 @smallexample
28068 @group
28069 @cartouche
28070 1. with k;
28071 2. package j is
28072 3. m : integer := k.r;
28073 |
28074 >>> warning: call to "r" may raise Program_Error
28075 >>> warning: missing pragma Elaborate_All for "k"
28076
28077 4. end;
28078 @end cartouche
28079 @end group
28080 @end smallexample
28081
28082 @noindent
28083 and these warnings can be used as a guide for supplying manually
28084 the missing pragmas. It is usually a bad idea to use this warning
28085 option during development. That's because it will warn you when
28086 you need to put in a pragma, but cannot warn you when it is time
28087 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28088 unnecessary dependencies and even false circularities.
28089
28090 This default mode is more restrictive than the Ada Reference
28091 Manual, and it is possible to construct programs which will compile
28092 using the dynamic model described there, but will run into a
28093 circularity using the safer static model we have described.
28094
28095 Of course any Ada compiler must be able to operate in a mode
28096 consistent with the requirements of the Ada Reference Manual,
28097 and in particular must have the capability of implementing the
28098 standard dynamic model of elaboration with run-time checks.
28099
28100 In GNAT, this standard mode can be achieved either by the use of
28101 the @option{-gnatE} switch on the compiler (@command{gcc} or
28102 @command{gnatmake}) command, or by the use of the configuration pragma:
28103
28104 @smallexample @c ada
28105 pragma Elaboration_Checks (RM);
28106 @end smallexample
28107
28108 @noindent
28109 Either approach will cause the unit affected to be compiled using the
28110 standard dynamic run-time elaboration checks described in the Ada
28111 Reference Manual. The static model is generally preferable, since it
28112 is clearly safer to rely on compile and link time checks rather than
28113 run-time checks. However, in the case of legacy code, it may be
28114 difficult to meet the requirements of the static model. This
28115 issue is further discussed in
28116 @ref{What to Do If the Default Elaboration Behavior Fails}.
28117
28118 Note that the static model provides a strict subset of the allowed
28119 behavior and programs of the Ada Reference Manual, so if you do
28120 adhere to the static model and no circularities exist,
28121 then you are assured that your program will
28122 work using the dynamic model, providing that you remove any
28123 pragma Elaborate statements from the source.
28124
28125 @node Treatment of Pragma Elaborate
28126 @section Treatment of Pragma Elaborate
28127 @cindex Pragma Elaborate
28128
28129 @noindent
28130 The use of @code{pragma Elaborate}
28131 should generally be avoided in Ada 95 and Ada 2005 programs,
28132 since there is no guarantee that transitive calls
28133 will be properly handled. Indeed at one point, this pragma was placed
28134 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28135
28136 Now that's a bit restrictive. In practice, the case in which
28137 @code{pragma Elaborate} is useful is when the caller knows that there
28138 are no transitive calls, or that the called unit contains all necessary
28139 transitive @code{pragma Elaborate} statements, and legacy code often
28140 contains such uses.
28141
28142 Strictly speaking the static mode in GNAT should ignore such pragmas,
28143 since there is no assurance at compile time that the necessary safety
28144 conditions are met. In practice, this would cause GNAT to be incompatible
28145 with correctly written Ada 83 code that had all necessary
28146 @code{pragma Elaborate} statements in place. Consequently, we made the
28147 decision that GNAT in its default mode will believe that if it encounters
28148 a @code{pragma Elaborate} then the programmer knows what they are doing,
28149 and it will trust that no elaboration errors can occur.
28150
28151 The result of this decision is two-fold. First to be safe using the
28152 static mode, you should remove all @code{pragma Elaborate} statements.
28153 Second, when fixing circularities in existing code, you can selectively
28154 use @code{pragma Elaborate} statements to convince the static mode of
28155 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28156 statement.
28157
28158 When using the static mode with @option{-gnatwl}, any use of
28159 @code{pragma Elaborate} will generate a warning about possible
28160 problems.
28161
28162 @node Elaboration Issues for Library Tasks
28163 @section Elaboration Issues for Library Tasks
28164 @cindex Library tasks, elaboration issues
28165 @cindex Elaboration of library tasks
28166
28167 @noindent
28168 In this section we examine special elaboration issues that arise for
28169 programs that declare library level tasks.
28170
28171 Generally the model of execution of an Ada program is that all units are
28172 elaborated, and then execution of the program starts. However, the
28173 declaration of library tasks definitely does not fit this model. The
28174 reason for this is that library tasks start as soon as they are declared
28175 (more precisely, as soon as the statement part of the enclosing package
28176 body is reached), that is to say before elaboration
28177 of the program is complete. This means that if such a task calls a
28178 subprogram, or an entry in another task, the callee may or may not be
28179 elaborated yet, and in the standard
28180 Reference Manual model of dynamic elaboration checks, you can even
28181 get timing dependent Program_Error exceptions, since there can be
28182 a race between the elaboration code and the task code.
28183
28184 The static model of elaboration in GNAT seeks to avoid all such
28185 dynamic behavior, by being conservative, and the conservative
28186 approach in this particular case is to assume that all the code
28187 in a task body is potentially executed at elaboration time if
28188 a task is declared at the library level.
28189
28190 This can definitely result in unexpected circularities. Consider
28191 the following example
28192
28193 @smallexample @c ada
28194 package Decls is
28195 task Lib_Task is
28196 entry Start;
28197 end Lib_Task;
28198
28199 type My_Int is new Integer;
28200
28201 function Ident (M : My_Int) return My_Int;
28202 end Decls;
28203
28204 with Utils;
28205 package body Decls is
28206 task body Lib_Task is
28207 begin
28208 accept Start;
28209 Utils.Put_Val (2);
28210 end Lib_Task;
28211
28212 function Ident (M : My_Int) return My_Int is
28213 begin
28214 return M;
28215 end Ident;
28216 end Decls;
28217
28218 with Decls;
28219 package Utils is
28220 procedure Put_Val (Arg : Decls.My_Int);
28221 end Utils;
28222
28223 with Text_IO;
28224 package body Utils is
28225 procedure Put_Val (Arg : Decls.My_Int) is
28226 begin
28227 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28228 end Put_Val;
28229 end Utils;
28230
28231 with Decls;
28232 procedure Main is
28233 begin
28234 Decls.Lib_Task.Start;
28235 end;
28236 @end smallexample
28237
28238 @noindent
28239 If the above example is compiled in the default static elaboration
28240 mode, then a circularity occurs. The circularity comes from the call
28241 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28242 this call occurs in elaboration code, we need an implicit pragma
28243 @code{Elaborate_All} for @code{Utils}. This means that not only must
28244 the spec and body of @code{Utils} be elaborated before the body
28245 of @code{Decls}, but also the spec and body of any unit that is
28246 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28247 the body of @code{Decls}. This is the transitive implication of
28248 pragma @code{Elaborate_All} and it makes sense, because in general
28249 the body of @code{Put_Val} might have a call to something in a
28250 @code{with'ed} unit.
28251
28252 In this case, the body of Utils (actually its spec) @code{with's}
28253 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28254 must be elaborated before itself, in case there is a call from the
28255 body of @code{Utils}.
28256
28257 Here is the exact chain of events we are worrying about:
28258
28259 @enumerate
28260 @item
28261 In the body of @code{Decls} a call is made from within the body of a library
28262 task to a subprogram in the package @code{Utils}. Since this call may
28263 occur at elaboration time (given that the task is activated at elaboration
28264 time), we have to assume the worst, i.e., that the
28265 call does happen at elaboration time.
28266
28267 @item
28268 This means that the body and spec of @code{Util} must be elaborated before
28269 the body of @code{Decls} so that this call does not cause an access before
28270 elaboration.
28271
28272 @item
28273 Within the body of @code{Util}, specifically within the body of
28274 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28275 by this package.
28276
28277 @item
28278 One such @code{with}'ed package is package @code{Decls}, so there
28279 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28280 In fact there is such a call in this example, but we would have to
28281 assume that there was such a call even if it were not there, since
28282 we are not supposed to write the body of @code{Decls} knowing what
28283 is in the body of @code{Utils}; certainly in the case of the
28284 static elaboration model, the compiler does not know what is in
28285 other bodies and must assume the worst.
28286
28287 @item
28288 This means that the spec and body of @code{Decls} must also be
28289 elaborated before we elaborate the unit containing the call, but
28290 that unit is @code{Decls}! This means that the body of @code{Decls}
28291 must be elaborated before itself, and that's a circularity.
28292 @end enumerate
28293
28294 @noindent
28295 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28296 the body of @code{Decls} you will get a true Ada Reference Manual
28297 circularity that makes the program illegal.
28298
28299 In practice, we have found that problems with the static model of
28300 elaboration in existing code often arise from library tasks, so
28301 we must address this particular situation.
28302
28303 Note that if we compile and run the program above, using the dynamic model of
28304 elaboration (that is to say use the @option{-gnatE} switch),
28305 then it compiles, binds,
28306 links, and runs, printing the expected result of 2. Therefore in some sense
28307 the circularity here is only apparent, and we need to capture
28308 the properties of this program that distinguish it from other library-level
28309 tasks that have real elaboration problems.
28310
28311 We have four possible answers to this question:
28312
28313 @itemize @bullet
28314
28315 @item
28316 Use the dynamic model of elaboration.
28317
28318 If we use the @option{-gnatE} switch, then as noted above, the program works.
28319 Why is this? If we examine the task body, it is apparent that the task cannot
28320 proceed past the
28321 @code{accept} statement until after elaboration has been completed, because
28322 the corresponding entry call comes from the main program, not earlier.
28323 This is why the dynamic model works here. But that's really giving
28324 up on a precise analysis, and we prefer to take this approach only if we cannot
28325 solve the
28326 problem in any other manner. So let us examine two ways to reorganize
28327 the program to avoid the potential elaboration problem.
28328
28329 @item
28330 Split library tasks into separate packages.
28331
28332 Write separate packages, so that library tasks are isolated from
28333 other declarations as much as possible. Let us look at a variation on
28334 the above program.
28335
28336 @smallexample @c ada
28337 package Decls1 is
28338 task Lib_Task is
28339 entry Start;
28340 end Lib_Task;
28341 end Decls1;
28342
28343 with Utils;
28344 package body Decls1 is
28345 task body Lib_Task is
28346 begin
28347 accept Start;
28348 Utils.Put_Val (2);
28349 end Lib_Task;
28350 end Decls1;
28351
28352 package Decls2 is
28353 type My_Int is new Integer;
28354 function Ident (M : My_Int) return My_Int;
28355 end Decls2;
28356
28357 with Utils;
28358 package body Decls2 is
28359 function Ident (M : My_Int) return My_Int is
28360 begin
28361 return M;
28362 end Ident;
28363 end Decls2;
28364
28365 with Decls2;
28366 package Utils is
28367 procedure Put_Val (Arg : Decls2.My_Int);
28368 end Utils;
28369
28370 with Text_IO;
28371 package body Utils is
28372 procedure Put_Val (Arg : Decls2.My_Int) is
28373 begin
28374 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28375 end Put_Val;
28376 end Utils;
28377
28378 with Decls1;
28379 procedure Main is
28380 begin
28381 Decls1.Lib_Task.Start;
28382 end;
28383 @end smallexample
28384
28385 @noindent
28386 All we have done is to split @code{Decls} into two packages, one
28387 containing the library task, and one containing everything else. Now
28388 there is no cycle, and the program compiles, binds, links and executes
28389 using the default static model of elaboration.
28390
28391 @item
28392 Declare separate task types.
28393
28394 A significant part of the problem arises because of the use of the
28395 single task declaration form. This means that the elaboration of
28396 the task type, and the elaboration of the task itself (i.e.@: the
28397 creation of the task) happen at the same time. A good rule
28398 of style in Ada is to always create explicit task types. By
28399 following the additional step of placing task objects in separate
28400 packages from the task type declaration, many elaboration problems
28401 are avoided. Here is another modified example of the example program:
28402
28403 @smallexample @c ada
28404 package Decls is
28405 task type Lib_Task_Type is
28406 entry Start;
28407 end Lib_Task_Type;
28408
28409 type My_Int is new Integer;
28410
28411 function Ident (M : My_Int) return My_Int;
28412 end Decls;
28413
28414 with Utils;
28415 package body Decls is
28416 task body Lib_Task_Type is
28417 begin
28418 accept Start;
28419 Utils.Put_Val (2);
28420 end Lib_Task_Type;
28421
28422 function Ident (M : My_Int) return My_Int is
28423 begin
28424 return M;
28425 end Ident;
28426 end Decls;
28427
28428 with Decls;
28429 package Utils is
28430 procedure Put_Val (Arg : Decls.My_Int);
28431 end Utils;
28432
28433 with Text_IO;
28434 package body Utils is
28435 procedure Put_Val (Arg : Decls.My_Int) is
28436 begin
28437 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28438 end Put_Val;
28439 end Utils;
28440
28441 with Decls;
28442 package Declst is
28443 Lib_Task : Decls.Lib_Task_Type;
28444 end Declst;
28445
28446 with Declst;
28447 procedure Main is
28448 begin
28449 Declst.Lib_Task.Start;
28450 end;
28451 @end smallexample
28452
28453 @noindent
28454 What we have done here is to replace the @code{task} declaration in
28455 package @code{Decls} with a @code{task type} declaration. Then we
28456 introduce a separate package @code{Declst} to contain the actual
28457 task object. This separates the elaboration issues for
28458 the @code{task type}
28459 declaration, which causes no trouble, from the elaboration issues
28460 of the task object, which is also unproblematic, since it is now independent
28461 of the elaboration of @code{Utils}.
28462 This separation of concerns also corresponds to
28463 a generally sound engineering principle of separating declarations
28464 from instances. This version of the program also compiles, binds, links,
28465 and executes, generating the expected output.
28466
28467 @item
28468 Use No_Entry_Calls_In_Elaboration_Code restriction.
28469 @cindex No_Entry_Calls_In_Elaboration_Code
28470
28471 The previous two approaches described how a program can be restructured
28472 to avoid the special problems caused by library task bodies. in practice,
28473 however, such restructuring may be difficult to apply to existing legacy code,
28474 so we must consider solutions that do not require massive rewriting.
28475
28476 Let us consider more carefully why our original sample program works
28477 under the dynamic model of elaboration. The reason is that the code
28478 in the task body blocks immediately on the @code{accept}
28479 statement. Now of course there is nothing to prohibit elaboration
28480 code from making entry calls (for example from another library level task),
28481 so we cannot tell in isolation that
28482 the task will not execute the accept statement during elaboration.
28483
28484 However, in practice it is very unusual to see elaboration code
28485 make any entry calls, and the pattern of tasks starting
28486 at elaboration time and then immediately blocking on @code{accept} or
28487 @code{select} statements is very common. What this means is that
28488 the compiler is being too pessimistic when it analyzes the
28489 whole package body as though it might be executed at elaboration
28490 time.
28491
28492 If we know that the elaboration code contains no entry calls, (a very safe
28493 assumption most of the time, that could almost be made the default
28494 behavior), then we can compile all units of the program under control
28495 of the following configuration pragma:
28496
28497 @smallexample
28498 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28499 @end smallexample
28500
28501 @noindent
28502 This pragma can be placed in the @file{gnat.adc} file in the usual
28503 manner. If we take our original unmodified program and compile it
28504 in the presence of a @file{gnat.adc} containing the above pragma,
28505 then once again, we can compile, bind, link, and execute, obtaining
28506 the expected result. In the presence of this pragma, the compiler does
28507 not trace calls in a task body, that appear after the first @code{accept}
28508 or @code{select} statement, and therefore does not report a potential
28509 circularity in the original program.
28510
28511 The compiler will check to the extent it can that the above
28512 restriction is not violated, but it is not always possible to do a
28513 complete check at compile time, so it is important to use this
28514 pragma only if the stated restriction is in fact met, that is to say
28515 no task receives an entry call before elaboration of all units is completed.
28516
28517 @end itemize
28518
28519 @node Mixing Elaboration Models
28520 @section Mixing Elaboration Models
28521 @noindent
28522 So far, we have assumed that the entire program is either compiled
28523 using the dynamic model or static model, ensuring consistency. It
28524 is possible to mix the two models, but rules have to be followed
28525 if this mixing is done to ensure that elaboration checks are not
28526 omitted.
28527
28528 The basic rule is that @emph{a unit compiled with the static model cannot
28529 be @code{with'ed} by a unit compiled with the dynamic model}. The
28530 reason for this is that in the static model, a unit assumes that
28531 its clients guarantee to use (the equivalent of) pragma
28532 @code{Elaborate_All} so that no elaboration checks are required
28533 in inner subprograms, and this assumption is violated if the
28534 client is compiled with dynamic checks.
28535
28536 The precise rule is as follows. A unit that is compiled with dynamic
28537 checks can only @code{with} a unit that meets at least one of the
28538 following criteria:
28539
28540 @itemize @bullet
28541
28542 @item
28543 The @code{with'ed} unit is itself compiled with dynamic elaboration
28544 checks (that is with the @option{-gnatE} switch.
28545
28546 @item
28547 The @code{with'ed} unit is an internal GNAT implementation unit from
28548 the System, Interfaces, Ada, or GNAT hierarchies.
28549
28550 @item
28551 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28552
28553 @item
28554 The @code{with'ing} unit (that is the client) has an explicit pragma
28555 @code{Elaborate_All} for the @code{with'ed} unit.
28556
28557 @end itemize
28558
28559 @noindent
28560 If this rule is violated, that is if a unit with dynamic elaboration
28561 checks @code{with's} a unit that does not meet one of the above four
28562 criteria, then the binder (@code{gnatbind}) will issue a warning
28563 similar to that in the following example:
28564
28565 @smallexample
28566 warning: "x.ads" has dynamic elaboration checks and with's
28567 warning: "y.ads" which has static elaboration checks
28568 @end smallexample
28569
28570 @noindent
28571 These warnings indicate that the rule has been violated, and that as a result
28572 elaboration checks may be missed in the resulting executable file.
28573 This warning may be suppressed using the @option{-ws} binder switch
28574 in the usual manner.
28575
28576 One useful application of this mixing rule is in the case of a subsystem
28577 which does not itself @code{with} units from the remainder of the
28578 application. In this case, the entire subsystem can be compiled with
28579 dynamic checks to resolve a circularity in the subsystem, while
28580 allowing the main application that uses this subsystem to be compiled
28581 using the more reliable default static model.
28582
28583 @node What to Do If the Default Elaboration Behavior Fails
28584 @section What to Do If the Default Elaboration Behavior Fails
28585
28586 @noindent
28587 If the binder cannot find an acceptable order, it outputs detailed
28588 diagnostics. For example:
28589 @smallexample
28590 @group
28591 @iftex
28592 @leftskip=0cm
28593 @end iftex
28594 error: elaboration circularity detected
28595 info: "proc (body)" must be elaborated before "pack (body)"
28596 info: reason: Elaborate_All probably needed in unit "pack (body)"
28597 info: recompile "pack (body)" with -gnatwl
28598 info: for full details
28599 info: "proc (body)"
28600 info: is needed by its spec:
28601 info: "proc (spec)"
28602 info: which is withed by:
28603 info: "pack (body)"
28604 info: "pack (body)" must be elaborated before "proc (body)"
28605 info: reason: pragma Elaborate in unit "proc (body)"
28606 @end group
28607
28608 @end smallexample
28609
28610 @noindent
28611 In this case we have a cycle that the binder cannot break. On the one
28612 hand, there is an explicit pragma Elaborate in @code{proc} for
28613 @code{pack}. This means that the body of @code{pack} must be elaborated
28614 before the body of @code{proc}. On the other hand, there is elaboration
28615 code in @code{pack} that calls a subprogram in @code{proc}. This means
28616 that for maximum safety, there should really be a pragma
28617 Elaborate_All in @code{pack} for @code{proc} which would require that
28618 the body of @code{proc} be elaborated before the body of
28619 @code{pack}. Clearly both requirements cannot be satisfied.
28620 Faced with a circularity of this kind, you have three different options.
28621
28622 @table @asis
28623 @item Fix the program
28624 The most desirable option from the point of view of long-term maintenance
28625 is to rearrange the program so that the elaboration problems are avoided.
28626 One useful technique is to place the elaboration code into separate
28627 child packages. Another is to move some of the initialization code to
28628 explicitly called subprograms, where the program controls the order
28629 of initialization explicitly. Although this is the most desirable option,
28630 it may be impractical and involve too much modification, especially in
28631 the case of complex legacy code.
28632
28633 @item Perform dynamic checks
28634 If the compilations are done using the
28635 @option{-gnatE}
28636 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28637 manner. Dynamic checks are generated for all calls that could possibly result
28638 in raising an exception. With this switch, the compiler does not generate
28639 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28640 exactly as specified in the @cite{Ada Reference Manual}.
28641 The binder will generate
28642 an executable program that may or may not raise @code{Program_Error}, and then
28643 it is the programmer's job to ensure that it does not raise an exception. Note
28644 that it is important to compile all units with the switch, it cannot be used
28645 selectively.
28646
28647 @item Suppress checks
28648 The drawback of dynamic checks is that they generate a
28649 significant overhead at run time, both in space and time. If you
28650 are absolutely sure that your program cannot raise any elaboration
28651 exceptions, and you still want to use the dynamic elaboration model,
28652 then you can use the configuration pragma
28653 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28654 example this pragma could be placed in the @file{gnat.adc} file.
28655
28656 @item Suppress checks selectively
28657 When you know that certain calls or instantiations in elaboration code cannot
28658 possibly lead to an elaboration error, and the binder nevertheless complains
28659 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28660 elaboration circularities, it is possible to remove those warnings locally and
28661 obtain a program that will bind. Clearly this can be unsafe, and it is the
28662 responsibility of the programmer to make sure that the resulting program has no
28663 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28664 used with different granularity to suppress warnings and break elaboration
28665 circularities:
28666
28667 @itemize @bullet
28668 @item
28669 Place the pragma that names the called subprogram in the declarative part
28670 that contains the call.
28671
28672 @item
28673 Place the pragma in the declarative part, without naming an entity. This
28674 disables warnings on all calls in the corresponding declarative region.
28675
28676 @item
28677 Place the pragma in the package spec that declares the called subprogram,
28678 and name the subprogram. This disables warnings on all elaboration calls to
28679 that subprogram.
28680
28681 @item
28682 Place the pragma in the package spec that declares the called subprogram,
28683 without naming any entity. This disables warnings on all elaboration calls to
28684 all subprograms declared in this spec.
28685
28686 @item Use Pragma Elaborate
28687 As previously described in section @xref{Treatment of Pragma Elaborate},
28688 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28689 that no elaboration checks are required on calls to the designated unit.
28690 There may be cases in which the caller knows that no transitive calls
28691 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28692 case where @code{pragma Elaborate_All} would cause a circularity.
28693 @end itemize
28694
28695 @noindent
28696 These five cases are listed in order of decreasing safety, and therefore
28697 require increasing programmer care in their application. Consider the
28698 following program:
28699
28700 @smallexample @c adanocomment
28701 package Pack1 is
28702 function F1 return Integer;
28703 X1 : Integer;
28704 end Pack1;
28705
28706 package Pack2 is
28707 function F2 return Integer;
28708 function Pure (x : integer) return integer;
28709 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
28710 -- pragma Suppress (Elaboration_Check); -- (4)
28711 end Pack2;
28712
28713 with Pack2;
28714 package body Pack1 is
28715 function F1 return Integer is
28716 begin
28717 return 100;
28718 end F1;
28719 Val : integer := Pack2.Pure (11); -- Elab. call (1)
28720 begin
28721 declare
28722 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
28723 -- pragma Suppress(Elaboration_Check); -- (2)
28724 begin
28725 X1 := Pack2.F2 + 1; -- Elab. call (2)
28726 end;
28727 end Pack1;
28728
28729 with Pack1;
28730 package body Pack2 is
28731 function F2 return Integer is
28732 begin
28733 return Pack1.F1;
28734 end F2;
28735 function Pure (x : integer) return integer is
28736 begin
28737 return x ** 3 - 3 * x;
28738 end;
28739 end Pack2;
28740
28741 with Pack1, Ada.Text_IO;
28742 procedure Proc3 is
28743 begin
28744 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28745 end Proc3;
28746 @end smallexample
28747 In the absence of any pragmas, an attempt to bind this program produces
28748 the following diagnostics:
28749 @smallexample
28750 @group
28751 @iftex
28752 @leftskip=.5cm
28753 @end iftex
28754 error: elaboration circularity detected
28755 info: "pack1 (body)" must be elaborated before "pack1 (body)"
28756 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
28757 info: recompile "pack1 (body)" with -gnatwl for full details
28758 info: "pack1 (body)"
28759 info: must be elaborated along with its spec:
28760 info: "pack1 (spec)"
28761 info: which is withed by:
28762 info: "pack2 (body)"
28763 info: which must be elaborated along with its spec:
28764 info: "pack2 (spec)"
28765 info: which is withed by:
28766 info: "pack1 (body)"
28767 @end group
28768 @end smallexample
28769 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28770 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28771 F2 is safe, even though F2 calls F1, because the call appears after the
28772 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28773 remove the warning on the call. It is also possible to use pragma (2)
28774 because there are no other potentially unsafe calls in the block.
28775
28776 @noindent
28777 The call to @code{Pure} is safe because this function does not depend on the
28778 state of @code{Pack2}. Therefore any call to this function is safe, and it
28779 is correct to place pragma (3) in the corresponding package spec.
28780
28781 @noindent
28782 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28783 warnings on all calls to functions declared therein. Note that this is not
28784 necessarily safe, and requires more detailed examination of the subprogram
28785 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28786 be already elaborated.
28787 @end table
28788
28789 @noindent
28790 It is hard to generalize on which of these four approaches should be
28791 taken. Obviously if it is possible to fix the program so that the default
28792 treatment works, this is preferable, but this may not always be practical.
28793 It is certainly simple enough to use
28794 @option{-gnatE}
28795 but the danger in this case is that, even if the GNAT binder
28796 finds a correct elaboration order, it may not always do so,
28797 and certainly a binder from another Ada compiler might not. A
28798 combination of testing and analysis (for which the warnings generated
28799 with the
28800 @option{-gnatwl}
28801 switch can be useful) must be used to ensure that the program is free
28802 of errors. One switch that is useful in this testing is the
28803 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28804 switch for
28805 @code{gnatbind}.
28806 Normally the binder tries to find an order that has the best chance
28807 of avoiding elaboration problems. However, if this switch is used, the binder
28808 plays a devil's advocate role, and tries to choose the order that
28809 has the best chance of failing. If your program works even with this
28810 switch, then it has a better chance of being error free, but this is still
28811 not a guarantee.
28812
28813 For an example of this approach in action, consider the C-tests (executable
28814 tests) from the ACVC suite. If these are compiled and run with the default
28815 treatment, then all but one of them succeed without generating any error
28816 diagnostics from the binder. However, there is one test that fails, and
28817 this is not surprising, because the whole point of this test is to ensure
28818 that the compiler can handle cases where it is impossible to determine
28819 a correct order statically, and it checks that an exception is indeed
28820 raised at run time.
28821
28822 This one test must be compiled and run using the
28823 @option{-gnatE}
28824 switch, and then it passes. Alternatively, the entire suite can
28825 be run using this switch. It is never wrong to run with the dynamic
28826 elaboration switch if your code is correct, and we assume that the
28827 C-tests are indeed correct (it is less efficient, but efficiency is
28828 not a factor in running the ACVC tests.)
28829
28830 @node Elaboration for Access-to-Subprogram Values
28831 @section Elaboration for Access-to-Subprogram Values
28832 @cindex Access-to-subprogram
28833
28834 @noindent
28835 Access-to-subprogram types (introduced in Ada 95) complicate
28836 the handling of elaboration. The trouble is that it becomes
28837 impossible to tell at compile time which procedure
28838 is being called. This means that it is not possible for the binder
28839 to analyze the elaboration requirements in this case.
28840
28841 If at the point at which the access value is created
28842 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28843 the body of the subprogram is
28844 known to have been elaborated, then the access value is safe, and its use
28845 does not require a check. This may be achieved by appropriate arrangement
28846 of the order of declarations if the subprogram is in the current unit,
28847 or, if the subprogram is in another unit, by using pragma
28848 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28849 on the referenced unit.
28850
28851 If the referenced body is not known to have been elaborated at the point
28852 the access value is created, then any use of the access value must do a
28853 dynamic check, and this dynamic check will fail and raise a
28854 @code{Program_Error} exception if the body has not been elaborated yet.
28855 GNAT will generate the necessary checks, and in addition, if the
28856 @option{-gnatwl}
28857 switch is set, will generate warnings that such checks are required.
28858
28859 The use of dynamic dispatching for tagged types similarly generates
28860 a requirement for dynamic checks, and premature calls to any primitive
28861 operation of a tagged type before the body of the operation has been
28862 elaborated, will result in the raising of @code{Program_Error}.
28863
28864 @node Summary of Procedures for Elaboration Control
28865 @section Summary of Procedures for Elaboration Control
28866 @cindex Elaboration control
28867
28868 @noindent
28869 First, compile your program with the default options, using none of
28870 the special elaboration control switches. If the binder successfully
28871 binds your program, then you can be confident that, apart from issues
28872 raised by the use of access-to-subprogram types and dynamic dispatching,
28873 the program is free of elaboration errors. If it is important that the
28874 program be portable, then use the
28875 @option{-gnatwl}
28876 switch to generate warnings about missing @code{Elaborate} or
28877 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28878
28879 If the program fails to bind using the default static elaboration
28880 handling, then you can fix the program to eliminate the binder
28881 message, or recompile the entire program with the
28882 @option{-gnatE} switch to generate dynamic elaboration checks,
28883 and, if you are sure there really are no elaboration problems,
28884 use a global pragma @code{Suppress (Elaboration_Check)}.
28885
28886 @node Other Elaboration Order Considerations
28887 @section Other Elaboration Order Considerations
28888 @noindent
28889 This section has been entirely concerned with the issue of finding a valid
28890 elaboration order, as defined by the Ada Reference Manual. In a case
28891 where several elaboration orders are valid, the task is to find one
28892 of the possible valid elaboration orders (and the static model in GNAT
28893 will ensure that this is achieved).
28894
28895 The purpose of the elaboration rules in the Ada Reference Manual is to
28896 make sure that no entity is accessed before it has been elaborated. For
28897 a subprogram, this means that the spec and body must have been elaborated
28898 before the subprogram is called. For an object, this means that the object
28899 must have been elaborated before its value is read or written. A violation
28900 of either of these two requirements is an access before elaboration order,
28901 and this section has been all about avoiding such errors.
28902
28903 In the case where more than one order of elaboration is possible, in the
28904 sense that access before elaboration errors are avoided, then any one of
28905 the orders is ``correct'' in the sense that it meets the requirements of
28906 the Ada Reference Manual, and no such error occurs.
28907
28908 However, it may be the case for a given program, that there are
28909 constraints on the order of elaboration that come not from consideration
28910 of avoiding elaboration errors, but rather from extra-lingual logic
28911 requirements. Consider this example:
28912
28913 @smallexample @c ada
28914 with Init_Constants;
28915 package Constants is
28916 X : Integer := 0;
28917 Y : Integer := 0;
28918 end Constants;
28919
28920 package Init_Constants is
28921 procedure P; -- require a body
28922 end Init_Constants;
28923
28924 with Constants;
28925 package body Init_Constants is
28926 procedure P is begin null; end;
28927 begin
28928 Constants.X := 3;
28929 Constants.Y := 4;
28930 end Init_Constants;
28931
28932 with Constants;
28933 package Calc is
28934 Z : Integer := Constants.X + Constants.Y;
28935 end Calc;
28936
28937 with Calc;
28938 with Text_IO; use Text_IO;
28939 procedure Main is
28940 begin
28941 Put_Line (Calc.Z'Img);
28942 end Main;
28943 @end smallexample
28944
28945 @noindent
28946 In this example, there is more than one valid order of elaboration. For
28947 example both the following are correct orders:
28948
28949 @smallexample
28950 Init_Constants spec
28951 Constants spec
28952 Calc spec
28953 Init_Constants body
28954 Main body
28955
28956 and
28957
28958 Init_Constants spec
28959 Init_Constants body
28960 Constants spec
28961 Calc spec
28962 Main body
28963 @end smallexample
28964
28965 @noindent
28966 There is no language rule to prefer one or the other, both are correct
28967 from an order of elaboration point of view. But the programmatic effects
28968 of the two orders are very different. In the first, the elaboration routine
28969 of @code{Calc} initializes @code{Z} to zero, and then the main program
28970 runs with this value of zero. But in the second order, the elaboration
28971 routine of @code{Calc} runs after the body of Init_Constants has set
28972 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28973 runs.
28974
28975 One could perhaps by applying pretty clever non-artificial intelligence
28976 to the situation guess that it is more likely that the second order of
28977 elaboration is the one desired, but there is no formal linguistic reason
28978 to prefer one over the other. In fact in this particular case, GNAT will
28979 prefer the second order, because of the rule that bodies are elaborated
28980 as soon as possible, but it's just luck that this is what was wanted
28981 (if indeed the second order was preferred).
28982
28983 If the program cares about the order of elaboration routines in a case like
28984 this, it is important to specify the order required. In this particular
28985 case, that could have been achieved by adding to the spec of Calc:
28986
28987 @smallexample @c ada
28988 pragma Elaborate_All (Constants);
28989 @end smallexample
28990
28991 @noindent
28992 which requires that the body (if any) and spec of @code{Constants},
28993 as well as the body and spec of any unit @code{with}'ed by
28994 @code{Constants} be elaborated before @code{Calc} is elaborated.
28995
28996 Clearly no automatic method can always guess which alternative you require,
28997 and if you are working with legacy code that had constraints of this kind
28998 which were not properly specified by adding @code{Elaborate} or
28999 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29000 compilers can choose different orders.
29001
29002 However, GNAT does attempt to diagnose the common situation where there
29003 are uninitialized variables in the visible part of a package spec, and the
29004 corresponding package body has an elaboration block that directly or
29005 indirectly initialized one or more of these variables. This is the situation
29006 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29007 a warning that suggests this addition if it detects this situation.
29008
29009 The @code{gnatbind}
29010 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29011 out problems. This switch causes bodies to be elaborated as late as possible
29012 instead of as early as possible. In the example above, it would have forced
29013 the choice of the first elaboration order. If you get different results
29014 when using this switch, and particularly if one set of results is right,
29015 and one is wrong as far as you are concerned, it shows that you have some
29016 missing @code{Elaborate} pragmas. For the example above, we have the
29017 following output:
29018
29019 @smallexample
29020 gnatmake -f -q main
29021 main
29022 7
29023 gnatmake -f -q main -bargs -p
29024 main
29025 0
29026 @end smallexample
29027
29028 @noindent
29029 It is of course quite unlikely that both these results are correct, so
29030 it is up to you in a case like this to investigate the source of the
29031 difference, by looking at the two elaboration orders that are chosen,
29032 and figuring out which is correct, and then adding the necessary
29033 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29034
29035
29036
29037 @c *******************************
29038 @node Conditional Compilation
29039 @appendix Conditional Compilation
29040 @c *******************************
29041 @cindex Conditional compilation
29042
29043 @noindent
29044 It is often necessary to arrange for a single source program
29045 to serve multiple purposes, where it is compiled in different
29046 ways to achieve these different goals. Some examples of the
29047 need for this feature are
29048
29049 @itemize @bullet
29050 @item Adapting a program to a different hardware environment
29051 @item Adapting a program to a different target architecture
29052 @item Turning debugging features on and off
29053 @item Arranging for a program to compile with different compilers
29054 @end itemize
29055
29056 @noindent
29057 In C, or C++, the typical approach would be to use the preprocessor
29058 that is defined as part of the language. The Ada language does not
29059 contain such a feature. This is not an oversight, but rather a very
29060 deliberate design decision, based on the experience that overuse of
29061 the preprocessing features in C and C++ can result in programs that
29062 are extremely difficult to maintain. For example, if we have ten
29063 switches that can be on or off, this means that there are a thousand
29064 separate programs, any one of which might not even be syntactically
29065 correct, and even if syntactically correct, the resulting program
29066 might not work correctly. Testing all combinations can quickly become
29067 impossible.
29068
29069 Nevertheless, the need to tailor programs certainly exists, and in
29070 this Appendix we will discuss how this can
29071 be achieved using Ada in general, and GNAT in particular.
29072
29073 @menu
29074 * Use of Boolean Constants::
29075 * Debugging - A Special Case::
29076 * Conditionalizing Declarations::
29077 * Use of Alternative Implementations::
29078 * Preprocessing::
29079 @end menu
29080
29081 @node Use of Boolean Constants
29082 @section Use of Boolean Constants
29083
29084 @noindent
29085 In the case where the difference is simply which code
29086 sequence is executed, the cleanest solution is to use Boolean
29087 constants to control which code is executed.
29088
29089 @smallexample @c ada
29090 @group
29091 FP_Initialize_Required : constant Boolean := True;
29092 @dots{}
29093 if FP_Initialize_Required then
29094 @dots{}
29095 end if;
29096 @end group
29097 @end smallexample
29098
29099 @noindent
29100 Not only will the code inside the @code{if} statement not be executed if
29101 the constant Boolean is @code{False}, but it will also be completely
29102 deleted from the program.
29103 However, the code is only deleted after the @code{if} statement
29104 has been checked for syntactic and semantic correctness.
29105 (In contrast, with preprocessors the code is deleted before the
29106 compiler ever gets to see it, so it is not checked until the switch
29107 is turned on.)
29108 @cindex Preprocessors (contrasted with conditional compilation)
29109
29110 Typically the Boolean constants will be in a separate package,
29111 something like:
29112
29113 @smallexample @c ada
29114 @group
29115 package Config is
29116 FP_Initialize_Required : constant Boolean := True;
29117 Reset_Available : constant Boolean := False;
29118 @dots{}
29119 end Config;
29120 @end group
29121 @end smallexample
29122
29123 @noindent
29124 The @code{Config} package exists in multiple forms for the various targets,
29125 with an appropriate script selecting the version of @code{Config} needed.
29126 Then any other unit requiring conditional compilation can do a @code{with}
29127 of @code{Config} to make the constants visible.
29128
29129
29130 @node Debugging - A Special Case
29131 @section Debugging - A Special Case
29132
29133 @noindent
29134 A common use of conditional code is to execute statements (for example
29135 dynamic checks, or output of intermediate results) under control of a
29136 debug switch, so that the debugging behavior can be turned on and off.
29137 This can be done using a Boolean constant to control whether the code
29138 is active:
29139
29140 @smallexample @c ada
29141 @group
29142 if Debugging then
29143 Put_Line ("got to the first stage!");
29144 end if;
29145 @end group
29146 @end smallexample
29147
29148 @noindent
29149 or
29150
29151 @smallexample @c ada
29152 @group
29153 if Debugging and then Temperature > 999.0 then
29154 raise Temperature_Crazy;
29155 end if;
29156 @end group
29157 @end smallexample
29158
29159 @noindent
29160 Since this is a common case, there are special features to deal with
29161 this in a convenient manner. For the case of tests, Ada 2005 has added
29162 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29163 @cindex pragma @code{Assert}
29164 on the @code{Assert} pragma that has always been available in GNAT, so this
29165 feature may be used with GNAT even if you are not using Ada 2005 features.
29166 The use of pragma @code{Assert} is described in
29167 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29168 example, the last test could be written:
29169
29170 @smallexample @c ada
29171 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29172 @end smallexample
29173
29174 @noindent
29175 or simply
29176
29177 @smallexample @c ada
29178 pragma Assert (Temperature <= 999.0);
29179 @end smallexample
29180
29181 @noindent
29182 In both cases, if assertions are active and the temperature is excessive,
29183 the exception @code{Assert_Failure} will be raised, with the given string in
29184 the first case or a string indicating the location of the pragma in the second
29185 case used as the exception message.
29186
29187 You can turn assertions on and off by using the @code{Assertion_Policy}
29188 pragma.
29189 @cindex pragma @code{Assertion_Policy}
29190 This is an Ada 2005 pragma which is implemented in all modes by
29191 GNAT, but only in the latest versions of GNAT which include Ada 2005
29192 capability. Alternatively, you can use the @option{-gnata} switch
29193 @cindex @option{-gnata} switch
29194 to enable assertions from the command line (this is recognized by all versions
29195 of GNAT).
29196
29197 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29198 @code{Debug} can be used:
29199 @cindex pragma @code{Debug}
29200
29201 @smallexample @c ada
29202 pragma Debug (Put_Line ("got to the first stage!"));
29203 @end smallexample
29204
29205 @noindent
29206 If debug pragmas are enabled, the argument, which must be of the form of
29207 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29208 Only one call can be present, but of course a special debugging procedure
29209 containing any code you like can be included in the program and then
29210 called in a pragma @code{Debug} argument as needed.
29211
29212 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29213 construct is that pragma @code{Debug} can appear in declarative contexts,
29214 such as at the very beginning of a procedure, before local declarations have
29215 been elaborated.
29216
29217 Debug pragmas are enabled using either the @option{-gnata} switch that also
29218 controls assertions, or with a separate Debug_Policy pragma.
29219 @cindex pragma @code{Debug_Policy}
29220 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29221 in Ada 95 and Ada 83 programs as well), and is analogous to
29222 pragma @code{Assertion_Policy} to control assertions.
29223
29224 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29225 and thus they can appear in @file{gnat.adc} if you are not using a
29226 project file, or in the file designated to contain configuration pragmas
29227 in a project file.
29228 They then apply to all subsequent compilations. In practice the use of
29229 the @option{-gnata} switch is often the most convenient method of controlling
29230 the status of these pragmas.
29231
29232 Note that a pragma is not a statement, so in contexts where a statement
29233 sequence is required, you can't just write a pragma on its own. You have
29234 to add a @code{null} statement.
29235
29236 @smallexample @c ada
29237 @group
29238 if @dots{} then
29239 @dots{} -- some statements
29240 else
29241 pragma Assert (Num_Cases < 10);
29242 null;
29243 end if;
29244 @end group
29245 @end smallexample
29246
29247
29248 @node Conditionalizing Declarations
29249 @section Conditionalizing Declarations
29250
29251 @noindent
29252 In some cases, it may be necessary to conditionalize declarations to meet
29253 different requirements. For example we might want a bit string whose length
29254 is set to meet some hardware message requirement.
29255
29256 In some cases, it may be possible to do this using declare blocks controlled
29257 by conditional constants:
29258
29259 @smallexample @c ada
29260 @group
29261 if Small_Machine then
29262 declare
29263 X : Bit_String (1 .. 10);
29264 begin
29265 @dots{}
29266 end;
29267 else
29268 declare
29269 X : Large_Bit_String (1 .. 1000);
29270 begin
29271 @dots{}
29272 end;
29273 end if;
29274 @end group
29275 @end smallexample
29276
29277 @noindent
29278 Note that in this approach, both declarations are analyzed by the
29279 compiler so this can only be used where both declarations are legal,
29280 even though one of them will not be used.
29281
29282 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29283 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29284 that are parameterized by these constants. For example
29285
29286 @smallexample @c ada
29287 @group
29288 for Rec use
29289 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29290 end record;
29291 @end group
29292 @end smallexample
29293
29294 @noindent
29295 If @code{Bits_Per_Word} is set to 32, this generates either
29296
29297 @smallexample @c ada
29298 @group
29299 for Rec use
29300 Field1 at 0 range 0 .. 32;
29301 end record;
29302 @end group
29303 @end smallexample
29304
29305 @noindent
29306 for the big endian case, or
29307
29308 @smallexample @c ada
29309 @group
29310 for Rec use record
29311 Field1 at 0 range 10 .. 32;
29312 end record;
29313 @end group
29314 @end smallexample
29315
29316 @noindent
29317 for the little endian case. Since a powerful subset of Ada expression
29318 notation is usable for creating static constants, clever use of this
29319 feature can often solve quite difficult problems in conditionalizing
29320 compilation (note incidentally that in Ada 95, the little endian
29321 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29322 need to define this one yourself).
29323
29324
29325 @node Use of Alternative Implementations
29326 @section Use of Alternative Implementations
29327
29328 @noindent
29329 In some cases, none of the approaches described above are adequate. This
29330 can occur for example if the set of declarations required is radically
29331 different for two different configurations.
29332
29333 In this situation, the official Ada way of dealing with conditionalizing
29334 such code is to write separate units for the different cases. As long as
29335 this does not result in excessive duplication of code, this can be done
29336 without creating maintenance problems. The approach is to share common
29337 code as far as possible, and then isolate the code and declarations
29338 that are different. Subunits are often a convenient method for breaking
29339 out a piece of a unit that is to be conditionalized, with separate files
29340 for different versions of the subunit for different targets, where the
29341 build script selects the right one to give to the compiler.
29342 @cindex Subunits (and conditional compilation)
29343
29344 As an example, consider a situation where a new feature in Ada 2005
29345 allows something to be done in a really nice way. But your code must be able
29346 to compile with an Ada 95 compiler. Conceptually you want to say:
29347
29348 @smallexample @c ada
29349 @group
29350 if Ada_2005 then
29351 @dots{} neat Ada 2005 code
29352 else
29353 @dots{} not quite as neat Ada 95 code
29354 end if;
29355 @end group
29356 @end smallexample
29357
29358 @noindent
29359 where @code{Ada_2005} is a Boolean constant.
29360
29361 But this won't work when @code{Ada_2005} is set to @code{False},
29362 since the @code{then} clause will be illegal for an Ada 95 compiler.
29363 (Recall that although such unreachable code would eventually be deleted
29364 by the compiler, it still needs to be legal. If it uses features
29365 introduced in Ada 2005, it will be illegal in Ada 95.)
29366
29367 So instead we write
29368
29369 @smallexample @c ada
29370 procedure Insert is separate;
29371 @end smallexample
29372
29373 @noindent
29374 Then we have two files for the subunit @code{Insert}, with the two sets of
29375 code.
29376 If the package containing this is called @code{File_Queries}, then we might
29377 have two files
29378
29379 @itemize @bullet
29380 @item @file{file_queries-insert-2005.adb}
29381 @item @file{file_queries-insert-95.adb}
29382 @end itemize
29383
29384 @noindent
29385 and the build script renames the appropriate file to
29386
29387 @smallexample
29388 file_queries-insert.adb
29389 @end smallexample
29390
29391 @noindent
29392 and then carries out the compilation.
29393
29394 This can also be done with project files' naming schemes. For example:
29395
29396 @smallexample @c project
29397 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29398 @end smallexample
29399
29400 @noindent
29401 Note also that with project files it is desirable to use a different extension
29402 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29403 conflict may arise through another commonly used feature: to declare as part
29404 of the project a set of directories containing all the sources obeying the
29405 default naming scheme.
29406
29407 The use of alternative units is certainly feasible in all situations,
29408 and for example the Ada part of the GNAT run-time is conditionalized
29409 based on the target architecture using this approach. As a specific example,
29410 consider the implementation of the AST feature in VMS. There is one
29411 spec:
29412
29413 @smallexample
29414 s-asthan.ads
29415 @end smallexample
29416
29417 @noindent
29418 which is the same for all architectures, and three bodies:
29419
29420 @table @file
29421 @item s-asthan.adb
29422 used for all non-VMS operating systems
29423 @item s-asthan-vms-alpha.adb
29424 used for VMS on the Alpha
29425 @item s-asthan-vms-ia64.adb
29426 used for VMS on the ia64
29427 @end table
29428
29429 @noindent
29430 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29431 this operating system feature is not available, and the two remaining
29432 versions interface with the corresponding versions of VMS to provide
29433 VMS-compatible AST handling. The GNAT build script knows the architecture
29434 and operating system, and automatically selects the right version,
29435 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29436
29437 Another style for arranging alternative implementations is through Ada's
29438 access-to-subprogram facility.
29439 In case some functionality is to be conditionally included,
29440 you can declare an access-to-procedure variable @code{Ref} that is initialized
29441 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29442 when appropriate.
29443 In some library package, set @code{Ref} to @code{Proc'Access} for some
29444 procedure @code{Proc} that performs the relevant processing.
29445 The initialization only occurs if the library package is included in the
29446 program.
29447 The same idea can also be implemented using tagged types and dispatching
29448 calls.
29449
29450
29451 @node Preprocessing
29452 @section Preprocessing
29453 @cindex Preprocessing
29454
29455 @noindent
29456 Although it is quite possible to conditionalize code without the use of
29457 C-style preprocessing, as described earlier in this section, it is
29458 nevertheless convenient in some cases to use the C approach. Moreover,
29459 older Ada compilers have often provided some preprocessing capability,
29460 so legacy code may depend on this approach, even though it is not
29461 standard.
29462
29463 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29464 extent on the various preprocessors that have been used
29465 with legacy code on other compilers, to enable easier transition).
29466
29467 The preprocessor may be used in two separate modes. It can be used quite
29468 separately from the compiler, to generate a separate output source file
29469 that is then fed to the compiler as a separate step. This is the
29470 @code{gnatprep} utility, whose use is fully described in
29471 @ref{Preprocessing Using gnatprep}.
29472 @cindex @code{gnatprep}
29473
29474 The preprocessing language allows such constructs as
29475
29476 @smallexample
29477 @group
29478 #if DEBUG or PRIORITY > 4 then
29479 bunch of declarations
29480 #else
29481 completely different bunch of declarations
29482 #end if;
29483 @end group
29484 @end smallexample
29485
29486 @noindent
29487 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29488 defined either on the command line or in a separate file.
29489
29490 The other way of running the preprocessor is even closer to the C style and
29491 often more convenient. In this approach the preprocessing is integrated into
29492 the compilation process. The compiler is fed the preprocessor input which
29493 includes @code{#if} lines etc, and then the compiler carries out the
29494 preprocessing internally and processes the resulting output.
29495 For more details on this approach, see @ref{Integrated Preprocessing}.
29496
29497
29498 @c *******************************
29499 @node Inline Assembler
29500 @appendix Inline Assembler
29501 @c *******************************
29502
29503 @noindent
29504 If you need to write low-level software that interacts directly
29505 with the hardware, Ada provides two ways to incorporate assembly
29506 language code into your program. First, you can import and invoke
29507 external routines written in assembly language, an Ada feature fully
29508 supported by GNAT@. However, for small sections of code it may be simpler
29509 or more efficient to include assembly language statements directly
29510 in your Ada source program, using the facilities of the implementation-defined
29511 package @code{System.Machine_Code}, which incorporates the gcc
29512 Inline Assembler. The Inline Assembler approach offers a number of advantages,
29513 including the following:
29514
29515 @itemize @bullet
29516 @item No need to use non-Ada tools
29517 @item Consistent interface over different targets
29518 @item Automatic usage of the proper calling conventions
29519 @item Access to Ada constants and variables
29520 @item Definition of intrinsic routines
29521 @item Possibility of inlining a subprogram comprising assembler code
29522 @item Code optimizer can take Inline Assembler code into account
29523 @end itemize
29524
29525 This chapter presents a series of examples to show you how to use
29526 the Inline Assembler. Although it focuses on the Intel x86,
29527 the general approach applies also to other processors.
29528 It is assumed that you are familiar with Ada
29529 and with assembly language programming.
29530
29531 @menu
29532 * Basic Assembler Syntax::
29533 * A Simple Example of Inline Assembler::
29534 * Output Variables in Inline Assembler::
29535 * Input Variables in Inline Assembler::
29536 * Inlining Inline Assembler Code::
29537 * Other Asm Functionality::
29538 @end menu
29539
29540 @c ---------------------------------------------------------------------------
29541 @node Basic Assembler Syntax
29542 @section Basic Assembler Syntax
29543
29544 @noindent
29545 The assembler used by GNAT and gcc is based not on the Intel assembly
29546 language, but rather on a language that descends from the AT&T Unix
29547 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29548 The following table summarizes the main features of @emph{as} syntax
29549 and points out the differences from the Intel conventions.
29550 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29551 pre-processor) documentation for further information.
29552
29553 @table @asis
29554 @item Register names
29555 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29556 @*
29557 Intel: No extra punctuation; for example @code{eax}
29558
29559 @item Immediate operand
29560 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29561 @*
29562 Intel: No extra punctuation; for example @code{4}
29563
29564 @item Address
29565 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29566 @*
29567 Intel: No extra punctuation; for example @code{loc}
29568
29569 @item Memory contents
29570 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29571 @*
29572 Intel: Square brackets; for example @code{[loc]}
29573
29574 @item Register contents
29575 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29576 @*
29577 Intel: Square brackets; for example @code{[eax]}
29578
29579 @item Hexadecimal numbers
29580 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29581 @*
29582 Intel: Trailing ``h''; for example @code{A0h}
29583
29584 @item Operand size
29585 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29586 a 16-bit word
29587 @*
29588 Intel: Implicit, deduced by assembler; for example @code{mov}
29589
29590 @item Instruction repetition
29591 gcc / @emph{as}: Split into two lines; for example
29592 @*
29593 @code{rep}
29594 @*
29595 @code{stosl}
29596 @*
29597 Intel: Keep on one line; for example @code{rep stosl}
29598
29599 @item Order of operands
29600 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29601 @*
29602 Intel: Destination first; for example @code{mov eax, 4}
29603 @end table
29604
29605 @c ---------------------------------------------------------------------------
29606 @node A Simple Example of Inline Assembler
29607 @section A Simple Example of Inline Assembler
29608
29609 @noindent
29610 The following example will generate a single assembly language statement,
29611 @code{nop}, which does nothing. Despite its lack of run-time effect,
29612 the example will be useful in illustrating the basics of
29613 the Inline Assembler facility.
29614
29615 @smallexample @c ada
29616 @group
29617 with System.Machine_Code; use System.Machine_Code;
29618 procedure Nothing is
29619 begin
29620 Asm ("nop");
29621 end Nothing;
29622 @end group
29623 @end smallexample
29624
29625 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29626 here it takes one parameter, a @emph{template string} that must be a static
29627 expression and that will form the generated instruction.
29628 @code{Asm} may be regarded as a compile-time procedure that parses
29629 the template string and additional parameters (none here),
29630 from which it generates a sequence of assembly language instructions.
29631
29632 The examples in this chapter will illustrate several of the forms
29633 for invoking @code{Asm}; a complete specification of the syntax
29634 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29635 Manual}.
29636
29637 Under the standard GNAT conventions, the @code{Nothing} procedure
29638 should be in a file named @file{nothing.adb}.
29639 You can build the executable in the usual way:
29640 @smallexample
29641 gnatmake nothing
29642 @end smallexample
29643 However, the interesting aspect of this example is not its run-time behavior
29644 but rather the generated assembly code.
29645 To see this output, invoke the compiler as follows:
29646 @smallexample
29647 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29648 @end smallexample
29649 where the options are:
29650
29651 @table @code
29652 @item -c
29653 compile only (no bind or link)
29654 @item -S
29655 generate assembler listing
29656 @item -fomit-frame-pointer
29657 do not set up separate stack frames
29658 @item -gnatp
29659 do not add runtime checks
29660 @end table
29661
29662 This gives a human-readable assembler version of the code. The resulting
29663 file will have the same name as the Ada source file, but with a @code{.s}
29664 extension. In our example, the file @file{nothing.s} has the following
29665 contents:
29666
29667 @smallexample
29668 @group
29669 .file "nothing.adb"
29670 gcc2_compiled.:
29671 ___gnu_compiled_ada:
29672 .text
29673 .align 4
29674 .globl __ada_nothing
29675 __ada_nothing:
29676 #APP
29677 nop
29678 #NO_APP
29679 jmp L1
29680 .align 2,0x90
29681 L1:
29682 ret
29683 @end group
29684 @end smallexample
29685
29686 The assembly code you included is clearly indicated by
29687 the compiler, between the @code{#APP} and @code{#NO_APP}
29688 delimiters. The character before the 'APP' and 'NOAPP'
29689 can differ on different targets. For example, GNU/Linux uses '#APP' while
29690 on NT you will see '/APP'.
29691
29692 If you make a mistake in your assembler code (such as using the
29693 wrong size modifier, or using a wrong operand for the instruction) GNAT
29694 will report this error in a temporary file, which will be deleted when
29695 the compilation is finished. Generating an assembler file will help
29696 in such cases, since you can assemble this file separately using the
29697 @emph{as} assembler that comes with gcc.
29698
29699 Assembling the file using the command
29700
29701 @smallexample
29702 as @file{nothing.s}
29703 @end smallexample
29704 @noindent
29705 will give you error messages whose lines correspond to the assembler
29706 input file, so you can easily find and correct any mistakes you made.
29707 If there are no errors, @emph{as} will generate an object file
29708 @file{nothing.out}.
29709
29710 @c ---------------------------------------------------------------------------
29711 @node Output Variables in Inline Assembler
29712 @section Output Variables in Inline Assembler
29713
29714 @noindent
29715 The examples in this section, showing how to access the processor flags,
29716 illustrate how to specify the destination operands for assembly language
29717 statements.
29718
29719 @smallexample @c ada
29720 @group
29721 with Interfaces; use Interfaces;
29722 with Ada.Text_IO; use Ada.Text_IO;
29723 with System.Machine_Code; use System.Machine_Code;
29724 procedure Get_Flags is
29725 Flags : Unsigned_32;
29726 use ASCII;
29727 begin
29728 Asm ("pushfl" & LF & HT & -- push flags on stack
29729 "popl %%eax" & LF & HT & -- load eax with flags
29730 "movl %%eax, %0", -- store flags in variable
29731 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29732 Put_Line ("Flags register:" & Flags'Img);
29733 end Get_Flags;
29734 @end group
29735 @end smallexample
29736
29737 In order to have a nicely aligned assembly listing, we have separated
29738 multiple assembler statements in the Asm template string with linefeed
29739 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29740 The resulting section of the assembly output file is:
29741
29742 @smallexample
29743 @group
29744 #APP
29745 pushfl
29746 popl %eax
29747 movl %eax, -40(%ebp)
29748 #NO_APP
29749 @end group
29750 @end smallexample
29751
29752 It would have been legal to write the Asm invocation as:
29753
29754 @smallexample
29755 Asm ("pushfl popl %%eax movl %%eax, %0")
29756 @end smallexample
29757
29758 but in the generated assembler file, this would come out as:
29759
29760 @smallexample
29761 #APP
29762 pushfl popl %eax movl %eax, -40(%ebp)
29763 #NO_APP
29764 @end smallexample
29765
29766 which is not so convenient for the human reader.
29767
29768 We use Ada comments
29769 at the end of each line to explain what the assembler instructions
29770 actually do. This is a useful convention.
29771
29772 When writing Inline Assembler instructions, you need to precede each register
29773 and variable name with a percent sign. Since the assembler already requires
29774 a percent sign at the beginning of a register name, you need two consecutive
29775 percent signs for such names in the Asm template string, thus @code{%%eax}.
29776 In the generated assembly code, one of the percent signs will be stripped off.
29777
29778 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29779 variables: operands you later define using @code{Input} or @code{Output}
29780 parameters to @code{Asm}.
29781 An output variable is illustrated in
29782 the third statement in the Asm template string:
29783 @smallexample
29784 movl %%eax, %0
29785 @end smallexample
29786 The intent is to store the contents of the eax register in a variable that can
29787 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
29788 necessarily work, since the compiler might optimize by using a register
29789 to hold Flags, and the expansion of the @code{movl} instruction would not be
29790 aware of this optimization. The solution is not to store the result directly
29791 but rather to advise the compiler to choose the correct operand form;
29792 that is the purpose of the @code{%0} output variable.
29793
29794 Information about the output variable is supplied in the @code{Outputs}
29795 parameter to @code{Asm}:
29796 @smallexample
29797 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29798 @end smallexample
29799
29800 The output is defined by the @code{Asm_Output} attribute of the target type;
29801 the general format is
29802 @smallexample
29803 Type'Asm_Output (constraint_string, variable_name)
29804 @end smallexample
29805
29806 The constraint string directs the compiler how
29807 to store/access the associated variable. In the example
29808 @smallexample
29809 Unsigned_32'Asm_Output ("=m", Flags);
29810 @end smallexample
29811 the @code{"m"} (memory) constraint tells the compiler that the variable
29812 @code{Flags} should be stored in a memory variable, thus preventing
29813 the optimizer from keeping it in a register. In contrast,
29814 @smallexample
29815 Unsigned_32'Asm_Output ("=r", Flags);
29816 @end smallexample
29817 uses the @code{"r"} (register) constraint, telling the compiler to
29818 store the variable in a register.
29819
29820 If the constraint is preceded by the equal character (@strong{=}), it tells
29821 the compiler that the variable will be used to store data into it.
29822
29823 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29824 allowing the optimizer to choose whatever it deems best.
29825
29826 There are a fairly large number of constraints, but the ones that are
29827 most useful (for the Intel x86 processor) are the following:
29828
29829 @table @code
29830 @item =
29831 output constraint
29832 @item g
29833 global (i.e.@: can be stored anywhere)
29834 @item m
29835 in memory
29836 @item I
29837 a constant
29838 @item a
29839 use eax
29840 @item b
29841 use ebx
29842 @item c
29843 use ecx
29844 @item d
29845 use edx
29846 @item S
29847 use esi
29848 @item D
29849 use edi
29850 @item r
29851 use one of eax, ebx, ecx or edx
29852 @item q
29853 use one of eax, ebx, ecx, edx, esi or edi
29854 @end table
29855
29856 The full set of constraints is described in the gcc and @emph{as}
29857 documentation; note that it is possible to combine certain constraints
29858 in one constraint string.
29859
29860 You specify the association of an output variable with an assembler operand
29861 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29862 integer. Thus in
29863 @smallexample @c ada
29864 @group
29865 Asm ("pushfl" & LF & HT & -- push flags on stack
29866 "popl %%eax" & LF & HT & -- load eax with flags
29867 "movl %%eax, %0", -- store flags in variable
29868 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29869 @end group
29870 @end smallexample
29871 @noindent
29872 @code{%0} will be replaced in the expanded code by the appropriate operand,
29873 whatever
29874 the compiler decided for the @code{Flags} variable.
29875
29876 In general, you may have any number of output variables:
29877 @itemize @bullet
29878 @item
29879 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29880 @item
29881 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29882 of @code{Asm_Output} attributes
29883 @end itemize
29884
29885 For example:
29886 @smallexample @c ada
29887 @group
29888 Asm ("movl %%eax, %0" & LF & HT &
29889 "movl %%ebx, %1" & LF & HT &
29890 "movl %%ecx, %2",
29891 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
29892 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
29893 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
29894 @end group
29895 @end smallexample
29896 @noindent
29897 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29898 in the Ada program.
29899
29900 As a variation on the @code{Get_Flags} example, we can use the constraints
29901 string to direct the compiler to store the eax register into the @code{Flags}
29902 variable, instead of including the store instruction explicitly in the
29903 @code{Asm} template string:
29904
29905 @smallexample @c ada
29906 @group
29907 with Interfaces; use Interfaces;
29908 with Ada.Text_IO; use Ada.Text_IO;
29909 with System.Machine_Code; use System.Machine_Code;
29910 procedure Get_Flags_2 is
29911 Flags : Unsigned_32;
29912 use ASCII;
29913 begin
29914 Asm ("pushfl" & LF & HT & -- push flags on stack
29915 "popl %%eax", -- save flags in eax
29916 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29917 Put_Line ("Flags register:" & Flags'Img);
29918 end Get_Flags_2;
29919 @end group
29920 @end smallexample
29921
29922 @noindent
29923 The @code{"a"} constraint tells the compiler that the @code{Flags}
29924 variable will come from the eax register. Here is the resulting code:
29925
29926 @smallexample
29927 @group
29928 #APP
29929 pushfl
29930 popl %eax
29931 #NO_APP
29932 movl %eax,-40(%ebp)
29933 @end group
29934 @end smallexample
29935
29936 @noindent
29937 The compiler generated the store of eax into Flags after
29938 expanding the assembler code.
29939
29940 Actually, there was no need to pop the flags into the eax register;
29941 more simply, we could just pop the flags directly into the program variable:
29942
29943 @smallexample @c ada
29944 @group
29945 with Interfaces; use Interfaces;
29946 with Ada.Text_IO; use Ada.Text_IO;
29947 with System.Machine_Code; use System.Machine_Code;
29948 procedure Get_Flags_3 is
29949 Flags : Unsigned_32;
29950 use ASCII;
29951 begin
29952 Asm ("pushfl" & LF & HT & -- push flags on stack
29953 "pop %0", -- save flags in Flags
29954 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29955 Put_Line ("Flags register:" & Flags'Img);
29956 end Get_Flags_3;
29957 @end group
29958 @end smallexample
29959
29960 @c ---------------------------------------------------------------------------
29961 @node Input Variables in Inline Assembler
29962 @section Input Variables in Inline Assembler
29963
29964 @noindent
29965 The example in this section illustrates how to specify the source operands
29966 for assembly language statements.
29967 The program simply increments its input value by 1:
29968
29969 @smallexample @c ada
29970 @group
29971 with Interfaces; use Interfaces;
29972 with Ada.Text_IO; use Ada.Text_IO;
29973 with System.Machine_Code; use System.Machine_Code;
29974 procedure Increment is
29975
29976 function Incr (Value : Unsigned_32) return Unsigned_32 is
29977 Result : Unsigned_32;
29978 begin
29979 Asm ("incl %0",
29980 Inputs => Unsigned_32'Asm_Input ("a", Value),
29981 Outputs => Unsigned_32'Asm_Output ("=a", Result));
29982 return Result;
29983 end Incr;
29984
29985 Value : Unsigned_32;
29986
29987 begin
29988 Value := 5;
29989 Put_Line ("Value before is" & Value'Img);
29990 Value := Incr (Value);
29991 Put_Line ("Value after is" & Value'Img);
29992 end Increment;
29993 @end group
29994 @end smallexample
29995
29996 The @code{Outputs} parameter to @code{Asm} specifies
29997 that the result will be in the eax register and that it is to be stored
29998 in the @code{Result} variable.
29999
30000 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30001 but with an @code{Asm_Input} attribute.
30002 The @code{"="} constraint, indicating an output value, is not present.
30003
30004 You can have multiple input variables, in the same way that you can have more
30005 than one output variable.
30006
30007 The parameter count (%0, %1) etc, now starts at the first input
30008 statement, and continues with the output statements.
30009 When both parameters use the same variable, the
30010 compiler will treat them as the same %n operand, which is the case here.
30011
30012 Just as the @code{Outputs} parameter causes the register to be stored into the
30013 target variable after execution of the assembler statements, so does the
30014 @code{Inputs} parameter cause its variable to be loaded into the register
30015 before execution of the assembler statements.
30016
30017 Thus the effect of the @code{Asm} invocation is:
30018 @enumerate
30019 @item load the 32-bit value of @code{Value} into eax
30020 @item execute the @code{incl %eax} instruction
30021 @item store the contents of eax into the @code{Result} variable
30022 @end enumerate
30023
30024 The resulting assembler file (with @option{-O2} optimization) contains:
30025 @smallexample
30026 @group
30027 _increment__incr.1:
30028 subl $4,%esp
30029 movl 8(%esp),%eax
30030 #APP
30031 incl %eax
30032 #NO_APP
30033 movl %eax,%edx
30034 movl %ecx,(%esp)
30035 addl $4,%esp
30036 ret
30037 @end group
30038 @end smallexample
30039
30040 @c ---------------------------------------------------------------------------
30041 @node Inlining Inline Assembler Code
30042 @section Inlining Inline Assembler Code
30043
30044 @noindent
30045 For a short subprogram such as the @code{Incr} function in the previous
30046 section, the overhead of the call and return (creating / deleting the stack
30047 frame) can be significant, compared to the amount of code in the subprogram
30048 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30049 which directs the compiler to expand invocations of the subprogram at the
30050 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30051 Here is the resulting program:
30052
30053 @smallexample @c ada
30054 @group
30055 with Interfaces; use Interfaces;
30056 with Ada.Text_IO; use Ada.Text_IO;
30057 with System.Machine_Code; use System.Machine_Code;
30058 procedure Increment_2 is
30059
30060 function Incr (Value : Unsigned_32) return Unsigned_32 is
30061 Result : Unsigned_32;
30062 begin
30063 Asm ("incl %0",
30064 Inputs => Unsigned_32'Asm_Input ("a", Value),
30065 Outputs => Unsigned_32'Asm_Output ("=a", Result));
30066 return Result;
30067 end Incr;
30068 pragma Inline (Increment);
30069
30070 Value : Unsigned_32;
30071
30072 begin
30073 Value := 5;
30074 Put_Line ("Value before is" & Value'Img);
30075 Value := Increment (Value);
30076 Put_Line ("Value after is" & Value'Img);
30077 end Increment_2;
30078 @end group
30079 @end smallexample
30080
30081 Compile the program with both optimization (@option{-O2}) and inlining
30082 (@option{-gnatn}) enabled.
30083
30084 The @code{Incr} function is still compiled as usual, but at the
30085 point in @code{Increment} where our function used to be called:
30086
30087 @smallexample
30088 @group
30089 pushl %edi
30090 call _increment__incr.1
30091 @end group
30092 @end smallexample
30093
30094 @noindent
30095 the code for the function body directly appears:
30096
30097 @smallexample
30098 @group
30099 movl %esi,%eax
30100 #APP
30101 incl %eax
30102 #NO_APP
30103 movl %eax,%edx
30104 @end group
30105 @end smallexample
30106
30107 @noindent
30108 thus saving the overhead of stack frame setup and an out-of-line call.
30109
30110 @c ---------------------------------------------------------------------------
30111 @node Other Asm Functionality
30112 @section Other @code{Asm} Functionality
30113
30114 @noindent
30115 This section describes two important parameters to the @code{Asm}
30116 procedure: @code{Clobber}, which identifies register usage;
30117 and @code{Volatile}, which inhibits unwanted optimizations.
30118
30119 @menu
30120 * The Clobber Parameter::
30121 * The Volatile Parameter::
30122 @end menu
30123
30124 @c ---------------------------------------------------------------------------
30125 @node The Clobber Parameter
30126 @subsection The @code{Clobber} Parameter
30127
30128 @noindent
30129 One of the dangers of intermixing assembly language and a compiled language
30130 such as Ada is that the compiler needs to be aware of which registers are
30131 being used by the assembly code. In some cases, such as the earlier examples,
30132 the constraint string is sufficient to indicate register usage (e.g.,
30133 @code{"a"} for
30134 the eax register). But more generally, the compiler needs an explicit
30135 identification of the registers that are used by the Inline Assembly
30136 statements.
30137
30138 Using a register that the compiler doesn't know about
30139 could be a side effect of an instruction (like @code{mull}
30140 storing its result in both eax and edx).
30141 It can also arise from explicit register usage in your
30142 assembly code; for example:
30143 @smallexample
30144 @group
30145 Asm ("movl %0, %%ebx" & LF & HT &
30146 "movl %%ebx, %1",
30147 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30148 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30149 @end group
30150 @end smallexample
30151 @noindent
30152 where the compiler (since it does not analyze the @code{Asm} template string)
30153 does not know you are using the ebx register.
30154
30155 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30156 to identify the registers that will be used by your assembly code:
30157
30158 @smallexample
30159 @group
30160 Asm ("movl %0, %%ebx" & LF & HT &
30161 "movl %%ebx, %1",
30162 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30163 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30164 Clobber => "ebx");
30165 @end group
30166 @end smallexample
30167
30168 The Clobber parameter is a static string expression specifying the
30169 register(s) you are using. Note that register names are @emph{not} prefixed
30170 by a percent sign. Also, if more than one register is used then their names
30171 are separated by commas; e.g., @code{"eax, ebx"}
30172
30173 The @code{Clobber} parameter has several additional uses:
30174 @enumerate
30175 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30176 @item Use ``register'' name @code{memory} if you changed a memory location
30177 @end enumerate
30178
30179 @c ---------------------------------------------------------------------------
30180 @node The Volatile Parameter
30181 @subsection The @code{Volatile} Parameter
30182 @cindex Volatile parameter
30183
30184 @noindent
30185 Compiler optimizations in the presence of Inline Assembler may sometimes have
30186 unwanted effects. For example, when an @code{Asm} invocation with an input
30187 variable is inside a loop, the compiler might move the loading of the input
30188 variable outside the loop, regarding it as a one-time initialization.
30189
30190 If this effect is not desired, you can disable such optimizations by setting
30191 the @code{Volatile} parameter to @code{True}; for example:
30192
30193 @smallexample @c ada
30194 @group
30195 Asm ("movl %0, %%ebx" & LF & HT &
30196 "movl %%ebx, %1",
30197 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
30198 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30199 Clobber => "ebx",
30200 Volatile => True);
30201 @end group
30202 @end smallexample
30203
30204 By default, @code{Volatile} is set to @code{False} unless there is no
30205 @code{Outputs} parameter.
30206
30207 Although setting @code{Volatile} to @code{True} prevents unwanted
30208 optimizations, it will also disable other optimizations that might be
30209 important for efficiency. In general, you should set @code{Volatile}
30210 to @code{True} only if the compiler's optimizations have created
30211 problems.
30212 @c END OF INLINE ASSEMBLER CHAPTER
30213 @c ===============================
30214
30215 @c ***********************************
30216 @c * Compatibility and Porting Guide *
30217 @c ***********************************
30218 @node Compatibility and Porting Guide
30219 @appendix Compatibility and Porting Guide
30220
30221 @noindent
30222 This chapter describes the compatibility issues that may arise between
30223 GNAT and other Ada compilation systems (including those for Ada 83),
30224 and shows how GNAT can expedite porting
30225 applications developed in other Ada environments.
30226
30227 @menu
30228 * Compatibility with Ada 83::
30229 * Compatibility between Ada 95 and Ada 2005::
30230 * Implementation-dependent characteristics::
30231 * Compatibility with Other Ada Systems::
30232 * Representation Clauses::
30233 @ifclear vms
30234 @c Brief section is only in non-VMS version
30235 @c Full chapter is in VMS version
30236 * Compatibility with HP Ada 83::
30237 @end ifclear
30238 @ifset vms
30239 * Transitioning to 64-Bit GNAT for OpenVMS::
30240 @end ifset
30241 @end menu
30242
30243 @node Compatibility with Ada 83
30244 @section Compatibility with Ada 83
30245 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30246
30247 @noindent
30248 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
30249 particular, the design intention was that the difficulties associated
30250 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30251 that occur when moving from one Ada 83 system to another.
30252
30253 However, there are a number of points at which there are minor
30254 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
30255 full details of these issues,
30256 and should be consulted for a complete treatment.
30257 In practice the
30258 following subsections treat the most likely issues to be encountered.
30259
30260 @menu
30261 * Legal Ada 83 programs that are illegal in Ada 95::
30262 * More deterministic semantics::
30263 * Changed semantics::
30264 * Other language compatibility issues::
30265 @end menu
30266
30267 @node Legal Ada 83 programs that are illegal in Ada 95
30268 @subsection Legal Ada 83 programs that are illegal in Ada 95
30269
30270 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30271 Ada 95 and thus also in Ada 2005:
30272
30273 @table @emph
30274 @item Character literals
30275 Some uses of character literals are ambiguous. Since Ada 95 has introduced
30276 @code{Wide_Character} as a new predefined character type, some uses of
30277 character literals that were legal in Ada 83 are illegal in Ada 95.
30278 For example:
30279 @smallexample @c ada
30280 for Char in 'A' .. 'Z' loop @dots{} end loop;
30281 @end smallexample
30282
30283 @noindent
30284 The problem is that @code{'A'} and @code{'Z'} could be from either
30285 @code{Character} or @code{Wide_Character}. The simplest correction
30286 is to make the type explicit; e.g.:
30287 @smallexample @c ada
30288 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30289 @end smallexample
30290
30291 @item New reserved words
30292 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30293 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30294 Existing Ada 83 code using any of these identifiers must be edited to
30295 use some alternative name.
30296
30297 @item Freezing rules
30298 The rules in Ada 95 are slightly different with regard to the point at
30299 which entities are frozen, and representation pragmas and clauses are
30300 not permitted past the freeze point. This shows up most typically in
30301 the form of an error message complaining that a representation item
30302 appears too late, and the appropriate corrective action is to move
30303 the item nearer to the declaration of the entity to which it refers.
30304
30305 A particular case is that representation pragmas
30306 @ifset vms
30307 (including the
30308 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30309 @end ifset
30310 cannot be applied to a subprogram body. If necessary, a separate subprogram
30311 declaration must be introduced to which the pragma can be applied.
30312
30313 @item Optional bodies for library packages
30314 In Ada 83, a package that did not require a package body was nevertheless
30315 allowed to have one. This lead to certain surprises in compiling large
30316 systems (situations in which the body could be unexpectedly ignored by the
30317 binder). In Ada 95, if a package does not require a body then it is not
30318 permitted to have a body. To fix this problem, simply remove a redundant
30319 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30320 into the spec that makes the body required. One approach is to add a private
30321 part to the package declaration (if necessary), and define a parameterless
30322 procedure called @code{Requires_Body}, which must then be given a dummy
30323 procedure body in the package body, which then becomes required.
30324 Another approach (assuming that this does not introduce elaboration
30325 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30326 since one effect of this pragma is to require the presence of a package body.
30327
30328 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30329 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30330 @code{Constraint_Error}.
30331 This means that it is illegal to have separate exception handlers for
30332 the two exceptions. The fix is simply to remove the handler for the
30333 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30334 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30335
30336 @item Indefinite subtypes in generics
30337 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30338 as the actual for a generic formal private type, but then the instantiation
30339 would be illegal if there were any instances of declarations of variables
30340 of this type in the generic body. In Ada 95, to avoid this clear violation
30341 of the methodological principle known as the ``contract model'',
30342 the generic declaration explicitly indicates whether
30343 or not such instantiations are permitted. If a generic formal parameter
30344 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30345 type name, then it can be instantiated with indefinite types, but no
30346 stand-alone variables can be declared of this type. Any attempt to declare
30347 such a variable will result in an illegality at the time the generic is
30348 declared. If the @code{(<>)} notation is not used, then it is illegal
30349 to instantiate the generic with an indefinite type.
30350 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30351 It will show up as a compile time error, and
30352 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30353 @end table
30354
30355 @node More deterministic semantics
30356 @subsection More deterministic semantics
30357
30358 @table @emph
30359 @item Conversions
30360 Conversions from real types to integer types round away from 0. In Ada 83
30361 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
30362 implementation freedom was intended to support unbiased rounding in
30363 statistical applications, but in practice it interfered with portability.
30364 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30365 is required. Numeric code may be affected by this change in semantics.
30366 Note, though, that this issue is no worse than already existed in Ada 83
30367 when porting code from one vendor to another.
30368
30369 @item Tasking
30370 The Real-Time Annex introduces a set of policies that define the behavior of
30371 features that were implementation dependent in Ada 83, such as the order in
30372 which open select branches are executed.
30373 @end table
30374
30375 @node Changed semantics
30376 @subsection Changed semantics
30377
30378 @noindent
30379 The worst kind of incompatibility is one where a program that is legal in
30380 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30381 possible in Ada 83. Fortunately this is extremely rare, but the one
30382 situation that you should be alert to is the change in the predefined type
30383 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30384
30385 @table @emph
30386 @item Range of type @code{Character}
30387 The range of @code{Standard.Character} is now the full 256 characters
30388 of Latin-1, whereas in most Ada 83 implementations it was restricted
30389 to 128 characters. Although some of the effects of
30390 this change will be manifest in compile-time rejection of legal
30391 Ada 83 programs it is possible for a working Ada 83 program to have
30392 a different effect in Ada 95, one that was not permitted in Ada 83.
30393 As an example, the expression
30394 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30395 delivers @code{255} as its value.
30396 In general, you should look at the logic of any
30397 character-processing Ada 83 program and see whether it needs to be adapted
30398 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
30399 character handling package that may be relevant if code needs to be adapted
30400 to account for the additional Latin-1 elements.
30401 The desirable fix is to
30402 modify the program to accommodate the full character set, but in some cases
30403 it may be convenient to define a subtype or derived type of Character that
30404 covers only the restricted range.
30405 @cindex Latin-1
30406 @end table
30407
30408 @node Other language compatibility issues
30409 @subsection Other language compatibility issues
30410
30411 @table @emph
30412 @item @option{-gnat83} switch
30413 All implementations of GNAT provide a switch that causes GNAT to operate
30414 in Ada 83 mode. In this mode, some but not all compatibility problems
30415 of the type described above are handled automatically. For example, the
30416 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30417 as identifiers as in Ada 83.
30418 However,
30419 in practice, it is usually advisable to make the necessary modifications
30420 to the program to remove the need for using this switch.
30421 See @ref{Compiling Different Versions of Ada}.
30422
30423 @item Support for removed Ada 83 pragmas and attributes
30424 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30425 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
30426 compilers are allowed, but not required, to implement these missing
30427 elements. In contrast with some other compilers, GNAT implements all
30428 such pragmas and attributes, eliminating this compatibility concern. These
30429 include @code{pragma Interface} and the floating point type attributes
30430 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30431 @end table
30432
30433
30434 @node Compatibility between Ada 95 and Ada 2005
30435 @section Compatibility between Ada 95 and Ada 2005
30436 @cindex Compatibility between Ada 95 and Ada 2005
30437
30438 @noindent
30439 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30440 a number of incompatibilities. Several are enumerated below;
30441 for a complete description please see the
30442 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30443 @cite{Rationale for Ada 2005}.
30444
30445 @table @emph
30446 @item New reserved words.
30447 The words @code{interface}, @code{overriding} and @code{synchronized} are
30448 reserved in Ada 2005.
30449 A pre-Ada 2005 program that uses any of these as an identifier will be
30450 illegal.
30451
30452 @item New declarations in predefined packages.
30453 A number of packages in the predefined environment contain new declarations:
30454 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30455 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30456 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30457 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30458 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30459 If an Ada 95 program does a @code{with} and @code{use} of any of these
30460 packages, the new declarations may cause name clashes.
30461
30462 @item Access parameters.
30463 A nondispatching subprogram with an access parameter cannot be renamed
30464 as a dispatching operation. This was permitted in Ada 95.
30465
30466 @item Access types, discriminants, and constraints.
30467 Rule changes in this area have led to some incompatibilities; for example,
30468 constrained subtypes of some access types are not permitted in Ada 2005.
30469
30470 @item Aggregates for limited types.
30471 The allowance of aggregates for limited types in Ada 2005 raises the
30472 possibility of ambiguities in legal Ada 95 programs, since additional types
30473 now need to be considered in expression resolution.
30474
30475 @item Fixed-point multiplication and division.
30476 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30477 were legal in Ada 95 and invoked the predefined versions of these operations,
30478 are now ambiguous.
30479 The ambiguity may be resolved either by applying a type conversion to the
30480 expression, or by explicitly invoking the operation from package
30481 @code{Standard}.
30482
30483 @item Return-by-reference types.
30484 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
30485 can declare a function returning a value from an anonymous access type.
30486 @end table
30487
30488
30489 @node Implementation-dependent characteristics
30490 @section Implementation-dependent characteristics
30491 @noindent
30492 Although the Ada language defines the semantics of each construct as
30493 precisely as practical, in some situations (for example for reasons of
30494 efficiency, or where the effect is heavily dependent on the host or target
30495 platform) the implementation is allowed some freedom. In porting Ada 83
30496 code to GNAT, you need to be aware of whether / how the existing code
30497 exercised such implementation dependencies. Such characteristics fall into
30498 several categories, and GNAT offers specific support in assisting the
30499 transition from certain Ada 83 compilers.
30500
30501 @menu
30502 * Implementation-defined pragmas::
30503 * Implementation-defined attributes::
30504 * Libraries::
30505 * Elaboration order::
30506 * Target-specific aspects::
30507 @end menu
30508
30509 @node Implementation-defined pragmas
30510 @subsection Implementation-defined pragmas
30511
30512 @noindent
30513 Ada compilers are allowed to supplement the language-defined pragmas, and
30514 these are a potential source of non-portability. All GNAT-defined pragmas
30515 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30516 Reference Manual}, and these include several that are specifically
30517 intended to correspond to other vendors' Ada 83 pragmas.
30518 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30519 For compatibility with HP Ada 83, GNAT supplies the pragmas
30520 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30521 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30522 and @code{Volatile}.
30523 Other relevant pragmas include @code{External} and @code{Link_With}.
30524 Some vendor-specific
30525 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30526 recognized, thus
30527 avoiding compiler rejection of units that contain such pragmas; they are not
30528 relevant in a GNAT context and hence are not otherwise implemented.
30529
30530 @node Implementation-defined attributes
30531 @subsection Implementation-defined attributes
30532
30533 Analogous to pragmas, the set of attributes may be extended by an
30534 implementation. All GNAT-defined attributes are described in
30535 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30536 Manual}, and these include several that are specifically intended
30537 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
30538 the attribute @code{VADS_Size} may be useful. For compatibility with HP
30539 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30540 @code{Type_Class}.
30541
30542 @node Libraries
30543 @subsection Libraries
30544 @noindent
30545 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
30546 code uses vendor-specific libraries then there are several ways to manage
30547 this in Ada 95 or Ada 2005:
30548 @enumerate
30549 @item
30550 If the source code for the libraries (specs and bodies) are
30551 available, then the libraries can be migrated in the same way as the
30552 application.
30553 @item
30554 If the source code for the specs but not the bodies are
30555 available, then you can reimplement the bodies.
30556 @item
30557 Some features introduced by Ada 95 obviate the need for library support. For
30558 example most Ada 83 vendors supplied a package for unsigned integers. The
30559 Ada 95 modular type feature is the preferred way to handle this need, so
30560 instead of migrating or reimplementing the unsigned integer package it may
30561 be preferable to retrofit the application using modular types.
30562 @end enumerate
30563
30564 @node Elaboration order
30565 @subsection Elaboration order
30566 @noindent
30567 The implementation can choose any elaboration order consistent with the unit
30568 dependency relationship. This freedom means that some orders can result in
30569 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30570 to invoke a subprogram its body has been elaborated, or to instantiate a
30571 generic before the generic body has been elaborated. By default GNAT
30572 attempts to choose a safe order (one that will not encounter access before
30573 elaboration problems) by implicitly inserting @code{Elaborate} or
30574 @code{Elaborate_All} pragmas where
30575 needed. However, this can lead to the creation of elaboration circularities
30576 and a resulting rejection of the program by gnatbind. This issue is
30577 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30578 In brief, there are several
30579 ways to deal with this situation:
30580
30581 @itemize @bullet
30582 @item
30583 Modify the program to eliminate the circularities, e.g.@: by moving
30584 elaboration-time code into explicitly-invoked procedures
30585 @item
30586 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30587 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30588 @code{Elaborate_All}
30589 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30590 (by selectively suppressing elaboration checks via pragma
30591 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30592 @end itemize
30593
30594 @node Target-specific aspects
30595 @subsection Target-specific aspects
30596 @noindent
30597 Low-level applications need to deal with machine addresses, data
30598 representations, interfacing with assembler code, and similar issues. If
30599 such an Ada 83 application is being ported to different target hardware (for
30600 example where the byte endianness has changed) then you will need to
30601 carefully examine the program logic; the porting effort will heavily depend
30602 on the robustness of the original design. Moreover, Ada 95 (and thus
30603 Ada 2005) are sometimes
30604 incompatible with typical Ada 83 compiler practices regarding implicit
30605 packing, the meaning of the Size attribute, and the size of access values.
30606 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30607
30608 @node Compatibility with Other Ada Systems
30609 @section Compatibility with Other Ada Systems
30610
30611 @noindent
30612 If programs avoid the use of implementation dependent and
30613 implementation defined features, as documented in the @cite{Ada
30614 Reference Manual}, there should be a high degree of portability between
30615 GNAT and other Ada systems. The following are specific items which
30616 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30617 compilers, but do not affect porting code to GNAT@.
30618 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30619 the following issues may or may not arise for Ada 2005 programs
30620 when other compilers appear.)
30621
30622 @table @emph
30623 @item Ada 83 Pragmas and Attributes
30624 Ada 95 compilers are allowed, but not required, to implement the missing
30625 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30626 GNAT implements all such pragmas and attributes, eliminating this as
30627 a compatibility concern, but some other Ada 95 compilers reject these
30628 pragmas and attributes.
30629
30630 @item Specialized Needs Annexes
30631 GNAT implements the full set of special needs annexes. At the
30632 current time, it is the only Ada 95 compiler to do so. This means that
30633 programs making use of these features may not be portable to other Ada
30634 95 compilation systems.
30635
30636 @item Representation Clauses
30637 Some other Ada 95 compilers implement only the minimal set of
30638 representation clauses required by the Ada 95 reference manual. GNAT goes
30639 far beyond this minimal set, as described in the next section.
30640 @end table
30641
30642 @node Representation Clauses
30643 @section Representation Clauses
30644
30645 @noindent
30646 The Ada 83 reference manual was quite vague in describing both the minimal
30647 required implementation of representation clauses, and also their precise
30648 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
30649 minimal set of capabilities required is still quite limited.
30650
30651 GNAT implements the full required set of capabilities in
30652 Ada 95 and Ada 2005, but also goes much further, and in particular
30653 an effort has been made to be compatible with existing Ada 83 usage to the
30654 greatest extent possible.
30655
30656 A few cases exist in which Ada 83 compiler behavior is incompatible with
30657 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
30658 intentional or accidental dependence on specific implementation dependent
30659 characteristics of these Ada 83 compilers. The following is a list of
30660 the cases most likely to arise in existing Ada 83 code.
30661
30662 @table @emph
30663 @item Implicit Packing
30664 Some Ada 83 compilers allowed a Size specification to cause implicit
30665 packing of an array or record. This could cause expensive implicit
30666 conversions for change of representation in the presence of derived
30667 types, and the Ada design intends to avoid this possibility.
30668 Subsequent AI's were issued to make it clear that such implicit
30669 change of representation in response to a Size clause is inadvisable,
30670 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30671 Reference Manuals as implementation advice that is followed by GNAT@.
30672 The problem will show up as an error
30673 message rejecting the size clause. The fix is simply to provide
30674 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30675 a Component_Size clause.
30676
30677 @item Meaning of Size Attribute
30678 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30679 the minimal number of bits required to hold values of the type. For example,
30680 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30681 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
30682 some 32 in this situation. This problem will usually show up as a compile
30683 time error, but not always. It is a good idea to check all uses of the
30684 'Size attribute when porting Ada 83 code. The GNAT specific attribute
30685 Object_Size can provide a useful way of duplicating the behavior of
30686 some Ada 83 compiler systems.
30687
30688 @item Size of Access Types
30689 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30690 and that therefore it will be the same size as a System.Address value. This
30691 assumption is true for GNAT in most cases with one exception. For the case of
30692 a pointer to an unconstrained array type (where the bounds may vary from one
30693 value of the access type to another), the default is to use a ``fat pointer'',
30694 which is represented as two separate pointers, one to the bounds, and one to
30695 the array. This representation has a number of advantages, including improved
30696 efficiency. However, it may cause some difficulties in porting existing Ada 83
30697 code which makes the assumption that, for example, pointers fit in 32 bits on
30698 a machine with 32-bit addressing.
30699
30700 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30701 access types in this case (where the designated type is an unconstrained array
30702 type). These thin pointers are indeed the same size as a System.Address value.
30703 To specify a thin pointer, use a size clause for the type, for example:
30704
30705 @smallexample @c ada
30706 type X is access all String;
30707 for X'Size use Standard'Address_Size;
30708 @end smallexample
30709
30710 @noindent
30711 which will cause the type X to be represented using a single pointer.
30712 When using this representation, the bounds are right behind the array.
30713 This representation is slightly less efficient, and does not allow quite
30714 such flexibility in the use of foreign pointers or in using the
30715 Unrestricted_Access attribute to create pointers to non-aliased objects.
30716 But for any standard portable use of the access type it will work in
30717 a functionally correct manner and allow porting of existing code.
30718 Note that another way of forcing a thin pointer representation
30719 is to use a component size clause for the element size in an array,
30720 or a record representation clause for an access field in a record.
30721 @end table
30722
30723 @ifclear vms
30724 @c This brief section is only in the non-VMS version
30725 @c The complete chapter on HP Ada is in the VMS version
30726 @node Compatibility with HP Ada 83
30727 @section Compatibility with HP Ada 83
30728
30729 @noindent
30730 The VMS version of GNAT fully implements all the pragmas and attributes
30731 provided by HP Ada 83, as well as providing the standard HP Ada 83
30732 libraries, including Starlet. In addition, data layouts and parameter
30733 passing conventions are highly compatible. This means that porting
30734 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30735 most other porting efforts. The following are some of the most
30736 significant differences between GNAT and HP Ada 83.
30737
30738 @table @emph
30739 @item Default floating-point representation
30740 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30741 it is VMS format. GNAT does implement the necessary pragmas
30742 (Long_Float, Float_Representation) for changing this default.
30743
30744 @item System
30745 The package System in GNAT exactly corresponds to the definition in the
30746 Ada 95 reference manual, which means that it excludes many of the
30747 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
30748 that contains the additional definitions, and a special pragma,
30749 Extend_System allows this package to be treated transparently as an
30750 extension of package System.
30751
30752 @item To_Address
30753 The definitions provided by Aux_DEC are exactly compatible with those
30754 in the HP Ada 83 version of System, with one exception.
30755 HP Ada provides the following declarations:
30756
30757 @smallexample @c ada
30758 TO_ADDRESS (INTEGER)
30759 TO_ADDRESS (UNSIGNED_LONGWORD)
30760 TO_ADDRESS (@i{universal_integer})
30761 @end smallexample
30762
30763 @noindent
30764 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30765 an extension to Ada 83 not strictly compatible with the reference manual.
30766 In GNAT, we are constrained to be exactly compatible with the standard,
30767 and this means we cannot provide this capability. In HP Ada 83, the
30768 point of this definition is to deal with a call like:
30769
30770 @smallexample @c ada
30771 TO_ADDRESS (16#12777#);
30772 @end smallexample
30773
30774 @noindent
30775 Normally, according to the Ada 83 standard, one would expect this to be
30776 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30777 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
30778 definition using @i{universal_integer} takes precedence.
30779
30780 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30781 is not possible to be 100% compatible. Since there are many programs using
30782 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30783 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30784 declarations provided in the GNAT version of AUX_Dec are:
30785
30786 @smallexample @c ada
30787 function To_Address (X : Integer) return Address;
30788 pragma Pure_Function (To_Address);
30789
30790 function To_Address_Long (X : Unsigned_Longword)
30791 return Address;
30792 pragma Pure_Function (To_Address_Long);
30793 @end smallexample
30794
30795 @noindent
30796 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30797 change the name to TO_ADDRESS_LONG@.
30798
30799 @item Task_Id values
30800 The Task_Id values assigned will be different in the two systems, and GNAT
30801 does not provide a specified value for the Task_Id of the environment task,
30802 which in GNAT is treated like any other declared task.
30803 @end table
30804
30805 @noindent
30806 For full details on these and other less significant compatibility issues,
30807 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30808 Overview and Comparison on HP Platforms}.
30809
30810 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30811 attributes are recognized, although only a subset of them can sensibly
30812 be implemented. The description of pragmas in @ref{Implementation
30813 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30814 indicates whether or not they are applicable to non-VMS systems.
30815 @end ifclear
30816
30817 @ifset vms
30818 @node Transitioning to 64-Bit GNAT for OpenVMS
30819 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30820
30821 @noindent
30822 This section is meant to assist users of pre-2006 @value{EDITION}
30823 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30824 the version of the GNAT technology supplied in 2006 and later for
30825 OpenVMS on both Alpha and I64.
30826
30827 @menu
30828 * Introduction to transitioning::
30829 * Migration of 32 bit code::
30830 * Taking advantage of 64 bit addressing::
30831 * Technical details::
30832 @end menu
30833
30834 @node Introduction to transitioning
30835 @subsection Introduction
30836
30837 @noindent
30838 64-bit @value{EDITION} for Open VMS has been designed to meet
30839 three main goals:
30840
30841 @enumerate
30842 @item
30843 Providing a full conforming implementation of Ada 95 and Ada 2005
30844
30845 @item
30846 Allowing maximum backward compatibility, thus easing migration of existing
30847 Ada source code
30848
30849 @item
30850 Supplying a path for exploiting the full 64-bit address range
30851 @end enumerate
30852
30853 @noindent
30854 Ada's strong typing semantics has made it
30855 impractical to have different 32-bit and 64-bit modes. As soon as
30856 one object could possibly be outside the 32-bit address space, this
30857 would make it necessary for the @code{System.Address} type to be 64 bits.
30858 In particular, this would cause inconsistencies if 32-bit code is
30859 called from 64-bit code that raises an exception.
30860
30861 This issue has been resolved by always using 64-bit addressing
30862 at the system level, but allowing for automatic conversions between
30863 32-bit and 64-bit addresses where required. Thus users who
30864 do not currently require 64-bit addressing capabilities, can
30865 recompile their code with only minimal changes (and indeed
30866 if the code is written in portable Ada, with no assumptions about
30867 the size of the @code{Address} type, then no changes at all are necessary).
30868 At the same time,
30869 this approach provides a simple, gradual upgrade path to future
30870 use of larger memories than available for 32-bit systems.
30871 Also, newly written applications or libraries will by default
30872 be fully compatible with future systems exploiting 64-bit
30873 addressing capabilities.
30874
30875 @ref{Migration of 32 bit code}, will focus on porting applications
30876 that do not require more than 2 GB of
30877 addressable memory. This code will be referred to as
30878 @emph{32-bit code}.
30879 For applications intending to exploit the full 64-bit address space,
30880 @ref{Taking advantage of 64 bit addressing},
30881 will consider further changes that may be required.
30882 Such code will be referred to below as @emph{64-bit code}.
30883
30884 @node Migration of 32 bit code
30885 @subsection Migration of 32-bit code
30886
30887 @menu
30888 * Address types::
30889 * Access types::
30890 * Unchecked conversions::
30891 * Predefined constants::
30892 * Interfacing with C::
30893 * Experience with source compatibility::
30894 @end menu
30895
30896 @node Address types
30897 @subsubsection Address types
30898
30899 @noindent
30900 To solve the problem of mixing 64-bit and 32-bit addressing,
30901 while maintaining maximum backward compatibility, the following
30902 approach has been taken:
30903
30904 @itemize @bullet
30905 @item
30906 @code{System.Address} always has a size of 64 bits
30907
30908 @item
30909 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30910 @end itemize
30911
30912 @noindent
30913 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30914 a @code{Short_Address}
30915 may be used where an @code{Address} is required, and vice versa, without
30916 needing explicit type conversions.
30917 By virtue of the Open VMS parameter passing conventions,
30918 even imported
30919 and exported subprograms that have 32-bit address parameters are
30920 compatible with those that have 64-bit address parameters.
30921 (See @ref{Making code 64 bit clean} for details.)
30922
30923 The areas that may need attention are those where record types have
30924 been defined that contain components of the type @code{System.Address}, and
30925 where objects of this type are passed to code expecting a record layout with
30926 32-bit addresses.
30927
30928 Different compilers on different platforms cannot be
30929 expected to represent the same type in the same way,
30930 since alignment constraints
30931 and other system-dependent properties affect the compiler's decision.
30932 For that reason, Ada code
30933 generally uses representation clauses to specify the expected
30934 layout where required.
30935
30936 If such a representation clause uses 32 bits for a component having
30937 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30938 will detect that error and produce a specific diagnostic message.
30939 The developer should then determine whether the representation
30940 should be 64 bits or not and make either of two changes:
30941 change the size to 64 bits and leave the type as @code{System.Address}, or
30942 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30943 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30944 required in any code setting or accessing the field; the compiler will
30945 automatically perform any needed conversions between address
30946 formats.
30947
30948 @node Access types
30949 @subsubsection Access types
30950
30951 @noindent
30952 By default, objects designated by access values are always
30953 allocated in the 32-bit
30954 address space. Thus legacy code will never contain
30955 any objects that are not addressable with 32-bit addresses, and
30956 the compiler will never raise exceptions as result of mixing
30957 32-bit and 64-bit addresses.
30958
30959 However, the access values themselves are represented in 64 bits, for optimum
30960 performance and future compatibility with 64-bit code. As was
30961 the case with @code{System.Address}, the compiler will give an error message
30962 if an object or record component has a representation clause that
30963 requires the access value to fit in 32 bits. In such a situation,
30964 an explicit size clause for the access type, specifying 32 bits,
30965 will have the desired effect.
30966
30967 General access types (declared with @code{access all}) can never be
30968 32 bits, as values of such types must be able to refer to any object
30969 of the designated type,
30970 including objects residing outside the 32-bit address range.
30971 Existing Ada 83 code will not contain such type definitions,
30972 however, since general access types were introduced in Ada 95.
30973
30974 @node Unchecked conversions
30975 @subsubsection Unchecked conversions
30976
30977 @noindent
30978 In the case of an @code{Unchecked_Conversion} where the source type is a
30979 64-bit access type or the type @code{System.Address}, and the target
30980 type is a 32-bit type, the compiler will generate a warning.
30981 Even though the generated code will still perform the required
30982 conversions, it is highly recommended in these cases to use
30983 respectively a 32-bit access type or @code{System.Short_Address}
30984 as the source type.
30985
30986 @node Predefined constants
30987 @subsubsection Predefined constants
30988
30989 @noindent
30990 The following table shows the correspondence between pre-2006 versions of
30991 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30992 (``New''):
30993
30994 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30995 @item @b{Constant} @tab @b{Old} @tab @b{New}
30996 @item @code{System.Word_Size} @tab 32 @tab 64
30997 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
30998 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
30999 @item @code{System.Address_Size} @tab 32 @tab 64
31000 @end multitable
31001
31002 @noindent
31003 If you need to refer to the specific
31004 memory size of a 32-bit implementation, instead of the
31005 actual memory size, use @code{System.Short_Memory_Size}
31006 rather than @code{System.Memory_Size}.
31007 Similarly, references to @code{System.Address_Size} may need
31008 to be replaced by @code{System.Short_Address'Size}.
31009 The program @command{gnatfind} may be useful for locating
31010 references to the above constants, so that you can verify that they
31011 are still correct.
31012
31013 @node Interfacing with C
31014 @subsubsection Interfacing with C
31015
31016 @noindent
31017 In order to minimize the impact of the transition to 64-bit addresses on
31018 legacy programs, some fundamental types in the @code{Interfaces.C}
31019 package hierarchy continue to be represented in 32 bits.
31020 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31021 This eases integration with the default HP C layout choices, for example
31022 as found in the system routines in @code{DECC$SHR.EXE}.
31023 Because of this implementation choice, the type fully compatible with
31024 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31025 Depending on the context the compiler will issue a
31026 warning or an error when type @code{Address} is used, alerting the user to a
31027 potential problem. Otherwise 32-bit programs that use
31028 @code{Interfaces.C} should normally not require code modifications
31029
31030 The other issue arising with C interfacing concerns pragma @code{Convention}.
31031 For VMS 64-bit systems, there is an issue of the appropriate default size
31032 of C convention pointers in the absence of an explicit size clause. The HP
31033 C compiler can choose either 32 or 64 bits depending on compiler options.
31034 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31035 clause is given. This proves a better choice for porting 32-bit legacy
31036 applications. In order to have a 64-bit representation, it is necessary to
31037 specify a size representation clause. For example:
31038
31039 @smallexample @c ada
31040 type int_star is access Interfaces.C.int;
31041 pragma Convention(C, int_star);
31042 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
31043 @end smallexample
31044
31045 @node Experience with source compatibility
31046 @subsubsection Experience with source compatibility
31047
31048 @noindent
31049 The Security Server and STARLET on I64 provide an interesting ``test case''
31050 for source compatibility issues, since it is in such system code
31051 where assumptions about @code{Address} size might be expected to occur.
31052 Indeed, there were a small number of occasions in the Security Server
31053 file @file{jibdef.ads}
31054 where a representation clause for a record type specified
31055 32 bits for a component of type @code{Address}.
31056 All of these errors were detected by the compiler.
31057 The repair was obvious and immediate; to simply replace @code{Address} by
31058 @code{Short_Address}.
31059
31060 In the case of STARLET, there were several record types that should
31061 have had representation clauses but did not. In these record types
31062 there was an implicit assumption that an @code{Address} value occupied
31063 32 bits.
31064 These compiled without error, but their usage resulted in run-time error
31065 returns from STARLET system calls.
31066 Future GNAT technology enhancements may include a tool that detects and flags
31067 these sorts of potential source code porting problems.
31068
31069 @c ****************************************
31070 @node Taking advantage of 64 bit addressing
31071 @subsection Taking advantage of 64-bit addressing
31072
31073 @menu
31074 * Making code 64 bit clean::
31075 * Allocating memory from the 64 bit storage pool::
31076 * Restrictions on use of 64 bit objects::
31077 * Using 64 bit storage pools by default::
31078 * General access types::
31079 * STARLET and other predefined libraries::
31080 @end menu
31081
31082 @node Making code 64 bit clean
31083 @subsubsection Making code 64-bit clean
31084
31085 @noindent
31086 In order to prevent problems that may occur when (parts of) a
31087 system start using memory outside the 32-bit address range,
31088 we recommend some additional guidelines:
31089
31090 @itemize @bullet
31091 @item
31092 For imported subprograms that take parameters of the
31093 type @code{System.Address}, ensure that these subprograms can
31094 indeed handle 64-bit addresses. If not, or when in doubt,
31095 change the subprogram declaration to specify
31096 @code{System.Short_Address} instead.
31097
31098 @item
31099 Resolve all warnings related to size mismatches in
31100 unchecked conversions. Failing to do so causes
31101 erroneous execution if the source object is outside
31102 the 32-bit address space.
31103
31104 @item
31105 (optional) Explicitly use the 32-bit storage pool
31106 for access types used in a 32-bit context, or use
31107 generic access types where possible
31108 (@pxref{Restrictions on use of 64 bit objects}).
31109 @end itemize
31110
31111 @noindent
31112 If these rules are followed, the compiler will automatically insert
31113 any necessary checks to ensure that no addresses or access values
31114 passed to 32-bit code ever refer to objects outside the 32-bit
31115 address range.
31116 Any attempt to do this will raise @code{Constraint_Error}.
31117
31118 @node Allocating memory from the 64 bit storage pool
31119 @subsubsection Allocating memory from the 64-bit storage pool
31120
31121 @noindent
31122 For any access type @code{T} that potentially requires memory allocations
31123 beyond the 32-bit address space,
31124 use the following representation clause:
31125
31126 @smallexample @c ada
31127 for T'Storage_Pool use System.Pool_64;
31128 @end smallexample
31129
31130 @node Restrictions on use of 64 bit objects
31131 @subsubsection Restrictions on use of 64-bit objects
31132
31133 @noindent
31134 Taking the address of an object allocated from a 64-bit storage pool,
31135 and then passing this address to a subprogram expecting
31136 @code{System.Short_Address},
31137 or assigning it to a variable of type @code{Short_Address}, will cause
31138 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31139 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31140 no exception is raised and execution
31141 will become erroneous.
31142
31143 @node Using 64 bit storage pools by default
31144 @subsubsection Using 64-bit storage pools by default
31145
31146 @noindent
31147 In some cases it may be desirable to have the compiler allocate
31148 from 64-bit storage pools by default. This may be the case for
31149 libraries that are 64-bit clean, but may be used in both 32-bit
31150 and 64-bit contexts. For these cases the following configuration
31151 pragma may be specified:
31152
31153 @smallexample @c ada
31154 pragma Pool_64_Default;
31155 @end smallexample
31156
31157 @noindent
31158 Any code compiled in the context of this pragma will by default
31159 use the @code{System.Pool_64} storage pool. This default may be overridden
31160 for a specific access type @code{T} by the representation clause:
31161
31162 @smallexample @c ada
31163 for T'Storage_Pool use System.Pool_32;
31164 @end smallexample
31165
31166 @noindent
31167 Any object whose address may be passed to a subprogram with a
31168 @code{Short_Address} argument, or assigned to a variable of type
31169 @code{Short_Address}, needs to be allocated from this pool.
31170
31171 @node General access types
31172 @subsubsection General access types
31173
31174 @noindent
31175 Objects designated by access values from a
31176 general access type (declared with @code{access all}) are never allocated
31177 from a 64-bit storage pool. Code that uses general access types will
31178 accept objects allocated in either 32-bit or 64-bit address spaces,
31179 but never allocate objects outside the 32-bit address space.
31180 Using general access types ensures maximum compatibility with both
31181 32-bit and 64-bit code.
31182
31183 @node STARLET and other predefined libraries
31184 @subsubsection STARLET and other predefined libraries
31185
31186 @noindent
31187 All code that comes as part of GNAT is 64-bit clean, but the
31188 restrictions given in @ref{Restrictions on use of 64 bit objects},
31189 still apply. Look at the package
31190 specs to see in which contexts objects allocated
31191 in 64-bit address space are acceptable.
31192
31193 @node Technical details
31194 @subsection Technical details
31195
31196 @noindent
31197 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31198 Ada standard with respect to the type of @code{System.Address}. Previous
31199 versions of GNAT Pro have defined this type as private and implemented it as a
31200 modular type.
31201
31202 In order to allow defining @code{System.Short_Address} as a proper subtype,
31203 and to match the implicit sign extension in parameter passing,
31204 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31205 visible (i.e., non-private) integer type.
31206 Standard operations on the type, such as the binary operators ``+'', ``-'',
31207 etc., that take @code{Address} operands and return an @code{Address} result,
31208 have been hidden by declaring these
31209 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31210 ambiguities that would otherwise result from overloading.
31211 (Note that, although @code{Address} is a visible integer type,
31212 good programming practice dictates against exploiting the type's
31213 integer properties such as literals, since this will compromise
31214 code portability.)
31215
31216 Defining @code{Address} as a visible integer type helps achieve
31217 maximum compatibility for existing Ada code,
31218 without sacrificing the capabilities of the 64-bit architecture.
31219 @end ifset
31220
31221 @c ************************************************
31222 @ifset unw
31223 @node Microsoft Windows Topics
31224 @appendix Microsoft Windows Topics
31225 @cindex Windows NT
31226 @cindex Windows 95
31227 @cindex Windows 98
31228
31229 @noindent
31230 This chapter describes topics that are specific to the Microsoft Windows
31231 platforms (NT, 2000, and XP Professional).
31232
31233 @menu
31234 * Using GNAT on Windows::
31235 * Using a network installation of GNAT::
31236 * CONSOLE and WINDOWS subsystems::
31237 * Temporary Files::
31238 * Mixed-Language Programming on Windows::
31239 * Windows Calling Conventions::
31240 * Introduction to Dynamic Link Libraries (DLLs)::
31241 * Using DLLs with GNAT::
31242 * Building DLLs with GNAT::
31243 * Building DLLs with GNAT Project files::
31244 * Building DLLs with gnatdll::
31245 * GNAT and Windows Resources::
31246 * Debugging a DLL::
31247 * Setting Stack Size from gnatlink::
31248 * Setting Heap Size from gnatlink::
31249 @end menu
31250
31251 @node Using GNAT on Windows
31252 @section Using GNAT on Windows
31253
31254 @noindent
31255 One of the strengths of the GNAT technology is that its tool set
31256 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31257 @code{gdb} debugger, etc.) is used in the same way regardless of the
31258 platform.
31259
31260 On Windows this tool set is complemented by a number of Microsoft-specific
31261 tools that have been provided to facilitate interoperability with Windows
31262 when this is required. With these tools:
31263
31264 @itemize @bullet
31265
31266 @item
31267 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31268 subsystems.
31269
31270 @item
31271 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31272 relocatable and non-relocatable DLLs are supported).
31273
31274 @item
31275 You can build Ada DLLs for use in other applications. These applications
31276 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31277 relocatable and non-relocatable Ada DLLs are supported.
31278
31279 @item
31280 You can include Windows resources in your Ada application.
31281
31282 @item
31283 You can use or create COM/DCOM objects.
31284 @end itemize
31285
31286 @noindent
31287 Immediately below are listed all known general GNAT-for-Windows restrictions.
31288 Other restrictions about specific features like Windows Resources and DLLs
31289 are listed in separate sections below.
31290
31291 @itemize @bullet
31292
31293 @item
31294 It is not possible to use @code{GetLastError} and @code{SetLastError}
31295 when tasking, protected records, or exceptions are used. In these
31296 cases, in order to implement Ada semantics, the GNAT run-time system
31297 calls certain Win32 routines that set the last error variable to 0 upon
31298 success. It should be possible to use @code{GetLastError} and
31299 @code{SetLastError} when tasking, protected record, and exception
31300 features are not used, but it is not guaranteed to work.
31301
31302 @item
31303 It is not possible to link against Microsoft libraries except for
31304 import libraries. The library must be built to be compatible with
31305 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31306 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31307 not be compatible with the GNAT runtime. Even if the library is
31308 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31309
31310 @item
31311 When the compilation environment is located on FAT32 drives, users may
31312 experience recompilations of the source files that have not changed if
31313 Daylight Saving Time (DST) state has changed since the last time files
31314 were compiled. NTFS drives do not have this problem.
31315
31316 @item
31317 No components of the GNAT toolset use any entries in the Windows
31318 registry. The only entries that can be created are file associations and
31319 PATH settings, provided the user has chosen to create them at installation
31320 time, as well as some minimal book-keeping information needed to correctly
31321 uninstall or integrate different GNAT products.
31322 @end itemize
31323
31324 @node Using a network installation of GNAT
31325 @section Using a network installation of GNAT
31326
31327 @noindent
31328 Make sure the system on which GNAT is installed is accessible from the
31329 current machine, i.e., the install location is shared over the network.
31330 Shared resources are accessed on Windows by means of UNC paths, which
31331 have the format @code{\\server\sharename\path}
31332
31333 In order to use such a network installation, simply add the UNC path of the
31334 @file{bin} directory of your GNAT installation in front of your PATH. For
31335 example, if GNAT is installed in @file{\GNAT} directory of a share location
31336 called @file{c-drive} on a machine @file{LOKI}, the following command will
31337 make it available:
31338
31339 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31340
31341 Be aware that every compilation using the network installation results in the
31342 transfer of large amounts of data across the network and will likely cause
31343 serious performance penalty.
31344
31345 @node CONSOLE and WINDOWS subsystems
31346 @section CONSOLE and WINDOWS subsystems
31347 @cindex CONSOLE Subsystem
31348 @cindex WINDOWS Subsystem
31349 @cindex -mwindows
31350
31351 @noindent
31352 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31353 (which is the default subsystem) will always create a console when
31354 launching the application. This is not something desirable when the
31355 application has a Windows GUI. To get rid of this console the
31356 application must be using the @code{WINDOWS} subsystem. To do so
31357 the @option{-mwindows} linker option must be specified.
31358
31359 @smallexample
31360 $ gnatmake winprog -largs -mwindows
31361 @end smallexample
31362
31363 @node Temporary Files
31364 @section Temporary Files
31365 @cindex Temporary files
31366
31367 @noindent
31368 It is possible to control where temporary files gets created by setting
31369 the @env{TMP} environment variable. The file will be created:
31370
31371 @itemize
31372 @item Under the directory pointed to by the @env{TMP} environment variable if
31373 this directory exists.
31374
31375 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31376 set (or not pointing to a directory) and if this directory exists.
31377
31378 @item Under the current working directory otherwise.
31379 @end itemize
31380
31381 @noindent
31382 This allows you to determine exactly where the temporary
31383 file will be created. This is particularly useful in networked
31384 environments where you may not have write access to some
31385 directories.
31386
31387 @node Mixed-Language Programming on Windows
31388 @section Mixed-Language Programming on Windows
31389
31390 @noindent
31391 Developing pure Ada applications on Windows is no different than on
31392 other GNAT-supported platforms. However, when developing or porting an
31393 application that contains a mix of Ada and C/C++, the choice of your
31394 Windows C/C++ development environment conditions your overall
31395 interoperability strategy.
31396
31397 If you use @command{gcc} to compile the non-Ada part of your application,
31398 there are no Windows-specific restrictions that affect the overall
31399 interoperability with your Ada code. If you plan to use
31400 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31401 the following limitations:
31402
31403 @itemize @bullet
31404 @item
31405 You cannot link your Ada code with an object or library generated with
31406 Microsoft tools if these use the @code{.tls} section (Thread Local
31407 Storage section) since the GNAT linker does not yet support this section.
31408
31409 @item
31410 You cannot link your Ada code with an object or library generated with
31411 Microsoft tools if these use I/O routines other than those provided in
31412 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31413 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31414 libraries can cause a conflict with @code{msvcrt.dll} services. For
31415 instance Visual C++ I/O stream routines conflict with those in
31416 @code{msvcrt.dll}.
31417 @end itemize
31418
31419 @noindent
31420 If you do want to use the Microsoft tools for your non-Ada code and hit one
31421 of the above limitations, you have two choices:
31422
31423 @enumerate
31424 @item
31425 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31426 application. In this case, use the Microsoft or whatever environment to
31427 build the DLL and use GNAT to build your executable
31428 (@pxref{Using DLLs with GNAT}).
31429
31430 @item
31431 Or you can encapsulate your Ada code in a DLL to be linked with the
31432 other part of your application. In this case, use GNAT to build the DLL
31433 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31434 environment to build your executable.
31435 @end enumerate
31436
31437 @node Windows Calling Conventions
31438 @section Windows Calling Conventions
31439 @findex Stdcall
31440 @findex APIENTRY
31441
31442 @menu
31443 * C Calling Convention::
31444 * Stdcall Calling Convention::
31445 * Win32 Calling Convention::
31446 * DLL Calling Convention::
31447 @end menu
31448
31449 @noindent
31450 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31451 (callee), there are several ways to push @code{G}'s parameters on the
31452 stack and there are several possible scenarios to clean up the stack
31453 upon @code{G}'s return. A calling convention is an agreed upon software
31454 protocol whereby the responsibilities between the caller (@code{F}) and
31455 the callee (@code{G}) are clearly defined. Several calling conventions
31456 are available for Windows:
31457
31458 @itemize @bullet
31459 @item
31460 @code{C} (Microsoft defined)
31461
31462 @item
31463 @code{Stdcall} (Microsoft defined)
31464
31465 @item
31466 @code{Win32} (GNAT specific)
31467
31468 @item
31469 @code{DLL} (GNAT specific)
31470 @end itemize
31471
31472 @node C Calling Convention
31473 @subsection @code{C} Calling Convention
31474
31475 @noindent
31476 This is the default calling convention used when interfacing to C/C++
31477 routines compiled with either @command{gcc} or Microsoft Visual C++.
31478
31479 In the @code{C} calling convention subprogram parameters are pushed on the
31480 stack by the caller from right to left. The caller itself is in charge of
31481 cleaning up the stack after the call. In addition, the name of a routine
31482 with @code{C} calling convention is mangled by adding a leading underscore.
31483
31484 The name to use on the Ada side when importing (or exporting) a routine
31485 with @code{C} calling convention is the name of the routine. For
31486 instance the C function:
31487
31488 @smallexample
31489 int get_val (long);
31490 @end smallexample
31491
31492 @noindent
31493 should be imported from Ada as follows:
31494
31495 @smallexample @c ada
31496 @group
31497 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31498 pragma Import (C, Get_Val, External_Name => "get_val");
31499 @end group
31500 @end smallexample
31501
31502 @noindent
31503 Note that in this particular case the @code{External_Name} parameter could
31504 have been omitted since, when missing, this parameter is taken to be the
31505 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31506 is missing, as in the above example, this parameter is set to be the
31507 @code{External_Name} with a leading underscore.
31508
31509 When importing a variable defined in C, you should always use the @code{C}
31510 calling convention unless the object containing the variable is part of a
31511 DLL (in which case you should use the @code{Stdcall} calling
31512 convention, @pxref{Stdcall Calling Convention}).
31513
31514 @node Stdcall Calling Convention
31515 @subsection @code{Stdcall} Calling Convention
31516
31517 @noindent
31518 This convention, which was the calling convention used for Pascal
31519 programs, is used by Microsoft for all the routines in the Win32 API for
31520 efficiency reasons. It must be used to import any routine for which this
31521 convention was specified.
31522
31523 In the @code{Stdcall} calling convention subprogram parameters are pushed
31524 on the stack by the caller from right to left. The callee (and not the
31525 caller) is in charge of cleaning the stack on routine exit. In addition,
31526 the name of a routine with @code{Stdcall} calling convention is mangled by
31527 adding a leading underscore (as for the @code{C} calling convention) and a
31528 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31529 bytes) of the parameters passed to the routine.
31530
31531 The name to use on the Ada side when importing a C routine with a
31532 @code{Stdcall} calling convention is the name of the C routine. The leading
31533 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31534 the compiler. For instance the Win32 function:
31535
31536 @smallexample
31537 @b{APIENTRY} int get_val (long);
31538 @end smallexample
31539
31540 @noindent
31541 should be imported from Ada as follows:
31542
31543 @smallexample @c ada
31544 @group
31545 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31546 pragma Import (Stdcall, Get_Val);
31547 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31548 @end group
31549 @end smallexample
31550
31551 @noindent
31552 As for the @code{C} calling convention, when the @code{External_Name}
31553 parameter is missing, it is taken to be the name of the Ada entity in lower
31554 case. If instead of writing the above import pragma you write:
31555
31556 @smallexample @c ada
31557 @group
31558 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31559 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31560 @end group
31561 @end smallexample
31562
31563 @noindent
31564 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31565 of specifying the @code{External_Name} parameter you specify the
31566 @code{Link_Name} as in the following example:
31567
31568 @smallexample @c ada
31569 @group
31570 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31571 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31572 @end group
31573 @end smallexample
31574
31575 @noindent
31576 then the imported routine is @code{retrieve_val}, that is, there is no
31577 decoration at all. No leading underscore and no Stdcall suffix
31578 @code{@@}@code{@var{nn}}.
31579
31580 @noindent
31581 This is especially important as in some special cases a DLL's entry
31582 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31583 name generated for a call has it.
31584
31585 @noindent
31586 It is also possible to import variables defined in a DLL by using an
31587 import pragma for a variable. As an example, if a DLL contains a
31588 variable defined as:
31589
31590 @smallexample
31591 int my_var;
31592 @end smallexample
31593
31594 @noindent
31595 then, to access this variable from Ada you should write:
31596
31597 @smallexample @c ada
31598 @group
31599 My_Var : Interfaces.C.int;
31600 pragma Import (Stdcall, My_Var);
31601 @end group
31602 @end smallexample
31603
31604 @noindent
31605 Note that to ease building cross-platform bindings this convention
31606 will be handled as a @code{C} calling convention on non-Windows platforms.
31607
31608 @node Win32 Calling Convention
31609 @subsection @code{Win32} Calling Convention
31610
31611 @noindent
31612 This convention, which is GNAT-specific is fully equivalent to the
31613 @code{Stdcall} calling convention described above.
31614
31615 @node DLL Calling Convention
31616 @subsection @code{DLL} Calling Convention
31617
31618 @noindent
31619 This convention, which is GNAT-specific is fully equivalent to the
31620 @code{Stdcall} calling convention described above.
31621
31622 @node Introduction to Dynamic Link Libraries (DLLs)
31623 @section Introduction to Dynamic Link Libraries (DLLs)
31624 @findex DLL
31625
31626 @noindent
31627 A Dynamically Linked Library (DLL) is a library that can be shared by
31628 several applications running under Windows. A DLL can contain any number of
31629 routines and variables.
31630
31631 One advantage of DLLs is that you can change and enhance them without
31632 forcing all the applications that depend on them to be relinked or
31633 recompiled. However, you should be aware than all calls to DLL routines are
31634 slower since, as you will understand below, such calls are indirect.
31635
31636 To illustrate the remainder of this section, suppose that an application
31637 wants to use the services of a DLL @file{API.dll}. To use the services
31638 provided by @file{API.dll} you must statically link against the DLL or
31639 an import library which contains a jump table with an entry for each
31640 routine and variable exported by the DLL. In the Microsoft world this
31641 import library is called @file{API.lib}. When using GNAT this import
31642 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31643 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31644
31645 After you have linked your application with the DLL or the import library
31646 and you run your application, here is what happens:
31647
31648 @enumerate
31649 @item
31650 Your application is loaded into memory.
31651
31652 @item
31653 The DLL @file{API.dll} is mapped into the address space of your
31654 application. This means that:
31655
31656 @itemize @bullet
31657 @item
31658 The DLL will use the stack of the calling thread.
31659
31660 @item
31661 The DLL will use the virtual address space of the calling process.
31662
31663 @item
31664 The DLL will allocate memory from the virtual address space of the calling
31665 process.
31666
31667 @item
31668 Handles (pointers) can be safely exchanged between routines in the DLL
31669 routines and routines in the application using the DLL.
31670 @end itemize
31671
31672 @item
31673 The entries in the jump table (from the import library @file{libAPI.dll.a}
31674 or @file{API.lib} or automatically created when linking against a DLL)
31675 which is part of your application are initialized with the addresses
31676 of the routines and variables in @file{API.dll}.
31677
31678 @item
31679 If present in @file{API.dll}, routines @code{DllMain} or
31680 @code{DllMainCRTStartup} are invoked. These routines typically contain
31681 the initialization code needed for the well-being of the routines and
31682 variables exported by the DLL.
31683 @end enumerate
31684
31685 @noindent
31686 There is an additional point which is worth mentioning. In the Windows
31687 world there are two kind of DLLs: relocatable and non-relocatable
31688 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31689 in the target application address space. If the addresses of two
31690 non-relocatable DLLs overlap and these happen to be used by the same
31691 application, a conflict will occur and the application will run
31692 incorrectly. Hence, when possible, it is always preferable to use and
31693 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31694 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31695 User's Guide) removes the debugging symbols from the DLL but the DLL can
31696 still be relocated.
31697
31698 As a side note, an interesting difference between Microsoft DLLs and
31699 Unix shared libraries, is the fact that on most Unix systems all public
31700 routines are exported by default in a Unix shared library, while under
31701 Windows it is possible (but not required) to list exported routines in
31702 a definition file (@pxref{The Definition File}).
31703
31704 @node Using DLLs with GNAT
31705 @section Using DLLs with GNAT
31706
31707 @menu
31708 * Creating an Ada Spec for the DLL Services::
31709 * Creating an Import Library::
31710 @end menu
31711
31712 @noindent
31713 To use the services of a DLL, say @file{API.dll}, in your Ada application
31714 you must have:
31715
31716 @enumerate
31717 @item
31718 The Ada spec for the routines and/or variables you want to access in
31719 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31720 header files provided with the DLL.
31721
31722 @item
31723 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31724 mentioned an import library is a statically linked library containing the
31725 import table which will be filled at load time to point to the actual
31726 @file{API.dll} routines. Sometimes you don't have an import library for the
31727 DLL you want to use. The following sections will explain how to build
31728 one. Note that this is optional.
31729
31730 @item
31731 The actual DLL, @file{API.dll}.
31732 @end enumerate
31733
31734 @noindent
31735 Once you have all the above, to compile an Ada application that uses the
31736 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31737 you simply issue the command
31738
31739 @smallexample
31740 $ gnatmake my_ada_app -largs -lAPI
31741 @end smallexample
31742
31743 @noindent
31744 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31745 tells the GNAT linker to look first for a library named @file{API.lib}
31746 (Microsoft-style name) and if not found for a libraries named
31747 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31748 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31749 contains the following pragma
31750
31751 @smallexample @c ada
31752 pragma Linker_Options ("-lAPI");
31753 @end smallexample
31754
31755 @noindent
31756 you do not have to add @option{-largs -lAPI} at the end of the
31757 @command{gnatmake} command.
31758
31759 If any one of the items above is missing you will have to create it
31760 yourself. The following sections explain how to do so using as an
31761 example a fictitious DLL called @file{API.dll}.
31762
31763 @node Creating an Ada Spec for the DLL Services
31764 @subsection Creating an Ada Spec for the DLL Services
31765
31766 @noindent
31767 A DLL typically comes with a C/C++ header file which provides the
31768 definitions of the routines and variables exported by the DLL. The Ada
31769 equivalent of this header file is a package spec that contains definitions
31770 for the imported entities. If the DLL you intend to use does not come with
31771 an Ada spec you have to generate one such spec yourself. For example if
31772 the header file of @file{API.dll} is a file @file{api.h} containing the
31773 following two definitions:
31774
31775 @smallexample
31776 @group
31777 @cartouche
31778 int some_var;
31779 int get (char *);
31780 @end cartouche
31781 @end group
31782 @end smallexample
31783
31784 @noindent
31785 then the equivalent Ada spec could be:
31786
31787 @smallexample @c ada
31788 @group
31789 @cartouche
31790 with Interfaces.C.Strings;
31791 package API is
31792 use Interfaces;
31793
31794 Some_Var : C.int;
31795 function Get (Str : C.Strings.Chars_Ptr) return C.int;
31796
31797 private
31798 pragma Import (C, Get);
31799 pragma Import (DLL, Some_Var);
31800 end API;
31801 @end cartouche
31802 @end group
31803 @end smallexample
31804
31805 @noindent
31806 Note that a variable is
31807 @strong{always imported with a Stdcall convention}. A function
31808 can have @code{C} or @code{Stdcall} convention.
31809 (@pxref{Windows Calling Conventions}).
31810
31811 @node Creating an Import Library
31812 @subsection Creating an Import Library
31813 @cindex Import library
31814
31815 @menu
31816 * The Definition File::
31817 * GNAT-Style Import Library::
31818 * Microsoft-Style Import Library::
31819 @end menu
31820
31821 @noindent
31822 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31823 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31824 with @file{API.dll} you can skip this section. You can also skip this
31825 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31826 as in this case it is possible to link directly against the
31827 DLL. Otherwise read on.
31828
31829 @node The Definition File
31830 @subsubsection The Definition File
31831 @cindex Definition file
31832 @findex .def
31833
31834 @noindent
31835 As previously mentioned, and unlike Unix systems, the list of symbols
31836 that are exported from a DLL must be provided explicitly in Windows.
31837 The main goal of a definition file is precisely that: list the symbols
31838 exported by a DLL. A definition file (usually a file with a @code{.def}
31839 suffix) has the following structure:
31840
31841 @smallexample
31842 @group
31843 @cartouche
31844 @r{[}LIBRARY @var{name}@r{]}
31845 @r{[}DESCRIPTION @var{string}@r{]}
31846 EXPORTS
31847 @var{symbol1}
31848 @var{symbol2}
31849 @dots{}
31850 @end cartouche
31851 @end group
31852 @end smallexample
31853
31854 @table @code
31855 @item LIBRARY @var{name}
31856 This section, which is optional, gives the name of the DLL.
31857
31858 @item DESCRIPTION @var{string}
31859 This section, which is optional, gives a description string that will be
31860 embedded in the import library.
31861
31862 @item EXPORTS
31863 This section gives the list of exported symbols (procedures, functions or
31864 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31865 section of @file{API.def} looks like:
31866
31867 @smallexample
31868 @group
31869 @cartouche
31870 EXPORTS
31871 some_var
31872 get
31873 @end cartouche
31874 @end group
31875 @end smallexample
31876 @end table
31877
31878 @noindent
31879 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31880 (@pxref{Windows Calling Conventions}) for a Stdcall
31881 calling convention function in the exported symbols list.
31882
31883 @noindent
31884 There can actually be other sections in a definition file, but these
31885 sections are not relevant to the discussion at hand.
31886
31887 @node GNAT-Style Import Library
31888 @subsubsection GNAT-Style Import Library
31889
31890 @noindent
31891 To create a static import library from @file{API.dll} with the GNAT tools
31892 you should proceed as follows:
31893
31894 @enumerate
31895 @item
31896 Create the definition file @file{API.def} (@pxref{The Definition File}).
31897 For that use the @code{dll2def} tool as follows:
31898
31899 @smallexample
31900 $ dll2def API.dll > API.def
31901 @end smallexample
31902
31903 @noindent
31904 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31905 to standard output the list of entry points in the DLL. Note that if
31906 some routines in the DLL have the @code{Stdcall} convention
31907 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31908 suffix then you'll have to edit @file{api.def} to add it, and specify
31909 @option{-k} to @command{gnatdll} when creating the import library.
31910
31911 @noindent
31912 Here are some hints to find the right @code{@@}@var{nn} suffix.
31913
31914 @enumerate
31915 @item
31916 If you have the Microsoft import library (.lib), it is possible to get
31917 the right symbols by using Microsoft @code{dumpbin} tool (see the
31918 corresponding Microsoft documentation for further details).
31919
31920 @smallexample
31921 $ dumpbin /exports api.lib
31922 @end smallexample
31923
31924 @item
31925 If you have a message about a missing symbol at link time the compiler
31926 tells you what symbol is expected. You just have to go back to the
31927 definition file and add the right suffix.
31928 @end enumerate
31929
31930 @item
31931 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31932 (@pxref{Using gnatdll}) as follows:
31933
31934 @smallexample
31935 $ gnatdll -e API.def -d API.dll
31936 @end smallexample
31937
31938 @noindent
31939 @code{gnatdll} takes as input a definition file @file{API.def} and the
31940 name of the DLL containing the services listed in the definition file
31941 @file{API.dll}. The name of the static import library generated is
31942 computed from the name of the definition file as follows: if the
31943 definition file name is @var{xyz}@code{.def}, the import library name will
31944 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31945 @option{-e} could have been removed because the name of the definition
31946 file (before the ``@code{.def}'' suffix) is the same as the name of the
31947 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31948 @end enumerate
31949
31950 @node Microsoft-Style Import Library
31951 @subsubsection Microsoft-Style Import Library
31952
31953 @noindent
31954 With GNAT you can either use a GNAT-style or Microsoft-style import
31955 library. A Microsoft import library is needed only if you plan to make an
31956 Ada DLL available to applications developed with Microsoft
31957 tools (@pxref{Mixed-Language Programming on Windows}).
31958
31959 To create a Microsoft-style import library for @file{API.dll} you
31960 should proceed as follows:
31961
31962 @enumerate
31963 @item
31964 Create the definition file @file{API.def} from the DLL. For this use either
31965 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31966 tool (see the corresponding Microsoft documentation for further details).
31967
31968 @item
31969 Build the actual import library using Microsoft's @code{lib} utility:
31970
31971 @smallexample
31972 $ lib -machine:IX86 -def:API.def -out:API.lib
31973 @end smallexample
31974
31975 @noindent
31976 If you use the above command the definition file @file{API.def} must
31977 contain a line giving the name of the DLL:
31978
31979 @smallexample
31980 LIBRARY "API"
31981 @end smallexample
31982
31983 @noindent
31984 See the Microsoft documentation for further details about the usage of
31985 @code{lib}.
31986 @end enumerate
31987
31988 @node Building DLLs with GNAT
31989 @section Building DLLs with GNAT
31990 @cindex DLLs, building
31991
31992 @noindent
31993 This section explain how to build DLLs using the GNAT built-in DLL
31994 support. With the following procedure it is straight forward to build
31995 and use DLLs with GNAT.
31996
31997 @enumerate
31998
31999 @item building object files
32000
32001 The first step is to build all objects files that are to be included
32002 into the DLL. This is done by using the standard @command{gnatmake} tool.
32003
32004 @item building the DLL
32005
32006 To build the DLL you must use @command{gcc}'s @option{-shared}
32007 option. It is quite simple to use this method:
32008
32009 @smallexample
32010 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32011 @end smallexample
32012
32013 It is important to note that in this case all symbols found in the
32014 object files are automatically exported. It is possible to restrict
32015 the set of symbols to export by passing to @command{gcc} a definition
32016 file, @pxref{The Definition File}. For example:
32017
32018 @smallexample
32019 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32020 @end smallexample
32021
32022 If you use a definition file you must export the elaboration procedures
32023 for every package that required one. Elaboration procedures are named
32024 using the package name followed by "_E".
32025
32026 @item preparing DLL to be used
32027
32028 For the DLL to be used by client programs the bodies must be hidden
32029 from it and the .ali set with read-only attribute. This is very important
32030 otherwise GNAT will recompile all packages and will not actually use
32031 the code in the DLL. For example:
32032
32033 @smallexample
32034 $ mkdir apilib
32035 $ copy *.ads *.ali api.dll apilib
32036 $ attrib +R apilib\*.ali
32037 @end smallexample
32038
32039 @end enumerate
32040
32041 At this point it is possible to use the DLL by directly linking
32042 against it. Note that you must use the GNAT shared runtime when using
32043 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32044 option.
32045
32046 @smallexample
32047 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32048 @end smallexample
32049
32050 @node Building DLLs with GNAT Project files
32051 @section Building DLLs with GNAT Project files
32052 @cindex DLLs, building
32053
32054 @noindent
32055 There is nothing specific to Windows in the build process.
32056 @pxref{Library Projects}.
32057
32058 @noindent
32059 Due to a system limitation, it is not possible under Windows to create threads
32060 when inside the @code{DllMain} routine which is used for auto-initialization
32061 of shared libraries, so it is not possible to have library level tasks in SALs.
32062
32063 @node Building DLLs with gnatdll
32064 @section Building DLLs with gnatdll
32065 @cindex DLLs, building
32066
32067 @menu
32068 * Limitations When Using Ada DLLs from Ada::
32069 * Exporting Ada Entities::
32070 * Ada DLLs and Elaboration::
32071 * Ada DLLs and Finalization::
32072 * Creating a Spec for Ada DLLs::
32073 * Creating the Definition File::
32074 * Using gnatdll::
32075 @end menu
32076
32077 @noindent
32078 Note that it is preferred to use the built-in GNAT DLL support
32079 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32080 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32081
32082 This section explains how to build DLLs containing Ada code using
32083 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32084 remainder of this section.
32085
32086 The steps required to build an Ada DLL that is to be used by Ada as well as
32087 non-Ada applications are as follows:
32088
32089 @enumerate
32090 @item
32091 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32092 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32093 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32094 skip this step if you plan to use the Ada DLL only from Ada applications.
32095
32096 @item
32097 Your Ada code must export an initialization routine which calls the routine
32098 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32099 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32100 routine exported by the Ada DLL must be invoked by the clients of the DLL
32101 to initialize the DLL.
32102
32103 @item
32104 When useful, the DLL should also export a finalization routine which calls
32105 routine @code{adafinal} generated by @command{gnatbind} to perform the
32106 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32107 The finalization routine exported by the Ada DLL must be invoked by the
32108 clients of the DLL when the DLL services are no further needed.
32109
32110 @item
32111 You must provide a spec for the services exported by the Ada DLL in each
32112 of the programming languages to which you plan to make the DLL available.
32113
32114 @item
32115 You must provide a definition file listing the exported entities
32116 (@pxref{The Definition File}).
32117
32118 @item
32119 Finally you must use @code{gnatdll} to produce the DLL and the import
32120 library (@pxref{Using gnatdll}).
32121 @end enumerate
32122
32123 @noindent
32124 Note that a relocatable DLL stripped using the @code{strip}
32125 binutils tool will not be relocatable anymore. To build a DLL without
32126 debug information pass @code{-largs -s} to @code{gnatdll}. This
32127 restriction does not apply to a DLL built using a Library Project.
32128 @pxref{Library Projects}.
32129
32130 @node Limitations When Using Ada DLLs from Ada
32131 @subsection Limitations When Using Ada DLLs from Ada
32132
32133 @noindent
32134 When using Ada DLLs from Ada applications there is a limitation users
32135 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32136 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32137 each Ada DLL includes the services of the GNAT run time that are necessary
32138 to the Ada code inside the DLL. As a result, when an Ada program uses an
32139 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32140 one in the main program.
32141
32142 It is therefore not possible to exchange GNAT run-time objects between the
32143 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32144 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32145 types, etc.
32146
32147 It is completely safe to exchange plain elementary, array or record types,
32148 Windows object handles, etc.
32149
32150 @node Exporting Ada Entities
32151 @subsection Exporting Ada Entities
32152 @cindex Export table
32153
32154 @noindent
32155 Building a DLL is a way to encapsulate a set of services usable from any
32156 application. As a result, the Ada entities exported by a DLL should be
32157 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32158 any Ada name mangling. As an example here is an Ada package
32159 @code{API}, spec and body, exporting two procedures, a function, and a
32160 variable:
32161
32162 @smallexample @c ada
32163 @group
32164 @cartouche
32165 with Interfaces.C; use Interfaces;
32166 package API is
32167 Count : C.int := 0;
32168 function Factorial (Val : C.int) return C.int;
32169
32170 procedure Initialize_API;
32171 procedure Finalize_API;
32172 -- Initialization & Finalization routines. More in the next section.
32173 private
32174 pragma Export (C, Initialize_API);
32175 pragma Export (C, Finalize_API);
32176 pragma Export (C, Count);
32177 pragma Export (C, Factorial);
32178 end API;
32179 @end cartouche
32180 @end group
32181 @end smallexample
32182
32183 @smallexample @c ada
32184 @group
32185 @cartouche
32186 package body API is
32187 function Factorial (Val : C.int) return C.int is
32188 Fact : C.int := 1;
32189 begin
32190 Count := Count + 1;
32191 for K in 1 .. Val loop
32192 Fact := Fact * K;
32193 end loop;
32194 return Fact;
32195 end Factorial;
32196
32197 procedure Initialize_API is
32198 procedure Adainit;
32199 pragma Import (C, Adainit);
32200 begin
32201 Adainit;
32202 end Initialize_API;
32203
32204 procedure Finalize_API is
32205 procedure Adafinal;
32206 pragma Import (C, Adafinal);
32207 begin
32208 Adafinal;
32209 end Finalize_API;
32210 end API;
32211 @end cartouche
32212 @end group
32213 @end smallexample
32214
32215 @noindent
32216 If the Ada DLL you are building will only be used by Ada applications
32217 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32218 convention. As an example, the previous package could be written as
32219 follows:
32220
32221 @smallexample @c ada
32222 @group
32223 @cartouche
32224 package API is
32225 Count : Integer := 0;
32226 function Factorial (Val : Integer) return Integer;
32227
32228 procedure Initialize_API;
32229 procedure Finalize_API;
32230 -- Initialization and Finalization routines.
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 : Integer) return Integer is
32241 Fact : Integer := 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 @dots{}
32251 -- The remainder of this package body is unchanged.
32252 end API;
32253 @end cartouche
32254 @end group
32255 @end smallexample
32256
32257 @noindent
32258 Note that if you do not export the Ada entities with a @code{C} or
32259 @code{Stdcall} convention you will have to provide the mangled Ada names
32260 in the definition file of the Ada DLL
32261 (@pxref{Creating the Definition File}).
32262
32263 @node Ada DLLs and Elaboration
32264 @subsection Ada DLLs and Elaboration
32265 @cindex DLLs and elaboration
32266
32267 @noindent
32268 The DLL that you are building contains your Ada code as well as all the
32269 routines in the Ada library that are needed by it. The first thing a
32270 user of your DLL must do is elaborate the Ada code
32271 (@pxref{Elaboration Order Handling in GNAT}).
32272
32273 To achieve this you must export an initialization routine
32274 (@code{Initialize_API} in the previous example), which must be invoked
32275 before using any of the DLL services. This elaboration routine must call
32276 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32277 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32278 @code{Initialize_Api} for an example. Note that the GNAT binder is
32279 automatically invoked during the DLL build process by the @code{gnatdll}
32280 tool (@pxref{Using gnatdll}).
32281
32282 When a DLL is loaded, Windows systematically invokes a routine called
32283 @code{DllMain}. It would therefore be possible to call @code{adainit}
32284 directly from @code{DllMain} without having to provide an explicit
32285 initialization routine. Unfortunately, it is not possible to call
32286 @code{adainit} from the @code{DllMain} if your program has library level
32287 tasks because access to the @code{DllMain} entry point is serialized by
32288 the system (that is, only a single thread can execute ``through'' it at a
32289 time), which means that the GNAT run time will deadlock waiting for the
32290 newly created task to complete its initialization.
32291
32292 @node Ada DLLs and Finalization
32293 @subsection Ada DLLs and Finalization
32294 @cindex DLLs and finalization
32295
32296 @noindent
32297 When the services of an Ada DLL are no longer needed, the client code should
32298 invoke the DLL finalization routine, if available. The DLL finalization
32299 routine is in charge of releasing all resources acquired by the DLL. In the
32300 case of the Ada code contained in the DLL, this is achieved by calling
32301 routine @code{adafinal} generated by the GNAT binder
32302 (@pxref{Binding with Non-Ada Main Programs}).
32303 See the body of @code{Finalize_Api} for an
32304 example. As already pointed out the GNAT binder is automatically invoked
32305 during the DLL build process by the @code{gnatdll} tool
32306 (@pxref{Using gnatdll}).
32307
32308 @node Creating a Spec for Ada DLLs
32309 @subsection Creating a Spec for Ada DLLs
32310
32311 @noindent
32312 To use the services exported by the Ada DLL from another programming
32313 language (e.g.@: C), you have to translate the specs of the exported Ada
32314 entities in that language. For instance in the case of @code{API.dll},
32315 the corresponding C header file could look like:
32316
32317 @smallexample
32318 @group
32319 @cartouche
32320 extern int *_imp__count;
32321 #define count (*_imp__count)
32322 int factorial (int);
32323 @end cartouche
32324 @end group
32325 @end smallexample
32326
32327 @noindent
32328 It is important to understand that when building an Ada DLL to be used by
32329 other Ada applications, you need two different specs for the packages
32330 contained in the DLL: one for building the DLL and the other for using
32331 the DLL. This is because the @code{DLL} calling convention is needed to
32332 use a variable defined in a DLL, but when building the DLL, the variable
32333 must have either the @code{Ada} or @code{C} calling convention. As an
32334 example consider a DLL comprising the following package @code{API}:
32335
32336 @smallexample @c ada
32337 @group
32338 @cartouche
32339 package API is
32340 Count : Integer := 0;
32341 @dots{}
32342 -- Remainder of the package omitted.
32343 end API;
32344 @end cartouche
32345 @end group
32346 @end smallexample
32347
32348 @noindent
32349 After producing a DLL containing package @code{API}, the spec that
32350 must be used to import @code{API.Count} from Ada code outside of the
32351 DLL is:
32352
32353 @smallexample @c ada
32354 @group
32355 @cartouche
32356 package API is
32357 Count : Integer;
32358 pragma Import (DLL, Count);
32359 end API;
32360 @end cartouche
32361 @end group
32362 @end smallexample
32363
32364 @node Creating the Definition File
32365 @subsection Creating the Definition File
32366
32367 @noindent
32368 The definition file is the last file needed to build the DLL. It lists
32369 the exported symbols. As an example, the definition file for a DLL
32370 containing only package @code{API} (where all the entities are exported
32371 with a @code{C} calling convention) is:
32372
32373 @smallexample
32374 @group
32375 @cartouche
32376 EXPORTS
32377 count
32378 factorial
32379 finalize_api
32380 initialize_api
32381 @end cartouche
32382 @end group
32383 @end smallexample
32384
32385 @noindent
32386 If the @code{C} calling convention is missing from package @code{API},
32387 then the definition file contains the mangled Ada names of the above
32388 entities, which in this case are:
32389
32390 @smallexample
32391 @group
32392 @cartouche
32393 EXPORTS
32394 api__count
32395 api__factorial
32396 api__finalize_api
32397 api__initialize_api
32398 @end cartouche
32399 @end group
32400 @end smallexample
32401
32402 @node Using gnatdll
32403 @subsection Using @code{gnatdll}
32404 @findex gnatdll
32405
32406 @menu
32407 * gnatdll Example::
32408 * gnatdll behind the Scenes::
32409 * Using dlltool::
32410 @end menu
32411
32412 @noindent
32413 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32414 and non-Ada sources that make up your DLL have been compiled.
32415 @code{gnatdll} is actually in charge of two distinct tasks: build the
32416 static import library for the DLL and the actual DLL. The form of the
32417 @code{gnatdll} command is
32418
32419 @smallexample
32420 @cartouche
32421 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32422 @end cartouche
32423 @end smallexample
32424
32425 @noindent
32426 where @var{list-of-files} is a list of ALI and object files. The object
32427 file list must be the exact list of objects corresponding to the non-Ada
32428 sources whose services are to be included in the DLL. The ALI file list
32429 must be the exact list of ALI files for the corresponding Ada sources
32430 whose services are to be included in the DLL. If @var{list-of-files} is
32431 missing, only the static import library is generated.
32432
32433 @noindent
32434 You may specify any of the following switches to @code{gnatdll}:
32435
32436 @table @code
32437 @item -a@ovar{address}
32438 @cindex @option{-a} (@code{gnatdll})
32439 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32440 specified the default address @var{0x11000000} will be used. By default,
32441 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32442 advise the reader to build relocatable DLL.
32443
32444 @item -b @var{address}
32445 @cindex @option{-b} (@code{gnatdll})
32446 Set the relocatable DLL base address. By default the address is
32447 @code{0x11000000}.
32448
32449 @item -bargs @var{opts}
32450 @cindex @option{-bargs} (@code{gnatdll})
32451 Binder options. Pass @var{opts} to the binder.
32452
32453 @item -d @var{dllfile}
32454 @cindex @option{-d} (@code{gnatdll})
32455 @var{dllfile} is the name of the DLL. This switch must be present for
32456 @code{gnatdll} to do anything. The name of the generated import library is
32457 obtained algorithmically from @var{dllfile} as shown in the following
32458 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32459 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32460 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32461 as shown in the following example:
32462 if @var{dllfile} is @code{xyz.dll}, the definition
32463 file used is @code{xyz.def}.
32464
32465 @item -e @var{deffile}
32466 @cindex @option{-e} (@code{gnatdll})
32467 @var{deffile} is the name of the definition file.
32468
32469 @item -g
32470 @cindex @option{-g} (@code{gnatdll})
32471 Generate debugging information. This information is stored in the object
32472 file and copied from there to the final DLL file by the linker,
32473 where it can be read by the debugger. You must use the
32474 @option{-g} switch if you plan on using the debugger or the symbolic
32475 stack traceback.
32476
32477 @item -h
32478 @cindex @option{-h} (@code{gnatdll})
32479 Help mode. Displays @code{gnatdll} switch usage information.
32480
32481 @item -Idir
32482 @cindex @option{-I} (@code{gnatdll})
32483 Direct @code{gnatdll} to search the @var{dir} directory for source and
32484 object files needed to build the DLL.
32485 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32486
32487 @item -k
32488 @cindex @option{-k} (@code{gnatdll})
32489 Removes the @code{@@}@var{nn} suffix from the import library's exported
32490 names, but keeps them for the link names. You must specify this
32491 option if you want to use a @code{Stdcall} function in a DLL for which
32492 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32493 of the Windows NT DLL for example. This option has no effect when
32494 @option{-n} option is specified.
32495
32496 @item -l @var{file}
32497 @cindex @option{-l} (@code{gnatdll})
32498 The list of ALI and object files used to build the DLL are listed in
32499 @var{file}, instead of being given in the command line. Each line in
32500 @var{file} contains the name of an ALI or object file.
32501
32502 @item -n
32503 @cindex @option{-n} (@code{gnatdll})
32504 No Import. Do not create the import library.
32505
32506 @item -q
32507 @cindex @option{-q} (@code{gnatdll})
32508 Quiet mode. Do not display unnecessary messages.
32509
32510 @item -v
32511 @cindex @option{-v} (@code{gnatdll})
32512 Verbose mode. Display extra information.
32513
32514 @item -largs @var{opts}
32515 @cindex @option{-largs} (@code{gnatdll})
32516 Linker options. Pass @var{opts} to the linker.
32517 @end table
32518
32519 @node gnatdll Example
32520 @subsubsection @code{gnatdll} Example
32521
32522 @noindent
32523 As an example the command to build a relocatable DLL from @file{api.adb}
32524 once @file{api.adb} has been compiled and @file{api.def} created is
32525
32526 @smallexample
32527 $ gnatdll -d api.dll api.ali
32528 @end smallexample
32529
32530 @noindent
32531 The above command creates two files: @file{libapi.dll.a} (the import
32532 library) and @file{api.dll} (the actual DLL). If you want to create
32533 only the DLL, just type:
32534
32535 @smallexample
32536 $ gnatdll -d api.dll -n api.ali
32537 @end smallexample
32538
32539 @noindent
32540 Alternatively if you want to create just the import library, type:
32541
32542 @smallexample
32543 $ gnatdll -d api.dll
32544 @end smallexample
32545
32546 @node gnatdll behind the Scenes
32547 @subsubsection @code{gnatdll} behind the Scenes
32548
32549 @noindent
32550 This section details the steps involved in creating a DLL. @code{gnatdll}
32551 does these steps for you. Unless you are interested in understanding what
32552 goes on behind the scenes, you should skip this section.
32553
32554 We use the previous example of a DLL containing the Ada package @code{API},
32555 to illustrate the steps necessary to build a DLL. The starting point is a
32556 set of objects that will make up the DLL and the corresponding ALI
32557 files. In the case of this example this means that @file{api.o} and
32558 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32559 the following:
32560
32561 @enumerate
32562 @item
32563 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32564 the information necessary to generate relocation information for the
32565 DLL.
32566
32567 @smallexample
32568 @group
32569 $ gnatbind -n api
32570 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32571 @end group
32572 @end smallexample
32573
32574 @noindent
32575 In addition to the base file, the @command{gnatlink} command generates an
32576 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32577 asks @command{gnatlink} to generate the routines @code{DllMain} and
32578 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32579 is loaded into memory.
32580
32581 @item
32582 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32583 export table (@file{api.exp}). The export table contains the relocation
32584 information in a form which can be used during the final link to ensure
32585 that the Windows loader is able to place the DLL anywhere in memory.
32586
32587 @smallexample
32588 @group
32589 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32590 --output-exp api.exp
32591 @end group
32592 @end smallexample
32593
32594 @item
32595 @code{gnatdll} builds the base file using the new export table. Note that
32596 @command{gnatbind} must be called once again since the binder generated file
32597 has been deleted during the previous call to @command{gnatlink}.
32598
32599 @smallexample
32600 @group
32601 $ gnatbind -n api
32602 $ gnatlink api -o api.jnk api.exp -mdll
32603 -Wl,--base-file,api.base
32604 @end group
32605 @end smallexample
32606
32607 @item
32608 @code{gnatdll} builds the new export table using the new base file and
32609 generates the DLL import library @file{libAPI.dll.a}.
32610
32611 @smallexample
32612 @group
32613 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32614 --output-exp api.exp --output-lib libAPI.a
32615 @end group
32616 @end smallexample
32617
32618 @item
32619 Finally @code{gnatdll} builds the relocatable DLL using the final export
32620 table.
32621
32622 @smallexample
32623 @group
32624 $ gnatbind -n api
32625 $ gnatlink api api.exp -o api.dll -mdll
32626 @end group
32627 @end smallexample
32628 @end enumerate
32629
32630 @node Using dlltool
32631 @subsubsection Using @code{dlltool}
32632
32633 @noindent
32634 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32635 DLLs and static import libraries. This section summarizes the most
32636 common @code{dlltool} switches. The form of the @code{dlltool} command
32637 is
32638
32639 @smallexample
32640 $ dlltool @ovar{switches}
32641 @end smallexample
32642
32643 @noindent
32644 @code{dlltool} switches include:
32645
32646 @table @option
32647 @item --base-file @var{basefile}
32648 @cindex @option{--base-file} (@command{dlltool})
32649 Read the base file @var{basefile} generated by the linker. This switch
32650 is used to create a relocatable DLL.
32651
32652 @item --def @var{deffile}
32653 @cindex @option{--def} (@command{dlltool})
32654 Read the definition file.
32655
32656 @item --dllname @var{name}
32657 @cindex @option{--dllname} (@command{dlltool})
32658 Gives the name of the DLL. This switch is used to embed the name of the
32659 DLL in the static import library generated by @code{dlltool} with switch
32660 @option{--output-lib}.
32661
32662 @item -k
32663 @cindex @option{-k} (@command{dlltool})
32664 Kill @code{@@}@var{nn} from exported names
32665 (@pxref{Windows Calling Conventions}
32666 for a discussion about @code{Stdcall}-style symbols.
32667
32668 @item --help
32669 @cindex @option{--help} (@command{dlltool})
32670 Prints the @code{dlltool} switches with a concise description.
32671
32672 @item --output-exp @var{exportfile}
32673 @cindex @option{--output-exp} (@command{dlltool})
32674 Generate an export file @var{exportfile}. The export file contains the
32675 export table (list of symbols in the DLL) and is used to create the DLL.
32676
32677 @item --output-lib @var{libfile}
32678 @cindex @option{--output-lib} (@command{dlltool})
32679 Generate a static import library @var{libfile}.
32680
32681 @item -v
32682 @cindex @option{-v} (@command{dlltool})
32683 Verbose mode.
32684
32685 @item --as @var{assembler-name}
32686 @cindex @option{--as} (@command{dlltool})
32687 Use @var{assembler-name} as the assembler. The default is @code{as}.
32688 @end table
32689
32690 @node GNAT and Windows Resources
32691 @section GNAT and Windows Resources
32692 @cindex Resources, windows
32693
32694 @menu
32695 * Building Resources::
32696 * Compiling Resources::
32697 * Using Resources::
32698 @end menu
32699
32700 @noindent
32701 Resources are an easy way to add Windows specific objects to your
32702 application. The objects that can be added as resources include:
32703
32704 @itemize @bullet
32705 @item
32706 menus
32707
32708 @item
32709 accelerators
32710
32711 @item
32712 dialog boxes
32713
32714 @item
32715 string tables
32716
32717 @item
32718 bitmaps
32719
32720 @item
32721 cursors
32722
32723 @item
32724 icons
32725
32726 @item
32727 fonts
32728 @end itemize
32729
32730 @noindent
32731 This section explains how to build, compile and use resources.
32732
32733 @node Building Resources
32734 @subsection Building Resources
32735 @cindex Resources, building
32736
32737 @noindent
32738 A resource file is an ASCII file. By convention resource files have an
32739 @file{.rc} extension.
32740 The easiest way to build a resource file is to use Microsoft tools
32741 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32742 @code{dlgedit.exe} to build dialogs.
32743 It is always possible to build an @file{.rc} file yourself by writing a
32744 resource script.
32745
32746 It is not our objective to explain how to write a resource file. A
32747 complete description of the resource script language can be found in the
32748 Microsoft documentation.
32749
32750 @node Compiling Resources
32751 @subsection Compiling Resources
32752 @findex rc
32753 @findex windres
32754 @cindex Resources, compiling
32755
32756 @noindent
32757 This section describes how to build a GNAT-compatible (COFF) object file
32758 containing the resources. This is done using the Resource Compiler
32759 @code{windres} as follows:
32760
32761 @smallexample
32762 $ windres -i myres.rc -o myres.o
32763 @end smallexample
32764
32765 @noindent
32766 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32767 file. You can specify an alternate preprocessor (usually named
32768 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32769 parameter. A list of all possible options may be obtained by entering
32770 the command @code{windres} @option{--help}.
32771
32772 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32773 to produce a @file{.res} file (binary resource file). See the
32774 corresponding Microsoft documentation for further details. In this case
32775 you need to use @code{windres} to translate the @file{.res} file to a
32776 GNAT-compatible object file as follows:
32777
32778 @smallexample
32779 $ windres -i myres.res -o myres.o
32780 @end smallexample
32781
32782 @node Using Resources
32783 @subsection Using Resources
32784 @cindex Resources, using
32785
32786 @noindent
32787 To include the resource file in your program just add the
32788 GNAT-compatible object file for the resource(s) to the linker
32789 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32790 option:
32791
32792 @smallexample
32793 $ gnatmake myprog -largs myres.o
32794 @end smallexample
32795
32796 @node Debugging a DLL
32797 @section Debugging a DLL
32798 @cindex DLL debugging
32799
32800 @menu
32801 * Program and DLL Both Built with GCC/GNAT::
32802 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32803 @end menu
32804
32805 @noindent
32806 Debugging a DLL is similar to debugging a standard program. But
32807 we have to deal with two different executable parts: the DLL and the
32808 program that uses it. We have the following four possibilities:
32809
32810 @enumerate 1
32811 @item
32812 The program and the DLL are built with @code{GCC/GNAT}.
32813 @item
32814 The program is built with foreign tools and the DLL is built with
32815 @code{GCC/GNAT}.
32816 @item
32817 The program is built with @code{GCC/GNAT} and the DLL is built with
32818 foreign tools.
32819 @item
32820 @end enumerate
32821
32822 @noindent
32823 In this section we address only cases one and two above.
32824 There is no point in trying to debug
32825 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32826 information in it. To do so you must use a debugger compatible with the
32827 tools suite used to build the DLL.
32828
32829 @node Program and DLL Both Built with GCC/GNAT
32830 @subsection Program and DLL Both Built with GCC/GNAT
32831
32832 @noindent
32833 This is the simplest case. Both the DLL and the program have @code{GDB}
32834 compatible debugging information. It is then possible to break anywhere in
32835 the process. Let's suppose here that the main procedure is named
32836 @code{ada_main} and that in the DLL there is an entry point named
32837 @code{ada_dll}.
32838
32839 @noindent
32840 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32841 program must have been built with the debugging information (see GNAT -g
32842 switch). Here are the step-by-step instructions for debugging it:
32843
32844 @enumerate 1
32845 @item Launch @code{GDB} on the main program.
32846
32847 @smallexample
32848 $ gdb -nw ada_main
32849 @end smallexample
32850
32851 @item Start the program and stop at the beginning of the main procedure
32852
32853 @smallexample
32854 (gdb) start
32855 @end smallexample
32856
32857 @noindent
32858 This step is required to be able to set a breakpoint inside the DLL. As long
32859 as the program is not run, the DLL is not loaded. This has the
32860 consequence that the DLL debugging information is also not loaded, so it is not
32861 possible to set a breakpoint in the DLL.
32862
32863 @item Set a breakpoint inside the DLL
32864
32865 @smallexample
32866 (gdb) break ada_dll
32867 (gdb) cont
32868 @end smallexample
32869
32870 @end enumerate
32871
32872 @noindent
32873 At this stage a breakpoint is set inside the DLL. From there on
32874 you can use the standard approach to debug the whole program
32875 (@pxref{Running and Debugging Ada Programs}).
32876
32877 @ignore
32878 @c This used to work, probably because the DLLs were non-relocatable
32879 @c keep this section around until the problem is sorted out.
32880
32881 To break on the @code{DllMain} routine it is not possible to follow
32882 the procedure above. At the time the program stop on @code{ada_main}
32883 the @code{DllMain} routine as already been called. Either you can use
32884 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32885
32886 @enumerate 1
32887 @item Launch @code{GDB} on the main program.
32888
32889 @smallexample
32890 $ gdb ada_main
32891 @end smallexample
32892
32893 @item Load DLL symbols
32894
32895 @smallexample
32896 (gdb) add-sym api.dll
32897 @end smallexample
32898
32899 @item Set a breakpoint inside the DLL
32900
32901 @smallexample
32902 (gdb) break ada_dll.adb:45
32903 @end smallexample
32904
32905 Note that at this point it is not possible to break using the routine symbol
32906 directly as the program is not yet running. The solution is to break
32907 on the proper line (break in @file{ada_dll.adb} line 45).
32908
32909 @item Start the program
32910
32911 @smallexample
32912 (gdb) run
32913 @end smallexample
32914
32915 @end enumerate
32916 @end ignore
32917
32918 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32919 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32920
32921 @menu
32922 * Debugging the DLL Directly::
32923 * Attaching to a Running Process::
32924 @end menu
32925
32926 @noindent
32927 In this case things are slightly more complex because it is not possible to
32928 start the main program and then break at the beginning to load the DLL and the
32929 associated DLL debugging information. It is not possible to break at the
32930 beginning of the program because there is no @code{GDB} debugging information,
32931 and therefore there is no direct way of getting initial control. This
32932 section addresses this issue by describing some methods that can be used
32933 to break somewhere in the DLL to debug it.
32934
32935 @noindent
32936 First suppose that the main procedure is named @code{main} (this is for
32937 example some C code built with Microsoft Visual C) and that there is a
32938 DLL named @code{test.dll} containing an Ada entry point named
32939 @code{ada_dll}.
32940
32941 @noindent
32942 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32943 been built with debugging information (see GNAT -g option).
32944
32945 @node Debugging the DLL Directly
32946 @subsubsection Debugging the DLL Directly
32947
32948 @enumerate 1
32949 @item
32950 Find out the executable starting address
32951
32952 @smallexample
32953 $ objdump --file-header main.exe
32954 @end smallexample
32955
32956 The starting address is reported on the last line. For example:
32957
32958 @smallexample
32959 main.exe: file format pei-i386
32960 architecture: i386, flags 0x0000010a:
32961 EXEC_P, HAS_DEBUG, D_PAGED
32962 start address 0x00401010
32963 @end smallexample
32964
32965 @item
32966 Launch the debugger on the executable.
32967
32968 @smallexample
32969 $ gdb main.exe
32970 @end smallexample
32971
32972 @item
32973 Set a breakpoint at the starting address, and launch the program.
32974
32975 @smallexample
32976 $ (gdb) break *0x00401010
32977 $ (gdb) run
32978 @end smallexample
32979
32980 The program will stop at the given address.
32981
32982 @item
32983 Set a breakpoint on a DLL subroutine.
32984
32985 @smallexample
32986 (gdb) break ada_dll.adb:45
32987 @end smallexample
32988
32989 Or if you want to break using a symbol on the DLL, you need first to
32990 select the Ada language (language used by the DLL).
32991
32992 @smallexample
32993 (gdb) set language ada
32994 (gdb) break ada_dll
32995 @end smallexample
32996
32997 @item
32998 Continue the program.
32999
33000 @smallexample
33001 (gdb) cont
33002 @end smallexample
33003
33004 @noindent
33005 This will run the program until it reaches the breakpoint that has been
33006 set. From that point you can use the standard way to debug a program
33007 as described in (@pxref{Running and Debugging Ada Programs}).
33008
33009 @end enumerate
33010
33011 @noindent
33012 It is also possible to debug the DLL by attaching to a running process.
33013
33014 @node Attaching to a Running Process
33015 @subsubsection Attaching to a Running Process
33016 @cindex DLL debugging, attach to process
33017
33018 @noindent
33019 With @code{GDB} it is always possible to debug a running process by
33020 attaching to it. It is possible to debug a DLL this way. The limitation
33021 of this approach is that the DLL must run long enough to perform the
33022 attach operation. It may be useful for instance to insert a time wasting
33023 loop in the code of the DLL to meet this criterion.
33024
33025 @enumerate 1
33026
33027 @item Launch the main program @file{main.exe}.
33028
33029 @smallexample
33030 $ main
33031 @end smallexample
33032
33033 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33034 that the process PID for @file{main.exe} is 208.
33035
33036 @item Launch gdb.
33037
33038 @smallexample
33039 $ gdb
33040 @end smallexample
33041
33042 @item Attach to the running process to be debugged.
33043
33044 @smallexample
33045 (gdb) attach 208
33046 @end smallexample
33047
33048 @item Load the process debugging information.
33049
33050 @smallexample
33051 (gdb) symbol-file main.exe
33052 @end smallexample
33053
33054 @item Break somewhere in the DLL.
33055
33056 @smallexample
33057 (gdb) break ada_dll
33058 @end smallexample
33059
33060 @item Continue process execution.
33061
33062 @smallexample
33063 (gdb) cont
33064 @end smallexample
33065
33066 @end enumerate
33067
33068 @noindent
33069 This last step will resume the process execution, and stop at
33070 the breakpoint we have set. From there you can use the standard
33071 approach to debug a program as described in
33072 (@pxref{Running and Debugging Ada Programs}).
33073
33074 @node Setting Stack Size from gnatlink
33075 @section Setting Stack Size from @command{gnatlink}
33076
33077 @noindent
33078 It is possible to specify the program stack size at link time. On modern
33079 versions of Windows, starting with XP, this is mostly useful to set the size of
33080 the main stack (environment task). The other task stacks are set with pragma
33081 Storage_Size or with the @command{gnatbind -d} command.
33082
33083 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33084 reserve size of individual tasks, the link-time stack size applies to all
33085 tasks, and pragma Storage_Size has no effect.
33086 In particular, Stack Overflow checks are made against this
33087 link-time specified size.
33088
33089 This setting can be done with
33090 @command{gnatlink} using either:
33091
33092 @itemize @bullet
33093
33094 @item using @option{-Xlinker} linker option
33095
33096 @smallexample
33097 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33098 @end smallexample
33099
33100 This sets the stack reserve size to 0x10000 bytes and the stack commit
33101 size to 0x1000 bytes.
33102
33103 @item using @option{-Wl} linker option
33104
33105 @smallexample
33106 $ gnatlink hello -Wl,--stack=0x1000000
33107 @end smallexample
33108
33109 This sets the stack reserve size to 0x1000000 bytes. Note that with
33110 @option{-Wl} option it is not possible to set the stack commit size
33111 because the coma is a separator for this option.
33112
33113 @end itemize
33114
33115 @node Setting Heap Size from gnatlink
33116 @section Setting Heap Size from @command{gnatlink}
33117
33118 @noindent
33119 Under Windows systems, it is possible to specify the program heap size from
33120 @command{gnatlink} using either:
33121
33122 @itemize @bullet
33123
33124 @item using @option{-Xlinker} linker option
33125
33126 @smallexample
33127 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33128 @end smallexample
33129
33130 This sets the heap reserve size to 0x10000 bytes and the heap commit
33131 size to 0x1000 bytes.
33132
33133 @item using @option{-Wl} linker option
33134
33135 @smallexample
33136 $ gnatlink hello -Wl,--heap=0x1000000
33137 @end smallexample
33138
33139 This sets the heap reserve size to 0x1000000 bytes. Note that with
33140 @option{-Wl} option it is not possible to set the heap commit size
33141 because the coma is a separator for this option.
33142
33143 @end itemize
33144
33145 @end ifset
33146
33147 @c **********************************
33148 @c * GNU Free Documentation License *
33149 @c **********************************
33150 @include fdl.texi
33151 @c GNU Free Documentation License
33152
33153 @node Index,,GNU Free Documentation License, Top
33154 @unnumbered Index
33155
33156 @printindex cp
33157
33158 @contents
33159 @c Put table of contents at end, otherwise it precedes the "title page" in
33160 @c the .txt version
33161 @c Edit the pdf file to move the contents to the beginning, after the title
33162 @c page
33163
33164 @bye