OSDN Git Service

PR ada/14150
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2004 Ada Core Technologies, Inc.               o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, USA.                                                       o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
24
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26 @c
27 @c                           GNAT_UGN Style Guide
28 @c
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
31 @c
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
37 @c
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
41 @c
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
57 @c
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
60 @c
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
63 @c
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
66 @c
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
69 @c
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
73 @c
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
77 @c
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
79
80 @setfilename gnat_ugn.info
81
82 @ifset vms
83 @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha
84 @end ifset
85
86 @ifset unw
87 @settitle GNAT User's Guide for Native Platforms / Unix and Windows
88 @end ifset
89
90 @include gcc-common.texi
91
92 @setchapternewpage odd
93 @syncodeindex fn cp
94 @c %**end of header
95
96 @copying
97 Copyright @copyright{} 1995-2004, Free Software Foundation
98
99 Permission is granted to copy, distribute and/or modify this document
100 under the terms of the GNU Free Documentation License, Version 1.2
101 or any later version published by the Free Software Foundation;
102 with the Invariant Sections being ``GNU Free Documentation License'', with the
103 Front-Cover Texts being
104 @ifset vms
105 ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'',
106 @end ifset
107 @ifset unw
108 ``GNAT User's Guide for Native Platforms / Unix and Windows'',
109 @end ifset
110 and with no Back-Cover Texts.
111 A copy of the license is included in the section entitled
112 ``GNU Free Documentation License''.
113 @end copying
114
115 @titlepage
116
117 @title GNAT User's Guide
118 @center @titlefont{for Native Platforms}
119 @sp 1
120
121 @flushright
122 @ifset unw
123 @titlefont{@i{Unix and Windows}}
124 @end ifset
125 @ifset vms
126 @titlefont{@i{OpenVMS Alpha}}
127 @end ifset
128 @end flushright
129 @sp 2
130
131 @subtitle GNAT, The GNU Ada 95 Compiler
132 @subtitle GCC version @value{version-GCC}
133
134 @author Ada Core Technologies, Inc.
135
136 @page
137 @vskip 0pt plus 1filll
138
139 @insertcopying
140
141 @end titlepage
142
143
144 @ifinfo
145 @node Top, About This Guide, (dir), (dir)
146 @top GNAT User's Guide
147
148 @ifset vms
149 @noindent
150 GNAT User's Guide for Native Platforms / OpenVMS Alpha
151 @end ifset
152
153 @ifset unw
154 @noindent
155 GNAT User's Guide for Native Platforms / Unix and Windows
156 @end ifset
157
158 @noindent
159 GNAT, The GNU Ada 95 Compiler@*
160 GCC version @value{version-GCC}@*
161
162 @noindent
163 Ada Core Technologies, Inc.@*
164
165 @menu
166 * About This Guide::
167 * Getting Started with GNAT::
168 * The GNAT Compilation Model::
169 * Compiling Using gcc::
170 * Binding Using gnatbind::
171 * Linking Using gnatlink::
172 * The GNAT Make Program gnatmake::
173 * Improving Performance::
174 * Renaming Files Using gnatchop::
175 * Configuration Pragmas::
176 * Handling Arbitrary File Naming Conventions Using gnatname::
177 * GNAT Project Manager::
178 * The Cross-Referencing Tools gnatxref and gnatfind::
179 * The GNAT Pretty-Printer gnatpp::
180 * File Name Krunching Using gnatkr::
181 * Preprocessing Using gnatprep::
182 @ifset vms
183 * The GNAT Run-Time Library Builder gnatlbr::
184 @end ifset
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Finding Memory Problems::
192 * Creating Sample Bodies Using gnatstub::
193 * Other Utility Programs::
194 * Running and Debugging Ada Programs::
195 @ifset vms
196 * Compatibility with DEC Ada::
197 @end ifset
198 * Platform-Specific Information for the Run-Time Libraries::
199 * Example of Binder Output File::
200 * Elaboration Order Handling in GNAT::
201 * Inline Assembler::
202 * Compatibility and Porting Guide::
203 @ifset unw
204 * Microsoft Windows Topics::
205 @end ifset
206 * GNU Free Documentation License::
207 * Index::
208
209  --- The Detailed Node Listing ---
210
211 About This Guide
212
213 * What This Guide Contains::
214 * What You Should Know before Reading This Guide::
215 * Related Information::
216 * Conventions::
217
218 Getting Started with GNAT
219
220 * Running GNAT::
221 * Running a Simple Ada Program::
222 * Running a Program with Multiple Units::
223 * Using the gnatmake Utility::
224 @ifset vms
225 * Editing with Emacs::
226 @end ifset
227 @ifclear vms
228 * Introduction to GPS::
229 * Introduction to Glide and GVD::
230 @end ifclear
231
232 The GNAT Compilation Model
233
234 * Source Representation::
235 * Foreign Language Representation::
236 * File Naming Rules::
237 * Using Other File Names::
238 * Alternative File Naming Schemes::
239 * Generating Object Files::
240 * Source Dependencies::
241 * The Ada Library Information Files::
242 * Binding an Ada Program::
243 * Mixed Language Programming::
244 * Building Mixed Ada & C++ Programs::
245 * Comparison between GNAT and C/C++ Compilation Models::
246 * Comparison between GNAT and Conventional Ada Library Models::
247 @ifset vms
248 * Placement of temporary files::
249 @end ifset
250
251 Foreign Language Representation
252
253 * Latin-1::
254 * Other 8-Bit Codes::
255 * Wide Character Encodings::
256
257 Compiling Ada Programs With gcc
258
259 * Compiling Programs::
260 * Switches for gcc::
261 * Search Paths and the Run-Time Library (RTL)::
262 * Order of Compilation Issues::
263 * Examples::
264
265 Switches for gcc
266
267 * Output and Error Message Control::
268 * Warning Message Control::
269 * Debugging and Assertion Control::
270 * Run-Time Checks::
271 * Stack Overflow Checking::
272 * Validity Checking::
273 * Style Checking::
274 * Using gcc for Syntax Checking::
275 * Using gcc for Semantic Checking::
276 * Compiling Ada 83 Programs::
277 * Character Set Control::
278 * File Naming Control::
279 * Subprogram Inlining Control::
280 * Auxiliary Output Control::
281 * Debugging Control::
282 * Exception Handling Control::
283 * Units to Sources Mapping Files::
284 * Integrated Preprocessing::
285 @ifset vms
286 * Return Codes::
287 @end ifset
288
289 Binding Ada Programs With gnatbind
290
291 * Running gnatbind::
292 * Switches for gnatbind::
293 * Command-Line Access::
294 * Search Paths for gnatbind::
295 * Examples of gnatbind Usage::
296
297 Switches for gnatbind
298
299 * Consistency-Checking Modes::
300 * Binder Error Message Control::
301 * Elaboration Control::
302 * Output Control::
303 * Binding with Non-Ada Main Programs::
304 * Binding Programs with No Main Subprogram::
305
306 Linking Using gnatlink
307
308 * Running gnatlink::
309 * Switches for gnatlink::
310 * Setting Stack Size from gnatlink::
311 * Setting Heap Size from 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
323 Improving Performance
324 * Performance Considerations::
325 * Reducing the Size of Ada Executables with gnatelim::
326
327 Performance Considerations
328 * Controlling Run-Time Checks::
329 * Use of Restrictions::
330 * Optimization Levels::
331 * Debugging Optimized Code::
332 * Inlining of Subprograms::
333 * Optimization and Strict Aliasing::
334 @ifset vms
335 * Coverage Analysis::
336 @end ifset
337
338 Reducing the Size of Ada Executables with gnatelim
339 * About gnatelim::
340 * Running gnatelim::
341 * Correcting the List of Eliminate Pragmas::
342 * Making Your Executables Smaller::
343 * Summary of the gnatelim Usage Cycle::
344
345 Renaming Files Using gnatchop
346
347 * Handling Files with Multiple Units::
348 * Operating gnatchop in Compilation Mode::
349 * Command Line for gnatchop::
350 * Switches for gnatchop::
351 * Examples of gnatchop Usage::
352
353 Configuration Pragmas
354
355 * Handling of Configuration Pragmas::
356 * The Configuration Pragmas Files::
357
358 Handling Arbitrary File Naming Conventions Using gnatname
359
360 * Arbitrary File Naming Conventions::
361 * Running gnatname::
362 * Switches for gnatname::
363 * Examples of gnatname Usage::
364
365 GNAT Project Manager
366
367 * Introduction::
368 * Examples of Project Files::
369 * Project File Syntax::
370 * Objects and Sources in Project Files::
371 * Importing Projects::
372 * Project Extension::
373 * External References in Project Files::
374 * Packages in Project Files::
375 * Variables from Imported Projects::
376 * Naming Schemes::
377 * Library Projects::
378 * Using Third-Party Libraries through Projects::
379 * Stand-alone Library Projects::
380 * Switches Related to Project Files::
381 * Tools Supporting Project Files::
382 * An Extended Example::
383 * Project File Complete Syntax::
384
385
386 The Cross-Referencing Tools gnatxref and gnatfind
387
388 * gnatxref Switches::
389 * gnatfind Switches::
390 * Project Files for gnatxref and gnatfind::
391 * Regular Expressions in gnatfind and gnatxref::
392 * Examples of gnatxref Usage::
393 * Examples of gnatfind Usage::
394
395
396 The GNAT Pretty-Printer gnatpp
397
398 * Switches for gnatpp::
399 * Formatting Rules::
400
401
402 File Name Krunching Using gnatkr
403
404 * About gnatkr::
405 * Using gnatkr::
406 * Krunching Method::
407 * Examples of gnatkr Usage::
408
409 Preprocessing Using gnatprep
410
411 * Using gnatprep::
412 * Switches for gnatprep::
413 * Form of Definitions File::
414 * Form of Input Text for gnatprep::
415
416 @ifset vms
417 The GNAT Run-Time Library Builder gnatlbr
418
419 * Running gnatlbr::
420 * Switches for gnatlbr::
421 * Examples of gnatlbr Usage::
422 @end ifset
423
424 The GNAT Library Browser gnatls
425
426 * Running gnatls::
427 * Switches for gnatls::
428 * Examples of gnatls Usage::
429
430 Cleaning Up Using gnatclean
431
432 * Running gnatclean::
433 * Switches for gnatclean::
434 * Examples of gnatclean Usage::
435
436 @ifclear vms
437
438 GNAT and Libraries
439
440 * Creating an Ada Library::
441 * Installing an Ada Library::
442 * Using an Ada Library::
443 * Creating an Ada Library to be Used in a Non-Ada Context::
444 * Rebuilding the GNAT Run-Time Library::
445
446 Using the GNU make Utility
447
448 * Using gnatmake in a Makefile::
449 * Automatically Creating a List of Directories::
450 * Generating the Command Line Switches::
451 * Overcoming Command Line Length Limits::
452 @end ifclear
453
454 Finding Memory Problems
455
456 @ifclear vms
457 * The gnatmem Tool::
458 @end ifclear
459 * The GNAT Debug Pool Facility::
460
461 @ifclear vms
462 The gnatmem Tool
463
464 * Running gnatmem::
465 * Switches for gnatmem::
466 * Example of gnatmem Usage::
467 @end ifclear
468
469 The GNAT Debug Pool Facility
470
471 Creating Sample Bodies Using gnatstub
472
473 * Running gnatstub::
474 * Switches for gnatstub::
475
476 Other Utility Programs
477
478 * Using Other Utility Programs with GNAT::
479 * The External Symbol Naming Scheme of GNAT::
480 @ifclear vms
481 * Ada Mode for Glide::
482 @end ifclear
483 * Converting Ada Files to html with gnathtml::
484
485 Running and Debugging Ada Programs
486
487 * The GNAT Debugger GDB::
488 * Running GDB::
489 * Introduction to GDB Commands::
490 * Using Ada Expressions::
491 * Calling User-Defined Subprograms::
492 * Using the Next Command in a Function::
493 * Ada Exceptions::
494 * Ada Tasks::
495 * Debugging Generic Units::
496 * GNAT Abnormal Termination or Failure to Terminate::
497 * Naming Conventions for GNAT Source Files::
498 * Getting Internal Debugging Information::
499 * Stack Traceback::
500
501 @ifset vms
502 * LSE::
503 @end ifset
504
505 @ifset vms
506 Compatibility with DEC Ada
507
508 * Ada 95 Compatibility::
509 * Differences in the Definition of Package System::
510 * Language-Related Features::
511 * The Package STANDARD::
512 * The Package SYSTEM::
513 * Tasking and Task-Related Features::
514 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
515 * Pragmas and Pragma-Related Features::
516 * Library of Predefined Units::
517 * Bindings::
518 * Main Program Definition::
519 * Implementation-Defined Attributes::
520 * Compiler and Run-Time Interfacing::
521 * Program Compilation and Library Management::
522 * Input-Output::
523 * Implementation Limits::
524 * Tools::
525
526 Language-Related Features
527
528 * Integer Types and Representations::
529 * Floating-Point Types and Representations::
530 * Pragmas Float_Representation and Long_Float::
531 * Fixed-Point Types and Representations::
532 * Record and Array Component Alignment::
533 * Address Clauses::
534 * Other Representation Clauses::
535
536 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
537
538 * Assigning Task IDs::
539 * Task IDs and Delays::
540 * Task-Related Pragmas::
541 * Scheduling and Task Priority::
542 * The Task Stack::
543 * External Interrupts::
544
545 Pragmas and Pragma-Related Features
546
547 * Restrictions on the Pragma INLINE::
548 * Restrictions on the Pragma INTERFACE::
549 * Restrictions on the Pragma SYSTEM_NAME::
550
551 Library of Predefined Units
552
553 * Changes to DECLIB::
554
555 Bindings
556
557 * Shared Libraries and Options Files::
558 * Interfaces to C::
559 @end ifset
560
561 Platform-Specific Information for the Run-Time Libraries
562
563 * Summary of Run-Time Configurations::
564 * Specifying a Run-Time Library::
565 * Choosing between Native and FSU Threads Libraries::
566 * Choosing the Scheduling Policy::
567 * Solaris-Specific Considerations::
568 * IRIX-Specific Considerations::
569 * Linux-Specific Considerations::
570
571 Example of Binder Output File
572
573 Elaboration Order Handling in GNAT
574
575 * Elaboration Code in Ada 95::
576 * Checking the Elaboration Order in Ada 95::
577 * Controlling the Elaboration Order in Ada 95::
578 * Controlling Elaboration in GNAT - Internal Calls::
579 * Controlling Elaboration in GNAT - External Calls::
580 * Default Behavior in GNAT - Ensuring Safety::
581 * Treatment of Pragma Elaborate::
582 * Elaboration Issues for Library Tasks::
583 * Mixing Elaboration Models::
584 * What to Do If the Default Elaboration Behavior Fails::
585 * Elaboration for Access-to-Subprogram Values::
586 * Summary of Procedures for Elaboration Control::
587 * Other Elaboration Order Considerations::
588
589 Inline Assembler
590
591 * Basic Assembler Syntax::
592 * A Simple Example of Inline Assembler::
593 * Output Variables in Inline Assembler::
594 * Input Variables in Inline Assembler::
595 * Inlining Inline Assembler Code::
596 * Other Asm Functionality::
597 * A Complete Example::
598
599 Compatibility and Porting Guide
600
601 * Compatibility with Ada 83::
602 * Implementation-dependent characteristics::
603 * Compatibility with DEC Ada 83::
604 * Compatibility with Other Ada 95 Systems::
605 * Representation Clauses::
606
607 @ifset unw
608 Microsoft Windows Topics
609
610 * Using GNAT on Windows::
611 * CONSOLE and WINDOWS subsystems::
612 * Temporary Files::
613 * Mixed-Language Programming on Windows::
614 * Windows Calling Conventions::
615 * Introduction to Dynamic Link Libraries (DLLs)::
616 * Using DLLs with GNAT::
617 * Building DLLs with GNAT::
618 * GNAT and Windows Resources::
619 * Debugging a DLL::
620 * GNAT and COM/DCOM Objects::
621 @end ifset
622
623
624 * Index::
625 @end menu
626 @end ifinfo
627
628 @node About This Guide
629 @unnumbered About This Guide
630
631 @noindent
632 @ifset vms
633 This guide describes the use of of GNAT, a full language compiler for the Ada
634 95 programming language, implemented on HP OpenVMS Alpha platforms.
635 @end ifset
636 @ifclear vms
637 This guide describes the use of GNAT, a compiler and software development
638 toolset for the full Ada 95 programming language.
639 @end ifclear
640 It describes the features of the compiler and tools, and details
641 how to use them to build Ada 95 applications.
642
643 @menu
644 * What This Guide Contains::
645 * What You Should Know before Reading This Guide::
646 * Related Information::
647 * Conventions::
648 @end menu
649
650 @node What This Guide Contains
651 @unnumberedsec What This Guide Contains
652
653 @noindent
654 This guide contains the following chapters:
655 @itemize @bullet
656
657 @item
658 @ref{Getting Started with GNAT}, describes how to get started compiling
659 and running Ada programs with the GNAT Ada programming environment.
660 @item
661 @ref{The GNAT Compilation Model}, describes the compilation model used
662 by GNAT.
663
664 @item
665 @ref{Compiling Using gcc}, describes how to compile
666 Ada programs with @code{gcc}, the Ada compiler.
667
668 @item
669 @ref{Binding Using gnatbind}, describes how to
670 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
671 utility.
672
673 @item
674 @ref{Linking Using gnatlink},
675 describes @code{gnatlink}, a
676 program that provides for linking using the GNAT run-time library to
677 construct a program. @code{gnatlink} can also incorporate foreign language
678 object units into the executable.
679
680 @item
681 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
682 utility that automatically determines the set of sources
683 needed by an Ada compilation unit, and executes the necessary compilations
684 binding and link.
685
686 @item
687 @ref{Improving Performance}, shows various techniques for making your
688 Ada program run faster or take less space.
689 It discusses the effect of the compiler's optimization switch and
690 also describes the @command{gnatelim} tool.
691
692 @item
693 @ref{Renaming Files Using gnatchop}, describes
694 @code{gnatchop}, a utility that allows you to preprocess a file that
695 contains Ada source code, and split it into one or more new files, one
696 for each compilation unit.
697
698 @item
699 @ref{Configuration Pragmas}, describes the configuration pragmas
700 handled by GNAT.
701
702 @item
703 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
704 shows how to override the default GNAT file naming conventions,
705 either for an individual unit or globally.
706
707 @item
708 @ref{GNAT Project Manager}, describes how to use project files
709 to organize large projects.
710
711 @item
712 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
713 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
714 way to navigate through sources.
715
716 @item
717 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
718 version of an Ada source file with control over casing, indentation,
719 comment placement, and other elements of program presentation style.
720
721
722 @item
723 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
724 file name krunching utility, used to handle shortened
725 file names on operating systems with a limit on the length of names.
726
727 @item
728 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
729 preprocessor utility that allows a single source file to be used to
730 generate multiple or parameterized source files, by means of macro
731 substitution.
732
733 @ifset vms
734 @item
735 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
736 a tool for rebuilding the GNAT run time with user-supplied
737 configuration pragmas.
738 @end ifset
739
740 @item
741 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
742 utility that displays information about compiled units, including dependences
743 on the corresponding sources files, and consistency of compilations.
744
745 @item
746 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
747 to delete files that are produced by the compiler, binder and linker.
748
749 @ifclear vms
750 @item
751 @ref{GNAT and Libraries}, describes the process of creating and using
752 Libraries with GNAT. It also describes how to recompile the GNAT run-time
753 library.
754
755 @item
756 @ref{Using the GNU make Utility}, describes some techniques for using
757 the GNAT toolset in Makefiles.
758 @end ifclear
759
760 @item
761 @ref{Finding Memory Problems}, describes
762 @ifclear vms
763 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
764 and helps detect ``memory leaks'', and
765 @end ifclear
766 the GNAT Debug Pool facility, which helps detect incorrect memory references.
767
768 @item
769 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
770 a utility that generates empty but compilable bodies for library units.
771
772 @item
773 @ref{Other Utility Programs}, discusses several other GNAT utilities,
774 including @code{gnathtml}.
775
776 @item
777 @ref{Running and Debugging Ada Programs}, describes how to run and debug
778 Ada programs.
779
780 @ifset vms
781 @item
782 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
783 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
784 developed by Digital Equipment Corporation and currently supported by HP.}
785 for OpenVMS Alpha.
786 @end ifset
787
788 @item
789 @ref{Platform-Specific Information for the Run-Time Libraries},
790 describes the various run-time
791 libraries supported by GNAT on various platforms and explains how to
792 choose a particular library.
793
794 @item
795 @ref{Example of Binder Output File}, shows the source code for the binder
796 output file for a sample program.
797
798 @item
799 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
800 you deal with elaboration order issues.
801
802 @item
803 @ref{Inline Assembler}, shows how to use the inline assembly facility
804 in an Ada program.
805
806 @item
807 @ref{Compatibility and Porting Guide}, includes sections on compatibility
808 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
809 in porting code from other environments.
810
811 @ifset unw
812 @item
813 @ref{Microsoft Windows Topics}, presents information relevant to the
814 Microsoft Windows platform.
815 @end ifset
816 @end itemize
817
818
819 @c *************************************************
820 @node What You Should Know before Reading This Guide
821 @c *************************************************
822 @unnumberedsec What You Should Know before Reading This Guide
823
824 @cindex Ada 95 Language Reference Manual
825 @noindent
826 This user's guide assumes that you are familiar with Ada 95 language, as
827 described in the International Standard ANSI/ISO/IEC-8652:1995, January
828 1995.
829
830 @node Related Information
831 @unnumberedsec Related Information
832
833 @noindent
834 For further information about related tools, refer to the following
835 documents:
836
837 @itemize @bullet
838 @item
839 @cite{GNAT Reference Manual}, which contains all reference
840 material for the GNAT implementation of Ada 95.
841
842 @ifset unw
843 @item
844 @cite{Using the GNAT Programming System}, which describes the GPS
845 integrated development environment.
846
847 @item
848 @cite{GNAT Programming System Tutorial}, which introduces the
849 main GPS features through examples.
850 @end ifset
851
852 @item
853 @cite{Ada 95 Language Reference Manual}, which contains all reference
854 material for the Ada 95 programming language.
855
856 @item
857 @cite{Debugging with GDB}
858 @ifset vms
859 , located in the GNU:[DOCS] directory,
860 @end ifset
861 contains all details on the use of the GNU source-level debugger.
862
863 @item
864 @cite{GNU Emacs Manual}
865 @ifset vms
866 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
867 @end ifset
868 contains full information on the extensible editor and programming
869 environment Emacs.
870
871 @end itemize
872
873 @c **************
874 @node Conventions
875 @unnumberedsec Conventions
876 @cindex Conventions
877 @cindex Typographical conventions
878
879 @noindent
880 Following are examples of the typographical and graphic conventions used
881 in this guide:
882
883 @itemize @bullet
884 @item
885 @code{Functions}, @code{utility program names}, @code{standard names},
886 and @code{classes}.
887
888 @item
889 @samp{Option flags}
890
891 @item
892 @file{File Names}, @file{button names}, and @file{field names}.
893
894 @item
895 @var{Variables}.
896
897 @item
898 @emph{Emphasis}.
899
900 @item
901 [optional information or parameters]
902
903 @item
904 Examples are described by text
905 @smallexample
906 and then shown this way.
907 @end smallexample
908 @end itemize
909
910 @noindent
911 Commands that are entered by the user are preceded in this manual by the
912 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
913 uses this sequence as a prompt, then the commands will appear exactly as
914 you see them in the manual. If your system uses some other prompt, then
915 the command will appear with the @code{$} replaced by whatever prompt
916 character you are using.
917
918 @ifset unw
919 Full file names are shown with the ``@code{/}'' character
920 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
921 If you are using GNAT on a Windows platform, please note that
922 the ``@code{\}'' character should be used instead.
923 @end ifset
924
925
926
927 @c ****************************
928 @node Getting Started with GNAT
929 @chapter Getting Started with GNAT
930
931 @noindent
932 This chapter describes some simple ways of using GNAT to build
933 executable Ada programs.
934 @ifset unw
935 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
936 show how to use the command line environment.
937 @ref{Introduction to Glide and GVD}, provides a brief
938 introduction to the visually-oriented IDE for GNAT.
939 Supplementing Glide on some platforms is GPS, the
940 GNAT Programming System, which offers a richer graphical
941 ``look and feel'', enhanced configurability, support for
942 development in other programming language, comprehensive
943 browsing features, and many other capabilities.
944 For information on GPS please refer to
945 @cite{Using the GNAT Programming System}.
946 @end ifset
947
948 @menu
949 * Running GNAT::
950 * Running a Simple Ada Program::
951 * Running a Program with Multiple Units::
952 * Using the gnatmake Utility::
953 @ifset vms
954 * Editing with Emacs::
955 @end ifset
956 @ifclear vms
957 * Introduction to GPS::
958 * Introduction to Glide and GVD::
959 @end ifclear
960 @end menu
961
962 @node Running GNAT
963 @section Running GNAT
964
965 @noindent
966 Three steps are needed to create an executable file from an Ada source
967 file:
968
969 @enumerate
970 @item
971 The source file(s) must be compiled.
972 @item
973 The file(s) must be bound using the GNAT binder.
974 @item
975 All appropriate object files must be linked to produce an executable.
976 @end enumerate
977
978 @noindent
979 All three steps are most commonly handled by using the @code{gnatmake}
980 utility program that, given the name of the main program, automatically
981 performs the necessary compilation, binding and linking steps.
982
983
984 @node Running a Simple Ada Program
985 @section Running a Simple Ada Program
986
987 @noindent
988 Any text editor may be used to prepare an Ada program.
989 @ifclear vms
990 If @code{Glide} is
991 used, the optional Ada mode may be helpful in laying out the program.
992 @end ifclear
993 The
994 program text is a normal text file. We will suppose in our initial
995 example that you have used your editor to prepare the following
996 standard format text file:
997
998 @smallexample @c ada
999 @cartouche
1000 with Ada.Text_IO; use Ada.Text_IO;
1001 procedure Hello is
1002 begin
1003    Put_Line ("Hello WORLD!");
1004 end Hello;
1005 @end cartouche
1006 @end smallexample
1007
1008 @noindent
1009 This file should be named @file{hello.adb}.
1010 With the normal default file naming conventions, GNAT requires
1011 that each file
1012 contain a single compilation unit whose file name is the
1013 unit name,
1014 with periods replaced by hyphens; the
1015 extension is @file{ads} for a
1016 spec and @file{adb} for a body.
1017 You can override this default file naming convention by use of the
1018 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1019 Alternatively, if you want to rename your files according to this default
1020 convention, which is probably more convenient if you will be using GNAT
1021 for all your compilations, then the @code{gnatchop} utility
1022 can be used to generate correctly-named source files
1023 (@pxref{Renaming Files Using gnatchop}).
1024
1025 You can compile the program using the following command (@code{$} is used
1026 as the command prompt in the examples in this document):
1027
1028 @smallexample
1029 $ gcc -c hello.adb
1030 @end smallexample
1031
1032 @noindent
1033 @code{gcc} is the command used to run the compiler. This compiler is
1034 capable of compiling programs in several languages, including Ada 95 and
1035 C. It assumes that you have given it an Ada program if the file extension is
1036 either @file{.ads} or @file{.adb}, and it will then call
1037 the GNAT compiler to compile the specified file.
1038
1039 @ifclear vms
1040 The @option{-c} switch is required. It tells @command{gcc} to only do a
1041 compilation. (For C programs, @command{gcc} can also do linking, but this
1042 capability is not used directly for Ada programs, so the @option{-c}
1043 switch must always be present.)
1044 @end ifclear
1045
1046 This compile command generates a file
1047 @file{hello.o}, which is the object
1048 file corresponding to your Ada program. It also generates
1049 an ``Ada Library Information'' file @file{hello.ali},
1050 which contains additional information used to check
1051 that an Ada program is consistent.
1052 To build an executable file,
1053 use @code{gnatbind} to bind the program
1054 and @code{gnatlink} to link it. The
1055 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1056 @file{ALI} file, but the default extension of @file{.ali} can
1057 be omitted. This means that in the most common case, the argument
1058 is simply the name of the main program:
1059
1060 @smallexample
1061 $ gnatbind hello
1062 $ gnatlink hello
1063 @end smallexample
1064
1065 @noindent
1066 A simpler method of carrying out these steps is to use
1067 @command{gnatmake},
1068 a master program that invokes all the required
1069 compilation, binding and linking tools in the correct order. In particular,
1070 @command{gnatmake} automatically recompiles any sources that have been
1071 modified since they were last compiled, or sources that depend
1072 on such modified sources, so that ``version skew'' is avoided.
1073 @cindex Version skew (avoided by @command{gnatmake})
1074
1075 @smallexample
1076 $ gnatmake hello.adb
1077 @end smallexample
1078
1079 @noindent
1080 The result is an executable program called @file{hello}, which can be
1081 run by entering:
1082
1083 @c The following should be removed (BMB 2001-01-23)
1084 @c @smallexample
1085 @c $ ^./hello^$ RUN HELLO^
1086 @c @end smallexample
1087
1088 @smallexample
1089 $ hello
1090 @end smallexample
1091
1092 @noindent
1093 assuming that the current directory is on the search path
1094 for executable programs.
1095
1096 @noindent
1097 and, if all has gone well, you will see
1098
1099 @smallexample
1100 Hello WORLD!
1101 @end smallexample
1102
1103 @noindent
1104 appear in response to this command.
1105
1106
1107 @c ****************************************
1108 @node Running a Program with Multiple Units
1109 @section Running a Program with Multiple Units
1110
1111 @noindent
1112 Consider a slightly more complicated example that has three files: a
1113 main program, and the spec and body of a package:
1114
1115 @smallexample @c ada
1116 @cartouche
1117 @group
1118 package Greetings is
1119    procedure Hello;
1120    procedure Goodbye;
1121 end Greetings;
1122
1123 with Ada.Text_IO; use Ada.Text_IO;
1124 package body Greetings is
1125    procedure Hello is
1126    begin
1127       Put_Line ("Hello WORLD!");
1128    end Hello;
1129
1130    procedure Goodbye is
1131    begin
1132       Put_Line ("Goodbye WORLD!");
1133    end Goodbye;
1134 end Greetings;
1135 @end group
1136
1137 @group
1138 with Greetings;
1139 procedure Gmain is
1140 begin
1141    Greetings.Hello;
1142    Greetings.Goodbye;
1143 end Gmain;
1144 @end group
1145 @end cartouche
1146 @end smallexample
1147
1148 @noindent
1149 Following the one-unit-per-file rule, place this program in the
1150 following three separate files:
1151
1152 @table @file
1153 @item greetings.ads
1154 spec of package @code{Greetings}
1155
1156 @item greetings.adb
1157 body of package @code{Greetings}
1158
1159 @item gmain.adb
1160 body of main program
1161 @end table
1162
1163 @noindent
1164 To build an executable version of
1165 this program, we could use four separate steps to compile, bind, and link
1166 the program, as follows:
1167
1168 @smallexample
1169 $ gcc -c gmain.adb
1170 $ gcc -c greetings.adb
1171 $ gnatbind gmain
1172 $ gnatlink gmain
1173 @end smallexample
1174
1175 @noindent
1176 Note that there is no required order of compilation when using GNAT.
1177 In particular it is perfectly fine to compile the main program first.
1178 Also, it is not necessary to compile package specs in the case where
1179 there is an accompanying body; you only need to compile the body. If you want
1180 to submit these files to the compiler for semantic checking and not code
1181 generation, then use the
1182 @option{-gnatc} switch:
1183
1184 @smallexample
1185 $ gcc -c greetings.ads -gnatc
1186 @end smallexample
1187
1188 @noindent
1189 Although the compilation can be done in separate steps as in the
1190 above example, in practice it is almost always more convenient
1191 to use the @code{gnatmake} tool. All you need to know in this case
1192 is the name of the main program's source file. The effect of the above four
1193 commands can be achieved with a single one:
1194
1195 @smallexample
1196 $ gnatmake gmain.adb
1197 @end smallexample
1198
1199 @noindent
1200 In the next section we discuss the advantages of using @code{gnatmake} in
1201 more detail.
1202
1203 @c *****************************
1204 @node Using the gnatmake Utility
1205 @section Using the @command{gnatmake} Utility
1206
1207 @noindent
1208 If you work on a program by compiling single components at a time using
1209 @code{gcc}, you typically keep track of the units you modify. In order to
1210 build a consistent system, you compile not only these units, but also any
1211 units that depend on the units you have modified.
1212 For example, in the preceding case,
1213 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1214 you edit @file{greetings.ads}, you must recompile both
1215 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1216 units that depend on @file{greetings.ads}.
1217
1218 @code{gnatbind} will warn you if you forget one of these compilation
1219 steps, so that it is impossible to generate an inconsistent program as a
1220 result of forgetting to do a compilation. Nevertheless it is tedious and
1221 error-prone to keep track of dependencies among units.
1222 One approach to handle the dependency-bookkeeping is to use a
1223 makefile. However, makefiles present maintenance problems of their own:
1224 if the dependencies change as you change the program, you must make
1225 sure that the makefile is kept up-to-date manually, which is also an
1226 error-prone process.
1227
1228 The @code{gnatmake} utility takes care of these details automatically.
1229 Invoke it using either one of the following forms:
1230
1231 @smallexample
1232 $ gnatmake gmain.adb
1233 $ gnatmake ^gmain^GMAIN^
1234 @end smallexample
1235
1236 @noindent
1237 The argument is the name of the file containing the main program;
1238 you may omit the extension. @code{gnatmake}
1239 examines the environment, automatically recompiles any files that need
1240 recompiling, and binds and links the resulting set of object files,
1241 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1242 In a large program, it
1243 can be extremely helpful to use @code{gnatmake}, because working out by hand
1244 what needs to be recompiled can be difficult.
1245
1246 Note that @code{gnatmake}
1247 takes into account all the Ada 95 rules that
1248 establish dependencies among units. These include dependencies that result
1249 from inlining subprogram bodies, and from
1250 generic instantiation. Unlike some other
1251 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1252 found by the compiler on a previous compilation, which may possibly
1253 be wrong when sources change. @code{gnatmake} determines the exact set of
1254 dependencies from scratch each time it is run.
1255
1256 @ifset vms
1257 @node Editing with Emacs
1258 @section Editing with Emacs
1259 @cindex Emacs
1260
1261 @noindent
1262 Emacs is an extensible self-documenting text editor that is available in a
1263 separate VMSINSTAL kit.
1264
1265 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1266 click on the Emacs Help menu and run the Emacs Tutorial.
1267 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1268 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1269
1270 Documentation on Emacs and other tools is available in Emacs under the
1271 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1272 use the middle mouse button to select a topic (e.g. Emacs).
1273
1274 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1275 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1276 get to the Emacs manual.
1277 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1278 prompt.
1279
1280 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1281 which is sufficiently extensible to provide for a complete programming
1282 environment and shell for the sophisticated user.
1283 @end ifset
1284
1285 @ifclear vms
1286 @node Introduction to GPS
1287 @section Introduction to GPS
1288 @cindex GPS (GNAT Programming System)
1289 @cindex GNAT Programming System (GPS)
1290 @noindent
1291 Although the command line interface (@command{gnatmake}, etc.) alone
1292 is sufficient, a graphical Interactive Development
1293 Environment can make it easier for you to compose, navigate, and debug
1294 programs.  This section describes the main features of GPS
1295 (``GNAT Programming System''), the GNAT graphical IDE.
1296 You will see how to use GPS to build and debug an executable, and
1297 you will also learn some of the basics of the GNAT ``project'' facility.
1298
1299 GPS enables you to do much more than is presented here;
1300 e.g., you can produce a call graph, interface to a third-party
1301 Version Control System, and inspect the generated assembly language
1302 for a program.
1303 Indeed, GPS also supports languages other than Ada.
1304 Such additional information, and an explanation of all of the GPS menu
1305 items. may be found in the on-line help, which includes
1306 a user's guide and a tutorial (these are also accessible from the GNAT
1307 startup menu).
1308
1309 @menu
1310 * Building a New Program with GPS::
1311 * Simple Debugging with GPS::
1312 @end menu
1313
1314
1315 @node Building a New Program with GPS
1316 @subsection Building a New Program with GPS
1317 @noindent
1318 GPS invokes the GNAT compilation tools using information
1319 contained in a @emph{project} (also known as a @emph{project file}):
1320 a collection of properties such
1321 as source directories, identities of main subprograms, tool switches, etc.,
1322 and their associated values.
1323 (See @ref{GNAT Project Manager}, for details.)
1324 In order to run GPS, you will need to either create a new project
1325 or else open an existing one.
1326
1327 This section will explain how you can use GPS to create a project,
1328 to associate Ada source files with a project, and to build and run
1329 programs.
1330
1331 @enumerate
1332 @item @emph{Creating a project}
1333
1334 Invoke GPS, either from the command line or the platform's IDE.
1335 After it starts, GPS will display a ``Welcome'' screen with three
1336 radio buttons:
1337
1338 @itemize @bullet
1339 @item
1340 @code{Start with default project in directory}
1341
1342 @item
1343 @code{Create new project with wizard}
1344
1345 @item
1346 @code{Open existing project}
1347 @end itemize
1348
1349 @noindent
1350 Select @code{Create new project with wizard} and press @code{OK}.
1351 A new window will appear.  In the text box labeled with
1352 @code{Enter the name of the project to create}, type @file{sample}
1353 as the project name.
1354 In the next box, browse to choose the directory in which you
1355 would like to create the project file.
1356 After selecting an appropriate directory, press @code{Forward}.
1357
1358 A window will appear with the title
1359 @code{Version Control System Configuration}.
1360 Simply press @code{Forward}.
1361
1362 A window will appear with the title
1363 @code{Please select the source directories for this project}.
1364 The directory that you specified for the project file will be selected
1365 by default as the one to use for sources; simply press @code{Forward}.
1366
1367 A window will appear with the title
1368 @code{Please select the build directory for this project}.
1369 The directory that you specified for the project file will be selected
1370 by default for object files and executables;
1371 simply press @code{Forward}.
1372
1373 A window will appear with the title
1374 @code{Please select the main units for this project}.
1375 You will supply this information later, after creating the source file.
1376 Simply press @code{Forward} for now.
1377
1378 A window will appear with the title
1379 @code{Please select the switches to build the project}.
1380 Press @code{Apply}.  This will create a project file named
1381 @file{sample.prj} in the directory that you had specified.
1382
1383 @item @emph{Creating and saving the source file}
1384
1385 After you create the new project, a GPS window will appear, which is
1386 partitioned into two main sections:
1387
1388 @itemize @bullet
1389 @item
1390 A @emph{Workspace area}, initially greyed out, which you will use for
1391 creating and editing source files
1392
1393 @item
1394 Directly below, a @emph{Messages area}, which initially displays a
1395 ``Welcome'' message.
1396 (If the Messages area is not visible, drag its border upward to expand it.)
1397 @end itemize
1398
1399 @noindent
1400 Select @code{File} on the menu bar, and then the @code{New} command.
1401 The Workspace area will become white, and you can now
1402 enter the source program explicitly.
1403 Type the following text
1404
1405 @smallexample @c ada
1406 @group
1407 with Ada.Text_IO; use Ada.Text_IO;
1408 procedure Hello is
1409 begin
1410   Put_Line("Hello from GPS!");
1411 end Hello;
1412 @end group
1413 @end smallexample
1414
1415 @noindent
1416 Select @code{File}, then @code{Save As}, and enter the source file name
1417 @file{hello.adb}.
1418 The file will be saved in the same directory you specified as the
1419 location of the default project file.
1420
1421
1422 @item @emph{Updating the project file}
1423
1424 You need to add the new source file to the project.
1425 To do this, select
1426 the @code{Project} menu and then @code{Edit project properties}.
1427 Click the @code{Main files} tab on the left, and then the
1428 @code{Add} button.
1429 Choose @file{hello.adb} from the list, and press @code{Open}.
1430 The project settings window will reflect this action.
1431 Click @code{OK}.
1432
1433 @item @emph{Building and running the program}
1434
1435 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1436 and select @file{hello.adb}.
1437 The Messages window will display the resulting invocations of @command{gcc},
1438 @command{gnatbind}, and @command{gnatlink}
1439 (reflecting the default switch settings from the
1440 project file that you created) and then a ``successful compilation/build''
1441 message.
1442
1443 To run the program, choose the @code{Build} menu, then @code{Run}, and
1444 select @command{hello}.
1445 An @emph{Arguments Selection} window will appear.
1446 There are no command line arguments, so just click @code{OK}.
1447
1448 The Messages window will now display the program's output (the string
1449 @code{Hello from GPS}), and at the bottom of the GPS window a status
1450 update is displayed (@code{Run: hello}).
1451 Close the GPS window (or select @code{File}, then @code{Exit}) to
1452 terminate this GPS session.
1453 @end enumerate
1454
1455
1456
1457 @node Simple Debugging with GPS
1458 @subsection Simple Debugging with GPS
1459 @noindent
1460 This section illustrates basic debugging techniques (setting breakpoints,
1461 examining/modifying variables, single stepping).
1462
1463 @enumerate
1464 @item @emph{Opening a project}
1465
1466 Start GPS and select @code{Open existing project}; browse to
1467 specify the project file @file{sample.prj} that you had created in the
1468 earlier example.
1469
1470 @item @emph{Creating a source file}
1471
1472 Select @code{File}, then @code{New}, and type in the following program:
1473
1474 @smallexample @c ada
1475 @group
1476 with Ada.Text_IO; use Ada.Text_IO;
1477 procedure Example is
1478    Line : String (1..80);
1479    N    : Natural;
1480 begin
1481    Put_Line("Type a line of text at each prompt; an empty line to exit");
1482    loop
1483       Put(": ");
1484       Get_Line (Line, N);
1485       Put_Line (Line (1..N) );
1486       exit when N=0;
1487    end loop;
1488 end Example;
1489 @end group
1490 @end smallexample
1491
1492 @noindent
1493 Select @code{File}, then @code{Save as}, and enter the file name
1494 @file{example.adb}.
1495
1496 @item @emph{Updating the project file}
1497
1498 Add @code{Example} as a new main unit for the project:
1499 @enumerate a
1500 @item
1501 Select @code{Project}, then @code{Edit Project Properties}.
1502
1503 @item
1504 Select the @code{Main files} tab, click @code{Add}, then
1505 select the file @file{example.adb} from the list, and
1506 click @code{Open}.
1507 You will see the file name appear in the list of main units
1508
1509 @item
1510 Click @code{OK}
1511 @end enumerate
1512
1513 @item @emph{Building/running the executable}
1514
1515 To build the executable
1516 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1517
1518 Run the program to see its effect (in the Messages area).
1519 Each line that you enter is displayed; an empty line will
1520 cause the loop to exit and the program to terminate.
1521
1522 @item @emph{Debugging the program}
1523
1524 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1525 which are required for debugging, are on by default when you create
1526 a new project.
1527 Thus unless you intentionally remove these settings, you will be able
1528 to debug any program that you develop using GPS.
1529
1530 @enumerate a
1531 @item @emph{Initializing}
1532
1533 Select @code{Debug}, then @code{Initialize}, then @file{example}
1534
1535 @item @emph{Setting a breakpoint}
1536
1537 After performing the initialization step, you will observe a small
1538 icon to the right of each line number.
1539 This serves as a toggle for breakpoints; clicking the icon will
1540 set a breakpoint at the corresponding line (the icon will change to
1541 a red circle with an ``x''), and clicking it again
1542 will remove the breakpoint / reset the icon.
1543
1544 For purposes of this example, set a breakpoint at line 10 (the
1545 statement @code{Put_Line@ (Line@ (1..N));}
1546
1547 @item @emph{Starting program execution}
1548
1549 Select @code{Debug}, then @code{Run}.  When the
1550 @code{Program Arguments} window appears, click @code{OK}.
1551 A console window will appear; enter some line of text,
1552 e.g. @code{abcde}, at the prompt.
1553 The program will pause execution when it gets to the
1554 breakpoint, and the corresponding line is highlighted.
1555
1556 @item @emph{Examining a variable}
1557
1558 Move the mouse over one of the occurrences of the variable @code{N}.
1559 You will see the value (5) displayed, in ``tool tip'' fashion.
1560 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1561 You will see information about @code{N} appear in the @code{Debugger Data}
1562 pane, showing the value as 5.
1563
1564
1565 @item @emph{Assigning a new value to a variable}
1566
1567 Right click on the @code{N} in the @code{Debugger Data} pane, and
1568 select @code{Set value of N}.
1569 When the input window appears, enter the value @code{4} and click
1570 @code{OK}.
1571 This value does not automatically appear in the @code{Debugger Data}
1572 pane; to see it, right click again on the @code{N} in the
1573 @code{Debugger Data} pane and select @code{Update value}.
1574 The new value, 4, will appear in red.
1575
1576 @item @emph{Single stepping}
1577
1578 Select @code{Debug}, then @code{Next}.
1579 This will cause the next statement to be executed, in this case the
1580 call of @code{Put_Line} with the string slice.
1581 Notice in the console window that the displayed string is simply
1582 @code{abcd} and not @code{abcde} which you had entered.
1583 This is because the upper bound of the slice is now 4 rather than 5.
1584
1585 @item @emph{Removing a breakpoint}
1586
1587 Toggle the breakpoint icon at line 10.
1588
1589 @item @emph{Resuming execution from a breakpoint}
1590
1591 Select @code{Debug}, then @code{Continue}.
1592 The program will reach the next iteration of the loop, and
1593 wait for input after displaying the prompt.
1594 This time, just hit the @kbd{Enter} key.
1595 The value of @code{N} will be 0, and the program will terminate.
1596 The console window will disappear.
1597 @end enumerate
1598 @end enumerate
1599
1600
1601 @node Introduction to Glide and GVD
1602 @section Introduction to Glide and GVD
1603 @cindex Glide
1604 @cindex GVD
1605 @noindent
1606 This section describes the main features of Glide,
1607 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1608 the GNU Visual Debugger.
1609 These tools may be present in addition to, or in place of, GPS on some
1610 platforms.
1611 Additional information on Glide and GVD may be found
1612 in the on-line help for these tools.
1613
1614 @menu
1615 * Building a New Program with Glide::
1616 * Simple Debugging with GVD::
1617 * Other Glide Features::
1618 @end menu
1619
1620 @node Building a New Program with Glide
1621 @subsection Building a New Program with Glide
1622 @noindent
1623 The simplest way to invoke Glide is to enter @command{glide}
1624 at the command prompt.  It will generally be useful to issue this
1625 as a background command, thus allowing you to continue using
1626 your command window for other purposes while Glide is running:
1627
1628 @smallexample
1629 $ glide&
1630 @end smallexample
1631
1632 @noindent
1633 Glide will start up with an initial screen displaying the top-level menu items
1634 as well as some other information.  The menu selections are as follows
1635 @itemize @bullet
1636 @item @code{Buffers}
1637 @item @code{Files}
1638 @item @code{Tools}
1639 @item @code{Edit}
1640 @item @code{Search}
1641 @item @code{Mule}
1642 @item @code{Glide}
1643 @item @code{Help}
1644 @end itemize
1645
1646 @noindent
1647 For this introductory example, you will need to create a new Ada source file.
1648 First, select the @code{Files} menu.  This will pop open a menu with around
1649 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1650 Depending on the platform, you may see a pop-up window where you can browse
1651 to an appropriate directory and then enter the file name, or else simply
1652 see a line at the bottom of the Glide window where you can likewise enter
1653 the file name.  Note that in Glide, when you attempt to open a non-existent
1654 file, the effect is to create a file with that name.  For this example enter
1655 @file{hello.adb} as the name of the file.
1656
1657 A new buffer will now appear, occupying the entire Glide window,
1658 with the file name at the top.  The menu selections are slightly different
1659 from the ones you saw on the opening screen; there is an @code{Entities} item,
1660 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1661 the file extension to identify the source language, so @file{adb} indicates
1662 an Ada source file.
1663
1664 You will enter some of the source program lines explicitly,
1665 and use the syntax-oriented template mechanism to enter other lines.
1666 First, type the following text:
1667 @smallexample
1668 with Ada.Text_IO; use Ada.Text_IO;
1669 procedure Hello is
1670 begin
1671 @end smallexample
1672
1673 @noindent
1674 Observe that Glide uses different colors to distinguish reserved words from
1675 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1676 automatically indented in anticipation of declarations.  When you enter
1677 @code{begin}, Glide recognizes that there are no declarations and thus places
1678 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1679 indented, where the statement(s) will be placed.
1680
1681 The main part of the program will be a @code{for} loop.  Instead of entering
1682 the text explicitly, however, use a statement template.  Select the @code{Ada}
1683 item on the top menu bar, move the mouse to the @code{Statements} item,
1684 and you will see a large selection of alternatives.  Choose @code{for loop}.
1685 You will be prompted (at the bottom of the buffer) for a loop name;
1686 simply press the @key{Enter} key since a loop name is not needed.
1687 You should see the beginning of a @code{for} loop appear in the source
1688 program window.  You will now be prompted for the name of the loop variable;
1689 enter a line with the identifier @code{ind} (lower case).  Note that,
1690 by default, Glide capitalizes the name (you can override such behavior
1691 if you wish, although this is outside the scope of this introduction).
1692 Next, Glide prompts you for the loop range; enter a line containing
1693 @code{1..5} and you will see this also appear in the source program,
1694 together with the remaining elements of the @code{for} loop syntax.
1695
1696 Next enter the statement (with an intentional error, a missing semicolon)
1697 that will form the body of the loop:
1698 @smallexample
1699 Put_Line("Hello, World" & Integer'Image(I))
1700 @end smallexample
1701
1702 @noindent
1703 Finally, type @code{end Hello;} as the last line in the program.
1704 Now save the file: choose the @code{File} menu item, and then the
1705 @code{Save buffer} selection.  You will see a message at the bottom
1706 of the buffer confirming that the file has been saved.
1707
1708 You are now ready to attempt to build the program.  Select the @code{Ada}
1709 item from the top menu bar.  Although we could choose simply to compile
1710 the file, we will instead attempt to do a build (which invokes
1711 @command{gnatmake}) since, if the compile is successful, we want to build
1712 an executable.  Thus select @code{Ada build}.  This will fail because of the
1713 compilation error, and you will notice that the Glide window has been split:
1714 the top window contains the source file, and the bottom window contains the
1715 output from the GNAT tools. Glide allows you to navigate from a compilation
1716 error to the source file position corresponding to the error: click the
1717 middle mouse button (or simultaneously press the left and right buttons,
1718 on a two-button mouse) on the diagnostic line in the tool window.  The
1719 focus will shift to the source window, and the cursor will be positioned
1720 on the character at which the error was detected.
1721
1722 Correct the error: type in a semicolon to terminate the statement.
1723 Although you can again save the file explicitly, you can also simply invoke
1724 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1725 This time the build will succeed; the tool output window shows you the
1726 options that are supplied by default.  The GNAT tools' output (e.g.
1727 object and ALI files, executable) will go in the directory from which
1728 Glide was launched.
1729
1730 To execute the program, choose @code{Ada} and then @code{Run}.
1731 You should see the program's output displayed in the bottom window:
1732
1733 @smallexample
1734 Hello, world 1
1735 Hello, world 2
1736 Hello, world 3
1737 Hello, world 4
1738 Hello, world 5
1739 @end smallexample
1740
1741 @node Simple Debugging with GVD
1742 @subsection Simple Debugging with GVD
1743
1744 @noindent
1745 This section describes how to set breakpoints, examine/modify variables,
1746 and step through execution.
1747
1748 In order to enable debugging, you need to pass the @option{-g} switch
1749 to both the compiler and to @command{gnatlink}.  If you are using
1750 the command line, passing @option{-g} to @command{gnatmake} will have
1751 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1752 by issuing the command:
1753
1754 @smallexample
1755 $ gvd hello
1756 @end smallexample
1757
1758 @noindent
1759 If you are using Glide, then @option{-g} is passed to the relevant tools
1760 by default when you do a build.  Start the debugger by selecting the
1761 @code{Ada} menu item, and then @code{Debug}.
1762
1763 GVD comes up in a multi-part window.  One pane shows the names of files
1764 comprising your executable; another pane shows the source code of the current
1765 unit (initially your main subprogram), another pane shows the debugger output
1766 and user interactions, and the fourth pane (the data canvas at the top
1767 of the window) displays data objects that you have selected.
1768
1769 To the left of the source file pane, you will notice green dots adjacent
1770 to some lines.  These are lines for which object code exists and where
1771 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1772 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1773 in a red circle.  Clicking the circle toggles the breakpoint off,
1774 and the red circle is replaced by the green dot.
1775
1776 For this example, set a breakpoint at the statement where @code{Put_Line}
1777 is invoked.
1778
1779 Start program execution by selecting the @code{Run} button on the top menu bar.
1780 (The @code{Start} button will also start your program, but it will
1781 cause program execution to break at the entry to your main subprogram.)
1782 Evidence of reaching the breakpoint will appear: the source file line will be
1783 highlighted, and the debugger interactions pane will display
1784 a relevant message.
1785
1786 You can examine the values of variables in several ways.  Move the mouse
1787 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1788 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1789 and select @code{Display Ind}; a box showing the variable's name and value
1790 will appear in the data canvas.
1791
1792 Although a loop index is a constant with respect to Ada semantics,
1793 you can change its value in the debugger.  Right-click in the box
1794 for @code{Ind}, and select the @code{Set Value of Ind} item.
1795 Enter @code{2} as the new value, and press @command{OK}.
1796 The box for @code{Ind} shows the update.
1797
1798 Press the @code{Step} button on the top menu bar; this will step through
1799 one line of program text (the invocation of @code{Put_Line}), and you can
1800 observe the effect of having modified @code{Ind} since the value displayed
1801 is @code{2}.
1802
1803 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1804 button.  You will see the remaining output lines displayed in the debugger
1805 interaction window, along with a message confirming normal program
1806 termination.
1807
1808 @node Other Glide Features
1809 @subsection Other Glide Features
1810
1811 @noindent
1812 You may have observed that some of the menu selections contain abbreviations;
1813 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1814 These are @emph{shortcut keys} that you can use instead of selecting
1815 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1816 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1817 of selecting @code{Files} and then @code{Open file...}.
1818
1819 To abort a Glide command, type @key{Ctrl-g}.
1820
1821 If you want Glide to start with an existing source file, you can either
1822 launch Glide as above and then open the file via @code{Files} @result{}
1823 @code{Open file...}, or else simply pass the name of the source file
1824 on the command line:
1825
1826 @smallexample
1827 $ glide hello.adb&
1828 @end smallexample
1829
1830 @noindent
1831 While you are using Glide, a number of @emph{buffers} exist.
1832 You create some explicitly; e.g., when you open/create a file.
1833 Others arise as an effect of the commands that you issue; e.g., the buffer
1834 containing the output of the tools invoked during a build.  If a buffer
1835 is hidden, you can bring it into a visible window by first opening
1836 the @code{Buffers} menu and then selecting the desired entry.
1837
1838 If a buffer occupies only part of the Glide screen and you want to expand it
1839 to fill the entire screen, then click in the buffer and then select
1840 @code{Files} @result{} @code{One Window}.
1841
1842 If a window is occupied by one buffer and you want to split the window
1843 to bring up a second buffer, perform the following steps:
1844 @itemize @bullet
1845 @item Select @code{Files} @result{} @code{Split Window};
1846 this will produce two windows each of which holds the original buffer
1847 (these are not copies, but rather different views of the same buffer contents)
1848
1849 @item With the focus in one of the windows,
1850 select the desired buffer from the @code{Buffers} menu
1851 @end itemize
1852
1853 @noindent
1854 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1855 @end ifclear
1856
1857 @node The GNAT Compilation Model
1858 @chapter The GNAT Compilation Model
1859 @cindex GNAT compilation model
1860 @cindex Compilation model
1861
1862 @menu
1863 * Source Representation::
1864 * Foreign Language Representation::
1865 * File Naming Rules::
1866 * Using Other File Names::
1867 * Alternative File Naming Schemes::
1868 * Generating Object Files::
1869 * Source Dependencies::
1870 * The Ada Library Information Files::
1871 * Binding an Ada Program::
1872 * Mixed Language Programming::
1873 * Building Mixed Ada & C++ Programs::
1874 * Comparison between GNAT and C/C++ Compilation Models::
1875 * Comparison between GNAT and Conventional Ada Library Models::
1876 @ifset vms
1877 * Placement of temporary files::
1878 @end ifset
1879 @end menu
1880
1881 @noindent
1882 This chapter describes the compilation model used by GNAT. Although
1883 similar to that used by other languages, such as C and C++, this model
1884 is substantially different from the traditional Ada compilation models,
1885 which are based on a library. The model is initially described without
1886 reference to the library-based model. If you have not previously used an
1887 Ada compiler, you need only read the first part of this chapter. The
1888 last section describes and discusses the differences between the GNAT
1889 model and the traditional Ada compiler models. If you have used other
1890 Ada compilers, this section will help you to understand those
1891 differences, and the advantages of the GNAT model.
1892
1893 @node Source Representation
1894 @section Source Representation
1895 @cindex Latin-1
1896
1897 @noindent
1898 Ada source programs are represented in standard text files, using
1899 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1900 7-bit ASCII set, plus additional characters used for
1901 representing foreign languages (@pxref{Foreign Language Representation}
1902 for support of non-USA character sets). The format effector characters
1903 are represented using their standard ASCII encodings, as follows:
1904
1905 @table @code
1906 @item VT
1907 @findex VT
1908 Vertical tab, @code{16#0B#}
1909
1910 @item HT
1911 @findex HT
1912 Horizontal tab, @code{16#09#}
1913
1914 @item CR
1915 @findex CR
1916 Carriage return, @code{16#0D#}
1917
1918 @item LF
1919 @findex LF
1920 Line feed, @code{16#0A#}
1921
1922 @item FF
1923 @findex FF
1924 Form feed, @code{16#0C#}
1925 @end table
1926
1927 @noindent
1928 Source files are in standard text file format. In addition, GNAT will
1929 recognize a wide variety of stream formats, in which the end of physical
1930 physical lines is marked by any of the following sequences:
1931 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1932 in accommodating files that are imported from other operating systems.
1933
1934 @cindex End of source file
1935 @cindex Source file, end
1936 @findex SUB
1937 The end of a source file is normally represented by the physical end of
1938 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1939 recognized as signalling the end of the source file. Again, this is
1940 provided for compatibility with other operating systems where this
1941 code is used to represent the end of file.
1942
1943 Each file contains a single Ada compilation unit, including any pragmas
1944 associated with the unit. For example, this means you must place a
1945 package declaration (a package @dfn{spec}) and the corresponding body in
1946 separate files. An Ada @dfn{compilation} (which is a sequence of
1947 compilation units) is represented using a sequence of files. Similarly,
1948 you will place each subunit or child unit in a separate file.
1949
1950 @node Foreign Language Representation
1951 @section Foreign Language Representation
1952
1953 @noindent
1954 GNAT supports the standard character sets defined in Ada 95 as well as
1955 several other non-standard character sets for use in localized versions
1956 of the compiler (@pxref{Character Set Control}).
1957 @menu
1958 * Latin-1::
1959 * Other 8-Bit Codes::
1960 * Wide Character Encodings::
1961 @end menu
1962
1963 @node Latin-1
1964 @subsection Latin-1
1965 @cindex Latin-1
1966
1967 @noindent
1968 The basic character set is Latin-1. This character set is defined by ISO
1969 standard 8859, part 1. The lower half (character codes @code{16#00#}
1970 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1971 is used to represent additional characters. These include extended letters
1972 used by European languages, such as French accents, the vowels with umlauts
1973 used in German, and the extra letter A-ring used in Swedish.
1974
1975 @findex Ada.Characters.Latin_1
1976 For a complete list of Latin-1 codes and their encodings, see the source
1977 file of library unit @code{Ada.Characters.Latin_1} in file
1978 @file{a-chlat1.ads}.
1979 You may use any of these extended characters freely in character or
1980 string literals. In addition, the extended characters that represent
1981 letters can be used in identifiers.
1982
1983 @node Other 8-Bit Codes
1984 @subsection Other 8-Bit Codes
1985
1986 @noindent
1987 GNAT also supports several other 8-bit coding schemes:
1988
1989 @table @asis
1990 @item ISO 8859-2 (Latin-2)
1991 @cindex Latin-2
1992 @cindex ISO 8859-2
1993 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1994 equivalence.
1995
1996 @item ISO 8859-3 (Latin-3)
1997 @cindex Latin-3
1998 @cindex ISO 8859-3
1999 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2000 equivalence.
2001
2002 @item ISO 8859-4 (Latin-4)
2003 @cindex Latin-4
2004 @cindex ISO 8859-4
2005 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2006 equivalence.
2007
2008 @item ISO 8859-5 (Cyrillic)
2009 @cindex ISO 8859-5
2010 @cindex Cyrillic
2011 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2012 lowercase equivalence.
2013
2014 @item ISO 8859-15 (Latin-9)
2015 @cindex ISO 8859-15
2016 @cindex Latin-9
2017 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2018 lowercase equivalence
2019
2020 @item IBM PC (code page 437)
2021 @cindex code page 437
2022 This code page is the normal default for PCs in the U.S. It corresponds
2023 to the original IBM PC character set. This set has some, but not all, of
2024 the extended Latin-1 letters, but these letters do not have the same
2025 encoding as Latin-1. In this mode, these letters are allowed in
2026 identifiers with uppercase and lowercase equivalence.
2027
2028 @item IBM PC (code page 850)
2029 @cindex code page 850
2030 This code page is a modification of 437 extended to include all the
2031 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2032 mode, all these letters are allowed in identifiers with uppercase and
2033 lowercase equivalence.
2034
2035 @item Full Upper 8-bit
2036 Any character in the range 80-FF allowed in identifiers, and all are
2037 considered distinct. In other words, there are no uppercase and lowercase
2038 equivalences in this range. This is useful in conjunction with
2039 certain encoding schemes used for some foreign character sets (e.g.
2040 the typical method of representing Chinese characters on the PC).
2041
2042 @item No Upper-Half
2043 No upper-half characters in the range 80-FF are allowed in identifiers.
2044 This gives Ada 83 compatibility for identifier names.
2045 @end table
2046
2047 @noindent
2048 For precise data on the encodings permitted, and the uppercase and lowercase
2049 equivalences that are recognized, see the file @file{csets.adb} in
2050 the GNAT compiler sources. You will need to obtain a full source release
2051 of GNAT to obtain this file.
2052
2053 @node Wide Character Encodings
2054 @subsection Wide Character Encodings
2055
2056 @noindent
2057 GNAT allows wide character codes to appear in character and string
2058 literals, and also optionally in identifiers, by means of the following
2059 possible encoding schemes:
2060
2061 @table @asis
2062
2063 @item Hex Coding
2064 In this encoding, a wide character is represented by the following five
2065 character sequence:
2066
2067 @smallexample
2068 ESC a b c d
2069 @end smallexample
2070
2071 @noindent
2072 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2073 characters (using uppercase letters) of the wide character code. For
2074 example, ESC A345 is used to represent the wide character with code
2075 @code{16#A345#}.
2076 This scheme is compatible with use of the full Wide_Character set.
2077
2078 @item Upper-Half Coding
2079 @cindex Upper-Half Coding
2080 The wide character with encoding @code{16#abcd#} where the upper bit is on
2081 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2082 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2083 character, but is not required to be in the upper half. This method can
2084 be also used for shift-JIS or EUC, where the internal coding matches the
2085 external coding.
2086
2087 @item Shift JIS Coding
2088 @cindex Shift JIS Coding
2089 A wide character is represented by a two-character sequence,
2090 @code{16#ab#} and
2091 @code{16#cd#}, with the restrictions described for upper-half encoding as
2092 described above. The internal character code is the corresponding JIS
2093 character according to the standard algorithm for Shift-JIS
2094 conversion. Only characters defined in the JIS code set table can be
2095 used with this encoding method.
2096
2097 @item EUC Coding
2098 @cindex EUC Coding
2099 A wide character is represented by a two-character sequence
2100 @code{16#ab#} and
2101 @code{16#cd#}, with both characters being in the upper half. The internal
2102 character code is the corresponding JIS character according to the EUC
2103 encoding algorithm. Only characters defined in the JIS code set table
2104 can be used with this encoding method.
2105
2106 @item UTF-8 Coding
2107 A wide character is represented using
2108 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2109 10646-1/Am.2. Depending on the character value, the representation
2110 is a one, two, or three byte sequence:
2111 @smallexample
2112 @iftex
2113 @leftskip=.7cm
2114 @end iftex
2115 16#0000#-16#007f#: 2#0xxxxxxx#
2116 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2117 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2118
2119 @end smallexample
2120
2121 @noindent
2122 where the xxx bits correspond to the left-padded bits of the
2123 16-bit character value. Note that all lower half ASCII characters
2124 are represented as ASCII bytes and all upper half characters and
2125 other wide characters are represented as sequences of upper-half
2126 (The full UTF-8 scheme allows for encoding 31-bit characters as
2127 6-byte sequences, but in this implementation, all UTF-8 sequences
2128 of four or more bytes length will be treated as illegal).
2129 @item Brackets Coding
2130 In this encoding, a wide character is represented by the following eight
2131 character sequence:
2132
2133 @smallexample
2134 [ " a b c d " ]
2135 @end smallexample
2136
2137 @noindent
2138 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2139 characters (using uppercase letters) of the wide character code. For
2140 example, [``A345''] is used to represent the wide character with code
2141 @code{16#A345#}. It is also possible (though not required) to use the
2142 Brackets coding for upper half characters. For example, the code
2143 @code{16#A3#} can be represented as @code{[``A3'']}.
2144
2145 This scheme is compatible with use of the full Wide_Character set,
2146 and is also the method used for wide character encoding in the standard
2147 ACVC (Ada Compiler Validation Capability) test suite distributions.
2148
2149 @end table
2150
2151 @noindent
2152 Note: Some of these coding schemes do not permit the full use of the
2153 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2154 use of the upper half of the Latin-1 set.
2155
2156 @node File Naming Rules
2157 @section File Naming Rules
2158
2159 @noindent
2160 The default file name is determined by the name of the unit that the
2161 file contains. The name is formed by taking the full expanded name of
2162 the unit and replacing the separating dots with hyphens and using
2163 ^lowercase^uppercase^ for all letters.
2164
2165 An exception arises if the file name generated by the above rules starts
2166 with one of the characters
2167 @ifset vms
2168 A,G,I, or S,
2169 @end ifset
2170 @ifclear vms
2171 a,g,i, or s,
2172 @end ifclear
2173 and the second character is a
2174 minus. In this case, the character ^tilde^dollar sign^ is used in place
2175 of the minus. The reason for this special rule is to avoid clashes with
2176 the standard names for child units of the packages System, Ada,
2177 Interfaces, and GNAT, which use the prefixes
2178 @ifset vms
2179 S- A- I- and G-
2180 @end ifset
2181 @ifclear vms
2182 s- a- i- and g-
2183 @end ifclear
2184 respectively.
2185
2186 The file extension is @file{.ads} for a spec and
2187 @file{.adb} for a body. The following list shows some
2188 examples of these rules.
2189
2190 @table @file
2191 @item main.ads
2192 Main (spec)
2193 @item main.adb
2194 Main (body)
2195 @item arith_functions.ads
2196 Arith_Functions (package spec)
2197 @item arith_functions.adb
2198 Arith_Functions (package body)
2199 @item func-spec.ads
2200 Func.Spec (child package spec)
2201 @item func-spec.adb
2202 Func.Spec (child package body)
2203 @item main-sub.adb
2204 Sub (subunit of Main)
2205 @item ^a~bad.adb^A$BAD.ADB^
2206 A.Bad (child package body)
2207 @end table
2208
2209 @noindent
2210 Following these rules can result in excessively long
2211 file names if corresponding
2212 unit names are long (for example, if child units or subunits are
2213 heavily nested). An option is available to shorten such long file names
2214 (called file name ``krunching''). This may be particularly useful when
2215 programs being developed with GNAT are to be used on operating systems
2216 with limited file name lengths. @xref{Using gnatkr}.
2217
2218 Of course, no file shortening algorithm can guarantee uniqueness over
2219 all possible unit names; if file name krunching is used, it is your
2220 responsibility to ensure no name clashes occur. Alternatively you
2221 can specify the exact file names that you want used, as described
2222 in the next section. Finally, if your Ada programs are migrating from a
2223 compiler with a different naming convention, you can use the gnatchop
2224 utility to produce source files that follow the GNAT naming conventions.
2225 (For details @pxref{Renaming Files Using gnatchop}.)
2226
2227 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2228 systems, case is not significant. So for example on @code{Windows XP}
2229 if the canonical name is @code{main-sub.adb}, you can use the file name
2230 @code{Main-Sub.adb} instead. However, case is significant for other
2231 operating systems, so for example, if you want to use other than
2232 canonically cased file names on a Unix system, you need to follow
2233 the procedures described in the next section.
2234
2235 @node Using Other File Names
2236 @section Using Other File Names
2237 @cindex File names
2238
2239 @noindent
2240 In the previous section, we have described the default rules used by
2241 GNAT to determine the file name in which a given unit resides. It is
2242 often convenient to follow these default rules, and if you follow them,
2243 the compiler knows without being explicitly told where to find all
2244 the files it needs.
2245
2246 However, in some cases, particularly when a program is imported from
2247 another Ada compiler environment, it may be more convenient for the
2248 programmer to specify which file names contain which units. GNAT allows
2249 arbitrary file names to be used by means of the Source_File_Name pragma.
2250 The form of this pragma is as shown in the following examples:
2251 @cindex Source_File_Name pragma
2252
2253 @smallexample @c ada
2254 @cartouche
2255 pragma Source_File_Name (My_Utilities.Stacks,
2256   Spec_File_Name => "myutilst_a.ada");
2257 pragma Source_File_name (My_Utilities.Stacks,
2258   Body_File_Name => "myutilst.ada");
2259 @end cartouche
2260 @end smallexample
2261
2262 @noindent
2263 As shown in this example, the first argument for the pragma is the unit
2264 name (in this example a child unit). The second argument has the form
2265 of a named association. The identifier
2266 indicates whether the file name is for a spec or a body;
2267 the file name itself is given by a string literal.
2268
2269 The source file name pragma is a configuration pragma, which means that
2270 normally it will be placed in the @file{gnat.adc}
2271 file used to hold configuration
2272 pragmas that apply to a complete compilation environment.
2273 For more details on how the @file{gnat.adc} file is created and used
2274 @pxref{Handling of Configuration Pragmas}
2275 @cindex @file{gnat.adc}
2276
2277 @ifclear vms
2278 GNAT allows completely arbitrary file names to be specified using the
2279 source file name pragma. However, if the file name specified has an
2280 extension other than @file{.ads} or @file{.adb} it is necessary to use
2281 a special syntax when compiling the file. The name in this case must be
2282 preceded by the special sequence @code{-x} followed by a space and the name
2283 of the language, here @code{ada}, as in:
2284
2285 @smallexample
2286 $ gcc -c -x ada peculiar_file_name.sim
2287 @end smallexample
2288 @end ifclear
2289
2290 @noindent
2291 @code{gnatmake} handles non-standard file names in the usual manner (the
2292 non-standard file name for the main program is simply used as the
2293 argument to gnatmake). Note that if the extension is also non-standard,
2294 then it must be included in the gnatmake command, it may not be omitted.
2295
2296 @node Alternative File Naming Schemes
2297 @section Alternative File Naming Schemes
2298 @cindex File naming schemes, alternative
2299 @cindex File names
2300
2301 In the previous section, we described the use of the @code{Source_File_Name}
2302 pragma to allow arbitrary names to be assigned to individual source files.
2303 However, this approach requires one pragma for each file, and especially in
2304 large systems can result in very long @file{gnat.adc} files, and also create
2305 a maintenance problem.
2306
2307 GNAT also provides a facility for specifying systematic file naming schemes
2308 other than the standard default naming scheme previously described. An
2309 alternative scheme for naming is specified by the use of
2310 @code{Source_File_Name} pragmas having the following format:
2311 @cindex Source_File_Name pragma
2312
2313 @smallexample @c ada
2314 pragma Source_File_Name (
2315    Spec_File_Name  => FILE_NAME_PATTERN
2316  [,Casing          => CASING_SPEC]
2317  [,Dot_Replacement => STRING_LITERAL]);
2318
2319 pragma Source_File_Name (
2320    Body_File_Name  => FILE_NAME_PATTERN
2321  [,Casing          => CASING_SPEC]
2322  [,Dot_Replacement => STRING_LITERAL]);
2323
2324 pragma Source_File_Name (
2325    Subunit_File_Name  => FILE_NAME_PATTERN
2326  [,Casing             => CASING_SPEC]
2327  [,Dot_Replacement    => STRING_LITERAL]);
2328
2329 FILE_NAME_PATTERN ::= STRING_LITERAL
2330 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2331 @end smallexample
2332
2333 @noindent
2334 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2335 It contains a single asterisk character, and the unit name is substituted
2336 systematically for this asterisk. The optional parameter
2337 @code{Casing} indicates
2338 whether the unit name is to be all upper-case letters, all lower-case letters,
2339 or mixed-case. If no
2340 @code{Casing} parameter is used, then the default is all
2341 ^lower-case^upper-case^.
2342
2343 The optional @code{Dot_Replacement} string is used to replace any periods
2344 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2345 argument is used then separating dots appear unchanged in the resulting
2346 file name.
2347 Although the above syntax indicates that the
2348 @code{Casing} argument must appear
2349 before the @code{Dot_Replacement} argument, but it
2350 is also permissible to write these arguments in the opposite order.
2351
2352 As indicated, it is possible to specify different naming schemes for
2353 bodies, specs, and subunits. Quite often the rule for subunits is the
2354 same as the rule for bodies, in which case, there is no need to give
2355 a separate @code{Subunit_File_Name} rule, and in this case the
2356 @code{Body_File_name} rule is used for subunits as well.
2357
2358 The separate rule for subunits can also be used to implement the rather
2359 unusual case of a compilation environment (e.g. a single directory) which
2360 contains a subunit and a child unit with the same unit name. Although
2361 both units cannot appear in the same partition, the Ada Reference Manual
2362 allows (but does not require) the possibility of the two units coexisting
2363 in the same environment.
2364
2365 The file name translation works in the following steps:
2366
2367 @itemize @bullet
2368
2369 @item
2370 If there is a specific @code{Source_File_Name} pragma for the given unit,
2371 then this is always used, and any general pattern rules are ignored.
2372
2373 @item
2374 If there is a pattern type @code{Source_File_Name} pragma that applies to
2375 the unit, then the resulting file name will be used if the file exists. If
2376 more than one pattern matches, the latest one will be tried first, and the
2377 first attempt resulting in a reference to a file that exists will be used.
2378
2379 @item
2380 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2381 for which the corresponding file exists, then the standard GNAT default
2382 naming rules are used.
2383
2384 @end itemize
2385
2386 @noindent
2387 As an example of the use of this mechanism, consider a commonly used scheme
2388 in which file names are all lower case, with separating periods copied
2389 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2390 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2391 two pragmas appear:
2392
2393 @smallexample @c ada
2394 pragma Source_File_Name
2395   (Spec_File_Name => "*.1.ada");
2396 pragma Source_File_Name
2397   (Body_File_Name => "*.2.ada");
2398 @end smallexample
2399
2400 @noindent
2401 The default GNAT scheme is actually implemented by providing the following
2402 default pragmas internally:
2403
2404 @smallexample @c ada
2405 pragma Source_File_Name
2406   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2407 pragma Source_File_Name
2408   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2409 @end smallexample
2410
2411 @noindent
2412 Our final example implements a scheme typically used with one of the
2413 Ada 83 compilers, where the separator character for subunits was ``__''
2414 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2415 by adding @file{.ADA}, and subunits by
2416 adding @file{.SEP}. All file names were
2417 upper case. Child units were not present of course since this was an
2418 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2419 the same double underscore separator for child units.
2420
2421 @smallexample @c ada
2422 pragma Source_File_Name
2423   (Spec_File_Name => "*_.ADA",
2424    Dot_Replacement => "__",
2425    Casing = Uppercase);
2426 pragma Source_File_Name
2427   (Body_File_Name => "*.ADA",
2428    Dot_Replacement => "__",
2429    Casing = Uppercase);
2430 pragma Source_File_Name
2431   (Subunit_File_Name => "*.SEP",
2432    Dot_Replacement => "__",
2433    Casing = Uppercase);
2434 @end smallexample
2435
2436 @node Generating Object Files
2437 @section Generating Object Files
2438
2439 @noindent
2440 An Ada program consists of a set of source files, and the first step in
2441 compiling the program is to generate the corresponding object files.
2442 These are generated by compiling a subset of these source files.
2443 The files you need to compile are the following:
2444
2445 @itemize @bullet
2446 @item
2447 If a package spec has no body, compile the package spec to produce the
2448 object file for the package.
2449
2450 @item
2451 If a package has both a spec and a body, compile the body to produce the
2452 object file for the package. The source file for the package spec need
2453 not be compiled in this case because there is only one object file, which
2454 contains the code for both the spec and body of the package.
2455
2456 @item
2457 For a subprogram, compile the subprogram body to produce the object file
2458 for the subprogram. The spec, if one is present, is as usual in a
2459 separate file, and need not be compiled.
2460
2461 @item
2462 @cindex Subunits
2463 In the case of subunits, only compile the parent unit. A single object
2464 file is generated for the entire subunit tree, which includes all the
2465 subunits.
2466
2467 @item
2468 Compile child units independently of their parent units
2469 (though, of course, the spec of all the ancestor unit must be present in order
2470 to compile a child unit).
2471
2472 @item
2473 @cindex Generics
2474 Compile generic units in the same manner as any other units. The object
2475 files in this case are small dummy files that contain at most the
2476 flag used for elaboration checking. This is because GNAT always handles generic
2477 instantiation by means of macro expansion. However, it is still necessary to
2478 compile generic units, for dependency checking and elaboration purposes.
2479 @end itemize
2480
2481 @noindent
2482 The preceding rules describe the set of files that must be compiled to
2483 generate the object files for a program. Each object file has the same
2484 name as the corresponding source file, except that the extension is
2485 @file{.o} as usual.
2486
2487 You may wish to compile other files for the purpose of checking their
2488 syntactic and semantic correctness. For example, in the case where a
2489 package has a separate spec and body, you would not normally compile the
2490 spec. However, it is convenient in practice to compile the spec to make
2491 sure it is error-free before compiling clients of this spec, because such
2492 compilations will fail if there is an error in the spec.
2493
2494 GNAT provides an option for compiling such files purely for the
2495 purposes of checking correctness; such compilations are not required as
2496 part of the process of building a program. To compile a file in this
2497 checking mode, use the @option{-gnatc} switch.
2498
2499 @node Source Dependencies
2500 @section Source Dependencies
2501
2502 @noindent
2503 A given object file clearly depends on the source file which is compiled
2504 to produce it. Here we are using @dfn{depends} in the sense of a typical
2505 @code{make} utility; in other words, an object file depends on a source
2506 file if changes to the source file require the object file to be
2507 recompiled.
2508 In addition to this basic dependency, a given object may depend on
2509 additional source files as follows:
2510
2511 @itemize @bullet
2512 @item
2513 If a file being compiled @code{with}'s a unit @var{X}, the object file
2514 depends on the file containing the spec of unit @var{X}. This includes
2515 files that are @code{with}'ed implicitly either because they are parents
2516 of @code{with}'ed child units or they are run-time units required by the
2517 language constructs used in a particular unit.
2518
2519 @item
2520 If a file being compiled instantiates a library level generic unit, the
2521 object file depends on both the spec and body files for this generic
2522 unit.
2523
2524 @item
2525 If a file being compiled instantiates a generic unit defined within a
2526 package, the object file depends on the body file for the package as
2527 well as the spec file.
2528
2529 @item
2530 @findex Inline
2531 @cindex @option{-gnatn} switch
2532 If a file being compiled contains a call to a subprogram for which
2533 pragma @code{Inline} applies and inlining is activated with the
2534 @option{-gnatn} switch, the object file depends on the file containing the
2535 body of this subprogram as well as on the file containing the spec. Note
2536 that for inlining to actually occur as a result of the use of this switch,
2537 it is necessary to compile in optimizing mode.
2538
2539 @cindex @option{-gnatN} switch
2540 The use of @option{-gnatN} activates a more extensive inlining optimization
2541 that is performed by the front end of the compiler. This inlining does
2542 not require that the code generation be optimized. Like @option{-gnatn},
2543 the use of this switch generates additional dependencies.
2544 Note that
2545 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2546 to specify both options.
2547
2548 @item
2549 If an object file O  depends on the proper body of a subunit through inlining
2550 or instantiation, it depends on the parent unit of the subunit. This means that
2551 any modification of the parent unit or one of its subunits affects the
2552 compilation of O.
2553
2554 @item
2555 The object file for a parent unit depends on all its subunit body files.
2556
2557 @item
2558 The previous two rules meant that for purposes of computing dependencies and
2559 recompilation, a body and all its subunits are treated as an indivisible whole.
2560
2561 @noindent
2562 These rules are applied transitively: if unit @code{A} @code{with}'s
2563 unit @code{B}, whose elaboration calls an inlined procedure in package
2564 @code{C}, the object file for unit @code{A} will depend on the body of
2565 @code{C}, in file @file{c.adb}.
2566
2567 The set of dependent files described by these rules includes all the
2568 files on which the unit is semantically dependent, as described in the
2569 Ada 95 Language Reference Manual. However, it is a superset of what the
2570 ARM describes, because it includes generic, inline, and subunit dependencies.
2571
2572 An object file must be recreated by recompiling the corresponding source
2573 file if any of the source files on which it depends are modified. For
2574 example, if the @code{make} utility is used to control compilation,
2575 the rule for an Ada object file must mention all the source files on
2576 which the object file depends, according to the above definition.
2577 The determination of the necessary
2578 recompilations is done automatically when one uses @code{gnatmake}.
2579 @end itemize
2580
2581 @node The Ada Library Information Files
2582 @section The Ada Library Information Files
2583 @cindex Ada Library Information files
2584 @cindex @file{ALI} files
2585
2586 @noindent
2587 Each compilation actually generates two output files. The first of these
2588 is the normal object file that has a @file{.o} extension. The second is a
2589 text file containing full dependency information. It has the same
2590 name as the source file, but an @file{.ali} extension.
2591 This file is known as the Ada Library Information (@file{ALI}) file.
2592 The following information is contained in the @file{ALI} file.
2593
2594 @itemize @bullet
2595 @item
2596 Version information (indicates which version of GNAT was used to compile
2597 the unit(s) in question)
2598
2599 @item
2600 Main program information (including priority and time slice settings,
2601 as well as the wide character encoding used during compilation).
2602
2603 @item
2604 List of arguments used in the @code{gcc} command for the compilation
2605
2606 @item
2607 Attributes of the unit, including configuration pragmas used, an indication
2608 of whether the compilation was successful, exception model used etc.
2609
2610 @item
2611 A list of relevant restrictions applying to the unit (used for consistency)
2612 checking.
2613
2614 @item
2615 Categorization information (e.g. use of pragma @code{Pure}).
2616
2617 @item
2618 Information on all @code{with}'ed units, including presence of
2619 @code{Elaborate} or @code{Elaborate_All} pragmas.
2620
2621 @item
2622 Information from any @code{Linker_Options} pragmas used in the unit
2623
2624 @item
2625 Information on the use of @code{Body_Version} or @code{Version}
2626 attributes in the unit.
2627
2628 @item
2629 Dependency information. This is a list of files, together with
2630 time stamp and checksum information. These are files on which
2631 the unit depends in the sense that recompilation is required
2632 if any of these units are modified.
2633
2634 @item
2635 Cross-reference data. Contains information on all entities referenced
2636 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2637 provide cross-reference information.
2638
2639 @end itemize
2640
2641 @noindent
2642 For a full detailed description of the format of the @file{ALI} file,
2643 see the source of the body of unit @code{Lib.Writ}, contained in file
2644 @file{lib-writ.adb} in the GNAT compiler sources.
2645
2646 @node Binding an Ada Program
2647 @section Binding an Ada Program
2648
2649 @noindent
2650 When using languages such as C and C++, once the source files have been
2651 compiled the only remaining step in building an executable program
2652 is linking the object modules together. This means that it is possible to
2653 link an inconsistent version of a program, in which two units have
2654 included different versions of the same header.
2655
2656 The rules of Ada do not permit such an inconsistent program to be built.
2657 For example, if two clients have different versions of the same package,
2658 it is illegal to build a program containing these two clients.
2659 These rules are enforced by the GNAT binder, which also determines an
2660 elaboration order consistent with the Ada rules.
2661
2662 The GNAT binder is run after all the object files for a program have
2663 been created. It is given the name of the main program unit, and from
2664 this it determines the set of units required by the program, by reading the
2665 corresponding ALI files. It generates error messages if the program is
2666 inconsistent or if no valid order of elaboration exists.
2667
2668 If no errors are detected, the binder produces a main program, in Ada by
2669 default, that contains calls to the elaboration procedures of those
2670 compilation unit that require them, followed by
2671 a call to the main program. This Ada program is compiled to generate the
2672 object file for the main program. The name of
2673 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2674 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2675 main program unit.
2676
2677 Finally, the linker is used to build the resulting executable program,
2678 using the object from the main program from the bind step as well as the
2679 object files for the Ada units of the program.
2680
2681 @node Mixed Language Programming
2682 @section Mixed Language Programming
2683 @cindex Mixed Language Programming
2684
2685 @noindent
2686 This section describes how to develop a mixed-language program,
2687 specifically one that comprises units in both Ada and C.
2688
2689 @menu
2690 * Interfacing to C::
2691 * Calling Conventions::
2692 @end menu
2693
2694 @node Interfacing to C
2695 @subsection Interfacing to C
2696 @noindent
2697 Interfacing Ada with a foreign language such as C involves using
2698 compiler directives to import and/or export entity definitions in each
2699 language---using @code{extern} statements in C, for instance, and the
2700 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2701 a full treatment of these topics, read Appendix B, section 1 of the Ada
2702 95 Language Reference Manual.
2703
2704 There are two ways to build a program using GNAT that contains some Ada
2705 sources and some foreign language sources, depending on whether or not
2706 the main subprogram is written in Ada.  Here is a source example with
2707 the main subprogram in Ada:
2708
2709 @smallexample
2710 /* file1.c */
2711 #include <stdio.h>
2712
2713 void print_num (int num)
2714 @{
2715   printf ("num is %d.\n", num);
2716   return;
2717 @}
2718
2719 /* file2.c */
2720
2721 /* num_from_Ada is declared in my_main.adb */
2722 extern int num_from_Ada;
2723
2724 int get_num (void)
2725 @{
2726   return num_from_Ada;
2727 @}
2728 @end smallexample
2729
2730 @smallexample @c ada
2731 --  my_main.adb
2732 procedure My_Main is
2733
2734    --  Declare then export an Integer entity called num_from_Ada
2735    My_Num : Integer := 10;
2736    pragma Export (C, My_Num, "num_from_Ada");
2737
2738    --  Declare an Ada function spec for Get_Num, then use
2739    --  C function get_num for the implementation.
2740    function Get_Num return Integer;
2741    pragma Import (C, Get_Num, "get_num");
2742
2743    --  Declare an Ada procedure spec for Print_Num, then use
2744    --  C function print_num for the implementation.
2745    procedure Print_Num (Num : Integer);
2746    pragma Import (C, Print_Num, "print_num");
2747
2748 begin
2749    Print_Num (Get_Num);
2750 end My_Main;
2751 @end smallexample
2752
2753 @enumerate
2754 @item
2755 To build this example, first compile the foreign language files to
2756 generate object files:
2757 @smallexample
2758 gcc -c file1.c
2759 gcc -c file2.c
2760 @end smallexample
2761
2762 @item
2763 Then, compile the Ada units to produce a set of object files and ALI
2764 files:
2765 @smallexample
2766 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2767 @end smallexample
2768
2769 @item
2770 Run the Ada binder on the Ada main program:
2771 @smallexample
2772 gnatbind my_main.ali
2773 @end smallexample
2774
2775 @item
2776 Link the Ada main program, the Ada objects and the other language
2777 objects:
2778 @smallexample
2779 gnatlink my_main.ali file1.o file2.o
2780 @end smallexample
2781 @end enumerate
2782
2783 The last three steps can be grouped in a single command:
2784 @smallexample
2785 gnatmake my_main.adb -largs file1.o file2.o
2786 @end smallexample
2787
2788 @cindex Binder output file
2789 @noindent
2790 If the main program is in a language other than Ada, then you may have
2791 more than one entry point into the Ada subsystem. You must use a special
2792 binder option to generate callable routines that initialize and
2793 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2794 Calls to the initialization and finalization routines must be inserted
2795 in the main program, or some other appropriate point in the code. The
2796 call to initialize the Ada units must occur before the first Ada
2797 subprogram is called, and the call to finalize the Ada units must occur
2798 after the last Ada subprogram returns. The binder will place the
2799 initialization and finalization subprograms into the
2800 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2801 sources.  To illustrate, we have the following example:
2802
2803 @smallexample
2804 /* main.c */
2805 extern void adainit (void);
2806 extern void adafinal (void);
2807 extern int add (int, int);
2808 extern int sub (int, int);
2809
2810 int main (int argc, char *argv[])
2811 @{
2812   int a = 21, b = 7;
2813
2814   adainit();
2815
2816   /* Should print "21 + 7 = 28" */
2817   printf ("%d + %d = %d\n", a, b, add (a, b));
2818   /* Should print "21 - 7 = 14" */
2819   printf ("%d - %d = %d\n", a, b, sub (a, b));
2820
2821   adafinal();
2822 @}
2823 @end smallexample
2824
2825 @smallexample @c ada
2826 --  unit1.ads
2827 package Unit1 is
2828    function Add (A, B : Integer) return Integer;
2829    pragma Export (C, Add, "add");
2830 end Unit1;
2831
2832 --  unit1.adb
2833 package body Unit1 is
2834    function Add (A, B : Integer) return Integer is
2835    begin
2836       return A + B;
2837    end Add;
2838 end Unit1;
2839
2840 --  unit2.ads
2841 package Unit2 is
2842    function Sub (A, B : Integer) return Integer;
2843    pragma Export (C, Sub, "sub");
2844 end Unit2;
2845
2846 --  unit2.adb
2847 package body Unit2 is
2848    function Sub (A, B : Integer) return Integer is
2849    begin
2850       return A - B;
2851    end Sub;
2852 end Unit2;
2853 @end smallexample
2854
2855 @enumerate
2856 @item
2857 The build procedure for this application is similar to the last
2858 example's.  First, compile the foreign language files to generate object
2859 files:
2860 @smallexample
2861 gcc -c main.c
2862 @end smallexample
2863
2864 @item
2865 Next, compile the Ada units to produce a set of object files and ALI
2866 files:
2867 @smallexample
2868 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2869 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2870 @end smallexample
2871
2872 @item
2873 Run the Ada binder on every generated ALI file.  Make sure to use the
2874 @option{-n} option to specify a foreign main program:
2875 @smallexample
2876 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2877 @end smallexample
2878
2879 @item
2880 Link the Ada main program, the Ada objects and the foreign language
2881 objects. You need only list the last ALI file here:
2882 @smallexample
2883 gnatlink unit2.ali main.o -o exec_file
2884 @end smallexample
2885
2886 This procedure yields a binary executable called @file{exec_file}.
2887 @end enumerate
2888
2889 @node Calling Conventions
2890 @subsection Calling Conventions
2891 @cindex Foreign Languages
2892 @cindex Calling Conventions
2893 GNAT follows standard calling sequence conventions and will thus interface
2894 to any other language that also follows these conventions. The following
2895 Convention identifiers are recognized by GNAT:
2896
2897 @table @code
2898 @cindex Interfacing to Ada
2899 @cindex Other Ada compilers
2900 @cindex Convention Ada
2901 @item Ada
2902 This indicates that the standard Ada calling sequence will be
2903 used and all Ada data items may be passed without any limitations in the
2904 case where GNAT is used to generate both the caller and callee. It is also
2905 possible to mix GNAT generated code and code generated by another Ada
2906 compiler. In this case, the data types should be restricted to simple
2907 cases, including primitive types. Whether complex data types can be passed
2908 depends on the situation. Probably it is safe to pass simple arrays, such
2909 as arrays of integers or floats. Records may or may not work, depending
2910 on whether both compilers lay them out identically. Complex structures
2911 involving variant records, access parameters, tasks, or protected types,
2912 are unlikely to be able to be passed.
2913
2914 Note that in the case of GNAT running
2915 on a platform that supports DEC Ada 83, a higher degree of compatibility
2916 can be guaranteed, and in particular records are layed out in an identical
2917 manner in the two compilers. Note also that if output from two different
2918 compilers is mixed, the program is responsible for dealing with elaboration
2919 issues. Probably the safest approach is to write the main program in the
2920 version of Ada other than GNAT, so that it takes care of its own elaboration
2921 requirements, and then call the GNAT-generated adainit procedure to ensure
2922 elaboration of the GNAT components. Consult the documentation of the other
2923 Ada compiler for further details on elaboration.
2924
2925 However, it is not possible to mix the tasking run time of GNAT and
2926 DEC Ada 83, All the tasking operations must either be entirely within
2927 GNAT compiled sections of the program, or entirely within DEC Ada 83
2928 compiled sections of the program.
2929
2930 @cindex Interfacing to Assembly
2931 @cindex Convention Assembler
2932 @item Assembler
2933 Specifies assembler as the convention. In practice this has the
2934 same effect as convention Ada (but is not equivalent in the sense of being
2935 considered the same convention).
2936
2937 @cindex Convention Asm
2938 @findex Asm
2939 @item Asm
2940 Equivalent to Assembler.
2941
2942 @cindex Interfacing to COBOL
2943 @cindex Convention COBOL
2944 @findex COBOL
2945 @item COBOL
2946 Data will be passed according to the conventions described
2947 in section B.4 of the Ada 95 Reference Manual.
2948
2949 @findex C
2950 @cindex Interfacing to C
2951 @cindex Convention C
2952 @item C
2953 Data will be passed according to the conventions described
2954 in section B.3 of the Ada 95 Reference Manual.
2955
2956 @findex C varargs function
2957 @cindex Intefacing to C varargs function
2958 @cindex varargs function intefacs
2959 @item C varargs function
2960 In C, @code{varargs} allows a function to take a variable number of
2961 arguments. There is no direct equivalent in this to Ada. One
2962 approach that can be used is to create a C wrapper for each
2963 different profile and then interface to this C wrapper. For
2964 example, to print an @code{int} value using @code{printf},
2965 create a C function @code{printfi} that takes two arguments, a
2966 pointer to a string and an int, and calls @code{printf}.
2967 Then in the Ada program, use pragma @code{Import} to
2968 interface to printfi.
2969
2970 It may work on some platforms to directly interface to
2971 a @code{varargs} function by providing a specific Ada profile
2972 for a a particular call. However, this does not work on
2973 all platforms, since there is no guarantee that the
2974 calling sequence for a two argument normal C function
2975 is the same as for calling a @code{varargs} C function with
2976 the same two arguments.
2977
2978 @cindex Convention Default
2979 @findex Default
2980 @item Default
2981 Equivalent to C.
2982
2983 @cindex Convention External
2984 @findex External
2985 @item External
2986 Equivalent to C.
2987
2988 @findex C++
2989 @cindex Interfacing to C++
2990 @cindex Convention C++
2991 @item CPP
2992 This stands for C++. For most purposes this is identical to C.
2993 See the separate description of the specialized GNAT pragmas relating to
2994 C++ interfacing for further details.
2995
2996 @findex Fortran
2997 @cindex Interfacing to Fortran
2998 @cindex Convention Fortran
2999 @item Fortran
3000 Data will be passed according to the conventions described
3001 in section B.5 of the Ada 95 Reference Manual.
3002
3003 @item Intrinsic
3004 This applies to an intrinsic operation, as defined in the Ada 95
3005 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3006 this means that the body of the subprogram is provided by the compiler itself,
3007 usually by means of an efficient code sequence, and that the user does not
3008 supply an explicit body for it. In an application program, the pragma can
3009 only be applied to the following two sets of names, which the GNAT compiler
3010 recognizes.
3011
3012 @itemize @bullet
3013 @item
3014 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3015 Arithmetic.  The corresponding subprogram declaration must have
3016 two formal parameters. The
3017 first one must be a signed integer type or a modular type with a binary
3018 modulus, and the second parameter must be of type Natural.
3019 The return type must be the same as the type of the first argument. The size
3020 of this type can only be 8, 16, 32, or 64.
3021 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3022 The corresponding operator declaration must have parameters and result type
3023 that have the same root numeric type (for example, all three are long_float
3024 types). This simplifies the definition of operations that use type checking
3025 to perform dimensional checks:
3026
3027 @smallexample @c ada
3028 type Distance is new Long_Float;
3029 type Time     is new Long_Float;
3030 type Velocity is new Long_Float;
3031 function "/" (D : Distance; T : Time)
3032   return Velocity;
3033 pragma Import (Intrinsic, "/");
3034 @end smallexample
3035
3036 @noindent
3037 This common idiom is often programmed with a generic definition and an
3038 explicit body. The pragma makes it simpler to introduce such declarations.
3039 It incurs no overhead in compilation time or code size, because it is
3040 implemented as a single machine instruction.
3041 @end itemize
3042 @noindent
3043
3044 @ifset unw
3045 @findex Stdcall
3046 @cindex Convention Stdcall
3047 @item Stdcall
3048 This is relevant only to NT/Win95 implementations of GNAT,
3049 and specifies that the Stdcall calling sequence will be used, as defined
3050 by the NT API.
3051
3052 @findex DLL
3053 @cindex Convention DLL
3054 @item DLL
3055 This is equivalent to Stdcall.
3056
3057 @findex Win32
3058 @cindex Convention Win32
3059 @item Win32
3060 This is equivalent to Stdcall.
3061 @end ifset
3062
3063 @findex Stubbed
3064 @cindex Convention Stubbed
3065 @item Stubbed
3066 This is a special convention that indicates that the compiler
3067 should provide a stub body that raises @code{Program_Error}.
3068 @end table
3069
3070 @noindent
3071 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3072 that can be used to parametrize conventions and allow additional synonyms
3073 to be specified. For example if you have legacy code in which the convention
3074 identifier Fortran77 was used for Fortran, you can use the configuration
3075 pragma:
3076
3077 @smallexample @c ada
3078 pragma Convention_Identifier (Fortran77, Fortran);
3079 @end smallexample
3080
3081 @noindent
3082 And from now on the identifier Fortran77 may be used as a convention
3083 identifier (for example in an @code{Import} pragma) with the same
3084 meaning as Fortran.
3085
3086 @node Building Mixed Ada & C++ Programs
3087 @section Building Mixed Ada & C++ Programs
3088
3089 @noindent
3090 A programmer inexperienced with mixed-language development may find that
3091 building an application containing both Ada and C++ code can be a
3092 challenge. As a matter of fact, interfacing with C++ has not been
3093 standardized in the Ada 95 Reference Manual due to the immaturity of --
3094 and lack of standards for -- C++ at the time. This section gives a few
3095 hints that should make this task easier. The first section addresses
3096 the differences regarding interfacing with C. The second section
3097 looks into the delicate problem of linking the complete application from
3098 its Ada and C++ parts. The last section gives some hints on how the GNAT
3099 run time can be adapted in order to allow inter-language dispatching
3100 with a new C++ compiler.
3101
3102 @menu
3103 * Interfacing to C++::
3104 * Linking a Mixed C++ & Ada Program::
3105 * A Simple Example::
3106 * Adapting the Run Time to a New C++ Compiler::
3107 @end menu
3108
3109 @node Interfacing to C++
3110 @subsection Interfacing to C++
3111
3112 @noindent
3113 GNAT supports interfacing with C++ compilers generating code that is
3114 compatible with the standard Application Binary Interface of the given
3115 platform.
3116
3117 @noindent
3118 Interfacing can be done at 3 levels: simple data, subprograms, and
3119 classes. In the first two cases, GNAT offers a specific @var{Convention
3120 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3121 the names of subprograms, and currently, GNAT does not provide any help
3122 to solve the demangling problem. This problem can be addressed in two
3123 ways:
3124 @itemize @bullet
3125 @item
3126 by modifying the C++ code in order to force a C convention using
3127 the @code{extern "C"} syntax.
3128
3129 @item
3130 by figuring out the mangled name and use it as the Link_Name argument of
3131 the pragma import.
3132 @end itemize
3133
3134 @noindent
3135 Interfacing at the class level can be achieved by using the GNAT specific
3136 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3137 Reference Manual for additional information.
3138
3139 @node Linking a Mixed C++ & Ada Program
3140 @subsection Linking a Mixed C++ & Ada Program
3141
3142 @noindent
3143 Usually the linker of the C++ development system must be used to link
3144 mixed applications because most C++ systems will resolve elaboration
3145 issues (such as calling constructors on global class instances)
3146 transparently during the link phase. GNAT has been adapted to ease the
3147 use of a foreign linker for the last phase. Three cases can be
3148 considered:
3149 @enumerate
3150
3151 @item
3152 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3153 The C++ linker can simply be called by using the C++ specific driver
3154 called @code{c++}. Note that this setup is not very common because it
3155 may involve recompiling the whole GCC tree from sources, which makes it
3156 harder to upgrade the compilation system for one language without
3157 destabilizing the other.
3158
3159 @smallexample
3160 $ c++ -c file1.C
3161 $ c++ -c file2.C
3162 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3163 @end smallexample
3164
3165 @item
3166 Using GNAT and G++ from two different GCC installations: If both
3167 compilers are on the PATH, the previous method may be used. It is
3168 important to note that environment variables such as C_INCLUDE_PATH,
3169 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3170 at the same time and may make one of the two compilers operate
3171 improperly if set during invocation of the wrong compiler.  It is also
3172 very important that the linker uses the proper @file{libgcc.a} GCC
3173 library -- that is, the one from the C++ compiler installation. The
3174 implicit link command as suggested in the gnatmake command from the
3175 former example can be replaced by an explicit link command with the
3176 full-verbosity option in order to verify which library is used:
3177 @smallexample
3178 $ gnatbind ada_unit
3179 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3180 @end smallexample
3181 If there is a problem due to interfering environment variables, it can
3182 be worked around by using an intermediate script. The following example
3183 shows the proper script to use when GNAT has not been installed at its
3184 default location and g++ has been installed at its default location:
3185
3186 @smallexample
3187 $ cat ./my_script
3188 #!/bin/sh
3189 unset BINUTILS_ROOT
3190 unset GCC_ROOT
3191 c++ $*
3192 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3193 @end smallexample
3194
3195 @item
3196 Using a non-GNU C++ compiler: The commands previously described can be
3197 used to insure that the C++ linker is used. Nonetheless, you need to add
3198 the path to libgcc explicitly, since some libraries needed by GNAT are
3199 located in this directory:
3200
3201 @smallexample
3202 $ cat ./my_script
3203 #!/bin/sh
3204 CC $* `gcc -print-libgcc-file-name`
3205 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3206 @end smallexample
3207
3208 Where CC is the name of the non-GNU C++ compiler.
3209
3210 @end enumerate
3211
3212 @node A Simple Example
3213 @subsection  A Simple Example
3214 @noindent
3215 The following example, provided as part of the GNAT examples, shows how
3216 to achieve procedural interfacing between Ada and C++ in both
3217 directions. The C++ class A has two methods. The first method is exported
3218 to Ada by the means of an extern C wrapper function. The second method
3219 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3220 a limited record with a layout comparable to the C++ class. The Ada
3221 subprogram, in turn, calls the C++ method. So, starting from the C++
3222 main program, the process passes back and forth between the two
3223 languages.
3224
3225 @noindent
3226 Here are the compilation commands:
3227 @smallexample
3228 $ gnatmake -c simple_cpp_interface
3229 $ c++ -c cpp_main.C
3230 $ c++ -c ex7.C
3231 $ gnatbind -n simple_cpp_interface
3232 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3233       -lstdc++ ex7.o cpp_main.o
3234 @end smallexample
3235
3236 @noindent
3237 Here are the corresponding sources:
3238 @smallexample
3239
3240 //cpp_main.C
3241
3242 #include "ex7.h"
3243
3244 extern "C" @{
3245   void adainit (void);
3246   void adafinal (void);
3247   void method1 (A *t);
3248 @}
3249
3250 void method1 (A *t)
3251 @{
3252   t->method1 ();
3253 @}
3254
3255 int main ()
3256 @{
3257   A obj;
3258   adainit ();
3259   obj.method2 (3030);
3260   adafinal ();
3261 @}
3262
3263 //ex7.h
3264
3265 class Origin @{
3266  public:
3267   int o_value;
3268 @};
3269 class A : public Origin @{
3270  public:
3271   void method1 (void);
3272   virtual void method2 (int v);
3273   A();
3274   int   a_value;
3275 @};
3276
3277 //ex7.C
3278
3279 #include "ex7.h"
3280 #include <stdio.h>
3281
3282 extern "C" @{ void ada_method2 (A *t, int v);@}
3283
3284 void A::method1 (void)
3285 @{
3286   a_value = 2020;
3287   printf ("in A::method1, a_value = %d \n",a_value);
3288
3289 @}
3290
3291 void A::method2 (int v)
3292 @{
3293    ada_method2 (this, v);
3294    printf ("in A::method2, a_value = %d \n",a_value);
3295
3296 @}
3297
3298 A::A(void)
3299 @{
3300    a_value = 1010;
3301   printf ("in A::A, a_value = %d \n",a_value);
3302 @}
3303
3304 -- Ada sources
3305 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3306
3307    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3308    @b{begin}
3309       Method1 (This);
3310       This.A_Value := V;
3311    @b{end} Ada_Method2;
3312
3313 @b{end} Simple_Cpp_Interface;
3314
3315 @b{package} Simple_Cpp_Interface @b{is}
3316    @b{type} A @b{is} @b{limited}
3317       @b{record}
3318          O_Value : Integer;
3319          A_Value : Integer;
3320       @b{end} @b{record};
3321    @b{pragma} Convention (C, A);
3322
3323    @b{procedure} Method1 (This : @b{in} @b{out} A);
3324    @b{pragma} Import (C, Method1);
3325
3326    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3327    @b{pragma} Export (C, Ada_Method2);
3328
3329 @b{end} Simple_Cpp_Interface;
3330 @end smallexample
3331
3332 @node Adapting the Run Time to a New C++ Compiler
3333 @subsection Adapting the Run Time to a New C++ Compiler
3334 @noindent
3335 GNAT offers the capability to derive Ada 95 tagged types directly from
3336 preexisting C++ classes and . See ``Interfacing with C++'' in the
3337 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3338 such a goal
3339 has been made user configurable through a GNAT library unit
3340 @code{Interfaces.CPP}. The default version of this file is adapted to
3341 the GNU C++ compiler. Internal knowledge of the virtual
3342 table layout used by the new C++ compiler is needed to configure
3343 properly this unit. The Interface of this unit is known by the compiler
3344 and cannot be changed except for the value of the constants defining the
3345 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3346 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3347 of this unit for more details.
3348
3349 @node Comparison between GNAT and C/C++ Compilation Models
3350 @section Comparison between GNAT and C/C++ Compilation Models
3351
3352 @noindent
3353 The GNAT model of compilation is close to the C and C++ models. You can
3354 think of Ada specs as corresponding to header files in C. As in C, you
3355 don't need to compile specs; they are compiled when they are used. The
3356 Ada @code{with} is similar in effect to the @code{#include} of a C
3357 header.
3358
3359 One notable difference is that, in Ada, you may compile specs separately
3360 to check them for semantic and syntactic accuracy. This is not always
3361 possible with C headers because they are fragments of programs that have
3362 less specific syntactic or semantic rules.
3363
3364 The other major difference is the requirement for running the binder,
3365 which performs two important functions. First, it checks for
3366 consistency. In C or C++, the only defense against assembling
3367 inconsistent programs lies outside the compiler, in a makefile, for
3368 example. The binder satisfies the Ada requirement that it be impossible
3369 to construct an inconsistent program when the compiler is used in normal
3370 mode.
3371
3372 @cindex Elaboration order control
3373 The other important function of the binder is to deal with elaboration
3374 issues. There are also elaboration issues in C++ that are handled
3375 automatically. This automatic handling has the advantage of being
3376 simpler to use, but the C++ programmer has no control over elaboration.
3377 Where @code{gnatbind} might complain there was no valid order of
3378 elaboration, a C++ compiler would simply construct a program that
3379 malfunctioned at run time.
3380
3381 @node Comparison between GNAT and Conventional Ada Library Models
3382 @section Comparison between GNAT and Conventional Ada Library Models
3383
3384 @noindent
3385 This section is intended to be useful to Ada programmers who have
3386 previously used an Ada compiler implementing the traditional Ada library
3387 model, as described in the Ada 95 Language Reference Manual. If you
3388 have not used such a system, please go on to the next section.
3389
3390 @cindex GNAT library
3391 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3392 source files themselves acts as the library. Compiling Ada programs does
3393 not generate any centralized information, but rather an object file and
3394 a ALI file, which are of interest only to the binder and linker.
3395 In a traditional system, the compiler reads information not only from
3396 the source file being compiled, but also from the centralized library.
3397 This means that the effect of a compilation depends on what has been
3398 previously compiled. In particular:
3399
3400 @itemize @bullet
3401 @item
3402 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3403 to the version of the unit most recently compiled into the library.
3404
3405 @item
3406 Inlining is effective only if the necessary body has already been
3407 compiled into the library.
3408
3409 @item
3410 Compiling a unit may obsolete other units in the library.
3411 @end itemize
3412
3413 @noindent
3414 In GNAT, compiling one unit never affects the compilation of any other
3415 units because the compiler reads only source files. Only changes to source
3416 files can affect the results of a compilation. In particular:
3417
3418 @itemize @bullet
3419 @item
3420 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3421 to the source version of the unit that is currently accessible to the
3422 compiler.
3423
3424 @item
3425 @cindex Inlining
3426 Inlining requires the appropriate source files for the package or
3427 subprogram bodies to be available to the compiler. Inlining is always
3428 effective, independent of the order in which units are complied.
3429
3430 @item
3431 Compiling a unit never affects any other compilations. The editing of
3432 sources may cause previous compilations to be out of date if they
3433 depended on the source file being modified.
3434 @end itemize
3435
3436 @noindent
3437 The most important result of these differences is that order of compilation
3438 is never significant in GNAT. There is no situation in which one is
3439 required to do one compilation before another. What shows up as order of
3440 compilation requirements in the traditional Ada library becomes, in
3441 GNAT, simple source dependencies; in other words, there is only a set
3442 of rules saying what source files must be present when a file is
3443 compiled.
3444
3445 @ifset vms
3446 @node Placement of temporary files
3447 @section Placement of temporary files
3448 @cindex Temporary files (user control over placement)
3449
3450 @noindent
3451 GNAT creates temporary files in the directory designated by the environment
3452 variable @env{TMPDIR}.
3453 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3454 for detailed information on how environment variables are resolved.
3455 For most users the easiest way to make use of this feature is to simply
3456 define @env{TMPDIR} as a job level logical name).
3457 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3458 for compiler temporary files, then you can include something like the
3459 following command in your @file{LOGIN.COM} file:
3460
3461 @smallexample
3462 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3463 @end smallexample
3464
3465 @noindent
3466 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3467 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3468 designated by @env{TEMP}.
3469 If none of these environment variables are defined then GNAT uses the
3470 directory designated by the logical name @code{SYS$SCRATCH:}
3471 (by default the user's home directory). If all else fails
3472 GNAT uses the current directory for temporary files.
3473 @end ifset
3474
3475
3476 @c *************************
3477 @node Compiling Using gcc
3478 @chapter Compiling Using @code{gcc}
3479
3480 @noindent
3481 This chapter discusses how to compile Ada programs using the @code{gcc}
3482 command. It also describes the set of switches
3483 that can be used to control the behavior of the compiler.
3484 @menu
3485 * Compiling Programs::
3486 * Switches for gcc::
3487 * Search Paths and the Run-Time Library (RTL)::
3488 * Order of Compilation Issues::
3489 * Examples::
3490 @end menu
3491
3492 @node Compiling Programs
3493 @section Compiling Programs
3494
3495 @noindent
3496 The first step in creating an executable program is to compile the units
3497 of the program using the @code{gcc} command. You must compile the
3498 following files:
3499
3500 @itemize @bullet
3501 @item
3502 the body file (@file{.adb}) for a library level subprogram or generic
3503 subprogram
3504
3505 @item
3506 the spec file (@file{.ads}) for a library level package or generic
3507 package that has no body
3508
3509 @item
3510 the body file (@file{.adb}) for a library level package
3511 or generic package that has a body
3512
3513 @end itemize
3514
3515 @noindent
3516 You need @emph{not} compile the following files
3517
3518 @itemize @bullet
3519
3520 @item
3521 the spec of a library unit which has a body
3522
3523 @item
3524 subunits
3525 @end itemize
3526
3527 @noindent
3528 because they are compiled as part of compiling related units. GNAT
3529 package specs
3530 when the corresponding body is compiled, and subunits when the parent is
3531 compiled.
3532
3533 @cindex cannot generate code
3534 If you attempt to compile any of these files, you will get one of the
3535 following error messages (where fff is the name of the file you compiled):
3536
3537 @smallexample
3538 cannot generate code for file @var{fff} (package spec)
3539 to check package spec, use -gnatc
3540
3541 cannot generate code for file @var{fff} (missing subunits)
3542 to check parent unit, use -gnatc
3543
3544 cannot generate code for file @var{fff} (subprogram spec)
3545 to check subprogram spec, use -gnatc
3546
3547 cannot generate code for file @var{fff} (subunit)
3548 to check subunit, use -gnatc
3549 @end smallexample
3550
3551 @noindent
3552 As indicated by the above error messages, if you want to submit
3553 one of these files to the compiler to check for correct semantics
3554 without generating code, then use the @option{-gnatc} switch.
3555
3556 The basic command for compiling a file containing an Ada unit is
3557
3558 @smallexample
3559 $ gcc -c [@var{switches}] @file{file name}
3560 @end smallexample
3561
3562 @noindent
3563 where @var{file name} is the name of the Ada file (usually
3564 having an extension
3565 @file{.ads} for a spec or @file{.adb} for a body).
3566 @ifclear vms
3567 You specify the
3568 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3569 @end ifclear
3570 The result of a successful compilation is an object file, which has the
3571 same name as the source file but an extension of @file{.o} and an Ada
3572 Library Information (ALI) file, which also has the same name as the
3573 source file, but with @file{.ali} as the extension. GNAT creates these
3574 two output files in the current directory, but you may specify a source
3575 file in any directory using an absolute or relative path specification
3576 containing the directory information.
3577
3578 @findex gnat1
3579 @code{gcc} is actually a driver program that looks at the extensions of
3580 the file arguments and loads the appropriate compiler. For example, the
3581 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3582 These programs are in directories known to the driver program (in some
3583 configurations via environment variables you set), but need not be in
3584 your path. The @code{gcc} driver also calls the assembler and any other
3585 utilities needed to complete the generation of the required object
3586 files.
3587
3588 It is possible to supply several file names on the same @code{gcc}
3589 command. This causes @code{gcc} to call the appropriate compiler for
3590 each file. For example, the following command lists three separate
3591 files to be compiled:
3592
3593 @smallexample
3594 $ gcc -c x.adb y.adb z.c
3595 @end smallexample
3596
3597 @noindent
3598 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3599 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3600 The compiler generates three object files @file{x.o}, @file{y.o} and
3601 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3602 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3603 @ifclear vms
3604 except for
3605 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3606 @end ifclear
3607
3608 @node Switches for gcc
3609 @section Switches for @code{gcc}
3610
3611 @noindent
3612 The @code{gcc} command accepts switches that control the
3613 compilation process. These switches are fully described in this section.
3614 First we briefly list all the switches, in alphabetical order, then we
3615 describe the switches in more detail in functionally grouped sections.
3616
3617 @menu
3618 * Output and Error Message Control::
3619 * Warning Message Control::
3620 * Debugging and Assertion Control::
3621 * Run-Time Checks::
3622 * Stack Overflow Checking::
3623 * Validity Checking::
3624 * Style Checking::
3625 * Using gcc for Syntax Checking::
3626 * Using gcc for Semantic Checking::
3627 * Compiling Ada 83 Programs::
3628 * Character Set Control::
3629 * File Naming Control::
3630 * Subprogram Inlining Control::
3631 * Auxiliary Output Control::
3632 * Debugging Control::
3633 * Exception Handling Control::
3634 * Units to Sources Mapping Files::
3635 * Integrated Preprocessing::
3636 @ifset vms
3637 * Return Codes::
3638 @end ifset
3639 @end menu
3640
3641 @table @option
3642 @c !sort!
3643 @ifclear vms
3644 @cindex @option{-b} (@code{gcc})
3645 @item -b @var{target}
3646 Compile your program to run on @var{target}, which is the name of a
3647 system configuration. You must have a GNAT cross-compiler built if
3648 @var{target} is not the same as your host system.
3649
3650 @item -B@var{dir}
3651 @cindex @option{-B} (@code{gcc})
3652 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3653 from @var{dir} instead of the default location. Only use this switch
3654 when multiple versions of the GNAT compiler are available. See the
3655 @code{gcc} manual page for further details. You would normally use the
3656 @option{-b} or @option{-V} switch instead.
3657
3658 @item -c
3659 @cindex @option{-c} (@code{gcc})
3660 Compile. Always use this switch when compiling Ada programs.
3661
3662 Note: for some other languages when using @code{gcc}, notably in
3663 the case of C and C++, it is possible to use
3664 use @code{gcc} without a @option{-c} switch to
3665 compile and link in one step. In the case of GNAT, you
3666 cannot use this approach, because the binder must be run
3667 and @code{gcc} cannot be used to run the GNAT binder.
3668 @end ifclear
3669
3670 @item -fno-inline
3671 @cindex @option{-fno-inline} (@code{gcc})
3672 Suppresses all back-end inlining, even if other optimization or inlining
3673 switches are set.
3674 This includes suppression of inlining that results
3675 from the use of the pragma @code{Inline_Always}.
3676 See also @option{-gnatn} and @option{-gnatN}.
3677
3678 @item -fno-strict-aliasing
3679 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3680 Causes the compiler to avoid assumptions regarding non-aliasing
3681 of objects of different types. See section
3682 @pxref{Optimization and Strict Aliasing} for details.
3683
3684 @item -fstack-check
3685 @cindex @option{-fstack-check} (@code{gcc})
3686 Activates stack checking.
3687 See @ref{Stack Overflow Checking} for details of the use of this option.
3688
3689 @item ^-g^/DEBUG^
3690 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3691 Generate debugging information. This information is stored in the object
3692 file and copied from there to the final executable file by the linker,
3693 where it can be read by the debugger. You must use the
3694 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3695
3696 @item -gnat83
3697 @cindex @option{-gnat83} (@code{gcc})
3698 Enforce Ada 83 restrictions.
3699
3700 @item -gnata
3701 @cindex @option{-gnata} (@code{gcc})
3702 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3703 activated.
3704
3705 @item -gnatA
3706 @cindex @option{-gnatA} (@code{gcc})
3707 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3708 it will be ignored.
3709
3710 @item -gnatb
3711 @cindex @option{-gnatb} (@code{gcc})
3712 Generate brief messages to @file{stderr} even if verbose mode set.
3713
3714 @item -gnatc
3715 @cindex @option{-gnatc} (@code{gcc})
3716 Check syntax and semantics only (no code generation attempted).
3717
3718 @item -gnatd
3719 @cindex @option{-gnatd} (@code{gcc})
3720 Specify debug options for the compiler. The string of characters after
3721 the @option{-gnatd} specify the specific debug options. The possible
3722 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3723 compiler source file @file{debug.adb} for details of the implemented
3724 debug options. Certain debug options are relevant to applications
3725 programmers, and these are documented at appropriate points in this
3726 users guide.
3727
3728 @item -gnatD
3729 @cindex @option{-gnatD} (@code{gcc})
3730 Create expanded source files for source level debugging. This switch
3731 also suppress generation of cross-reference information
3732 (see @option{-gnatx}).
3733
3734 @item -gnatec=@var{path}
3735 @cindex @option{-gnatec} (@code{gcc})
3736 Specify a configuration pragma file
3737 @ifclear vms
3738 (the equal sign is optional)
3739 @end ifclear
3740 (see @ref{The Configuration Pragmas Files}).
3741
3742 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3743 @cindex @option{-gnateD} (@code{gcc})
3744 Defines a symbol, associated with value, for preprocessing.
3745 (see @ref{Integrated Preprocessing})
3746
3747 @item -gnatef
3748 @cindex @option{-gnatef} (@code{gcc})
3749 Display full source path name in brief error messages.
3750
3751 @item -gnatem=@var{path}
3752 @cindex @option{-gnatem} (@code{gcc})
3753 Specify a mapping file
3754 @ifclear vms
3755 (the equal sign is optional)
3756 @end ifclear
3757 (see @ref{Units to Sources Mapping Files}).
3758
3759 @item -gnatep=@var{file}
3760 @cindex @option{-gnatep} (@code{gcc})
3761 Specify a preprocessing data file
3762 @ifclear vms
3763 (the equal sign is optional)
3764 @end ifclear
3765 (see @ref{Integrated Preprocessing}).
3766
3767 @item -gnatE
3768 @cindex @option{-gnatE} (@code{gcc})
3769 Full dynamic elaboration checks.
3770
3771 @item -gnatf
3772 @cindex @option{-gnatf} (@code{gcc})
3773 Full errors. Multiple errors per line, all undefined references, do not
3774 attempt to suppress cascaded errors.
3775
3776 @item -gnatF
3777 @cindex @option{-gnatF} (@code{gcc})
3778 Externals names are folded to all uppercase.
3779
3780 @item -gnatg
3781 @cindex @option{-gnatg} (@code{gcc})
3782 Internal GNAT implementation mode. This should not be used for
3783 applications programs, it is intended only for use by the compiler
3784 and its run-time library. For documentation, see the GNAT sources.
3785 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3786 are generated on unreferenced entities, and all warnings are treated
3787 as errors.
3788
3789 @item -gnatG
3790 @cindex @option{-gnatG} (@code{gcc})
3791 List generated expanded code in source form.
3792
3793 @item ^-gnath^/HELP^
3794 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3795 Output usage information. The output is written to @file{stdout}.
3796
3797 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3798 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3799 Identifier character set
3800 @ifclear vms
3801 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3802 @end ifclear
3803 @ifset vms
3804 For details of the possible selections for @var{c},
3805 see @xref{Character Set Control}.
3806 @end ifset
3807
3808 @item -gnatk=@var{n}
3809 @cindex @option{-gnatk} (@code{gcc})
3810 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3811
3812 @item -gnatl
3813 @cindex @option{-gnatl} (@code{gcc})
3814 Output full source listing with embedded error messages.
3815
3816 @item -gnatL
3817 @cindex @option{-gnatL} (@code{gcc})
3818 Use the longjmp/setjmp method for exception handling
3819
3820 @item -gnatm=@var{n}
3821 @cindex @option{-gnatm} (@code{gcc})
3822 Limit number of detected error or warning messages to @var{n}
3823 where @var{n} is in the range 1..999_999. The default setting if
3824 no switch is given is 9999. Compilation is terminated if this
3825 limit is exceeded.
3826
3827 @item -gnatn
3828 @cindex @option{-gnatn} (@code{gcc})
3829 Activate inlining for subprograms for which
3830 pragma @code{inline} is specified. This inlining is performed
3831 by the GCC back-end.
3832
3833 @item -gnatN
3834 @cindex @option{-gnatN} (@code{gcc})
3835 Activate front end inlining for subprograms for which
3836 pragma @code{Inline} is specified. This inlining is performed
3837 by the front end and will be visible in the
3838 @option{-gnatG} output.
3839 In some cases, this has proved more effective than the back end
3840 inlining resulting from the use of
3841 @option{-gnatn}.
3842 Note that
3843 @option{-gnatN} automatically implies
3844 @option{-gnatn} so it is not necessary
3845 to specify both options. There are a few cases that the back-end inlining
3846 catches that cannot be dealt with in the front-end.
3847
3848 @item -gnato
3849 @cindex @option{-gnato} (@code{gcc})
3850 Enable numeric overflow checking (which is not normally enabled by
3851 default). Not that division by zero is a separate check that is not
3852 controlled by this switch (division by zero checking is on by default).
3853
3854 @item -gnatp
3855 @cindex @option{-gnatp} (@code{gcc})
3856 Suppress all checks.
3857
3858 @item -gnatP
3859 @cindex @option{-gnatP} (@code{gcc})
3860 Enable polling. This is required on some systems (notably Windows NT) to
3861 obtain asynchronous abort and asynchronous transfer of control capability.
3862 See the description of pragma Polling in the GNAT Reference Manual for
3863 full details.
3864
3865 @item -gnatq
3866 @cindex @option{-gnatq} (@code{gcc})
3867 Don't quit; try semantics, even if parse errors.
3868
3869 @item -gnatQ
3870 @cindex @option{-gnatQ} (@code{gcc})
3871 Don't quit; generate @file{ALI} and tree files even if illegalities.
3872
3873 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3874 @cindex @option{-gnatR} (@code{gcc})
3875 Output representation information for declared types and objects.
3876
3877 @item -gnats
3878 @cindex @option{-gnats} (@code{gcc})
3879 Syntax check only.
3880
3881 @item -gnatS
3882 @cindex @option{-gnatS} (@code{gcc})
3883 Print package Standard.
3884
3885 @item -gnatt
3886 @cindex @option{-gnatt} (@code{gcc})
3887 Generate tree output file.
3888
3889 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3890 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3891 All compiler tables start at @var{nnn} times usual starting size.
3892
3893 @item -gnatu
3894 @cindex @option{-gnatu} (@code{gcc})
3895 List units for this compilation.
3896
3897 @item -gnatU
3898 @cindex @option{-gnatU} (@code{gcc})
3899 Tag all error messages with the unique string ``error:''
3900
3901 @item -gnatv
3902 @cindex @option{-gnatv} (@code{gcc})
3903 Verbose mode. Full error output with source lines to @file{stdout}.
3904
3905 @item -gnatV
3906 @cindex @option{-gnatV} (@code{gcc})
3907 Control level of validity checking. See separate section describing
3908 this feature.
3909
3910 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3911 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3912 Warning mode where
3913 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3914 the exact warnings that
3915 are enabled or disabled. (see @ref{Warning Message Control})
3916
3917 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3918 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3919 Wide character encoding method
3920 @ifclear vms
3921 (@var{e}=n/h/u/s/e/8).
3922 @end ifclear
3923 @ifset vms
3924 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3925 @end ifset
3926
3927 @item -gnatx
3928 @cindex @option{-gnatx} (@code{gcc})
3929 Suppress generation of cross-reference information.
3930
3931 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3932 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3933 Enable built-in style checks. (see @ref{Style Checking})
3934
3935 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3936 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3937 Distribution stub generation and compilation
3938 @ifclear vms
3939 (@var{m}=r/c for receiver/caller stubs).
3940 @end ifclear
3941 @ifset vms
3942 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3943 to be generated and compiled).
3944 @end ifset
3945
3946 @item -gnatZ
3947 Use the zero cost method for exception handling
3948
3949 @item ^-I^/SEARCH=^@var{dir}
3950 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3951 @cindex RTL
3952 Direct GNAT to search the @var{dir} directory for source files needed by
3953 the current compilation
3954 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3955
3956 @item ^-I-^/NOCURRENT_DIRECTORY^
3957 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3958 @cindex RTL
3959 Except for the source file named in the command line, do not look for source
3960 files in the directory containing the source file named in the command line
3961 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3962
3963 @ifclear vms
3964 @item -mbig-switch
3965 @cindex @option{-mbig-switch} (@command{gcc})
3966 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3967 This standard gcc switch causes the compiler to use larger offsets in its
3968 jump table representation for @code{case} statements.
3969 This may result in less efficient code, but is sometimes necessary
3970 (for example on HP-UX targets)
3971 @cindex HP-UX and @option{-mbig-switch} option
3972 in order to compile large and/or nested @code{case} statements.
3973
3974 @item -o @var{file}
3975 @cindex @option{-o} (@code{gcc})
3976 This switch is used in @code{gcc} to redirect the generated object file
3977 and its associated ALI file. Beware of this switch with GNAT, because it may
3978 cause the object file and ALI file to have different names which in turn
3979 may confuse the binder and the linker.
3980 @end ifclear
3981
3982 @item -nostdinc
3983 @cindex @option{-nostdinc} (@command{gcc})
3984 Inhibit the search of the default location for the GNAT Run Time
3985 Library (RTL) source files.
3986
3987 @item -nostdlib
3988 @cindex @option{-nostdlib} (@command{gcc})
3989 Inhibit the search of the default location for the GNAT Run Time
3990 Library (RTL) ALI files.
3991
3992 @ifclear vms
3993 @item -O[@var{n}]
3994 @cindex @option{-O} (@code{gcc})
3995 @var{n} controls the optimization level.
3996
3997 @table @asis
3998 @item n = 0
3999 No optimization, the default setting if no @option{-O} appears
4000
4001 @item n = 1
4002 Normal optimization, the default if you specify @option{-O} without
4003 an operand.
4004
4005 @item n = 2
4006 Extensive optimization
4007
4008 @item n = 3
4009 Extensive optimization with automatic inlining of subprograms not
4010 specified by pragma @code{Inline}. This applies only to
4011 inlining within a unit. For details on control of inlining
4012 see @xref{Subprogram Inlining Control}.
4013 @end table
4014 @end ifclear
4015
4016 @ifset vms
4017 @item  /NOOPTIMIZE
4018 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4019 Equivalent to @option{/OPTIMIZE=NONE}.
4020 This is the default behavior in the absence of an @option{/OPTMIZE}
4021 qualifier.
4022
4023 @item /OPTIMIZE[=(keyword[,...])]
4024 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4025 Selects the level of optimization for your program. The supported
4026 keywords are as follows:
4027 @table @code
4028 @item   ALL
4029 Perform most optimizations, including those that
4030 are expensive.
4031 This is the default if the @option{/OPTMIZE} qualifier is supplied
4032 without keyword options.
4033
4034 @item   NONE
4035 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4036
4037 @item SOME
4038 Perform some optimizations, but omit ones that are costly.
4039
4040 @item   DEVELOPMENT
4041 Same as @code{SOME}.
4042
4043 @item   INLINING
4044 Full optimization, and also attempt automatic inlining of small
4045 subprograms within a unit even when pragma @code{Inline}
4046 is not specified (@pxref{Inlining of Subprograms}).
4047
4048 @item   UNROLL_LOOPS
4049 Try to unroll loops. This keyword may be specified together with
4050 any keyword above other than @code{NONE}. Loop unrolling
4051 usually, but not always, improves the performance of programs.
4052 @end table
4053 @end ifset
4054
4055 @ifclear vms
4056 @item -pass-exit-codes
4057 @cindex @option{-pass-exit-codes} (@code{gcc})
4058 Catch exit codes from the compiler and use the most meaningful as
4059 exit status.
4060 @end ifclear
4061
4062 @item --RTS=@var{rts-path}
4063 @cindex @option{--RTS} (@code{gcc})
4064 Specifies the default location of the runtime library. Same meaning as the
4065 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4066
4067 @item ^-S^/ASM^
4068 @cindex @option{^-S^/ASM^} (@code{gcc})
4069 ^Used in place of @option{-c} to^Used to^
4070 cause the assembler source file to be
4071 generated, using @file{^.s^.S^} as the extension,
4072 instead of the object file.
4073 This may be useful if you need to examine the generated assembly code.
4074
4075 @item ^-v^/VERBOSE^
4076 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4077 Show commands generated by the @code{gcc} driver. Normally used only for
4078 debugging purposes or if you need to be sure what version of the
4079 compiler you are executing.
4080
4081 @ifclear vms
4082 @item -V @var{ver}
4083 @cindex @option{-V} (@code{gcc})
4084 Execute @var{ver} version of the compiler. This is the @code{gcc}
4085 version, not the GNAT version.
4086 @end ifclear
4087
4088 @end table
4089
4090 @ifclear vms
4091 You may combine a sequence of GNAT switches into a single switch. For
4092 example, the combined switch
4093
4094 @cindex Combining GNAT switches
4095 @smallexample
4096 -gnatofi3
4097 @end smallexample
4098
4099 @noindent
4100 is equivalent to specifying the following sequence of switches:
4101
4102 @smallexample
4103 -gnato -gnatf -gnati3
4104 @end smallexample
4105 @end ifclear
4106
4107
4108 @c NEED TO CHECK THIS FOR VMS
4109
4110 @noindent
4111 The following restrictions apply to the combination of switches
4112 in this manner:
4113
4114 @itemize @bullet
4115 @item
4116 The switch @option{-gnatc} if combined with other switches must come
4117 first in the string.
4118
4119 @item
4120 The switch @option{-gnats} if combined with other switches must come
4121 first in the string.
4122
4123 @item
4124 The switches
4125 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4126 may not be combined with any other switches.
4127
4128 @ifclear vms
4129 @item
4130 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4131 switch), then all further characters in the switch are interpreted
4132 as style modifiers (see description of @option{-gnaty}).
4133
4134 @item
4135 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4136 switch), then all further characters in the switch are interpreted
4137 as debug flags (see description of @option{-gnatd}).
4138
4139 @item
4140 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4141 switch), then all further characters in the switch are interpreted
4142 as warning mode modifiers (see description of @option{-gnatw}).
4143
4144 @item
4145 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4146 switch), then all further characters in the switch are interpreted
4147 as validity checking options (see description of @option{-gnatV}).
4148 @end ifclear
4149 @end itemize
4150
4151
4152 @node Output and Error Message Control
4153 @subsection Output and Error Message Control
4154 @findex stderr
4155
4156 @noindent
4157 The standard default format for error messages is called ``brief format''.
4158 Brief format messages are written to @file{stderr} (the standard error
4159 file) and have the following form:
4160
4161 @smallexample
4162 e.adb:3:04: Incorrect spelling of keyword "function"
4163 e.adb:4:20: ";" should be "is"
4164 @end smallexample
4165
4166 @noindent
4167 The first integer after the file name is the line number in the file,
4168 and the second integer is the column number within the line.
4169 @code{glide} can parse the error messages
4170 and point to the referenced character.
4171 The following switches provide control over the error message
4172 format:
4173
4174 @table @option
4175 @c !sort!
4176 @item -gnatv
4177 @cindex @option{-gnatv} (@code{gcc})
4178 @findex stdout
4179 @ifclear vms
4180 The v stands for verbose.
4181 @end ifclear
4182 The effect of this setting is to write long-format error
4183 messages to @file{stdout} (the standard output file.
4184 The same program compiled with the
4185 @option{-gnatv} switch would generate:
4186
4187 @smallexample
4188 @cartouche
4189 3. funcion X (Q : Integer)
4190    |
4191 >>> Incorrect spelling of keyword "function"
4192 4. return Integer;
4193                  |
4194 >>> ";" should be "is"
4195 @end cartouche
4196 @end smallexample
4197
4198 @noindent
4199 The vertical bar indicates the location of the error, and the @samp{>>>}
4200 prefix can be used to search for error messages. When this switch is
4201 used the only source lines output are those with errors.
4202
4203 @item -gnatl
4204 @cindex @option{-gnatl} (@code{gcc})
4205 @ifclear vms
4206 The @code{l} stands for list.
4207 @end ifclear
4208 This switch causes a full listing of
4209 the file to be generated. The output might look as follows:
4210
4211 @smallexample
4212 @cartouche
4213  1. procedure E is
4214  2.    V : Integer;
4215  3.    funcion X (Q : Integer)
4216        |
4217     >>> Incorrect spelling of keyword "function"
4218  4.     return Integer;
4219                       |
4220     >>> ";" should be "is"
4221  5.    begin
4222  6.       return Q + Q;
4223  7.    end;
4224  8. begin
4225  9.    V := X + X;
4226 10.end E;
4227 @end cartouche
4228 @end smallexample
4229
4230 @noindent
4231 @findex stderr
4232 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4233 standard output is redirected, a brief summary is written to
4234 @file{stderr} (standard error) giving the number of error messages and
4235 warning messages generated.
4236
4237 @item -gnatU
4238 @cindex @option{-gnatU} (@code{gcc})
4239 This switch forces all error messages to be preceded by the unique
4240 string ``error:''. This means that error messages take a few more
4241 characters in space, but allows easy searching for and identification
4242 of error messages.
4243
4244 @item -gnatb
4245 @cindex @option{-gnatb} (@code{gcc})
4246 @ifclear vms
4247 The @code{b} stands for brief.
4248 @end ifclear
4249 This switch causes GNAT to generate the
4250 brief format error messages to @file{stderr} (the standard error
4251 file) as well as the verbose
4252 format message or full listing (which as usual is written to
4253 @file{stdout} (the standard output file).
4254
4255 @item -gnatm^^=^@var{n}
4256 @cindex @option{-gnatm} (@code{gcc})
4257 @ifclear vms
4258 The @code{m} stands for maximum.
4259 @end ifclear
4260 @var{n} is a decimal integer in the
4261 range of 1 to 999 and limits the number of error messages to be
4262 generated. For example, using @option{-gnatm2} might yield
4263
4264 @smallexample
4265 e.adb:3:04: Incorrect spelling of keyword "function"
4266 e.adb:5:35: missing ".."
4267 fatal error: maximum errors reached
4268 compilation abandoned
4269 @end smallexample
4270
4271 @item -gnatf
4272 @cindex @option{-gnatf} (@code{gcc})
4273 @cindex Error messages, suppressing
4274 @ifclear vms
4275 The @code{f} stands for full.
4276 @end ifclear
4277 Normally, the compiler suppresses error messages that are likely to be
4278 redundant. This switch causes all error
4279 messages to be generated. In particular, in the case of
4280 references to undefined variables. If a given variable is referenced
4281 several times, the normal format of messages is
4282 @smallexample
4283 e.adb:7:07: "V" is undefined (more references follow)
4284 @end smallexample
4285
4286 @noindent
4287 where the parenthetical comment warns that there are additional
4288 references to the variable @code{V}. Compiling the same program with the
4289 @option{-gnatf} switch yields
4290
4291 @smallexample
4292 e.adb:7:07: "V" is undefined
4293 e.adb:8:07: "V" is undefined
4294 e.adb:8:12: "V" is undefined
4295 e.adb:8:16: "V" is undefined
4296 e.adb:9:07: "V" is undefined
4297 e.adb:9:12: "V" is undefined
4298 @end smallexample
4299
4300 @noindent
4301 The @option{-gnatf} switch also generates additional information for
4302 some error messages.  Some examples are:
4303
4304 @itemize @bullet
4305 @item
4306 Full details on entities not available in high integrity mode
4307 @item
4308 Details on possibly non-portable unchecked conversion
4309 @item
4310 List possible interpretations for ambiguous calls
4311 @item
4312 Additional details on incorrect parameters
4313 @end itemize
4314
4315
4316 @item -gnatq
4317 @cindex @option{-gnatq} (@code{gcc})
4318 @ifclear vms
4319 The @code{q} stands for quit (really ``don't quit'').
4320 @end ifclear
4321 In normal operation mode, the compiler first parses the program and
4322 determines if there are any syntax errors. If there are, appropriate
4323 error messages are generated and compilation is immediately terminated.
4324 This switch tells
4325 GNAT to continue with semantic analysis even if syntax errors have been
4326 found. This may enable the detection of more errors in a single run. On
4327 the other hand, the semantic analyzer is more likely to encounter some
4328 internal fatal error when given a syntactically invalid tree.
4329
4330 @item -gnatQ
4331 @cindex @option{-gnatQ} (@code{gcc})
4332 In normal operation mode, the @file{ALI} file is not generated if any
4333 illegalities are detected in the program. The use of @option{-gnatQ} forces
4334 generation of the @file{ALI} file. This file is marked as being in
4335 error, so it cannot be used for binding purposes, but it does contain
4336 reasonably complete cross-reference information, and thus may be useful
4337 for use by tools (e.g. semantic browsing tools or integrated development
4338 environments) that are driven from the @file{ALI} file. This switch
4339 implies @option{-gnatq}, since the semantic phase must be run to get a
4340 meaningful ALI file.
4341
4342 In addition, if @option{-gnatt} is also specified, then the tree file is
4343 generated even if there are illegalities. It may be useful in this case
4344 to also specify @option{-gnatq} to ensure that full semantic processing
4345 occurs. The resulting tree file can be processed by ASIS, for the purpose
4346 of providing partial information about illegal units, but if the error
4347 causes the tree to be badly malformed, then ASIS may crash during the
4348 analysis.
4349
4350 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4351 being in error, @code{gnatmake} will attempt to recompile the source when it
4352 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4353
4354 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4355 since ALI files are never generated if @option{-gnats} is set.
4356
4357 @end table
4358
4359
4360 @node Warning Message Control
4361 @subsection Warning Message Control
4362 @cindex Warning messages
4363 @noindent
4364 In addition to error messages, which correspond to illegalities as defined
4365 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4366 situations.
4367
4368 First, the compiler considers some constructs suspicious and generates a
4369 warning message to alert you to a possible error. Second, if the
4370 compiler detects a situation that is sure to raise an exception at
4371 run time, it generates a warning message. The following shows an example
4372 of warning messages:
4373 @smallexample
4374 e.adb:4:24: warning: creation of object may raise Storage_Error
4375 e.adb:10:17: warning: static value out of range
4376 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4377 @end smallexample
4378
4379 @noindent
4380 GNAT considers a large number of situations as appropriate
4381 for the generation of warning messages. As always, warnings are not
4382 definite indications of errors. For example, if you do an out-of-range
4383 assignment with the deliberate intention of raising a
4384 @code{Constraint_Error} exception, then the warning that may be
4385 issued does not indicate an error. Some of the situations for which GNAT
4386 issues warnings (at least some of the time) are given in the following
4387 list. This list is not complete, and new warnings are often added to
4388 subsequent versions of GNAT. The list is intended to give a general idea
4389 of the kinds of warnings that are generated.
4390
4391 @itemize @bullet
4392 @item
4393 Possible infinitely recursive calls
4394
4395 @item
4396 Out-of-range values being assigned
4397
4398 @item
4399 Possible order of elaboration problems
4400
4401 @item
4402 Unreachable code
4403
4404 @item
4405 Fixed-point type declarations with a null range
4406
4407 @item
4408 Variables that are never assigned a value
4409
4410 @item
4411 Variables that are referenced before being initialized
4412
4413 @item
4414 Task entries with no corresponding @code{accept} statement
4415
4416 @item
4417 Duplicate accepts for the same task entry in a @code{select}
4418
4419 @item
4420 Objects that take too much storage
4421
4422 @item
4423 Unchecked conversion between types of differing sizes
4424
4425 @item
4426 Missing @code{return} statement along some execution path in a function
4427
4428 @item
4429 Incorrect (unrecognized) pragmas
4430
4431 @item
4432 Incorrect external names
4433
4434 @item
4435 Allocation from empty storage pool
4436
4437 @item
4438 Potentially blocking operation in protected type
4439
4440 @item
4441 Suspicious parenthesization of expressions
4442
4443 @item
4444 Mismatching bounds in an aggregate
4445
4446 @item
4447 Attempt to return local value by reference
4448
4449
4450 @item
4451 Premature instantiation of a generic body
4452
4453 @item
4454 Attempt to pack aliased components
4455
4456 @item
4457 Out of bounds array subscripts
4458
4459 @item
4460 Wrong length on string assignment
4461
4462 @item
4463 Violations of style rules if style checking is enabled
4464
4465 @item
4466 Unused @code{with} clauses
4467
4468 @item
4469 @code{Bit_Order} usage that does not have any effect
4470
4471 @item
4472 @code{Standard.Duration} used to resolve universal fixed expression
4473
4474 @item
4475 Dereference of possibly null value
4476
4477 @item
4478 Declaration that is likely to cause storage error
4479
4480 @item
4481 Internal GNAT unit @code{with}'ed by application unit
4482
4483 @item
4484 Values known to be out of range at compile time
4485
4486 @item
4487 Unreferenced labels and variables
4488
4489 @item
4490 Address overlays that could clobber memory
4491
4492 @item
4493 Unexpected initialization when address clause present
4494
4495 @item
4496 Bad alignment for address clause
4497
4498 @item
4499 Useless type conversions
4500
4501 @item
4502 Redundant assignment statements and other redundant constructs
4503
4504 @item
4505 Useless exception handlers
4506
4507 @item
4508 Accidental hiding of name by child unit
4509
4510
4511 @item
4512 Access before elaboration detected at compile time
4513
4514 @item
4515 A range in a @code{for} loop that is known to be null or might be null
4516
4517 @end itemize
4518
4519 @noindent
4520 The following switches are available to control the handling of
4521 warning messages:
4522
4523 @table @option
4524 @c !sort!
4525 @item -gnatwa
4526 @emph{Activate all optional errors.}
4527 @cindex @option{-gnatwa} (@code{gcc})
4528 This switch activates most optional warning messages, see remaining list
4529 in this section for details on optional warning messages that can be
4530 individually controlled.  The warnings that are not turned on by this
4531 switch are
4532 @option{-gnatwd} (implicit dereferencing),
4533 @option{-gnatwh} (hiding),
4534 and @option{-gnatwl} (elaboration warnings).
4535 All other optional warnings are turned on.
4536
4537 @item -gnatwA
4538 @emph{Suppress all optional errors.}
4539 @cindex @option{-gnatwA} (@code{gcc})
4540 This switch suppresses all optional warning messages, see remaining list
4541 in this section for details on optional warning messages that can be
4542 individually controlled.
4543
4544 @item -gnatwc
4545 @emph{Activate warnings on conditionals.}
4546 @cindex @option{-gnatwc} (@code{gcc})
4547 @cindex Conditionals, constant
4548 This switch activates warnings for conditional expressions used in
4549 tests that are known to be True or False at compile time. The default
4550 is that such warnings are not generated.
4551 Note that this warning does
4552 not get issued for the use of boolean variables or constants whose
4553 values are known at compile time, since this is a standard technique
4554 for conditional compilation in Ada, and this would generate too many
4555 ``false positive'' warnings.
4556 This warning can also be turned on using @option{-gnatwa}.
4557
4558 @item -gnatwC
4559 @emph{Suppress warnings on conditionals.}
4560 @cindex @option{-gnatwC} (@code{gcc})
4561 This switch suppresses warnings for conditional expressions used in
4562 tests that are known to be True or False at compile time.
4563
4564 @item -gnatwd
4565 @emph{Activate warnings on implicit dereferencing.}
4566 @cindex @option{-gnatwd} (@code{gcc})
4567 If this switch is set, then the use of a prefix of an access type
4568 in an indexed component, slice, or selected component without an
4569 explicit @code{.all} will generate a warning. With this warning
4570 enabled, access checks occur only at points where an explicit
4571 @code{.all} appears in the source code (assuming no warnings are
4572 generated as a result of this switch). The default is that such
4573 warnings are not generated.
4574 Note that @option{-gnatwa} does not affect the setting of
4575 this warning option.
4576
4577 @item -gnatwD
4578 @emph{Suppress warnings on implicit dereferencing.}
4579 @cindex @option{-gnatwD} (@code{gcc})
4580 @cindex Implicit dereferencing
4581 @cindex Dereferencing, implicit
4582 This switch suppresses warnings for implicit dereferences in
4583 indexed components, slices, and selected components.
4584
4585 @item -gnatwe
4586 @emph{Treat warnings as errors.}
4587 @cindex @option{-gnatwe} (@code{gcc})
4588 @cindex Warnings, treat as error
4589 This switch causes warning messages to be treated as errors.
4590 The warning string still appears, but the warning messages are counted
4591 as errors, and prevent the generation of an object file.
4592
4593 @item -gnatwf
4594 @emph{Activate warnings on unreferenced formals.}
4595 @cindex @option{-gnatwf} (@code{gcc})
4596 @cindex Formals, unreferenced
4597 This switch causes a warning to be generated if a formal parameter
4598 is not referenced in the body of the subprogram. This warning can
4599 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4600
4601 @item -gnatwF
4602 @emph{Suppress warnings on unreferenced formals.}
4603 @cindex @option{-gnatwF} (@code{gcc})
4604 This switch suppresses warnings for unreferenced formal
4605 parameters. Note that the
4606 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4607 effect of warning on unreferenced entities other than subprogram
4608 formals.
4609
4610 @item -gnatwg
4611 @emph{Activate warnings on unrecognized pragmas.}
4612 @cindex @option{-gnatwg} (@code{gcc})
4613 @cindex Pragmas, unrecognized
4614 This switch causes a warning to be generated if an unrecognized
4615 pragma is encountered. Apart from issuing this warning, the
4616 pragma is ignored and has no effect. This warning can
4617 also be turned on using @option{-gnatwa}. The default
4618 is that such warnings are issued (satisfying the Ada Reference
4619 Manual requirement that such warnings appear).
4620
4621 @item -gnatwG
4622 @emph{Suppress warnings on unrecognized pragmas.}
4623 @cindex @option{-gnatwG} (@code{gcc})
4624 This switch suppresses warnings for unrecognized pragmas.
4625
4626 @item -gnatwh
4627 @emph{Activate warnings on hiding.}
4628 @cindex @option{-gnatwh} (@code{gcc})
4629 @cindex Hiding of Declarations
4630 This switch activates warnings on hiding declarations.
4631 A declaration is considered hiding
4632 if it is for a non-overloadable entity, and it declares an entity with the
4633 same name as some other entity that is directly or use-visible. The default
4634 is that such warnings are not generated.
4635 Note that @option{-gnatwa} does not affect the setting of this warning option.
4636
4637 @item -gnatwH
4638 @emph{Suppress warnings on hiding.}
4639 @cindex @option{-gnatwH} (@code{gcc})
4640 This switch suppresses warnings on hiding declarations.
4641
4642 @item -gnatwi
4643 @emph{Activate warnings on implementation units.}
4644 @cindex @option{-gnatwi} (@code{gcc})
4645 This switch activates warnings for a @code{with} of an internal GNAT
4646 implementation unit, defined as any unit from the @code{Ada},
4647 @code{Interfaces}, @code{GNAT},
4648 ^^@code{DEC},^ or @code{System}
4649 hierarchies that is not
4650 documented in either the Ada Reference Manual or the GNAT
4651 Programmer's Reference Manual. Such units are intended only
4652 for internal implementation purposes and should not be @code{with}'ed
4653 by user programs. The default is that such warnings are generated
4654 This warning can also be turned on using @option{-gnatwa}.
4655
4656 @item -gnatwI
4657 @emph{Disable warnings on implementation units.}
4658 @cindex @option{-gnatwI} (@code{gcc})
4659 This switch disables warnings for a @code{with} of an internal GNAT
4660 implementation unit.
4661
4662 @item -gnatwj
4663 @emph{Activate warnings on obsolescent features (Annex J).}
4664 @cindex @option{-gnatwj} (@code{gcc})
4665 @cindex Features, obsolescent
4666 @cindex Obsolescent features
4667 If this warning option is activated, then warnings are generated for
4668 calls to subprograms marked with @code{pragma Obsolescent} and
4669 for use of features in Annex J of the Ada Reference Manual. In the
4670 case of Annex J, not all features are flagged. In particular use
4671 of the renamed packages (like @code{Text_IO}) and use of package
4672 @code{ASCII} are not flagged, since these are very common and
4673 would generate many annoying positive warnings. The default is that
4674 such warnings are not generated.
4675
4676 @item -gnatwJ
4677 @emph{Suppress warnings on obsolescent features (Annex J).}
4678 @cindex @option{-gnatwJ} (@code{gcc})
4679 This switch disables warnings on use of obsolescent features.
4680
4681 @item -gnatwk
4682 @emph{Activate warnings on variables that could be constants.}
4683 @cindex @option{-gnatwk} (@code{gcc})
4684 This switch activates warnings for variables that are initialized but
4685 never modified, and then could be declared constants.
4686
4687 @item -gnatwK
4688 @emph{Suppress warnings on variables that could be constants.}
4689 @cindex @option{-gnatwK} (@code{gcc})
4690 This switch disables warnings on variables that could be declared constants.
4691
4692 @item -gnatwl
4693 @emph{Activate warnings for missing elaboration pragmas.}
4694 @cindex @option{-gnatwl} (@code{gcc})
4695 @cindex Elaboration, warnings
4696 This switch activates warnings on missing
4697 @code{pragma Elaborate_All} statements.
4698 See the section in this guide on elaboration checking for details on
4699 when such pragma should be used. Warnings are also generated if you
4700 are using the static mode of elaboration, and a @code{pragma Elaborate}
4701 is encountered. The default is that such warnings
4702 are not generated.
4703 This warning is not automatically turned on by the use of @option{-gnatwa}.
4704
4705 @item -gnatwL
4706 @emph{Suppress warnings for missing elaboration pragmas.}
4707 @cindex @option{-gnatwL} (@code{gcc})
4708 This switch suppresses warnings on missing pragma Elaborate_All statements.
4709 See the section in this guide on elaboration checking for details on
4710 when such pragma should be used.
4711
4712 @item -gnatwm
4713 @emph{Activate warnings on modified but unreferenced variables.}
4714 @cindex @option{-gnatwm} (@code{gcc})
4715 This switch activates warnings for variables that are assigned (using
4716 an initialization value or with one or more assignment statements) but
4717 whose value is never read. The warning is suppressed for volatile
4718 variables and also for variables that are renamings of other variables
4719 or for which an address clause is given.
4720 This warning can also be turned on using @option{-gnatwa}.
4721
4722 @item -gnatwM
4723 @emph{Disable warnings on modified but unreferenced variables.}
4724 @cindex @option{-gnatwM} (@code{gcc})
4725 This switch disables warnings for variables that are assigned or
4726 initialized, but never read.
4727
4728 @item -gnatwn
4729 @emph{Set normal warnings mode.}
4730 @cindex @option{-gnatwn} (@code{gcc})
4731 This switch sets normal warning mode, in which enabled warnings are
4732 issued and treated as warnings rather than errors. This is the default
4733 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4734 an explicit @option{-gnatws} or
4735 @option{-gnatwe}. It also cancels the effect of the
4736 implicit @option{-gnatwe} that is activated by the
4737 use of @option{-gnatg}.
4738
4739 @item -gnatwo
4740 @emph{Activate warnings on address clause overlays.}
4741 @cindex @option{-gnatwo} (@code{gcc})
4742 @cindex Address Clauses, warnings
4743 This switch activates warnings for possibly unintended initialization
4744 effects of defining address clauses that cause one variable to overlap
4745 another. The default is that such warnings are generated.
4746 This warning can also be turned on using @option{-gnatwa}.
4747
4748 @item -gnatwO
4749 @emph{Suppress warnings on address clause overlays.}
4750 @cindex @option{-gnatwO} (@code{gcc})
4751 This switch suppresses warnings on possibly unintended initialization
4752 effects of defining address clauses that cause one variable to overlap
4753 another.
4754
4755 @item -gnatwp
4756 @emph{Activate warnings on ineffective pragma Inlines.}
4757 @cindex @option{-gnatwp} (@code{gcc})
4758 @cindex Inlining, warnings
4759 This switch activates warnings for failure of front end inlining
4760 (activated by @option{-gnatN}) to inline a particular call. There are
4761 many reasons for not being able to inline a call, including most
4762 commonly that the call is too complex to inline.
4763 This warning can also be turned on using @option{-gnatwa}.
4764
4765 @item -gnatwP
4766 @emph{Suppress warnings on ineffective pragma Inlines.}
4767 @cindex @option{-gnatwP} (@code{gcc})
4768 This switch suppresses warnings on ineffective pragma Inlines. If the
4769 inlining mechanism cannot inline a call, it will simply ignore the
4770 request silently.
4771
4772 @item -gnatwr
4773 @emph{Activate warnings on redundant constructs.}
4774 @cindex @option{-gnatwr} (@code{gcc})
4775 This switch activates warnings for redundant constructs. The following
4776 is the current list of constructs regarded as redundant:
4777 This warning can also be turned on using @option{-gnatwa}.
4778
4779 @itemize @bullet
4780 @item
4781 Assignment of an item to itself.
4782 @item
4783 Type conversion that converts an expression to its own type.
4784 @item
4785 Use of the attribute @code{Base} where @code{typ'Base} is the same
4786 as @code{typ}.
4787 @item
4788 Use of pragma @code{Pack} when all components are placed by a record
4789 representation clause.
4790 @item
4791 Exception handler containing only a reraise statement (raise with no
4792 operand) which has no effect.
4793 @item
4794 Use of the operator abs on an operand that is known at compile time
4795 to be non-negative
4796 @item
4797 Use of an unnecessary extra level of parentheses (C-style) around conditions
4798 in @code{if} statements, @code{while} statements and @code{exit} statements.
4799 @item
4800 Comparison of boolean expressions to an explicit True value.
4801 @end itemize
4802
4803 @item -gnatwR
4804 @emph{Suppress warnings on redundant constructs.}
4805 @cindex @option{-gnatwR} (@code{gcc})
4806 This switch suppresses warnings for redundant constructs.
4807
4808 @item -gnatws
4809 @emph{Suppress all warnings.}
4810 @cindex @option{-gnatws} (@code{gcc})
4811 This switch completely suppresses the
4812 output of all warning messages from the GNAT front end.
4813 Note that it does not suppress warnings from the @code{gcc} back end.
4814 To suppress these back end warnings as well, use the switch @option{-w}
4815 in addition to @option{-gnatws}.
4816
4817 @item -gnatwu
4818 @emph{Activate warnings on unused entities.}
4819 @cindex @option{-gnatwu} (@code{gcc})
4820 This switch activates warnings to be generated for entities that
4821 are declared but not referenced, and for units that are @code{with}'ed
4822 and not
4823 referenced. In the case of packages, a warning is also generated if
4824 no entities in the package are referenced. This means that if the package
4825 is referenced but the only references are in @code{use}
4826 clauses or @code{renames}
4827 declarations, a warning is still generated. A warning is also generated
4828 for a generic package that is @code{with}'ed but never instantiated.
4829 In the case where a package or subprogram body is compiled, and there
4830 is a @code{with} on the corresponding spec
4831 that is only referenced in the body,
4832 a warning is also generated, noting that the
4833 @code{with} can be moved to the body. The default is that
4834 such warnings are not generated.
4835 This switch also activates warnings on unreferenced formals
4836 (it is includes the effect of @option{-gnatwf}).
4837 This warning can also be turned on using @option{-gnatwa}.
4838
4839 @item -gnatwU
4840 @emph{Suppress warnings on unused entities.}
4841 @cindex @option{-gnatwU} (@code{gcc})
4842 This switch suppresses warnings for unused entities and packages.
4843 It also turns off warnings on unreferenced formals (and thus includes
4844 the effect of @option{-gnatwF}).
4845
4846 @item -gnatwv
4847 @emph{Activate warnings on unassigned variables.}
4848 @cindex @option{-gnatwv} (@code{gcc})
4849 @cindex Unassigned variable warnings
4850 This switch activates warnings for access to variables which
4851 may not be properly initialized. The default is that
4852 such warnings are generated.
4853
4854 @item -gnatwV
4855 @emph{Suppress warnings on unassigned variables.}
4856 @cindex @option{-gnatwV} (@code{gcc})
4857 This switch suppresses warnings for access to variables which
4858 may not be properly initialized.
4859
4860 @item -gnatwx
4861 @emph{Activate warnings on Export/Import pragmas.}
4862 @cindex @option{-gnatwx} (@code{gcc})
4863 @cindex Export/Import pragma warnings
4864 This switch activates warnings on Export/Import pragmas when
4865 the compiler detects a possible conflict between the Ada and
4866 foreign language calling sequences. For example, the use of
4867 default parameters in a convention C procedure is dubious
4868 because the C compiler cannot supply the proper default, so
4869 a warning is issued. The default is that such warnings are
4870 generated.
4871
4872 @item -gnatwX
4873 @emph{Suppress warnings on Export/Import pragmas.}
4874 @cindex @option{-gnatwX} (@code{gcc})
4875 This switch suppresses warnings on Export/Import pragmas.
4876 The sense of this is that you are telling the compiler that
4877 you know what you are doing in writing the pragma, and it
4878 should not complain at you.
4879
4880 @item -gnatwz
4881 @emph{Activate warnings on unchecked conversions.}
4882 @cindex @option{-gnatwz} (@code{gcc})
4883 @cindex Unchecked_Conversion warnings
4884 This switch activates warnings for unchecked conversions
4885 where the types are known at compile time to have different
4886 sizes. The default
4887 is that such warnings are generated.
4888
4889 @item -gnatwZ
4890 @emph{Suppress warnings on unchecked conversions.}
4891 @cindex @option{-gnatwZ} (@code{gcc})
4892 This switch suppresses warnings for unchecked conversions
4893 where the types are known at compile time to have different
4894 sizes.
4895
4896 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4897 @cindex @option{-Wuninitialized}
4898 The warnings controlled by the @option{-gnatw} switch are generated by the
4899 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4900 can provide additional warnings. One such useful warning is provided by
4901 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4902 conjunction with tunrning on optimization mode. This causes the flow
4903 analysis circuits of the back end optimizer to output additional
4904 warnings about uninitialized variables.
4905
4906 @item ^-w^/NO_BACK_END_WARNINGS^
4907 @cindex @option{-w}
4908 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4909 be used in conjunction with @option{-gnatws} to ensure that all warnings
4910 are suppressed during the entire compilation process.
4911
4912 @end table
4913
4914 @noindent
4915 @ifclear vms
4916 A string of warning parameters can be used in the same parameter. For example:
4917
4918 @smallexample
4919 -gnatwaLe
4920 @end smallexample
4921
4922 @noindent
4923 will turn on all optional warnings except for elaboration pragma warnings,
4924 and also specify that warnings should be treated as errors.
4925 @end ifclear
4926 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4927
4928 @table @option
4929 @c !sort!
4930 @item -gnatwC
4931 @item -gnatwD
4932 @item -gnatwF
4933 @item -gnatwg
4934 @item -gnatwH
4935 @item -gnatwi
4936 @item -gnatwJ
4937 @item -gnatwK
4938 @item -gnatwL
4939 @item -gnatwM
4940 @item -gnatwn
4941 @item -gnatwo
4942 @item -gnatwP
4943 @item -gnatwR
4944 @item -gnatwU
4945 @item -gnatwv
4946 @item -gnatwz
4947 @item -gnatwx
4948
4949 @end table
4950
4951
4952 @node Debugging and Assertion Control
4953 @subsection Debugging and Assertion Control
4954
4955 @table @option
4956 @item -gnata
4957 @cindex @option{-gnata} (@code{gcc})
4958 @findex Assert
4959 @findex Debug
4960 @cindex Assertions
4961
4962 @noindent
4963 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4964 are ignored. This switch, where @samp{a} stands for assert, causes
4965 @code{Assert} and @code{Debug} pragmas to be activated.
4966
4967 The pragmas have the form:
4968
4969 @smallexample
4970 @cartouche
4971    @b{pragma} Assert (@var{Boolean-expression} [,
4972                       @var{static-string-expression}])
4973    @b{pragma} Debug (@var{procedure call})
4974 @end cartouche
4975 @end smallexample
4976
4977 @noindent
4978 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4979 If the result is @code{True}, the pragma has no effect (other than
4980 possible side effects from evaluating the expression). If the result is
4981 @code{False}, the exception @code{Assert_Failure} declared in the package
4982 @code{System.Assertions} is
4983 raised (passing @var{static-string-expression}, if present, as the
4984 message associated with the exception). If no string expression is
4985 given the default is a string giving the file name and line number
4986 of the pragma.
4987
4988 The @code{Debug} pragma causes @var{procedure} to be called. Note that
4989 @code{pragma Debug} may appear within a declaration sequence, allowing
4990 debugging procedures to be called between declarations.
4991
4992 @ifset vms
4993 @item /DEBUG[=debug-level]
4994 @itemx  /NODEBUG
4995 Specifies how much debugging information is to be included in
4996 the resulting object file where 'debug-level' is one of the following:
4997 @table @code
4998 @item   TRACEBACK
4999 Include both debugger symbol records and traceback
5000 the object file.
5001 This is the default setting.
5002 @item   ALL
5003 Include both debugger symbol records and traceback in
5004 object file.
5005 @item   NONE
5006 Excludes both debugger symbol records and traceback
5007 the object file. Same as /NODEBUG.
5008 @item   SYMBOLS
5009 Includes only debugger symbol records in the object
5010 file. Note that this doesn't include traceback information.
5011 @end table
5012 @end ifset
5013 @end table
5014
5015 @node Validity Checking
5016 @subsection Validity Checking
5017 @findex Validity Checking
5018
5019 @noindent
5020 The Ada 95 Reference Manual has specific requirements for checking
5021 for invalid values. In particular, RM 13.9.1 requires that the
5022 evaluation of invalid values (for example from unchecked conversions),
5023 not result in erroneous execution. In GNAT, the result of such an
5024 evaluation in normal default mode is to either use the value
5025 unmodified, or to raise Constraint_Error in those cases where use
5026 of the unmodified value would cause erroneous execution. The cases
5027 where unmodified values might lead to erroneous execution are case
5028 statements (where a wild jump might result from an invalid value),
5029 and subscripts on the left hand side (where memory corruption could
5030 occur as a result of an invalid value).
5031
5032 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5033 checking mode.
5034 @ifclear vms
5035 The @code{x} argument is a string of letters that
5036 indicate validity checks that are performed or not performed in addition
5037 to the default checks described above.
5038 @end ifclear
5039 @ifset vms
5040 The options allowed for this qualifier
5041 indicate validity checks that are performed or not performed in addition
5042 to the default checks described above.
5043 @end ifset
5044
5045
5046 @table @option
5047 @c !sort!
5048 @item -gnatVa
5049 @emph{All validity checks.}
5050 @cindex @option{-gnatVa} (@code{gcc})
5051 All validity checks are turned on.
5052 @ifclear vms
5053 That is, @option{-gnatVa} is
5054 equivalent to @option{gnatVcdfimorst}.
5055 @end ifclear
5056
5057 @item -gnatVc
5058 @emph{Validity checks for copies.}
5059 @cindex @option{-gnatVc} (@code{gcc})
5060 The right hand side of assignments, and the initializing values of
5061 object declarations are validity checked.
5062
5063 @item -gnatVd
5064 @emph{Default (RM) validity checks.}
5065 @cindex @option{-gnatVd} (@code{gcc})
5066 Some validity checks are done by default following normal Ada semantics
5067 (RM 13.9.1 (9-11)).
5068 A check is done in case statements that the expression is within the range
5069 of the subtype. If it is not, Constraint_Error is raised.
5070 For assignments to array components, a check is done that the expression used
5071 as index is within the range. If it is not, Constraint_Error is raised.
5072 Both these validity checks may be turned off using switch @option{-gnatVD}.
5073 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5074 switch @option{-gnatVd} will leave the checks turned on.
5075 Switch @option{-gnatVD} should be used only if you are sure that all such
5076 expressions have valid values. If you use this switch and invalid values
5077 are present, then the program is erroneous, and wild jumps or memory
5078 overwriting may occur.
5079
5080 @item -gnatVf
5081 @emph{Validity checks for floating-point values.}
5082 @cindex @option{-gnatVf} (@code{gcc})
5083 In the absence of this switch, validity checking occurs only for discrete
5084 values. If @option{-gnatVf} is specified, then validity checking also applies
5085 for floating-point values, and NaN's and infinities are considered invalid,
5086 as well as out of range values for constrained types. Note that this means
5087 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5088 in which floating-point values are checked depends on the setting of other
5089 options. For example,
5090 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5091 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5092 (the order does not matter) specifies that floating-point parameters of mode
5093 @code{in} should be validity checked.
5094
5095 @item -gnatVi
5096 @emph{Validity checks for @code{in} mode parameters}
5097 @cindex @option{-gnatVi} (@code{gcc})
5098 Arguments for parameters of mode @code{in} are validity checked in function
5099 and procedure calls at the point of call.
5100
5101 @item -gnatVm
5102 @emph{Validity checks for @code{in out} mode parameters.}
5103 @cindex @option{-gnatVm} (@code{gcc})
5104 Arguments for parameters of mode @code{in out} are validity checked in
5105 procedure calls at the point of call. The @code{'m'} here stands for
5106 modify, since this concerns parameters that can be modified by the call.
5107 Note that there is no specific option to test @code{out} parameters,
5108 but any reference within the subprogram will be tested in the usual
5109 manner, and if an invalid value is copied back, any reference to it
5110 will be subject to validity checking.
5111
5112 @item -gnatVn
5113 @emph{No validity checks.}
5114 @cindex @option{-gnatVn} (@code{gcc})
5115 This switch turns off all validity checking, including the default checking
5116 for case statements and left hand side subscripts. Note that the use of
5117 the switch @option{-gnatp} suppresses all run-time checks, including
5118 validity checks, and thus implies @option{-gnatVn}. When this switch
5119 is used, it cancels any other @option{-gnatV} previously issued.
5120
5121 @item -gnatVo
5122 @emph{Validity checks for operator and attribute operands.}
5123 @cindex @option{-gnatVo} (@code{gcc})
5124 Arguments for predefined operators and attributes are validity checked.
5125 This includes all operators in package @code{Standard},
5126 the shift operators defined as intrinsic in package @code{Interfaces}
5127 and operands for attributes such as @code{Pos}. Checks are also made
5128 on individual component values for composite comparisons.
5129
5130 @item -gnatVp
5131 @emph{Validity checks for parameters.}
5132 @cindex @option{-gnatVp} (@code{gcc})
5133 This controls the treatment of parameters within a subprogram (as opposed
5134 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5135 of parameters on a call. If either of these call options is used, then
5136 normally an assumption is made within a subprogram that the input arguments
5137 have been validity checking at the point of call, and do not need checking
5138 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5139 is not made, and parameters are not assumed to be valid, so their validity
5140 will be checked (or rechecked) within the subprogram.
5141
5142 @item -gnatVr
5143 @emph{Validity checks for function returns.}
5144 @cindex @option{-gnatVr} (@code{gcc})
5145 The expression in @code{return} statements in functions is validity
5146 checked.
5147
5148 @item -gnatVs
5149 @emph{Validity checks for subscripts.}
5150 @cindex @option{-gnatVs} (@code{gcc})
5151 All subscripts expressions are checked for validity, whether they appear
5152 on the right side or left side (in default mode only left side subscripts
5153 are validity checked).
5154
5155 @item -gnatVt
5156 @emph{Validity checks for tests.}
5157 @cindex @option{-gnatVt} (@code{gcc})
5158 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5159 statements are checked, as well as guard expressions in entry calls.
5160
5161 @end table
5162
5163 @noindent
5164 The @option{-gnatV} switch may be followed by
5165 ^a string of letters^a list of options^
5166 to turn on a series of validity checking options.
5167 For example,
5168 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5169 specifies that in addition to the default validity checking, copies and
5170 function return expressions are to be validity checked.
5171 In order to make it easier
5172 to specify the desired combination of effects,
5173 @ifclear vms
5174 the upper case letters @code{CDFIMORST} may
5175 be used to turn off the corresponding lower case option.
5176 @end ifclear
5177 @ifset vms
5178 the prefix @code{NO} on an option turns off the corresponding validity
5179 checking:
5180 @itemize @bullet
5181 @item @code{NOCOPIES}
5182 @item @code{NODEFAULT}
5183 @item @code{NOFLOATS}
5184 @item @code{NOIN_PARAMS}
5185 @item @code{NOMOD_PARAMS}
5186 @item @code{NOOPERANDS}
5187 @item @code{NORETURNS}
5188 @item @code{NOSUBSCRIPTS}
5189 @item @code{NOTESTS}
5190 @end itemize
5191 @end ifset
5192 Thus
5193 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5194 turns on all validity checking options except for
5195 checking of @code{@b{in out}} procedure arguments.
5196
5197 The specification of additional validity checking generates extra code (and
5198 in the case of @option{-gnatVa} the code expansion can be substantial.
5199 However, these additional checks can be very useful in detecting
5200 uninitialized variables, incorrect use of unchecked conversion, and other
5201 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5202 is useful in conjunction with the extra validity checking, since this
5203 ensures that wherever possible uninitialized variables have invalid values.
5204
5205 See also the pragma @code{Validity_Checks} which allows modification of
5206 the validity checking mode at the program source level, and also allows for
5207 temporary disabling of validity checks.
5208
5209
5210 @node Style Checking
5211 @subsection Style Checking
5212 @findex Style checking
5213
5214 @noindent
5215 The @option{-gnaty^x^(option,option,...)^} switch
5216 @cindex @option{-gnaty} (@code{gcc})
5217 causes the compiler to
5218 enforce specified style rules. A limited set of style rules has been used
5219 in writing the GNAT sources themselves. This switch allows user programs
5220 to activate all or some of these checks. If the source program fails a
5221 specified style check, an appropriate warning message is given, preceded by
5222 the character sequence ``(style)''.
5223 @ifset vms
5224 @code{(option,option,...)} is a sequence of keywords
5225 @end ifset
5226 @ifclear vms
5227 The string @var{x} is a sequence of letters or digits
5228 @end ifclear
5229 indicating the particular style
5230 checks to be performed. The following checks are defined:
5231
5232 @table @option
5233 @c !sort!
5234 @item 1-9
5235 @emph{Specify indentation level.}
5236 If a digit from 1-9 appears
5237 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5238 then proper indentation is checked, with the digit indicating the
5239 indentation level required.
5240 The general style of required indentation is as specified by
5241 the examples in the Ada Reference Manual. Full line comments must be
5242 aligned with the @code{--} starting on a column that is a multiple of
5243 the alignment level.
5244
5245 @item ^a^ATTRIBUTE^
5246 @emph{Check attribute casing.}
5247 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5248 then attribute names, including the case of keywords such as @code{digits}
5249 used as attributes names, must be written in mixed case, that is, the
5250 initial letter and any letter following an underscore must be uppercase.
5251 All other letters must be lowercase.
5252
5253 @item ^b^BLANKS^
5254 @emph{Blanks not allowed at statement end.}
5255 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5256 trailing blanks are not allowed at the end of statements. The purpose of this
5257 rule, together with h (no horizontal tabs), is to enforce a canonical format
5258 for the use of blanks to separate source tokens.
5259
5260 @item ^c^COMMENTS^
5261 @emph{Check comments.}
5262 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5263 then comments must meet the following set of rules:
5264
5265 @itemize @bullet
5266
5267 @item
5268 The ``@code{--}'' that starts the column must either start in column one,
5269 or else at least one blank must precede this sequence.
5270
5271 @item
5272 Comments that follow other tokens on a line must have at least one blank
5273 following the ``@code{--}'' at the start of the comment.
5274
5275 @item
5276 Full line comments must have two blanks following the ``@code{--}'' that
5277 starts the comment, with the following exceptions.
5278
5279 @item
5280 A line consisting only of the ``@code{--}'' characters, possibly preceded
5281 by blanks is permitted.
5282
5283 @item
5284 A comment starting with ``@code{--x}'' where @code{x} is a special character
5285 is permitted.
5286 This allows proper processing of the output generated by specialized tools
5287 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5288 annotation
5289 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5290 special character is defined as being in one of the ASCII ranges
5291 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5292 Note that this usage is not permitted
5293 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5294
5295 @item
5296 A line consisting entirely of minus signs, possibly preceded by blanks, is
5297 permitted. This allows the construction of box comments where lines of minus
5298 signs are used to form the top and bottom of the box.
5299
5300 @item
5301 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5302 least one blank follows the initial ``@code{--}''. Together with the preceding
5303 rule, this allows the construction of box comments, as shown in the following
5304 example:
5305 @smallexample
5306 ---------------------------
5307 -- This is a box comment --
5308 -- with two text lines.  --
5309 ---------------------------
5310 @end smallexample
5311 @end itemize
5312
5313 @item ^e^END^
5314 @emph{Check end/exit labels.}
5315 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5316 optional labels on @code{end} statements ending subprograms and on
5317 @code{exit} statements exiting named loops, are required to be present.
5318
5319 @item ^f^VTABS^
5320 @emph{No form feeds or vertical tabs.}
5321 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5322 neither form feeds nor vertical tab characters are not permitted
5323 in the source text.
5324
5325 @item ^h^HTABS^
5326 @emph{No horizontal tabs.}
5327 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5328 horizontal tab characters are not permitted in the source text.
5329 Together with the b (no blanks at end of line) check, this
5330 enforces a canonical form for the use of blanks to separate
5331 source tokens.
5332
5333 @item ^i^IF_THEN^
5334 @emph{Check if-then layout.}
5335 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5336 then the keyword @code{then} must appear either on the same
5337 line as corresponding @code{if}, or on a line on its own, lined
5338 up under the @code{if} with at least one non-blank line in between
5339 containing all or part of the condition to be tested.
5340
5341 @item ^k^KEYWORD^
5342 @emph{Check keyword casing.}
5343 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5344 all keywords must be in lower case (with the exception of keywords
5345 such as @code{digits} used as attribute names to which this check
5346 does not apply).
5347
5348 @item ^l^LAYOUT^
5349 @emph{Check layout.}
5350 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5351 layout of statement and declaration constructs must follow the
5352 recommendations in the Ada Reference Manual, as indicated by the
5353 form of the syntax rules. For example an @code{else} keyword must
5354 be lined up with the corresponding @code{if} keyword.
5355
5356 There are two respects in which the style rule enforced by this check
5357 option are more liberal than those in the Ada Reference Manual. First
5358 in the case of record declarations, it is permissible to put the
5359 @code{record} keyword on the same line as the @code{type} keyword, and
5360 then the @code{end} in @code{end record} must line up under @code{type}.
5361 For example, either of the following two layouts is acceptable:
5362
5363 @smallexample @c ada
5364 @cartouche
5365 type q is record
5366    a : integer;
5367    b : integer;
5368 end record;
5369
5370 type q is
5371    record
5372       a : integer;
5373       b : integer;
5374    end record;
5375 @end cartouche
5376 @end smallexample
5377
5378 @noindent
5379 Second, in the case of a block statement, a permitted alternative
5380 is to put the block label on the same line as the @code{declare} or
5381 @code{begin} keyword, and then line the @code{end} keyword up under
5382 the block label. For example both the following are permitted:
5383
5384 @smallexample @c ada
5385 @cartouche
5386 Block : declare
5387    A : Integer := 3;
5388 begin
5389    Proc (A, A);
5390 end Block;
5391
5392 Block :
5393    declare
5394       A : Integer := 3;
5395    begin
5396       Proc (A, A);
5397    end Block;
5398 @end cartouche
5399 @end smallexample
5400
5401 @noindent
5402 The same alternative format is allowed for loops. For example, both of
5403 the following are permitted:
5404
5405 @smallexample @c ada
5406 @cartouche
5407 Clear : while J < 10 loop
5408    A (J) := 0;
5409 end loop Clear;
5410
5411 Clear :
5412    while J < 10 loop
5413       A (J) := 0;
5414    end loop Clear;
5415 @end cartouche
5416 @end smallexample
5417
5418 @item ^m^LINE_LENGTH^
5419 @emph{Check maximum line length.}
5420 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5421 then the length of source lines must not exceed 79 characters, including
5422 any trailing blanks. The value of 79 allows convenient display on an
5423 80 character wide device or window, allowing for possible special
5424 treatment of 80 character lines. Note that this count is of raw
5425 characters in the source text. This means that a tab character counts
5426 as one character in this count and a wide character sequence counts as
5427 several characters (however many are needed in the encoding).
5428
5429 @item ^Mnnn^MAX_LENGTH=nnn^
5430 @emph{Set maximum line length.}
5431 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5432 the string after @option{-gnaty} then the length of lines must not exceed the
5433 given value.
5434
5435 @item ^n^STANDARD_CASING^
5436 @emph{Check casing of entities in Standard.}
5437 If the ^letter n^word STANDARD_CASING^ appears in the string
5438 after @option{-gnaty} then any identifier from Standard must be cased
5439 to match the presentation in the Ada Reference Manual (for example,
5440 @code{Integer} and @code{ASCII.NUL}).
5441
5442 @item ^o^ORDERED_SUBPROGRAMS^
5443 @emph{Check order of subprogram bodies.}
5444 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5445 after @option{-gnaty} then all subprogram bodies in a given scope
5446 (e.g. a package body) must be in alphabetical order. The ordering
5447 rule uses normal Ada rules for comparing strings, ignoring casing
5448 of letters, except that if there is a trailing numeric suffix, then
5449 the value of this suffix is used in the ordering (e.g. Junk2 comes
5450 before Junk10).
5451
5452 @item ^p^PRAGMA^
5453 @emph{Check pragma casing.}
5454 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5455 pragma names must be written in mixed case, that is, the
5456 initial letter and any letter following an underscore must be uppercase.
5457 All other letters must be lowercase.
5458
5459 @item ^r^REFERENCES^
5460 @emph{Check references.}
5461 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5462 then all identifier references must be cased in the same way as the
5463 corresponding declaration. No specific casing style is imposed on
5464 identifiers. The only requirement is for consistency of references
5465 with declarations.
5466
5467 @item ^s^SPECS^
5468 @emph{Check separate specs.}
5469 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5470 separate declarations (``specs'') are required for subprograms (a
5471 body is not allowed to serve as its own declaration). The only
5472 exception is that parameterless library level procedures are
5473 not required to have a separate declaration. This exception covers
5474 the most frequent form of main program procedures.
5475
5476 @item ^t^TOKEN^
5477 @emph{Check token spacing.}
5478 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5479 the following token spacing rules are enforced:
5480
5481 @itemize @bullet
5482
5483 @item
5484 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5485
5486 @item
5487 The token @code{=>} must be surrounded by spaces.
5488
5489 @item
5490 The token @code{<>} must be preceded by a space or a left parenthesis.
5491
5492 @item
5493 Binary operators other than @code{**} must be surrounded by spaces.
5494 There is no restriction on the layout of the @code{**} binary operator.
5495
5496 @item
5497 Colon must be surrounded by spaces.
5498
5499 @item
5500 Colon-equal (assignment, initialization) must be surrounded by spaces.
5501
5502 @item
5503 Comma must be the first non-blank character on the line, or be
5504 immediately preceded by a non-blank character, and must be followed
5505 by a space.
5506
5507 @item
5508 If the token preceding a left parenthesis ends with a letter or digit, then
5509 a space must separate the two tokens.
5510
5511 @item
5512 A right parenthesis must either be the first non-blank character on
5513 a line, or it must be preceded by a non-blank character.
5514
5515 @item
5516 A semicolon must not be preceded by a space, and must not be followed by
5517 a non-blank character.
5518
5519 @item
5520 A unary plus or minus may not be followed by a space.
5521
5522 @item
5523 A vertical bar must be surrounded by spaces.
5524 @end itemize
5525
5526 @noindent
5527 In the above rules, appearing in column one is always permitted, that is,
5528 counts as meeting either a requirement for a required preceding space,
5529 or as meeting a requirement for no preceding space.
5530
5531 Appearing at the end of a line is also always permitted, that is, counts
5532 as meeting either a requirement for a following space, or as meeting
5533 a requirement for no following space.
5534
5535 @end table
5536
5537 @noindent
5538 If any of these style rules is violated, a message is generated giving
5539 details on the violation. The initial characters of such messages are
5540 always ``@code{(style)}''. Note that these messages are treated as warning
5541 messages, so they normally do not prevent the generation of an object
5542 file. The @option{-gnatwe} switch can be used to treat warning messages,
5543 including style messages, as fatal errors.
5544
5545 The switch
5546 @ifclear vms
5547 @option{-gnaty} on its own (that is not
5548 followed by any letters or digits),
5549 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5550 options enabled with the exception of -gnatyo,
5551 @end ifclear
5552 @ifset vms
5553 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5554 the exception of ORDERED_SUBPROGRAMS,
5555 @end ifset
5556 with an indentation level of 3. This is the standard
5557 checking option that is used for the GNAT sources.
5558
5559 The switch
5560 @ifclear vms
5561 @option{-gnatyN}
5562 @end ifclear
5563 @ifset vms
5564 /STYLE_CHECKS=NONE
5565 @end ifset
5566 clears any previously set style checks.
5567
5568 @node Run-Time Checks
5569 @subsection Run-Time Checks
5570 @cindex Division by zero
5571 @cindex Access before elaboration
5572 @cindex Checks, division by zero
5573 @cindex Checks, access before elaboration
5574
5575 @noindent
5576 If you compile with the default options, GNAT will insert many run-time
5577 checks into the compiled code, including code that performs range
5578 checking against constraints, but not arithmetic overflow checking for
5579 integer operations (including division by zero) or checks for access
5580 before elaboration on subprogram calls. All other run-time checks, as
5581 required by the Ada 95 Reference Manual, are generated by default.
5582 The following @code{gcc} switches refine this default behavior:
5583
5584 @table @option
5585 @c !sort!
5586 @item -gnatp
5587 @cindex @option{-gnatp} (@code{gcc})
5588 @cindex Suppressing checks
5589 @cindex Checks, suppressing
5590 @findex Suppress
5591 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5592 had been present in the source. Validity checks are also suppressed (in
5593 other words @option{-gnatp} also implies @option{-gnatVn}.
5594 Use this switch to improve the performance
5595 of the code at the expense of safety in the presence of invalid data or
5596 program bugs.
5597
5598 @item -gnato
5599 @cindex @option{-gnato} (@code{gcc})
5600 @cindex Overflow checks
5601 @cindex Check, overflow
5602 Enables overflow checking for integer operations.
5603 This causes GNAT to generate slower and larger executable
5604 programs by adding code to check for overflow (resulting in raising
5605 @code{Constraint_Error} as required by standard Ada
5606 semantics). These overflow checks correspond to situations in which
5607 the true value of the result of an operation may be outside the base
5608 range of the result type. The following example shows the distinction:
5609
5610 @smallexample @c ada
5611 X1 : Integer := Integer'Last;
5612 X2 : Integer range 1 .. 5 := 5;
5613 X3 : Integer := Integer'Last;
5614 X4 : Integer range 1 .. 5 := 5;
5615 F  : Float := 2.0E+20;
5616 ...
5617 X1 := X1 + 1;
5618 X2 := X2 + 1;
5619 X3 := Integer (F);
5620 X4 := Integer (F);
5621 @end smallexample
5622
5623 @noindent
5624 Here the first addition results in a value that is outside the base range
5625 of Integer, and hence requires an overflow check for detection of the
5626 constraint error. Thus the first assignment to @code{X1} raises a
5627 @code{Constraint_Error} exception only if @option{-gnato} is set.
5628
5629 The second increment operation results in a violation
5630 of the explicit range constraint, and such range checks are always
5631 performed (unless specifically suppressed with a pragma @code{suppress}
5632 or the use of @option{-gnatp}).
5633
5634 The two conversions of @code{F} both result in values that are outside
5635 the base range of type @code{Integer} and thus will raise
5636 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5637 The fact that the result of the second conversion is assigned to
5638 variable @code{X4} with a restricted range is irrelevant, since the problem
5639 is in the conversion, not the assignment.
5640
5641 Basically the rule is that in the default mode (@option{-gnato} not
5642 used), the generated code assures that all integer variables stay
5643 within their declared ranges, or within the base range if there is
5644 no declared range. This prevents any serious problems like indexes
5645 out of range for array operations.
5646
5647 What is not checked in default mode is an overflow that results in
5648 an in-range, but incorrect value. In the above example, the assignments
5649 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5650 range of the target variable, but the result is wrong in the sense that
5651 it is too large to be represented correctly. Typically the assignment
5652 to @code{X1} will result in wrap around to the largest negative number.
5653 The conversions of @code{F} will result in some @code{Integer} value
5654 and if that integer value is out of the @code{X4} range then the
5655 subsequent assignment would generate an exception.
5656
5657 @findex Machine_Overflows
5658 Note that the @option{-gnato} switch does not affect the code generated
5659 for any floating-point operations; it applies only to integer
5660 semantics).
5661 For floating-point, GNAT has the @code{Machine_Overflows}
5662 attribute set to @code{False} and the normal mode of operation is to
5663 generate IEEE NaN and infinite values on overflow or invalid operations
5664 (such as dividing 0.0 by 0.0).
5665
5666 The reason that we distinguish overflow checking from other kinds of
5667 range constraint checking is that a failure of an overflow check can
5668 generate an incorrect value, but cannot cause erroneous behavior. This
5669 is unlike the situation with a constraint check on an array subscript,
5670 where failure to perform the check can result in random memory description,
5671 or the range check on a case statement, where failure to perform the check
5672 can cause a wild jump.
5673
5674 Note again that @option{-gnato} is off by default, so overflow checking is
5675 not performed in default mode. This means that out of the box, with the
5676 default settings, GNAT does not do all the checks expected from the
5677 language description in the Ada Reference Manual. If you want all constraint
5678 checks to be performed, as described in this Manual, then you must
5679 explicitly use the -gnato switch either on the @code{gnatmake} or
5680 @code{gcc} command.
5681
5682 @item -gnatE
5683 @cindex @option{-gnatE} (@code{gcc})
5684 @cindex Elaboration checks
5685 @cindex Check, elaboration
5686 Enables dynamic checks for access-before-elaboration
5687 on subprogram calls and generic instantiations.
5688 For full details of the effect and use of this switch,
5689 @xref{Compiling Using gcc}.
5690 @end table
5691
5692 @findex Unsuppress
5693 @noindent
5694 The setting of these switches only controls the default setting of the
5695 checks. You may modify them using either @code{Suppress} (to remove
5696 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5697 the program source.
5698
5699 @node Stack Overflow Checking
5700 @subsection Stack Overflow Checking
5701 @cindex Stack Overflow Checking
5702 @cindex -fstack-check
5703
5704 @noindent
5705 For most operating systems, @code{gcc} does not perform stack overflow
5706 checking by default. This means that if the main environment task or
5707 some other task exceeds the available stack space, then unpredictable
5708 behavior will occur.
5709
5710 To activate stack checking, compile all units with the gcc option
5711 @option{-fstack-check}. For example:
5712
5713 @smallexample
5714 gcc -c -fstack-check package1.adb
5715 @end smallexample
5716
5717 @noindent
5718 Units compiled with this option will generate extra instructions to check
5719 that any use of the stack (for procedure calls or for declaring local
5720 variables in declare blocks) do not exceed the available stack space.
5721 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5722
5723 For declared tasks, the stack size is always controlled by the size
5724 given in an applicable @code{Storage_Size} pragma (or is set to
5725 the default size if no pragma is used.
5726
5727 For the environment task, the stack size depends on
5728 system defaults and is unknown to the compiler. The stack
5729 may even dynamically grow on some systems, precluding the
5730 normal Ada semantics for stack overflow. In the worst case,
5731 unbounded stack usage, causes unbounded stack expansion
5732 resulting in the system running out of virtual memory.
5733
5734 The stack checking may still work correctly if a fixed
5735 size stack is allocated, but this cannot be guaranteed.
5736 To ensure that a clean exception is signalled for stack
5737 overflow, set the environment variable
5738 @code{GNAT_STACK_LIMIT} to indicate the maximum
5739 stack area that can be used, as in:
5740 @cindex GNAT_STACK_LIMIT
5741
5742 @smallexample
5743 SET GNAT_STACK_LIMIT 1600
5744 @end smallexample
5745
5746 @noindent
5747 The limit is given in kilobytes, so the above declaration would
5748 set the stack limit of the environment task to 1.6 megabytes.
5749 Note that the only purpose of this usage is to limit the amount
5750 of stack used by the environment task. If it is necessary to
5751 increase the amount of stack for the environment task, then this
5752 is an operating systems issue, and must be addressed with the
5753 appropriate operating systems commands.
5754
5755
5756 @node Using gcc for Syntax Checking
5757 @subsection Using @code{gcc} for Syntax Checking
5758 @table @option
5759 @item -gnats
5760 @cindex @option{-gnats} (@code{gcc})
5761 @ifclear vms
5762
5763 @noindent
5764 The @code{s} stands for ``syntax''.
5765 @end ifclear
5766
5767 Run GNAT in syntax checking only mode. For
5768 example, the command
5769
5770 @smallexample
5771 $ gcc -c -gnats x.adb
5772 @end smallexample
5773
5774 @noindent
5775 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5776 series of files in a single command
5777 @ifclear vms
5778 , and can use wild cards to specify such a group of files.
5779 Note that you must specify the @option{-c} (compile
5780 only) flag in addition to the @option{-gnats} flag.
5781 @end ifclear
5782 .
5783 You may use other switches in conjunction with @option{-gnats}. In
5784 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5785 format of any generated error messages.
5786
5787 When the source file is empty or contains only empty lines and/or comments,
5788 the output is a warning:
5789
5790 @smallexample
5791 $ gcc -c -gnats -x ada toto.txt
5792 toto.txt:1:01: warning: empty file, contains no compilation units
5793 $
5794 @end smallexample
5795
5796 Otherwise, the output is simply the error messages, if any. No object file or
5797 ALI file is generated by a syntax-only compilation. Also, no units other
5798 than the one specified are accessed. For example, if a unit @code{X}
5799 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5800 check only mode does not access the source file containing unit
5801 @code{Y}.
5802
5803 @cindex Multiple units, syntax checking
5804 Normally, GNAT allows only a single unit in a source file. However, this
5805 restriction does not apply in syntax-check-only mode, and it is possible
5806 to check a file containing multiple compilation units concatenated
5807 together. This is primarily used by the @code{gnatchop} utility
5808 (@pxref{Renaming Files Using gnatchop}).
5809 @end table
5810
5811
5812 @node Using gcc for Semantic Checking
5813 @subsection Using @code{gcc} for Semantic Checking
5814 @table @option
5815 @item -gnatc
5816 @cindex @option{-gnatc} (@code{gcc})
5817
5818 @ifclear vms
5819 @noindent
5820 The @code{c} stands for ``check''.
5821 @end ifclear
5822 Causes the compiler to operate in semantic check mode,
5823 with full checking for all illegalities specified in the
5824 Ada 95 Reference Manual, but without generation of any object code
5825 (no object file is generated).
5826
5827 Because dependent files must be accessed, you must follow the GNAT
5828 semantic restrictions on file structuring to operate in this mode:
5829
5830 @itemize @bullet
5831 @item
5832 The needed source files must be accessible
5833 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5834
5835 @item
5836 Each file must contain only one compilation unit.
5837
5838 @item
5839 The file name and unit name must match (@pxref{File Naming Rules}).
5840 @end itemize
5841
5842 The output consists of error messages as appropriate. No object file is
5843 generated. An @file{ALI} file is generated for use in the context of
5844 cross-reference tools, but this file is marked as not being suitable
5845 for binding (since no object file is generated).
5846 The checking corresponds exactly to the notion of
5847 legality in the Ada 95 Reference Manual.
5848
5849 Any unit can be compiled in semantics-checking-only mode, including
5850 units that would not normally be compiled (subunits,
5851 and specifications where a separate body is present).
5852 @end table
5853
5854 @node Compiling Ada 83 Programs
5855 @subsection Compiling Ada 83 Programs
5856 @table @option
5857 @cindex Ada 83 compatibility
5858 @item -gnat83
5859 @cindex @option{-gnat83} (@code{gcc})
5860 @cindex ACVC, Ada 83 tests
5861
5862 @noindent
5863 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5864 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5865 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5866 where this can be done easily.
5867 It is not possible to guarantee this switch does a perfect
5868 job; for example, some subtle tests, such as are
5869 found in earlier ACVC tests (and that have been removed from the ACATS suite
5870 for Ada 95), might not compile correctly.
5871 Nevertheless, this switch may be useful in some circumstances, for example
5872 where, due to contractual reasons, legacy code needs to be maintained
5873 using only Ada 83 features.
5874
5875 With few exceptions (most notably the need to use @code{<>} on
5876 @cindex Generic formal parameters
5877 unconstrained generic formal parameters, the use of the new Ada 95
5878 reserved words, and the use of packages
5879 with optional bodies), it is not necessary to use the
5880 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5881 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5882 means that a correct Ada 83 program is usually also a correct Ada 95
5883 program.
5884 For further information, please refer to @ref{Compatibility and Porting Guide}.
5885
5886 @end table
5887
5888 @node Character Set Control
5889 @subsection Character Set Control
5890 @table @option
5891 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5892 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5893
5894 @noindent
5895 Normally GNAT recognizes the Latin-1 character set in source program
5896 identifiers, as described in the Ada 95 Reference Manual.
5897 This switch causes
5898 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5899 single character ^^or word^ indicating the character set, as follows:
5900
5901 @table @code
5902 @item 1
5903 ISO 8859-1 (Latin-1) identifiers
5904
5905 @item 2
5906 ISO 8859-2 (Latin-2) letters allowed in identifiers
5907
5908 @item 3
5909 ISO 8859-3 (Latin-3) letters allowed in identifiers
5910
5911 @item 4
5912 ISO 8859-4 (Latin-4) letters allowed in identifiers
5913
5914 @item 5
5915 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5916
5917 @item 9
5918 ISO 8859-15 (Latin-9) letters allowed in identifiers
5919
5920 @item ^p^PC^
5921 IBM PC letters (code page 437) allowed in identifiers
5922
5923 @item ^8^PC850^
5924 IBM PC letters (code page 850) allowed in identifiers
5925
5926 @item ^f^FULL_UPPER^
5927 Full upper-half codes allowed in identifiers
5928
5929 @item ^n^NO_UPPER^
5930 No upper-half codes allowed in identifiers
5931
5932 @item ^w^WIDE^
5933 Wide-character codes (that is, codes greater than 255)
5934 allowed in identifiers
5935 @end table
5936
5937 @xref{Foreign Language Representation}, for full details on the
5938 implementation of these character sets.
5939
5940 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5941 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5942 Specify the method of encoding for wide characters.
5943 @var{e} is one of the following:
5944
5945 @table @code
5946
5947 @item ^h^HEX^
5948 Hex encoding (brackets coding also recognized)
5949
5950 @item ^u^UPPER^
5951 Upper half encoding (brackets encoding also recognized)
5952
5953 @item ^s^SHIFT_JIS^
5954 Shift/JIS encoding (brackets encoding also recognized)
5955
5956 @item ^e^EUC^
5957 EUC encoding (brackets encoding also recognized)
5958
5959 @item ^8^UTF8^
5960 UTF-8 encoding (brackets encoding also recognized)
5961
5962 @item ^b^BRACKETS^
5963 Brackets encoding only (default value)
5964 @end table
5965 For full details on the these encoding
5966 methods see @xref{Wide Character Encodings}.
5967 Note that brackets coding is always accepted, even if one of the other
5968 options is specified, so for example @option{-gnatW8} specifies that both
5969 brackets and @code{UTF-8} encodings will be recognized. The units that are
5970 with'ed directly or indirectly will be scanned using the specified
5971 representation scheme, and so if one of the non-brackets scheme is
5972 used, it must be used consistently throughout the program. However,
5973 since brackets encoding is always recognized, it may be conveniently
5974 used in standard libraries, allowing these libraries to be used with
5975 any of the available coding schemes.
5976 scheme. If no @option{-gnatW?} parameter is present, then the default
5977 representation is Brackets encoding only.
5978
5979 Note that the wide character representation that is specified (explicitly
5980 or by default) for the main program also acts as the default encoding used
5981 for Wide_Text_IO files if not specifically overridden by a WCEM form
5982 parameter.
5983
5984 @end table
5985 @node File Naming Control
5986 @subsection File Naming Control
5987
5988 @table @option
5989 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5990 @cindex @option{-gnatk} (@code{gcc})
5991 Activates file name ``krunching''. @var{n}, a decimal integer in the range
5992 1-999, indicates the maximum allowable length of a file name (not
5993 including the @file{.ads} or @file{.adb} extension). The default is not
5994 to enable file name krunching.
5995
5996 For the source file naming rules, @xref{File Naming Rules}.
5997 @end table
5998
5999
6000 @node Subprogram Inlining Control
6001 @subsection Subprogram Inlining Control
6002
6003 @table @option
6004 @c !sort!
6005 @item -gnatn
6006 @cindex @option{-gnatn} (@code{gcc})
6007 @ifclear vms
6008 The @code{n} here is intended to suggest the first syllable of the
6009 word ``inline''.
6010 @end ifclear
6011 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6012 inlining to actually occur, optimization must be enabled. To enable
6013 inlining of subprograms specified by pragma @code{Inline},
6014 you must also specify this switch.
6015 In the absence of this switch, GNAT does not attempt
6016 inlining and does not need to access the bodies of
6017 subprograms for which @code{pragma Inline} is specified if they are not
6018 in the current unit.
6019
6020 If you specify this switch the compiler will access these bodies,
6021 creating an extra source dependency for the resulting object file, and
6022 where possible, the call will be inlined.
6023 For further details on when inlining is possible
6024 see @xref{Inlining of Subprograms}.
6025
6026 @item -gnatN
6027 @cindex @option{-gnatN} (@code{gcc})
6028 The front end inlining activated by this switch is generally more extensive,
6029 and quite often more effective than the standard @option{-gnatn} inlining mode.
6030 It will also generate additional dependencies.
6031 Note that
6032 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6033 to specify both options.
6034 @end table
6035
6036 @node Auxiliary Output Control
6037 @subsection Auxiliary Output Control
6038
6039 @table @option
6040 @item -gnatt
6041 @cindex @option{-gnatt} (@code{gcc})
6042 @cindex Writing internal trees
6043 @cindex Internal trees, writing to file
6044 Causes GNAT to write the internal tree for a unit to a file (with the
6045 extension @file{.adt}.
6046 This not normally required, but is used by separate analysis tools.
6047 Typically
6048 these tools do the necessary compilations automatically, so you should
6049 not have to specify this switch in normal operation.
6050
6051 @item -gnatu
6052 @cindex @option{-gnatu} (@code{gcc})
6053 Print a list of units required by this compilation on @file{stdout}.
6054 The listing includes all units on which the unit being compiled depends
6055 either directly or indirectly.
6056
6057 @ifclear vms
6058 @item -pass-exit-codes
6059 @cindex @option{-pass-exit-codes} (@code{gcc})
6060 If this switch is not used, the exit code returned by @code{gcc} when
6061 compiling multiple files indicates whether all source files have
6062 been successfully used to generate object files or not.
6063
6064 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6065 exit status and allows an integrated development environment to better
6066 react to a compilation failure. Those exit status are:
6067
6068 @table @asis
6069 @item 5
6070 There was an error in at least one source file.
6071 @item 3
6072 At least one source file did not generate an object file.
6073 @item 2
6074 The compiler died unexpectedly (internal error for example).
6075 @item 0
6076 An object file has been generated for every source file.
6077 @end table
6078 @end ifclear
6079 @end table
6080
6081 @node Debugging Control
6082 @subsection Debugging Control
6083
6084 @table @option
6085 @c !sort!
6086 @cindex Debugging options
6087 @ifclear vms
6088 @item -gnatd@var{x}
6089 @cindex @option{-gnatd} (@code{gcc})
6090 Activate internal debugging switches. @var{x} is a letter or digit, or
6091 string of letters or digits, which specifies the type of debugging
6092 outputs desired. Normally these are used only for internal development
6093 or system debugging purposes. You can find full documentation for these
6094 switches in the body of the @code{Debug} unit in the compiler source
6095 file @file{debug.adb}.
6096 @end ifclear
6097
6098 @item -gnatG
6099 @cindex @option{-gnatG} (@code{gcc})
6100 This switch causes the compiler to generate auxiliary output containing
6101 a pseudo-source listing of the generated expanded code. Like most Ada
6102 compilers, GNAT works by first transforming the high level Ada code into
6103 lower level constructs. For example, tasking operations are transformed
6104 into calls to the tasking run-time routines. A unique capability of GNAT
6105 is to list this expanded code in a form very close to normal Ada source.
6106 This is very useful in understanding the implications of various Ada
6107 usage on the efficiency of the generated code. There are many cases in
6108 Ada (e.g. the use of controlled types), where simple Ada statements can
6109 generate a lot of run-time code. By using @option{-gnatG} you can identify
6110 these cases, and consider whether it may be desirable to modify the coding
6111 approach to improve efficiency.
6112
6113 The format of the output is very similar to standard Ada source, and is
6114 easily understood by an Ada programmer. The following special syntactic
6115 additions correspond to low level features used in the generated code that
6116 do not have any exact analogies in pure Ada source form. The following
6117 is a partial list of these special constructions. See the specification
6118 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6119
6120 @table @code
6121 @item new @var{xxx} [storage_pool = @var{yyy}]
6122 Shows the storage pool being used for an allocator.
6123
6124 @item at end @var{procedure-name};
6125 Shows the finalization (cleanup) procedure for a scope.
6126
6127 @item (if @var{expr} then @var{expr} else @var{expr})
6128 Conditional expression equivalent to the @code{x?y:z} construction in C.
6129
6130 @item @var{target}^^^(@var{source})
6131 A conversion with floating-point truncation instead of rounding.
6132
6133 @item @var{target}?(@var{source})
6134 A conversion that bypasses normal Ada semantic checking. In particular
6135 enumeration types and fixed-point types are treated simply as integers.
6136
6137 @item @var{target}?^^^(@var{source})
6138 Combines the above two cases.
6139
6140 @item @var{x} #/ @var{y}
6141 @itemx @var{x} #mod @var{y}
6142 @itemx @var{x} #* @var{y}
6143 @itemx @var{x} #rem @var{y}
6144 A division or multiplication of fixed-point values which are treated as
6145 integers without any kind of scaling.
6146
6147 @item free @var{expr} [storage_pool = @var{xxx}]
6148 Shows the storage pool associated with a @code{free} statement.
6149
6150 @item freeze @var{typename} [@var{actions}]
6151 Shows the point at which @var{typename} is frozen, with possible
6152 associated actions to be performed at the freeze point.
6153
6154 @item reference @var{itype}
6155 Reference (and hence definition) to internal type @var{itype}.
6156
6157 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6158 Intrinsic function call.
6159
6160 @item @var{labelname} : label
6161 Declaration of label @var{labelname}.
6162
6163 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6164 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6165 @var{expr}, but handled more efficiently).
6166
6167 @item [constraint_error]
6168 Raise the @code{Constraint_Error} exception.
6169
6170 @item @var{expression}'reference
6171 A pointer to the result of evaluating @var{expression}.
6172
6173 @item @var{target-type}!(@var{source-expression})
6174 An unchecked conversion of @var{source-expression} to @var{target-type}.
6175
6176 @item [@var{numerator}/@var{denominator}]
6177 Used to represent internal real literals (that) have no exact
6178 representation in base 2-16 (for example, the result of compile time
6179 evaluation of the expression 1.0/27.0).
6180 @end table
6181
6182 @item -gnatD
6183 @cindex @option{-gnatD} (@code{gcc})
6184 When used in conjunction with @option{-gnatG}, this switch causes
6185 the expanded source, as described above for
6186 @option{-gnatG} to be written to files with names
6187 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6188 instead of to the standard ooutput file. For
6189 example, if the source file name is @file{hello.adb}, then a file
6190 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6191 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6192 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6193 you to do source level debugging using the generated code which is
6194 sometimes useful for complex code, for example to find out exactly
6195 which part of a complex construction raised an exception. This switch
6196 also suppress generation of cross-reference information (see
6197 @option{-gnatx}) since otherwise the cross-reference information
6198 would refer to the @file{^.dg^.DG^} file, which would cause
6199 confusion since this is not the original source file.
6200
6201 Note that @option{-gnatD} actually implies @option{-gnatG}
6202 automatically, so it is not necessary to give both options.
6203 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6204
6205 @ifclear vms
6206 @item -gnatR[0|1|2|3[s]]
6207 @cindex @option{-gnatR} (@code{gcc})
6208 This switch controls output from the compiler of a listing showing
6209 representation information for declared types and objects. For
6210 @option{-gnatR0}, no information is output (equivalent to omitting
6211 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6212 so @option{-gnatR} with no parameter has the same effect), size and alignment
6213 information is listed for declared array and record types. For
6214 @option{-gnatR2}, size and alignment information is listed for all
6215 expression information for values that are computed at run time for
6216 variant records. These symbolic expressions have a mostly obvious
6217 format with #n being used to represent the value of the n'th
6218 discriminant. See source files @file{repinfo.ads/adb} in the
6219 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6220 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6221 the output is to a file with the name @file{^file.rep^file_REP^} where
6222 file is the name of the corresponding source file.
6223 @end ifclear
6224 @ifset vms
6225 @item /REPRESENTATION_INFO
6226 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6227 This qualifier controls output from the compiler of a listing showing
6228 representation information for declared types and objects. For
6229 @option{/REPRESENTATION_INFO=NONE}, no information is output
6230 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6231 @option{/REPRESENTATION_INFO} without option is equivalent to
6232 @option{/REPRESENTATION_INFO=ARRAYS}.
6233 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6234 information is listed for declared array and record types. For
6235 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6236 is listed for all expression information for values that are computed
6237 at run time for variant records. These symbolic expressions have a mostly
6238 obvious format with #n being used to represent the value of the n'th
6239 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6240 @code{GNAT} sources for full details on the format of
6241 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6242 If _FILE is added at the end of an option
6243 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6244 then the output is to a file with the name @file{file_REP} where
6245 file is the name of the corresponding source file.
6246 @end ifset
6247
6248 @item -gnatS
6249 @cindex @option{-gnatS} (@code{gcc})
6250 The use of the switch @option{-gnatS} for an
6251 Ada compilation will cause the compiler to output a
6252 representation of package Standard in a form very
6253 close to standard Ada. It is not quite possible to
6254 do this and remain entirely Standard (since new
6255 numeric base types cannot be created in standard
6256 Ada), but the output is easily
6257 readable to any Ada programmer, and is useful to
6258 determine the characteristics of target dependent
6259 types in package Standard.
6260
6261 @item -gnatx
6262 @cindex @option{-gnatx} (@code{gcc})
6263 Normally the compiler generates full cross-referencing information in
6264 the @file{ALI} file. This information is used by a number of tools,
6265 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6266 suppresses this information. This saves some space and may slightly
6267 speed up compilation, but means that these tools cannot be used.
6268 @end table
6269
6270 @node Exception Handling Control
6271 @subsection Exception Handling Control
6272
6273 @noindent
6274 GNAT uses two methods for handling exceptions at run-time. The
6275 @code{longjmp/setjmp} method saves the context when entering
6276 a frame with an exception handler. Then when an exception is
6277 raised, the context can be restored immediately, without the
6278 need for tracing stack frames. This method provides very fast
6279 exception propagation, but introduces significant overhead for
6280 the use of exception handlers, even if no exception is raised.
6281
6282 The other approach is called ``zero cost'' exception handling.
6283 With this method, the compiler builds static tables to describe
6284 the exception ranges. No dynamic code is required when entering
6285 a frame containing an exception handler. When an exception is
6286 raised, the tables are used to control a back trace of the
6287 subprogram invocation stack to locate the required exception
6288 handler. This method has considerably poorer performance for
6289 the propagation of exceptions, but there is no overhead for
6290 exception handlers if no exception is raised.
6291
6292 The following switches can be used to control which of the
6293 two exception handling methods is used.
6294
6295 @table @option
6296 @c !sort!
6297
6298 @item -gnatL
6299 @cindex @option{-gnatL} (@code{gcc})
6300 This switch causes the longjmp/setjmp approach to be used
6301 for exception handling. If this is the default mechanism for the
6302 target (see below), then this has no effect. If the default
6303 mechanism for the target is zero cost exceptions, then
6304 this switch can be used to modify this default, but it must be
6305 used for all units in the partition, including all run-time
6306 library units. One way to achieve this is to use the
6307 @option{-a} and @option{-f} switches for @code{gnatmake}.
6308 This option is rarely used. One case in which it may be
6309 advantageous is if you have an application where exception
6310 raising is common and the overall performance of the
6311 application is improved by favoring exception propagation.
6312
6313 @item -gnatZ
6314 @cindex @option{-gnatZ} (@code{gcc})
6315 @cindex Zero Cost Exceptions
6316 This switch causes the zero cost approach to be sed
6317 for exception handling. If this is the default mechanism for the
6318 target (see below), then this has no effect. If the default
6319 mechanism for the target is longjmp/setjmp exceptions, then
6320 this switch can be used to modify this default, but it must be
6321 used for all units in the partition, including all run-time
6322 library units. One way to achieve this is to use the
6323 @option{-a} and @option{-f} switches for @code{gnatmake}.
6324 This option can only be used if the zero cost approach
6325 is available for the target in use (see below).
6326 @end table
6327
6328 @noindent
6329 The @code{longjmp/setjmp} approach is available on all targets, but
6330 the @code{zero cost} approach is only available on selected targets.
6331 To determine whether zero cost exceptions can be used for a
6332 particular target, look at the private part of the file system.ads.
6333 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6334 be True to use the zero cost approach. If both of these switches
6335 are set to False, this means that zero cost exception handling
6336 is not yet available for that target. The switch
6337 @code{ZCX_By_Default} indicates the default approach. If this
6338 switch is set to True, then the @code{zero cost} approach is
6339 used by default.
6340
6341 @node Units to Sources Mapping Files
6342 @subsection Units to Sources Mapping Files
6343
6344 @table @option
6345
6346 @item -gnatem^^=^@var{path}
6347 @cindex @option{-gnatem} (@code{gcc})
6348 A mapping file is a way to communicate to the compiler two mappings:
6349 from unit names to file names (without any directory information) and from
6350 file names to path names (with full directory information). These mappings
6351 are used by the compiler to short-circuit the path search.
6352
6353 The use of mapping files is not required for correct operation of the
6354 compiler, but mapping files can improve efficiency, particularly when
6355 sources are read over a slow network connection. In normal operation,
6356 you need not be concerned with the format or use of mapping files,
6357 and the @option{-gnatem} switch is not a switch that you would use
6358 explicitly. it is intended only for use by automatic tools such as
6359 @code{gnatmake} running under the project file facility. The
6360 description here of the format of mapping files is provided
6361 for completeness and for possible use by other tools.
6362
6363 A mapping file is a sequence of sets of three lines. In each set,
6364 the first line is the unit name, in lower case, with ``@code{%s}''
6365 appended for
6366 specifications and ``@code{%b}'' appended for bodies; the second line is the
6367 file name; and the third line is the path name.
6368
6369 Example:
6370 @smallexample
6371    main%b
6372    main.2.ada
6373    /gnat/project1/sources/main.2.ada
6374 @end smallexample
6375
6376 When the switch @option{-gnatem} is specified, the compiler will create
6377 in memory the two mappings from the specified file. If there is any problem
6378 (non existent file, truncated file or duplicate entries), no mapping
6379 will be created.
6380
6381 Several @option{-gnatem} switches may be specified; however, only the last
6382 one on the command line will be taken into account.
6383
6384 When using a project file, @code{gnatmake} create a temporary mapping file
6385 and communicates it to the compiler using this switch.
6386
6387 @end table
6388
6389
6390 @node Integrated Preprocessing
6391 @subsection Integrated Preprocessing
6392
6393 @noindent
6394 GNAT sources may be preprocessed immediately before compilation; the actual
6395 text of the source is not the text of the source file, but is derived from it
6396 through a process called preprocessing. Integrated preprocessing is specified
6397 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6398 indicates, through a text file, the preprocessing data to be used.
6399 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6400
6401 @noindent
6402 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6403 used when Integrated Preprocessing is used. The reason is that preprocessing
6404 with another Preprocessing Data file without changing the sources will
6405 not trigger recompilation without this switch.
6406
6407 @noindent
6408 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6409 always trigger recompilation for sources that are preprocessed,
6410 because @code{gnatmake} cannot compute the checksum of the source after
6411 preprocessing.
6412
6413 @noindent
6414 The actual preprocessing function is described in details in section
6415 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6416 preprocessing is triggered and parameterized.
6417
6418 @table @code
6419
6420 @item -gnatep=@var{file}
6421 @cindex @option{-gnatep} (@code{gcc})
6422 This switch indicates to the compiler the file name (without directory
6423 information) of the preprocessor data file to use. The preprocessor data file
6424 should be found in the source directories.
6425
6426 @noindent
6427 A preprocessing data file is a text file with significant lines indicating
6428 how should be preprocessed either a specific source or all sources not
6429 mentioned in other lines. A significant line is a non empty, non comment line.
6430 Comments are similar to Ada comments.
6431
6432 @noindent
6433 Each significant line starts with either a literal string or the character '*'.
6434 A literal string is the file name (without directory information) of the source
6435 to preprocess. A character '*' indicates the preprocessing for all the sources
6436 that are not specified explicitly on other lines (order of the lines is not
6437 significant). It is an error to have two lines with the same file name or two
6438 lines starting with the character '*'.
6439
6440 @noindent
6441 After the file name or the character '*', another optional literal string
6442 indicating the file name of the definition file to be used for preprocessing.
6443 (see @ref{Form of Definitions File}. The definition files are found by the
6444 compiler in one of the source directories. In some cases, when compiling
6445 a source in a directory other than the current directory, if the definition
6446 file is in the current directory, it may be necessary to add the current
6447 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6448 the compiler would not find the definition file.
6449
6450 @noindent
6451 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6452 be found. Those ^switches^switches^ are:
6453
6454 @table @code
6455
6456 @item -b
6457 Causes both preprocessor lines and the lines deleted by
6458 preprocessing to be replaced by blank lines, preserving the line number.
6459 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6460 it cancels the effect of @option{-c}.
6461
6462 @item -c
6463 Causes both preprocessor lines and the lines deleted
6464 by preprocessing to be retained as comments marked
6465 with the special string ``@code{--! }''.
6466
6467 @item -Dsymbol=value
6468 Define or redefine a symbol, associated with value. A symbol is an Ada
6469 identifier, or an Ada reserved word, with the exception of @code{if},
6470 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6471 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6472 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6473 same name defined in a definition file.
6474
6475 @item -s
6476 Causes a sorted list of symbol names and values to be
6477 listed on the standard output file.
6478
6479 @item -u
6480 Causes undefined symbols to be treated as having the value @code{FALSE}
6481 in the context
6482 of a preprocessor test. In the absence of this option, an undefined symbol in
6483 a @code{#if} or @code{#elsif} test will be treated as an error.
6484
6485 @end table
6486
6487 @noindent
6488 Examples of valid lines in a preprocessor data file:
6489
6490 @smallexample
6491   "toto.adb"  "prep.def" -u
6492   --  preprocess "toto.adb", using definition file "prep.def",
6493   --  undefined symbol are False.
6494
6495   * -c -DVERSION=V101
6496   --  preprocess all other sources without a definition file;
6497   --  suppressed lined are commented; symbol VERSION has the value V101.
6498
6499   "titi.adb" "prep2.def" -s
6500   --  preprocess "titi.adb", using definition file "prep2.def";
6501   --  list all symbols with their values.
6502 @end smallexample
6503
6504 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6505 @cindex @option{-gnateD} (@code{gcc})
6506 Define or redefine a preprocessing symbol, associated with value. If no value
6507 is given on the command line, then the value of the symbol is @code{True}.
6508 A symbol is an identifier, following normal Ada (case-insensitive)
6509 rules for its syntax, and value is any sequence (including an empty sequence)
6510 of characters from the set (letters, digits, period, underline).
6511 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6512 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6513
6514 @noindent
6515 A symbol declared with this ^switch^switch^ on the command line replaces a
6516 symbol with the same name either in a definition file or specified with a
6517 ^switch^switch^ -D in the preprocessor data file.
6518
6519 @noindent
6520 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6521
6522 @end table
6523
6524 @ifset vms
6525 @node Return Codes
6526 @subsection Return Codes
6527 @cindex Return Codes
6528 @cindex @option{/RETURN_CODES=VMS}
6529
6530 @noindent
6531 On VMS, GNAT compiled programs return POSIX-style codes by default,
6532 e.g. @option{/RETURN_CODES=POSIX}.
6533
6534 To enable VMS style return codes, GNAT LINK with the option
6535 @option{/RETURN_CODES=VMS}. For example:
6536
6537 @smallexample
6538 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6539 @end smallexample
6540
6541 @noindent
6542 Programs built with /RETURN_CODES=VMS are suitable to be called in
6543 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6544 are suitable for spawning with appropriate GNAT RTL routines.
6545
6546 @end ifset
6547
6548
6549 @node Search Paths and the Run-Time Library (RTL)
6550 @section Search Paths and the Run-Time Library (RTL)
6551
6552 @noindent
6553 With the GNAT source-based library system, the compiler must be able to
6554 find source files for units that are needed by the unit being compiled.
6555 Search paths are used to guide this process.
6556
6557 The compiler compiles one source file whose name must be given
6558 explicitly on the command line. In other words, no searching is done
6559 for this file. To find all other source files that are needed (the most
6560 common being the specs of units), the compiler examines the following
6561 directories, in the following order:
6562
6563 @enumerate
6564 @item
6565 The directory containing the source file of the main unit being compiled
6566 (the file name on the command line).
6567
6568 @item
6569 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6570 @code{gcc} command line, in the order given.
6571
6572 @item
6573 @findex ADA_INCLUDE_PATH
6574 Each of the directories listed in the value of the
6575 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6576 @ifclear vms
6577 Construct this value
6578 exactly as the @code{PATH} environment variable: a list of directory
6579 names separated by colons (semicolons when working with the NT version).
6580 @end ifclear
6581 @ifset vms
6582 Normally, define this value as a logical name containing a comma separated
6583 list of directory names.
6584
6585 This variable can also be defined by means of an environment string
6586 (an argument to the DEC C exec* set of functions).
6587
6588 Logical Name:
6589 @smallexample
6590 DEFINE ANOTHER_PATH FOO:[BAG]
6591 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6592 @end smallexample
6593
6594 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6595 first, followed by the standard Ada 95
6596 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6597 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6598 (Text_IO, Sequential_IO, etc)
6599 instead of the Ada95 packages. Thus, in order to get the Ada 95
6600 packages by default, ADA_INCLUDE_PATH must be redefined.
6601 @end ifset
6602
6603 @item
6604 @findex ADA_PRJ_INCLUDE_FILE
6605 Each of the directories listed in the text file whose name is given
6606 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6607
6608 @noindent
6609 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6610 driver when project files are used. It should not normally be set
6611 by other means.
6612
6613 @item
6614 The content of the @file{ada_source_path} file which is part of the GNAT
6615 installation tree and is used to store standard libraries such as the
6616 GNAT Run Time Library (RTL) source files.
6617 @ifclear vms
6618 @ref{Installing an Ada Library}
6619 @end ifclear
6620 @end enumerate
6621
6622 @noindent
6623 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6624 inhibits the use of the directory
6625 containing the source file named in the command line. You can still
6626 have this directory on your search path, but in this case it must be
6627 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6628
6629 Specifying the switch @option{-nostdinc}
6630 inhibits the search of the default location for the GNAT Run Time
6631 Library (RTL) source files.
6632
6633 The compiler outputs its object files and ALI files in the current
6634 working directory.
6635 @ifclear vms
6636 Caution: The object file can be redirected with the @option{-o} switch;
6637 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6638 so the @file{ALI} file will not go to the right place. Therefore, you should
6639 avoid using the @option{-o} switch.
6640 @end ifclear
6641
6642 @findex System.IO
6643 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6644 children make up the GNAT RTL, together with the simple @code{System.IO}
6645 package used in the @code{"Hello World"} example. The sources for these units
6646 are needed by the compiler and are kept together in one directory. Not
6647 all of the bodies are needed, but all of the sources are kept together
6648 anyway. In a normal installation, you need not specify these directory
6649 names when compiling or binding. Either the environment variables or
6650 the built-in defaults cause these files to be found.
6651
6652 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6653 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6654 consisting of child units of @code{GNAT}. This is a collection of generally
6655 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6656 further details.
6657
6658 Besides simplifying access to the RTL, a major use of search paths is
6659 in compiling sources from multiple directories. This can make
6660 development environments much more flexible.
6661
6662
6663 @node Order of Compilation Issues
6664 @section Order of Compilation Issues
6665
6666 @noindent
6667 If, in our earlier example, there was a spec for the @code{hello}
6668 procedure, it would be contained in the file @file{hello.ads}; yet this
6669 file would not have to be explicitly compiled. This is the result of the
6670 model we chose to implement library management. Some of the consequences
6671 of this model are as follows:
6672
6673 @itemize @bullet
6674 @item
6675 There is no point in compiling specs (except for package
6676 specs with no bodies) because these are compiled as needed by clients. If
6677 you attempt a useless compilation, you will receive an error message.
6678 It is also useless to compile subunits because they are compiled as needed
6679 by the parent.
6680
6681 @item
6682 There are no order of compilation requirements: performing a
6683 compilation never obsoletes anything. The only way you can obsolete
6684 something and require recompilations is to modify one of the
6685 source files on which it depends.
6686
6687 @item
6688 There is no library as such, apart from the ALI files
6689 (@pxref{The Ada Library Information Files}, for information on the format
6690 of these files). For now we find it convenient to create separate ALI files,
6691 but eventually the information therein may be incorporated into the object
6692 file directly.
6693
6694 @item
6695 When you compile a unit, the source files for the specs of all units
6696 that it @code{with}'s, all its subunits, and the bodies of any generics it
6697 instantiates must be available (reachable by the search-paths mechanism
6698 described above), or you will receive a fatal error message.
6699 @end itemize
6700
6701 @node Examples
6702 @section Examples
6703
6704 @noindent
6705 The following are some typical Ada compilation command line examples:
6706
6707 @table @code
6708 @item $ gcc -c xyz.adb
6709 Compile body in file @file{xyz.adb} with all default options.
6710
6711 @ifclear vms
6712 @item $ gcc -c -O2 -gnata xyz-def.adb
6713 @end ifclear
6714 @ifset vms
6715 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6716 @end ifset
6717
6718 Compile the child unit package in file @file{xyz-def.adb} with extensive
6719 optimizations, and pragma @code{Assert}/@code{Debug} statements
6720 enabled.
6721
6722 @item $ gcc -c -gnatc abc-def.adb
6723 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6724 mode.
6725 @end table
6726
6727 @node Binding Using gnatbind
6728 @chapter Binding Using @code{gnatbind}
6729 @findex gnatbind
6730
6731 @menu
6732 * Running gnatbind::
6733 * Switches for gnatbind::
6734 * Command-Line Access::
6735 * Search Paths for gnatbind::
6736 * Examples of gnatbind Usage::
6737 @end menu
6738
6739 @noindent
6740 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6741 to bind compiled GNAT objects. The @code{gnatbind} program performs
6742 four separate functions:
6743
6744 @enumerate
6745 @item
6746 Checks that a program is consistent, in accordance with the rules in
6747 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6748 messages are generated if a program uses inconsistent versions of a
6749 given unit.
6750
6751 @item
6752 Checks that an acceptable order of elaboration exists for the program
6753 and issues an error message if it cannot find an order of elaboration
6754 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6755
6756 @item
6757 Generates a main program incorporating the given elaboration order.
6758 This program is a small Ada package (body and spec) that
6759 must be subsequently compiled
6760 using the GNAT compiler. The necessary compilation step is usually
6761 performed automatically by @code{gnatlink}. The two most important
6762 functions of this program
6763 are to call the elaboration routines of units in an appropriate order
6764 and to call the main program.
6765
6766 @item
6767 Determines the set of object files required by the given main program.
6768 This information is output in the forms of comments in the generated program,
6769 to be read by the @code{gnatlink} utility used to link the Ada application.
6770 @end enumerate
6771
6772
6773 @node Running gnatbind
6774 @section Running @code{gnatbind}
6775
6776 @noindent
6777 The form of the @code{gnatbind} command is
6778
6779 @smallexample
6780 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6781 @end smallexample
6782
6783 @noindent
6784 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6785 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6786 package in two files whose names are
6787 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6788 For example, if given the
6789 parameter @file{hello.ali}, for a main program contained in file
6790 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6791 and @file{b~hello.adb}.
6792
6793 When doing consistency checking, the binder takes into consideration
6794 any source files it can locate. For example, if the binder determines
6795 that the given main program requires the package @code{Pack}, whose
6796 @file{.ALI}
6797 file is @file{pack.ali} and whose corresponding source spec file is
6798 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6799 (using the same search path conventions as previously described for the
6800 @code{gcc} command). If it can locate this source file, it checks that
6801 the time stamps
6802 or source checksums of the source and its references to in @file{ALI} files
6803 match. In other words, any @file{ALI} files that mentions this spec must have
6804 resulted from compiling this version of the source file (or in the case
6805 where the source checksums match, a version close enough that the
6806 difference does not matter).
6807
6808 @cindex Source files, use by binder
6809 The effect of this consistency checking, which includes source files, is
6810 that the binder ensures that the program is consistent with the latest
6811 version of the source files that can be located at bind time. Editing a
6812 source file without compiling files that depend on the source file cause
6813 error messages to be generated by the binder.
6814
6815 For example, suppose you have a main program @file{hello.adb} and a
6816 package @code{P}, from file @file{p.ads} and you perform the following
6817 steps:
6818
6819 @enumerate
6820 @item
6821 Enter @code{gcc -c hello.adb} to compile the main program.
6822
6823 @item
6824 Enter @code{gcc -c p.ads} to compile package @code{P}.
6825
6826 @item
6827 Edit file @file{p.ads}.
6828
6829 @item
6830 Enter @code{gnatbind hello}.
6831 @end enumerate
6832
6833 @noindent
6834 At this point, the file @file{p.ali} contains an out-of-date time stamp
6835 because the file @file{p.ads} has been edited. The attempt at binding
6836 fails, and the binder generates the following error messages:
6837
6838 @smallexample
6839 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6840 error: "p.ads" has been modified and must be recompiled
6841 @end smallexample
6842
6843 @noindent
6844 Now both files must be recompiled as indicated, and then the bind can
6845 succeed, generating a main program. You need not normally be concerned
6846 with the contents of this file, but for reference purposes a sample
6847 binder output file is given in @ref{Example of Binder Output File}.
6848
6849 In most normal usage, the default mode of @command{gnatbind} which is to
6850 generate the main package in Ada, as described in the previous section.
6851 In particular, this means that any Ada programmer can read and understand
6852 the generated main program. It can also be debugged just like any other
6853 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6854 @command{gnatbind} and @command{gnatlink}.
6855
6856 However for some purposes it may be convenient to generate the main
6857 program in C rather than Ada. This may for example be helpful when you
6858 are generating a mixed language program with the main program in C. The
6859 GNAT compiler itself is an example.
6860 The use of the @option{^-C^/BIND_FILE=C^} switch
6861 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6862 be generated in C (and compiled using the gnu C compiler).
6863
6864
6865 @node Switches for gnatbind
6866 @section Switches for @command{gnatbind}
6867
6868 @noindent
6869 The following switches are available with @code{gnatbind}; details will
6870 be presented in subsequent sections.
6871
6872 @menu
6873 * Consistency-Checking Modes::
6874 * Binder Error Message Control::
6875 * Elaboration Control::
6876 * Output Control::
6877 * Binding with Non-Ada Main Programs::
6878 * Binding Programs with No Main Subprogram::
6879 @end menu
6880
6881 @table @option
6882 @c !sort!
6883 @item ^-aO^/OBJECT_SEARCH^
6884 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6885 Specify directory to be searched for ALI files.
6886
6887 @item ^-aI^/SOURCE_SEARCH^
6888 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6889 Specify directory to be searched for source file.
6890
6891 @item ^-A^/BIND_FILE=ADA^
6892 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6893 Generate binder program in Ada (default)
6894
6895 @item ^-b^/REPORT_ERRORS=BRIEF^
6896 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6897 Generate brief messages to @file{stderr} even if verbose mode set.
6898
6899 @item ^-c^/NOOUTPUT^
6900 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6901 Check only, no generation of binder output file.
6902
6903 @item ^-C^/BIND_FILE=C^
6904 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6905 Generate binder program in C
6906
6907 @item ^-e^/ELABORATION_DEPENDENCIES^
6908 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6909 Output complete list of elaboration-order dependencies.
6910
6911 @item ^-E^/STORE_TRACEBACKS^
6912 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6913 Store tracebacks in exception occurrences when the target supports it.
6914 This is the default with the zero cost exception mechanism.
6915 @ignore
6916 @c The following may get moved to an appendix
6917 This option is currently supported on the following targets:
6918 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6919 @end ignore
6920 See also the packages @code{GNAT.Traceback} and
6921 @code{GNAT.Traceback.Symbolic} for more information.
6922 @ifclear vms
6923 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6924 @code{gcc} option.
6925 @end ifclear vms
6926
6927 @item ^-F^/FORCE_ELABS_FLAGS^
6928 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6929 Force the checks of elaboration flags. @command{gnatbind} does not normally
6930 generate checks of elaboration flags for the main executable, except when
6931 a Stand-Alone Library is used. However, there are cases when this cannot be
6932 detected by gnatbind. An example is importing an interface of a Stand-Alone
6933 Library through a pragma Import and only specifying through a linker switch
6934 this Stand-Alone Library. This switch is used to guarantee that elaboration
6935 flag checks are generated.
6936
6937 @item ^-h^/HELP^
6938 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6939 Output usage (help) information
6940
6941 @item ^-I^/SEARCH^
6942 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6943 Specify directory to be searched for source and ALI files.
6944
6945 @item ^-I-^/NOCURRENT_DIRECTORY^
6946 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6947 Do not look for sources in the current directory where @code{gnatbind} was
6948 invoked, and do not look for ALI files in the directory containing the
6949 ALI file named in the @code{gnatbind} command line.
6950
6951 @item ^-l^/ORDER_OF_ELABORATION^
6952 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
6953 Output chosen elaboration order.
6954
6955 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
6956 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
6957 Binds the units for library building. In this case the adainit and
6958 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6959 are renamed to ^xxxinit^XXXINIT^ and
6960 ^xxxfinal^XXXFINAL^.
6961 Implies ^-n^/NOCOMPILE^.
6962 @ifclear vms
6963 (@pxref{GNAT and Libraries}, for more details.)
6964 @end ifclear
6965 @ifset vms
6966 On OpenVMS, these init and final procedures are exported in uppercase
6967 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
6968 the init procedure will be "TOTOINIT" and the exported name of the final
6969 procedure will be "TOTOFINAL".
6970 @end ifset
6971
6972 @item ^-Mxyz^/RENAME_MAIN=xyz^
6973 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
6974 Rename generated main program from main to xyz
6975
6976 @item ^-m^/ERROR_LIMIT=^@var{n}
6977 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
6978 Limit number of detected errors to @var{n}, where @var{n} is
6979 in the range 1..999_999. The default value if no switch is
6980 given is 9999. Binding is terminated if the limit is exceeded.
6981 @ifset unw
6982 Furthermore, under Windows, the sources pointed to by the libraries path
6983 set in the registry are not searched for.
6984 @end ifset
6985
6986 @item ^-n^/NOMAIN^
6987 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
6988 No main program.
6989
6990 @item -nostdinc
6991 @cindex @option{-nostdinc} (@command{gnatbind})
6992 Do not look for sources in the system default directory.
6993
6994 @item -nostdlib
6995 @cindex @option{-nostdlib} (@command{gnatbind})
6996 Do not look for library files in the system default directory.
6997
6998 @item --RTS=@var{rts-path}
6999 @cindex @option{--RTS} (@code{gnatbind})
7000 Specifies the default location of the runtime library. Same meaning as the
7001 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7002
7003 @item ^-o ^/OUTPUT=^@var{file}
7004 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7005 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7006 Note that if this option is used, then linking must be done manually,
7007 gnatlink cannot be used.
7008
7009 @item ^-O^/OBJECT_LIST^
7010 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7011 Output object list.
7012
7013 @item ^-p^/PESSIMISTIC_ELABORATION^
7014 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7015 Pessimistic (worst-case) elaboration order
7016
7017 @item ^-s^/READ_SOURCES=ALL^
7018 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7019 Require all source files to be present.
7020
7021 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7022 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7023 Specifies the value to be used when detecting uninitialized scalar
7024 objects with pragma Initialize_Scalars.
7025 The @var{xxx} ^string specified with the switch^option^ may be either
7026 @itemize @bullet
7027 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7028 @item ``@option{^lo^LOW^}'' for the lowest possible value
7029 possible, and the low
7030 @item ``@option{^hi^HIGH^}'' for the highest possible value
7031 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7032 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7033 @end itemize
7034
7035 In addition, you can specify @option{-Sev} to indicate that the value is
7036 to be set at run time. In this case, the program will look for an environment
7037 @cindex GNAT_INIT_SCALARS
7038 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7039 of @option{in/lo/hi/xx} with the same meanings as above.
7040 If no environment variable is found, or if it does not have a valid value,
7041 then the default is @option{in} (invalid values).
7042
7043 @ifclear vms
7044 @item -static
7045 @cindex @option{-static} (@code{gnatbind})
7046 Link against a static GNAT run time.
7047
7048 @item -shared
7049 @cindex @option{-shared} (@code{gnatbind})
7050 Link against a shared GNAT run time when available.
7051 @end ifclear
7052
7053 @item ^-t^/NOTIME_STAMP_CHECK^
7054 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7055 Tolerate time stamp and other consistency errors
7056
7057 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7058 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7059 Set the time slice value to @var{n} milliseconds. If the system supports
7060 the specification of a specific time slice value, then the indicated value
7061 is used. If the system does not support specific time slice values, but
7062 does support some general notion of round-robin scheduling, then any
7063 non-zero value will activate round-robin scheduling.
7064
7065 A value of zero is treated specially. It turns off time
7066 slicing, and in addition, indicates to the tasking run time that the
7067 semantics should match as closely as possible the Annex D
7068 requirements of the Ada RM, and in particular sets the default
7069 scheduling policy to @code{FIFO_Within_Priorities}.
7070
7071 @item ^-v^/REPORT_ERRORS=VERBOSE^
7072 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7073 Verbose mode. Write error messages, header, summary output to
7074 @file{stdout}.
7075
7076 @ifclear vms
7077 @item -w@var{x}
7078 @cindex @option{-w} (@code{gnatbind})
7079 Warning mode (@var{x}=s/e for suppress/treat as error)
7080 @end ifclear
7081
7082 @ifset vms
7083 @item /WARNINGS=NORMAL
7084 @cindex @option{/WARNINGS} (@code{gnatbind})
7085 Normal warnings mode. Warnings are issued but ignored
7086
7087 @item /WARNINGS=SUPPRESS
7088 @cindex @option{/WARNINGS} (@code{gnatbind})
7089 All warning messages are suppressed
7090
7091 @item /WARNINGS=ERROR
7092 @cindex @option{/WARNINGS} (@code{gnatbind})
7093 Warning messages are treated as fatal errors
7094 @end ifset
7095
7096 @item ^-x^/READ_SOURCES=NONE^
7097 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7098 Exclude source files (check object consistency only).
7099
7100 @ifset vms
7101 @item /READ_SOURCES=AVAILABLE
7102 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7103 Default mode, in which sources are checked for consistency only if
7104 they are available.
7105 @end ifset
7106
7107 @item ^-z^/ZERO_MAIN^
7108 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7109 No main subprogram.
7110 @end table
7111
7112 @ifclear vms
7113 @noindent
7114 You may obtain this listing of switches by running @code{gnatbind} with
7115 no arguments.
7116 @end ifclear
7117
7118
7119 @node Consistency-Checking Modes
7120 @subsection Consistency-Checking Modes
7121
7122 @noindent
7123 As described earlier, by default @code{gnatbind} checks
7124 that object files are consistent with one another and are consistent
7125 with any source files it can locate. The following switches control binder
7126 access to sources.
7127
7128 @table @option
7129 @c !sort!
7130 @item ^-s^/READ_SOURCES=ALL^
7131 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7132 Require source files to be present. In this mode, the binder must be
7133 able to locate all source files that are referenced, in order to check
7134 their consistency. In normal mode, if a source file cannot be located it
7135 is simply ignored. If you specify this switch, a missing source
7136 file is an error.
7137
7138 @item ^-x^/READ_SOURCES=NONE^
7139 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7140 Exclude source files. In this mode, the binder only checks that ALI
7141 files are consistent with one another. Source files are not accessed.
7142 The binder runs faster in this mode, and there is still a guarantee that
7143 the resulting program is self-consistent.
7144 If a source file has been edited since it was last compiled, and you
7145 specify this switch, the binder will not detect that the object
7146 file is out of date with respect to the source file. Note that this is the
7147 mode that is automatically used by @code{gnatmake} because in this
7148 case the checking against sources has already been performed by
7149 @code{gnatmake} in the course of compilation (i.e. before binding).
7150
7151 @ifset vms
7152 @item /READ_SOURCES=AVAILABLE
7153 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7154 This is the default mode in which source files are checked if they are
7155 available, and ignored if they are not available.
7156 @end ifset
7157 @end table
7158
7159 @node Binder Error Message Control
7160 @subsection Binder Error Message Control
7161
7162 @noindent
7163 The following switches provide control over the generation of error
7164 messages from the binder:
7165
7166 @table @option
7167 @c !sort!
7168 @item ^-v^/REPORT_ERRORS=VERBOSE^
7169 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7170 Verbose mode. In the normal mode, brief error messages are generated to
7171 @file{stderr}. If this switch is present, a header is written
7172 to @file{stdout} and any error messages are directed to @file{stdout}.
7173 All that is written to @file{stderr} is a brief summary message.
7174
7175 @item ^-b^/REPORT_ERRORS=BRIEF^
7176 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7177 Generate brief error messages to @file{stderr} even if verbose mode is
7178 specified. This is relevant only when used with the
7179 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7180
7181 @ifclear vms
7182 @item -m@var{n}
7183 @cindex @option{-m} (@code{gnatbind})
7184 Limits the number of error messages to @var{n}, a decimal integer in the
7185 range 1-999. The binder terminates immediately if this limit is reached.
7186
7187 @item -M@var{xxx}
7188 @cindex @option{-M} (@code{gnatbind})
7189 Renames the generated main program from @code{main} to @code{xxx}.
7190 This is useful in the case of some cross-building environments, where
7191 the actual main program is separate from the one generated
7192 by @code{gnatbind}.
7193 @end ifclear
7194
7195 @item ^-ws^/WARNINGS=SUPPRESS^
7196 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7197 @cindex Warnings
7198 Suppress all warning messages.
7199
7200 @item ^-we^/WARNINGS=ERROR^
7201 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7202 Treat any warning messages as fatal errors.
7203
7204 @ifset vms
7205 @item /WARNINGS=NORMAL
7206 Standard mode with warnings generated, but warnings do not get treated
7207 as errors.
7208 @end ifset
7209
7210 @item ^-t^/NOTIME_STAMP_CHECK^
7211 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7212 @cindex Time stamp checks, in binder
7213 @cindex Binder consistency checks
7214 @cindex Consistency checks, in binder
7215 The binder performs a number of consistency checks including:
7216
7217 @itemize @bullet
7218 @item
7219 Check that time stamps of a given source unit are consistent
7220 @item
7221 Check that checksums of a given source unit are consistent
7222 @item
7223 Check that consistent versions of @code{GNAT} were used for compilation
7224 @item
7225 Check consistency of configuration pragmas as required
7226 @end itemize
7227
7228 @noindent
7229 Normally failure of such checks, in accordance with the consistency
7230 requirements of the Ada Reference Manual, causes error messages to be
7231 generated which abort the binder and prevent the output of a binder
7232 file and subsequent link to obtain an executable.
7233
7234 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7235 into warnings, so that
7236 binding and linking can continue to completion even in the presence of such
7237 errors. The result may be a failed link (due to missing symbols), or a
7238 non-functional executable which has undefined semantics.
7239 @emph{This means that
7240 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7241 with extreme care.}
7242 @end table
7243
7244 @node Elaboration Control
7245 @subsection Elaboration Control
7246
7247 @noindent
7248 The following switches provide additional control over the elaboration
7249 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7250
7251 @table @option
7252 @item ^-p^/PESSIMISTIC_ELABORATION^
7253 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7254 Normally the binder attempts to choose an elaboration order that is
7255 likely to minimize the likelihood of an elaboration order error resulting
7256 in raising a @code{Program_Error} exception. This switch reverses the
7257 action of the binder, and requests that it deliberately choose an order
7258 that is likely to maximize the likelihood of an elaboration error.
7259 This is useful in ensuring portability and avoiding dependence on
7260 accidental fortuitous elaboration ordering.
7261
7262 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7263 switch if dynamic
7264 elaboration checking is used (@option{-gnatE} switch used for compilation).
7265 This is because in the default static elaboration mode, all necessary
7266 @code{Elaborate_All} pragmas are implicitly inserted.
7267 These implicit pragmas are still respected by the binder in
7268 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7269 safe elaboration order is assured.
7270 @end table
7271
7272 @node Output Control
7273 @subsection Output Control
7274
7275 @noindent
7276 The following switches allow additional control over the output
7277 generated by the binder.
7278
7279 @table @option
7280 @c !sort!
7281
7282 @item ^-A^/BIND_FILE=ADA^
7283 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7284 Generate binder program in Ada (default). The binder program is named
7285 @file{b~@var{mainprog}.adb} by default. This can be changed with
7286 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7287
7288 @item ^-c^/NOOUTPUT^
7289 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7290 Check only. Do not generate the binder output file. In this mode the
7291 binder performs all error checks but does not generate an output file.
7292
7293 @item ^-C^/BIND_FILE=C^
7294 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7295 Generate binder program in C. The binder program is named
7296 @file{b_@var{mainprog}.c}.
7297 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7298 option.
7299
7300 @item ^-e^/ELABORATION_DEPENDENCIES^
7301 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7302 Output complete list of elaboration-order dependencies, showing the
7303 reason for each dependency. This output can be rather extensive but may
7304 be useful in diagnosing problems with elaboration order. The output is
7305 written to @file{stdout}.
7306
7307 @item ^-h^/HELP^
7308 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7309 Output usage information. The output is written to @file{stdout}.
7310
7311 @item ^-K^/LINKER_OPTION_LIST^
7312 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7313 Output linker options to @file{stdout}. Includes library search paths,
7314 contents of pragmas Ident and Linker_Options, and libraries added
7315 by @code{gnatbind}.
7316
7317 @item ^-l^/ORDER_OF_ELABORATION^
7318 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7319 Output chosen elaboration order. The output is written to @file{stdout}.
7320
7321 @item ^-O^/OBJECT_LIST^
7322 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7323 Output full names of all the object files that must be linked to provide
7324 the Ada component of the program. The output is written to @file{stdout}.
7325 This list includes the files explicitly supplied and referenced by the user
7326 as well as implicitly referenced run-time unit files. The latter are
7327 omitted if the corresponding units reside in shared libraries. The
7328 directory names for the run-time units depend on the system configuration.
7329
7330 @item ^-o ^/OUTPUT=^@var{file}
7331 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7332 Set name of output file to @var{file} instead of the normal
7333 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7334 binder generated body filename. In C mode you would normally give
7335 @var{file} an extension of @file{.c} because it will be a C source program.
7336 Note that if this option is used, then linking must be done manually.
7337 It is not possible to use gnatlink in this case, since it cannot locate
7338 the binder file.
7339
7340 @item ^-r^/RESTRICTION_LIST^
7341 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7342 Generate list of @code{pragma Restrictions} that could be applied to
7343 the current unit. This is useful for code audit purposes, and also may
7344 be used to improve code generation in some cases.
7345
7346 @end table
7347
7348 @node Binding with Non-Ada Main Programs
7349 @subsection Binding with Non-Ada Main Programs
7350
7351 @noindent
7352 In our description so far we have assumed that the main
7353 program is in Ada, and that the task of the binder is to generate a
7354 corresponding function @code{main} that invokes this Ada main
7355 program. GNAT also supports the building of executable programs where
7356 the main program is not in Ada, but some of the called routines are
7357 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7358 The following switch is used in this situation:
7359
7360 @table @option
7361 @item ^-n^/NOMAIN^
7362 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7363 No main program. The main program is not in Ada.
7364 @end table
7365
7366 @noindent
7367 In this case, most of the functions of the binder are still required,
7368 but instead of generating a main program, the binder generates a file
7369 containing the following callable routines:
7370
7371 @table @code
7372 @item adainit
7373 @findex adainit
7374 You must call this routine to initialize the Ada part of the program by
7375 calling the necessary elaboration routines. A call to @code{adainit} is
7376 required before the first call to an Ada subprogram.
7377
7378 Note that it is assumed that the basic execution environment must be setup
7379 to be appropriate for Ada execution at the point where the first Ada
7380 subprogram is called. In particular, if the Ada code will do any
7381 floating-point operations, then the FPU must be setup in an appropriate
7382 manner. For the case of the x86, for example, full precision mode is
7383 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7384 that the FPU is in the right state.
7385
7386 @item adafinal
7387 @findex adafinal
7388 You must call this routine to perform any library-level finalization
7389 required by the Ada subprograms. A call to @code{adafinal} is required
7390 after the last call to an Ada subprogram, and before the program
7391 terminates.
7392 @end table
7393
7394 @noindent
7395 If the @option{^-n^/NOMAIN^} switch
7396 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7397 @cindex Binder, multiple input files
7398 is given, more than one ALI file may appear on
7399 the command line for @code{gnatbind}. The normal @dfn{closure}
7400 calculation is performed for each of the specified units. Calculating
7401 the closure means finding out the set of units involved by tracing
7402 @code{with} references. The reason it is necessary to be able to
7403 specify more than one ALI file is that a given program may invoke two or
7404 more quite separate groups of Ada units.
7405
7406 The binder takes the name of its output file from the last specified ALI
7407 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7408 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7409 The output is an Ada unit in source form that can
7410 be compiled with GNAT unless the -C switch is used in which case the
7411 output is a C source file, which must be compiled using the C compiler.
7412 This compilation occurs automatically as part of the @code{gnatlink}
7413 processing.
7414
7415 Currently the GNAT run time requires a FPU using 80 bits mode
7416 precision. Under targets where this is not the default it is required to
7417 call GNAT.Float_Control.Reset before using floating point numbers (this
7418 include float computation, float input and output) in the Ada code. A
7419 side effect is that this could be the wrong mode for the foreign code
7420 where floating point computation could be broken after this call.
7421
7422 @node Binding Programs with No Main Subprogram
7423 @subsection Binding Programs with No Main Subprogram
7424
7425 @noindent
7426 It is possible to have an Ada program which does not have a main
7427 subprogram. This program will call the elaboration routines of all the
7428 packages, then the finalization routines.
7429
7430 The following switch is used to bind programs organized in this manner:
7431
7432 @table @option
7433 @item ^-z^/ZERO_MAIN^
7434 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7435 Normally the binder checks that the unit name given on the command line
7436 corresponds to a suitable main subprogram. When this switch is used,
7437 a list of ALI files can be given, and the execution of the program
7438 consists of elaboration of these units in an appropriate order.
7439 @end table
7440
7441
7442 @node Command-Line Access
7443 @section Command-Line Access
7444
7445 @noindent
7446 The package @code{Ada.Command_Line} provides access to the command-line
7447 arguments and program name. In order for this interface to operate
7448 correctly, the two variables
7449
7450 @smallexample
7451 @group
7452 int gnat_argc;
7453 char **gnat_argv;
7454 @end group
7455 @end smallexample
7456
7457 @noindent
7458 @findex gnat_argv
7459 @findex gnat_argc
7460 are declared in one of the GNAT library routines. These variables must
7461 be set from the actual @code{argc} and @code{argv} values passed to the
7462 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7463 generates the C main program to automatically set these variables.
7464 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7465 set these variables. If they are not set, the procedures in
7466 @code{Ada.Command_Line} will not be available, and any attempt to use
7467 them will raise @code{Constraint_Error}. If command line access is
7468 required, your main program must set @code{gnat_argc} and
7469 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7470 it.
7471
7472
7473 @node Search Paths for gnatbind
7474 @section Search Paths for @code{gnatbind}
7475
7476 @noindent
7477 The binder takes the name of an ALI file as its argument and needs to
7478 locate source files as well as other ALI files to verify object consistency.
7479
7480 For source files, it follows exactly the same search rules as @code{gcc}
7481 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7482 directories searched are:
7483
7484 @enumerate
7485 @item
7486 The directory containing the ALI file named in the command line, unless
7487 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7488
7489 @item
7490 All directories specified by @option{^-I^/SEARCH^}
7491 switches on the @code{gnatbind}
7492 command line, in the order given.
7493
7494 @item
7495 @findex ADA_OBJECTS_PATH
7496 Each of the directories listed in the value of the
7497 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7498 @ifset unw
7499 Construct this value
7500 exactly as the @code{PATH} environment variable: a list of directory
7501 names separated by colons (semicolons when working with the NT version
7502 of GNAT).
7503 @end ifset
7504 @ifset vms
7505 Normally, define this value as a logical name containing a comma separated
7506 list of directory names.
7507
7508 This variable can also be defined by means of an environment string
7509 (an argument to the DEC C exec* set of functions).
7510
7511 Logical Name:
7512 @smallexample
7513 DEFINE ANOTHER_PATH FOO:[BAG]
7514 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7515 @end smallexample
7516
7517 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7518 first, followed by the standard Ada 95
7519 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7520 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7521 (Text_IO, Sequential_IO, etc)
7522 instead of the Ada95 packages. Thus, in order to get the Ada 95
7523 packages by default, ADA_OBJECTS_PATH must be redefined.
7524 @end ifset
7525
7526 @item
7527 @findex ADA_PRJ_OBJECTS_FILE
7528 Each of the directories listed in the text file whose name is given
7529 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7530
7531 @noindent
7532 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7533 driver when project files are used. It should not normally be set
7534 by other means.
7535
7536 @item
7537 The content of the @file{ada_object_path} file which is part of the GNAT
7538 installation tree and is used to store standard libraries such as the
7539 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7540 specified.
7541 @ifclear vms
7542 @ref{Installing an Ada Library}
7543 @end ifclear
7544 @end enumerate
7545
7546 @noindent
7547 In the binder the switch @option{^-I^/SEARCH^}
7548 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7549 is used to specify both source and
7550 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7551 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7552 instead if you want to specify
7553 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7554 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7555 if you want to specify library paths
7556 only. This means that for the binder
7557 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7558 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7559 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7560 The binder generates the bind file (a C language source file) in the
7561 current working directory.
7562
7563 @findex Ada
7564 @findex System
7565 @findex Interfaces
7566 @findex GNAT
7567 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7568 children make up the GNAT Run-Time Library, together with the package
7569 GNAT and its children, which contain a set of useful additional
7570 library functions provided by GNAT. The sources for these units are
7571 needed by the compiler and are kept together in one directory. The ALI
7572 files and object files generated by compiling the RTL are needed by the
7573 binder and the linker and are kept together in one directory, typically
7574 different from the directory containing the sources. In a normal
7575 installation, you need not specify these directory names when compiling
7576 or binding. Either the environment variables or the built-in defaults
7577 cause these files to be found.
7578
7579 Besides simplifying access to the RTL, a major use of search paths is
7580 in compiling sources from multiple directories. This can make
7581 development environments much more flexible.
7582
7583 @node Examples of gnatbind Usage
7584 @section Examples of @code{gnatbind} Usage
7585
7586 @noindent
7587 This section contains a number of examples of using the GNAT binding
7588 utility @code{gnatbind}.
7589
7590 @table @code
7591 @item gnatbind hello
7592 The main program @code{Hello} (source program in @file{hello.adb}) is
7593 bound using the standard switch settings. The generated main program is
7594 @file{b~hello.adb}. This is the normal, default use of the binder.
7595
7596 @ifclear vms
7597 @item gnatbind hello -o mainprog.adb
7598 @end ifclear
7599 @ifset vms
7600 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7601 @end ifset
7602 The main program @code{Hello} (source program in @file{hello.adb}) is
7603 bound using the standard switch settings. The generated main program is
7604 @file{mainprog.adb} with the associated spec in
7605 @file{mainprog.ads}. Note that you must specify the body here not the
7606 spec, in the case where the output is in Ada. Note that if this option
7607 is used, then linking must be done manually, since gnatlink will not
7608 be able to find the generated file.
7609
7610 @ifclear vms
7611 @item gnatbind main -C -o mainprog.c -x
7612 @end ifclear
7613 @ifset vms
7614 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7615 @end ifset
7616 The main program @code{Main} (source program in
7617 @file{main.adb}) is bound, excluding source files from the
7618 consistency checking, generating
7619 the file @file{mainprog.c}.
7620
7621 @ifclear vms
7622 @item gnatbind -x main_program -C -o mainprog.c
7623 This command is exactly the same as the previous example. Switches may
7624 appear anywhere in the command line, and single letter switches may be
7625 combined into a single switch.
7626 @end ifclear
7627
7628 @ifclear vms
7629 @item gnatbind -n math dbase -C -o ada-control.c
7630 @end ifclear
7631 @ifset vms
7632 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7633 @end ifset
7634 The main program is in a language other than Ada, but calls to
7635 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7636 to @code{gnatbind} generates the file @file{ada-control.c} containing
7637 the @code{adainit} and @code{adafinal} routines to be called before and
7638 after accessing the Ada units.
7639 @end table
7640
7641
7642 @c ------------------------------------
7643 @node Linking Using gnatlink
7644 @chapter Linking Using @code{gnatlink}
7645 @c ------------------------------------
7646 @findex gnatlink
7647
7648 @noindent
7649 This chapter discusses @code{gnatlink}, a tool that links
7650 an Ada program and builds an executable file. This utility
7651 invokes the system linker ^(via the @code{gcc} command)^^
7652 with a correct list of object files and library references.
7653 @code{gnatlink} automatically determines the list of files and
7654 references for the Ada part of a program. It uses the binder file
7655 generated by the @command{gnatbind} to determine this list.
7656
7657 @menu
7658 * Running gnatlink::
7659 * Switches for gnatlink::
7660 * Setting Stack Size from gnatlink::
7661 * Setting Heap Size from gnatlink::
7662 @end menu
7663
7664 @node Running gnatlink
7665 @section Running @code{gnatlink}
7666
7667 @noindent
7668 The form of the @code{gnatlink} command is
7669
7670 @smallexample
7671 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7672            [@var{non-Ada objects}] [@var{linker options}]
7673 @end smallexample
7674
7675 @noindent
7676 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7677 non-Ada objects
7678 or linker options) may be in any order, provided that no non-Ada object may
7679 be mistaken for a main @file{ALI} file.
7680 Any file name @file{F} without the @file{.ali}
7681 extension will be taken as the main @file{ALI} file if a file exists
7682 whose name is the concatenation of @file{F} and @file{.ali}.
7683
7684 @noindent
7685 @file{@var{mainprog}.ali} references the ALI file of the main program.
7686 The @file{.ali} extension of this file can be omitted. From this
7687 reference, @code{gnatlink} locates the corresponding binder file
7688 @file{b~@var{mainprog}.adb} and, using the information in this file along
7689 with the list of non-Ada objects and linker options, constructs a
7690 linker command file to create the executable.
7691
7692 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7693 file are passed to the linker uninterpreted.
7694 They typically include the names of
7695 object files for units written in other languages than Ada and any library
7696 references required to resolve references in any of these foreign language
7697 units, or in @code{Import} pragmas in any Ada units.
7698
7699 @var{linker options} is an optional list of linker specific
7700 switches.
7701 The default linker called by gnatlink is @var{gcc} which in
7702 turn calls the appropriate system linker.
7703 Standard options for the linker such as @option{-lmy_lib} or
7704 @option{-Ldir} can be added as is.
7705 For options that are not recognized by
7706 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7707 @option{-Wl,}.
7708 Refer to the GCC documentation for
7709 details. Here is an example showing how to generate a linker map:
7710
7711 @ifclear vms
7712 @smallexample
7713 $ gnatlink my_prog -Wl,-Map,MAPFILE
7714 @end smallexample
7715 @end ifclear
7716
7717 @ifset vms
7718 <<Need example for VMS>>
7719 @end ifset
7720
7721 Using @var{linker options} it is possible to set the program stack and
7722 heap size. See @ref{Setting Stack Size from gnatlink}, and
7723 @ref{Setting Heap Size from gnatlink}.
7724
7725 @code{gnatlink} determines the list of objects required by the Ada
7726 program and prepends them to the list of objects passed to the linker.
7727 @code{gnatlink} also gathers any arguments set by the use of
7728 @code{pragma Linker_Options} and adds them to the list of arguments
7729 presented to the linker.
7730
7731 @ifset vms
7732 @code{gnatlink} accepts the following types of extra files on the command
7733 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7734 options files (.OPT). These are recognized and handled according to their
7735 extension.
7736 @end ifset
7737
7738 @node Switches for gnatlink
7739 @section Switches for @code{gnatlink}
7740
7741 @noindent
7742 The following switches are available with the @code{gnatlink} utility:
7743
7744 @table @option
7745 @c !sort!
7746
7747 @item ^-A^/BIND_FILE=ADA^
7748 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7749 The binder has generated code in Ada. This is the default.
7750
7751 @item ^-C^/BIND_FILE=C^
7752 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7753 If instead of generating a file in Ada, the binder has generated one in
7754 C, then the linker needs to know about it. Use this switch to signal
7755 to @code{gnatlink} that the binder has generated C code rather than
7756 Ada code.
7757
7758 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7759 @cindex Command line length
7760 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7761 On some targets, the command line length is limited, and @code{gnatlink}
7762 will generate a separate file for the linker if the list of object files
7763 is too long.
7764 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7765 to be generated even if
7766 the limit is not exceeded. This is useful in some cases to deal with
7767 special situations where the command line length is exceeded.
7768
7769 @item ^-g^/DEBUG^
7770 @cindex Debugging information, including
7771 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7772 The option to include debugging information causes the Ada bind file (in
7773 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7774 @option{^-g^/DEBUG^}.
7775 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7776 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7777 Without @option{^-g^/DEBUG^}, the binder removes these files by
7778 default. The same procedure apply if a C bind file was generated using
7779 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7780 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7781
7782 @item ^-n^/NOCOMPILE^
7783 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7784 Do not compile the file generated by the binder. This may be used when
7785 a link is rerun with different options, but there is no need to recompile
7786 the binder file.
7787
7788 @item ^-v^/VERBOSE^
7789 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7790 Causes additional information to be output, including a full list of the
7791 included object files. This switch option is most useful when you want
7792 to see what set of object files are being used in the link step.
7793
7794 @item ^-v -v^/VERBOSE/VERBOSE^
7795 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7796 Very verbose mode. Requests that the compiler operate in verbose mode when
7797 it compiles the binder file, and that the system linker run in verbose mode.
7798
7799 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7800 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7801 @var{exec-name} specifies an alternate name for the generated
7802 executable program. If this switch is omitted, the executable has the same
7803 name as the main unit. For example, @code{gnatlink try.ali} creates
7804 an executable called @file{^try^TRY.EXE^}.
7805
7806 @ifclear vms
7807 @item -b @var{target}
7808 @cindex @option{-b} (@code{gnatlink})
7809 Compile your program to run on @var{target}, which is the name of a
7810 system configuration. You must have a GNAT cross-compiler built if
7811 @var{target} is not the same as your host system.
7812
7813 @item -B@var{dir}
7814 @cindex @option{-B} (@code{gnatlink})
7815 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7816 from @var{dir} instead of the default location. Only use this switch
7817 when multiple versions of the GNAT compiler are available. See the
7818 @code{gcc} manual page for further details. You would normally use the
7819 @option{-b} or @option{-V} switch instead.
7820
7821 @item --GCC=@var{compiler_name}
7822 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7823 Program used for compiling the binder file. The default is
7824 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7825 @code{compiler_name} contains spaces or other separator characters. As
7826 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7827 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7828 inserted after your command name. Thus in the above example the compiler
7829 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7830 If several @option{--GCC=compiler_name} are used, only the last
7831 @var{compiler_name} is taken into account. However, all the additional
7832 switches are also taken into account. Thus,
7833 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7834 @option{--GCC="bar -x -y -z -t"}.
7835
7836 @item --LINK=@var{name}
7837 @cindex @option{--LINK=} (@code{gnatlink})
7838 @var{name} is the name of the linker to be invoked. This is especially
7839 useful in mixed language programs since languages such as C++ require
7840 their own linker to be used. When this switch is omitted, the default
7841 name for the linker is (@file{gcc}). When this switch is used, the
7842 specified linker is called instead of (@file{gcc}) with exactly the same
7843 parameters that would have been passed to (@file{gcc}) so if the desired
7844 linker requires different parameters it is necessary to use a wrapper
7845 script that massages the parameters before invoking the real linker. It
7846 may be useful to control the exact invocation by using the verbose
7847 switch.
7848
7849 @end ifclear
7850
7851 @ifset vms
7852 @item /DEBUG=TRACEBACK
7853 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7854 This qualifier causes sufficient information to be included in the
7855 executable file to allow a traceback, but does not include the full
7856 symbol information needed by the debugger.
7857
7858 @item /IDENTIFICATION="<string>"
7859 @code{"<string>"} specifies the string to be stored in the image file
7860 identification field in the image header.
7861 It overrides any pragma @code{Ident} specified string.
7862
7863 @item /NOINHIBIT-EXEC
7864 Generate the executable file even if there are linker warnings.
7865
7866 @item /NOSTART_FILES
7867 Don't link in the object file containing the ``main'' transfer address.
7868 Used when linking with a foreign language main program compiled with a
7869 Digital compiler.
7870
7871 @item /STATIC
7872 Prefer linking with object libraries over sharable images, even without
7873 /DEBUG.
7874 @end ifset
7875
7876 @end table
7877
7878 @node Setting Stack Size from gnatlink
7879 @section Setting Stack Size from @code{gnatlink}
7880
7881 @noindent
7882 Under Windows systems, it is possible to specify the program stack size from
7883 @code{gnatlink} using either:
7884
7885 @itemize @bullet
7886
7887 @item using @option{-Xlinker} linker option
7888
7889 @smallexample
7890 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7891 @end smallexample
7892
7893 This sets the stack reserve size to 0x10000 bytes and the stack commit
7894 size to 0x1000 bytes.
7895
7896 @item using @option{-Wl} linker option
7897
7898 @smallexample
7899 $ gnatlink hello -Wl,--stack=0x1000000
7900 @end smallexample
7901
7902 This sets the stack reserve size to 0x1000000 bytes. Note that with
7903 @option{-Wl} option it is not possible to set the stack commit size
7904 because the coma is a separator for this option.
7905
7906 @end itemize
7907
7908 @node Setting Heap Size from gnatlink
7909 @section Setting Heap Size from @code{gnatlink}
7910
7911 @noindent
7912 Under Windows systems, it is possible to specify the program heap size from
7913 @code{gnatlink} using either:
7914
7915 @itemize @bullet
7916
7917 @item using @option{-Xlinker} linker option
7918
7919 @smallexample
7920 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7921 @end smallexample
7922
7923 This sets the heap reserve size to 0x10000 bytes and the heap commit
7924 size to 0x1000 bytes.
7925
7926 @item using @option{-Wl} linker option
7927
7928 @smallexample
7929 $ gnatlink hello -Wl,--heap=0x1000000
7930 @end smallexample
7931
7932 This sets the heap reserve size to 0x1000000 bytes. Note that with
7933 @option{-Wl} option it is not possible to set the heap commit size
7934 because the coma is a separator for this option.
7935
7936 @end itemize
7937
7938 @node The GNAT Make Program gnatmake
7939 @chapter The GNAT Make Program @code{gnatmake}
7940 @findex gnatmake
7941
7942 @menu
7943 * Running gnatmake::
7944 * Switches for gnatmake::
7945 * Mode Switches for gnatmake::
7946 * Notes on the Command Line::
7947 * How gnatmake Works::
7948 * Examples of gnatmake Usage::
7949 @end menu
7950 @noindent
7951 A typical development cycle when working on an Ada program consists of
7952 the following steps:
7953
7954 @enumerate
7955 @item
7956 Edit some sources to fix bugs.
7957
7958 @item
7959 Add enhancements.
7960
7961 @item
7962 Compile all sources affected.
7963
7964 @item
7965 Rebind and relink.
7966
7967 @item
7968 Test.
7969 @end enumerate
7970
7971 @noindent
7972 The third step can be tricky, because not only do the modified files
7973 @cindex Dependency rules
7974 have to be compiled, but any files depending on these files must also be
7975 recompiled. The dependency rules in Ada can be quite complex, especially
7976 in the presence of overloading, @code{use} clauses, generics and inlined
7977 subprograms.
7978
7979 @code{gnatmake} automatically takes care of the third and fourth steps
7980 of this process. It determines which sources need to be compiled,
7981 compiles them, and binds and links the resulting object files.
7982
7983 Unlike some other Ada make programs, the dependencies are always
7984 accurately recomputed from the new sources. The source based approach of
7985 the GNAT compilation model makes this possible. This means that if
7986 changes to the source program cause corresponding changes in
7987 dependencies, they will always be tracked exactly correctly by
7988 @code{gnatmake}.
7989
7990 @node Running gnatmake
7991 @section Running @code{gnatmake}
7992
7993 @noindent
7994 The usual form of the @code{gnatmake} command is
7995
7996 @smallexample
7997 $ gnatmake [@var{switches}] @var{file_name}
7998       [@var{file_names}] [@var{mode_switches}]
7999 @end smallexample
8000
8001 @noindent
8002 The only required argument is one @var{file_name}, which specifies
8003 a compilation unit that is a main program. Several @var{file_names} can be
8004 specified: this will result in several executables being built.
8005 If @code{switches} are present, they can be placed before the first
8006 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8007 If @var{mode_switches} are present, they must always be placed after
8008 the last @var{file_name} and all @code{switches}.
8009
8010 If you are using standard file extensions (.adb and .ads), then the
8011 extension may be omitted from the @var{file_name} arguments. However, if
8012 you are using non-standard extensions, then it is required that the
8013 extension be given. A relative or absolute directory path can be
8014 specified in a @var{file_name}, in which case, the input source file will
8015 be searched for in the specified directory only. Otherwise, the input
8016 source file will first be searched in the directory where
8017 @code{gnatmake} was invoked and if it is not found, it will be search on
8018 the source path of the compiler as described in
8019 @ref{Search Paths and the Run-Time Library (RTL)}.
8020
8021 All @code{gnatmake} output (except when you specify
8022 @option{^-M^/DEPENDENCIES_LIST^}) is to
8023 @file{stderr}. The output produced by the
8024 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8025 @file{stdout}.
8026
8027 @node Switches for gnatmake
8028 @section Switches for @code{gnatmake}
8029
8030 @noindent
8031 You may specify any of the following switches to @code{gnatmake}:
8032
8033 @table @option
8034 @c !sort!
8035 @ifclear vms
8036 @item --GCC=@var{compiler_name}
8037 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8038 Program used for compiling. The default is `@code{gcc}'. You need to use
8039 quotes around @var{compiler_name} if @code{compiler_name} contains
8040 spaces or other separator characters. As an example @option{--GCC="foo -x
8041 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8042 compiler. Note that switch @option{-c} is always inserted after your
8043 command name. Thus in the above example the compiler command that will
8044 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8045 If several @option{--GCC=compiler_name} are used, only the last
8046 @var{compiler_name} is taken into account. However, all the additional
8047 switches are also taken into account. Thus,
8048 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8049 @option{--GCC="bar -x -y -z -t"}.
8050
8051 @item --GNATBIND=@var{binder_name}
8052 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8053 Program used for binding. The default is `@code{gnatbind}'. You need to
8054 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8055 or other separator characters. As an example @option{--GNATBIND="bar -x
8056 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8057 binder. Binder switches that are normally appended by @code{gnatmake} to
8058 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8059
8060 @item --GNATLINK=@var{linker_name}
8061 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8062 Program used for linking. The default is `@code{gnatlink}'. You need to
8063 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8064 or other separator characters. As an example @option{--GNATLINK="lan -x
8065 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8066 linker. Linker switches that are normally appended by @code{gnatmake} to
8067 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8068
8069 @end ifclear
8070
8071 @item ^-a^/ALL_FILES^
8072 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8073 Consider all files in the make process, even the GNAT internal system
8074 files (for example, the predefined Ada library files), as well as any
8075 locked files. Locked files are files whose ALI file is write-protected.
8076 By default,
8077 @code{gnatmake} does not check these files,
8078 because the assumption is that the GNAT internal files are properly up
8079 to date, and also that any write protected ALI files have been properly
8080 installed. Note that if there is an installation problem, such that one
8081 of these files is not up to date, it will be properly caught by the
8082 binder.
8083 You may have to specify this switch if you are working on GNAT
8084 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8085 in conjunction with @option{^-f^/FORCE_COMPILE^}
8086 if you need to recompile an entire application,
8087 including run-time files, using special configuration pragmas,
8088 such as a @code{Normalize_Scalars} pragma.
8089
8090 By default
8091 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8092 internal files with
8093 @ifclear vms
8094 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8095 @end ifclear
8096 @ifset vms
8097 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8098 @end ifset
8099
8100 @item ^-b^/ACTIONS=BIND^
8101 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8102 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8103 compilation and binding, but no link.
8104 Can be combined with @option{^-l^/ACTIONS=LINK^}
8105 to do binding and linking. When not combined with
8106 @option{^-c^/ACTIONS=COMPILE^}
8107 all the units in the closure of the main program must have been previously
8108 compiled and must be up to date. The root unit specified by @var{file_name}
8109 may be given without extension, with the source extension or, if no GNAT
8110 Project File is specified, with the ALI file extension.
8111
8112 @item ^-c^/ACTIONS=COMPILE^
8113 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8114 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8115 is also specified. Do not perform linking, except if both
8116 @option{^-b^/ACTIONS=BIND^} and
8117  @option{^-l^/ACTIONS=LINK^} are also specified.
8118 If the root unit specified by @var{file_name} is not a main unit, this is the
8119 default. Otherwise @code{gnatmake} will attempt binding and linking
8120 unless all objects are up to date and the executable is more recent than
8121 the objects.
8122
8123 @item ^-C^/MAPPING^
8124 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8125 Use a temporary mapping file. A mapping file is a way to communicate to the
8126 compiler two mappings: from unit names to file names (without any directory
8127 information) and from file names to path names (with full directory
8128 information). These mappings are used by the compiler to short-circuit the path
8129 search. When @code{gnatmake} is invoked with this switch, it will create
8130 a temporary mapping file, initially populated by the project manager,
8131 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8132 Each invocation of the compiler will add the newly accessed sources to the
8133 mapping file. This will improve the source search during the next invocation
8134 of the compiler.
8135
8136 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8137 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8138 Use a specific mapping file. The file, specified as a path name (absolute or
8139 relative) by this switch, should already exist, otherwise the switch is
8140 ineffective. The specified mapping file will be communicated to the compiler.
8141 This switch is not compatible with a project file
8142 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8143 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8144
8145 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8146 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8147 Put all object files and ALI file in directory @var{dir}.
8148 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8149 and ALI files go in the current working directory.
8150
8151 This switch cannot be used when using a project file.
8152
8153 @item ^-f^/FORCE_COMPILE^
8154 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8155 Force recompilations. Recompile all sources, even though some object
8156 files may be up to date, but don't recompile predefined or GNAT internal
8157 files or locked files (files with a write-protected ALI file),
8158 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8159
8160 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8161 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8162 When using project files, if some errors or warnings are detected during
8163 parsing and verbose mode is not in effect (no use of switch
8164 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8165 file, rather than its simple file name.
8166
8167 @item ^-i^/IN_PLACE^
8168 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8169 In normal mode, @code{gnatmake} compiles all object files and ALI files
8170 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8171 then instead object files and ALI files that already exist are overwritten
8172 in place. This means that once a large project is organized into separate
8173 directories in the desired manner, then @code{gnatmake} will automatically
8174 maintain and update this organization. If no ALI files are found on the
8175 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8176 the new object and ALI files are created in the
8177 directory containing the source being compiled. If another organization
8178 is desired, where objects and sources are kept in different directories,
8179 a useful technique is to create dummy ALI files in the desired directories.
8180 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8181 the corresponding source file, and it will be put the resulting object
8182 and ALI files in the directory where it found the dummy file.
8183
8184 @item ^-j^/PROCESSES=^@var{n}
8185 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8186 @cindex Parallel make
8187 Use @var{n} processes to carry out the (re)compilations. On a
8188 multiprocessor machine compilations will occur in parallel. In the
8189 event of compilation errors, messages from various compilations might
8190 get interspersed (but @code{gnatmake} will give you the full ordered
8191 list of failing compiles at the end). If this is problematic, rerun
8192 the make process with n set to 1 to get a clean list of messages.
8193
8194 @item ^-k^/CONTINUE_ON_ERROR^
8195 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8196 Keep going. Continue as much as possible after a compilation error. To
8197 ease the programmer's task in case of compilation errors, the list of
8198 sources for which the compile fails is given when @code{gnatmake}
8199 terminates.
8200
8201 If @code{gnatmake} is invoked with several @file{file_names} and with this
8202 switch, if there are compilation errors when building an executable,
8203 @code{gnatmake} will not attempt to build the following executables.
8204
8205 @item ^-l^/ACTIONS=LINK^
8206 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8207 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8208 and linking. Linking will not be performed if combined with
8209 @option{^-c^/ACTIONS=COMPILE^}
8210 but not with @option{^-b^/ACTIONS=BIND^}.
8211 When not combined with @option{^-b^/ACTIONS=BIND^}
8212 all the units in the closure of the main program must have been previously
8213 compiled and must be up to date, and the main program need to have been bound.
8214 The root unit specified by @var{file_name}
8215 may be given without extension, with the source extension or, if no GNAT
8216 Project File is specified, with the ALI file extension.
8217
8218 @item ^-m^/MINIMAL_RECOMPILATION^
8219 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8220 Specifies that the minimum necessary amount of recompilations
8221 be performed. In this mode @code{gnatmake} ignores time
8222 stamp differences when the only
8223 modifications to a source file consist in adding/removing comments,
8224 empty lines, spaces or tabs. This means that if you have changed the
8225 comments in a source file or have simply reformatted it, using this
8226 switch will tell gnatmake not to recompile files that depend on it
8227 (provided other sources on which these files depend have undergone no
8228 semantic modifications). Note that the debugging information may be
8229 out of date with respect to the sources if the @option{-m} switch causes
8230 a compilation to be switched, so the use of this switch represents a
8231 trade-off between compilation time and accurate debugging information.
8232
8233 @item ^-M^/DEPENDENCIES_LIST^
8234 @cindex Dependencies, producing list
8235 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8236 Check if all objects are up to date. If they are, output the object
8237 dependences to @file{stdout} in a form that can be directly exploited in
8238 a @file{Makefile}. By default, each source file is prefixed with its
8239 (relative or absolute) directory name. This name is whatever you
8240 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8241 and @option{^-I^/SEARCH^} switches. If you use
8242 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8243 @option{^-q^/QUIET^}
8244 (see below), only the source file names,
8245 without relative paths, are output. If you just specify the
8246 @option{^-M^/DEPENDENCIES_LIST^}
8247 switch, dependencies of the GNAT internal system files are omitted. This
8248 is typically what you want. If you also specify
8249 the @option{^-a^/ALL_FILES^} switch,
8250 dependencies of the GNAT internal files are also listed. Note that
8251 dependencies of the objects in external Ada libraries (see switch
8252 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8253 are never reported.
8254
8255 @item ^-n^/DO_OBJECT_CHECK^
8256 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8257 Don't compile, bind, or link. Checks if all objects are up to date.
8258 If they are not, the full name of the first file that needs to be
8259 recompiled is printed.
8260 Repeated use of this option, followed by compiling the indicated source
8261 file, will eventually result in recompiling all required units.
8262
8263 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8264 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8265 Output executable name. The name of the final executable program will be
8266 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8267 name for the executable will be the name of the input file in appropriate form
8268 for an executable file on the host system.
8269
8270 This switch cannot be used when invoking @code{gnatmake} with several
8271 @file{file_names}.
8272
8273 @item ^-P^/PROJECT_FILE=^@var{project}
8274 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8275 Use project file @var{project}. Only one such switch can be used.
8276 See @ref{gnatmake and Project Files}.
8277
8278 @item ^-q^/QUIET^
8279 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8280 Quiet. When this flag is not set, the commands carried out by
8281 @code{gnatmake} are displayed.
8282
8283 @item ^-s^/SWITCH_CHECK/^
8284 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8285 Recompile if compiler switches have changed since last compilation.
8286 All compiler switches but -I and -o are taken into account in the
8287 following way:
8288 orders between different ``first letter'' switches are ignored, but
8289 orders between same switches are taken into account. For example,
8290 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8291 is equivalent to @option{-O -g}.
8292
8293 This switch is recommended when Integrated Preprocessing is used.
8294
8295 @item ^-u^/UNIQUE^
8296 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8297 Unique. Recompile at most the main files. It implies -c. Combined with
8298 -f, it is equivalent to calling the compiler directly. Note that using
8299 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8300 (see @ref{Project Files and Main Subprograms}).
8301
8302 @item ^-U^/ALL_PROJECTS^
8303 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8304 When used without a project file or with one or several mains on the command
8305 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8306 on the command line, all sources of all project files are checked and compiled
8307 if not up to date, and libraries are rebuilt, if necessary.
8308
8309 @item ^-v^/REASONS^
8310 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8311 Verbose. Displays the reason for all recompilations @code{gnatmake}
8312 decides are necessary.
8313
8314 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8315 Indicates the verbosity of the parsing of GNAT project files.
8316 See @ref{Switches Related to Project Files}.
8317
8318 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8319 Indicates that external variable @var{name} has the value @var{value}.
8320 The Project Manager will use this value for occurrences of
8321 @code{external(name)} when parsing the project file.
8322 See @ref{Switches Related to Project Files}.
8323
8324 @item ^-z^/NOMAIN^
8325 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8326 No main subprogram. Bind and link the program even if the unit name
8327 given on the command line is a package name. The resulting executable
8328 will execute the elaboration routines of the package and its closure,
8329 then the finalization routines.
8330
8331 @item ^-g^/DEBUG^
8332 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8333 Enable debugging. This switch is simply passed to the compiler and to the
8334 linker.
8335
8336 @end table
8337
8338 @table @asis
8339 @item @code{gcc} @asis{switches}
8340 @ifclear vms
8341 Any uppercase switch (other than @option{-A},
8342 @option{-L} or
8343 @option{-S}) or any switch that is more than one character is passed to
8344 @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8345 @end ifclear
8346 @ifset vms
8347 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8348 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8349 automatically treated as a compiler switch, and passed on to all
8350 compilations that are carried out.
8351 @end ifset
8352 @end table
8353
8354 @noindent
8355 Source and library search path switches:
8356
8357 @table @option
8358 @c !sort!
8359 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8360 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8361 When looking for source files also look in directory @var{dir}.
8362 The order in which source files search is undertaken is
8363 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8364
8365 @item ^-aL^/SKIP_MISSING=^@var{dir}
8366 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8367 Consider @var{dir} as being an externally provided Ada library.
8368 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8369 files have been located in directory @var{dir}. This allows you to have
8370 missing bodies for the units in @var{dir} and to ignore out of date bodies
8371 for the same units. You still need to specify
8372 the location of the specs for these units by using the switches
8373 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8374 or @option{^-I^/SEARCH=^@var{dir}}.
8375 Note: this switch is provided for compatibility with previous versions
8376 of @code{gnatmake}. The easier method of causing standard libraries
8377 to be excluded from consideration is to write-protect the corresponding
8378 ALI files.
8379
8380 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8381 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8382 When searching for library and object files, look in directory
8383 @var{dir}. The order in which library files are searched is described in
8384 @ref{Search Paths for gnatbind}.
8385
8386 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8387 @cindex Search paths, for @code{gnatmake}
8388 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8389 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8390 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8391
8392 @item ^-I^/SEARCH=^@var{dir}
8393 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8394 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8395 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8396
8397 @item ^-I-^/NOCURRENT_DIRECTORY^
8398 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8399 @cindex Source files, suppressing search
8400 Do not look for source files in the directory containing the source
8401 file named in the command line.
8402 Do not look for ALI or object files in the directory
8403 where @code{gnatmake} was invoked.
8404
8405 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8406 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8407 @cindex Linker libraries
8408 Add directory @var{dir} to the list of directories in which the linker
8409 will search for libraries. This is equivalent to
8410 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8411 @ifclear vms
8412 Furthermore, under Windows, the sources pointed to by the libraries path
8413 set in the registry are not searched for.
8414 @end ifclear
8415
8416 @item -nostdinc
8417 @cindex @option{-nostdinc} (@code{gnatmake})
8418 Do not look for source files in the system default directory.
8419
8420 @item -nostdlib
8421 @cindex @option{-nostdlib} (@code{gnatmake})
8422 Do not look for library files in the system default directory.
8423
8424 @item --RTS=@var{rts-path}
8425 @cindex @option{--RTS} (@code{gnatmake})
8426 Specifies the default location of the runtime library. GNAT looks for the
8427 runtime
8428 in the following directories, and stops as soon as a valid runtime is found
8429 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8430 @file{ada_object_path} present):
8431
8432 @itemize @bullet
8433 @item <current directory>/$rts_path
8434
8435 @item <default-search-dir>/$rts_path
8436
8437 @item <default-search-dir>/rts-$rts_path
8438 @end itemize
8439
8440 @noindent
8441 The selected path is handled like a normal RTS path.
8442
8443 @end table
8444
8445 @node Mode Switches for gnatmake
8446 @section Mode Switches for @code{gnatmake}
8447
8448 @noindent
8449 The mode switches (referred to as @code{mode_switches}) allow the
8450 inclusion of switches that are to be passed to the compiler itself, the
8451 binder or the linker. The effect of a mode switch is to cause all
8452 subsequent switches up to the end of the switch list, or up to the next
8453 mode switch, to be interpreted as switches to be passed on to the
8454 designated component of GNAT.
8455
8456 @table @option
8457 @c !sort!
8458 @item -cargs @var{switches}
8459 @cindex @option{-cargs} (@code{gnatmake})
8460 Compiler switches. Here @var{switches} is a list of switches
8461 that are valid switches for @code{gcc}. They will be passed on to
8462 all compile steps performed by @code{gnatmake}.
8463
8464 @item -bargs @var{switches}
8465 @cindex @option{-bargs} (@code{gnatmake})
8466 Binder switches. Here @var{switches} is a list of switches
8467 that are valid switches for @code{gnatbind}. They will be passed on to
8468 all bind steps performed by @code{gnatmake}.
8469
8470 @item -largs @var{switches}
8471 @cindex @option{-largs} (@code{gnatmake})
8472 Linker switches. Here @var{switches} is a list of switches
8473 that are valid switches for @code{gnatlink}. They will be passed on to
8474 all link steps performed by @code{gnatmake}.
8475
8476 @item -margs @var{switches}
8477 @cindex @option{-margs} (@code{gnatmake})
8478 Make switches. The switches are directly interpreted by @code{gnatmake},
8479 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8480 or @option{-largs}.
8481 @end table
8482
8483 @node Notes on the Command Line
8484 @section Notes on the Command Line
8485
8486 @noindent
8487 This section contains some additional useful notes on the operation
8488 of the @code{gnatmake} command.
8489
8490 @itemize @bullet
8491 @item
8492 @cindex Recompilation, by @code{gnatmake}
8493 If @code{gnatmake} finds no ALI files, it recompiles the main program
8494 and all other units required by the main program.
8495 This means that @code{gnatmake}
8496 can be used for the initial compile, as well as during subsequent steps of
8497 the development cycle.
8498
8499 @item
8500 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8501 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8502 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8503 warning.
8504
8505 @item
8506 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8507 is used to specify both source and
8508 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8509 instead if you just want to specify
8510 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8511 if you want to specify library paths
8512 only.
8513
8514 @item
8515 @code{gnatmake} examines both an ALI file and its corresponding object file
8516 for consistency. If an ALI is more recent than its corresponding object,
8517 or if the object file is missing, the corresponding source will be recompiled.
8518 Note that @code{gnatmake} expects an ALI and the corresponding object file
8519 to be in the same directory.
8520
8521 @item
8522 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8523 This may conveniently be used to exclude standard libraries from
8524 consideration and in particular it means that the use of the
8525 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8526 unless @option{^-a^/ALL_FILES^} is also specified.
8527
8528 @item
8529 @code{gnatmake} has been designed to make the use of Ada libraries
8530 particularly convenient. Assume you have an Ada library organized
8531 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8532 of your Ada compilation units,
8533 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8534 specs of these units, but no bodies. Then to compile a unit
8535 stored in @code{main.adb}, which uses this Ada library you would just type
8536
8537 @smallexample
8538 @ifclear vms
8539 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8540 @end ifclear
8541 @ifset vms
8542 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8543            /SKIP_MISSING=@i{[OBJ_DIR]} main
8544 @end ifset
8545 @end smallexample
8546
8547 @item
8548 Using @code{gnatmake} along with the
8549 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8550 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8551 this switch,
8552 you can update the comments/format of your
8553 source files without having to recompile everything. Note, however, that
8554 adding or deleting lines in a source files may render its debugging
8555 info obsolete. If the file in question is a spec, the impact is rather
8556 limited, as that debugging info will only be useful during the
8557 elaboration phase of your program. For bodies the impact can be more
8558 significant. In all events, your debugger will warn you if a source file
8559 is more recent than the corresponding object, and alert you to the fact
8560 that the debugging information may be out of date.
8561 @end itemize
8562
8563 @node How gnatmake Works
8564 @section How @code{gnatmake} Works
8565
8566 @noindent
8567 Generally @code{gnatmake} automatically performs all necessary
8568 recompilations and you don't need to worry about how it works. However,
8569 it may be useful to have some basic understanding of the @code{gnatmake}
8570 approach and in particular to understand how it uses the results of
8571 previous compilations without incorrectly depending on them.
8572
8573 First a definition: an object file is considered @dfn{up to date} if the
8574 corresponding ALI file exists and its time stamp predates that of the
8575 object file and if all the source files listed in the
8576 dependency section of this ALI file have time stamps matching those in
8577 the ALI file. This means that neither the source file itself nor any
8578 files that it depends on have been modified, and hence there is no need
8579 to recompile this file.
8580
8581 @code{gnatmake} works by first checking if the specified main unit is up
8582 to date. If so, no compilations are required for the main unit. If not,
8583 @code{gnatmake} compiles the main program to build a new ALI file that
8584 reflects the latest sources. Then the ALI file of the main unit is
8585 examined to find all the source files on which the main program depends,
8586 and @code{gnatmake} recursively applies the above procedure on all these files.
8587
8588 This process ensures that @code{gnatmake} only trusts the dependencies
8589 in an existing ALI file if they are known to be correct. Otherwise it
8590 always recompiles to determine a new, guaranteed accurate set of
8591 dependencies. As a result the program is compiled ``upside down'' from what may
8592 be more familiar as the required order of compilation in some other Ada
8593 systems. In particular, clients are compiled before the units on which
8594 they depend. The ability of GNAT to compile in any order is critical in
8595 allowing an order of compilation to be chosen that guarantees that
8596 @code{gnatmake} will recompute a correct set of new dependencies if
8597 necessary.
8598
8599 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8600 imported by several of the executables, it will be recompiled at most once.
8601
8602 Note: when using non-standard naming conventions
8603 (See @ref{Using Other File Names}), changing through a configuration pragmas
8604 file the version of a source and invoking @code{gnatmake} to recompile may
8605 have no effect, if the previous version of the source is still accessible
8606 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8607
8608 @node Examples of gnatmake Usage
8609 @section Examples of @code{gnatmake} Usage
8610
8611 @table @code
8612 @item gnatmake hello.adb
8613 Compile all files necessary to bind and link the main program
8614 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8615 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8616
8617 @item gnatmake main1 main2 main3
8618 Compile all files necessary to bind and link the main programs
8619 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8620 (containing unit @code{Main2}) and @file{main3.adb}
8621 (containing unit @code{Main3}) and bind and link the resulting object files
8622 to generate three executable files @file{^main1^MAIN1.EXE^},
8623 @file{^main2^MAIN2.EXE^}
8624 and @file{^main3^MAIN3.EXE^}.
8625
8626 @ifclear vms
8627 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8628 @end ifclear
8629
8630 @ifset vms
8631 @item gnatmake Main_Unit /QUIET
8632    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8633    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8634 @end ifset
8635 Compile all files necessary to bind and link the main program unit
8636 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8637 be done with optimization level 2 and the order of elaboration will be
8638 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8639 displaying commands it is executing.
8640 @end table
8641
8642
8643 @c *************************
8644 @node Improving Performance
8645 @chapter Improving Performance
8646 @cindex Improving performance
8647
8648 @noindent
8649 This chapter presents several topics related to program performance.
8650 It first describes some of the tradeoffs that need to be considered
8651 and some of the techniques for making your program run faster.
8652 It then documents the @command{gnatelim} tool, which can reduce
8653 the size of program executables.
8654
8655 @ifinfo
8656 @menu
8657 * Performance Considerations::
8658 * Reducing the Size of Ada Executables with gnatelim::
8659 @end menu
8660 @end ifinfo
8661
8662
8663 @c *****************************
8664 @node Performance Considerations
8665 @section Performance Considerations
8666
8667 @noindent
8668 The GNAT system provides a number of options that allow a trade-off
8669 between
8670
8671 @itemize @bullet
8672 @item
8673 performance of the generated code
8674
8675 @item
8676 speed of compilation
8677
8678 @item
8679 minimization of dependences and recompilation
8680
8681 @item
8682 the degree of run-time checking.
8683 @end itemize
8684
8685 @noindent
8686 The defaults (if no options are selected) aim at improving the speed
8687 of compilation and minimizing dependences, at the expense of performance
8688 of the generated code:
8689
8690 @itemize @bullet
8691 @item
8692 no optimization
8693
8694 @item
8695 no inlining of subprogram calls
8696
8697 @item
8698 all run-time checks enabled except overflow and elaboration checks
8699 @end itemize
8700
8701 @noindent
8702 These options are suitable for most program development purposes. This
8703 chapter describes how you can modify these choices, and also provides
8704 some guidelines on debugging optimized code.
8705
8706 @menu
8707 * Controlling Run-Time Checks::
8708 * Use of Restrictions::
8709 * Optimization Levels::
8710 * Debugging Optimized Code::
8711 * Inlining of Subprograms::
8712 * Optimization and Strict Aliasing::
8713 @ifset vms
8714 * Coverage Analysis::
8715 @end ifset
8716 @end menu
8717
8718 @node Controlling Run-Time Checks
8719 @subsection Controlling Run-Time Checks
8720
8721 @noindent
8722 By default, GNAT generates all run-time checks, except arithmetic overflow
8723 checking for integer operations and checks for access before elaboration on
8724 subprogram calls. The latter are not required in default mode, because all
8725 necessary checking is done at compile time.
8726 @cindex @option{-gnatp} (@code{gcc})
8727 @cindex @option{-gnato} (@code{gcc})
8728 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8729 be modified. @xref{Run-Time Checks}.
8730
8731 Our experience is that the default is suitable for most development
8732 purposes.
8733
8734 We treat integer overflow specially because these
8735 are quite expensive and in our experience are not as important as other
8736 run-time checks in the development process. Note that division by zero
8737 is not considered an overflow check, and divide by zero checks are
8738 generated where required by default.
8739
8740 Elaboration checks are off by default, and also not needed by default, since
8741 GNAT uses a static elaboration analysis approach that avoids the need for
8742 run-time checking. This manual contains a full chapter discussing the issue
8743 of elaboration checks, and if the default is not satisfactory for your use,
8744 you should read this chapter.
8745
8746 For validity checks, the minimal checks required by the Ada Reference
8747 Manual (for case statements and assignments to array elements) are on
8748 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8749 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8750 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8751 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8752 are also suppressed entirely if @option{-gnatp} is used.
8753
8754 @cindex Overflow checks
8755 @cindex Checks, overflow
8756 @findex Suppress
8757 @findex Unsuppress
8758 @cindex pragma Suppress
8759 @cindex pragma Unsuppress
8760 Note that the setting of the switches controls the default setting of
8761 the checks. They may be modified using either @code{pragma Suppress} (to
8762 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8763 checks) in the program source.
8764
8765 @node Use of Restrictions
8766 @subsection Use of Restrictions
8767
8768 @noindent
8769 The use of pragma Restrictions allows you to control which features are
8770 permitted in your program. Apart from the obvious point that if you avoid
8771 relatively expensive features like finalization (enforceable by the use
8772 of pragma Restrictions (No_Finalization), the use of this pragma does not
8773 affect the generated code in most cases.
8774
8775 One notable exception to this rule is that the possibility of task abort
8776 results in some distributed overhead, particularly if finalization or
8777 exception handlers are used. The reason is that certain sections of code
8778 have to be marked as non-abortable.
8779
8780 If you use neither the @code{abort} statement, nor asynchronous transfer
8781 of control (@code{select .. then abort}), then this distributed overhead
8782 is removed, which may have a general positive effect in improving
8783 overall performance.  Especially code involving frequent use of tasking
8784 constructs and controlled types will show much improved performance.
8785 The relevant restrictions pragmas are
8786
8787 @smallexample
8788    pragma Restrictions (No_Abort_Statements);
8789    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8790 @end smallexample
8791
8792 @noindent
8793 It is recommended that these restriction pragmas be used if possible. Note
8794 that this also means that you can write code without worrying about the
8795 possibility of an immediate abort at any point.
8796
8797 @node Optimization Levels
8798 @subsection Optimization Levels
8799 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8800
8801 @noindent
8802 The default is optimization off. This results in the fastest compile
8803 times, but GNAT makes absolutely no attempt to optimize, and the
8804 generated programs are considerably larger and slower than when
8805 optimization is enabled. You can use the
8806 @ifclear vms
8807 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8808 @end ifclear
8809 @ifset vms
8810 @code{OPTIMIZE} qualifier
8811 @end ifset
8812 to @code{gcc} to control the optimization level:
8813
8814 @table @option
8815 @item ^-O0^/OPTIMIZE=NONE^
8816 No optimization (the default);
8817 generates unoptimized code but has
8818 the fastest compilation time.
8819
8820 @item ^-O1^/OPTIMIZE=SOME^
8821 Medium level optimization;
8822 optimizes reasonably well but does not
8823 degrade compilation time significantly.
8824
8825 @item ^-O2^/OPTIMIZE=ALL^
8826 @ifset vms
8827 @itemx /OPTIMIZE=DEVELOPMENT
8828 @end ifset
8829 Full optimization;
8830 generates highly optimized code and has
8831 the slowest compilation time.
8832
8833 @item ^-O3^/OPTIMIZE=INLINING^
8834 Full optimization as in @option{-O2},
8835 and also attempts automatic inlining of small
8836 subprograms within a unit (@pxref{Inlining of Subprograms}).
8837 @end table
8838
8839 @noindent
8840 Higher optimization levels perform more global transformations on the
8841 program and apply more expensive analysis algorithms in order to generate
8842 faster and more compact code. The price in compilation time, and the
8843 resulting improvement in execution time,
8844 both depend on the particular application and the hardware environment.
8845 You should experiment to find the best level for your application.
8846
8847 Since the precise set of optimizations done at each level will vary from
8848 release to release (and sometime from target to target), it is best to think
8849 of the optimization settings in general terms.
8850 The @cite{Using GNU GCC} manual contains details about
8851 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8852 individually enable or disable specific optimizations.
8853
8854 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8855 been tested extensively at all optimization levels. There are some bugs
8856 which appear only with optimization turned on, but there have also been
8857 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8858 level of optimization does not improve the reliability of the code
8859 generator, which in practice is highly reliable at all optimization
8860 levels.
8861
8862 Note regarding the use of @option{-O3}: The use of this optimization level
8863 is generally discouraged with GNAT, since it often results in larger
8864 executables which run more slowly. See further discussion of this point
8865 in @pxref{Inlining of Subprograms}.
8866
8867
8868 @node Debugging Optimized Code
8869 @subsection Debugging Optimized Code
8870 @cindex Debugging optimized code
8871 @cindex Optimization and debugging
8872
8873 @noindent
8874 Although it is possible to do a reasonable amount of debugging at
8875 @ifclear vms
8876 non-zero optimization levels,
8877 the higher the level the more likely that
8878 @end ifclear
8879 @ifset vms
8880 @option{/OPTIMIZE} settings other than @code{NONE},
8881 such settings will make it more likely that
8882 @end ifset
8883 source-level constructs will have been eliminated by optimization.
8884 For example, if a loop is strength-reduced, the loop
8885 control variable may be completely eliminated and thus cannot be
8886 displayed in the debugger.
8887 This can only happen at @option{-O2} or @option{-O3}.
8888 Explicit temporary variables that you code might be eliminated at
8889 ^level^setting^ @option{-O1} or higher.
8890
8891 The use of the @option{^-g^/DEBUG^} switch,
8892 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8893 which is needed for source-level debugging,
8894 affects the size of the program executable on disk,
8895 and indeed the debugging information can be quite large.
8896 However, it has no effect on the generated code (and thus does not
8897 degrade performance)
8898
8899 Since the compiler generates debugging tables for a compilation unit before
8900 it performs optimizations, the optimizing transformations may invalidate some
8901 of the debugging data.  You therefore need to anticipate certain
8902 anomalous situations that may arise while debugging optimized code.
8903 These are the most common cases:
8904
8905 @enumerate
8906 @item
8907 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8908 commands show
8909 the PC bouncing back and forth in the code.  This may result from any of
8910 the following optimizations:
8911
8912 @itemize @bullet
8913 @item
8914 @i{Common subexpression elimination:} using a single instance of code for a
8915 quantity that the source computes several times.  As a result you
8916 may not be able to stop on what looks like a statement.
8917
8918 @item
8919 @i{Invariant code motion:} moving an expression that does not change within a
8920 loop, to the beginning of the loop.
8921
8922 @item
8923 @i{Instruction scheduling:} moving instructions so as to
8924 overlap loads and stores (typically) with other code, or in
8925 general to move computations of values closer to their uses. Often
8926 this causes you to pass an assignment statement without the assignment
8927 happening and then later bounce back to the statement when the
8928 value is actually needed.  Placing a breakpoint on a line of code
8929 and then stepping over it may, therefore, not always cause all the
8930 expected side-effects.
8931 @end itemize
8932
8933 @item
8934 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8935 two identical pieces of code are merged and the program counter suddenly
8936 jumps to a statement that is not supposed to be executed, simply because
8937 it (and the code following) translates to the same thing as the code
8938 that @emph{was} supposed to be executed.  This effect is typically seen in
8939 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8940 a @code{break} in a C @code{^switch^switch^} statement.
8941
8942 @item
8943 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8944 There are various reasons for this effect:
8945
8946 @itemize @bullet
8947 @item
8948 In a subprogram prologue, a parameter may not yet have been moved to its
8949 ``home''.
8950
8951 @item
8952 A variable may be dead, and its register re-used.  This is
8953 probably the most common cause.
8954
8955 @item
8956 As mentioned above, the assignment of a value to a variable may
8957 have been moved.
8958
8959 @item
8960 A variable may be eliminated entirely by value propagation or
8961 other means.  In this case, GCC may incorrectly generate debugging
8962 information for the variable
8963 @end itemize
8964
8965 @noindent
8966 In general, when an unexpected value appears for a local variable or parameter
8967 you should first ascertain if that value was actually computed by
8968 your program, as opposed to being incorrectly reported by the debugger.
8969 Record fields or
8970 array elements in an object designated by an access value
8971 are generally less of a problem, once you have ascertained that the access
8972 value is sensible.
8973 Typically, this means checking variables in the preceding code and in the
8974 calling subprogram to verify that the value observed is explainable from other
8975 values (one must apply the procedure recursively to those
8976 other values); or re-running the code and stopping a little earlier
8977 (perhaps before the call) and stepping to better see how the variable obtained
8978 the value in question; or continuing to step @emph{from} the point of the
8979 strange value to see if code motion had simply moved the variable's
8980 assignments later.
8981 @end enumerate
8982
8983 @noindent
8984 In light of such anomalies, a recommended technique is to use @option{-O0}
8985 early in the software development cycle, when extensive debugging capabilities
8986 are most needed, and then move to @option{-O1} and later @option{-O2} as
8987 the debugger becomes less critical.
8988 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
8989 a release management issue.
8990 @ifclear vms
8991 Note that if you use @option{-g} you can then use the @command{strip} program
8992 on the resulting executable,
8993 which removes both debugging information and global symbols.
8994 @end ifclear
8995
8996
8997 @node Inlining of Subprograms
8998 @subsection Inlining of Subprograms
8999
9000 @noindent
9001 A call to a subprogram in the current unit is inlined if all the
9002 following conditions are met:
9003
9004 @itemize @bullet
9005 @item
9006 The optimization level is at least @option{-O1}.
9007
9008 @item
9009 The called subprogram is suitable for inlining: It must be small enough
9010 and not contain nested subprograms or anything else that @code{gcc}
9011 cannot support in inlined subprograms.
9012
9013 @item
9014 The call occurs after the definition of the body of the subprogram.
9015
9016 @item
9017 @cindex pragma Inline
9018 @findex Inline
9019 Either @code{pragma Inline} applies to the subprogram or it is
9020 small and automatic inlining (optimization level @option{-O3}) is
9021 specified.
9022 @end itemize
9023
9024 @noindent
9025 Calls to subprograms in @code{with}'ed units are normally not inlined.
9026 To achieve this level of inlining, the following conditions must all be
9027 true:
9028
9029 @itemize @bullet
9030 @item
9031 The optimization level is at least @option{-O1}.
9032
9033 @item
9034 The called subprogram is suitable for inlining: It must be small enough
9035 and not contain nested subprograms or anything else @code{gcc} cannot
9036 support in inlined subprograms.
9037
9038 @item
9039 The call appears in a body (not in a package spec).
9040
9041 @item
9042 There is a @code{pragma Inline} for the subprogram.
9043
9044 @item
9045 @cindex @option{-gnatn} (@code{gcc})
9046 The @option{^-gnatn^/INLINE^} switch
9047 is used in the @code{gcc} command line
9048 @end itemize
9049
9050 Note that specifying the @option{-gnatn} switch causes additional
9051 compilation dependencies. Consider the following:
9052
9053 @smallexample @c ada
9054 @cartouche
9055 package R is
9056    procedure Q;
9057    pragma Inline (Q);
9058 end R;
9059 package body R is
9060    ...
9061 end R;
9062
9063 with R;
9064 procedure Main is
9065 begin
9066    ...
9067    R.Q;
9068 end Main;
9069 @end cartouche
9070 @end smallexample
9071
9072 @noindent
9073 With the default behavior (no @option{-gnatn} switch specified), the
9074 compilation of the @code{Main} procedure depends only on its own source,
9075 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9076 means that editing the body of @code{R} does not require recompiling
9077 @code{Main}.
9078
9079 On the other hand, the call @code{R.Q} is not inlined under these
9080 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9081 is compiled, the call will be inlined if the body of @code{Q} is small
9082 enough, but now @code{Main} depends on the body of @code{R} in
9083 @file{r.adb} as well as on the spec. This means that if this body is edited,
9084 the main program must be recompiled. Note that this extra dependency
9085 occurs whether or not the call is in fact inlined by @code{gcc}.
9086
9087 The use of front end inlining with @option{-gnatN} generates similar
9088 additional dependencies.
9089
9090 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9091 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9092 can be used to prevent
9093 all inlining. This switch overrides all other conditions and ensures
9094 that no inlining occurs. The extra dependences resulting from
9095 @option{-gnatn} will still be active, even if
9096 this switch is used to suppress the resulting inlining actions.
9097
9098 Note regarding the use of @option{-O3}: There is no difference in inlining
9099 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9100 pragma @code{Inline} assuming the use of @option{-gnatn}
9101 or @option{-gnatN} (the switches that activate inlining). If you have used
9102 pragma @code{Inline} in appropriate cases, then it is usually much better
9103 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9104 in this case only has the effect of inlining subprograms you did not
9105 think should be inlined. We often find that the use of @option{-O3} slows
9106 down code by performing excessive inlining, leading to increased instruction
9107 cache pressure from the increased code size. So the bottom line here is
9108 that you should not automatically assume that @option{-O3} is better than
9109 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9110 it actually improves performance.
9111
9112 @node Optimization and Strict Aliasing
9113 @subsection Optimization and Strict Aliasing
9114 @cindex Aliasing
9115 @cindex Strict Aliasing
9116 @cindex No_Strict_Aliasing
9117
9118 @noindent
9119 The strong typing capabilities of Ada allow an optimizer to generate
9120 efficient code in situations where other languages would be forced to
9121 make worst case assumptions preventing such optimizations. Consider
9122 the following example:
9123
9124 @smallexample @c ada
9125 @cartouche
9126 procedure R is
9127    type Int1 is new Integer;
9128    type Int2 is new Integer;
9129    type Int1A is access Int1;
9130    type Int2A is access Int2;
9131    Int1V : Int1A;
9132    Int2V : Int2A;
9133    ...
9134
9135 begin
9136    ...
9137    for J in Data'Range loop
9138       if Data (J) = Int1V.all then
9139          Int2V.all := Int2V.all + 1;
9140       end if;
9141    end loop;
9142    ...
9143 end R;
9144 @end cartouche
9145 @end smallexample
9146
9147 @noindent
9148 In this example, since the variable @code{Int1V} can only access objects
9149 of type @code{Int1}, and @code{Int2V} can only access objects of type
9150 @code{Int2}, there is no possibility that the assignment to
9151 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9152 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9153 for all iterations of the loop and avoid the extra memory reference
9154 required to dereference it each time through the loop.
9155
9156 This kind of optimziation, called strict aliasing analysis, is
9157 triggered by specifying an optimization level of @option{-O2} or
9158 higher and allows @code{GNAT} to generate more efficient code
9159 when access values are involved.
9160
9161 However, although this optimization is always correct in terms of
9162 the formal semantics of the Ada Reference Manual, difficulties can
9163 arise if features like @code{Unchecked_Conversion} are used to break
9164 the typing system. Consider the following complete program example:
9165
9166 @smallexample @c ada
9167 @cartouche
9168 package p1 is
9169    type int1 is new integer;
9170    type int2 is new integer;
9171    type a1 is access int1;
9172    type a2 is access int2;
9173 end p1;
9174
9175 with p1; use p1;
9176 package p2 is
9177    function to_a2 (Input : a1) return a2;
9178 end p2;
9179
9180 with Unchecked_Conversion;
9181 package body p2 is
9182    function to_a2 (Input : a1) return a2 is
9183       function to_a2u is
9184         new Unchecked_Conversion (a1, a2);
9185    begin
9186       return to_a2u (Input);
9187    end to_a2;
9188 end p2;
9189
9190 with p2; use p2;
9191 with p1; use p1;
9192 with Text_IO; use Text_IO;
9193 procedure m is
9194    v1 : a1 := new int1;
9195    v2 : a2 := to_a2 (v1);
9196 begin
9197    v1.all := 1;
9198    v2.all := 0;
9199    put_line (int1'image (v1.all));
9200 end;
9201 @end cartouche
9202 @end smallexample
9203
9204 @noindent
9205 This program prints out 0 in @code{-O0} or @code{-O1}
9206 mode, but it prints out 1 in @code{-O2} mode. That's
9207 because in strict aliasing mode, the compiler can and
9208 does assume that the assignment to @code{v2.all} could not
9209 affect the value of @code{v1.all}, since different types
9210 are involved.
9211
9212 This behavior is not a case of non-conformance with the standard, since
9213 the Ada RM specifies that an unchecked conversion where the resulting
9214 bit pattern is not a correct value of the target type can result in an
9215 abnormal value and attempting to reference an abnormal value makes the
9216 execution of a program erroneous.  That's the case here since the result
9217 does not point to an object of type @code{int2}.  This means that the
9218 effect is entirely unpredictable.
9219
9220 However, although that explanation may satisfy a language
9221 lawyer, in practice an applications programmer expects an
9222 unchecked conversion involving pointers to create true
9223 aliases and the behavior of printing 1 seems plain wrong.
9224 In this case, the strict aliasing optimization is unwelcome.
9225
9226 Indeed the compiler recognizes this possibility, and the
9227 unchecked conversion generates a warning:
9228
9229 @smallexample
9230 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9231 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9232 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9233 @end smallexample
9234
9235 @noindent
9236 Unfortunately the problem is recognized when compiling the body of
9237 package @code{p2}, but the actual "bad" code is generated while
9238 compiling the body of @code{m} and this latter compilation does not see
9239 the suspicious @code{Unchecked_Conversion}.
9240
9241 As implied by the warning message, there are approaches you can use to
9242 avoid the unwanted strict aliasing optimization in a case like this.
9243
9244 One possibility is to simply avoid the use of @code{-O2}, but
9245 that is a bit drastic, since it throws away a number of useful
9246 optimizations that do not involve strict aliasing assumptions.
9247
9248 A less drastic approach is to compile the program using the
9249 option @code{-fno-strict-aliasing}. Actually it is only the
9250 unit containing the dereferencing of the suspicious pointer
9251 that needs to be compiled. So in this case, if we compile
9252 unit @code{m} with this switch, then we get the expected
9253 value of zero printed. Analyzing which units might need
9254 the switch can be painful, so a more reasonable approach
9255 is to compile the entire program with options @code{-O2}
9256 and @code{-fno-strict-aliasing}. If the performance is
9257 satisfactory with this combination of options, then the
9258 advantage is that the entire issue of possible "wrong"
9259 optimization due to strict aliasing is avoided.
9260
9261 To avoid the use of compiler switches, the configuration
9262 pragma @code{No_Strict_Aliasing} with no parameters may be
9263 used to specify that for all access types, the strict
9264 aliasing optimization should be suppressed.
9265
9266 However, these approaches are still overkill, in that they causes
9267 all manipulations of all access values to be deoptimized. A more
9268 refined approach is to concentrate attention on the specific
9269 access type identified as problematic.
9270
9271 First, if a careful analysis of uses of the pointer shows
9272 that there are no possible problematic references, then
9273 the warning can be suppressed by bracketing the
9274 instantiation of @code{Unchecked_Conversion} to turn
9275 the warning off:
9276
9277 @smallexample @c ada
9278    pragma Warnings (Off);
9279    function to_a2u is
9280      new Unchecked_Conversion (a1, a2);
9281    pragma Warnings (On);
9282 @end smallexample
9283
9284 @noindent
9285 Of course that approach is not appropriate for this particular
9286 example, since indeed there is a problematic reference. In this
9287 case we can take one of two other approaches.
9288
9289 The first possibility is to move the instantiation of unchecked
9290 conversion to the unit in which the type is declared. In
9291 this example, we would move the instantiation of
9292 @code{Unchecked_Conversion} from the body of package
9293 @code{p2} to the spec of package @code{p1}. Now the
9294 warning disappears. That's because any use of the
9295 access type knows there is a suspicious unchecked
9296 conversion, and the strict aliasing optimization
9297 is automatically suppressed for the type.
9298
9299 If it is not practical to move the unchecked conversion to the same unit
9300 in which the destination access type is declared (perhaps because the
9301 source type is not visible in that unit), you may use pragma
9302 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9303 same declarative sequence as the declaration of the access type:
9304
9305 @smallexample @c ada
9306    type a2 is access int2;
9307    pragma No_Strict_Aliasing (a2);
9308 @end smallexample
9309
9310 @noindent
9311 Here again, the compiler now knows that the strict aliasing optimization
9312 should be suppressed for any reference to type @code{a2} and the
9313 expected behavior is obtained.
9314
9315 Finally, note that although the compiler can generate warnings for
9316 simple cases of unchecked conversions, there are tricker and more
9317 indirect ways of creating type incorrect aliases which the compiler
9318 cannot detect. Examples are the use of address overlays and unchecked
9319 conversions involving composite types containing access types as
9320 components. In such cases, no warnings are generated, but there can
9321 still be aliasing problems. One safe coding practice is to forbid the
9322 use of address clauses for type overlaying, and to allow unchecked
9323 conversion only for primitive types. This is not really a significant
9324 restriction since any possible desired effect can be achieved by
9325 unchecked conversion of access values.
9326
9327 @ifset vms
9328 @node Coverage Analysis
9329 @subsection Coverage Analysis
9330
9331 @noindent
9332 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9333 the user to determine the distribution of execution time across a program,
9334 @pxref{Profiling} for details of usage.
9335 @end ifset
9336
9337 @node Reducing the Size of Ada Executables with gnatelim
9338 @section Reducing the Size of Ada Executables with @code{gnatelim}
9339 @findex gnatelim
9340
9341 @noindent
9342 This section describes @command{gnatelim}, a tool which detects unused
9343 subprograms and helps the compiler to create a smaller executable for your
9344 program.
9345
9346 @menu
9347 * About gnatelim::
9348 * Running gnatelim::
9349 * Correcting the List of Eliminate Pragmas::
9350 * Making Your Executables Smaller::
9351 * Summary of the gnatelim Usage Cycle::
9352 @end menu
9353
9354 @node About gnatelim
9355 @subsection About @code{gnatelim}
9356
9357 @noindent
9358 When a program shares a set of Ada
9359 packages with other programs, it may happen that this program uses
9360 only a fraction of the subprograms defined in these packages. The code
9361 created for these unused subprograms increases the size of the executable.
9362
9363 @code{gnatelim} tracks unused subprograms in an Ada program and
9364 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9365 subprograms that are declared but never called. By placing the list of
9366 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9367 recompiling your program, you may decrease the size of its executable,
9368 because the compiler will not generate the code for 'eliminated' subprograms.
9369 See GNAT Reference Manual for more information about this pragma.
9370
9371 @code{gnatelim} needs as its input data the name of the main subprogram
9372 and a bind file for a main subprogram.
9373
9374 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9375 the main subprogram. @code{gnatelim} can work with both Ada and C
9376 bind files; when both are present, it uses the Ada bind file.
9377 The following commands will build the program and create the bind file:
9378
9379 @smallexample
9380 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9381 $ gnatbind main_prog
9382 @end smallexample
9383
9384 Note that @code{gnatelim} needs neither object nor ALI files.
9385
9386 @node Running gnatelim
9387 @subsection Running @code{gnatelim}
9388
9389 @noindent
9390 @code{gnatelim} has the following command-line interface:
9391
9392 @smallexample
9393 $ gnatelim [options] name
9394 @end smallexample
9395
9396 @noindent
9397 @code{name} should be a name of a source file that contains the main subprogram
9398 of a program (partition).
9399
9400 @code{gnatelim} has the following switches:
9401
9402 @table @option
9403 @c !sort!
9404 @item ^-q^/QUIET^
9405 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9406 Quiet mode: by default @code{gnatelim} outputs to the standard error
9407 stream the number of program units left to be processed. This option turns
9408 this trace off.
9409
9410 @item ^-v^/VERBOSE^
9411 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9412 Verbose mode: @code{gnatelim} version information is printed as Ada
9413 comments to the standard output stream. Also, in addition to the number of
9414 program units left @code{gnatelim} will output the name of the current unit
9415 being processed.
9416
9417 @item ^-a^/ALL^
9418 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9419 Also look for subprograms from the GNAT run time that can be eliminated. Note
9420 that when @file{gnat.adc} is produced using this switch, the entire program
9421 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9422
9423 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9424 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9425 When looking for source files also look in directory @var{dir}. Specifying
9426 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9427 sources in the current directory.
9428
9429 @item ^-b^/BIND_FILE=^@var{bind_file}
9430 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9431 Specifies @var{bind_file} as the bind file to process. If not set, the name
9432 of the bind file is computed from the full expanded Ada name
9433 of a main subprogram.
9434
9435 @item ^-C^/CONFIG_FILE=^@var{config_file}
9436 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9437 Specifies a file @var{config_file} that contains configuration pragmas. The
9438 file must be specified with full path.
9439
9440 @item ^--GCC^/COMPILER^=@var{compiler_name}
9441 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9442 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9443 available on the path.
9444
9445 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9446 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9447 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9448 available on the path.
9449
9450 @item -d@var{x}
9451 @cindex @option{-d@var{x}} (@command{gnatelim})
9452 Activate internal debugging switches. @var{x} is a letter or digit, or
9453 string of letters or digits, which specifies the type of debugging
9454 mode desired.  Normally these are used only for internal development
9455 or system debugging purposes. You can find full documentation for these
9456 switches in the spec of the @code{Gnatelim} unit in the compiler
9457 source file @file{gnatelim.ads}.
9458 @end table
9459
9460 @noindent
9461 @code{gnatelim} sends its output to the standard output stream, and all the
9462 tracing and debug information is sent to the standard error stream.
9463 In order to produce a proper GNAT configuration file
9464 @file{gnat.adc}, redirection must be used:
9465
9466 @smallexample
9467 @ifset vms
9468 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9469 @end ifset
9470 @ifclear vms
9471 $ gnatelim main_prog.adb > gnat.adc
9472 @end ifclear
9473 @end smallexample
9474
9475 @ifclear vms
9476 @noindent
9477 or
9478
9479 @smallexample
9480 $ gnatelim main_prog.adb >> gnat.adc
9481 @end smallexample
9482
9483 @noindent
9484 in order to append the @code{gnatelim} output to the existing contents of
9485 @file{gnat.adc}.
9486 @end ifclear
9487
9488 @node Correcting the List of Eliminate Pragmas
9489 @subsection Correcting the List of Eliminate Pragmas
9490
9491 @noindent
9492 In some rare cases @code{gnatelim} may try to eliminate
9493 subprograms that are actually called in the program. In this case, the
9494 compiler will generate an error message of the form:
9495
9496 @smallexample
9497 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9498 @end smallexample
9499
9500 @noindent
9501 You will need to manually remove the wrong @code{Eliminate} pragmas from
9502 the @file{gnat.adc} file. You should recompile your program
9503 from scratch after that, because you need a consistent @file{gnat.adc} file
9504 during the entire compilation.
9505
9506
9507 @node Making Your Executables Smaller
9508 @subsection Making Your Executables Smaller
9509
9510 @noindent
9511 In order to get a smaller executable for your program you now have to
9512 recompile the program completely with the new @file{gnat.adc} file
9513 created by @code{gnatelim} in your current directory:
9514
9515 @smallexample
9516 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9517 @end smallexample
9518
9519 @noindent
9520 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9521 recompile everything
9522 with the set of pragmas @code{Eliminate} that you have obtained with
9523 @command{gnatelim}).
9524
9525 Be aware that the set of @code{Eliminate} pragmas is specific to each
9526 program. It is not recommended to merge sets of @code{Eliminate}
9527 pragmas created for different programs in one @file{gnat.adc} file.
9528
9529 @node Summary of the gnatelim Usage Cycle
9530 @subsection Summary of the gnatelim Usage Cycle
9531
9532 @noindent
9533 Here is a quick summary of the steps to be taken in order to reduce
9534 the size of your executables with @code{gnatelim}. You may use
9535 other GNAT options to control the optimization level,
9536 to produce the debugging information, to set search path, etc.
9537
9538 @enumerate
9539 @item
9540 Produce a bind file
9541
9542 @smallexample
9543 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9544 $ gnatbind main_prog
9545 @end smallexample
9546
9547 @item
9548 Generate a list of @code{Eliminate} pragmas
9549 @smallexample
9550 @ifset vms
9551 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9552 @end ifset
9553 @ifclear vms
9554 $ gnatelim main_prog >[>] gnat.adc
9555 @end ifclear
9556 @end smallexample
9557
9558 @item
9559 Recompile the application
9560
9561 @smallexample
9562 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9563 @end smallexample
9564
9565 @end enumerate
9566
9567
9568
9569
9570 @c ********************************
9571 @node Renaming Files Using gnatchop
9572 @chapter Renaming Files Using @code{gnatchop}
9573 @findex gnatchop
9574
9575 @noindent
9576 This chapter discusses how to handle files with multiple units by using
9577 the @code{gnatchop} utility. This utility is also useful in renaming
9578 files to meet the standard GNAT default file naming conventions.
9579
9580 @menu
9581 * Handling Files with Multiple Units::
9582 * Operating gnatchop in Compilation Mode::
9583 * Command Line for gnatchop::
9584 * Switches for gnatchop::
9585 * Examples of gnatchop Usage::
9586 @end menu
9587
9588 @node Handling Files with Multiple Units
9589 @section Handling Files with Multiple Units
9590
9591 @noindent
9592 The basic compilation model of GNAT requires that a file submitted to the
9593 compiler have only one unit and there be a strict correspondence
9594 between the file name and the unit name.
9595
9596 The @code{gnatchop} utility allows both of these rules to be relaxed,
9597 allowing GNAT to process files which contain multiple compilation units
9598 and files with arbitrary file names. @code{gnatchop}
9599 reads the specified file and generates one or more output files,
9600 containing one unit per file. The unit and the file name correspond,
9601 as required by GNAT.
9602
9603 If you want to permanently restructure a set of ``foreign'' files so that
9604 they match the GNAT rules, and do the remaining development using the
9605 GNAT structure, you can simply use @command{gnatchop} once, generate the
9606 new set of files and work with them from that point on.
9607
9608 Alternatively, if you want to keep your files in the ``foreign'' format,
9609 perhaps to maintain compatibility with some other Ada compilation
9610 system, you can set up a procedure where you use @command{gnatchop} each
9611 time you compile, regarding the source files that it writes as temporary
9612 files that you throw away.
9613
9614
9615 @node Operating gnatchop in Compilation Mode
9616 @section Operating gnatchop in Compilation Mode
9617
9618 @noindent
9619 The basic function of @code{gnatchop} is to take a file with multiple units
9620 and split it into separate files. The boundary between files is reasonably
9621 clear, except for the issue of comments and pragmas. In default mode, the
9622 rule is that any pragmas between units belong to the previous unit, except
9623 that configuration pragmas always belong to the following unit. Any comments
9624 belong to the following unit. These rules
9625 almost always result in the right choice of
9626 the split point without needing to mark it explicitly and most users will
9627 find this default to be what they want. In this default mode it is incorrect to
9628 submit a file containing only configuration pragmas, or one that ends in
9629 configuration pragmas, to @code{gnatchop}.
9630
9631 However, using a special option to activate ``compilation mode'',
9632 @code{gnatchop}
9633 can perform another function, which is to provide exactly the semantics
9634 required by the RM for handling of configuration pragmas in a compilation.
9635 In the absence of configuration pragmas (at the main file level), this
9636 option has no effect, but it causes such configuration pragmas to be handled
9637 in a quite different manner.
9638
9639 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9640 only configuration pragmas, then this file is appended to the
9641 @file{gnat.adc} file in the current directory. This behavior provides
9642 the required behavior described in the RM for the actions to be taken
9643 on submitting such a file to the compiler, namely that these pragmas
9644 should apply to all subsequent compilations in the same compilation
9645 environment. Using GNAT, the current directory, possibly containing a
9646 @file{gnat.adc} file is the representation
9647 of a compilation environment. For more information on the
9648 @file{gnat.adc} file, see the section on handling of configuration
9649 pragmas @pxref{Handling of Configuration Pragmas}.
9650
9651 Second, in compilation mode, if @code{gnatchop}
9652 is given a file that starts with
9653 configuration pragmas, and contains one or more units, then these
9654 configuration pragmas are prepended to each of the chopped files. This
9655 behavior provides the required behavior described in the RM for the
9656 actions to be taken on compiling such a file, namely that the pragmas
9657 apply to all units in the compilation, but not to subsequently compiled
9658 units.
9659
9660 Finally, if configuration pragmas appear between units, they are appended
9661 to the previous unit. This results in the previous unit being illegal,
9662 since the compiler does not accept configuration pragmas that follow
9663 a unit. This provides the required RM behavior that forbids configuration
9664 pragmas other than those preceding the first compilation unit of a
9665 compilation.
9666
9667 For most purposes, @code{gnatchop} will be used in default mode. The
9668 compilation mode described above is used only if you need exactly
9669 accurate behavior with respect to compilations, and you have files
9670 that contain multiple units and configuration pragmas. In this
9671 circumstance the use of @code{gnatchop} with the compilation mode
9672 switch provides the required behavior, and is for example the mode
9673 in which GNAT processes the ACVC tests.
9674
9675 @node Command Line for gnatchop
9676 @section Command Line for @code{gnatchop}
9677
9678 @noindent
9679 The @code{gnatchop} command has the form:
9680
9681 @smallexample
9682 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9683       [@var{directory}]
9684 @end smallexample
9685
9686 @noindent
9687 The only required argument is the file name of the file to be chopped.
9688 There are no restrictions on the form of this file name. The file itself
9689 contains one or more Ada units, in normal GNAT format, concatenated
9690 together. As shown, more than one file may be presented to be chopped.
9691
9692 When run in default mode, @code{gnatchop} generates one output file in
9693 the current directory for each unit in each of the files.
9694
9695 @var{directory}, if specified, gives the name of the directory to which
9696 the output files will be written. If it is not specified, all files are
9697 written to the current directory.
9698
9699 For example, given a
9700 file called @file{hellofiles} containing
9701
9702 @smallexample @c ada
9703 @group
9704 @cartouche
9705 procedure hello;
9706
9707 with Text_IO; use Text_IO;
9708 procedure hello is
9709 begin
9710    Put_Line ("Hello");
9711 end hello;
9712 @end cartouche
9713 @end group
9714 @end smallexample
9715
9716 @noindent
9717 the command
9718
9719 @smallexample
9720 $ gnatchop ^hellofiles^HELLOFILES.^
9721 @end smallexample
9722
9723 @noindent
9724 generates two files in the current directory, one called
9725 @file{hello.ads} containing the single line that is the procedure spec,
9726 and the other called @file{hello.adb} containing the remaining text. The
9727 original file is not affected. The generated files can be compiled in
9728 the normal manner.
9729
9730 @noindent
9731 When gnatchop is invoked on a file that is empty or that contains only empty
9732 lines and/or comments, gnatchop will not fail, but will not produce any
9733 new sources.
9734
9735 For example, given a
9736 file called @file{toto.txt} containing
9737
9738 @smallexample @c ada
9739 @group
9740 @cartouche
9741 --  Just a comment
9742 @end cartouche
9743 @end group
9744 @end smallexample
9745
9746 @noindent
9747 the command
9748
9749 @smallexample
9750 $ gnatchop ^toto.txt^TOT.TXT^
9751 @end smallexample
9752
9753 @noindent
9754 will not produce any new file and will result in the following warnings:
9755
9756 @smallexample
9757 toto.txt:1:01: warning: empty file, contains no compilation units
9758 no compilation units found
9759 no source files written
9760 @end smallexample
9761
9762 @node Switches for gnatchop
9763 @section Switches for @code{gnatchop}
9764
9765 @noindent
9766 @command{gnatchop} recognizes the following switches:
9767
9768 @table @option
9769 @c !sort!
9770
9771 @item ^-c^/COMPILATION^
9772 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9773 Causes @code{gnatchop} to operate in compilation mode, in which
9774 configuration pragmas are handled according to strict RM rules. See
9775 previous section for a full description of this mode.
9776
9777 @ifclear vms
9778 @item -gnatxxx
9779 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9780 used to parse the given file. Not all @code{xxx} options make sense,
9781 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9782 process a source file that uses Latin-2 coding for identifiers.
9783 @end ifclear
9784
9785 @item ^-h^/HELP^
9786 Causes @code{gnatchop} to generate a brief help summary to the standard
9787 output file showing usage information.
9788
9789 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9790 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9791 Limit generated file names to the specified number @code{mm}
9792 of characters.
9793 This is useful if the
9794 resulting set of files is required to be interoperable with systems
9795 which limit the length of file names.
9796 @ifset vms
9797 If no value is given, or
9798 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9799 a default of 39, suitable for OpenVMS Alpha
9800 Systems, is assumed
9801 @end ifset
9802 @ifclear vms
9803 No space is allowed between the @option{-k} and the numeric value. The numeric
9804 value may be omitted in which case a default of @option{-k8},
9805 suitable for use
9806 with DOS-like file systems, is used. If no @option{-k} switch
9807 is present then
9808 there is no limit on the length of file names.
9809 @end ifclear
9810
9811 @item ^-p^/PRESERVE^
9812 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9813 Causes the file ^modification^creation^ time stamp of the input file to be
9814 preserved and used for the time stamp of the output file(s). This may be
9815 useful for preserving coherency of time stamps in an environment where
9816 @code{gnatchop} is used as part of a standard build process.
9817
9818 @item ^-q^/QUIET^
9819 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9820 Causes output of informational messages indicating the set of generated
9821 files to be suppressed. Warnings and error messages are unaffected.
9822
9823 @item ^-r^/REFERENCE^
9824 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9825 @findex Source_Reference
9826 Generate @code{Source_Reference} pragmas. Use this switch if the output
9827 files are regarded as temporary and development is to be done in terms
9828 of the original unchopped file. This switch causes
9829 @code{Source_Reference} pragmas to be inserted into each of the
9830 generated files to refers back to the original file name and line number.
9831 The result is that all error messages refer back to the original
9832 unchopped file.
9833 In addition, the debugging information placed into the object file (when
9834 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9835 also refers back to this original file so that tools like profilers and
9836 debuggers will give information in terms of the original unchopped file.
9837
9838 If the original file to be chopped itself contains
9839 a @code{Source_Reference}
9840 pragma referencing a third file, then gnatchop respects
9841 this pragma, and the generated @code{Source_Reference} pragmas
9842 in the chopped file refer to the original file, with appropriate
9843 line numbers. This is particularly useful when @code{gnatchop}
9844 is used in conjunction with @code{gnatprep} to compile files that
9845 contain preprocessing statements and multiple units.
9846
9847 @item ^-v^/VERBOSE^
9848 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9849 Causes @code{gnatchop} to operate in verbose mode. The version
9850 number and copyright notice are output, as well as exact copies of
9851 the gnat1 commands spawned to obtain the chop control information.
9852
9853 @item ^-w^/OVERWRITE^
9854 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9855 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9856 fatal error if there is already a file with the same name as a
9857 file it would otherwise output, in other words if the files to be
9858 chopped contain duplicated units. This switch bypasses this
9859 check, and causes all but the last instance of such duplicated
9860 units to be skipped.
9861
9862 @ifclear vms
9863 @item --GCC=xxxx
9864 @cindex @option{--GCC=} (@code{gnatchop})
9865 Specify the path of the GNAT parser to be used. When this switch is used,
9866 no attempt is made to add the prefix to the GNAT parser executable.
9867 @end ifclear
9868 @end table
9869
9870 @node Examples of gnatchop Usage
9871 @section Examples of @code{gnatchop} Usage
9872
9873 @table @code
9874 @ifset vms
9875 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9876 @end ifset
9877 @ifclear vms
9878 @item gnatchop -w hello_s.ada prerelease/files
9879 @end ifclear
9880
9881 Chops the source file @file{hello_s.ada}. The output files will be
9882 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9883 overwriting any
9884 files with matching names in that directory (no files in the current
9885 directory are modified).
9886
9887 @item gnatchop ^archive^ARCHIVE.^
9888 Chops the source file @file{^archive^ARCHIVE.^}
9889 into the current directory. One
9890 useful application of @code{gnatchop} is in sending sets of sources
9891 around, for example in email messages. The required sources are simply
9892 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9893 command), and then
9894 @code{gnatchop} is used at the other end to reconstitute the original
9895 file names.
9896
9897 @item gnatchop file1 file2 file3 direc
9898 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9899 the resulting files in the directory @file{direc}. Note that if any units
9900 occur more than once anywhere within this set of files, an error message
9901 is generated, and no files are written. To override this check, use the
9902 @option{^-w^/OVERWRITE^} switch,
9903 in which case the last occurrence in the last file will
9904 be the one that is output, and earlier duplicate occurrences for a given
9905 unit will be skipped.
9906 @end table
9907
9908 @node Configuration Pragmas
9909 @chapter Configuration Pragmas
9910 @cindex Configuration pragmas
9911 @cindex Pragmas, configuration
9912
9913 @noindent
9914 In Ada 95, configuration pragmas include those pragmas described as
9915 such in the Ada 95 Reference Manual, as well as
9916 implementation-dependent pragmas that are configuration pragmas. See the
9917 individual descriptions of pragmas in the GNAT Reference Manual for
9918 details on these additional GNAT-specific configuration pragmas. Most
9919 notably, the pragma @code{Source_File_Name}, which allows
9920 specifying non-default names for source files, is a configuration
9921 pragma. The following is a complete list of configuration pragmas
9922 recognized by @code{GNAT}:
9923
9924 @smallexample
9925    Ada_83
9926    Ada_95
9927    C_Pass_By_Copy
9928    Component_Alignment
9929    Discard_Names
9930    Elaboration_Checks
9931    Eliminate
9932    Extend_System
9933    Extensions_Allowed
9934    External_Name_Casing
9935    Float_Representation
9936    Initialize_Scalars
9937    License
9938    Locking_Policy
9939    Long_Float
9940    Normalize_Scalars
9941    Polling
9942    Propagate_Exceptions
9943    Queuing_Policy
9944    Ravenscar
9945    Restricted_Run_Time
9946    Restrictions
9947    Reviewable
9948    Source_File_Name
9949    Style_Checks
9950    Suppress
9951    Task_Dispatching_Policy
9952    Universal_Data
9953    Unsuppress
9954    Use_VADS_Size
9955    Warnings
9956    Validity_Checks
9957 @end smallexample
9958
9959 @menu
9960 * Handling of Configuration Pragmas::
9961 * The Configuration Pragmas Files::
9962 @end menu
9963
9964 @node Handling of Configuration Pragmas
9965 @section Handling of Configuration Pragmas
9966
9967 Configuration pragmas may either appear at the start of a compilation
9968 unit, in which case they apply only to that unit, or they may apply to
9969 all compilations performed in a given compilation environment.
9970
9971 GNAT also provides the @code{gnatchop} utility to provide an automatic
9972 way to handle configuration pragmas following the semantics for
9973 compilations (that is, files with multiple units), described in the RM.
9974 See section @pxref{Operating gnatchop in Compilation Mode} for details.
9975 However, for most purposes, it will be more convenient to edit the
9976 @file{gnat.adc} file that contains configuration pragmas directly,
9977 as described in the following section.
9978
9979 @node The Configuration Pragmas Files
9980 @section The Configuration Pragmas Files
9981 @cindex @file{gnat.adc}
9982
9983 @noindent
9984 In GNAT a compilation environment is defined by the current
9985 directory at the time that a compile command is given. This current
9986 directory is searched for a file whose name is @file{gnat.adc}. If
9987 this file is present, it is expected to contain one or more
9988 configuration pragmas that will be applied to the current compilation.
9989 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
9990 considered.
9991
9992 Configuration pragmas may be entered into the @file{gnat.adc} file
9993 either by running @code{gnatchop} on a source file that consists only of
9994 configuration pragmas, or more conveniently  by
9995 direct editing of the @file{gnat.adc} file, which is a standard format
9996 source file.
9997
9998 In addition to @file{gnat.adc}, one additional file containing configuration
9999 pragmas may be applied to the current compilation using the switch
10000 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10001 contains only configuration pragmas. These configuration pragmas are
10002 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10003 is present and switch @option{-gnatA} is not used).
10004
10005 It is allowed to specify several switches @option{-gnatec}, however only
10006 the last one on the command line will be taken into account.
10007
10008 If you are using project file, a separate mechanism is provided using
10009 project attributes, see @ref{Specifying Configuration Pragmas} for more
10010 details.
10011
10012 @ifset vms
10013 Of special interest to GNAT OpenVMS Alpha is the following
10014 configuration pragma:
10015
10016 @smallexample @c ada
10017 @cartouche
10018 pragma Extend_System (Aux_DEC);
10019 @end cartouche
10020 @end smallexample
10021
10022 @noindent
10023 In the presence of this pragma, GNAT adds to the definition of the
10024 predefined package SYSTEM all the additional types and subprograms that are
10025 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10026 @end ifset
10027
10028 @node Handling Arbitrary File Naming Conventions Using gnatname
10029 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10030 @cindex Arbitrary File Naming Conventions
10031
10032 @menu
10033 * Arbitrary File Naming Conventions::
10034 * Running gnatname::
10035 * Switches for gnatname::
10036 * Examples of gnatname Usage::
10037 @end menu
10038
10039 @node Arbitrary File Naming Conventions
10040 @section Arbitrary File Naming Conventions
10041
10042 @noindent
10043 The GNAT compiler must be able to know the source file name of a compilation
10044 unit.  When using the standard GNAT default file naming conventions
10045 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10046 does not need additional information.
10047
10048 @noindent
10049 When the source file names do not follow the standard GNAT default file naming
10050 conventions, the GNAT compiler must be given additional information through
10051 a configuration pragmas file (see @ref{Configuration Pragmas})
10052 or a project file.
10053 When the non standard file naming conventions are well-defined,
10054 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10055 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10056 if the file naming conventions are irregular or arbitrary, a number
10057 of pragma @code{Source_File_Name} for individual compilation units
10058 must be defined.
10059 To help maintain the correspondence between compilation unit names and
10060 source file names within the compiler,
10061 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10062 set of files.
10063
10064 @node Running gnatname
10065 @section Running @code{gnatname}
10066
10067 @noindent
10068 The usual form of the @code{gnatname} command is
10069
10070 @smallexample
10071 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10072 @end smallexample
10073
10074 @noindent
10075 All of the arguments are optional. If invoked without any argument,
10076 @code{gnatname} will display its usage.
10077
10078 @noindent
10079 When used with at least one naming pattern, @code{gnatname} will attempt to
10080 find all the compilation units in files that follow at least one of the
10081 naming patterns. To find these compilation units,
10082 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10083 regular files.
10084
10085 @noindent
10086 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10087 Each Naming Pattern is enclosed between double quotes.
10088 A Naming Pattern is a regular expression similar to the wildcard patterns
10089 used in file names by the Unix shells or the DOS prompt.
10090
10091 @noindent
10092 Examples of Naming Patterns are
10093
10094 @smallexample
10095    "*.[12].ada"
10096    "*.ad[sb]*"
10097    "body_*"    "spec_*"
10098 @end smallexample
10099
10100 @noindent
10101 For a more complete description of the syntax of Naming Patterns,
10102 see the second kind of regular expressions described in @file{g-regexp.ads}
10103 (the ``Glob'' regular expressions).
10104
10105 @noindent
10106 When invoked with no switches, @code{gnatname} will create a configuration
10107 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10108 @code{Source_File_Name} for each file that contains a valid Ada unit.
10109
10110 @node Switches for gnatname
10111 @section Switches for @code{gnatname}
10112
10113 @noindent
10114 Switches for @code{gnatname} must precede any specified Naming Pattern.
10115
10116 @noindent
10117 You may specify any of the following switches to @code{gnatname}:
10118
10119 @table @option
10120 @c !sort!
10121
10122 @item ^-c^/CONFIG_FILE=^@file{file}
10123 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10124 Create a configuration pragmas file @file{file} (instead of the default
10125 @file{gnat.adc}).
10126 @ifclear vms
10127 There may be zero, one or more space between @option{-c} and
10128 @file{file}.
10129 @end ifclear
10130 @file{file} may include directory information. @file{file} must be
10131 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10132 When a switch @option{^-c^/CONFIG_FILE^} is
10133 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10134
10135 @item ^-d^/SOURCE_DIRS=^@file{dir}
10136 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10137 Look for source files in directory @file{dir}. There may be zero, one or more
10138 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10139 When a switch @option{^-d^/SOURCE_DIRS^}
10140 is specified, the current working directory will not be searched for source
10141 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10142 or @option{^-D^/DIR_FILES^} switch.
10143 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10144 If @file{dir} is a relative path, it is relative to the directory of
10145 the configuration pragmas file specified with switch
10146 @option{^-c^/CONFIG_FILE^},
10147 or to the directory of the project file specified with switch
10148 @option{^-P^/PROJECT_FILE^} or,
10149 if neither switch @option{^-c^/CONFIG_FILE^}
10150 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10151 current working directory. The directory
10152 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10153
10154 @item ^-D^/DIRS_FILE=^@file{file}
10155 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10156 Look for source files in all directories listed in text file @file{file}.
10157 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10158 and @file{file}.
10159 @file{file} must be an existing, readable text file.
10160 Each non empty line in @file{file} must be a directory.
10161 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10162 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10163 @file{file}.
10164
10165 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10166 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10167 Foreign patterns. Using this switch, it is possible to add sources of languages
10168 other than Ada to the list of sources of a project file.
10169 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10170 For example,
10171 @smallexample
10172 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10173 @end smallexample
10174 @noindent
10175 will look for Ada units in all files with the @file{.ada} extension,
10176 and will add to the list of file for project @file{prj.gpr} the C files
10177 with extension ".^c^C^".
10178
10179 @item ^-h^/HELP^
10180 @cindex @option{^-h^/HELP^} (@code{gnatname})
10181 Output usage (help) information. The output is written to @file{stdout}.
10182
10183 @item ^-P^/PROJECT_FILE=^@file{proj}
10184 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10185 Create or update project file @file{proj}. There may be zero, one or more space
10186 between @option{-P} and @file{proj}. @file{proj} may include directory
10187 information. @file{proj} must be writable.
10188 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10189 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10190 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10191
10192 @item ^-v^/VERBOSE^
10193 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10194 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10195 This includes name of the file written, the name of the directories to search
10196 and, for each file in those directories whose name matches at least one of
10197 the Naming Patterns, an indication of whether the file contains a unit,
10198 and if so the name of the unit.
10199
10200 @item ^-v -v^/VERBOSE /VERBOSE^
10201 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10202 Very Verbose mode. In addition to the output produced in verbose mode,
10203 for each file in the searched directories whose name matches none of
10204 the Naming Patterns, an indication is given that there is no match.
10205
10206 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10207 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10208 Excluded patterns. Using this switch, it is possible to exclude some files
10209 that would match the name patterns. For example,
10210 @smallexample
10211 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10212 @end smallexample
10213 @noindent
10214 will look for Ada units in all files with the @file{.ada} extension,
10215 except those whose names end with @file{_nt.ada}.
10216
10217 @end table
10218
10219 @node Examples of gnatname Usage
10220 @section Examples of @code{gnatname} Usage
10221
10222 @ifset vms
10223 @smallexample
10224 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10225 @end smallexample
10226 @end ifset
10227
10228 @ifclear vms
10229 @smallexample
10230 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10231 @end smallexample
10232 @end ifclear
10233
10234 @noindent
10235 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10236 and be writable. In addition, the directory
10237 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10238 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10239
10240 @ifclear vms
10241 Note the optional spaces after @option{-c} and @option{-d}.
10242 @end ifclear
10243
10244 @smallexample
10245 @ifclear vms
10246 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10247   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10248 @end ifclear
10249 @ifset vms
10250 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10251   /EXCLUDED_PATTERN=*_nt_body.ada
10252   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10253   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10254 @end ifset
10255 @end smallexample
10256
10257 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10258 even in conjunction with one or several switches
10259 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10260 are used in this example.
10261
10262
10263 @c *****************************************
10264 @c * G N A T  P r o j e c t  M a n a g e r *
10265 @c *****************************************
10266 @node GNAT Project Manager
10267 @chapter GNAT Project Manager
10268
10269 @menu
10270 * Introduction::
10271 * Examples of Project Files::
10272 * Project File Syntax::
10273 * Objects and Sources in Project Files::
10274 * Importing Projects::
10275 * Project Extension::
10276 * External References in Project Files::
10277 * Packages in Project Files::
10278 * Variables from Imported Projects::
10279 * Naming Schemes::
10280 * Library Projects::
10281 * Using Third-Party Libraries through Projects::
10282 * Stand-alone Library Projects::
10283 * Switches Related to Project Files::
10284 * Tools Supporting Project Files::
10285 * An Extended Example::
10286 * Project File Complete Syntax::
10287 @end menu
10288
10289 @c ****************
10290 @c * Introduction *
10291 @c ****************
10292
10293 @node Introduction
10294 @section Introduction
10295
10296 @noindent
10297 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10298 you to manage complex builds involving a number of source files, directories,
10299 and compilation options for different system configurations. In particular,
10300 project files allow you to specify:
10301 @itemize @bullet
10302 @item
10303 The directory or set of directories containing the source files, and/or the
10304 names of the specific source files themselves
10305 @item
10306 The directory in which the compiler's output
10307 (@file{ALI} files, object files, tree files) is to be placed
10308 @item
10309 The directory in which the executable programs is to be placed
10310 @item
10311 ^Switch^Switch^ settings for any of the project-enabled tools
10312 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10313 @code{gnatfind}); you can apply these settings either globally or to individual
10314 compilation units.
10315 @item
10316 The source files containing the main subprogram(s) to be built
10317 @item
10318 The source programming language(s) (currently Ada and/or C)
10319 @item
10320 Source file naming conventions; you can specify these either globally or for
10321 individual compilation units
10322 @end itemize
10323
10324 @menu
10325 * Project Files::
10326 @end menu
10327
10328 @node Project Files
10329 @subsection Project Files
10330
10331 @noindent
10332 Project files are written in a syntax close to that of Ada, using  familiar
10333 notions such as packages, context clauses, declarations, default values,
10334 assignments, and inheritance. Finally, project files can be built
10335 hierarchically from other project files, simplifying complex system
10336 integration and project reuse.
10337
10338 A @dfn{project} is a specific set of values for various compilation properties.
10339 The settings for a given project are described by means of
10340 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10341 Property values in project files are either strings or lists of strings.
10342 Properties that are not explicitly set receive default values.  A project
10343 file may interrogate the values of @dfn{external variables} (user-defined
10344 command-line switches or environment variables), and it may specify property
10345 settings conditionally, based on the value of such variables.
10346
10347 In simple cases, a project's source files depend only on other source files
10348 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10349 used in
10350 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10351 the Project Manager also allows more sophisticated arrangements,
10352 where the source files in one project depend on source files in other
10353 projects:
10354 @itemize @bullet
10355 @item
10356 One project can @emph{import} other projects containing needed source files.
10357 @item
10358 You can organize GNAT projects in a hierarchy: a @emph{child} project
10359 can extend a @emph{parent} project, inheriting the parent's source files and
10360 optionally overriding any of them with alternative versions
10361 @end itemize
10362
10363 @noindent
10364 More generally, the Project Manager lets you structure large development
10365 efforts into hierarchical subsystems, where build decisions are delegated
10366 to the subsystem level, and thus different compilation environments
10367 (^switch^switch^ settings) used for different subsystems.
10368
10369 The Project Manager is invoked through the
10370 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10371 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10372 @ifclear vms
10373 There may be zero, one or more spaces between @option{-P} and
10374 @option{@emph{projectfile}}.
10375 @end ifclear
10376 If you want to define (on the command line) an external variable that is
10377 queried by the project file, you must use the
10378 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10379 The Project Manager parses and interprets the project file, and drives the
10380 invoked tool based on the project settings.
10381
10382 The Project Manager supports a wide range of development strategies,
10383 for systems of all sizes.  Here are some typical practices that are
10384 easily handled:
10385 @itemize @bullet
10386 @item
10387 Using a common set of source files, but generating object files in different
10388 directories via different ^switch^switch^ settings
10389 @item
10390 Using a mostly-shared set of source files, but with different versions of
10391 some unit or units
10392 @end itemize
10393
10394 @noindent
10395 The destination of an executable can be controlled inside a project file
10396 using the @option{^-o^-o^}
10397 ^switch^switch^.
10398 In the absence of such a ^switch^switch^ either inside
10399 the project file or on the command line, any executable files generated by
10400 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10401 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10402 in the object directory of the project.
10403
10404 You can use project files to achieve some of the effects of a source
10405 versioning system (for example, defining separate projects for
10406 the different sets of sources that comprise different releases) but the
10407 Project Manager is independent of any source configuration management tools
10408 that might be used by the developers.
10409
10410 The next section introduces the main features of GNAT's project facility
10411 through a sequence of examples; subsequent sections will present the syntax
10412 and semantics in more detail. A more formal description of the project
10413 facility appears in the GNAT Reference Manual.
10414
10415 @c *****************************
10416 @c * Examples of Project Files *
10417 @c *****************************
10418
10419 @node Examples of Project Files
10420 @section Examples of Project Files
10421 @noindent
10422 This section illustrates some of the typical uses of project files and
10423 explains their basic structure and behavior.
10424
10425 @menu
10426 * Common Sources with Different ^Switches^Switches^ and Directories::
10427 * Using External Variables::
10428 * Importing Other Projects::
10429 * Extending a Project::
10430 @end menu
10431
10432 @node Common Sources with Different ^Switches^Switches^ and Directories
10433 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10434
10435 @menu
10436 * Source Files::
10437 * Specifying the Object Directory::
10438 * Specifying the Exec Directory::
10439 * Project File Packages::
10440 * Specifying ^Switch^Switch^ Settings::
10441 * Main Subprograms::
10442 * Executable File Names::
10443 * Source File Naming Conventions::
10444 * Source Language(s)::
10445 @end menu
10446
10447 @noindent
10448 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10449 @file{proc.adb} are in the @file{/common} directory.  The file
10450 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10451 package @code{Pack}.  We want to compile these source files under two sets
10452 of ^switches^switches^:
10453 @itemize @bullet
10454 @item
10455 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10456 and the @option{^-gnata^-gnata^},
10457 @option{^-gnato^-gnato^},
10458 and @option{^-gnatE^-gnatE^} switches to the
10459 compiler; the compiler's output is to appear in @file{/common/debug}
10460 @item
10461 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10462 to the compiler; the compiler's output is to appear in @file{/common/release}
10463 @end itemize
10464
10465 @noindent
10466 The GNAT project files shown below, respectively @file{debug.gpr} and
10467 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10468
10469 Schematically:
10470 @smallexample
10471 @group
10472 ^/common^[COMMON]^
10473   debug.gpr
10474   release.gpr
10475   pack.ads
10476   pack.adb
10477   proc.adb
10478 @end group
10479 @group
10480 ^/common/debug^[COMMON.DEBUG]^
10481   proc.ali, proc.o
10482   pack.ali, pack.o
10483 @end group
10484 @group
10485 ^/common/release^[COMMON.RELEASE]^
10486   proc.ali, proc.o
10487   pack.ali, pack.o
10488 @end group
10489 @end smallexample
10490 Here are the corresponding project files:
10491
10492 @smallexample @c projectfile
10493 @group
10494 project Debug is
10495   for Object_Dir use "debug";
10496   for Main use ("proc");
10497
10498   package Builder is
10499     for ^Default_Switches^Default_Switches^ ("Ada")
10500         use ("^-g^-g^");
10501     for Executable ("proc.adb") use "proc1";
10502   end Builder;
10503 @end group
10504
10505 @group
10506   package Compiler is
10507     for ^Default_Switches^Default_Switches^ ("Ada")
10508        use ("-fstack-check",
10509             "^-gnata^-gnata^",
10510             "^-gnato^-gnato^",
10511             "^-gnatE^-gnatE^");
10512   end Compiler;
10513 end Debug;
10514 @end group
10515 @end smallexample
10516
10517 @smallexample @c projectfile
10518 @group
10519 project Release is
10520   for Object_Dir use "release";
10521   for Exec_Dir use ".";
10522   for Main use ("proc");
10523
10524   package Compiler is
10525     for ^Default_Switches^Default_Switches^ ("Ada")
10526         use ("^-O2^-O2^");
10527   end Compiler;
10528 end Release;
10529 @end group
10530 @end smallexample
10531
10532 @noindent
10533 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10534 insensitive), and analogously the project defined by @file{release.gpr} is
10535 @code{"Release"}.  For consistency the file should have the same name as the
10536 project, and the project file's extension should be @code{"gpr"}. These
10537 conventions are not required, but a warning is issued if they are not followed.
10538
10539 If the current directory is @file{^/temp^[TEMP]^}, then the command
10540 @smallexample
10541 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10542 @end smallexample
10543
10544 @noindent
10545 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10546 as well as the @code{^proc1^PROC1.EXE^} executable,
10547 using the ^switch^switch^ settings defined in the project file.
10548
10549 Likewise, the command
10550 @smallexample
10551 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10552 @end smallexample
10553
10554 @noindent
10555 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10556 and the @code{^proc^PROC.EXE^}
10557 executable in @file{^/common^[COMMON]^},
10558 using the ^switch^switch^ settings from the project file.
10559
10560 @node Source Files
10561 @unnumberedsubsubsec Source Files
10562
10563 @noindent
10564 If a project file does not explicitly specify a set of source directories or
10565 a set of source files, then by default the project's source files are the
10566 Ada source files in the project file directory.  Thus @file{pack.ads},
10567 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10568
10569 @node Specifying the Object Directory
10570 @unnumberedsubsubsec Specifying the Object Directory
10571
10572 @noindent
10573 Several project properties are modeled by Ada-style @emph{attributes};
10574 a property is defined by supplying the equivalent of an Ada attribute
10575 definition clause in the project file.
10576 A project's object directory is another such a property; the corresponding
10577 attribute is @code{Object_Dir}, and its value is also a string expression,
10578 specified either as absolute or relative. In the later case,
10579 it is relative to the project file directory. Thus the compiler's
10580 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10581 (for the @code{Debug} project)
10582 and to @file{^/common/release^[COMMON.RELEASE]^}
10583 (for the @code{Release} project).
10584 If @code{Object_Dir} is not specified, then the default is the project file
10585 directory itself.
10586
10587 @node Specifying the Exec Directory
10588 @unnumberedsubsubsec Specifying the Exec Directory
10589
10590 @noindent
10591 A project's exec directory is another property; the corresponding
10592 attribute is @code{Exec_Dir}, and its value is also a string expression,
10593 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10594 then the default is the object directory (which may also be the project file
10595 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10596 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10597 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10598 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10599
10600 @node Project File Packages
10601 @unnumberedsubsubsec Project File Packages
10602
10603 @noindent
10604 A GNAT tool that is integrated with the Project Manager is modeled by a
10605 corresponding package in the project file. In the example above,
10606 The @code{Debug} project defines the packages @code{Builder}
10607 (for @command{gnatmake}) and @code{Compiler};
10608 the @code{Release} project defines only the @code{Compiler} package.
10609
10610 The Ada-like package syntax is not to be taken literally.  Although packages in
10611 project files bear a surface resemblance to packages in Ada source code, the
10612 notation is simply a way to convey a grouping of properties for a named
10613 entity.  Indeed, the package names permitted in project files are restricted
10614 to a predefined set, corresponding to the project-aware tools, and the contents
10615 of packages are limited to a small set of constructs.
10616 The packages in the example above contain attribute definitions.
10617
10618 @node Specifying ^Switch^Switch^ Settings
10619 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10620
10621 @noindent
10622 ^Switch^Switch^ settings for a project-aware tool can be specified through
10623 attributes in the package that corresponds to the tool.
10624 The example above illustrates one of the relevant attributes,
10625 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10626 in both project files.
10627 Unlike simple attributes like @code{Source_Dirs},
10628 @code{^Default_Switches^Default_Switches^} is
10629 known as an @emph{associative array}.  When you define this attribute, you must
10630 supply an ``index'' (a literal string), and the effect of the attribute
10631 definition is to set the value of the array at the specified index.
10632 For the @code{^Default_Switches^Default_Switches^} attribute,
10633 the index is a programming language (in our case, Ada),
10634 and the value specified (after @code{use}) must be a list
10635 of string expressions.
10636
10637 The attributes permitted in project files are restricted to a predefined set.
10638 Some may appear at project level, others in packages.
10639 For any attribute that is an associative array, the index must always be a
10640 literal string, but the restrictions on this string (e.g., a file name or a
10641 language name) depend on the individual attribute.
10642 Also depending on the attribute, its specified value will need to be either a
10643 string or a string list.
10644
10645 In the @code{Debug} project, we set the switches for two tools,
10646 @command{gnatmake} and the compiler, and thus we include the two corresponding
10647 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10648 attribute with index @code{"Ada"}.
10649 Note that the package corresponding to
10650 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10651 similar, but only includes the @code{Compiler} package.
10652
10653 In project @code{Debug} above, the ^switches^switches^ starting with
10654 @option{-gnat} that are specified in package @code{Compiler}
10655 could have been placed in package @code{Builder}, since @command{gnatmake}
10656 transmits all such ^switches^switches^ to the compiler.
10657
10658 @node Main Subprograms
10659 @unnumberedsubsubsec Main Subprograms
10660
10661 @noindent
10662 One of the specifiable properties of a project is a list of files that contain
10663 main subprograms.  This property is captured in the @code{Main} attribute,
10664 whose value is a list of strings.  If a project defines the @code{Main}
10665 attribute, it is not necessary to identify the main subprogram(s) when
10666 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10667
10668 @node Executable File Names
10669 @unnumberedsubsubsec Executable File Names
10670
10671 @noindent
10672 By default, the executable file name corresponding to a main source is
10673 deducted from the main source file name. Through the attributes
10674 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10675 it is possible to change this default.
10676 In project @code{Debug} above, the executable file name
10677 for main source @file{^proc.adb^PROC.ADB^} is
10678 @file{^proc1^PROC1.EXE^}.
10679 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10680 of the the executable files, when no attribute @code{Executable} applies:
10681 its value replace the platform-specific executable suffix.
10682 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10683 specify a non default executable file name when several mains are built at once
10684 in a single @command{gnatmake} command.
10685
10686 @node Source File Naming Conventions
10687 @unnumberedsubsubsec Source File Naming Conventions
10688
10689 @noindent
10690 Since the project files above do not specify any source file naming
10691 conventions, the GNAT defaults are used.  The mechanism for defining source
10692 file naming conventions -- a package named @code{Naming} --
10693 is described below (@pxref{Naming Schemes}).
10694
10695 @node Source Language(s)
10696 @unnumberedsubsubsec Source Language(s)
10697
10698 @noindent
10699 Since the project files do not specify a @code{Languages} attribute, by
10700 default the GNAT tools assume that the language of the project file is Ada.
10701 More generally, a project can comprise source files
10702 in Ada, C, and/or other languages.
10703
10704 @node Using External Variables
10705 @subsection Using External Variables
10706
10707 @noindent
10708 Instead of supplying different project files for debug and release, we can
10709 define a single project file that queries an external variable (set either
10710 on the command line or via an ^environment variable^logical name^) in order to
10711 conditionally define the appropriate settings.  Again, assume that the
10712 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10713 located in directory @file{^/common^[COMMON]^}.  The following project file,
10714 @file{build.gpr}, queries the external variable named @code{STYLE} and
10715 defines an object directory and ^switch^switch^ settings based on whether
10716 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10717 the default is @code{"deb"}.
10718
10719 @smallexample @c projectfile
10720 @group
10721 project Build is
10722   for Main use ("proc");
10723
10724   type Style_Type is ("deb", "rel");
10725   Style : Style_Type := external ("STYLE", "deb");
10726
10727   case Style is
10728     when "deb" =>
10729       for Object_Dir use "debug";
10730
10731     when "rel" =>
10732       for Object_Dir use "release";
10733       for Exec_Dir use ".";
10734   end case;
10735 @end group
10736
10737 @group
10738   package Builder is
10739
10740     case Style is
10741       when "deb" =>
10742         for ^Default_Switches^Default_Switches^ ("Ada")
10743             use ("^-g^-g^");
10744         for Executable ("proc") use "proc1";
10745     end case;
10746
10747   end Builder;
10748 @end group
10749
10750 @group
10751   package Compiler is
10752
10753     case Style is
10754       when "deb" =>
10755         for ^Default_Switches^Default_Switches^ ("Ada")
10756             use ("^-gnata^-gnata^",
10757                  "^-gnato^-gnato^",
10758                  "^-gnatE^-gnatE^");
10759
10760       when "rel" =>
10761         for ^Default_Switches^Default_Switches^ ("Ada")
10762             use ("^-O2^-O2^");
10763     end case;
10764
10765   end Compiler;
10766
10767 end Build;
10768 @end group
10769 @end smallexample
10770
10771 @noindent
10772 @code{Style_Type} is an example of a @emph{string type}, which is the project
10773 file analog of an Ada enumeration type but whose components are string literals
10774 rather than identifiers.  @code{Style} is declared as a variable of this type.
10775
10776 The form @code{external("STYLE", "deb")} is known as an
10777 @emph{external reference}; its first argument is the name of an
10778 @emph{external variable}, and the second argument is a default value to be
10779 used if the external variable doesn't exist.  You can define an external
10780 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10781 or you can use ^an environment variable^a logical name^
10782 as an external variable.
10783
10784 Each @code{case} construct is expanded by the Project Manager based on the
10785 value of @code{Style}. Thus the command
10786 @ifclear vms
10787 @smallexample
10788 gnatmake -P/common/build.gpr -XSTYLE=deb
10789 @end smallexample
10790 @end ifclear
10791
10792 @ifset vms
10793 @smallexample
10794 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10795 @end smallexample
10796 @end ifset
10797
10798 @noindent
10799 is equivalent to the @command{gnatmake} invocation using the project file
10800 @file{debug.gpr} in the earlier example.  So is the command
10801 @smallexample
10802 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10803 @end smallexample
10804
10805 @noindent
10806 since @code{"deb"} is the default for @code{STYLE}.
10807
10808 Analogously,
10809
10810 @ifclear vms
10811 @smallexample
10812 gnatmake -P/common/build.gpr -XSTYLE=rel
10813 @end smallexample
10814 @end ifclear
10815
10816 @ifset vms
10817 @smallexample
10818 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10819 @end smallexample
10820 @end ifset
10821
10822 @noindent
10823 is equivalent to the @command{gnatmake} invocation using the project file
10824 @file{release.gpr} in the earlier example.
10825
10826 @node Importing Other Projects
10827 @subsection Importing Other Projects
10828
10829 @noindent
10830 A compilation unit in a source file in one project may depend on compilation
10831 units in source files in other projects.  To compile this unit under
10832 control of a project file, the
10833 dependent project must @emph{import} the projects containing the needed source
10834 files.
10835 This effect is obtained using syntax similar to an Ada @code{with} clause,
10836 but where @code{with}ed entities are strings that denote project files.
10837
10838 As an example, suppose that the two projects @code{GUI_Proj} and
10839 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10840 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10841 and @file{^/comm^[COMM]^}, respectively.
10842 Suppose that the source files for @code{GUI_Proj} are
10843 @file{gui.ads} and @file{gui.adb}, and that the source files for
10844 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10845 files is located in its respective project file directory.  Schematically:
10846
10847 @smallexample
10848 @group
10849 ^/gui^[GUI]^
10850   gui_proj.gpr
10851   gui.ads
10852   gui.adb
10853 @end group
10854
10855 @group
10856 ^/comm^[COMM]^
10857   comm_proj.gpr
10858   comm.ads
10859   comm.adb
10860 @end group
10861 @end smallexample
10862
10863 @noindent
10864 We want to develop an application in directory @file{^/app^[APP]^} that
10865 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10866 the corresponding project files (e.g. the ^switch^switch^ settings
10867 and object directory).
10868 Skeletal code for a main procedure might be something like the following:
10869
10870 @smallexample @c ada
10871 @group
10872 with GUI, Comm;
10873 procedure App_Main is
10874    ...
10875 begin
10876    ...
10877 end App_Main;
10878 @end group
10879 @end smallexample
10880
10881 @noindent
10882 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10883 effect:
10884
10885 @smallexample @c projectfile
10886 @group
10887 with "/gui/gui_proj", "/comm/comm_proj";
10888 project App_Proj is
10889    for Main use ("app_main");
10890 end App_Proj;
10891 @end group
10892 @end smallexample
10893
10894 @noindent
10895 Building an executable is achieved through the command:
10896 @smallexample
10897 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10898 @end smallexample
10899 @noindent
10900 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10901 in the directory where @file{app_proj.gpr} resides.
10902
10903 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10904 (as illustrated above) the @code{with} clause can omit the extension.
10905
10906 Our example specified an absolute path for each imported project file.
10907 Alternatively, the directory name of an imported object can be omitted
10908 if either
10909 @itemize @bullet
10910 @item
10911 The imported project file is in the same directory as the importing project
10912 file, or
10913 @item
10914 You have defined ^an environment variable^a logical name^
10915 that includes the directory containing
10916 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10917 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10918 directory names separated by colons (semicolons on Windows).
10919 @end itemize
10920
10921 @noindent
10922 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10923 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10924 as follows:
10925
10926 @smallexample @c projectfile
10927 @group
10928 with "gui_proj", "comm_proj";
10929 project App_Proj is
10930    for Main use ("app_main");
10931 end App_Proj;
10932 @end group
10933 @end smallexample
10934
10935 @noindent
10936 Importing other projects can create ambiguities.
10937 For example, the same unit might be present in different imported projects, or
10938 it might be present in both the importing project and in an imported project.
10939 Both of these conditions are errors.  Note that in the current version of
10940 the Project Manager, it is illegal to have an ambiguous unit even if the
10941 unit is never referenced by the importing project.  This restriction may be
10942 relaxed in a future release.
10943
10944 @node Extending a Project
10945 @subsection Extending a Project
10946
10947 @noindent
10948 In large software systems it is common to have multiple
10949 implementations of a common interface; in Ada terms, multiple versions of a
10950 package body for the same specification.  For example, one implementation
10951 might be safe for use in tasking programs, while another might only be used
10952 in sequential applications.  This can be modeled in GNAT using the concept
10953 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
10954 another project (the ``parent'') then by default all source files of the
10955 parent project are inherited by the child, but the child project can
10956 override any of the parent's source files with new versions, and can also
10957 add new files.  This facility is the project analog of a type extension in
10958 Object-Oriented Programming.  Project hierarchies are permitted (a child
10959 project may be the parent of yet another project), and a project that
10960 inherits one project can also import other projects.
10961
10962 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
10963 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
10964 @file{pack.adb}, and @file{proc.adb}:
10965
10966 @smallexample
10967 @group
10968 ^/seq^[SEQ]^
10969   pack.ads
10970   pack.adb
10971   proc.adb
10972   seq_proj.gpr
10973 @end group
10974 @end smallexample
10975
10976 @noindent
10977 Note that the project file can simply be empty (that is, no attribute or
10978 package is defined):
10979
10980 @smallexample @c projectfile
10981 @group
10982 project Seq_Proj is
10983 end Seq_Proj;
10984 @end group
10985 @end smallexample
10986
10987 @noindent
10988 implying that its source files are all the Ada source files in the project
10989 directory.
10990
10991 Suppose we want to supply an alternate version of @file{pack.adb}, in
10992 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
10993 @file{pack.ads} and @file{proc.adb}.  We can define a project
10994 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
10995
10996 @smallexample
10997 @group
10998 ^/tasking^[TASKING]^
10999   pack.adb
11000   tasking_proj.gpr
11001 @end group
11002
11003 @group
11004 project Tasking_Proj extends "/seq/seq_proj" is
11005 end Tasking_Proj;
11006 @end group
11007 @end smallexample
11008
11009 @noindent
11010 The version of @file{pack.adb} used in a build depends on which project file
11011 is specified.
11012
11013 Note that we could have obtained the desired behavior using project import
11014 rather than project inheritance; a @code{base} project would contain the
11015 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11016 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11017 would import @code{base} and add a different version of @file{pack.adb}.  The
11018 choice depends on whether other sources in the original project need to be
11019 overridden.  If they do, then project extension is necessary, otherwise,
11020 importing is sufficient.
11021
11022 @noindent
11023 In a project file that extends another project file, it is possible to
11024 indicate that an inherited source is not part of the sources of the extending
11025 project. This is necessary sometimes when a package spec has been overloaded
11026 and no longer requires a body: in this case, it is necessary to indicate that
11027 the inherited body is not part of the sources of the project, otherwise there
11028 will be a compilation error when compiling the spec.
11029
11030 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11031 Its value is a string list: a list of file names.
11032
11033 @smallexample @c @projectfile
11034 project B extends "a" is
11035    for Source_Files use ("pkg.ads");
11036    --  New spec of Pkg does not need a completion
11037    for Locally_Removed_Files use ("pkg.adb");
11038 end B;
11039 @end smallexample
11040
11041 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11042 is still needed: if it is possible to build using @code{gnatmake} when such
11043 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11044 it is possible to remove the source completely from a system that includes
11045 project P.
11046
11047 @c ***********************
11048 @c * Project File Syntax *
11049 @c ***********************
11050
11051 @node Project File Syntax
11052 @section Project File Syntax
11053
11054 @menu
11055 * Basic Syntax::
11056 * Packages::
11057 * Expressions::
11058 * String Types::
11059 * Variables::
11060 * Attributes::
11061 * Associative Array Attributes::
11062 * case Constructions::
11063 @end menu
11064
11065 @noindent
11066 This section describes the structure of project files.
11067
11068 A project may be an @emph{independent project}, entirely defined by a single
11069 project file. Any Ada source file in an independent project depends only
11070 on the predefined library and other Ada source files in the same project.
11071
11072 @noindent
11073 A project may also @dfn{depend on} other projects, in either or both of
11074 the following ways:
11075 @itemize @bullet
11076 @item It may import any number of projects
11077 @item It may extend at most one other project
11078 @end itemize
11079
11080 @noindent
11081 The dependence relation is a directed acyclic graph (the subgraph reflecting
11082 the ``extends'' relation is a tree).
11083
11084 A project's @dfn{immediate sources} are the source files directly defined by
11085 that project, either implicitly by residing in the project file's directory,
11086 or explicitly through any of the source-related attributes described below.
11087 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11088 of @var{proj} together with the immediate sources (unless overridden) of any
11089 project on which @var{proj} depends (either directly or indirectly).
11090
11091 @node Basic Syntax
11092 @subsection Basic Syntax
11093
11094 @noindent
11095 As seen in the earlier examples, project files have an Ada-like syntax.
11096 The minimal project file is:
11097 @smallexample @c projectfile
11098 @group
11099 project Empty is
11100
11101 end Empty;
11102 @end group
11103 @end smallexample
11104
11105 @noindent
11106 The identifier @code{Empty} is the name of the project.
11107 This project name must be present after the reserved
11108 word @code{end} at the end of the project file, followed by a semi-colon.
11109
11110 Any name in a project file, such as the project name or a variable name,
11111 has the same syntax as an Ada identifier.
11112
11113 The reserved words of project files are the Ada reserved words plus
11114 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11115 reserved words currently used in project file syntax are:
11116
11117 @itemize @bullet
11118 @item
11119 @code{case}
11120 @item
11121 @code{end}
11122 @item
11123 @code{for}
11124 @item
11125 @code{is}
11126 @item
11127 @code{others}
11128 @item
11129 @code{package}
11130 @item
11131 @code{renames}
11132 @item
11133 @code{type}
11134 @item
11135 @code{use}
11136 @item
11137 @code{when}
11138 @item
11139 @code{with}
11140 @end itemize
11141
11142 @noindent
11143 Comments in project files have the same syntax as in Ada, two consecutives
11144 hyphens through the end of the line.
11145
11146 @node Packages
11147 @subsection Packages
11148
11149 @noindent
11150 A project file may contain @emph{packages}. The name of a package must be one
11151 of the identifiers from the following list. A package
11152 with a given name may only appear once in a project file. Package names are
11153 case insensitive. The following package names are legal:
11154
11155 @itemize @bullet
11156 @item
11157 @code{Naming}
11158 @item
11159 @code{Builder}
11160 @item
11161 @code{Compiler}
11162 @item
11163 @code{Binder}
11164 @item
11165 @code{Linker}
11166 @item
11167 @code{Finder}
11168 @item
11169 @code{Cross_Reference}
11170 @item
11171 @code{Eliminate}
11172 @item
11173 @code{gnatls}
11174 @item
11175 @code{gnatstub}
11176 @item
11177 @code{IDE}
11178 @end itemize
11179
11180 @noindent
11181 In its simplest form, a package may be empty:
11182
11183 @smallexample @c projectfile
11184 @group
11185 project Simple is
11186   package Builder is
11187   end Builder;
11188 end Simple;
11189 @end group
11190 @end smallexample
11191
11192 @noindent
11193 A package may contain @emph{attribute declarations},
11194 @emph{variable declarations} and @emph{case constructions}, as will be
11195 described below.
11196
11197 When there is ambiguity between a project name and a package name,
11198 the name always designates the project. To avoid possible confusion, it is
11199 always a good idea to avoid naming a project with one of the
11200 names allowed for packages or any name that starts with @code{gnat}.
11201
11202 @node Expressions
11203 @subsection Expressions
11204
11205 @noindent
11206 An @emph{expression} is either a @emph{string expression} or a
11207 @emph{string list expression}.
11208
11209 A @emph{string expression} is either a @emph{simple string expression} or a
11210 @emph{compound string expression}.
11211
11212 A @emph{simple string expression} is one of the following:
11213 @itemize @bullet
11214 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11215 @item A string-valued variable reference (see @ref{Variables})
11216 @item A string-valued attribute reference (see @ref{Attributes})
11217 @item An external reference (see @ref{External References in Project Files})
11218 @end itemize
11219
11220 @noindent
11221 A @emph{compound string expression} is a concatenation of string expressions,
11222 using the operator @code{"&"}
11223 @smallexample
11224        Path & "/" & File_Name & ".ads"
11225 @end smallexample
11226
11227 @noindent
11228 A @emph{string list expression} is either a
11229 @emph{simple string list expression} or a
11230 @emph{compound string list expression}.
11231
11232 A @emph{simple string list expression} is one of the following:
11233 @itemize @bullet
11234 @item A parenthesized list of zero or more string expressions,
11235 separated by commas
11236 @smallexample
11237    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11238    Empty_List := ();
11239 @end smallexample
11240 @item A string list-valued variable reference
11241 @item A string list-valued attribute reference
11242 @end itemize
11243
11244 @noindent
11245 A @emph{compound string list expression} is the concatenation (using
11246 @code{"&"}) of a simple string list expression and an expression.  Note that
11247 each term in a compound string list expression, except the first, may be
11248 either a string expression or a string list expression.
11249
11250 @smallexample @c projectfile
11251 @group
11252    File_Name_List := () & File_Name; --  One string in this list
11253    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11254    --  Two strings
11255    Big_List := File_Name_List & Extended_File_Name_List;
11256    --  Concatenation of two string lists: three strings
11257    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11258    --  Illegal: must start with a string list
11259 @end group
11260 @end smallexample
11261
11262 @node String Types
11263 @subsection String Types
11264
11265 @noindent
11266 A @emph{string type declaration} introduces a discrete set of string literals.
11267 If a string variable is declared to have this type, its value
11268 is restricted to the given set of literals.
11269
11270 Here is an example of a string type declaration:
11271
11272 @smallexample @c projectfile
11273    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11274 @end smallexample
11275
11276 @noindent
11277 Variables of a string type are called @emph{typed variables}; all other
11278 variables are called @emph{untyped variables}. Typed variables are
11279 particularly useful in @code{case} constructions, to support conditional
11280 attribute declarations.
11281 (see @ref{case Constructions}).
11282
11283 The string literals in the list are case sensitive and must all be different.
11284 They may include any graphic characters allowed in Ada, including spaces.
11285
11286 A string type may only be declared at the project level, not inside a package.
11287
11288 A string type may be referenced by its name if it has been declared in the same
11289 project file, or by an expanded name whose prefix is the name of the project
11290 in which it is declared.
11291
11292 @node Variables
11293 @subsection Variables
11294
11295 @noindent
11296 A variable may be declared at the project file level, or within a package.
11297 Here are some examples of variable declarations:
11298
11299 @smallexample @c projectfile
11300 @group
11301    This_OS : OS := external ("OS"); --  a typed variable declaration
11302    That_OS := "GNU/Linux";          --  an untyped variable declaration
11303 @end group
11304 @end smallexample
11305
11306 @noindent
11307 The syntax of a @emph{typed variable declaration} is identical to the Ada
11308 syntax for an object declaration. By contrast, the syntax of an untyped
11309 variable declaration is identical to an Ada assignment statement. In fact,
11310 variable declarations in project files have some of the characteristics of
11311 an assignment, in that successive declarations for the same variable are
11312 allowed. Untyped variable declarations do establish the expected kind of the
11313 variable (string or string list), and successive declarations for it must
11314 respect the initial kind.
11315
11316 @noindent
11317 A string variable declaration (typed or untyped) declares a variable
11318 whose value is a string. This variable may be used as a string expression.
11319 @smallexample @c projectfile
11320    File_Name       := "readme.txt";
11321    Saved_File_Name := File_Name & ".saved";
11322 @end smallexample
11323
11324 @noindent
11325 A string list variable declaration declares a variable whose value is a list
11326 of strings. The list may contain any number (zero or more) of strings.
11327
11328 @smallexample @c projectfile
11329    Empty_List := ();
11330    List_With_One_Element := ("^-gnaty^-gnaty^");
11331    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11332    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11333                  "pack2.ada", "util_.ada", "util.ada");
11334 @end smallexample
11335
11336 @noindent
11337 The same typed variable may not be declared more than once at project level,
11338 and it may not be declared more than once in any package; it is in effect
11339 a constant.
11340
11341 The same untyped variable may be declared several times. Declarations are
11342 elaborated in the order in which they appear, so  the new value replaces
11343 the old one, and any subsequent reference to the variable uses the new value.
11344 However, as noted above, if a variable has been declared as a string, all
11345 subsequent
11346 declarations must give it a string value. Similarly, if a variable has
11347 been declared as a string list, all subsequent declarations
11348 must give it a string list value.
11349
11350 A @emph{variable reference} may take several forms:
11351
11352 @itemize @bullet
11353 @item The simple variable name, for a variable in the current package (if any)
11354 or in the current project
11355 @item An expanded name, whose prefix is a context name.
11356 @end itemize
11357
11358 @noindent
11359 A @emph{context} may be one of the following:
11360
11361 @itemize @bullet
11362 @item The name of an existing package in the current project
11363 @item The name of an imported project of the current project
11364 @item The name of an ancestor project (i.e., a project extended by the current
11365 project, either directly or indirectly)
11366 @item An expanded name whose prefix is an imported/parent project name, and
11367 whose selector is a package name in that project.
11368 @end itemize
11369
11370 @noindent
11371 A variable reference may be used in an expression.
11372
11373 @node Attributes
11374 @subsection Attributes
11375
11376 @noindent
11377 A project (and its packages) may have @emph{attributes} that define
11378 the project's properties.  Some attributes have values that are strings;
11379 others have values that are string lists.
11380
11381 There are two categories of attributes: @emph{simple attributes}
11382 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11383
11384 Legal project attribute names, and attribute names for each legal package are
11385 listed below. Attributes names are case-insensitive.
11386
11387 The following attributes are defined on projects (all are simple attributes):
11388
11389 @multitable @columnfractions .4 .3
11390 @item @emph{Attribute Name}
11391 @tab @emph{Value}
11392 @item @code{Source_Files}
11393 @tab string list
11394 @item @code{Source_Dirs}
11395 @tab string list
11396 @item @code{Source_List_File}
11397 @tab string
11398 @item @code{Object_Dir}
11399 @tab string
11400 @item @code{Exec_Dir}
11401 @tab string
11402 @item @code{Locally_Removed_Files}
11403 @tab string list
11404 @item @code{Main}
11405 @tab string list
11406 @item @code{Languages}
11407 @tab string list
11408 @item @code{Main_Language}
11409 @tab string
11410 @item @code{Library_Dir}
11411 @tab string
11412 @item @code{Library_Name}
11413 @tab string
11414 @item @code{Library_Kind}
11415 @tab string
11416 @item @code{Library_Version}
11417 @tab string
11418 @item @code{Library_Interface}
11419 @tab string
11420 @item @code{Library_Auto_Init}
11421 @tab string
11422 @item @code{Library_Options}
11423 @tab string list
11424 @item @code{Library_GCC}
11425 @tab string
11426 @end multitable
11427
11428 @noindent
11429 The following attributes are defined for package  @code{Naming}
11430 (see @ref{Naming Schemes}):
11431
11432 @multitable @columnfractions .4 .2 .2 .2
11433 @item Attribute Name @tab Category @tab Index @tab Value
11434 @item @code{Spec_Suffix}
11435 @tab associative array
11436 @tab language name
11437 @tab string
11438 @item @code{Body_Suffix}
11439 @tab associative array
11440 @tab language name
11441 @tab string
11442 @item @code{Separate_Suffix}
11443 @tab simple attribute
11444 @tab n/a
11445 @tab string
11446 @item @code{Casing}
11447 @tab simple attribute
11448 @tab n/a
11449 @tab string
11450 @item @code{Dot_Replacement}
11451 @tab simple attribute
11452 @tab n/a
11453 @tab string
11454 @item @code{Spec}
11455 @tab associative array
11456 @tab Ada unit name
11457 @tab string
11458 @item @code{Body}
11459 @tab associative array
11460 @tab Ada unit name
11461 @tab string
11462 @item @code{Specification_Exceptions}
11463 @tab associative array
11464 @tab language name
11465 @tab string list
11466 @item @code{Implementation_Exceptions}
11467 @tab associative array
11468 @tab language name
11469 @tab string list
11470 @end multitable
11471
11472 @noindent
11473 The following attributes are defined for packages @code{Builder},
11474 @code{Compiler}, @code{Binder},
11475 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11476 (see @ref{^Switches^Switches^ and Project Files}).
11477
11478 @multitable @columnfractions .4 .2 .2 .2
11479 @item Attribute Name @tab Category @tab Index @tab Value
11480 @item @code{^Default_Switches^Default_Switches^}
11481 @tab associative array
11482 @tab language name
11483 @tab string list
11484 @item @code{^Switches^Switches^}
11485 @tab associative array
11486 @tab file name
11487 @tab string list
11488 @end multitable
11489
11490 @noindent
11491 In addition, package @code{Compiler} has a single string attribute
11492 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11493 string attribute @code{Global_Configuration_Pragmas}.
11494
11495 @noindent
11496 Each simple attribute has a default value: the empty string (for string-valued
11497 attributes) and the empty list (for string list-valued attributes).
11498
11499 An attribute declaration defines a new value for an attribute.
11500
11501 Examples of simple attribute declarations:
11502
11503 @smallexample @c projectfile
11504    for Object_Dir use "objects";
11505    for Source_Dirs use ("units", "test/drivers");
11506 @end smallexample
11507
11508 @noindent
11509 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11510 attribute definition clause in Ada.
11511
11512 Attributes references may be appear in expressions.
11513 The general form for such a reference is @code{<entity>'<attribute>}:
11514 Associative array attributes are functions. Associative
11515 array attribute references must have an argument that is a string literal.
11516
11517 Examples are:
11518
11519 @smallexample @c projectfile
11520   project'Object_Dir
11521   Naming'Dot_Replacement
11522   Imported_Project'Source_Dirs
11523   Imported_Project.Naming'Casing
11524   Builder'^Default_Switches^Default_Switches^("Ada")
11525 @end smallexample
11526
11527 @noindent
11528 The prefix of an attribute may be:
11529 @itemize @bullet
11530 @item @code{project} for an attribute of the current project
11531 @item The name of an existing package of the current project
11532 @item The name of an imported project
11533 @item The name of a parent project that is extended by the current project
11534 @item An expanded name whose prefix is imported/parent project name,
11535       and whose selector is a package name
11536 @end itemize
11537
11538 @noindent
11539 Example:
11540 @smallexample @c projectfile
11541 @group
11542    project Prj is
11543      for Source_Dirs use project'Source_Dirs & "units";
11544      for Source_Dirs use project'Source_Dirs & "test/drivers"
11545    end Prj;
11546 @end group
11547 @end smallexample
11548
11549 @noindent
11550 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11551 has the default value: an empty string list. After this declaration,
11552 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11553 After the second attribute declaration @code{Source_Dirs} is a string list of
11554 two elements: @code{"units"} and @code{"test/drivers"}.
11555
11556 Note: this example is for illustration only. In practice,
11557 the project file would contain only one attribute declaration:
11558
11559 @smallexample @c projectfile
11560    for Source_Dirs use ("units", "test/drivers");
11561 @end smallexample
11562
11563 @node Associative Array Attributes
11564 @subsection Associative Array Attributes
11565
11566 @noindent
11567 Some attributes are defined as @emph{associative arrays}. An associative
11568 array may be regarded as a function that takes a string as a parameter
11569 and delivers a string or string list value as its result.
11570
11571 Here are some examples of single associative array attribute associations:
11572
11573 @smallexample @c projectfile
11574    for Body ("main") use "Main.ada";
11575    for ^Switches^Switches^ ("main.ada")
11576        use ("^-v^-v^",
11577             "^-gnatv^-gnatv^");
11578    for ^Switches^Switches^ ("main.ada")
11579             use Builder'^Switches^Switches^ ("main.ada")
11580               & "^-g^-g^";
11581 @end smallexample
11582
11583 @noindent
11584 Like untyped variables and simple attributes, associative array attributes
11585 may be declared several times. Each declaration supplies a new value for the
11586 attribute, and replaces the previous setting.
11587
11588 @noindent
11589 An associative array attribute may be declared as a full associative array
11590 declaration, with the value of the same attribute in an imported or extended
11591 project.
11592
11593 @smallexample @c projectfile
11594    package Builder is
11595       for Default_Switches use Default.Builder'Default_Switches;
11596    end Builder;
11597 @end smallexample
11598
11599 @noindent
11600 In this example, @code{Default} must be either an project imported by the
11601 current project, or the project that the current project extends. If the
11602 attribute is in a package (in this case, in package @code{Builder}), the same
11603 package needs to be specified.
11604
11605 @noindent
11606 A full associative array declaration replaces any other declaration for the
11607 attribute, including other full associative array declaration. Single
11608 associative array associations may be declare after a full associative
11609 declaration, modifying the value for a single association of the attribute.
11610
11611 @node case Constructions
11612 @subsection @code{case} Constructions
11613
11614 @noindent
11615 A @code{case} construction is used in a project file to effect conditional
11616 behavior.
11617 Here is a typical example:
11618
11619 @smallexample @c projectfile
11620 @group
11621 project MyProj is
11622    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11623
11624    OS : OS_Type := external ("OS", "GNU/Linux");
11625 @end group
11626
11627 @group
11628    package Compiler is
11629      case OS is
11630        when "GNU/Linux" | "Unix" =>
11631          for ^Default_Switches^Default_Switches^ ("Ada")
11632              use ("^-gnath^-gnath^");
11633        when "NT" =>
11634          for ^Default_Switches^Default_Switches^ ("Ada")
11635              use ("^-gnatP^-gnatP^");
11636        when others =>
11637      end case;
11638    end Compiler;
11639 end MyProj;
11640 @end group
11641 @end smallexample
11642
11643 @noindent
11644 The syntax of a @code{case} construction is based on the Ada case statement
11645 (although there is no @code{null} construction for empty alternatives).
11646
11647 The case expression must a typed string variable.
11648 Each alternative comprises the reserved word @code{when}, either a list of
11649 literal strings separated by the @code{"|"} character or the reserved word
11650 @code{others},  and the @code{"=>"} token.
11651 Each literal string must belong to the string type that is the type of the
11652 case variable.
11653 An @code{others} alternative, if present, must occur last.
11654
11655 After each @code{=>}, there are zero or more constructions.  The only
11656 constructions allowed in a case construction are other case constructions and
11657 attribute declarations. String type declarations, variable declarations and
11658 package declarations are not allowed.
11659
11660 The value of the case variable is often given by an external reference
11661 (see @ref{External References in Project Files}).
11662
11663 @c ****************************************
11664 @c * Objects and Sources in Project Files *
11665 @c ****************************************
11666
11667 @node Objects and Sources in Project Files
11668 @section Objects and Sources in Project Files
11669
11670 @menu
11671 * Object Directory::
11672 * Exec Directory::
11673 * Source Directories::
11674 * Source File Names::
11675 @end menu
11676
11677 @noindent
11678 Each project has exactly one object directory and one or more source
11679 directories. The source directories must contain at least one source file,
11680 unless  the project file explicitly specifies that no source files are present
11681 (see @ref{Source File Names}).
11682
11683 @node Object Directory
11684 @subsection Object Directory
11685
11686 @noindent
11687 The object directory for a project is the directory containing the compiler's
11688 output (such as @file{ALI} files and object files) for the project's immediate
11689 sources.
11690
11691 The object directory is given by the value of the attribute @code{Object_Dir}
11692 in the project file.
11693
11694 @smallexample @c projectfile
11695    for Object_Dir use "objects";
11696 @end smallexample
11697
11698 @noindent
11699 The attribute @var{Object_Dir} has a string value, the path name of the object
11700 directory. The path name may be absolute or relative to the directory of the
11701 project file. This directory must already exist, and be readable and writable.
11702
11703 By default, when the attribute @code{Object_Dir} is not given an explicit value
11704 or when its value is the empty string, the object directory is the same as the
11705 directory containing the project file.
11706
11707 @node Exec Directory
11708 @subsection Exec Directory
11709
11710 @noindent
11711 The exec directory for a project is the directory containing the executables
11712 for the project's main subprograms.
11713
11714 The exec directory is given by the value of the attribute @code{Exec_Dir}
11715 in the project file.
11716
11717 @smallexample @c projectfile
11718    for Exec_Dir use "executables";
11719 @end smallexample
11720
11721 @noindent
11722 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11723 directory. The path name may be absolute or relative to the directory of the
11724 project file. This directory must already exist, and be writable.
11725
11726 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11727 or when its value is the empty string, the exec directory is the same as the
11728 object directory of the project file.
11729
11730 @node Source Directories
11731 @subsection Source Directories
11732
11733 @noindent
11734 The source directories of a project are specified by the project file
11735 attribute @code{Source_Dirs}.
11736
11737 This attribute's value is a string list. If the attribute is not given an
11738 explicit value, then there is only one source directory, the one where the
11739 project file resides.
11740
11741 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11742 as in
11743
11744 @smallexample @c projectfile
11745     for Source_Dirs use ();
11746 @end smallexample
11747
11748 @noindent
11749 indicates that the project contains no source files.
11750
11751 Otherwise, each string in the string list designates one or more
11752 source directories.
11753
11754 @smallexample @c projectfile
11755    for Source_Dirs use ("sources", "test/drivers");
11756 @end smallexample
11757
11758 @noindent
11759 If a string in the list ends with @code{"/**"},  then the directory whose path
11760 name precedes the two asterisks, as well as all its subdirectories
11761 (recursively), are source directories.
11762
11763 @smallexample @c projectfile
11764    for Source_Dirs use ("/system/sources/**");
11765 @end smallexample
11766
11767 @noindent
11768 Here the directory @code{/system/sources} and all of its subdirectories
11769 (recursively) are source directories.
11770
11771 To specify that the source directories are the directory of the project file
11772 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11773 @smallexample @c projectfile
11774    for Source_Dirs use ("./**");
11775 @end smallexample
11776
11777 @noindent
11778 Each of the source directories must exist and be readable.
11779
11780 @node Source File Names
11781 @subsection Source File Names
11782
11783 @noindent
11784 In a project that contains source files, their names may be specified by the
11785 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11786 (a string). Source file names never include any directory information.
11787
11788 If the attribute @code{Source_Files} is given an explicit value, then each
11789 element of the list is a source file name.
11790
11791 @smallexample @c projectfile
11792    for Source_Files use ("main.adb");
11793    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11794 @end smallexample
11795
11796 @noindent
11797 If the attribute @code{Source_Files} is not given an explicit value,
11798 but the attribute @code{Source_List_File} is given a string value,
11799 then the source file names are contained in the text file whose path name
11800 (absolute or relative to the directory of the project file) is the
11801 value of the attribute @code{Source_List_File}.
11802
11803 Each line in the file that is not empty or is not a comment
11804 contains a source file name.
11805
11806 @smallexample @c projectfile
11807    for Source_List_File use "source_list.txt";
11808 @end smallexample
11809
11810 @noindent
11811 By default, if neither the attribute @code{Source_Files} nor the attribute
11812 @code{Source_List_File} is given an explicit value, then each file in the
11813 source directories that conforms to the project's naming scheme
11814 (see @ref{Naming Schemes}) is an immediate source of the project.
11815
11816 A warning is issued if both attributes @code{Source_Files} and
11817 @code{Source_List_File} are given explicit values. In this case, the attribute
11818 @code{Source_Files} prevails.
11819
11820 Each source file name must be the name of one existing source file
11821 in one of the source directories.
11822
11823 A @code{Source_Files} attribute whose value is an empty list
11824 indicates that there are no source files in the project.
11825
11826 If the order of the source directories is known statically, that is if
11827 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11828 be several files with the same source file name. In this case, only the file
11829 in the first directory is considered as an immediate source of the project
11830 file. If the order of the source directories is not known statically, it is
11831 an error to have several files with the same source file name.
11832
11833 Projects can be specified to have no Ada source
11834 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11835 list, or the @code{"Ada"} may be absent from @code{Languages}:
11836
11837 @smallexample @c projectfile
11838    for Source_Dirs use ();
11839    for Source_Files use ();
11840    for Languages use ("C", "C++");
11841 @end smallexample
11842
11843 @noindent
11844 Otherwise, a project must contain at least one immediate source.
11845
11846 Projects with no source files are useful as template packages
11847 (see @ref{Packages in Project Files}) for other projects; in particular to
11848 define a package @code{Naming} (see @ref{Naming Schemes}).
11849
11850 @c ****************************
11851 @c * Importing Projects *
11852 @c ****************************
11853
11854 @node  Importing Projects
11855 @section Importing Projects
11856
11857 @noindent
11858 An immediate source of a project P may depend on source files that
11859 are neither immediate sources of P nor in the predefined library.
11860 To get this effect, P must @emph{import} the projects that contain the needed
11861 source files.
11862
11863 @smallexample @c projectfile
11864 @group
11865   with "project1", "utilities.gpr";
11866   with "/namings/apex.gpr";
11867   project Main is
11868     ...
11869 @end group
11870 @end smallexample
11871
11872 @noindent
11873 As can be seen in this example, the syntax for importing projects is similar
11874 to the syntax for importing compilation units in Ada. However, project files
11875 use literal strings instead of names, and the @code{with} clause identifies
11876 project files rather than packages.
11877
11878 Each literal string is the file name or path name (absolute or relative) of a
11879 project file. If a string is simply a file name, with no path, then its
11880 location is determined by the @emph{project path}:
11881
11882 @itemize @bullet
11883 @item
11884 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11885 then the project path includes all the directories in this
11886 ^environment variable^logical name^, plus the directory of the project file.
11887
11888 @item
11889 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11890 exist, then the project path contains only one directory, namely the one where
11891 the project file is located.
11892 @end itemize
11893
11894 @noindent
11895 If a relative pathname is used, as in
11896
11897 @smallexample @c projectfile
11898   with "tests/proj";
11899 @end smallexample
11900
11901 @noindent
11902 then the path is relative to the directory where the importing project file is
11903 located. Any symbolic link will be fully resolved in the directory
11904 of the importing project file before the imported project file is examined.
11905
11906 If the @code{with}'ed project file name does not have an extension,
11907 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11908 then the file name as specified in the @code{with} clause (no extension) will
11909 be used. In the above example, if a file @code{project1.gpr} is found, then it
11910 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11911 then it will be used; if neither file exists, this is an error.
11912
11913 A warning is issued if the name of the project file does not match the
11914 name of the project; this check is case insensitive.
11915
11916 Any source file that is an immediate source of the imported project can be
11917 used by the immediate sources of the importing project, transitively. Thus
11918 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11919 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11920 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11921 because if and when @code{B} ceases to import @code{C}, some sources in
11922 @code{A} will no longer compile.
11923
11924 A side effect of this capability is that normally cyclic dependencies are not
11925 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11926 is not allowed to import @code{A}. However, there are cases when cyclic
11927 dependencies would be beneficial. For these cases, another form of import
11928 between projects exists, the @code{limited with}: a project @code{A} that
11929 imports a project @code{B} with a straigh @code{with} may also be imported,
11930 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11931 to @code{A} include at least one @code{limited with}.
11932
11933 @smallexample @c 0projectfile
11934 with "../b/b.gpr";
11935 with "../c/c.gpr";
11936 project A is
11937 end A;
11938
11939 limited with "../a/a.gpr";
11940 project B is
11941 end B;
11942
11943 with "../d/d.gpr";
11944 project C is
11945 end C;
11946
11947 limited with "../a/a.gpr";
11948 project D is
11949 end D;
11950 @end smallexample
11951
11952 @noindent
11953 In the above legal example, there are two project cycles:
11954 @itemize @bullet
11955 @item A-> B-> A
11956 @item A -> C -> D -> A
11957 @end itemize
11958
11959 @noindent
11960 In each of these cycle there is one @code{limited with}: import of @code{A}
11961 from @code{B} and import of @code{A} from @code{D}.
11962
11963 The difference between straight @code{with} and @code{limited with} is that
11964 the name of a project imported with a @code{limited with} cannot be used in the
11965 project that imports it. In particular, its packages cannot be renamed and
11966 its variables cannot be referred to.
11967
11968 An exception to the above rules for @code{limited with} is that for the main
11969 project specified to @command{gnatmake} or to the @command{GNAT} driver a
11970 @code{limited with} is equivalent to a straight @code{with}. For example,
11971 in the example above, projects @code{B} and @code{D} could not be main
11972 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
11973 each have a @code{limited with} that is the only one in a cycle of importing
11974 projects.
11975
11976 @c *********************
11977 @c * Project Extension *
11978 @c *********************
11979
11980 @node Project Extension
11981 @section Project Extension
11982
11983 @noindent
11984 During development of a large system, it is sometimes necessary to use
11985 modified versions of some of the source files, without changing the original
11986 sources. This can be achieved through the @emph{project extension} facility.
11987
11988 @smallexample @c projectfile
11989    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
11990 @end smallexample
11991
11992 @noindent
11993 A project extension declaration introduces an extending project
11994 (the @emph{child}) and a project being extended (the @emph{parent}).
11995
11996 By default, a child project inherits all the sources of its parent.
11997 However, inherited sources can be overridden: a unit in a parent is hidden
11998 by a unit of the same name in the child.
11999
12000 Inherited sources are considered to be sources (but not immediate sources)
12001 of the child project; see @ref{Project File Syntax}.
12002
12003 An inherited source file retains any switches specified in the parent project.
12004
12005 For example if the project @code{Utilities} contains the specification and the
12006 body of an Ada package @code{Util_IO}, then the project
12007 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12008 The original body of @code{Util_IO} will not be considered in program builds.
12009 However, the package specification will still be found in the project
12010 @code{Utilities}.
12011
12012 A child project can have only one parent but it may import any number of other
12013 projects.
12014
12015 A project is not allowed to import directly or indirectly at the same time a
12016 child project and any of its ancestors.
12017
12018 @c ****************************************
12019 @c * External References in Project Files *
12020 @c ****************************************
12021
12022 @node  External References in Project Files
12023 @section External References in Project Files
12024
12025 @noindent
12026 A project file may contain references to external variables; such references
12027 are called @emph{external references}.
12028
12029 An external variable is either defined as part of the environment (an
12030 environment variable in Unix, for example) or else specified on the command
12031 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12032 If both, then the command line value is used.
12033
12034 The value of an external reference is obtained by means of the built-in
12035 function @code{external}, which returns a string value.
12036 This function has two forms:
12037 @itemize @bullet
12038 @item @code{external (external_variable_name)}
12039 @item @code{external (external_variable_name, default_value)}
12040 @end itemize
12041
12042 @noindent
12043 Each parameter must be a string literal.  For example:
12044
12045 @smallexample @c projectfile
12046    external ("USER")
12047    external ("OS", "GNU/Linux")
12048 @end smallexample
12049
12050 @noindent
12051 In the form with one parameter, the function returns the value of
12052 the external variable given as parameter. If this name is not present in the
12053 environment, the function returns an empty string.
12054
12055 In the form with two string parameters, the second argument is
12056 the value returned when the variable given as the first argument is not
12057 present in the environment. In the example above, if @code{"OS"} is not
12058 the name of ^an environment variable^a logical name^ and is not passed on
12059 the command line, then the returned value is @code{"GNU/Linux"}.
12060
12061 An external reference may be part of a string expression or of a string
12062 list expression, and can therefore appear in a variable declaration or
12063 an attribute declaration.
12064
12065 @smallexample @c projectfile
12066 @group
12067    type Mode_Type is ("Debug", "Release");
12068    Mode : Mode_Type := external ("MODE");
12069    case Mode is
12070      when "Debug" =>
12071         ...
12072 @end group
12073 @end smallexample
12074
12075 @c *****************************
12076 @c * Packages in Project Files *
12077 @c *****************************
12078
12079 @node  Packages in Project Files
12080 @section Packages in Project Files
12081
12082 @noindent
12083 A @emph{package} defines the settings for project-aware tools within a
12084 project.
12085 For each such tool one can declare a package; the names for these
12086 packages are preset (see @ref{Packages}).
12087 A package may contain variable declarations, attribute declarations, and case
12088 constructions.
12089
12090 @smallexample @c projectfile
12091 @group
12092    project Proj is
12093       package Builder is  -- used by gnatmake
12094          for ^Default_Switches^Default_Switches^ ("Ada")
12095              use ("^-v^-v^",
12096                   "^-g^-g^");
12097       end Builder;
12098    end Proj;
12099 @end group
12100 @end smallexample
12101
12102 @noindent
12103 The syntax of package declarations mimics that of package in Ada.
12104
12105 Most of the packages have an attribute
12106 @code{^Default_Switches^Default_Switches^}.
12107 This attribute is an associative array, and its value is a string list.
12108 The index of the associative array is the name of a programming language (case
12109 insensitive). This attribute indicates the ^switch^switch^
12110 or ^switches^switches^ to be used
12111 with the corresponding tool.
12112
12113 Some packages also have another attribute, @code{^Switches^Switches^},
12114 an associative array whose value is a string list.
12115 The index is the name of a source file.
12116 This attribute indicates the ^switch^switch^
12117 or ^switches^switches^ to be used by the corresponding
12118 tool when dealing with this specific file.
12119
12120 Further information on these ^switch^switch^-related attributes is found in
12121 @ref{^Switches^Switches^ and Project Files}.
12122
12123 A package may be declared as a @emph{renaming} of another package; e.g., from
12124 the project file for an imported project.
12125
12126 @smallexample @c projectfile
12127 @group
12128   with "/global/apex.gpr";
12129   project Example is
12130     package Naming renames Apex.Naming;
12131     ...
12132   end Example;
12133 @end group
12134 @end smallexample
12135
12136 @noindent
12137 Packages that are renamed in other project files often come from project files
12138 that have no sources: they are just used as templates. Any modification in the
12139 template will be reflected automatically in all the project files that rename
12140 a package from the template.
12141
12142 In addition to the tool-oriented packages, you can also declare a package
12143 named @code{Naming} to establish specialized source file naming conventions
12144 (see @ref{Naming Schemes}).
12145
12146 @c ************************************
12147 @c * Variables from Imported Projects *
12148 @c ************************************
12149
12150 @node Variables from Imported Projects
12151 @section Variables from Imported Projects
12152
12153 @noindent
12154 An attribute or variable defined in an imported or parent project can
12155 be used in expressions in the importing / extending project.
12156 Such an attribute or variable is denoted by an expanded name whose prefix
12157 is either the name of the project or the expanded name of a package within
12158 a project.
12159
12160 @smallexample @c projectfile
12161 @group
12162   with "imported";
12163   project Main extends "base" is
12164      Var1 := Imported.Var;
12165      Var2 := Base.Var & ".new";
12166 @end group
12167
12168 @group
12169      package Builder is
12170         for ^Default_Switches^Default_Switches^ ("Ada")
12171             use Imported.Builder.Ada_^Switches^Switches^ &
12172                 "^-gnatg^-gnatg^" &
12173                 "^-v^-v^";
12174      end Builder;
12175 @end group
12176
12177 @group
12178      package Compiler is
12179         for ^Default_Switches^Default_Switches^ ("Ada")
12180             use Base.Compiler.Ada_^Switches^Switches^;
12181      end Compiler;
12182   end Main;
12183 @end group
12184 @end smallexample
12185
12186 @noindent
12187 In this example:
12188
12189 @itemize @bullet
12190 @item
12191 The value of @code{Var1} is a copy of the variable @code{Var} defined
12192 in the project file @file{"imported.gpr"}
12193 @item
12194 the value of @code{Var2} is a copy of the value of variable @code{Var}
12195 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12196 @item
12197 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12198 @code{Builder} is a string list that includes in its value a copy of the value
12199 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12200 in project file @file{imported.gpr} plus two new elements:
12201 @option{"^-gnatg^-gnatg^"}
12202 and @option{"^-v^-v^"};
12203 @item
12204 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12205 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12206 defined in the @code{Compiler} package in project file @file{base.gpr},
12207 the project being extended.
12208 @end itemize
12209
12210 @c ******************
12211 @c * Naming Schemes *
12212 @c ******************
12213
12214 @node  Naming Schemes
12215 @section Naming Schemes
12216
12217 @noindent
12218 Sometimes an Ada software system is ported from a foreign compilation
12219 environment to GNAT, and the file names do not use the default GNAT
12220 conventions. Instead of changing all the file names (which for a variety
12221 of reasons might not be possible), you can define the relevant file
12222 naming scheme in the @code{Naming} package in your project file.
12223
12224 @noindent
12225 Note that the use of pragmas described in @ref{Alternative
12226 File Naming Schemes} by mean of a configuration pragmas file is not
12227 supported when using project files. You must use the features described
12228 in this paragraph. You can however use specify other configuration
12229 pragmas (see @ref{Specifying Configuration Pragmas}).
12230
12231 @ifclear vms
12232 For example, the following
12233 package models the Apex file naming rules:
12234
12235 @smallexample @c projectfile
12236 @group
12237   package Naming is
12238     for Casing               use "lowercase";
12239     for Dot_Replacement      use ".";
12240     for Spec_Suffix ("Ada")  use ".1.ada";
12241     for Body_Suffix ("Ada")  use ".2.ada";
12242   end Naming;
12243 @end group
12244 @end smallexample
12245 @end ifclear
12246
12247 @ifset vms
12248 For example, the following package models the DEC Ada file naming rules:
12249
12250 @smallexample @c projectfile
12251 @group
12252   package Naming is
12253     for Casing               use "lowercase";
12254     for Dot_Replacement      use "__";
12255     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12256     for Body_Suffix ("Ada")  use ".^ada^ada^";
12257   end Naming;
12258 @end group
12259 @end smallexample
12260
12261 @noindent
12262 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12263 names in lower case)
12264 @end ifset
12265
12266 @noindent
12267 You can define the following attributes in package @code{Naming}:
12268
12269 @table @code
12270
12271 @item @var{Casing}
12272 This must be a string with one of the three values @code{"lowercase"},
12273 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12274
12275 @noindent
12276 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12277
12278 @item @var{Dot_Replacement}
12279 This must be a string whose value satisfies the following conditions:
12280
12281 @itemize @bullet
12282 @item It must not be empty
12283 @item It cannot start or end with an alphanumeric character
12284 @item It cannot be a single underscore
12285 @item It cannot start with an underscore followed by an alphanumeric
12286 @item It cannot contain a dot @code{'.'} except if the entire string
12287 is @code{"."}
12288 @end itemize
12289
12290 @noindent
12291 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12292
12293 @item @var{Spec_Suffix}
12294 This is an associative array (indexed by the programming language name, case
12295 insensitive) whose value is a string that must satisfy the following
12296 conditions:
12297
12298 @itemize @bullet
12299 @item It must not be empty
12300 @item It must include at least one dot
12301 @end itemize
12302 @noindent
12303 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12304 @code{"^.ads^.ADS^"}.
12305
12306 @item @var{Body_Suffix}
12307 This is an associative array (indexed by the programming language name, case
12308 insensitive) whose value is a string that must satisfy the following
12309 conditions:
12310
12311 @itemize @bullet
12312 @item It must not be empty
12313 @item It must include at least one dot
12314 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12315 @end itemize
12316 @noindent
12317 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12318 @code{"^.adb^.ADB^"}.
12319
12320 @item @var{Separate_Suffix}
12321 This must be a string whose value satisfies the same conditions as
12322 @code{Body_Suffix}.
12323
12324 @noindent
12325 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12326 value as @code{Body_Suffix ("Ada")}.
12327
12328 @item @var{Spec}
12329 @noindent
12330 You can use the associative array attribute @code{Spec}  to define
12331 the source file name for an individual Ada compilation unit's spec. The array
12332 index must be a string literal that identifies the Ada unit (case insensitive).
12333 The value of this attribute must be a string that identifies the file that
12334 contains this unit's spec (case sensitive or insensitive depending on the
12335 operating system).
12336
12337 @smallexample @c projectfile
12338    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12339 @end smallexample
12340
12341 @item @var{Body}
12342
12343 You can use the associative array attribute @code{Body} to
12344 define the source file name for an individual Ada compilation unit's body
12345 (possibly a subunit).  The array index must be a string literal that identifies
12346 the Ada unit (case insensitive).  The value of this attribute must be a string
12347 that identifies the file that contains this unit's body or subunit (case
12348 sensitive or insensitive depending on the operating system).
12349
12350 @smallexample @c projectfile
12351    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12352 @end smallexample
12353 @end table
12354
12355 @c ********************
12356 @c * Library Projects *
12357 @c ********************
12358
12359 @node Library Projects
12360 @section Library Projects
12361
12362 @noindent
12363 @emph{Library projects} are projects whose object code is placed in a library.
12364 (Note that this facility is not yet supported on all platforms)
12365
12366 To create a library project, you need to define in its project file
12367 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12368 Additionally, you may define the library-related attributes
12369 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12370 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12371
12372 The @code{Library_Name} attribute has a string value. There is no restriction
12373 on the name of a library. It is the responsability of the developer to
12374 choose a name that will be accepted by the platform. It is recommanded to
12375 choose names that could be Ada identifiers; such names are almost guaranteed
12376 to be acceptable on all platforms.
12377
12378 The @code{Library_Dir} attribute has a string value that designates the path
12379 (absolute or relative) of the directory where the library will reside.
12380 It must designate an existing directory, and this directory must be
12381 different from the project's object directory. It also needs to be writable.
12382
12383 If both @code{Library_Name} and @code{Library_Dir} are specified and
12384 are legal, then the project file defines a library project.  The optional
12385 library-related attributes are checked only for such project files.
12386
12387 The @code{Library_Kind} attribute has a string value that must be one of the
12388 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12389 @code{"relocatable"}. If this attribute is not specified, the library is a
12390 static library, that is an archive of object files that can be potentially
12391 linked into an static executable. Otherwise, the library may be dynamic or
12392 relocatable, that is a library that is loaded only at the start of execution.
12393 Depending on the operating system, there may or may not be a distinction
12394 between dynamic and relocatable libraries. For Unix and VMS Unix there is no
12395 such distinction.
12396
12397 If you need to build both a static and a dynamic library, you should use two
12398 different object directories, since in some cases some extra code needs to
12399 be generated for the latter. For such cases, it is recommended to either use
12400 two different project files, or a single one which uses external variables
12401 to indicate what kind of library should be build.
12402
12403 The @code{Library_Version} attribute has a string value whose interpretation
12404 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12405 used only for dynamic/relocatable libraries as the internal name of the
12406 library (the @code{"soname"}). If the library file name (built from the
12407 @code{Library_Name}) is different from the @code{Library_Version}, then the
12408 library file will be a symbolic link to the actual file whose name will be
12409 @code{Library_Version}.
12410
12411 Example (on Unix):
12412
12413 @smallexample @c projectfile
12414 @group
12415 project Plib is
12416
12417    Version := "1";
12418
12419    for Library_Dir use "lib_dir";
12420    for Library_Name use "dummy";
12421    for Library_Kind use "relocatable";
12422    for Library_Version use "libdummy.so." & Version;
12423
12424 end Plib;
12425 @end group
12426 @end smallexample
12427
12428 @noindent
12429 Directory @file{lib_dir} will contain the internal library file whose name
12430 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12431 @file{libdummy.so.1}.
12432
12433 When @command{gnatmake} detects that a project file
12434 is a library project file, it will check all immediate sources of the project
12435 and rebuild the library if any of the sources have been recompiled.
12436
12437 When a library is built or rebuilt, an attempt is made to delete all
12438 files in the library directory.
12439 All @file{ALI} files will also be copied from the object directory to the
12440 library directory. To build executables, @command{gnatmake} will use the
12441 library rather than the individual object files. The copy of the @file{ALI}
12442 files are made read-only.
12443
12444
12445 @c **********************************************
12446 @c * Using Third-Party Libraries through Projects
12447 @c **********************************************
12448 @node Using Third-Party Libraries through Projects
12449 @section Using Third-Party Libraries through Projects
12450
12451 Whether you are exporting your own library to make it available to
12452 clients, or you are using a library provided by a third party, it is
12453 convenient to have project files that automatically set the correct
12454 command line switches for the compiler and linker.
12455
12456 Such project files are very similar to the library project files;
12457 @xref{Library Projects}. The only difference is that you set the
12458 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12459 directories where, respectively, the sources and the read-only ALI files have
12460 been installed.
12461
12462 If you need to interface with a set of libraries, as opposed to a
12463 single one, you need to create one library project for each of the
12464 libraries. In addition, a top-level project that imports all these
12465 library projects should be provided, so that the user of your library
12466 has a single @code{with} clause to add to his own projects.
12467
12468 For instance, let's assume you are providing two static libraries
12469 @file{liba.a} and @file{libb.a}. The user needs to link with
12470 both of these libraries. Each of these is associated with its
12471 own set of header files. Let's assume furthermore that all the
12472 header files for the two libraries have been installed in the same
12473 directory @file{headers}. The @file{ALI} files are found in the same
12474 @file{headers} directory.
12475
12476 In this case, you should provide the following three projects:
12477
12478 @smallexample @c projectfile
12479 @group
12480 with "liba", "libb";
12481 project My_Library is
12482   for Source_Dirs use ("headers");
12483   for Object_Dir  use "headers";
12484 end My_Library;
12485 @end group
12486
12487 @group
12488 project Liba is
12489    for Source_Dirs use ();
12490    for Library_Dir use "lib";
12491    for Library_Name use "a";
12492    for Library_Kind use "static";
12493 end Liba;
12494 @end group
12495
12496 @group
12497 project Libb is
12498    for Source_Dirs use ();
12499    for Library_Dir use "lib";
12500    for Library_Name use "b";
12501    for Library_Kind use "static";
12502 end Libb;
12503 @end group
12504 @end smallexample
12505
12506 @c *******************************
12507 @c * Stand-alone Library Projects *
12508 @c *******************************
12509
12510 @node Stand-alone Library Projects
12511 @section Stand-alone Library Projects
12512
12513 @noindent
12514 A Stand-alone Library is a library that contains the necessary code to
12515 elaborate the Ada units that are included in the library. A Stand-alone
12516 Library is suitable to be used in an executable when the main is not
12517 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12518 subprogram.
12519
12520 A Stand-alone Library Project is a Library Project where the library is
12521 a Stand-alone Library.
12522
12523 To be a Stand-alone Library Project, in addition to the two attributes
12524 that make a project a Library Project (@code{Library_Name} and
12525 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12526 @code{Library_Interface} must be defined.
12527
12528 @smallexample @c projectfile
12529 @group
12530    for Library_Dir use "lib_dir";
12531    for Library_Name use "dummy";
12532    for Library_Interface use ("int1", "int1.child");
12533 @end group
12534 @end smallexample
12535
12536 Attribute @code{Library_Interface} has a non empty string list value,
12537 each string in the list designating a unit contained in an immediate source
12538 of the project file.
12539
12540 When a Stand-alone Library is built, first the binder is invoked to build
12541 a package whose name depends on the library name
12542 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12543 This binder-generated package includes initialization and
12544 finalization procedures whose
12545 names depend on the library name (dummyinit and dummyfinal in the example
12546 above). The object corresponding to this package is included in the library.
12547
12548 A dynamic or relocatable Stand-alone Library is automatically initialized
12549 if automatic initialization of Stand-alone Libraries is supported on the
12550 platform and if attribute @code{Library_Auto_Init} is not specified or
12551 is specified with the value "true". A static Stand-alone Library is never
12552 automatically initialized.
12553
12554 Single string attribute @code{Library_Auto_Init} may be specified with only
12555 two possible values: "false" or "true" (case-insensitive). Specifying
12556 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12557 initialization of dynamic or relocatable libraries.
12558
12559 When a non automatically initialized Stand-alone Library is used
12560 in an executable, its initialization procedure must be called before
12561 any service of the library is used.
12562 When the main subprogram is in Ada, it may mean that the initialization
12563 procedure has to be called during elaboration of another package.
12564
12565 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12566 (those that are listed in attribute @code{Library_Interface}) are copied to
12567 the Library Directory. As a consequence, only the Interface Units may be
12568 imported from Ada units outside of the library. If other units are imported,
12569 the binding phase will fail.
12570
12571 When a Stand-Alone Library is bound, the switches that are specified in
12572 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12573 used in the call to @command{gnatbind}.
12574
12575 The string list attribute @code{Library_Options} may be used to specified
12576 additional switches to the call to @command{gcc} to link the library.
12577
12578 The attribute @code{Library_Src_Dir}, may be specified for a
12579 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12580 single string value. Its value must be the path (absolute or relative to the
12581 project directory) of an existing directory. This directory cannot be the
12582 object directory or one of the source directories, but it can be the same as
12583 the library directory. The sources of the Interface
12584 Units of the library, necessary to an Ada client of the library, will be
12585 copied to the designated directory, called Interface Copy directory.
12586 These sources includes the specs of the Interface Units, but they may also
12587 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12588 are used, or when there is a generic units in the spec. Before the sources
12589 are copied to the Interface Copy directory, an attempt is made to delete all
12590 files in the Interface Copy directory.
12591
12592 @c *************************************
12593 @c * Switches Related to Project Files *
12594 @c *************************************
12595 @node Switches Related to Project Files
12596 @section Switches Related to Project Files
12597
12598 @noindent
12599 The following switches are used by GNAT tools that support project files:
12600
12601 @table @option
12602
12603 @item ^-P^/PROJECT_FILE=^@var{project}
12604 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12605 Indicates the name of a project file. This project file will be parsed with
12606 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12607 if any, and using the external references indicated
12608 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12609 @ifclear vms
12610 There may zero, one or more spaces between @option{-P} and @var{project}.
12611 @end ifclear
12612
12613 @noindent
12614 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12615
12616 @noindent
12617 Since the Project Manager parses the project file only after all the switches
12618 on the command line are checked, the order of the switches
12619 @option{^-P^/PROJECT_FILE^},
12620 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12621 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12622
12623 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12624 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12625 Indicates that external variable @var{name} has the value @var{value}.
12626 The Project Manager will use this value for occurrences of
12627 @code{external(name)} when parsing the project file.
12628
12629 @ifclear vms
12630 @noindent
12631 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12632 put between quotes.
12633 @smallexample
12634   -XOS=NT
12635   -X"user=John Doe"
12636 @end smallexample
12637 @end ifclear
12638
12639 @noindent
12640 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12641 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12642 @var{name}, only the last one is used.
12643
12644 @noindent
12645 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12646 takes precedence over the value of the same name in the environment.
12647
12648 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12649 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12650 @c Previous line uses code vs option command, to stay less than 80 chars
12651 Indicates the verbosity of the parsing of GNAT project files.
12652
12653 @ifclear vms
12654 @option{-vP0} means Default;
12655 @option{-vP1} means Medium;
12656 @option{-vP2} means High.
12657 @end ifclear
12658
12659 @ifset vms
12660 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12661 HIGH.
12662 @end ifset
12663
12664 @noindent
12665 The default is ^Default^DEFAULT^: no output for syntactically correct
12666 project files.
12667 @noindent
12668 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12669 only the last one is used.
12670
12671 @end table
12672
12673 @c **********************************
12674 @c * Tools Supporting Project Files *
12675 @c **********************************
12676
12677 @node  Tools Supporting Project Files
12678 @section Tools Supporting Project Files
12679
12680 @menu
12681 * gnatmake and Project Files::
12682 * The GNAT Driver and Project Files::
12683 @ifclear vms
12684 * Glide and Project Files::
12685 @end ifclear
12686 @end menu
12687
12688 @node gnatmake and Project Files
12689 @subsection gnatmake and Project Files
12690
12691 @noindent
12692 This section covers several topics related to @command{gnatmake} and
12693 project files: defining ^switches^switches^ for @command{gnatmake}
12694 and for the tools that it invokes; specifying configuration pragmas;
12695 the use of the @code{Main} attribute; building and rebuilding library project
12696 files.
12697
12698 @menu
12699 * ^Switches^Switches^ and Project Files::
12700 * Specifying Configuration Pragmas::
12701 * Project Files and Main Subprograms::
12702 * Library Project Files::
12703 @end menu
12704
12705 @node ^Switches^Switches^ and Project Files
12706 @subsubsection ^Switches^Switches^ and Project Files
12707
12708 @ifset vms
12709 It is not currently possible to specify VMS style qualifiers in the project
12710 files; only Unix style ^switches^switches^ may be specified.
12711 @end ifset
12712
12713 @noindent
12714 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12715 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12716 attribute, a @code{^Switches^Switches^} attribute, or both;
12717 as their names imply, these ^switch^switch^-related
12718 attributes affect the ^switches^switches^ that are used for each of these GNAT
12719 components when
12720 @command{gnatmake} is invoked.  As will be explained below, these
12721 component-specific ^switches^switches^ precede
12722 the ^switches^switches^ provided on the @command{gnatmake} command line.
12723
12724 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12725 array indexed by language name (case insensitive) whose value is a string list.
12726 For example:
12727
12728 @smallexample @c projectfile
12729 @group
12730 package Compiler is
12731   for ^Default_Switches^Default_Switches^ ("Ada")
12732       use ("^-gnaty^-gnaty^",
12733            "^-v^-v^");
12734 end Compiler;
12735 @end group
12736 @end smallexample
12737
12738 @noindent
12739 The @code{^Switches^Switches^} attribute is also an associative array,
12740 indexed by a file name (which may or may not be case sensitive, depending
12741 on the operating system) whose value is a string list.  For example:
12742
12743 @smallexample @c projectfile
12744 @group
12745 package Builder is
12746    for ^Switches^Switches^ ("main1.adb")
12747        use ("^-O2^-O2^");
12748    for ^Switches^Switches^ ("main2.adb")
12749        use ("^-g^-g^");
12750 end Builder;
12751 @end group
12752 @end smallexample
12753
12754 @noindent
12755 For the @code{Builder} package, the file names must designate source files
12756 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12757 file names must designate @file{ALI} or source files for main subprograms.
12758 In each case just the file name without an explicit extension is acceptable.
12759
12760 For each tool used in a program build (@command{gnatmake}, the compiler, the
12761 binder, and the linker), the corresponding package @dfn{contributes} a set of
12762 ^switches^switches^ for each file on which the tool is invoked, based on the
12763 ^switch^switch^-related attributes defined in the package.
12764 In particular, the ^switches^switches^
12765 that each of these packages contributes for a given file @var{f} comprise:
12766
12767 @itemize @bullet
12768 @item
12769 the value of attribute @code{^Switches^Switches^ (@var{f})},
12770 if it is specified in the package for the given file,
12771 @item
12772 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12773 if it is specified in the package.
12774 @end itemize
12775
12776 @noindent
12777 If neither of these attributes is defined in the package, then the package does
12778 not contribute any ^switches^switches^ for the given file.
12779
12780 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12781 two sets, in the following order: those contributed for the file
12782 by the @code{Builder} package;
12783 and the switches passed on the command line.
12784
12785 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12786 the ^switches^switches^ passed to the tool comprise three sets,
12787 in the following order:
12788
12789 @enumerate
12790 @item
12791 the applicable ^switches^switches^ contributed for the file
12792 by the @code{Builder} package in the project file supplied on the command line;
12793
12794 @item
12795 those contributed for the file by the package (in the relevant project file --
12796 see below) corresponding to the tool; and
12797
12798 @item
12799 the applicable switches passed on the command line.
12800 @end enumerate
12801
12802 @noindent
12803 The term @emph{applicable ^switches^switches^} reflects the fact that
12804 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12805 tools, depending on the individual ^switch^switch^.
12806
12807 @command{gnatmake} may invoke the compiler on source files from different
12808 projects. The Project Manager will use the appropriate project file to
12809 determine the @code{Compiler} package for each source file being compiled.
12810 Likewise for the @code{Binder} and @code{Linker} packages.
12811
12812 As an example, consider the following package in a project file:
12813
12814 @smallexample @c projectfile
12815 @group
12816 project Proj1 is
12817    package Compiler is
12818       for ^Default_Switches^Default_Switches^ ("Ada")
12819           use ("^-g^-g^");
12820       for ^Switches^Switches^ ("a.adb")
12821           use ("^-O1^-O1^");
12822       for ^Switches^Switches^ ("b.adb")
12823           use ("^-O2^-O2^",
12824                "^-gnaty^-gnaty^");
12825    end Compiler;
12826 end Proj1;
12827 @end group
12828 @end smallexample
12829
12830 @noindent
12831 If @command{gnatmake} is invoked with this project file, and it needs to
12832 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12833 @file{a.adb} will be compiled with the ^switch^switch^
12834 @option{^-O1^-O1^},
12835 @file{b.adb} with ^switches^switches^
12836 @option{^-O2^-O2^}
12837 and @option{^-gnaty^-gnaty^},
12838 and @file{c.adb} with @option{^-g^-g^}.
12839
12840 The following example illustrates the ordering of the ^switches^switches^
12841 contributed by different packages:
12842
12843 @smallexample @c projectfile
12844 @group
12845 project Proj2 is
12846    package Builder is
12847       for ^Switches^Switches^ ("main.adb")
12848           use ("^-g^-g^",
12849                "^-O1^-)1^",
12850                "^-f^-f^");
12851    end Builder;
12852 @end group
12853
12854 @group
12855    package Compiler is
12856       for ^Switches^Switches^ ("main.adb")
12857           use ("^-O2^-O2^");
12858    end Compiler;
12859 end Proj2;
12860 @end group
12861 @end smallexample
12862
12863 @noindent
12864 If you issue the command:
12865
12866 @smallexample
12867     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12868 @end smallexample
12869
12870 @noindent
12871 then the compiler will be invoked on @file{main.adb} with the following
12872 sequence of ^switches^switches^
12873
12874 @smallexample
12875    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12876 @end smallexample
12877
12878 with the last @option{^-O^-O^}
12879 ^switch^switch^ having precedence over the earlier ones;
12880 several other ^switches^switches^
12881 (such as @option{^-c^-c^}) are added implicitly.
12882
12883 The ^switches^switches^
12884 @option{^-g^-g^}
12885 and @option{^-O1^-O1^} are contributed by package
12886 @code{Builder},  @option{^-O2^-O2^} is contributed
12887 by the package @code{Compiler}
12888 and @option{^-O0^-O0^} comes from the command line.
12889
12890 The @option{^-g^-g^}
12891 ^switch^switch^ will also be passed in the invocation of
12892 @command{Gnatlink.}
12893
12894 A final example illustrates switch contributions from packages in different
12895 project files:
12896
12897 @smallexample @c projectfile
12898 @group
12899 project Proj3 is
12900    for Source_Files use ("pack.ads", "pack.adb");
12901    package Compiler is
12902       for ^Default_Switches^Default_Switches^ ("Ada")
12903           use ("^-gnata^-gnata^");
12904    end Compiler;
12905 end Proj3;
12906 @end group
12907
12908 @group
12909 with "Proj3";
12910 project Proj4 is
12911    for Source_Files use ("foo_main.adb", "bar_main.adb");
12912    package Builder is
12913       for ^Switches^Switches^ ("foo_main.adb")
12914           use ("^-s^-s^",
12915                "^-g^-g^");
12916    end Builder;
12917 end Proj4;
12918 @end group
12919
12920 @group
12921 -- Ada source file:
12922 with Pack;
12923 procedure Foo_Main is
12924    ...
12925 end Foo_Main;
12926 @end group
12927 @end smallexample
12928
12929 If the command is
12930 @smallexample
12931 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12932 @end smallexample
12933
12934 @noindent
12935 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12936 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12937 @option{^-gnato^-gnato^} (passed on the command line).
12938 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12939 are @option{^-g^-g^} from @code{Proj4.Builder},
12940 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12941 and @option{^-gnato^-gnato^} from the command line.
12942
12943 @noindent
12944 When using @command{gnatmake} with project files, some ^switches^switches^ or
12945 arguments may be expressed as relative paths. As the working directory where
12946 compilation occurs may change, these relative paths are converted to absolute
12947 paths. For the ^switches^switches^ found in a project file, the relative paths
12948 are relative to the project file directory, for the switches on the command
12949 line, they are relative to the directory where @command{gnatmake} is invoked.
12950 The ^switches^switches^ for which this occurs are:
12951 ^-I^-I^,
12952 ^-A^-A^,
12953 ^-L^-L^,
12954 ^-aO^-aO^,
12955 ^-aL^-aL^,
12956 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12957 ^switch^switch^
12958 ^-o^-o^, object files specified in package @code{Linker} or after
12959 -largs on the command line). The exception to this rule is the ^switch^switch^
12960 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12961
12962 @node Specifying Configuration Pragmas
12963 @subsubsection Specifying Configuration Pragmas
12964
12965 When using @command{gnatmake} with project files, if there exists a file
12966 @file{gnat.adc} that contains configuration pragmas, this file will be
12967 ignored.
12968
12969 Configuration pragmas can be defined by means of the following attributes in
12970 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12971 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12972
12973 Both these attributes are single string attributes. Their values is the path
12974 name of a file containing configuration pragmas. If a path name is relative,
12975 then it is relative to the project directory of the project file where the
12976 attribute is defined.
12977
12978 When compiling a source, the configuration pragmas used are, in order,
12979 those listed in the file designated by attribute
12980 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12981 project file, if it is specified, and those listed in the file designated by
12982 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12983 the project file of the source, if it exists.
12984
12985 @node Project Files and Main Subprograms
12986 @subsubsection Project Files and Main Subprograms
12987
12988 @noindent
12989 When using a project file, you can invoke @command{gnatmake}
12990 with one or several main subprograms, by specifying their source files on the
12991 command line.
12992
12993 @smallexample
12994     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
12995 @end smallexample
12996
12997 @noindent
12998 Each of these needs to be a source file of the same project, except
12999 when the switch ^-u^/UNIQUE^ is used.
13000
13001 @noindent
13002 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13003 same project, one of the project in the tree rooted at the project specified
13004 on the command line. The package @code{Builder} of this common project, the
13005 "main project" is the one that is considered by @command{gnatmake}.
13006
13007 @noindent
13008 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13009 imported directly or indirectly by the project specified on the command line.
13010 Note that if such a source file is not part of the project specified on the
13011 command line, the ^switches^switches^ found in package @code{Builder} of the
13012 project specified on the command line, if any, that are transmitted
13013 to the compiler will still be used, not those found in the project file of
13014 the source file.
13015
13016 @noindent
13017 When using a project file, you can also invoke @command{gnatmake} without
13018 explicitly specifying any main, and the effect depends on whether you have
13019 defined the @code{Main} attribute.  This attribute has a string list value,
13020 where each element in the list is the name of a source file (the file
13021 extension is optional) that contains a unit that can be a main subprogram.
13022
13023 If the @code{Main} attribute is defined in a project file as a non-empty
13024 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13025 line, then invoking @command{gnatmake} with this project file but without any
13026 main on the command line is equivalent to invoking @command{gnatmake} with all
13027 the file names in the @code{Main} attribute on the command line.
13028
13029 Example:
13030 @smallexample @c projectfile
13031 @group
13032    project Prj is
13033       for Main use ("main1", "main2", "main3");
13034    end Prj;
13035 @end group
13036 @end smallexample
13037
13038 @noindent
13039 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13040 is equivalent to
13041 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13042
13043 When the project attribute @code{Main} is not specified, or is specified
13044 as an empty string list, or when the switch @option{-u} is used on the command
13045 line, then invoking @command{gnatmake} with no main on the command line will
13046 result in all immediate sources of the project file being checked, and
13047 potentially recompiled. Depending on the presence of the switch @option{-u},
13048 sources from other project files on which the immediate sources of the main
13049 project file depend are also checked and potentially recompiled. In other
13050 words, the @option{-u} switch is applied to all of the immediate sources of the
13051 main project file.
13052
13053 When no main is specified on the command line and attribute @code{Main} exists
13054 and includes several mains, or when several mains are specified on the
13055 command line, the default ^switches^switches^ in package @code{Builder} will
13056 be used for all mains, even if there are specific ^switches^switches^
13057 specified for one or several mains.
13058
13059 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13060 the specific ^switches^switches^ for each main, if they are specified.
13061
13062 @node Library Project Files
13063 @subsubsection Library Project Files
13064
13065 @noindent
13066 When @command{gnatmake} is invoked with a main project file that is a library
13067 project file, it is not allowed to specify one or more mains on the command
13068 line.
13069
13070 @noindent
13071 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13072 ^-l^/ACTION=LINK^ have special meanings.
13073
13074 @itemize @bullet
13075 @item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates
13076 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13077 library.
13078
13079 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13080 to @command{gnatmake} that the binder generated file should be compiled
13081 (in the case of a stand-alone library) and that the library should be built.
13082
13083 @end itemize
13084
13085 @node The GNAT Driver and Project Files
13086 @subsection The GNAT Driver and Project Files
13087
13088 @noindent
13089 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13090 are project-aware:
13091 @command{^gnatbind^gnatbind^},
13092 @command{^gnatfind^gnatfind^},
13093 @command{^gnatlink^gnatlink^},
13094 @command{^gnatls^gnatls^},
13095 @command{^gnatelim^gnatelim^},
13096 @command{^gnatpp^gnatpp^},
13097 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13098 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13099 They must be invoked through the @command{gnat} driver.
13100
13101 The @command{gnat} driver is a front-end that accepts a number of commands and
13102 call the corresponding tool. It has been designed initially for VMS to convert
13103 VMS style qualifiers to Unix style switches, but it is now available to all
13104 the GNAT supported platforms.
13105
13106 On non VMS platforms, the @command{gnat} driver accepts the following commands
13107 (case insensitive):
13108
13109 @itemize @bullet
13110 @item
13111 BIND to invoke @command{^gnatbind^gnatbind^}
13112 @item
13113 CHOP to invoke @command{^gnatchop^gnatchop^}
13114 @item
13115 CLEAN to invoke @command{^gnatclean^gnatclean^}
13116 @item
13117 COMP or COMPILE to invoke the compiler
13118 @item
13119 ELIM to invoke @command{^gnatelim^gnatelim^}
13120 @item
13121 FIND to invoke @command{^gnatfind^gnatfind^}
13122 @item
13123 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13124 @item
13125 LINK to invoke @command{^gnatlink^gnatlink^}
13126 @item
13127 LS or LIST to invoke @command{^gnatls^gnatls^}
13128 @item
13129 MAKE to invoke @command{^gnatmake^gnatmake^}
13130 @item
13131 NAME to invoke @command{^gnatname^gnatname^}
13132 @item
13133 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13134 @item
13135 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13136 @item
13137 STUB to invoke @command{^gnatstub^gnatstub^}
13138 @item
13139 XREF to invoke @command{^gnatxref^gnatxref^}
13140 @end itemize
13141
13142 @noindent
13143 Note that the compiler is invoked using the command
13144 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}.
13145
13146 @noindent
13147 The command may be followed by switches and arguments for the invoked
13148 tool.
13149
13150 @smallexample
13151   gnat bind -C main.ali
13152   gnat ls -a main
13153   gnat chop foo.txt
13154 @end smallexample
13155
13156 @noindent
13157 Switches may also be put in text files, one switch per line, and the text
13158 files may be specified with their path name preceded by '@@'.
13159
13160 @smallexample
13161    gnat bind @@args.txt main.ali
13162 @end smallexample
13163
13164 @noindent
13165 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13166 PP or PRETTY and XREF, the project file related switches
13167 (@option{^-P^/PROJECT_FILE^},
13168 @option{^-X^/EXTERNAL_REFERENCE^} and
13169 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13170 the switches of the invoking tool.
13171
13172 @noindent
13173 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13174 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13175 the immediate sources of the specified project file.
13176
13177 @noindent
13178 For each of these commands, there is optionally a corresponding  package
13179 in the main project.
13180
13181 @itemize @bullet
13182 @item
13183 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13184
13185 @item
13186 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13187
13188 @item
13189 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13190
13191 @item
13192 package @code{Eliminate} for command ELIM (invoking
13193 @code{^gnatelim^gnatelim^})
13194
13195 @item
13196 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13197
13198 @item
13199 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13200
13201 @item
13202 package @code{Pretty_Printer} for command PP or PRETTY
13203 (invoking @code{^gnatpp^gnatpp^})
13204
13205 @item
13206 package @code{Cross_Reference} for command XREF (invoking
13207 @code{^gnatxref^gnatxref^})
13208
13209 @end itemize
13210
13211 @noindent
13212 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13213 a simple variable with a string list value. It contains ^switches^switches^
13214 for the invocation of @code{^gnatls^gnatls^}.
13215
13216 @smallexample @c projectfile
13217 @group
13218 project Proj1 is
13219    package gnatls is
13220       for ^Switches^Switches^
13221           use ("^-a^-a^",
13222                "^-v^-v^");
13223    end gnatls;
13224 end Proj1;
13225 @end group
13226 @end smallexample
13227
13228 @noindent
13229 All other packages have two attribute @code{^Switches^Switches^} and
13230 @code{^Default_Switches^Default_Switches^}.
13231
13232 @noindent
13233 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13234 source file name, that has a string list value: the ^switches^switches^ to be
13235 used when the tool corresponding to the package is invoked for the specific
13236 source file.
13237
13238 @noindent
13239 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13240 indexed by  the programming language that has a string list value.
13241 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13242 ^switches^switches^ for the invocation of the tool corresponding
13243 to the package, except if a specific @code{^Switches^Switches^} attribute
13244 is specified for the source file.
13245
13246 @smallexample @c projectfile
13247 @group
13248 project Proj is
13249
13250    for Source_Dirs use ("./**");
13251
13252    package gnatls is
13253       for ^Switches^Switches^ use
13254           ("^-a^-a^",
13255            "^-v^-v^");
13256    end gnatls;
13257 @end group
13258 @group
13259
13260    package Compiler is
13261       for ^Default_Switches^Default_Switches^ ("Ada")
13262           use ("^-gnatv^-gnatv^",
13263                "^-gnatwa^-gnatwa^");
13264    end Binder;
13265 @end group
13266 @group
13267
13268    package Binder is
13269       for ^Default_Switches^Default_Switches^ ("Ada")
13270           use ("^-C^-C^",
13271                "^-e^-e^");
13272    end Binder;
13273 @end group
13274 @group
13275
13276    package Linker is
13277       for ^Default_Switches^Default_Switches^ ("Ada")
13278           use ("^-C^-C^");
13279       for ^Switches^Switches^ ("main.adb")
13280           use ("^-C^-C^",
13281                "^-v^-v^",
13282                "^-v^-v^");
13283    end Linker;
13284 @end group
13285 @group
13286
13287    package Finder is
13288       for ^Default_Switches^Default_Switches^ ("Ada")
13289            use ("^-a^-a^",
13290                 "^-f^-f^");
13291    end Finder;
13292 @end group
13293 @group
13294
13295    package Cross_Reference is
13296       for ^Default_Switches^Default_Switches^ ("Ada")
13297           use ("^-a^-a^",
13298                "^-f^-f^",
13299                "^-d^-d^",
13300                "^-u^-u^");
13301    end Cross_Reference;
13302 end Proj;
13303 @end group
13304 @end smallexample
13305
13306 @noindent
13307 With the above project file, commands such as
13308
13309 @smallexample
13310    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13311    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13312    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13313    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13314    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13315 @end smallexample
13316
13317 @noindent
13318 will set up the environment properly and invoke the tool with the switches
13319 found in the package corresponding to the tool:
13320 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13321 except @code{^Switches^Switches^ ("main.adb")}
13322 for @code{^gnatlink^gnatlink^}.
13323
13324 @ifclear vms
13325 @node Glide and Project Files
13326 @subsection Glide and Project Files
13327
13328 @noindent
13329 Glide will automatically recognize the @file{.gpr} extension for
13330 project files, and will
13331 convert them to its own internal format automatically. However, it
13332 doesn't provide a syntax-oriented editor for modifying these
13333 files.
13334 The project file will be loaded as text when you select the menu item
13335 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13336 You can edit this text and save the @file{gpr} file;
13337 when you next select this project file in Glide it
13338 will be automatically reloaded.
13339 @end ifclear
13340
13341 @c **********************
13342 @node An Extended Example
13343 @section An Extended Example
13344
13345 @noindent
13346 Suppose that we have two programs, @var{prog1} and @var{prog2},
13347 whose sources are in corresponding directories. We would like
13348 to build them with a single @command{gnatmake} command, and we want to place
13349 their object files into @file{build} subdirectories of the source directories.
13350 Furthermore, we want to have to have two separate subdirectories
13351 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13352 the object files compiled with different set of compilation flags.
13353
13354 In other words, we have the following structure:
13355
13356 @smallexample
13357 @group
13358    main
13359      |- prog1
13360      |    |- build
13361      |         | debug
13362      |         | release
13363      |- prog2
13364           |- build
13365                | debug
13366                | release
13367 @end group
13368 @end smallexample
13369
13370 @noindent
13371 Here are the project files that we must place in a directory @file{main}
13372 to maintain this structure:
13373
13374 @enumerate
13375
13376 @item We create a @code{Common} project with a package @code{Compiler} that
13377 specifies the compilation ^switches^switches^:
13378
13379 @smallexample
13380 File "common.gpr":
13381 @group
13382 @b{project} Common @b{is}
13383
13384    @b{for} Source_Dirs @b{use} (); -- No source files
13385 @end group
13386
13387 @group
13388    @b{type} Build_Type @b{is} ("release", "debug");
13389    Build : Build_Type := External ("BUILD", "debug");
13390 @end group
13391 @group
13392    @b{package} Compiler @b{is}
13393       @b{case} Build @b{is}
13394          @b{when} "release" =>
13395            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13396                    @b{use} ("^-O2^-O2^");
13397          @b{when} "debug"   =>
13398            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13399                    @b{use} ("^-g^-g^");
13400       @b{end case};
13401    @b{end} Compiler;
13402
13403 @b{end} Common;
13404 @end group
13405 @end smallexample
13406
13407 @item We create separate projects for the two programs:
13408
13409 @smallexample
13410 @group
13411 File "prog1.gpr":
13412
13413 @b{with} "common";
13414 @b{project} Prog1 @b{is}
13415
13416     @b{for} Source_Dirs @b{use} ("prog1");
13417     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13418
13419     @b{package} Compiler @b{renames} Common.Compiler;
13420
13421 @b{end} Prog1;
13422 @end group
13423 @end smallexample
13424
13425 @smallexample
13426 @group
13427 File "prog2.gpr":
13428
13429 @b{with} "common";
13430 @b{project} Prog2 @b{is}
13431
13432     @b{for} Source_Dirs @b{use} ("prog2");
13433     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13434
13435     @b{package} Compiler @b{renames} Common.Compiler;
13436
13437 @end group
13438 @b{end} Prog2;
13439 @end smallexample
13440
13441 @item We create a wrapping project @code{Main}:
13442
13443 @smallexample
13444 @group
13445 File "main.gpr":
13446
13447 @b{with} "common";
13448 @b{with} "prog1";
13449 @b{with} "prog2";
13450 @b{project} Main @b{is}
13451
13452    @b{package} Compiler @b{renames} Common.Compiler;
13453
13454 @b{end} Main;
13455 @end group
13456 @end smallexample
13457
13458 @item Finally we need to create a dummy procedure that @code{with}s (either
13459 explicitly or implicitly) all the sources of our two programs.
13460
13461 @end enumerate
13462
13463 @noindent
13464 Now we can build the programs using the command
13465
13466 @smallexample
13467    gnatmake ^-P^/PROJECT_FILE=^main dummy
13468 @end smallexample
13469
13470 @noindent
13471 for the Debug mode, or
13472
13473 @ifclear vms
13474 @smallexample
13475    gnatmake -Pmain -XBUILD=release
13476 @end smallexample
13477 @end ifclear
13478
13479 @ifset vms
13480 @smallexample
13481    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13482 @end smallexample
13483 @end ifset
13484
13485 @noindent
13486 for the Release mode.
13487
13488 @c ********************************
13489 @c * Project File Complete Syntax *
13490 @c ********************************
13491
13492 @node Project File Complete Syntax
13493 @section Project File Complete Syntax
13494
13495 @smallexample
13496 project ::=
13497   context_clause project_declaration
13498
13499 context_clause ::=
13500   @{with_clause@}
13501
13502 with_clause ::=
13503   @b{with} path_name @{ , path_name @} ;
13504
13505 path_name ::=
13506    string_literal
13507
13508 project_declaration ::=
13509   simple_project_declaration | project_extension
13510
13511 simple_project_declaration ::=
13512   @b{project} <project_>simple_name @b{is}
13513     @{declarative_item@}
13514   @b{end} <project_>simple_name;
13515
13516 project_extension ::=
13517   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13518     @{declarative_item@}
13519   @b{end} <project_>simple_name;
13520
13521 declarative_item ::=
13522   package_declaration |
13523   typed_string_declaration |
13524   other_declarative_item
13525
13526 package_declaration ::=
13527   package_specification | package_renaming
13528
13529 package_specification ::=
13530   @b{package} package_identifier @b{is}
13531     @{simple_declarative_item@}
13532   @b{end} package_identifier ;
13533
13534 package_identifier ::=
13535   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13536   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13537   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13538
13539 package_renaming ::==
13540   @b{package} package_identifier @b{renames}
13541        <project_>simple_name.package_identifier ;
13542
13543 typed_string_declaration ::=
13544   @b{type} <typed_string_>_simple_name @b{is}
13545    ( string_literal @{, string_literal@} );
13546
13547 other_declarative_item ::=
13548   attribute_declaration |
13549   typed_variable_declaration |
13550   variable_declaration |
13551   case_construction
13552
13553 attribute_declaration ::=
13554   full_associative_array_declaration |
13555   @b{for} attribute_designator @b{use} expression ;
13556
13557 full_associative_array_declaration ::=
13558   @b{for} <associative_array_attribute_>simple_name @b{use}
13559   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13560
13561 attribute_designator ::=
13562   <simple_attribute_>simple_name |
13563   <associative_array_attribute_>simple_name ( string_literal )
13564
13565 typed_variable_declaration ::=
13566   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13567
13568 variable_declaration ::=
13569   <variable_>simple_name := expression;
13570
13571 expression ::=
13572   term @{& term@}
13573
13574 term ::=
13575   literal_string |
13576   string_list |
13577   <variable_>name |
13578   external_value |
13579   attribute_reference
13580
13581 string_literal ::=
13582   (same as Ada)
13583
13584 string_list ::=
13585   ( <string_>expression @{ , <string_>expression @} )
13586
13587 external_value ::=
13588   @b{external} ( string_literal [, string_literal] )
13589
13590 attribute_reference ::=
13591   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13592
13593 attribute_prefix ::=
13594   @b{project} |
13595   <project_>simple_name | package_identifier |
13596   <project_>simple_name . package_identifier
13597
13598 case_construction ::=
13599   @b{case} <typed_variable_>name @b{is}
13600     @{case_item@}
13601   @b{end case} ;
13602
13603 case_item ::=
13604   @b{when} discrete_choice_list =>
13605       @{case_construction | attribute_declaration@}
13606
13607 discrete_choice_list ::=
13608   string_literal @{| string_literal@} |
13609   @b{others}
13610
13611 name ::=
13612   simple_name @{. simple_name@}
13613
13614 simple_name ::=
13615   identifier (same as Ada)
13616
13617 @end smallexample
13618
13619
13620 @node The Cross-Referencing Tools gnatxref and gnatfind
13621 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13622 @findex gnatxref
13623 @findex gnatfind
13624
13625 @noindent
13626 The compiler generates cross-referencing information (unless
13627 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13628 This information indicates where in the source each entity is declared and
13629 referenced. Note that entities in package Standard are not included, but
13630 entities in all other predefined units are included in the output.
13631
13632 Before using any of these two tools, you need to compile successfully your
13633 application, so that GNAT gets a chance to generate the cross-referencing
13634 information.
13635
13636 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13637 information to provide the user with the capability to easily locate the
13638 declaration and references to an entity. These tools are quite similar,
13639 the difference being that @code{gnatfind} is intended for locating
13640 definitions and/or references to a specified entity or entities, whereas
13641 @code{gnatxref} is oriented to generating a full report of all
13642 cross-references.
13643
13644 To use these tools, you must not compile your application using the
13645 @option{-gnatx} switch on the @file{gnatmake} command line
13646 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13647 information will not be generated.
13648
13649 @menu
13650 * gnatxref Switches::
13651 * gnatfind Switches::
13652 * Project Files for gnatxref and gnatfind::
13653 * Regular Expressions in gnatfind and gnatxref::
13654 * Examples of gnatxref Usage::
13655 * Examples of gnatfind Usage::
13656 @end menu
13657
13658 @node gnatxref Switches
13659 @section @code{gnatxref} Switches
13660
13661 @noindent
13662 The command invocation for @code{gnatxref} is:
13663 @smallexample
13664 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13665 @end smallexample
13666
13667 @noindent
13668 where
13669
13670 @table @code
13671 @item sourcefile1, sourcefile2
13672 identifies the source files for which a report is to be generated. The
13673 ``with''ed units will be processed too. You must provide at least one file.
13674
13675 These file names are considered to be regular expressions, so for instance
13676 specifying @file{source*.adb} is the same as giving every file in the current
13677 directory whose name starts with @file{source} and whose extension is
13678 @file{adb}.
13679
13680 @end table
13681
13682 @noindent
13683 The switches can be :
13684 @table @option
13685 @c !sort!
13686 @item ^-a^/ALL_FILES^
13687 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13688 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13689 the read-only files found in the library search path. Otherwise, these files
13690 will be ignored. This option can be used to protect Gnat sources or your own
13691 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13692 much faster, and their output much smaller. Read-only here refers to access
13693 or permissions status in the file system for the current user.
13694
13695 @item -aIDIR
13696 @cindex @option{-aIDIR} (@command{gnatxref})
13697 When looking for source files also look in directory DIR. The order in which
13698 source file search is undertaken is the same as for @file{gnatmake}.
13699
13700 @item -aODIR
13701 @cindex @option{-aODIR} (@command{gnatxref})
13702 When searching for library and object files, look in directory
13703 DIR. The order in which library files are searched is the same as for
13704 @file{gnatmake}.
13705
13706 @item -nostdinc
13707 @cindex @option{-nostdinc} (@command{gnatxref})
13708 Do not look for sources in the system default directory.
13709
13710 @item -nostdlib
13711 @cindex @option{-nostdlib} (@command{gnatxref})
13712 Do not look for library files in the system default directory.
13713
13714 @item --RTS=@var{rts-path}
13715 @cindex @option{--RTS} (@command{gnatxref})
13716 Specifies the default location of the runtime library. Same meaning as the
13717 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13718
13719 @item ^-d^/DERIVED_TYPES^
13720 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13721 If this switch is set @code{gnatxref} will output the parent type
13722 reference for each matching derived types.
13723
13724 @item ^-f^/FULL_PATHNAME^
13725 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13726 If this switch is set, the output file names will be preceded by their
13727 directory (if the file was found in the search path). If this switch is
13728 not set, the directory will not be printed.
13729
13730 @item ^-g^/IGNORE_LOCALS^
13731 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13732 If this switch is set, information is output only for library-level
13733 entities, ignoring local entities. The use of this switch may accelerate
13734 @code{gnatfind} and @code{gnatxref}.
13735
13736 @item -IDIR
13737 @cindex @option{-IDIR} (@command{gnatxref})
13738 Equivalent to @samp{-aODIR -aIDIR}.
13739
13740 @item -pFILE
13741 @cindex @option{-pFILE} (@command{gnatxref})
13742 Specify a project file to use @xref{Project Files}. These project files are
13743 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13744 project files, you should use gnatxref through the GNAT driver
13745 (@command{gnat xref -Pproject}).
13746
13747 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13748 project file in the current directory.
13749
13750 If a project file is either specified or found by the tools, then the content
13751 of the source directory and object directory lines are added as if they
13752 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13753 and @samp{^-aO^OBJECT_SEARCH^}.
13754 @item ^-u^/UNUSED^
13755 Output only unused symbols. This may be really useful if you give your
13756 main compilation unit on the command line, as @code{gnatxref} will then
13757 display every unused entity and 'with'ed package.
13758
13759 @ifclear vms
13760 @item -v
13761 Instead of producing the default output, @code{gnatxref} will generate a
13762 @file{tags} file that can be used by vi. For examples how to use this
13763 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13764 to the standard output, thus you will have to redirect it to a file.
13765 @end ifclear
13766
13767 @end table
13768
13769 @noindent
13770 All these switches may be in any order on the command line, and may even
13771 appear after the file names. They need not be separated by spaces, thus
13772 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13773 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13774
13775 @node gnatfind Switches
13776 @section @code{gnatfind} Switches
13777
13778 @noindent
13779 The command line for @code{gnatfind} is:
13780
13781 @smallexample
13782 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13783       [file1 file2 ...]
13784 @end smallexample
13785
13786 @noindent
13787 where
13788
13789 @table @code
13790 @item pattern
13791 An entity will be output only if it matches the regular expression found
13792 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13793
13794 Omitting the pattern is equivalent to specifying @samp{*}, which
13795 will match any entity. Note that if you do not provide a pattern, you
13796 have to provide both a sourcefile and a line.
13797
13798 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13799 for matching purposes. At the current time there is no support for
13800 8-bit codes other than Latin-1, or for wide characters in identifiers.
13801
13802 @item sourcefile
13803 @code{gnatfind} will look for references, bodies or declarations
13804 of symbols referenced in @file{sourcefile}, at line @samp{line}
13805 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13806 for syntax examples.
13807
13808 @item line
13809 is a decimal integer identifying the line number containing
13810 the reference to the entity (or entities) to be located.
13811
13812 @item column
13813 is a decimal integer identifying the exact location on the
13814 line of the first character of the identifier for the
13815 entity reference. Columns are numbered from 1.
13816
13817 @item file1 file2 ...
13818 The search will be restricted to these source files. If none are given, then
13819 the search will be done for every library file in the search path.
13820 These file must appear only after the pattern or sourcefile.
13821
13822 These file names are considered to be regular expressions, so for instance
13823 specifying 'source*.adb' is the same as giving every file in the current
13824 directory whose name starts with 'source' and whose extension is 'adb'.
13825
13826 The location of the spec of the entity will always be displayed, even if it
13827 isn't in one of file1, file2,... The occurrences of the entity in the
13828 separate units of the ones given on the command line will also be displayed.
13829
13830 Note that if you specify at least one file in this part, @code{gnatfind} may
13831 sometimes not be able to find the body of the subprograms...
13832
13833 @end table
13834
13835 @noindent
13836 At least one of 'sourcefile' or 'pattern' has to be present on
13837 the command line.
13838
13839 The following switches are available:
13840 @table @option
13841 @c !sort!
13842
13843 @item ^-a^/ALL_FILES^
13844 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13845 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13846 the read-only files found in the library search path. Otherwise, these files
13847 will be ignored. This option can be used to protect Gnat sources or your own
13848 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13849 much faster, and their output much smaller. Read-only here refers to access
13850 or permission status in the file system for the current user.
13851
13852 @item -aIDIR
13853 @cindex @option{-aIDIR} (@command{gnatfind})
13854 When looking for source files also look in directory DIR. The order in which
13855 source file search is undertaken is the same as for @file{gnatmake}.
13856
13857 @item -aODIR
13858 @cindex @option{-aODIR} (@command{gnatfind})
13859 When searching for library and object files, look in directory
13860 DIR. The order in which library files are searched is the same as for
13861 @file{gnatmake}.
13862
13863 @item -nostdinc
13864 @cindex @option{-nostdinc} (@command{gnatfind})
13865 Do not look for sources in the system default directory.
13866
13867 @item -nostdlib
13868 @cindex @option{-nostdlib} (@command{gnatfind})
13869 Do not look for library files in the system default directory.
13870
13871 @item --RTS=@var{rts-path}
13872 @cindex @option{--RTS} (@command{gnatfind})
13873 Specifies the default location of the runtime library. Same meaning as the
13874 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13875
13876 @item ^-d^/DERIVED_TYPE_INFORMATION^
13877 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13878 If this switch is set, then @code{gnatfind} will output the parent type
13879 reference for each matching derived types.
13880
13881 @item ^-e^/EXPRESSIONS^
13882 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13883 By default, @code{gnatfind} accept the simple regular expression set for
13884 @samp{pattern}. If this switch is set, then the pattern will be
13885 considered as full Unix-style regular expression.
13886
13887 @item ^-f^/FULL_PATHNAME^
13888 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13889 If this switch is set, the output file names will be preceded by their
13890 directory (if the file was found in the search path). If this switch is
13891 not set, the directory will not be printed.
13892
13893 @item ^-g^/IGNORE_LOCALS^
13894 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13895 If this switch is set, information is output only for library-level
13896 entities, ignoring local entities. The use of this switch may accelerate
13897 @code{gnatfind} and @code{gnatxref}.
13898
13899 @item -IDIR
13900 @cindex @option{-IDIR} (@command{gnatfind})
13901 Equivalent to @samp{-aODIR -aIDIR}.
13902
13903 @item -pFILE
13904 @cindex @option{-pFILE} (@command{gnatfind})
13905 Specify a project file (@pxref{Project Files}) to use.
13906 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13907 project file in the current directory.
13908
13909 If a project file is either specified or found by the tools, then the content
13910 of the source directory and object directory lines are added as if they
13911 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13912 @samp{^-aO^/OBJECT_SEARCH^}.
13913
13914 @item ^-r^/REFERENCES^
13915 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13916 By default, @code{gnatfind} will output only the information about the
13917 declaration, body or type completion of the entities. If this switch is
13918 set, the @code{gnatfind} will locate every reference to the entities in
13919 the files specified on the command line (or in every file in the search
13920 path if no file is given on the command line).
13921
13922 @item ^-s^/PRINT_LINES^
13923 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13924 If this switch is set, then @code{gnatfind} will output the content
13925 of the Ada source file lines were the entity was found.
13926
13927 @item ^-t^/TYPE_HIERARCHY^
13928 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13929 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13930 the specified type. It act like -d option but recursively from parent
13931 type to parent type. When this switch is set it is not possible to
13932 specify more than one file.
13933
13934 @end table
13935
13936 @noindent
13937 All these switches may be in any order on the command line, and may even
13938 appear after the file names. They need not be separated by spaces, thus
13939 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13940 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13941
13942 As stated previously, gnatfind will search in every directory in the
13943 search path. You can force it to look only in the current directory if
13944 you specify @code{*} at the end of the command line.
13945
13946 @node Project Files for gnatxref and gnatfind
13947 @section Project Files for @command{gnatxref} and @command{gnatfind}
13948
13949 @noindent
13950 Project files allow a programmer to specify how to compile its
13951 application, where to find sources, etc.  These files are used
13952 @ifclear vms
13953 primarily by the Glide Ada mode, but they can also be used
13954 @end ifclear
13955 by the two tools
13956 @code{gnatxref} and @code{gnatfind}.
13957
13958 A project file name must end with @file{.gpr}. If a single one is
13959 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13960 extract the information from it. If multiple project files are found, none of
13961 them is read, and you have to use the @samp{-p} switch to specify the one
13962 you want to use.
13963
13964 The following lines can be included, even though most of them have default
13965 values which can be used in most cases.
13966 The lines can be entered in any order in the file.
13967 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13968 each line. If you have multiple instances, only the last one is taken into
13969 account.
13970
13971 @table @code
13972 @item src_dir=DIR
13973 [default: @code{"^./^[]^"}]
13974 specifies a directory where to look for source files. Multiple @code{src_dir}
13975 lines can be specified and they will be searched in the order they
13976 are specified.
13977
13978 @item obj_dir=DIR
13979 [default: @code{"^./^[]^"}]
13980 specifies a directory where to look for object and library files. Multiple
13981 @code{obj_dir} lines can be specified, and they will be searched in the order
13982 they are specified
13983
13984 @item comp_opt=SWITCHES
13985 [default: @code{""}]
13986 creates a variable which can be referred to subsequently by using
13987 the @code{$@{comp_opt@}} notation. This is intended to store the default
13988 switches given to @command{gnatmake} and @command{gcc}.
13989
13990 @item bind_opt=SWITCHES
13991 [default: @code{""}]
13992 creates a variable which can be referred to subsequently by using
13993 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13994 switches given to @command{gnatbind}.
13995
13996 @item link_opt=SWITCHES
13997 [default: @code{""}]
13998 creates a variable which can be referred to subsequently by using
13999 the @samp{$@{link_opt@}} notation. This is intended to store the default
14000 switches given to @command{gnatlink}.
14001
14002 @item main=EXECUTABLE
14003 [default: @code{""}]
14004 specifies the name of the executable for the application. This variable can
14005 be referred to in the following lines by using the @samp{$@{main@}} notation.
14006
14007 @ifset vms
14008 @item comp_cmd=COMMAND
14009 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14010 @end ifset
14011 @ifclear vms
14012 @item comp_cmd=COMMAND
14013 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14014 @end ifclear
14015 specifies the command used to compile a single file in the application.
14016
14017 @ifset vms
14018 @item make_cmd=COMMAND
14019 [default: @code{"GNAT MAKE $@{main@}
14020 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14021 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14022 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14023 @end ifset
14024 @ifclear vms
14025 @item make_cmd=COMMAND
14026 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14027  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14028  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14029 @end ifclear
14030 specifies the command used to recompile the whole application.
14031
14032 @item run_cmd=COMMAND
14033 [default: @code{"$@{main@}"}]
14034 specifies the command used to run the application.
14035
14036 @item debug_cmd=COMMAND
14037 [default: @code{"gdb $@{main@}"}]
14038 specifies the command used to debug the application
14039
14040 @end table
14041
14042 @noindent
14043 @command{gnatxref} and @command{gnatfind} only take into account the
14044 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14045
14046 @node Regular Expressions in gnatfind and gnatxref
14047 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14048
14049 @noindent
14050 As specified in the section about @command{gnatfind}, the pattern can be a
14051 regular expression. Actually, there are to set of regular expressions
14052 which are recognized by the program :
14053
14054 @table @code
14055 @item globbing patterns
14056 These are the most usual regular expression. They are the same that you
14057 generally used in a Unix shell command line, or in a DOS session.
14058
14059 Here is a more formal grammar :
14060 @smallexample
14061 @group
14062 @iftex
14063 @leftskip=.5cm
14064 @end iftex
14065 regexp ::= term
14066 term   ::= elmt            -- matches elmt
14067 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14068 term   ::= *               -- any string of 0 or more characters
14069 term   ::= ?               -- matches any character
14070 term   ::= [char @{char@}] -- matches any character listed
14071 term   ::= [char - char]   -- matches any character in range
14072 @end group
14073 @end smallexample
14074
14075 @item full regular expression
14076 The second set of regular expressions is much more powerful. This is the
14077 type of regular expressions recognized by utilities such a @file{grep}.
14078
14079 The following is the form of a regular expression, expressed in Ada
14080 reference manual style BNF is as follows
14081
14082 @smallexample
14083 @iftex
14084 @leftskip=.5cm
14085 @end iftex
14086 @group
14087 regexp ::= term @{| term@} -- alternation (term or term ...)
14088
14089 term ::= item @{item@}     -- concatenation (item then item)
14090
14091 item ::= elmt              -- match elmt
14092 item ::= elmt *            -- zero or more elmt's
14093 item ::= elmt +            -- one or more elmt's
14094 item ::= elmt ?            -- matches elmt or nothing
14095 @end group
14096 @group
14097 elmt ::= nschar            -- matches given character
14098 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14099 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14100 elmt ::= [char - char]     -- matches chars in given range
14101 elmt ::= \ char            -- matches given character
14102 elmt ::= .                 -- matches any single character
14103 elmt ::= ( regexp )        -- parens used for grouping
14104
14105 char ::= any character, including special characters
14106 nschar ::= any character except ()[].*+?^^^
14107 @end group
14108 @end smallexample
14109
14110 Following are a few examples :
14111
14112 @table @samp
14113 @item abcde|fghi
14114 will match any of the two strings 'abcde' and 'fghi'.
14115
14116 @item abc*d
14117 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14118
14119 @item [a-z]+
14120 will match any string which has only lowercase characters in it (and at
14121 least one character
14122
14123 @end table
14124 @end table
14125
14126 @node Examples of gnatxref Usage
14127 @section Examples of @code{gnatxref} Usage
14128
14129 @subsection General Usage
14130
14131 @noindent
14132 For the following examples, we will consider the following units :
14133
14134 @smallexample @c ada
14135 @group
14136 @cartouche
14137 main.ads:
14138 1: with Bar;
14139 2: package Main is
14140 3:     procedure Foo (B : in Integer);
14141 4:     C : Integer;
14142 5: private
14143 6:     D : Integer;
14144 7: end Main;
14145
14146 main.adb:
14147 1: package body Main is
14148 2:     procedure Foo (B : in Integer) is
14149 3:     begin
14150 4:        C := B;
14151 5:        D := B;
14152 6:        Bar.Print (B);
14153 7:        Bar.Print (C);
14154 8:     end Foo;
14155 9: end Main;
14156
14157 bar.ads:
14158 1: package Bar is
14159 2:     procedure Print (B : Integer);
14160 3: end bar;
14161 @end cartouche
14162 @end group
14163 @end smallexample
14164
14165 @table @code
14166
14167 @noindent
14168 The first thing to do is to recompile your application (for instance, in
14169 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14170 the cross-referencing information.
14171 You can then issue any of the following commands:
14172
14173 @item gnatxref main.adb
14174 @code{gnatxref} generates cross-reference information for main.adb
14175 and every unit 'with'ed by main.adb.
14176
14177 The output would be:
14178 @smallexample
14179 @iftex
14180 @leftskip=0cm
14181 @end iftex
14182 B                                                      Type: Integer
14183   Decl: bar.ads           2:22
14184 B                                                      Type: Integer
14185   Decl: main.ads          3:20
14186   Body: main.adb          2:20
14187   Ref:  main.adb          4:13     5:13     6:19
14188 Bar                                                    Type: Unit
14189   Decl: bar.ads           1:9
14190   Ref:  main.adb          6:8      7:8
14191        main.ads           1:6
14192 C                                                      Type: Integer
14193   Decl: main.ads          4:5
14194   Modi: main.adb          4:8
14195   Ref:  main.adb          7:19
14196 D                                                      Type: Integer
14197   Decl: main.ads          6:5
14198   Modi: main.adb          5:8
14199 Foo                                                    Type: Unit
14200   Decl: main.ads          3:15
14201   Body: main.adb          2:15
14202 Main                                                    Type: Unit
14203   Decl: main.ads          2:9
14204   Body: main.adb          1:14
14205 Print                                                   Type: Unit
14206   Decl: bar.ads           2:15
14207   Ref:  main.adb          6:12     7:12
14208 @end smallexample
14209
14210 @noindent
14211 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14212 its body is in main.adb, line 1, column 14 and is not referenced any where.
14213
14214 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14215 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14216
14217 @item gnatxref package1.adb package2.ads
14218 @code{gnatxref} will generates cross-reference information for
14219 package1.adb, package2.ads and any other package 'with'ed by any
14220 of these.
14221
14222 @end table
14223
14224 @ifclear vms
14225 @subsection Using gnatxref with vi
14226
14227 @code{gnatxref} can generate a tags file output, which can be used
14228 directly from @file{vi}. Note that the standard version of @file{vi}
14229 will not work properly with overloaded symbols. Consider using another
14230 free implementation of @file{vi}, such as @file{vim}.
14231
14232 @smallexample
14233 $ gnatxref -v gnatfind.adb > tags
14234 @end smallexample
14235
14236 @noindent
14237 will generate the tags file for @code{gnatfind} itself (if the sources
14238 are in the search path!).
14239
14240 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14241 (replacing @i{entity} by whatever you are looking for), and vi will
14242 display a new file with the corresponding declaration of entity.
14243 @end ifclear
14244
14245 @node Examples of gnatfind Usage
14246 @section Examples of @code{gnatfind} Usage
14247
14248 @table @code
14249
14250 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14251 Find declarations for all entities xyz referenced at least once in
14252 main.adb. The references are search in every library file in the search
14253 path.
14254
14255 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14256 switch is set)
14257
14258 The output will look like:
14259 @smallexample
14260 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14261 ^directory/^[directory]^main.adb:24:10: xyz <= body
14262 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14263 @end smallexample
14264
14265 @noindent
14266 that is to say, one of the entities xyz found in main.adb is declared at
14267 line 12 of main.ads (and its body is in main.adb), and another one is
14268 declared at line 45 of foo.ads
14269
14270 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14271 This is the same command as the previous one, instead @code{gnatfind} will
14272 display the content of the Ada source file lines.
14273
14274 The output will look like:
14275
14276 @smallexample
14277 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14278    procedure xyz;
14279 ^directory/^[directory]^main.adb:24:10: xyz <= body
14280    procedure xyz is
14281 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14282    xyz : Integer;
14283 @end smallexample
14284
14285 @noindent
14286 This can make it easier to find exactly the location your are looking
14287 for.
14288
14289 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14290 Find references to all entities containing an x that are
14291 referenced on line 123 of main.ads.
14292 The references will be searched only in main.ads and foo.adb.
14293
14294 @item gnatfind main.ads:123
14295 Find declarations and bodies for all entities that are referenced on
14296 line 123 of main.ads.
14297
14298 This is the same as @code{gnatfind "*":main.adb:123}.
14299
14300 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14301 Find the declaration for the entity referenced at column 45 in
14302 line 123 of file main.adb in directory mydir. Note that it
14303 is usual to omit the identifier name when the column is given,
14304 since the column position identifies a unique reference.
14305
14306 The column has to be the beginning of the identifier, and should not
14307 point to any character in the middle of the identifier.
14308
14309 @end table
14310
14311
14312 @c *********************************
14313 @node The GNAT Pretty-Printer gnatpp
14314 @chapter The GNAT Pretty-Printer @command{gnatpp}
14315 @findex gnatpp
14316 @cindex Pretty-Printer
14317
14318 @noindent
14319 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14320 for source reformatting / pretty-printing.
14321 It takes an Ada source file as input and generates a reformatted
14322 version as output.
14323 You can specify various style directives via switches; e.g.,
14324 identifier case conventions, rules of indentation, and comment layout.
14325
14326 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14327 tree for the input source and thus requires the input to be syntactically and
14328 semantically legal.
14329 If this condition is not met, @command{gnatpp} will terminate with an
14330 error message; no output file will be generated.
14331
14332 If the compilation unit
14333 contained in the input source depends semantically upon units located
14334 outside the current directory, you have to provide the source search path
14335 when invoking @command{gnatpp}; see the description of the @command{gnatpp}
14336 switches below.
14337
14338 The @command{gnatpp} command has the form
14339
14340 @smallexample
14341 $ gnatpp [@var{switches}] @var{filename}
14342 @end smallexample
14343
14344 @noindent
14345 where
14346 @itemize @bullet
14347 @item
14348 @var{switches} is an optional sequence of switches defining such properties as
14349 the formatting rules, the source search path, and the destination for the
14350 output source file
14351
14352 @item
14353 @var{filename} is the name (including the extension) of the source file to
14354 reformat; ``wildcards'' or several file names on the same gnatpp command are
14355 allowed.  The file name may contain path information; it does not have to follow
14356 the GNAT file naming rules
14357 @end itemize
14358
14359
14360 @menu
14361 * Switches for gnatpp::
14362 * Formatting Rules::
14363 @end menu
14364
14365 @node Switches for gnatpp
14366 @section Switches for @command{gnatpp}
14367
14368 @noindent
14369 The following subsections describe the various switches accepted by
14370 @command{gnatpp}, organized by category.
14371
14372 @ifclear vms
14373 You specify a switch by supplying a name and generally also a value.
14374 In many cases the values for a switch with a given name are incompatible with
14375 each other
14376 (for example the switch that controls the casing of a reserved word may have
14377 exactly one value: upper case, lower case, or
14378 mixed case) and thus exactly one such switch can be in effect for an
14379 invocation of @command{gnatpp}.
14380 If more than one is supplied, the last one is used.
14381 However, some values for the same switch are mutually compatible.
14382 You may supply several such switches to @command{gnatpp}, but then
14383 each must be specified in full, with both the name and the value.
14384 Abbreviated forms (the name appearing once, followed by each value) are
14385 not permitted.
14386 For example, to set
14387 the alignment of the assignment delimiter both in declarations and in
14388 assignment statements, you must write @option{-A2A3}
14389 (or @option{-A2 -A3}), but not @option{-A23}.
14390 @end ifclear
14391
14392 @ifset vms
14393 In many cases the set of options for a given qualifier are incompatible with
14394 each other (for example the qualifier that controls the casing of a reserved
14395 word may have exactly one option, which specifies either upper case, lower
14396 case, or mixed case), and thus exactly one such option can be in effect for
14397 an invocation of @command{gnatpp}.
14398 If more than one is supplied, the last one is used.
14399 However, some qualifiers have options that are mutually compatible,
14400 and then you may then supply several such options when invoking
14401 @command{gnatpp}.
14402 @end ifset
14403
14404 In most cases, it is obvious whether or not the
14405 ^values for a switch with a given name^options for a given qualifier^
14406 are compatible with each other.
14407 When the semantics might not be evident, the summaries below explicitly
14408 indicate the effect.
14409
14410 @menu
14411 * Alignment Control::
14412 * Casing Control::
14413 * Construct Layout Control::
14414 * General Text Layout Control::
14415 * Other Formatting Options::
14416 * Setting the Source Search Path::
14417 * Output File Control::
14418 * Other gnatpp Switches::
14419 @end menu
14420
14421
14422 @node Alignment Control
14423 @subsection Alignment Control
14424 @cindex Alignment control in @command{gnatpp}
14425
14426 @noindent
14427 Programs can be easier to read if certain constructs are vertically aligned.
14428 By default all alignments are set ON.
14429 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14430 OFF, and then use one or more of the other
14431 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14432 to activate alignment for specific constructs.
14433
14434 @table @option
14435 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14436
14437 @ifset vms
14438 @item /ALIGN=ON
14439 Set all alignments to ON
14440 @end ifset
14441
14442 @item ^-A0^/ALIGN=OFF^
14443 Set all alignments to OFF
14444
14445 @item ^-A1^/ALIGN=COLONS^
14446 Align @code{:} in declarations
14447
14448 @item ^-A2^/ALIGN=DECLARATIONS^
14449 Align @code{:=} in initializations in declarations
14450
14451 @item ^-A3^/ALIGN=STATEMENTS^
14452 Align @code{:=} in assignment statements
14453
14454 @item ^-A4^/ALIGN=ARROWS^
14455 Align @code{=>} in associations
14456 @end table
14457
14458 @noindent
14459 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14460 is allowed.
14461
14462
14463 @node Casing Control
14464 @subsection Casing Control
14465 @cindex Casing control in @command{gnatpp}
14466
14467 @noindent
14468 @command{gnatpp} allows you to specify the casing for reserved words,
14469 pragma names, attribute designators and identifiers.
14470 For identifiers you may define a
14471 general rule for name casing but also override this rule
14472 via a set of dictionary files.
14473
14474 Three types of casing are supported: lower case, upper case, and mixed case.
14475 Lower and upper case are self-explanatory (but since some letters in
14476 Latin1 and other GNAT-supported character sets
14477 exist only in lower-case form, an upper case conversion will have no
14478 effect on them.)
14479 ``Mixed case'' means that the first letter, and also each letter immediately
14480 following an underscore, are converted to their uppercase forms;
14481 all the other letters are converted to their lowercase forms.
14482
14483 @table @option
14484 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14485 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14486 Attribute designators are lower case
14487
14488 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14489 Attribute designators are upper case
14490
14491 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14492 Attribute designators are mixed case (this is the default)
14493
14494 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14495 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14496 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14497 lower case (this is the default)
14498
14499 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14500 Keywords are upper case
14501
14502 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14503 @item ^-nD^/NAME_CASING=AS_DECLARED^
14504 Name casing for defining occurrences are as they appear in the source file
14505 (this is the default)
14506
14507 @item ^-nU^/NAME_CASING=UPPER_CASE^
14508 Names are in upper case
14509
14510 @item ^-nL^/NAME_CASING=LOWER_CASE^
14511 Names are in lower case
14512
14513 @item ^-nM^/NAME_CASING=MIXED_CASE^
14514 Names are in mixed case
14515
14516 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14517 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14518 Pragma names are lower case
14519
14520 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14521 Pragma names are upper case
14522
14523 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14524 Pragma names are mixed case (this is the default)
14525
14526 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14527 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14528 Use @var{file} as a @emph{dictionary file} that defines
14529 the casing for a set of specified names,
14530 thereby overriding the effect on these names by
14531 any explicit or implicit
14532 ^-n^/NAME_CASING^ switch.
14533 To supply more than one dictionary file,
14534 use ^several @option{-D} switches^a list of files as options^.
14535
14536 @noindent
14537 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14538 to define the casing for the Ada predefined names and
14539 the names declared in the GNAT libraries.
14540
14541 @item ^-D-^/SPECIFIC_CASING^
14542 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14543 Do not use the default dictionary file;
14544 instead, use the casing
14545 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14546 dictionary file(s)
14547 @end table
14548
14549 @noindent
14550 The structure of a dictionary file, and details on the conventions
14551 used in the default dictionary file, are defined in @ref{Name Casing}.
14552
14553 The @option{^-D-^/SPECIFIC_CASING^} and
14554 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14555 compatible.
14556
14557
14558 @node Construct Layout Control
14559 @subsection Construct Layout Control
14560 @cindex Layout control in @command{gnatpp}
14561
14562 @noindent
14563 This group of @command{gnatpp} switches controls the layout of comments and
14564 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14565 on their effect.
14566
14567 @table @option
14568 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14569 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14570 GNAT-style comment line indentation (this is the default).
14571
14572 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14573 Reference-manual comment line indentation.
14574
14575 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14576 GNAT-style comment beginning
14577
14578 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14579 Reformat comment blocks
14580
14581 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14582 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14583 GNAT-style layout (this is the default)
14584
14585 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14586 Compact layout
14587
14588 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14589 Uncompact layout
14590
14591 @item ^-notab^/NOTABS^
14592 All the VT characters are removed from the comment text. All the HT characters are
14593 expanded with the sequences of space characters to get to the next tab stops.
14594
14595 @end table
14596
14597 @ifclear vms
14598 @noindent
14599 The @option{-c1} and @option{-c2} switches are incompatible.
14600 The @option{-c3} and @option{-c4} switches are compatible with each other and
14601 also with @option{-c1} and @option{-c2}.
14602
14603 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14604 @end ifclear
14605
14606 @ifset vms
14607 @noindent
14608 For the @option{/COMMENTS_LAYOUT} qualifier:
14609 @itemize @bullet
14610 @item
14611 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14612 @item
14613 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14614 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14615 @end itemize
14616
14617 @noindent
14618 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14619 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14620 @end ifset
14621
14622 @node General Text Layout Control
14623 @subsection General Text Layout Control
14624
14625 @noindent
14626 These switches allow control over line length and indentation.
14627
14628 @table @option
14629 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14630 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14631 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14632
14633 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14634 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14635 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14636
14637 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14638 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14639 Indentation level for continuation lines (relative to the line being
14640 continued), @i{nnn} from 1 .. 9.
14641 The default
14642 value is one less then the (normal) indentation level, unless the
14643 indentation is set to 1 (in which case the default value for continuation
14644 line indentation is also 1)
14645 @end table
14646
14647
14648 @node Other Formatting Options
14649 @subsection Other Formatting Options
14650
14651 @noindent
14652 These switches control the inclusion of missing end/exit labels, and
14653 the indentation level in @b{case} statements.
14654
14655 @table @option
14656 @item ^-e^/NO_MISSED_LABELS^
14657 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14658 Do not insert missing end/exit labels. An end label is the name of
14659 a construct that may optionally be repeated at the end of the
14660 construct's declaration;
14661 e.g., the names of packages, subprograms, and tasks.
14662 An exit label is the name of a loop that may appear as target
14663 of an exit statement within the loop.
14664 By default, @command{gnatpp} inserts these end/exit labels when
14665 they are absent from the original source. This option suppresses such
14666 insertion, so that the formatted source reflects the original.
14667
14668 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14669 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14670 Insert a Form Feed character after a pragma Page.
14671
14672 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14673 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14674 Do not use an additional indentation level for @b{case} alternatives
14675 and variants if there are @i{nnn} or more (the default
14676 value is 10).
14677 If @i{nnn} is 0, an additional indentation level is
14678 used for @b{case} alternatives and variants regardless of their number.
14679 @end table
14680
14681 @node Setting the Source Search Path
14682 @subsection Setting the Source Search Path
14683
14684 @noindent
14685 To define the search path for the input source file, @command{gnatpp}
14686 uses the same switches as the GNAT compiler, with the same effects.
14687
14688 @table @option
14689 @item ^-I^/SEARCH=^@var{dir}
14690 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14691 The same as the corresponding gcc switch
14692
14693 @item ^-I-^/NOCURRENT_DIRECTORY^
14694 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14695 The same as the corresponding gcc switch
14696
14697 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14698 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14699 The same as the corresponding gcc switch
14700
14701 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14702 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14703 The same as the corresponding gcc switch
14704
14705 @end table
14706
14707
14708 @node Output File Control
14709 @subsection Output File Control
14710
14711 @noindent
14712 By default the output is sent to the file whose name is obtained by appending
14713 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14714 (if the file with this name already exists, it is unconditionally overwritten).
14715 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14716 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14717 as output file.
14718 The output may be redirected by the following switches:
14719
14720 @table @option
14721 @item ^-pipe^/STANDARD_OUTPUT^
14722 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14723 Send the output to @code{Standard_Output}
14724
14725 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14726 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14727 Write the output into @var{output_file}.
14728 If @var{output_file} already exists, @command{gnatpp} terminates without
14729 reading or processing the input file.
14730
14731 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14732 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14733 Write the output into @var{output_file}, overwriting the existing file
14734 (if one is present).
14735
14736 @item ^-r^/REPLACE^
14737 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14738 Replace the input source file with the reformatted output, and copy the
14739 original input source into the file whose name is obtained by appending the
14740 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14741 If a file with this name already exists, @command{gnatpp} terminates without
14742 reading or processing the input file.
14743
14744 @item ^-rf^/OVERRIDING_REPLACE^
14745 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14746 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14747 already exists, it is overwritten.
14748 @end table
14749
14750 @noindent
14751 Options @option{^-pipe^/STANDARD_OUTPUT^},
14752 @option{^-o^/OUTPUT^} and
14753 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14754 contains only one file to reformat
14755
14756 @node Other gnatpp Switches
14757 @subsection Other @code{gnatpp} Switches
14758
14759 @noindent
14760 The additional @command{gnatpp} switches are defined in this subsection.
14761
14762 @table @option
14763 @item ^-v^/VERBOSE^
14764 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14765 Verbose mode;
14766 @command{gnatpp} generates version information and then
14767 a trace of the actions it takes to produce or obtain the ASIS tree.
14768
14769 @item ^-w^/WARNINGS^
14770 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14771 Warning mode;
14772 @command{gnatpp} generates a warning whenever it can not provide
14773 a required layout in the result source.
14774 @end table
14775
14776
14777 @node Formatting Rules
14778 @section Formatting Rules
14779
14780 @noindent
14781 The following subsections show how @command{gnatpp} treats ``white space'',
14782 comments, program layout, and name casing.
14783 They provide the detailed descriptions of the switches shown above.
14784
14785 @menu
14786 * White Space and Empty Lines::
14787 * Formatting Comments::
14788 * Construct Layout::
14789 * Name Casing::
14790 @end menu
14791
14792
14793 @node White Space and Empty Lines
14794 @subsection White Space and Empty Lines
14795
14796 @noindent
14797 @command{gnatpp} does not have an option to control space characters.
14798 It will add or remove spaces according to the style illustrated by the
14799 examples in the @cite{Ada Reference Manual}.
14800
14801 The only format effectors
14802 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14803 that will appear in the output file are platform-specific line breaks,
14804 and also format effectors within (but not at the end of) comments.
14805 In particular, each horizontal tab character that is not inside
14806 a comment will be treated as a space and thus will appear in the
14807 output file as zero or more spaces depending on
14808 the reformatting of the line in which it appears.
14809 The only exception is a Form Feed character, which is inserted after a
14810 pragma @code{Page} when @option{-ff} is set.
14811
14812 The output file will contain no lines with trailing ``white space'' (spaces,
14813 format effectors).
14814
14815 Empty lines in the original source are preserved
14816 only if they separate declarations or statements.
14817 In such contexts, a
14818 sequence of two or more empty lines is replaced by exactly one empty line.
14819 Note that a blank line will be removed if it separates two ``comment blocks''
14820 (a comment block is a sequence of whole-line comments).
14821 In order to preserve a visual separation between comment blocks, use an
14822 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14823 Likewise, if for some reason you wish to have a sequence of empty lines,
14824 use a sequence of empty comments instead.
14825
14826
14827 @node Formatting Comments
14828 @subsection Formatting Comments
14829
14830 @noindent
14831 Comments in Ada code are of two kinds:
14832 @itemize @bullet
14833 @item
14834 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14835 ``white space'') on a line
14836
14837 @item
14838 an @emph{end-of-line comment}, which follows some other Ada lexical element
14839 on the same line.
14840 @end itemize
14841
14842 @noindent
14843 The indentation of a whole-line comment is that of either
14844 the preceding or following line in
14845 the formatted source, depending on switch settings as will be described below.
14846
14847 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14848 between the end of the preceding Ada lexical element and the beginning
14849 of the comment as appear in the original source,
14850 unless either the comment has to be split to
14851 satisfy the line length limitation, or else the next line contains a
14852 whole line comment that is considered a continuation of this end-of-line
14853 comment (because it starts at the same position).
14854 In the latter two
14855 cases, the start of the end-of-line comment is moved right to the nearest
14856 multiple of the indentation level.
14857 This may result in a ``line overflow'' (the right-shifted comment extending
14858 beyond the maximum line length), in which case the comment is split as
14859 described below.
14860
14861 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14862 (GNAT-style comment line indentation)
14863 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14864 (reference-manual comment line indentation).
14865 With reference-manual style, a whole-line comment is indented as if it
14866 were a declaration or statement at the same place
14867 (i.e., according to the indentation of the preceding line(s)).
14868 With GNAT style, a whole-line comment that is immediately followed by an
14869 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14870 word @b{begin}, is indented based on the construct that follows it.
14871
14872 For example:
14873 @smallexample @c ada
14874 @cartouche
14875 if A then
14876     null;
14877        -- some comment
14878 else
14879    null;
14880 end if;
14881 @end cartouche
14882 @end smallexample
14883
14884 @noindent
14885 Reference-manual indentation produces:
14886
14887 @smallexample @c ada
14888 @cartouche
14889 if A then
14890    null;
14891    --  some comment
14892 else
14893    null;
14894 end if;
14895 @end cartouche
14896 @end smallexample
14897
14898 @noindent
14899 while GNAT-style indentation produces:
14900
14901 @smallexample @c ada
14902 @cartouche
14903 if A then
14904    null;
14905 --  some comment
14906 else
14907    null;
14908 end if;
14909 @end cartouche
14910 @end smallexample
14911
14912 @noindent
14913 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14914 (GNAT style comment beginning) has the following
14915 effect:
14916
14917 @itemize @bullet
14918 @item
14919 For each whole-line comment that does not end with two hyphens,
14920 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14921 to ensure that there are at least two spaces between these hyphens and the
14922 first non-blank character of the comment.
14923 @end itemize
14924
14925 @noindent
14926 For an end-of-line comment, if in the original source the next line is a
14927 whole-line comment that starts at the same position
14928 as the end-of-line comment,
14929 then the whole-line comment (and all whole-line comments
14930 that follow it and that start at the same position)
14931 will start at this position in the output file.
14932
14933 @noindent
14934 That is, if in the original source we have:
14935
14936 @smallexample @c ada
14937 @cartouche
14938 begin
14939 A := B + C;            --  B must be in the range Low1..High1
14940                        --  C must be in the range Low2..High2
14941              --B+C will be in the range Low1+Low2..High1+High2
14942 X := X + 1;
14943 @end cartouche
14944 @end smallexample
14945
14946 @noindent
14947 Then in the formatted source we get
14948
14949 @smallexample @c ada
14950 @cartouche
14951 begin
14952    A := B + C;            --  B must be in the range Low1..High1
14953                           --  C must be in the range Low2..High2
14954    --  B+C will be in the range Low1+Low2..High1+High2
14955    X := X + 1;
14956 @end cartouche
14957 @end smallexample
14958
14959 @noindent
14960 A comment that exceeds the line length limit will be split.
14961 Unless switch
14962 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14963 the line belongs to a reformattable block, splitting the line generates a
14964 @command{gnatpp} warning.
14965 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14966 comments may be reformatted in typical
14967 word processor style (that is, moving words between lines and putting as
14968 many words in a line as possible).
14969
14970
14971 @node Construct Layout
14972 @subsection Construct Layout
14973
14974 @noindent
14975 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14976 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14977 layout on the one hand, and uncompact layout
14978 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14979 can be illustrated by the following examples:
14980
14981 @iftex
14982 @cartouche
14983 @multitable @columnfractions .5 .5
14984 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14985
14986 @item
14987 @smallexample @c ada
14988 type q is record
14989    a : integer;
14990    b : integer;
14991 end record;
14992 @end smallexample
14993 @tab
14994 @smallexample @c ada
14995 type q is
14996    record
14997       a : integer;
14998       b : integer;
14999    end record;
15000 @end smallexample
15001
15002 @item
15003 @smallexample @c ada
15004 Block : declare
15005    A : Integer := 3;
15006 begin
15007    Proc (A, A);
15008 end Block;
15009 @end smallexample
15010 @tab
15011 @smallexample @c ada
15012 Block :
15013    declare
15014       A : Integer := 3;
15015    begin
15016       Proc (A, A);
15017    end Block;
15018 @end smallexample
15019
15020 @item
15021 @smallexample @c ada
15022 Clear : for J in 1 .. 10 loop
15023    A (J) := 0;
15024 end loop Clear;
15025 @end smallexample
15026 @tab
15027 @smallexample @c ada
15028 Clear :
15029    for J in 1 .. 10 loop
15030       A (J) := 0;
15031    end loop Clear;
15032 @end smallexample
15033 @end multitable
15034 @end cartouche
15035 @end iftex
15036
15037 @ifinfo
15038 @smallexample
15039 @cartouche
15040 GNAT style, compact layout              Uncompact layout
15041
15042 type q is record                        type q is
15043    a : integer;                            record
15044    b : integer;                               a : integer;
15045 end record;                                   b : integer;
15046                                            end record;
15047
15048
15049 Block : declare                         Block :
15050    A : Integer := 3;                       declare
15051 begin                                         A : Integer := 3;
15052    Proc (A, A);                            begin
15053 end Block;                                    Proc (A, A);
15054                                            end Block;
15055
15056 Clear : for J in 1 .. 10 loop           Clear :
15057    A (J) := 0;                             for J in 1 .. 10 loop
15058 end loop Clear;                               A (J) := 0;
15059                                            end loop Clear;
15060 @end cartouche
15061 @end smallexample
15062 @end ifinfo
15063
15064 @noindent
15065 A further difference between GNAT style layout and compact layout is that
15066 GNAT style layout inserts empty lines as separation for
15067 compound statements, return statements and bodies.
15068
15069
15070 @node Name Casing
15071 @subsection Name Casing
15072
15073 @noindent
15074 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15075 the same casing as the corresponding defining identifier.
15076
15077 You control the casing for defining occurrences via the
15078 @option{^-n^/NAME_CASING^} switch.
15079 @ifclear vms
15080 With @option{-nD} (``as declared'', which is the default),
15081 @end ifclear
15082 @ifset vms
15083 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15084 @end ifset
15085 defining occurrences appear exactly as in the source file
15086 where they are declared.
15087 The other ^values for this switch^options for this qualifier^ ---
15088 @option{^-nU^UPPER_CASE^},
15089 @option{^-nL^LOWER_CASE^},
15090 @option{^-nM^MIXED_CASE^} ---
15091 result in
15092 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15093 If @command{gnatpp} changes the casing of a defining
15094 occurrence, it analogously changes the casing of all the
15095 usage occurrences of this name.
15096
15097 If the defining occurrence of a name is not in the source compilation unit
15098 currently being processed by @command{gnatpp}, the casing of each reference to
15099 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15100 switch (subject to the dictionary file mechanism described below).
15101 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15102 had affected the
15103 casing for the defining occurrence of the name.
15104
15105 Some names may need to be spelled with casing conventions that are not
15106 covered by the upper-, lower-, and mixed-case transformations.
15107 You can arrange correct casing by placing such names in a
15108 @emph{dictionary file},
15109 and then supplying a @option{^-D^/DICTIONARY^} switch.
15110 The casing of names from dictionary files overrides
15111 any @option{^-n^/NAME_CASING^} switch.
15112
15113 To handle the casing of Ada predefined names and the names from GNAT libraries,
15114 @command{gnatpp} assumes a default dictionary file.
15115 The name of each predefined entity is spelled with the same casing as is used
15116 for the entity in the @cite{Ada Reference Manual}.
15117 The name of each entity in the GNAT libraries is spelled with the same casing
15118 as is used in the declaration of that entity.
15119
15120 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15121 default dictionary file.
15122 Instead, the casing for predefined and GNAT-defined names will be established
15123 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15124 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15125 will appear as just shown,
15126 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15127 To ensure that even such names are rendered in uppercase,
15128 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15129 (or else, less conveniently, place these names in upper case in a dictionary
15130 file).
15131
15132 A dictionary file is
15133 a plain text file; each line in this file can be either a blank line
15134 (containing only space characters and ASCII.HT characters), an Ada comment
15135 line, or the specification of exactly one @emph{casing schema}.
15136
15137 A casing schema is a string that has the following syntax:
15138
15139 @smallexample
15140 @cartouche
15141   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15142
15143   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15144 @end cartouche
15145 @end smallexample
15146
15147 @noindent
15148 (The @code{[]} metanotation stands for an optional part;
15149 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15150 @var{identifier} lexical element and the @var{letter_or_digit} category).
15151
15152 The casing schema string can be followed by white space and/or an Ada-style
15153 comment; any amount of white space is allowed before the string.
15154
15155 If a dictionary file is passed as
15156 @ifclear vms
15157 the value of a @option{-D@var{file}} switch
15158 @end ifclear
15159 @ifset vms
15160 an option to the @option{/DICTIONARY} qualifier
15161 @end ifset
15162 then for every
15163 simple name and every identifier, @command{gnatpp} checks if the dictionary
15164 defines the casing for the name or for some of its parts (the term ``subword''
15165 is used below to denote the part of a name which is delimited by ``_'' or by
15166 the beginning or end of the word and which does not contain any ``_'' inside):
15167
15168 @itemize @bullet
15169 @item
15170 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15171 the casing defined by the dictionary; no subwords are checked for this word
15172
15173 @item
15174 for the first subword (that is, for the subword preceding the leftmost
15175 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15176 string of the form @code{@var{simple_identifier}*}, and if it does, the
15177 casing of this @var{simple_identifier} is used for this subword
15178
15179 @item
15180 for the last subword (following the rightmost ``_'') @command{gnatpp}
15181 checks if the dictionary contains the corresponding string of the form
15182 @code{*@var{simple_identifier}}, and if it does, the casing of this
15183 @var{simple_identifier} is used for this subword
15184
15185 @item
15186 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15187 if the dictionary contains the corresponding string of the form
15188 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15189 simple_identifier is used for this subword
15190
15191 @item
15192 if more than one dictionary file is passed as @command{gnatpp} switches, each
15193 dictionary adds new casing exceptions and overrides all the existing casing
15194 exceptions set by the previous dictionaries
15195
15196 @item
15197 when @command{gnatpp} checks if the word or subword is in the dictionary,
15198 this check is not case sensitive
15199 @end itemize
15200
15201 @noindent
15202 For example, suppose we have the following source to reformat:
15203
15204 @smallexample @c ada
15205 @cartouche
15206 procedure test is
15207    name1 : integer := 1;
15208    name4_name3_name2 : integer := 2;
15209    name2_name3_name4 : Boolean;
15210    name1_var : Float;
15211 begin
15212    name2_name3_name4 := name4_name3_name2 > name1;
15213 end;
15214 @end cartouche
15215 @end smallexample
15216
15217 @noindent
15218 And suppose we have two dictionaries:
15219
15220 @smallexample
15221 @cartouche
15222 @i{dict1:}
15223    NAME1
15224    *NaMe3*
15225    *NAME2
15226 @end cartouche
15227
15228 @cartouche
15229 @i{dict2:}
15230   *NAME3*
15231 @end cartouche
15232 @end smallexample
15233
15234 @noindent
15235 If @command{gnatpp} is called with the following switches:
15236
15237 @smallexample
15238 @ifclear vms
15239 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15240 @end ifclear
15241 @ifset vms
15242 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15243 @end ifset
15244 @end smallexample
15245
15246 @noindent
15247 then we will get the following name casing in the @command{gnatpp} output:
15248
15249 @smallexample @c ada
15250 @cartouche
15251 procedure Test is
15252    NAME1             : Integer := 1;
15253    Name4_NAME3_NAME2 : integer := 2;
15254    Name2_NAME3_Name4 : Boolean;
15255    Name1_Var         : Float;
15256 begin
15257    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15258 end Test;
15259 @end cartouche
15260 @end smallexample
15261
15262
15263
15264 @c ***********************************
15265 @node File Name Krunching Using gnatkr
15266 @chapter File Name Krunching Using @code{gnatkr}
15267 @findex gnatkr
15268
15269 @noindent
15270 This chapter discusses the method used by the compiler to shorten
15271 the default file names chosen for Ada units so that they do not
15272 exceed the maximum length permitted. It also describes the
15273 @code{gnatkr} utility that can be used to determine the result of
15274 applying this shortening.
15275 @menu
15276 * About gnatkr::
15277 * Using gnatkr::
15278 * Krunching Method::
15279 * Examples of gnatkr Usage::
15280 @end menu
15281
15282 @node About gnatkr
15283 @section About @code{gnatkr}
15284
15285 @noindent
15286 The default file naming rule in GNAT
15287 is that the file name must be derived from
15288 the unit name. The exact default rule is as follows:
15289 @itemize @bullet
15290 @item
15291 Take the unit name and replace all dots by hyphens.
15292 @item
15293 If such a replacement occurs in the
15294 second character position of a name, and the first character is
15295 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15296 ^~ (tilde)^$ (dollar sign)^
15297 instead of a minus.
15298 @end itemize
15299 The reason for this exception is to avoid clashes
15300 with the standard names for children of System, Ada, Interfaces,
15301 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15302 respectively.
15303
15304 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15305 switch of the compiler activates a ``krunching''
15306 circuit that limits file names to nn characters (where nn is a decimal
15307 integer). For example, using OpenVMS,
15308 where the maximum file name length is
15309 39, the value of nn is usually set to 39, but if you want to generate
15310 a set of files that would be usable if ported to a system with some
15311 different maximum file length, then a different value can be specified.
15312 The default value of 39 for OpenVMS need not be specified.
15313
15314 The @code{gnatkr} utility can be used to determine the krunched name for
15315 a given file, when krunched to a specified maximum length.
15316
15317 @node Using gnatkr
15318 @section Using @code{gnatkr}
15319
15320 @noindent
15321 The @code{gnatkr} command has the form
15322
15323 @ifclear vms
15324 @smallexample
15325 $ gnatkr @var{name} [@var{length}]
15326 @end smallexample
15327 @end ifclear
15328
15329 @ifset vms
15330 @smallexample
15331 $ gnatkr @var{name} /COUNT=nn
15332 @end smallexample
15333 @end ifset
15334
15335 @noindent
15336 @var{name} is the uncrunched file name, derived from the name of the unit
15337 in the standard manner described in the previous section (i.e. in particular
15338 all dots are replaced by hyphens). The file name may or may not have an
15339 extension (defined as a suffix of the form period followed by arbitrary
15340 characters other than period). If an extension is present then it will
15341 be preserved in the output. For example, when krunching @file{hellofile.ads}
15342 to eight characters, the result will be hellofil.ads.
15343
15344 Note: for compatibility with previous versions of @code{gnatkr} dots may
15345 appear in the name instead of hyphens, but the last dot will always be
15346 taken as the start of an extension. So if @code{gnatkr} is given an argument
15347 such as @file{Hello.World.adb} it will be treated exactly as if the first
15348 period had been a hyphen, and for example krunching to eight characters
15349 gives the result @file{hellworl.adb}.
15350
15351 Note that the result is always all lower case (except on OpenVMS where it is
15352 all upper case). Characters of the other case are folded as required.
15353
15354 @var{length} represents the length of the krunched name. The default
15355 when no argument is given is ^8^39^ characters. A length of zero stands for
15356 unlimited, in other words do not chop except for system files where the
15357 impled crunching length is always eight characters.
15358
15359 @noindent
15360 The output is the krunched name. The output has an extension only if the
15361 original argument was a file name with an extension.
15362
15363 @node Krunching Method
15364 @section Krunching Method
15365
15366 @noindent
15367 The initial file name is determined by the name of the unit that the file
15368 contains. The name is formed by taking the full expanded name of the
15369 unit and replacing the separating dots with hyphens and
15370 using ^lowercase^uppercase^
15371 for all letters, except that a hyphen in the second character position is
15372 replaced by a ^tilde^dollar sign^ if the first character is
15373 ^a, i, g, or s^A, I, G, or S^.
15374 The extension is @code{.ads} for a
15375 specification and @code{.adb} for a body.
15376 Krunching does not affect the extension, but the file name is shortened to
15377 the specified length by following these rules:
15378
15379 @itemize @bullet
15380 @item
15381 The name is divided into segments separated by hyphens, tildes or
15382 underscores and all hyphens, tildes, and underscores are
15383 eliminated. If this leaves the name short enough, we are done.
15384
15385 @item
15386 If the name is too long, the longest segment is located (left-most
15387 if there are two of equal length), and shortened by dropping
15388 its last character. This is repeated until the name is short enough.
15389
15390 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15391 to fit the name into 8 characters as required by some operating systems.
15392
15393 @smallexample
15394 our-strings-wide_fixed 22
15395 our strings wide fixed 19
15396 our string  wide fixed 18
15397 our strin   wide fixed 17
15398 our stri    wide fixed 16
15399 our stri    wide fixe  15
15400 our str     wide fixe  14
15401 our str     wid  fixe  13
15402 our str     wid  fix   12
15403 ou  str     wid  fix   11
15404 ou  st      wid  fix   10
15405 ou  st      wi   fix   9
15406 ou  st      wi   fi    8
15407 Final file name: oustwifi.adb
15408 @end smallexample
15409
15410 @item
15411 The file names for all predefined units are always krunched to eight
15412 characters. The krunching of these predefined units uses the following
15413 special prefix replacements:
15414
15415 @table @file
15416 @item ada-
15417 replaced by @file{^a^A^-}
15418
15419 @item gnat-
15420 replaced by @file{^g^G^-}
15421
15422 @item interfaces-
15423 replaced by @file{^i^I^-}
15424
15425 @item system-
15426 replaced by @file{^s^S^-}
15427 @end table
15428
15429 These system files have a hyphen in the second character position. That
15430 is why normal user files replace such a character with a
15431 ^tilde^dollar sign^, to
15432 avoid confusion with system file names.
15433
15434 As an example of this special rule, consider
15435 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15436
15437 @smallexample
15438 ada-strings-wide_fixed 22
15439 a-  strings wide fixed 18
15440 a-  string  wide fixed 17
15441 a-  strin   wide fixed 16
15442 a-  stri    wide fixed 15
15443 a-  stri    wide fixe  14
15444 a-  str     wide fixe  13
15445 a-  str     wid  fixe  12
15446 a-  str     wid  fix   11
15447 a-  st      wid  fix   10
15448 a-  st      wi   fix   9
15449 a-  st      wi   fi    8
15450 Final file name: a-stwifi.adb
15451 @end smallexample
15452 @end itemize
15453
15454 Of course no file shortening algorithm can guarantee uniqueness over all
15455 possible unit names, and if file name krunching is used then it is your
15456 responsibility to ensure that no name clashes occur. The utility
15457 program @code{gnatkr} is supplied for conveniently determining the
15458 krunched name of a file.
15459
15460 @node Examples of gnatkr Usage
15461 @section Examples of @code{gnatkr} Usage
15462
15463 @smallexample
15464 @iftex
15465 @leftskip=0cm
15466 @end iftex
15467 @ifclear vms
15468 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15469 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15470 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15471 $ gnatkr grandparent-parent-child     --> grparchi
15472 @end ifclear
15473 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15474 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15475 @end smallexample
15476
15477 @node Preprocessing Using gnatprep
15478 @chapter Preprocessing Using @code{gnatprep}
15479 @findex gnatprep
15480
15481 @noindent
15482 The @code{gnatprep} utility provides
15483 a simple preprocessing capability for Ada programs.
15484 It is designed for use with GNAT, but is not dependent on any special
15485 features of GNAT.
15486
15487 @menu
15488 * Using gnatprep::
15489 * Switches for gnatprep::
15490 * Form of Definitions File::
15491 * Form of Input Text for gnatprep::
15492 @end menu
15493
15494 @node Using gnatprep
15495 @section Using @code{gnatprep}
15496
15497 @noindent
15498 To call @code{gnatprep} use
15499
15500 @smallexample
15501 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15502 @end smallexample
15503
15504 @noindent
15505 where
15506 @table @code
15507 @item infile
15508 is the full name of the input file, which is an Ada source
15509 file containing preprocessor directives.
15510
15511 @item outfile
15512 is the full name of the output file, which is an Ada source
15513 in standard Ada form. When used with GNAT, this file name will
15514 normally have an ads or adb suffix.
15515
15516 @item deffile
15517 is the full name of a text file containing definitions of
15518 symbols to be referenced by the preprocessor. This argument is
15519 optional, and can be replaced by the use of the @option{-D} switch.
15520
15521 @item switches
15522 is an optional sequence of switches as described in the next section.
15523 @end table
15524
15525 @node Switches for gnatprep
15526 @section Switches for @code{gnatprep}
15527
15528 @table @option
15529 @c !sort!
15530
15531 @item ^-b^/BLANK_LINES^
15532 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15533 Causes both preprocessor lines and the lines deleted by
15534 preprocessing to be replaced by blank lines in the output source file,
15535 preserving line numbers in the output file.
15536
15537 @item ^-c^/COMMENTS^
15538 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15539 Causes both preprocessor lines and the lines deleted
15540 by preprocessing to be retained in the output source as comments marked
15541 with the special string @code{"--! "}. This option will result in line numbers
15542 being preserved in the output file.
15543
15544 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15545 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15546 Defines a new symbol, associated with value. If no value is given on the
15547 command line, then symbol is considered to be @code{True}. This switch
15548 can be used in place of a definition file.
15549
15550 @ifset vms
15551 @item /REMOVE
15552 @cindex @option{/REMOVE} (@command{gnatprep})
15553 This is the default setting which causes lines deleted by preprocessing
15554 to be entirely removed from the output file.
15555 @end ifset
15556
15557 @item ^-r^/REFERENCE^
15558 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15559 Causes a @code{Source_Reference} pragma to be generated that
15560 references the original input file, so that error messages will use
15561 the file name of this original file. The use of this switch implies
15562 that preprocessor lines are not to be removed from the file, so its
15563 use will force @option{^-b^/BLANK_LINES^} mode if
15564 @option{^-c^/COMMENTS^}
15565 has not been specified explicitly.
15566
15567 Note that if the file to be preprocessed contains multiple units, then
15568 it will be necessary to @code{gnatchop} the output file from
15569 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15570 in the preprocessed file, it will be respected by
15571 @code{gnatchop ^-r^/REFERENCE^}
15572 so that the final chopped files will correctly refer to the original
15573 input source file for @code{gnatprep}.
15574
15575 @item ^-s^/SYMBOLS^
15576 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15577 Causes a sorted list of symbol names and values to be
15578 listed on the standard output file.
15579
15580 @item ^-u^/UNDEFINED^
15581 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15582 Causes undefined symbols to be treated as having the value FALSE in the context
15583 of a preprocessor test. In the absence of this option, an undefined symbol in
15584 a @code{#if} or @code{#elsif} test will be treated as an error.
15585
15586 @end table
15587
15588 @ifclear vms
15589 @noindent
15590 Note: if neither @option{-b} nor @option{-c} is present,
15591 then preprocessor lines and
15592 deleted lines are completely removed from the output, unless -r is
15593 specified, in which case -b is assumed.
15594 @end ifclear
15595
15596 @node Form of Definitions File
15597 @section Form of Definitions File
15598
15599 @noindent
15600 The definitions file contains lines of the form
15601
15602 @smallexample
15603 symbol := value
15604 @end smallexample
15605
15606 @noindent
15607 where symbol is an identifier, following normal Ada (case-insensitive)
15608 rules for its syntax, and value is one of the following:
15609
15610 @itemize @bullet
15611 @item
15612 Empty, corresponding to a null substitution
15613 @item
15614 A string literal using normal Ada syntax
15615 @item
15616 Any sequence of characters from the set
15617 (letters, digits, period, underline).
15618 @end itemize
15619
15620 @noindent
15621 Comment lines may also appear in the definitions file, starting with
15622 the usual @code{--},
15623 and comments may be added to the definitions lines.
15624
15625 @node Form of Input Text for gnatprep
15626 @section Form of Input Text for @code{gnatprep}
15627
15628 @noindent
15629 The input text may contain preprocessor conditional inclusion lines,
15630 as well as general symbol substitution sequences.
15631
15632 The preprocessor conditional inclusion commands have the form
15633
15634 @smallexample
15635 @group
15636 @cartouche
15637 #if @i{expression} [then]
15638    lines
15639 #elsif @i{expression} [then]
15640    lines
15641 #elsif @i{expression} [then]
15642    lines
15643 ...
15644 #else
15645    lines
15646 #end if;
15647 @end cartouche
15648 @end group
15649 @end smallexample
15650
15651 @noindent
15652 In this example, @i{expression} is defined by the following grammar:
15653 @smallexample
15654 @i{expression} ::=  <symbol>
15655 @i{expression} ::=  <symbol> = "<value>"
15656 @i{expression} ::=  <symbol> = <symbol>
15657 @i{expression} ::=  <symbol> 'Defined
15658 @i{expression} ::=  not @i{expression}
15659 @i{expression} ::=  @i{expression} and @i{expression}
15660 @i{expression} ::=  @i{expression} or @i{expression}
15661 @i{expression} ::=  @i{expression} and then @i{expression}
15662 @i{expression} ::=  @i{expression} or else @i{expression}
15663 @i{expression} ::=  ( @i{expression} )
15664 @end smallexample
15665
15666 @noindent
15667 For the first test (@i{expression} ::= <symbol>) the symbol must have
15668 either the value true or false, that is to say the right-hand of the
15669 symbol definition must be one of the (case-insensitive) literals
15670 @code{True} or @code{False}. If the value is true, then the
15671 corresponding lines are included, and if the value is false, they are
15672 excluded.
15673
15674 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15675 the symbol has been defined in the definition file or by a @option{-D}
15676 switch on the command line. Otherwise, the test is false.
15677
15678 The equality tests are case insensitive, as are all the preprocessor lines.
15679
15680 If the symbol referenced is not defined in the symbol definitions file,
15681 then the effect depends on whether or not switch @option{-u}
15682 is specified. If so, then the symbol is treated as if it had the value
15683 false and the test fails. If this switch is not specified, then
15684 it is an error to reference an undefined symbol. It is also an error to
15685 reference a symbol that is defined with a value other than @code{True}
15686 or @code{False}.
15687
15688 The use of the @code{not} operator inverts the sense of this logical test, so
15689 that the lines are included only if the symbol is not defined.
15690 The @code{then} keyword is optional as shown
15691
15692 The @code{#} must be the first non-blank character on a line, but
15693 otherwise the format is free form. Spaces or tabs may appear between
15694 the @code{#} and the keyword. The keywords and the symbols are case
15695 insensitive as in normal Ada code. Comments may be used on a
15696 preprocessor line, but other than that, no other tokens may appear on a
15697 preprocessor line. Any number of @code{elsif} clauses can be present,
15698 including none at all. The @code{else} is optional, as in Ada.
15699
15700 The @code{#} marking the start of a preprocessor line must be the first
15701 non-blank character on the line, i.e. it must be preceded only by
15702 spaces or horizontal tabs.
15703
15704 Symbol substitution outside of preprocessor lines is obtained by using
15705 the sequence
15706
15707 @smallexample
15708 $symbol
15709 @end smallexample
15710
15711 @noindent
15712 anywhere within a source line, except in a comment or within a
15713 string literal. The identifier
15714 following the @code{$} must match one of the symbols defined in the symbol
15715 definition file, and the result is to substitute the value of the
15716 symbol in place of @code{$symbol} in the output file.
15717
15718 Note that although the substitution of strings within a string literal
15719 is not possible, it is possible to have a symbol whose defined value is
15720 a string literal. So instead of setting XYZ to @code{hello} and writing:
15721
15722 @smallexample
15723 Header : String := "$XYZ";
15724 @end smallexample
15725
15726 @noindent
15727 you should set XYZ to @code{"hello"} and write:
15728
15729 @smallexample
15730 Header : String := $XYZ;
15731 @end smallexample
15732
15733 @noindent
15734 and then the substitution will occur as desired.
15735
15736 @ifset vms
15737 @node The GNAT Run-Time Library Builder gnatlbr
15738 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15739 @findex gnatlbr
15740 @cindex Library builder
15741
15742 @noindent
15743 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15744 supplied configuration pragmas.
15745
15746 @menu
15747 * Running gnatlbr::
15748 * Switches for gnatlbr::
15749 * Examples of gnatlbr Usage::
15750 @end menu
15751
15752 @node Running gnatlbr
15753 @section Running @code{gnatlbr}
15754
15755 @noindent
15756 The @code{gnatlbr} command has the form
15757
15758 @smallexample
15759 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15760 @end smallexample
15761
15762 @node Switches for gnatlbr
15763 @section Switches for @code{gnatlbr}
15764
15765 @noindent
15766 @code{gnatlbr} recognizes the following switches:
15767
15768 @table @option
15769 @c !sort!
15770 @item /CREATE=directory
15771 @cindex @code{/CREATE} (@code{gnatlbr})
15772      Create the new run-time library in the specified directory.
15773
15774 @item /SET=directory
15775 @cindex @code{/SET} (@code{gnatlbr})
15776      Make the library in the specified directory the current run-time
15777      library.
15778
15779 @item /DELETE=directory
15780 @cindex @code{/DELETE} (@code{gnatlbr})
15781      Delete the run-time library in the specified directory.
15782
15783 @item /CONFIG=file
15784 @cindex @code{/CONFIG} (@code{gnatlbr})
15785      With /CREATE:
15786      Use the configuration pragmas in the specified file when building
15787      the library.
15788
15789      With /SET:
15790      Use the configuration pragmas in the specified file when compiling.
15791
15792 @end table
15793
15794 @node Examples of gnatlbr Usage
15795 @section Example of @code{gnatlbr} Usage
15796
15797 @smallexample
15798 Contents of VAXFLOAT.ADC:
15799 pragma Float_Representation (VAX_Float);
15800
15801 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15802
15803 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15804
15805 @end smallexample
15806 @end ifset
15807
15808 @node The GNAT Library Browser gnatls
15809 @chapter The GNAT Library Browser @code{gnatls}
15810 @findex gnatls
15811 @cindex Library browser
15812
15813 @noindent
15814 @code{gnatls} is a tool that outputs information about compiled
15815 units. It gives the relationship between objects, unit names and source
15816 files. It can also be used to check the source dependencies of a unit
15817 as well as various characteristics.
15818
15819 @menu
15820 * Running gnatls::
15821 * Switches for gnatls::
15822 * Examples of gnatls Usage::
15823 @end menu
15824
15825 @node Running gnatls
15826 @section Running @code{gnatls}
15827
15828 @noindent
15829 The @code{gnatls} command has the form
15830
15831 @smallexample
15832 $ gnatls switches @var{object_or_ali_file}
15833 @end smallexample
15834
15835 @noindent
15836 The main argument is the list of object or @file{ali} files
15837 (@pxref{The Ada Library Information Files})
15838 for which information is requested.
15839
15840 In normal mode, without additional option, @code{gnatls} produces a
15841 four-column listing. Each line represents information for a specific
15842 object. The first column gives the full path of the object, the second
15843 column gives the name of the principal unit in this object, the third
15844 column gives the status of the source and the fourth column gives the
15845 full path of the source representing this unit.
15846 Here is a simple example of use:
15847
15848 @smallexample
15849 $ gnatls *.o
15850 ^./^[]^demo1.o            demo1            DIF demo1.adb
15851 ^./^[]^demo2.o            demo2             OK demo2.adb
15852 ^./^[]^hello.o            h1                OK hello.adb
15853 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15854 ^./^[]^instr.o            instr             OK instr.adb
15855 ^./^[]^tef.o              tef              DIF tef.adb
15856 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15857 ^./^[]^tgef.o             tgef             DIF tgef.adb
15858 @end smallexample
15859
15860 @noindent
15861 The first line can be interpreted as follows: the main unit which is
15862 contained in
15863 object file @file{demo1.o} is demo1, whose main source is in
15864 @file{demo1.adb}. Furthermore, the version of the source used for the
15865 compilation of demo1 has been modified (DIF). Each source file has a status
15866 qualifier which can be:
15867
15868 @table @code
15869 @item OK (unchanged)
15870 The version of the source file used for the compilation of the
15871 specified unit corresponds exactly to the actual source file.
15872
15873 @item MOK (slightly modified)
15874 The version of the source file used for the compilation of the
15875 specified unit differs from the actual source file but not enough to
15876 require recompilation. If you use gnatmake with the qualifier
15877 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15878 MOK will not be recompiled.
15879
15880 @item DIF (modified)
15881 No version of the source found on the path corresponds to the source
15882 used to build this object.
15883
15884 @item ??? (file not found)
15885 No source file was found for this unit.
15886
15887 @item HID (hidden,  unchanged version not first on PATH)
15888 The version of the source that corresponds exactly to the source used
15889 for compilation has been found on the path but it is hidden by another
15890 version of the same source that has been modified.
15891
15892 @end table
15893
15894 @node Switches for gnatls
15895 @section Switches for @code{gnatls}
15896
15897 @noindent
15898 @code{gnatls} recognizes the following switches:
15899
15900 @table @option
15901 @c !sort!
15902 @item ^-a^/ALL_UNITS^
15903 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15904 Consider all units, including those of the predefined Ada library.
15905 Especially useful with @option{^-d^/DEPENDENCIES^}.
15906
15907 @item ^-d^/DEPENDENCIES^
15908 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15909 List sources from which specified units depend on.
15910
15911 @item ^-h^/OUTPUT=OPTIONS^
15912 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15913 Output the list of options.
15914
15915 @item ^-o^/OUTPUT=OBJECTS^
15916 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15917 Only output information about object files.
15918
15919 @item ^-s^/OUTPUT=SOURCES^
15920 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15921 Only output information about source files.
15922
15923 @item ^-u^/OUTPUT=UNITS^
15924 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15925 Only output information about compilation units.
15926
15927 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15928 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15929 @itemx ^-I^/SEARCH=^@var{dir}
15930 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15931 @itemx -nostdinc
15932 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15933 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15934 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15935 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15936 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
15937 (see @ref{Switches for gnatmake}).
15938
15939 @item --RTS=@var{rts-path}
15940 @cindex @option{--RTS} (@code{gnatls})
15941 Specifies the default location of the runtime library. Same meaning as the
15942 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
15943
15944 @item ^-v^/OUTPUT=VERBOSE^
15945 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15946 Verbose mode. Output the complete source and object paths. Do not use
15947 the default column layout but instead use long format giving as much as
15948 information possible on each requested units, including special
15949 characteristics such as:
15950
15951 @table @code
15952 @item  Preelaborable
15953 The unit is preelaborable in the Ada 95 sense.
15954
15955 @item No_Elab_Code
15956 No elaboration code has been produced by the compiler for this unit.
15957
15958 @item Pure
15959 The unit is pure in the Ada 95 sense.
15960
15961 @item Elaborate_Body
15962 The unit contains a pragma Elaborate_Body.
15963
15964 @item Remote_Types
15965 The unit contains a pragma Remote_Types.
15966
15967 @item Shared_Passive
15968 The unit contains a pragma Shared_Passive.
15969
15970 @item Predefined
15971 This unit is part of the predefined environment and cannot be modified
15972 by the user.
15973
15974 @item Remote_Call_Interface
15975 The unit contains a pragma Remote_Call_Interface.
15976
15977 @end table
15978
15979 @end table
15980
15981 @node Examples of gnatls Usage
15982 @section Example of @code{gnatls} Usage
15983 @ifclear vms
15984
15985 @noindent
15986 Example of using the verbose switch. Note how the source and
15987 object paths are affected by the -I switch.
15988
15989 @smallexample
15990 $ gnatls -v -I.. demo1.o
15991
15992 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
15993
15994 Source Search Path:
15995    <Current_Directory>
15996    ../
15997    /home/comar/local/adainclude/
15998
15999 Object Search Path:
16000    <Current_Directory>
16001    ../
16002    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16003
16004 ./demo1.o
16005    Unit =>
16006      Name   => demo1
16007      Kind   => subprogram body
16008      Flags  => No_Elab_Code
16009      Source => demo1.adb    modified
16010 @end smallexample
16011
16012 @noindent
16013 The following is an example of use of the dependency list.
16014 Note the use of the -s switch
16015 which gives a straight list of source files. This can be useful for
16016 building specialized scripts.
16017
16018 @smallexample
16019 $ gnatls -d demo2.o
16020 ./demo2.o   demo2        OK demo2.adb
16021                          OK gen_list.ads
16022                          OK gen_list.adb
16023                          OK instr.ads
16024                          OK instr-child.ads
16025
16026 $ gnatls -d -s -a demo1.o
16027 demo1.adb
16028 /home/comar/local/adainclude/ada.ads
16029 /home/comar/local/adainclude/a-finali.ads
16030 /home/comar/local/adainclude/a-filico.ads
16031 /home/comar/local/adainclude/a-stream.ads
16032 /home/comar/local/adainclude/a-tags.ads
16033 gen_list.ads
16034 gen_list.adb
16035 /home/comar/local/adainclude/gnat.ads
16036 /home/comar/local/adainclude/g-io.ads
16037 instr.ads
16038 /home/comar/local/adainclude/system.ads
16039 /home/comar/local/adainclude/s-exctab.ads
16040 /home/comar/local/adainclude/s-finimp.ads
16041 /home/comar/local/adainclude/s-finroo.ads
16042 /home/comar/local/adainclude/s-secsta.ads
16043 /home/comar/local/adainclude/s-stalib.ads
16044 /home/comar/local/adainclude/s-stoele.ads
16045 /home/comar/local/adainclude/s-stratt.ads
16046 /home/comar/local/adainclude/s-tasoli.ads
16047 /home/comar/local/adainclude/s-unstyp.ads
16048 /home/comar/local/adainclude/unchconv.ads
16049 @end smallexample
16050 @end ifclear
16051
16052 @ifset vms
16053 @smallexample
16054 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16055
16056 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16057 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16058 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16059 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16060 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16061 demo1.adb
16062 gen_list.ads
16063 gen_list.adb
16064 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16065 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16066 instr.ads
16067 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16068 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16069 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16070 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16071 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16072 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16073 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16074 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16075 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16076 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16077 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16078 @end smallexample
16079 @end ifset
16080
16081 @node Cleaning Up Using gnatclean
16082 @chapter Cleaning Up Using @code{gnatclean}
16083 @findex gnatclean
16084 @cindex Cleaning tool
16085
16086 @noindent
16087 @code{gnatclean} is a tool that allows the deletion of files produced by the
16088 compiler, binder and linker, including ALI files, object files, tree files,
16089 expanded source files, library files, interface copy source files, binder
16090 generated files and executable files.
16091
16092 @menu
16093 * Running gnatclean::
16094 * Switches for gnatclean::
16095 * Examples of gnatclean Usage::
16096 @end menu
16097
16098 @node Running gnatclean
16099 @section Running @code{gnatclean}
16100
16101 @noindent
16102 The @code{gnatclean} command has the form:
16103
16104 @smallexample
16105 $ gnatclean switches @var{names}
16106 @end smallexample
16107
16108 @noindent
16109 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16110 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16111 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16112
16113 @noindent
16114 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16115 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16116 the linker. In informative-only mode, specified by switch
16117 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16118 normal mode is listed, but no file is actually deleted.
16119
16120 @node Switches for gnatclean
16121 @section Switches for @code{gnatclean}
16122
16123 @noindent
16124 @code{gnatclean} recognizes the following switches:
16125
16126 @table @option
16127 @c !sort!
16128 @item ^-c^/COMPILER_FILES_ONLY^
16129 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16130 Only attempt to delete the files produced by the compiler, not those produced
16131 by the binder or the linker. The files that are not to be deleted are library
16132 files, interface copy files, binder generated files and executable files.
16133
16134 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16135 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16136 Indicate that ALI and object files should normally be found in directory
16137 @var{dir}.
16138
16139 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16140 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16141 When using project files, if some errors or warnings are detected during
16142 parsing and verbose mode is not in effect (no use of switch
16143 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16144 file, rather than its simple file name.
16145
16146 @item ^-h^/HELP^
16147 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16148 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16149
16150 @item ^-n^/NODELETE^
16151 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16152 Informative-only mode. Do not delete any files. Output the list of the files
16153 that would have been deleted if this switch was not specified.
16154
16155 @item ^-P^/PROJECT_FILE=^@var{project}
16156 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16157 Use project file @var{project}. Only one such switch can be used.
16158 When cleaning a project file, the files produced by the compilation of the
16159 immediate sources or inherited sources of the project files are to be
16160 deleted. This is not depending on the presence or not of executable names
16161 on the command line.
16162
16163 @item ^-q^/QUIET^
16164 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16165 Quiet output. If there are no error, do not ouuput anything, except in
16166 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16167 (switch ^-n^/NODELETE^).
16168
16169 @item ^-r^/RECURSIVE^
16170 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16171 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16172 clean all imported and extended project files, recursively. If this switch
16173 is not specified, only the files related to the main project file are to be
16174 deleted. This switch has no effect if no project file is specified.
16175
16176 @item ^-v^/VERBOSE^
16177 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16178 Verbose mode.
16179
16180 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16181 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16182 Indicates the verbosity of the parsing of GNAT project files.
16183 See @ref{Switches Related to Project Files}.
16184
16185 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16186 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16187 Indicates that external variable @var{name} has the value @var{value}.
16188 The Project Manager will use this value for occurrences of
16189 @code{external(name)} when parsing the project file.
16190 See @ref{Switches Related to Project Files}.
16191
16192 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16193 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16194 When searching for ALI and object files, look in directory
16195 @var{dir}.
16196
16197 @item ^-I^/SEARCH=^@var{dir}
16198 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16199 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16200
16201 @item ^-I-^/NOCURRENT_DIRECTORY^
16202 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16203 @cindex Source files, suppressing search
16204 Do not look for ALI or object files in the directory
16205 where @code{gnatclean} was invoked.
16206
16207 @end table
16208
16209 @node Examples of gnatclean Usage
16210 @section Examples of @code{gnatclean} Usage
16211
16212 @ifclear vms
16213 @node GNAT and Libraries
16214 @chapter GNAT and Libraries
16215 @cindex Library, building, installing
16216
16217 @noindent
16218 This chapter addresses some of the issues related to building and using
16219 a library with GNAT. It also shows how the GNAT run-time library can be
16220 recompiled.
16221
16222 @menu
16223 * Creating an Ada Library::
16224 * Installing an Ada Library::
16225 * Using an Ada Library::
16226 * Creating an Ada Library to be Used in a Non-Ada Context::
16227 * Rebuilding the GNAT Run-Time Library::
16228 @end menu
16229
16230 @node Creating an Ada Library
16231 @section Creating an Ada Library
16232
16233 @noindent
16234 In the GNAT environment, a library has two components:
16235 @itemize @bullet
16236 @item
16237 Source files.
16238 @item
16239 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
16240 @end itemize
16241
16242 @noindent
16243 In order to use other packages @ref{The GNAT Compilation Model}
16244 requires a certain number of sources to be available to the compiler.
16245 The minimal set of
16246 sources required includes the specs of all the packages that make up the
16247 visible part of the library as well as all the sources upon which they
16248 depend. The bodies of all visible generic units must also be provided.
16249 @noindent
16250 Although it is not strictly mandatory, it is recommended that all sources
16251 needed to recompile the library be provided, so that the user can make
16252 full use of inter-unit inlining and source-level debugging. This can also
16253 make the situation easier for users that need to upgrade their compilation
16254 toolchain and thus need to recompile the library from sources.
16255
16256 @noindent
16257 The compiled code can be provided in different ways. The simplest way is
16258 to provide directly the set of objects produced by the compiler during
16259 the compilation of the library. It is also possible to group the objects
16260 into an archive using whatever commands are provided by the operating
16261 system. Finally, it is also possible to create a shared library (see
16262 option -shared in the GCC manual).
16263
16264 @noindent
16265 There are various possibilities for compiling the units that make up the
16266 library: for example with a Makefile @ref{Using the GNU make Utility},
16267 or with a conventional script.
16268 For simple libraries, it is also possible to create a
16269 dummy main program which depends upon all the packages that comprise the
16270 interface of the library. This dummy main program can then be given to
16271 gnatmake, in order to build all the necessary objects. Here is an example
16272 of such a dummy program and the generic commands used to build an
16273 archive or a shared library.
16274
16275 @smallexample @c ada
16276 @iftex
16277 @leftskip=.7cm
16278 @end iftex
16279 with My_Lib.Service1;
16280 with My_Lib.Service2;
16281 with My_Lib.Service3;
16282 procedure My_Lib_Dummy is
16283 begin
16284    null;
16285 end;
16286 @end smallexample
16287
16288 @smallexample
16289 # compiling the library
16290 $ gnatmake -c my_lib_dummy.adb
16291
16292 # we don't need the dummy object itself
16293 $ rm my_lib_dummy.o my_lib_dummy.ali
16294
16295 # create an archive with the remaining objects
16296 $ ar rc libmy_lib.a *.o
16297 # some systems may require "ranlib" to be run as well
16298
16299 # or create a shared library
16300 $ gcc -shared -o libmy_lib.so *.o
16301 # some systems may require the code to have been compiled with -fPIC
16302
16303 # remove the object files that are now in the library
16304 $ rm *.o
16305
16306 # Make the ALI files read-only so that gnatmake will not try to
16307 # regenerate the objects that are in the library
16308 $ chmod -w *.ali
16309
16310 @end smallexample
16311
16312 @noindent
16313 When the objects are grouped in an archive or a shared library, the user
16314 needs to specify the desired library at link time, unless a pragma
16315 linker_options has been used in one of the sources:
16316 @smallexample @c ada
16317 pragma Linker_Options ("-lmy_lib");
16318 @end smallexample
16319
16320 @noindent
16321 Please note that the library must have a name of the form libxxx.a or
16322 libxxx.so in order to be accessed by the directive -lxxx at link
16323 time.
16324
16325 @node Installing an Ada Library
16326 @section Installing an Ada Library
16327
16328 @noindent
16329 In the GNAT model, installing a library consists in copying into a specific
16330 location the files that make up this library. It is possible to install
16331 the sources in a different directory from the other files (ALI, objects,
16332 archives) since the source path and the object path can easily be
16333 specified separately.
16334
16335 @noindent
16336 For general purpose libraries, it is possible for the system
16337 administrator to put those libraries in the default compiler paths. To
16338 achieve this, he must specify their location in the configuration files
16339 @file{ada_source_path} and @file{ada_object_path} that must be located in
16340 the GNAT
16341 installation tree at the same place as the gcc spec file. The location of
16342 the gcc spec file can be determined as follows:
16343 @smallexample
16344 $ gcc -v
16345 @end smallexample
16346
16347 @noindent
16348 The configuration files mentioned above have simple format: each line in them
16349 must contain one unique
16350 directory name. Those names are added to the corresponding path
16351 in their order of appearance in the file. The names can be either absolute
16352 or relative, in the latter case, they are relative to where theses files
16353 are located.
16354
16355 @noindent
16356 @file{ada_source_path} and @file{ada_object_path} might actually not be
16357 present in a
16358 GNAT installation, in which case, GNAT will look for its run-time library in
16359 he directories @file{adainclude} for the sources and @file{adalib} for the
16360 objects and @file{ALI} files. When the files exist, the compiler does not
16361 look in @file{adainclude} and @file{adalib} at all, and thus the
16362 @file{ada_source_path} file
16363 must contain the location for the GNAT run-time sources (which can simply
16364 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16365 contain the location for the GNAT run-time objects (which can simply
16366 be @file{adalib}).
16367
16368 @noindent
16369 You can also specify a new default path to the runtime library at compilation
16370 time with the switch @option{--RTS=rts-path}. You can easily choose and change
16371 the runtime you want your program to be compiled with. This switch is
16372 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
16373
16374 @noindent
16375 It is possible to install a library before or after the standard GNAT
16376 library, by reordering the lines in the configuration files. In general, a
16377 library must be installed before the GNAT library if it redefines
16378 any part of it.
16379
16380 @node Using an Ada Library
16381 @section Using an Ada Library
16382
16383 @noindent
16384 In order to use a Ada library, you need to make sure that this
16385 library is on both your source and object path
16386 @ref{Search Paths and the Run-Time Library (RTL)}
16387 and @ref{Search Paths for gnatbind}. For
16388 instance, you can use the library @file{mylib} installed in
16389 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16390
16391 @smallexample
16392 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16393   -largs -lmy_lib
16394 @end smallexample
16395
16396 @noindent
16397 This can be simplified down to the following:
16398 @smallexample
16399 $ gnatmake my_appl
16400 @end smallexample
16401 when the following conditions are met:
16402 @itemize @bullet
16403 @item
16404 @file{/dir/my_lib_src} has been added by the user to the environment
16405 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16406 @file{ada_source_path}
16407 @item
16408 @file{/dir/my_lib_obj} has been added by the user to the environment
16409 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16410 @file{ada_object_path}
16411 @item
16412 a pragma @code{Linker_Options}, as mentioned in @ref{Creating an Ada Library},
16413 has been added to the sources.
16414 @end itemize
16415 @noindent
16416
16417 @node Creating an Ada Library to be Used in a Non-Ada Context
16418 @section Creating an Ada Library to be Used in a Non-Ada Context
16419
16420 @noindent
16421 The previous sections detailed how to create and install a library that
16422 was usable from an Ada main program. Using this library in a non-Ada
16423 context is not possible, because the elaboration of the library is
16424 automatically done as part of the main program elaboration.
16425
16426 GNAT also provides the ability to build libraries that can be used both
16427 in an Ada and non-Ada context.  This section describes how to build such
16428 a library, and then how to use it from a C program. The method for
16429 interfacing with the library from other languages such as Fortran for
16430 instance remains the same.
16431
16432 @subsection Creating the Library
16433
16434 @itemize @bullet
16435 @item Identify the units representing the interface of the library.
16436
16437 Here is an example of simple library interface:
16438
16439 @smallexample @c ada
16440 package Interface is
16441
16442    procedure Do_Something;
16443
16444    procedure Do_Something_Else;
16445
16446 end Interface;
16447 @end smallexample
16448
16449 @item Use @code{pragma Export} or @code{pragma Convention} for the
16450 exported entities.
16451
16452 Our package @code{Interface} is then updated as follow:
16453 @smallexample @c ada
16454 package Interface is
16455
16456    procedure Do_Something;
16457    pragma Export (C, Do_Something, "do_something");
16458
16459    procedure Do_Something_Else;
16460    pragma Export (C, Do_Something_Else, "do_something_else");
16461
16462 end Interface;
16463 @end smallexample
16464
16465 @item Compile all the units composing the library.
16466
16467 @item Bind the library objects.
16468
16469 This step is performed by invoking gnatbind with the @option{-L<prefix>}
16470 switch. @code{gnatbind} will then generate the library elaboration
16471 procedure (named @code{<prefix>init}) and the run-time finalization
16472 procedure (named @code{<prefix>final}).
16473
16474 @smallexample
16475 # generate the binder file in Ada
16476 $ gnatbind -Lmylib interface
16477
16478 # generate the binder file in C
16479 $ gnatbind -C -Lmylib interface
16480 @end smallexample
16481
16482 @item Compile the files generated by the binder
16483
16484 @smallexample
16485 $ gcc -c b~interface.adb
16486 @end smallexample
16487
16488 @item Create the library;
16489
16490 The procedure is identical to the procedure explained in
16491 @ref{Creating an Ada Library},
16492 except that @file{b~interface.o} needs to be added to
16493 the list of objects.
16494
16495 @smallexample
16496 # create an archive file
16497 $ ar cr libmylib.a b~interface.o <other object files>
16498
16499 # create a shared library
16500 $ gcc -shared -o libmylib.so b~interface.o <other object files>
16501 @end smallexample
16502
16503 @item Provide a ``foreign'' view of the library interface;
16504
16505 The example below shows the content of @code{mylib_interface.h} (note
16506 that there is no rule for the naming of this file, any name can be used)
16507 @smallexample
16508 /* the library elaboration procedure */
16509 extern void mylibinit (void);
16510
16511 /* the library finalization procedure */
16512 extern void mylibfinal (void);
16513
16514 /* the interface exported by the library */
16515 extern void do_something (void);
16516 extern void do_something_else (void);
16517 @end smallexample
16518 @end itemize
16519
16520 @subsection Using the Library
16521
16522 @noindent
16523 Libraries built as explained above can be used from any program, provided
16524 that the elaboration procedures (named @code{mylibinit} in the previous
16525 example) are called before the library services are used. Any number of
16526 libraries can be used simultaneously, as long as the elaboration
16527 procedure of each library is called.
16528
16529 Below is an example of C program that uses our @code{mylib} library.
16530
16531 @smallexample
16532 #include "mylib_interface.h"
16533
16534 int
16535 main (void)
16536 @{
16537    /* First, elaborate the library before using it */
16538    mylibinit ();
16539
16540    /* Main program, using the library exported entities */
16541    do_something ();
16542    do_something_else ();
16543
16544    /* Library finalization at the end of the program */
16545    mylibfinal ();
16546    return 0;
16547 @}
16548 @end smallexample
16549
16550 @noindent
16551 Note that this same library can be used from an equivalent Ada main
16552 program. In addition, if the libraries are installed as detailed in
16553 @ref{Installing an Ada Library}, it is not necessary to invoke the
16554 library elaboration and finalization routines. The binder will ensure
16555 that this is done as part of the main program elaboration and
16556 finalization phases.
16557
16558 @subsection The Finalization Phase
16559
16560 @noindent
16561 Invoking any library finalization procedure generated by @code{gnatbind}
16562 shuts down the Ada run time permanently. Consequently, the finalization
16563 of all Ada libraries must be performed at the end of the program. No
16564 call to these libraries nor the Ada run time should be made past the
16565 finalization phase.
16566
16567 @subsection Restrictions in Libraries
16568
16569 @noindent
16570 The pragmas listed below should be used with caution inside libraries,
16571 as they can create incompatibilities with other Ada libraries:
16572 @itemize @bullet
16573 @item pragma @code{Locking_Policy}
16574 @item pragma @code{Queuing_Policy}
16575 @item pragma @code{Task_Dispatching_Policy}
16576 @item pragma @code{Unreserve_All_Interrupts}
16577 @end itemize
16578 When using a library that contains such pragmas, the user must make sure
16579 that all libraries use the same pragmas with the same values. Otherwise,
16580 a @code{Program_Error} will
16581 be raised during the elaboration of the conflicting
16582 libraries. The usage of these pragmas and its consequences for the user
16583 should therefore be well documented.
16584
16585 Similarly, the traceback in exception occurrences mechanism should be
16586 enabled or disabled in a consistent manner across all libraries.
16587 Otherwise, a Program_Error will be raised during the elaboration of the
16588 conflicting libraries.
16589
16590 If the @code{'Version} and @code{'Body_Version}
16591 attributes are used inside a library, then it is necessary to
16592 perform a @code{gnatbind} step that mentions all @file{ALI} files in all
16593 libraries, so that version identifiers can be properly computed.
16594 In practice these attributes are rarely used, so this is unlikely
16595 to be a consideration.
16596
16597 @node  Rebuilding the GNAT Run-Time Library
16598 @section Rebuilding the GNAT Run-Time Library
16599
16600 @noindent
16601 It may be useful to recompile the GNAT library in various contexts, the
16602 most important one being the use of partition-wide configuration pragmas
16603 such as Normalize_Scalar. A special Makefile called
16604 @code{Makefile.adalib} is provided to that effect and can be found in
16605 the directory containing the GNAT library. The location of this
16606 directory depends on the way the GNAT environment has been installed and can
16607 be determined by means of the command:
16608
16609 @smallexample
16610 $ gnatls -v
16611 @end smallexample
16612
16613 @noindent
16614 The last entry in the object search path usually contains the
16615 gnat library. This Makefile contains its own documentation and in
16616 particular the set of instructions needed to rebuild a new library and
16617 to use it.
16618
16619 @node Using the GNU make Utility
16620 @chapter Using the GNU @code{make} Utility
16621 @findex make
16622
16623 @noindent
16624 This chapter offers some examples of makefiles that solve specific
16625 problems. It does not explain how to write a makefile (see the GNU make
16626 documentation), nor does it try to replace the @code{gnatmake} utility
16627 (@pxref{The GNAT Make Program gnatmake}).
16628
16629 All the examples in this section are specific to the GNU version of
16630 make. Although @code{make} is a standard utility, and the basic language
16631 is the same, these examples use some advanced features found only in
16632 @code{GNU make}.
16633
16634 @menu
16635 * Using gnatmake in a Makefile::
16636 * Automatically Creating a List of Directories::
16637 * Generating the Command Line Switches::
16638 * Overcoming Command Line Length Limits::
16639 @end menu
16640
16641 @node Using gnatmake in a Makefile
16642 @section Using gnatmake in a Makefile
16643 @findex makefile
16644 @cindex GNU make
16645
16646 @noindent
16647 Complex project organizations can be handled in a very powerful way by
16648 using GNU make combined with gnatmake. For instance, here is a Makefile
16649 which allows you to build each subsystem of a big project into a separate
16650 shared library. Such a makefile allows you to significantly reduce the link
16651 time of very big applications while maintaining full coherence at
16652 each step of the build process.
16653
16654 The list of dependencies are handled automatically by
16655 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16656 the appropriate directories.
16657
16658 Note that you should also read the example on how to automatically
16659 create the list of directories
16660 (@pxref{Automatically Creating a List of Directories})
16661 which might help you in case your project has a lot of subdirectories.
16662
16663 @smallexample
16664 @iftex
16665 @leftskip=0cm
16666 @font@heightrm=cmr8
16667 @heightrm
16668 @end iftex
16669 ## This Makefile is intended to be used with the following directory
16670 ## configuration:
16671 ##  - The sources are split into a series of csc (computer software components)
16672 ##    Each of these csc is put in its own directory.
16673 ##    Their name are referenced by the directory names.
16674 ##    They will be compiled into shared library (although this would also work
16675 ##    with static libraries
16676 ##  - The main program (and possibly other packages that do not belong to any
16677 ##    csc is put in the top level directory (where the Makefile is).
16678 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16679 ##                    \_ second_csc (sources) __ lib (will contain the library)
16680 ##                    \_ ...
16681 ## Although this Makefile is build for shared library, it is easy to modify
16682 ## to build partial link objects instead (modify the lines with -shared and
16683 ## gnatlink below)
16684 ##
16685 ## With this makefile, you can change any file in the system or add any new
16686 ## file, and everything will be recompiled correctly (only the relevant shared
16687 ## objects will be recompiled, and the main program will be re-linked).
16688
16689 # The list of computer software component for your project. This might be
16690 # generated automatically.
16691 CSC_LIST=aa bb cc
16692
16693 # Name of the main program (no extension)
16694 MAIN=main
16695
16696 # If we need to build objects with -fPIC, uncomment the following line
16697 #NEED_FPIC=-fPIC
16698
16699 # The following variable should give the directory containing libgnat.so
16700 # You can get this directory through 'gnatls -v'. This is usually the last
16701 # directory in the Object_Path.
16702 GLIB=...
16703
16704 # The directories for the libraries
16705 # (This macro expands the list of CSC to the list of shared libraries, you
16706 # could simply use the expanded form :
16707 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16708 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16709
16710 $@{MAIN@}: objects $@{LIB_DIR@}
16711     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16712     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16713
16714 objects::
16715     # recompile the sources
16716     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16717
16718 # Note: In a future version of GNAT, the following commands will be simplified
16719 # by a new tool, gnatmlib
16720 $@{LIB_DIR@}:
16721     mkdir -p $@{dir $@@ @}
16722     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16723     cd $@{dir $@@ @}; cp -f ../*.ali .
16724
16725 # The dependencies for the modules
16726 # Note that we have to force the expansion of *.o, since in some cases
16727 # make won't be able to do it itself.
16728 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16729 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16730 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16731
16732 # Make sure all of the shared libraries are in the path before starting the
16733 # program
16734 run::
16735     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16736
16737 clean::
16738     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16739     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16740     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16741     $@{RM@} *.o *.ali $@{MAIN@}
16742 @end smallexample
16743
16744 @node Automatically Creating a List of Directories
16745 @section Automatically Creating a List of Directories
16746
16747 @noindent
16748 In most makefiles, you will have to specify a list of directories, and
16749 store it in a variable. For small projects, it is often easier to
16750 specify each of them by hand, since you then have full control over what
16751 is the proper order for these directories, which ones should be
16752 included...
16753
16754 However, in larger projects, which might involve hundreds of
16755 subdirectories, it might be more convenient to generate this list
16756 automatically.
16757
16758 The example below presents two methods. The first one, although less
16759 general, gives you more control over the list. It involves wildcard
16760 characters, that are automatically expanded by @code{make}. Its
16761 shortcoming is that you need to explicitly specify some of the
16762 organization of your project, such as for instance the directory tree
16763 depth, whether some directories are found in a separate tree,...
16764
16765 The second method is the most general one. It requires an external
16766 program, called @code{find}, which is standard on all Unix systems. All
16767 the directories found under a given root directory will be added to the
16768 list.
16769
16770 @smallexample
16771 @iftex
16772 @leftskip=0cm
16773 @font@heightrm=cmr8
16774 @heightrm
16775 @end iftex
16776 # The examples below are based on the following directory hierarchy:
16777 # All the directories can contain any number of files
16778 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16779 #                       ->  ab
16780 #                       ->  ac
16781 #                ->  b  ->  ba  ->  baa
16782 #                       ->  bb
16783 #                       ->  bc
16784 # This Makefile creates a variable called DIRS, that can be reused any time
16785 # you need this list (see the other examples in this section)
16786
16787 # The root of your project's directory hierarchy
16788 ROOT_DIRECTORY=.
16789
16790 ####
16791 # First method: specify explicitly the list of directories
16792 # This allows you to specify any subset of all the directories you need.
16793 ####
16794
16795 DIRS := a/aa/ a/ab/ b/ba/
16796
16797 ####
16798 # Second method: use wildcards
16799 # Note that the argument(s) to wildcard below should end with a '/'.
16800 # Since wildcards also return file names, we have to filter them out
16801 # to avoid duplicate directory names.
16802 # We thus use make's @code{dir} and @code{sort} functions.
16803 # It sets DIRs to the following value (note that the directories aaa and baa
16804 # are not given, unless you change the arguments to wildcard).
16805 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16806 ####
16807
16808 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16809                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16810
16811 ####
16812 # Third method: use an external program
16813 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16814 # This is the most complete command: it sets DIRs to the following value:
16815 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16816 ####
16817
16818 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16819
16820 @end smallexample
16821
16822 @node Generating the Command Line Switches
16823 @section Generating the Command Line Switches
16824
16825 @noindent
16826 Once you have created the list of directories as explained in the
16827 previous section (@pxref{Automatically Creating a List of Directories}),
16828 you can easily generate the command line arguments to pass to gnatmake.
16829
16830 For the sake of completeness, this example assumes that the source path
16831 is not the same as the object path, and that you have two separate lists
16832 of directories.
16833
16834 @smallexample
16835 # see "Automatically creating a list of directories" to create
16836 # these variables
16837 SOURCE_DIRS=
16838 OBJECT_DIRS=
16839
16840 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16841 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16842
16843 all:
16844         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16845 @end smallexample
16846
16847 @node Overcoming Command Line Length Limits
16848 @section Overcoming Command Line Length Limits
16849
16850 @noindent
16851 One problem that might be encountered on big projects is that many
16852 operating systems limit the length of the command line. It is thus hard to give
16853 gnatmake the list of source and object directories.
16854
16855 This example shows how you can set up environment variables, which will
16856 make @code{gnatmake} behave exactly as if the directories had been
16857 specified on the command line, but have a much higher length limit (or
16858 even none on most systems).
16859
16860 It assumes that you have created a list of directories in your Makefile,
16861 using one of the methods presented in
16862 @ref{Automatically Creating a List of Directories}.
16863 For the sake of completeness, we assume that the object
16864 path (where the ALI files are found) is different from the sources patch.
16865
16866 Note a small trick in the Makefile below: for efficiency reasons, we
16867 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16868 expanded immediately by @code{make}. This way we overcome the standard
16869 make behavior which is to expand the variables only when they are
16870 actually used.
16871
16872 On Windows, if you are using the standard Windows command shell, you must
16873 replace colons with semicolons in the assignments to these variables.
16874
16875 @smallexample
16876 @iftex
16877 @leftskip=0cm
16878 @font@heightrm=cmr8
16879 @heightrm
16880 @end iftex
16881 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16882 # This is the same thing as putting the -I arguments on the command line.
16883 # (the equivalent of using -aI on the command line would be to define
16884 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16885 # You can of course have different values for these variables.
16886 #
16887 # Note also that we need to keep the previous values of these variables, since
16888 # they might have been set before running 'make' to specify where the GNAT
16889 # library is installed.
16890
16891 # see "Automatically creating a list of directories" to create these
16892 # variables
16893 SOURCE_DIRS=
16894 OBJECT_DIRS=
16895
16896 empty:=
16897 space:=$@{empty@} $@{empty@}
16898 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16899 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16900 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16901 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16902 export ADA_INCLUDE_PATH
16903 export ADA_OBJECT_PATH
16904
16905 all:
16906         gnatmake main_unit
16907 @end smallexample
16908 @end ifclear
16909
16910
16911 @node Finding Memory Problems
16912 @chapter Finding Memory Problems
16913
16914 @noindent
16915 This chapter describes
16916 @ifclear vms
16917 the @command{gnatmem} tool, which can be used to track down
16918 ``memory leaks'', and
16919 @end ifclear
16920 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
16921 access values (including ``dangling references'').
16922
16923 @menu
16924 @ifclear vms
16925 * The gnatmem Tool::
16926 @end ifclear
16927 * The GNAT Debug Pool Facility::
16928 @end menu
16929
16930
16931 @ifclear vms
16932 @node The gnatmem Tool
16933 @section The @command{gnatmem} Tool
16934 @findex gnatmem
16935
16936 @noindent
16937 The @code{gnatmem} utility monitors dynamic allocation and
16938 deallocation activity in a program, and displays information about
16939 incorrect deallocations and possible sources of memory leaks.
16940 It provides three type of information:
16941 @itemize @bullet
16942 @item
16943 General information concerning memory management, such as the total
16944 number of allocations and deallocations, the amount of allocated
16945 memory and the high water mark, i.e. the largest amount of allocated
16946 memory in the course of program execution.
16947
16948 @item
16949 Backtraces for all incorrect deallocations, that is to say deallocations
16950 which do not correspond to a valid allocation.
16951
16952 @item
16953 Information on each allocation that is potentially the origin of a memory
16954 leak.
16955 @end itemize
16956
16957 @menu
16958 * Running gnatmem::
16959 * Switches for gnatmem::
16960 * Example of gnatmem Usage::
16961 @end menu
16962
16963 @node Running gnatmem
16964 @subsection Running @code{gnatmem}
16965
16966 @noindent
16967 @code{gnatmem} makes use of the output created by the special version of
16968 allocation and deallocation routines that record call information. This
16969 allows to obtain accurate dynamic memory usage history at a minimal cost to
16970 the execution speed. Note however, that @code{gnatmem} is not supported on
16971 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
16972 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
16973
16974 @noindent
16975 The @code{gnatmem} command has the form
16976
16977 @smallexample
16978    $ gnatmem [switches] user_program
16979 @end smallexample
16980
16981 @noindent
16982 The program must have been linked with the instrumented version of the
16983 allocation and deallocation routines. This is done by linking with the
16984 @file{libgmem.a} library. For correct symbolic backtrace information,
16985 the user program should be compiled with debugging options
16986 @ref{Switches for gcc}. For example to build @file{my_program}:
16987
16988 @smallexample
16989 $ gnatmake -g my_program -largs -lgmem
16990 @end smallexample
16991
16992 @noindent
16993 When running @file{my_program} the file @file{gmem.out} is produced. This file
16994 contains information about all allocations and deallocations done by the
16995 program. It is produced by the instrumented allocations and
16996 deallocations routines and will be used by @code{gnatmem}.
16997
16998 @noindent
16999 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17000 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17001 @code{-i} switch, gnatmem will assume that this file can be found in the
17002 current directory. For example, after you have executed @file{my_program},
17003 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17004
17005 @smallexample
17006 $ gnatmem my_program
17007 @end smallexample
17008
17009 @noindent
17010 This will produce the output with the following format:
17011
17012 *************** debut cc
17013 @smallexample
17014 $ gnatmem my_program
17015
17016 Global information
17017 ------------------
17018    Total number of allocations        :  45
17019    Total number of deallocations      :   6
17020    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17021    High Water Mark                    :  11.40 Kilobytes
17022
17023 .
17024 .
17025 .
17026 Allocation Root # 2
17027 -------------------
17028  Number of non freed allocations    :  11
17029  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17030  High Water Mark                    :   1.27 Kilobytes
17031  Backtrace                          :
17032    my_program.adb:23 my_program.alloc
17033 .
17034 .
17035 .
17036 @end smallexample
17037
17038 The first block of output gives general information. In this case, the
17039 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17040 Unchecked_Deallocation routine occurred.
17041
17042 @noindent
17043 Subsequent paragraphs display  information on all allocation roots.
17044 An allocation root is a specific point in the execution of the program
17045 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17046 construct. This root is represented by an execution backtrace (or subprogram
17047 call stack). By default the backtrace depth for allocations roots is 1, so
17048 that a root corresponds exactly to a source location. The backtrace can
17049 be made deeper, to make the root more specific.
17050
17051 @node Switches for gnatmem
17052 @subsection Switches for @code{gnatmem}
17053
17054 @noindent
17055 @code{gnatmem} recognizes the following switches:
17056
17057 @table @option
17058
17059 @item -q
17060 @cindex @option{-q} (@code{gnatmem})
17061 Quiet. Gives the minimum output needed to identify the origin of the
17062 memory leaks. Omits statistical information.
17063
17064 @item @var{N}
17065 @cindex @var{N} (@code{gnatmem})
17066 N is an integer literal (usually between 1 and 10) which controls the
17067 depth of the backtraces defining allocation root. The default value for
17068 N is 1. The deeper the backtrace, the more precise the localization of
17069 the root. Note that the total number of roots can depend on this
17070 parameter. This parameter must be specified @emph{before} the name of the
17071 executable to be analyzed, to avoid ambiguity.
17072
17073 @item -b n
17074 @cindex @option{-b} (@code{gnatmem})
17075 This switch has the same effect as just depth parameter.
17076
17077 @item -i @var{file}
17078 @cindex @option{-i} (@code{gnatmem})
17079 Do the @code{gnatmem} processing starting from @file{file}, rather than
17080 @file{gmem.out} in the current directory.
17081
17082 @item -m n
17083 @cindex @option{-m} (@code{gnatmem})
17084 This switch causes @code{gnatmem} to mask the allocation roots that have less
17085 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17086 examine even the roots that didn't result in leaks.
17087
17088 @item -s order
17089 @cindex @option{-s} (@code{gnatmem})
17090 This switch causes @code{gnatmem} to sort the allocation roots according to the
17091 specified order of sort criteria, each identified by a single letter. The
17092 currently supported criteria are @code{n, h, w} standing respectively for
17093 number of unfreed allocations, high watermark, and final watermark
17094 corresponding to a specific root. The default order is @code{nwh}.
17095
17096 @end table
17097
17098 @node Example of gnatmem Usage
17099 @subsection Example of @code{gnatmem} Usage
17100
17101 @noindent
17102 The following example shows the use of @code{gnatmem}
17103 on a simple memory-leaking program.
17104 Suppose that we have the following Ada program:
17105
17106 @smallexample @c ada
17107 @group
17108 @cartouche
17109 with Unchecked_Deallocation;
17110 procedure Test_Gm is
17111
17112    type T is array (1..1000) of Integer;
17113    type Ptr is access T;
17114    procedure Free is new Unchecked_Deallocation (T, Ptr);
17115    A : Ptr;
17116
17117    procedure My_Alloc is
17118    begin
17119       A := new T;
17120    end My_Alloc;
17121
17122    procedure My_DeAlloc is
17123       B : Ptr := A;
17124    begin
17125       Free (B);
17126    end My_DeAlloc;
17127
17128 begin
17129    My_Alloc;
17130    for I in 1 .. 5 loop
17131       for J in I .. 5 loop
17132          My_Alloc;
17133       end loop;
17134       My_Dealloc;
17135    end loop;
17136 end;
17137 @end cartouche
17138 @end group
17139 @end smallexample
17140
17141 @noindent
17142 The program needs to be compiled with debugging option and linked with
17143 @code{gmem} library:
17144
17145 @smallexample
17146 $ gnatmake -g test_gm -largs -lgmem
17147 @end smallexample
17148
17149 @noindent
17150 Then we execute the program as usual:
17151
17152 @smallexample
17153 $ test_gm
17154 @end smallexample
17155
17156 @noindent
17157 Then @code{gnatmem} is invoked simply with
17158 @smallexample
17159 $ gnatmem test_gm
17160 @end smallexample
17161
17162 @noindent
17163 which produces the following output (result may vary on different platforms):
17164
17165 @smallexample
17166 Global information
17167 ------------------
17168    Total number of allocations        :  18
17169    Total number of deallocations      :   5
17170    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17171    High Water Mark                    :  56.90 Kilobytes
17172
17173 Allocation Root # 1
17174 -------------------
17175  Number of non freed allocations    :  11
17176  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17177  High Water Mark                    :  46.88 Kilobytes
17178  Backtrace                          :
17179    test_gm.adb:11 test_gm.my_alloc
17180
17181 Allocation Root # 2
17182 -------------------
17183  Number of non freed allocations    :   1
17184  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17185  High Water Mark                    :  10.02 Kilobytes
17186  Backtrace                          :
17187    s-secsta.adb:81 system.secondary_stack.ss_init
17188
17189 Allocation Root # 3
17190 -------------------
17191  Number of non freed allocations    :   1
17192  Final Water Mark (non freed mem)   :  12 Bytes
17193  High Water Mark                    :  12 Bytes
17194  Backtrace                          :
17195    s-secsta.adb:181 system.secondary_stack.ss_init
17196 @end smallexample
17197
17198 @noindent
17199 Note that the GNAT run time contains itself a certain number of
17200 allocations that have no  corresponding deallocation,
17201 as shown here for root #2 and root
17202 #3. This is a normal behavior when the number of non freed allocations
17203 is one, it allocates dynamic data structures that the run time needs for
17204 the complete lifetime of the program. Note also that there is only one
17205 allocation root in the user program with a single line back trace:
17206 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17207 program shows that 'My_Alloc' is called at 2 different points in the
17208 source (line 21 and line 24). If those two allocation roots need to be
17209 distinguished, the backtrace depth parameter can be used:
17210
17211 @smallexample
17212 $ gnatmem 3 test_gm
17213 @end smallexample
17214
17215 @noindent
17216 which will give the following output:
17217
17218 @smallexample
17219 Global information
17220 ------------------
17221    Total number of allocations        :  18
17222    Total number of deallocations      :   5
17223    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17224    High Water Mark                    :  56.90 Kilobytes
17225
17226 Allocation Root # 1
17227 -------------------
17228  Number of non freed allocations    :  10
17229  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17230  High Water Mark                    :  42.97 Kilobytes
17231  Backtrace                          :
17232    test_gm.adb:11 test_gm.my_alloc
17233    test_gm.adb:24 test_gm
17234    b_test_gm.c:52 main
17235
17236 Allocation Root # 2
17237 -------------------
17238  Number of non freed allocations    :   1
17239  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17240  High Water Mark                    :  10.02 Kilobytes
17241  Backtrace                          :
17242    s-secsta.adb:81  system.secondary_stack.ss_init
17243    s-secsta.adb:283 <system__secondary_stack___elabb>
17244    b_test_gm.c:33   adainit
17245
17246 Allocation Root # 3
17247 -------------------
17248  Number of non freed allocations    :   1
17249  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17250  High Water Mark                    :   3.91 Kilobytes
17251  Backtrace                          :
17252    test_gm.adb:11 test_gm.my_alloc
17253    test_gm.adb:21 test_gm
17254    b_test_gm.c:52 main
17255
17256 Allocation Root # 4
17257 -------------------
17258  Number of non freed allocations    :   1
17259  Final Water Mark (non freed mem)   :  12 Bytes
17260  High Water Mark                    :  12 Bytes
17261  Backtrace                          :
17262    s-secsta.adb:181 system.secondary_stack.ss_init
17263    s-secsta.adb:283 <system__secondary_stack___elabb>
17264    b_test_gm.c:33   adainit
17265 @end smallexample
17266
17267 @noindent
17268 The allocation root #1 of the first example has been split in 2 roots #1
17269 and #3 thanks to the more precise associated backtrace.
17270
17271 @end ifclear
17272
17273
17274 @node The GNAT Debug Pool Facility
17275 @section The GNAT Debug Pool Facility
17276 @findex Debug Pool
17277 @cindex storage, pool, memory corruption
17278
17279 @noindent
17280 The use of unchecked deallocation and unchecked conversion can easily
17281 lead to incorrect memory references. The problems generated by such
17282 references are usually difficult to tackle because the symptoms can be
17283 very remote from the origin of the problem. In such cases, it is
17284 very helpful to detect the problem as early as possible. This is the
17285 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17286
17287 In order to use the GNAT specific debugging pool, the user must
17288 associate a debug pool object with each of the access types that may be
17289 related to suspected memory problems. See Ada Reference Manual 13.11.
17290 @smallexample @c ada
17291 type Ptr is access Some_Type;
17292 Pool : GNAT.Debug_Pools.Debug_Pool;
17293 for Ptr'Storage_Pool use Pool;
17294 @end smallexample
17295
17296 @noindent
17297 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17298 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17299 allow the user to redefine allocation and deallocation strategies. They
17300 also provide a checkpoint for each dereference, through the use of
17301 the primitive operation @code{Dereference} which is implicitly called at
17302 each dereference of an access value.
17303
17304 Once an access type has been associated with a debug pool, operations on
17305 values of the type may raise four distinct exceptions,
17306 which correspond to four potential kinds of memory corruption:
17307 @itemize @bullet
17308 @item
17309 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17310 @item
17311 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17312 @item
17313 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17314 @item
17315 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17316 @end itemize
17317
17318 @noindent
17319 For types associated with a Debug_Pool, dynamic allocation is performed using
17320 the standard
17321 GNAT allocation routine. References to all allocated chunks of memory
17322 are kept in an internal dictionary.
17323 Several deallocation strategies are provided, whereupon the user can choose
17324 to release the memory to the system, keep it allocated for further invalid
17325 access checks, or fill it with an easily recognizable pattern for debug
17326 sessions.
17327 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17328
17329 See the documentation in the file g-debpoo.ads for more information on the
17330 various strategies.
17331
17332 Upon each dereference, a check is made that the access value denotes a
17333 properly allocated memory location. Here is a complete example of use of
17334 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17335 @smallexample @c ada
17336 @iftex
17337 @leftskip=0cm
17338 @end iftex
17339 with Gnat.Io; use Gnat.Io;
17340 with Unchecked_Deallocation;
17341 with Unchecked_Conversion;
17342 with GNAT.Debug_Pools;
17343 with System.Storage_Elements;
17344 with Ada.Exceptions; use Ada.Exceptions;
17345 procedure Debug_Pool_Test is
17346
17347    type T is access Integer;
17348    type U is access all T;
17349
17350    P : GNAT.Debug_Pools.Debug_Pool;
17351    for T'Storage_Pool use P;
17352
17353    procedure Free is new Unchecked_Deallocation (Integer, T);
17354    function UC is new Unchecked_Conversion (U, T);
17355    A, B : aliased T;
17356
17357    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17358
17359 begin
17360    Info (P);
17361    A := new Integer;
17362    B := new Integer;
17363    B := A;
17364    Info (P);
17365    Free (A);
17366    begin
17367       Put_Line (Integer'Image(B.all));
17368    exception
17369       when E : others => Put_Line ("raised: " & Exception_Name (E));
17370    end;
17371    begin
17372       Free (B);
17373    exception
17374       when E : others => Put_Line ("raised: " & Exception_Name (E));
17375    end;
17376    B := UC(A'Access);
17377    begin
17378       Put_Line (Integer'Image(B.all));
17379    exception
17380       when E : others => Put_Line ("raised: " & Exception_Name (E));
17381    end;
17382    begin
17383       Free (B);
17384    exception
17385       when E : others => Put_Line ("raised: " & Exception_Name (E));
17386    end;
17387    Info (P);
17388 end Debug_Pool_Test;
17389 @end smallexample
17390
17391 @noindent
17392 The debug pool mechanism provides the following precise diagnostics on the
17393 execution of this erroneous program:
17394 @smallexample
17395 Debug Pool info:
17396   Total allocated bytes :  0
17397   Total deallocated bytes :  0
17398   Current Water Mark:  0
17399   High Water Mark:  0
17400
17401 Debug Pool info:
17402   Total allocated bytes :  8
17403   Total deallocated bytes :  0
17404   Current Water Mark:  8
17405   High Water Mark:  8
17406
17407 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17408 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17409 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17410 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17411 Debug Pool info:
17412   Total allocated bytes :  8
17413   Total deallocated bytes :  4
17414   Current Water Mark:  4
17415   High Water Mark:  8
17416 @end smallexample
17417
17418
17419 @node Creating Sample Bodies Using gnatstub
17420 @chapter Creating Sample Bodies Using @command{gnatstub}
17421 @findex gnatstub
17422
17423 @noindent
17424 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17425 for library unit declarations.
17426
17427 To create a body stub, @command{gnatstub} has to compile the library
17428 unit declaration. Therefore, bodies can be created only for legal
17429 library units. Moreover, if a library unit depends semantically upon
17430 units located outside the current directory, you have to provide
17431 the source search path when calling @command{gnatstub}, see the description
17432 of @command{gnatstub} switches below.
17433
17434 @menu
17435 * Running gnatstub::
17436 * Switches for gnatstub::
17437 @end menu
17438
17439 @node Running gnatstub
17440 @section Running @command{gnatstub}
17441
17442 @noindent
17443 @command{gnatstub} has the command-line interface of the form
17444
17445 @smallexample
17446 $ gnatstub [switches] filename [directory]
17447 @end smallexample
17448
17449 @noindent
17450 where
17451 @table @emph
17452 @item filename
17453 is the name of the source file that contains a library unit declaration
17454 for which a body must be created. The file name may contain the path
17455 information.
17456 The file name does not have to follow the GNAT file name conventions. If the
17457 name
17458 does not follow GNAT file naming conventions, the name of the body file must
17459 be provided
17460 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17461 If the file name follows the GNAT file naming
17462 conventions and the name of the body file is not provided,
17463 @command{gnatstub}
17464 creates the name
17465 of the body file from the argument file name by replacing the @file{.ads}
17466 suffix
17467 with the @file{.adb} suffix.
17468
17469 @item directory
17470 indicates the directory in which the body stub is to be placed (the default
17471 is the
17472 current directory)
17473
17474 @item switches
17475 is an optional sequence of switches as described in the next section
17476 @end table
17477
17478 @node Switches for gnatstub
17479 @section Switches for @command{gnatstub}
17480
17481 @table @option
17482 @c !sort!
17483
17484 @item ^-f^/FULL^
17485 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17486 If the destination directory already contains a file with the name of the
17487 body file
17488 for the argument spec file, replace it with the generated body stub.
17489
17490 @item ^-hs^/HEADER=SPEC^
17491 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17492 Put the comment header (i.e., all the comments preceding the
17493 compilation unit) from the source of the library unit declaration
17494 into the body stub.
17495
17496 @item ^-hg^/HEADER=GENERAL^
17497 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17498 Put a sample comment header into the body stub.
17499
17500 @ifclear vms
17501 @item -IDIR
17502 @cindex @option{-IDIR} (@command{gnatstub})
17503 @itemx -I-
17504 @cindex @option{-I-} (@command{gnatstub})
17505 @end ifclear
17506 @ifset vms
17507 @item /NOCURRENT_DIRECTORY
17508 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17509 @end ifset
17510 ^These switches have ^This switch has^ the same meaning as in calls to
17511 @command{gcc}.
17512 ^They define ^It defines ^ the source search path in the call to
17513 @command{gcc} issued
17514 by @command{gnatstub} to compile an argument source file.
17515
17516 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17517 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17518 This switch has the same meaning as in calls to @command{gcc}.
17519 It defines the additional configuration file to be passed to the call to
17520 @command{gcc} issued
17521 by @command{gnatstub} to compile an argument source file.
17522
17523 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17524 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17525 (@var{n} is a non-negative integer). Set the maximum line length in the
17526 body stub to @var{n}; the default is 79. The maximum value that can be
17527 specified is 32767.
17528
17529 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17530 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17531 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17532 the generated body sample to @var{n}.
17533 The default indentation is 3.
17534
17535 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17536 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17537 Order local bodies alphabetically. (By default local bodies are ordered
17538 in the same way as the corresponding local specs in the argument spec file.)
17539
17540 @item ^-i^/INDENTATION=^@var{n}
17541 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17542 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17543
17544 @item ^-k^/TREE_FILE=SAVE^
17545 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17546 Do not remove the tree file (i.e., the snapshot of the compiler internal
17547 structures used by @command{gnatstub}) after creating the body stub.
17548
17549 @item ^-l^/LINE_LENGTH=^@var{n}
17550 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17551 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17552
17553 @item ^-o^/BODY=^@var{body-name}
17554 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17555 Body file name.  This should be set if the argument file name does not
17556 follow
17557 the GNAT file naming
17558 conventions. If this switch is omitted the default name for the body will be
17559 obtained
17560 from the argument file name according to the GNAT file naming conventions.
17561
17562 @item ^-q^/QUIET^
17563 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17564 Quiet mode: do not generate a confirmation when a body is
17565 successfully created, and do not generate a message when a body is not
17566 required for an
17567 argument unit.
17568
17569 @item ^-r^/TREE_FILE=REUSE^
17570 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17571 Reuse the tree file (if it exists) instead of creating it.  Instead of
17572 creating the tree file for the library unit declaration, @command{gnatstub}
17573 tries to find it in the current directory and use it for creating
17574 a body. If the tree file is not found, no body is created. This option
17575 also implies @option{^-k^/SAVE^}, whether or not
17576 the latter is set explicitly.
17577
17578 @item ^-t^/TREE_FILE=OVERWRITE^
17579 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17580 Overwrite the existing tree file.  If the current directory already
17581 contains the file which, according to the GNAT file naming rules should
17582 be considered as a tree file for the argument source file,
17583 @command{gnatstub}
17584 will refuse to create the tree file needed to create a sample body
17585 unless this option is set.
17586
17587 @item ^-v^/VERBOSE^
17588 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17589 Verbose mode: generate version information.
17590
17591 @end table
17592
17593
17594 @node Other Utility Programs
17595 @chapter Other Utility Programs
17596
17597 @noindent
17598 This chapter discusses some other utility programs available in the Ada
17599 environment.
17600
17601 @menu
17602 * Using Other Utility Programs with GNAT::
17603 * The External Symbol Naming Scheme of GNAT::
17604 @ifclear vms
17605 * Ada Mode for Glide::
17606 @end ifclear
17607 * Converting Ada Files to html with gnathtml::
17608 * Installing gnathtml::
17609 @ifset vms
17610 * LSE::
17611 * Profiling::
17612 @end ifset
17613 @end menu
17614
17615 @node Using Other Utility Programs with GNAT
17616 @section Using Other Utility Programs with GNAT
17617
17618 @noindent
17619 The object files generated by GNAT are in standard system format and in
17620 particular the debugging information uses this format. This means
17621 programs generated by GNAT can be used with existing utilities that
17622 depend on these formats.
17623
17624 @ifclear vms
17625 In general, any utility program that works with C will also often work with
17626 Ada programs generated by GNAT. This includes software utilities such as
17627 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17628 as Purify.
17629 @end ifclear
17630
17631 @node The External Symbol Naming Scheme of GNAT
17632 @section The External Symbol Naming Scheme of GNAT
17633
17634 @noindent
17635 In order to interpret the output from GNAT, when using tools that are
17636 originally intended for use with other languages, it is useful to
17637 understand the conventions used to generate link names from the Ada
17638 entity names.
17639
17640 All link names are in all lowercase letters. With the exception of library
17641 procedure names, the mechanism used is simply to use the full expanded
17642 Ada name with dots replaced by double underscores. For example, suppose
17643 we have the following package spec:
17644
17645 @smallexample @c ada
17646 @group
17647 @cartouche
17648 package QRS is
17649    MN : Integer;
17650 end QRS;
17651 @end cartouche
17652 @end group
17653 @end smallexample
17654
17655 @noindent
17656 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17657 the corresponding link name is @code{qrs__mn}.
17658 @findex Export
17659 Of course if a @code{pragma Export} is used this may be overridden:
17660
17661 @smallexample @c ada
17662 @group
17663 @cartouche
17664 package Exports is
17665    Var1 : Integer;
17666    pragma Export (Var1, C, External_Name => "var1_name");
17667    Var2 : Integer;
17668    pragma Export (Var2, C, Link_Name => "var2_link_name");
17669 end Exports;
17670 @end cartouche
17671 @end group
17672 @end smallexample
17673
17674 @noindent
17675 In this case, the link name for @var{Var1} is whatever link name the
17676 C compiler would assign for the C function @var{var1_name}. This typically
17677 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17678 system conventions, but other possibilities exist. The link name for
17679 @var{Var2} is @var{var2_link_name}, and this is not operating system
17680 dependent.
17681
17682 @findex _main
17683 One exception occurs for library level procedures. A potential ambiguity
17684 arises between the required name @code{_main} for the C main program,
17685 and the name we would otherwise assign to an Ada library level procedure
17686 called @code{Main} (which might well not be the main program).
17687
17688 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17689 names. So if we have a library level procedure such as
17690
17691 @smallexample @c ada
17692 @group
17693 @cartouche
17694 procedure Hello (S : String);
17695 @end cartouche
17696 @end group
17697 @end smallexample
17698
17699 @noindent
17700 the external name of this procedure will be @var{_ada_hello}.
17701
17702 @ifclear vms
17703 @node Ada Mode for Glide
17704 @section Ada Mode for @code{Glide}
17705 @cindex Ada mode (for Glide)
17706
17707 @noindent
17708 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
17709 user to understand and navigate existing code, and facilitates writing
17710 new code. It furthermore provides some utility functions for easier
17711 integration of standard Emacs features when programming in Ada.
17712
17713 Its general features include:
17714
17715 @itemize @bullet
17716 @item
17717 An Integrated Development Environment with functionality such as the
17718 following
17719
17720 @itemize @bullet
17721 @item
17722 ``Project files'' for configuration-specific aspects
17723 (e.g. directories and compilation options)
17724
17725 @item
17726 Compiling and stepping through error messages.
17727
17728 @item
17729 Running and debugging an applications within Glide.
17730 @end itemize
17731
17732 @item
17733 Pull-down menus
17734
17735 @item
17736 User configurability
17737 @end itemize
17738
17739 Some of the specific Ada mode features are:
17740
17741 @itemize @bullet
17742 @item
17743 Functions for easy and quick stepping through Ada code
17744
17745 @item
17746 Getting cross reference information for identifiers (e.g., finding a
17747 defining occurrence)
17748
17749 @item
17750 Displaying an index menu of types and subprograms, allowing
17751 direct selection for browsing
17752
17753 @item
17754 Automatic color highlighting of the various Ada entities
17755 @end itemize
17756
17757 Glide directly supports writing Ada code, via several facilities:
17758
17759 @itemize @bullet
17760 @item
17761 Switching between spec and body files with possible
17762 autogeneration of body files
17763
17764 @item
17765 Automatic formating of subprogram parameter lists
17766
17767 @item
17768 Automatic indentation according to Ada syntax
17769
17770 @item
17771 Automatic completion of identifiers
17772
17773 @item
17774 Automatic (and configurable) casing of identifiers, keywords, and attributes
17775
17776 @item
17777 Insertion of syntactic templates
17778
17779 @item
17780 Block commenting / uncommenting
17781 @end itemize
17782
17783 @noindent
17784 For more information, please refer to the online documentation
17785 available in the @code{Glide} @result{} @code{Help} menu.
17786 @end ifclear
17787
17788
17789 @node Converting Ada Files to html with gnathtml
17790 @section Converting Ada Files to HTML with @code{gnathtml}
17791
17792 @noindent
17793 This @code{Perl} script allows Ada source files to be browsed using
17794 standard Web browsers. For installation procedure, see the section
17795 @xref{Installing gnathtml}.
17796
17797 Ada reserved keywords are highlighted in a bold font and Ada comments in
17798 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17799 switch to suppress the generation of cross-referencing information, user
17800 defined variables and types will appear in a different color; you will
17801 be able to click on any identifier and go to its declaration.
17802
17803 The command line is as follow:
17804 @smallexample
17805 $ perl gnathtml.pl [switches] ada-files
17806 @end smallexample
17807
17808 @noindent
17809 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17810 an html file for every ada file, and a global file called @file{index.htm}.
17811 This file is an index of every identifier defined in the files.
17812
17813 The available switches are the following ones :
17814
17815 @table @option
17816 @item -83
17817 @cindex @option{-83} (@code{gnathtml})
17818 Only the subset on the Ada 83 keywords will be highlighted, not the full
17819 Ada 95 keywords set.
17820
17821 @item -cc @var{color}
17822 @cindex @option{-cc} (@code{gnathtml})
17823 This option allows you to change the color used for comments. The default
17824 value is green. The color argument can be any name accepted by html.
17825
17826 @item -d
17827 @cindex @option{-d} (@code{gnathtml})
17828 If the ada files depend on some other files (using for instance the
17829 @code{with} command, the latter will also be converted to html.
17830 Only the files in the user project will be converted to html, not the files
17831 in the run-time library itself.
17832
17833 @item -D
17834 @cindex @option{-D} (@code{gnathtml})
17835 This command is the same as @option{-d} above, but @command{gnathtml} will
17836 also look for files in the run-time library, and generate html files for them.
17837
17838 @item -ext @var{extension}
17839 @cindex @option{-ext} (@code{gnathtml})
17840 This option allows you to change the extension of the generated HTML files.
17841 If you do not specify an extension, it will default to @file{htm}.
17842
17843 @item -f
17844 @cindex @option{-f} (@code{gnathtml})
17845 By default, gnathtml will generate html links only for global entities
17846 ('with'ed units, global variables and types,...). If you specify the
17847 @option{-f} on the command line, then links will be generated for local
17848 entities too.
17849
17850 @item -l @var{number}
17851 @cindex @option{-l} (@code{gnathtml})
17852 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
17853 will number the html files every @var{number} line.
17854
17855 @item -I @var{dir}
17856 @cindex @option{-I} (@code{gnathtml})
17857 Specify a directory to search for library files (@file{.ALI} files) and
17858 source files. You can provide several -I switches on the command line,
17859 and the directories will be parsed in the order of the command line.
17860
17861 @item -o @var{dir}
17862 @cindex @option{-o} (@code{gnathtml})
17863 Specify the output directory for html files. By default, gnathtml will
17864 saved the generated html files in a subdirectory named @file{html/}.
17865
17866 @item -p @var{file}
17867 @cindex @option{-p} (@code{gnathtml})
17868 If you are using Emacs and the most recent Emacs Ada mode, which provides
17869 a full Integrated Development Environment for compiling, checking,
17870 running and debugging applications, you may use @file{.gpr} files
17871 to give the directories where Emacs can find sources and object files.
17872
17873 Using this switch, you can tell gnathtml to use these files. This allows
17874 you to get an html version of your application, even if it is spread
17875 over multiple directories.
17876
17877 @item -sc @var{color}
17878 @cindex @option{-sc} (@code{gnathtml})
17879 This option allows you to change the color used for symbol definitions.
17880 The default value is red. The color argument can be any name accepted by html.
17881
17882 @item -t @var{file}
17883 @cindex @option{-t} (@code{gnathtml})
17884 This switch provides the name of a file. This file contains a list of
17885 file names to be converted, and the effect is exactly as though they had
17886 appeared explicitly on the command line. This
17887 is the recommended way to work around the command line length limit on some
17888 systems.
17889
17890 @end table
17891
17892 @node Installing gnathtml
17893 @section Installing @code{gnathtml}
17894
17895 @noindent
17896 @code{Perl} needs to be installed on your machine to run this script.
17897 @code{Perl} is freely available for almost every architecture and
17898 Operating System via the Internet.
17899
17900 On Unix systems, you  may want to modify  the  first line of  the script
17901 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17902 is. The syntax of this line is :
17903 @smallexample
17904 #!full_path_name_to_perl
17905 @end smallexample
17906
17907 @noindent
17908 Alternatively, you may run the script using the following command line:
17909
17910 @smallexample
17911 $ perl gnathtml.pl [switches] files
17912 @end smallexample
17913
17914 @ifset vms
17915 @node LSE
17916 @section LSE
17917 @findex LSE
17918
17919 @noindent
17920 The GNAT distribution provides an Ada 95 template for the Digital Language
17921 Sensitive Editor (LSE), a component of DECset. In order to
17922 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
17923
17924 @node Profiling
17925 @section Profiling
17926 @findex PCA
17927
17928 @noindent
17929 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
17930 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
17931 the collection phase with the /DEBUG qualifier.
17932
17933 @smallexample
17934 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
17935 $ DEFINE LIB$DEBUG PCA$COLLECTOR
17936 $ RUN/DEBUG <PROGRAM_NAME>
17937 @end smallexample
17938 @noindent
17939 @end ifset
17940
17941 @node Running and Debugging Ada Programs
17942 @chapter Running and Debugging Ada Programs
17943 @cindex Debugging
17944
17945 @noindent
17946 This chapter discusses how to debug Ada programs. An incorrect Ada program
17947 may be handled in three ways by the GNAT compiler:
17948
17949 @enumerate
17950 @item
17951 The illegality may be a violation of the static semantics of Ada. In
17952 that case GNAT diagnoses the constructs in the program that are illegal.
17953 It is then a straightforward matter for the user to modify those parts of
17954 the program.
17955
17956 @item
17957 The illegality may be a violation of the dynamic semantics of Ada. In
17958 that case the program compiles and executes, but may generate incorrect
17959 results, or may terminate abnormally with some exception.
17960
17961 @item
17962 When presented with a program that contains convoluted errors, GNAT
17963 itself may terminate abnormally without providing full diagnostics on
17964 the incorrect user program.
17965 @end enumerate
17966
17967 @menu
17968 * The GNAT Debugger GDB::
17969 * Running GDB::
17970 * Introduction to GDB Commands::
17971 * Using Ada Expressions::
17972 * Calling User-Defined Subprograms::
17973 * Using the Next Command in a Function::
17974 * Ada Exceptions::
17975 * Ada Tasks::
17976 * Debugging Generic Units::
17977 * GNAT Abnormal Termination or Failure to Terminate::
17978 * Naming Conventions for GNAT Source Files::
17979 * Getting Internal Debugging Information::
17980 * Stack Traceback::
17981 @end menu
17982
17983 @cindex Debugger
17984 @findex gdb
17985
17986 @node The GNAT Debugger GDB
17987 @section The GNAT Debugger GDB
17988
17989 @noindent
17990 @code{GDB} is a general purpose, platform-independent debugger that
17991 can be used to debug mixed-language programs compiled with @code{GCC},
17992 and in particular is capable of debugging Ada programs compiled with
17993 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
17994 complex Ada data structures.
17995
17996 The manual @cite{Debugging with GDB}
17997 @ifset vms
17998 , located in the GNU:[DOCS] directory,
17999 @end ifset
18000 contains full details on the usage of @code{GDB}, including a section on
18001 its usage on programs. This manual should be consulted for full
18002 details. The section that follows is a brief introduction to the
18003 philosophy and use of @code{GDB}.
18004
18005 When GNAT programs are compiled, the compiler optionally writes debugging
18006 information into the generated object file, including information on
18007 line numbers, and on declared types and variables. This information is
18008 separate from the generated code. It makes the object files considerably
18009 larger, but it does not add to the size of the actual executable that
18010 will be loaded into memory, and has no impact on run-time performance. The
18011 generation of debug information is triggered by the use of the
18012 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18013 the compilations. It is important to emphasize that the use of these
18014 options does not change the generated code.
18015
18016 The debugging information is written in standard system formats that
18017 are used by many tools, including debuggers and profilers. The format
18018 of the information is typically designed to describe C types and
18019 semantics, but GNAT implements a translation scheme which allows full
18020 details about Ada types and variables to be encoded into these
18021 standard C formats. Details of this encoding scheme may be found in
18022 the file exp_dbug.ads in the GNAT source distribution. However, the
18023 details of this encoding are, in general, of no interest to a user,
18024 since @code{GDB} automatically performs the necessary decoding.
18025
18026 When a program is bound and linked, the debugging information is
18027 collected from the object files, and stored in the executable image of
18028 the program. Again, this process significantly increases the size of
18029 the generated executable file, but it does not increase the size of
18030 the executable program itself. Furthermore, if this program is run in
18031 the normal manner, it runs exactly as if the debug information were
18032 not present, and takes no more actual memory.
18033
18034 However, if the program is run under control of @code{GDB}, the
18035 debugger is activated.  The image of the program is loaded, at which
18036 point it is ready to run.  If a run command is given, then the program
18037 will run exactly as it would have if @code{GDB} were not present. This
18038 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18039 entirely non-intrusive until a breakpoint is encountered.  If no
18040 breakpoint is ever hit, the program will run exactly as it would if no
18041 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18042 the debugging information and can respond to user commands to inspect
18043 variables, and more generally to report on the state of execution.
18044
18045 @c **************
18046 @node Running GDB
18047 @section Running GDB
18048
18049 @noindent
18050 The debugger can be launched directly and simply from @code{glide} or
18051 through its graphical interface: @code{gvd}. It can also be used
18052 directly in text mode. Here is described the basic use of @code{GDB}
18053 in text mode. All the commands described below can be used in the
18054 @code{gvd} console window even though there is usually other more
18055 graphical ways to achieve the same goals.
18056
18057 @ifclear vms
18058 @noindent
18059 The command to run the graphical interface of the debugger is
18060 @smallexample
18061 $ gvd program
18062 @end smallexample
18063 @end ifclear
18064
18065 @noindent
18066 The command to run @code{GDB} in text mode is
18067
18068 @smallexample
18069 $ ^gdb program^$ GDB PROGRAM^
18070 @end smallexample
18071
18072 @noindent
18073 where @code{^program^PROGRAM^} is the name of the executable file. This
18074 activates the debugger and results in a prompt for debugger commands.
18075 The simplest command is simply @code{run}, which causes the program to run
18076 exactly as if the debugger were not present. The following section
18077 describes some of the additional commands that can be given to @code{GDB}.
18078
18079
18080 @c *******************************
18081 @node Introduction to GDB Commands
18082 @section Introduction to GDB Commands
18083
18084 @noindent
18085 @code{GDB} contains a large repertoire of commands. The manual
18086 @cite{Debugging with GDB}
18087 @ifset vms
18088 , located in the GNU:[DOCS] directory,
18089 @end ifset
18090 includes extensive documentation on the use
18091 of these commands, together with examples of their use. Furthermore,
18092 the command @var{help} invoked from within @code{GDB} activates a simple help
18093 facility which summarizes the available commands and their options.
18094 In this section we summarize a few of the most commonly
18095 used commands to give an idea of what @code{GDB} is about. You should create
18096 a simple program with debugging information and experiment with the use of
18097 these @code{GDB} commands on the program as you read through the
18098 following section.
18099
18100 @table @code
18101 @item set args @var{arguments}
18102 The @var{arguments} list above is a list of arguments to be passed to
18103 the program on a subsequent run command, just as though the arguments
18104 had been entered on a normal invocation of the program. The @code{set args}
18105 command is not needed if the program does not require arguments.
18106
18107 @item run
18108 The @code{run} command causes execution of the program to start from
18109 the beginning. If the program is already running, that is to say if
18110 you are currently positioned at a breakpoint, then a prompt will ask
18111 for confirmation that you want to abandon the current execution and
18112 restart.
18113
18114 @item breakpoint @var{location}
18115 The breakpoint command sets a breakpoint, that is to say a point at which
18116 execution will halt and @code{GDB} will await further
18117 commands. @var{location} is
18118 either a line number within a file, given in the format @code{file:linenumber},
18119 or it is the name of a subprogram. If you request that a breakpoint be set on
18120 a subprogram that is overloaded, a prompt will ask you to specify on which of
18121 those subprograms you want to breakpoint. You can also
18122 specify that all of them should be breakpointed. If the program is run
18123 and execution encounters the breakpoint, then the program
18124 stops and @code{GDB} signals that the breakpoint was encountered by
18125 printing the line of code before which the program is halted.
18126
18127 @item breakpoint exception @var{name}
18128 A special form of the breakpoint command which breakpoints whenever
18129 exception @var{name} is raised.
18130 If @var{name} is omitted,
18131 then a breakpoint will occur when any exception is raised.
18132
18133 @item print @var{expression}
18134 This will print the value of the given expression. Most simple
18135 Ada expression formats are properly handled by @code{GDB}, so the expression
18136 can contain function calls, variables, operators, and attribute references.
18137
18138 @item continue
18139 Continues execution following a breakpoint, until the next breakpoint or the
18140 termination of the program.
18141
18142 @item step
18143 Executes a single line after a breakpoint. If the next statement
18144 is a subprogram call, execution continues into (the first statement of)
18145 the called subprogram.
18146
18147 @item next
18148 Executes a single line. If this line is a subprogram call, executes and
18149 returns from the call.
18150
18151 @item list
18152 Lists a few lines around the current source location. In practice, it
18153 is usually more convenient to have a separate edit window open with the
18154 relevant source file displayed. Successive applications of this command
18155 print subsequent lines. The command can be given an argument which is a
18156 line number, in which case it displays a few lines around the specified one.
18157
18158 @item backtrace
18159 Displays a backtrace of the call chain. This command is typically
18160 used after a breakpoint has occurred, to examine the sequence of calls that
18161 leads to the current breakpoint. The display includes one line for each
18162 activation record (frame) corresponding to an active subprogram.
18163
18164 @item up
18165 At a breakpoint, @code{GDB} can display the values of variables local
18166 to the current frame. The command @code{up} can be used to
18167 examine the contents of other active frames, by moving the focus up
18168 the stack, that is to say from callee to caller, one frame at a time.
18169
18170 @item down
18171 Moves the focus of @code{GDB} down from the frame currently being
18172 examined to the frame of its callee (the reverse of the previous command),
18173
18174 @item frame @var{n}
18175 Inspect the frame with the given number. The value 0 denotes the frame
18176 of the current breakpoint, that is to say the top of the call stack.
18177
18178 @end table
18179
18180 The above list is a very short introduction to the commands that
18181 @code{GDB} provides. Important additional capabilities, including conditional
18182 breakpoints, the ability to execute command sequences on a breakpoint,
18183 the ability to debug at the machine instruction level and many other
18184 features are described in detail in @cite{Debugging with GDB}.
18185 Note that most commands can be abbreviated
18186 (for example, c for continue, bt for backtrace).
18187
18188 @node Using Ada Expressions
18189 @section Using Ada Expressions
18190 @cindex Ada expressions
18191
18192 @noindent
18193 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18194 extensions. The philosophy behind the design of this subset is
18195
18196 @itemize @bullet
18197 @item
18198 That @code{GDB} should provide basic literals and access to operations for
18199 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18200 leaving more sophisticated computations to subprograms written into the
18201 program (which therefore may be called from @code{GDB}).
18202
18203 @item
18204 That type safety and strict adherence to Ada language restrictions
18205 are not particularly important to the @code{GDB} user.
18206
18207 @item
18208 That brevity is important to the @code{GDB} user.
18209 @end itemize
18210
18211 Thus, for brevity, the debugger acts as if there were
18212 implicit @code{with} and @code{use} clauses in effect for all user-written
18213 packages, thus making it unnecessary to fully qualify most names with
18214 their packages, regardless of context. Where this causes ambiguity,
18215 @code{GDB} asks the user's intent.
18216
18217 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18218
18219 @node Calling User-Defined Subprograms
18220 @section Calling User-Defined Subprograms
18221
18222 @noindent
18223 An important capability of @code{GDB} is the ability to call user-defined
18224 subprograms while debugging. This is achieved simply by entering
18225 a subprogram call statement in the form:
18226
18227 @smallexample
18228 call subprogram-name (parameters)
18229 @end smallexample
18230
18231 @noindent
18232 The keyword @code{call} can be omitted in the normal case where the
18233 @code{subprogram-name} does not coincide with any of the predefined
18234 @code{GDB} commands.
18235
18236 The effect is to invoke the given subprogram, passing it the
18237 list of parameters that is supplied. The parameters can be expressions and
18238 can include variables from the program being debugged. The
18239 subprogram must be defined
18240 at the library level within your program, and @code{GDB} will call the
18241 subprogram within the environment of your program execution (which
18242 means that the subprogram is free to access or even modify variables
18243 within your program).
18244
18245 The most important use of this facility is in allowing the inclusion of
18246 debugging routines that are tailored to particular data structures
18247 in your program. Such debugging routines can be written to provide a suitably
18248 high-level description of an abstract type, rather than a low-level dump
18249 of its physical layout. After all, the standard
18250 @code{GDB print} command only knows the physical layout of your
18251 types, not their abstract meaning. Debugging routines can provide information
18252 at the desired semantic level and are thus enormously useful.
18253
18254 For example, when debugging GNAT itself, it is crucial to have access to
18255 the contents of the tree nodes used to represent the program internally.
18256 But tree nodes are represented simply by an integer value (which in turn
18257 is an index into a table of nodes).
18258 Using the @code{print} command on a tree node would simply print this integer
18259 value, which is not very useful. But the PN routine (defined in file
18260 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18261 a useful high level representation of the tree node, which includes the
18262 syntactic category of the node, its position in the source, the integers
18263 that denote descendant nodes and parent node, as well as varied
18264 semantic information. To study this example in more detail, you might want to
18265 look at the body of the PN procedure in the stated file.
18266
18267 @node Using the Next Command in a Function
18268 @section Using the Next Command in a Function
18269
18270 @noindent
18271 When you use the @code{next} command in a function, the current source
18272 location will advance to the next statement as usual. A special case
18273 arises in the case of a @code{return} statement.
18274
18275 Part of the code for a return statement is the ``epilog'' of the function.
18276 This is the code that returns to the caller. There is only one copy of
18277 this epilog code, and it is typically associated with the last return
18278 statement in the function if there is more than one return. In some
18279 implementations, this epilog is associated with the first statement
18280 of the function.
18281
18282 The result is that if you use the @code{next} command from a return
18283 statement that is not the last return statement of the function you
18284 may see a strange apparent jump to the last return statement or to
18285 the start of the function. You should simply ignore this odd jump.
18286 The value returned is always that from the first return statement
18287 that was stepped through.
18288
18289 @node Ada Exceptions
18290 @section Breaking on Ada Exceptions
18291 @cindex Exceptions
18292
18293 @noindent
18294 You can set breakpoints that trip when your program raises
18295 selected exceptions.
18296
18297 @table @code
18298 @item break exception
18299 Set a breakpoint that trips whenever (any task in the) program raises
18300 any exception.
18301
18302 @item break exception @var{name}
18303 Set a breakpoint that trips whenever (any task in the) program raises
18304 the exception @var{name}.
18305
18306 @item break exception unhandled
18307 Set a breakpoint that trips whenever (any task in the) program raises an
18308 exception for which there is no handler.
18309
18310 @item info exceptions
18311 @itemx info exceptions @var{regexp}
18312 The @code{info exceptions} command permits the user to examine all defined
18313 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18314 argument, prints out only those exceptions whose name matches @var{regexp}.
18315 @end table
18316
18317 @node Ada Tasks
18318 @section Ada Tasks
18319 @cindex Tasks
18320
18321 @noindent
18322 @code{GDB} allows the following task-related commands:
18323
18324 @table @code
18325 @item info tasks
18326 This command shows a list of current Ada tasks, as in the following example:
18327
18328 @smallexample
18329 @iftex
18330 @leftskip=0cm
18331 @end iftex
18332 (gdb) info tasks
18333   ID       TID P-ID   Thread Pri State                 Name
18334    1   8088000   0   807e000  15 Child Activation Wait main_task
18335    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18336    3   809a800   1   80a4800  15 Child Activation Wait a
18337 *  4   80ae800   3   80b8000  15 Running               c
18338 @end smallexample
18339
18340 @noindent
18341 In this listing, the asterisk before the first task indicates it to be the
18342 currently running task. The first column lists the task ID that is used
18343 to refer to tasks in the following commands.
18344
18345 @item break @var{linespec} task @var{taskid}
18346 @itemx break @var{linespec} task @var{taskid} if @dots{}
18347 @cindex Breakpoints and tasks
18348 These commands are like the @code{break @dots{} thread @dots{}}.
18349 @var{linespec} specifies source lines.
18350
18351 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18352 to specify that you only want @code{GDB} to stop the program when a
18353 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18354 numeric task identifiers assigned by @code{GDB}, shown in the first
18355 column of the @samp{info tasks} display.
18356
18357 If you do not specify @samp{task @var{taskid}} when you set a
18358 breakpoint, the breakpoint applies to @emph{all} tasks of your
18359 program.
18360
18361 You can use the @code{task} qualifier on conditional breakpoints as
18362 well; in this case, place @samp{task @var{taskid}} before the
18363 breakpoint condition (before the @code{if}).
18364
18365 @item task @var{taskno}
18366 @cindex Task switching
18367
18368 This command allows to switch to the task referred by @var{taskno}. In
18369 particular, This allows to browse the backtrace of the specified
18370 task. It is advised to switch back to the original task before
18371 continuing execution otherwise the scheduling of the program may be
18372 perturbated.
18373 @end table
18374
18375 @noindent
18376 For more detailed information on the tasking support,
18377 see @cite{Debugging with GDB}.
18378
18379 @node Debugging Generic Units
18380 @section Debugging Generic Units
18381 @cindex Debugging Generic Units
18382 @cindex Generics
18383
18384 @noindent
18385 GNAT always uses code expansion for generic instantiation. This means that
18386 each time an instantiation occurs, a complete copy of the original code is
18387 made, with appropriate substitutions of formals by actuals.
18388
18389 It is not possible to refer to the original generic entities in
18390 @code{GDB}, but it is always possible to debug a particular instance of
18391 a generic, by using the appropriate expanded names. For example, if we have
18392
18393 @smallexample @c ada
18394 @group
18395 @cartouche
18396 procedure g is
18397
18398    generic package k is
18399       procedure kp (v1 : in out integer);
18400    end k;
18401
18402    package body k is
18403       procedure kp (v1 : in out integer) is
18404       begin
18405          v1 := v1 + 1;
18406       end kp;
18407    end k;
18408
18409    package k1 is new k;
18410    package k2 is new k;
18411
18412    var : integer := 1;
18413
18414 begin
18415    k1.kp (var);
18416    k2.kp (var);
18417    k1.kp (var);
18418    k2.kp (var);
18419 end;
18420 @end cartouche
18421 @end group
18422 @end smallexample
18423
18424 @noindent
18425 Then to break on a call to procedure kp in the k2 instance, simply
18426 use the command:
18427
18428 @smallexample
18429 (gdb) break g.k2.kp
18430 @end smallexample
18431
18432 @noindent
18433 When the breakpoint occurs, you can step through the code of the
18434 instance in the normal manner and examine the values of local variables, as for
18435 other units.
18436
18437 @node GNAT Abnormal Termination or Failure to Terminate
18438 @section GNAT Abnormal Termination or Failure to Terminate
18439 @cindex GNAT Abnormal Termination or Failure to Terminate
18440
18441 @noindent
18442 When presented with programs that contain serious errors in syntax
18443 or semantics,
18444 GNAT may on rare occasions  experience problems in operation, such
18445 as aborting with a
18446 segmentation fault or illegal memory access, raising an internal
18447 exception, terminating abnormally, or failing to terminate at all.
18448 In such cases, you can activate
18449 various features of GNAT that can help you pinpoint the construct in your
18450 program that is the likely source of the problem.
18451
18452 The following strategies are presented in increasing order of
18453 difficulty, corresponding to your experience in using GNAT and your
18454 familiarity with compiler internals.
18455
18456 @enumerate
18457 @item
18458 Run @code{gcc} with the @option{-gnatf}. This first
18459 switch causes all errors on a given line to be reported. In its absence,
18460 only the first error on a line is displayed.
18461
18462 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18463 are encountered, rather than after compilation is terminated. If GNAT
18464 terminates prematurely or goes into an infinite loop, the last error
18465 message displayed may help to pinpoint the culprit.
18466
18467 @item
18468 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18469 @code{gcc} produces ongoing information about the progress of the
18470 compilation and provides the name of each procedure as code is
18471 generated. This switch allows you to find which Ada procedure was being
18472 compiled when it encountered a code generation problem.
18473
18474 @item
18475 @cindex @option{-gnatdc} switch
18476 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18477 switch that does for the front-end what @option{^-v^VERBOSE^} does
18478 for the back end. The system prints the name of each unit,
18479 either a compilation unit or nested unit, as it is being analyzed.
18480 @item
18481 Finally, you can start
18482 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18483 front-end of GNAT, and can be run independently (normally it is just
18484 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18485 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18486 @code{where} command is the first line of attack; the variable
18487 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18488 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18489 which the execution stopped, and @code{input_file name} indicates the name of
18490 the source file.
18491 @end enumerate
18492
18493 @node Naming Conventions for GNAT Source Files
18494 @section Naming Conventions for GNAT Source Files
18495
18496 @noindent
18497 In order to examine the workings of the GNAT system, the following
18498 brief description of its organization may be helpful:
18499
18500 @itemize @bullet
18501 @item
18502 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18503
18504 @item
18505 All files prefixed with @file{^par^PAR^} are components of the parser. The
18506 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18507 parsing of select statements can be found in @file{par-ch9.adb}.
18508
18509 @item
18510 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18511 numbers correspond to chapters of the Ada standard. For example, all
18512 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18513 addition, some features of the language require sufficient special processing
18514 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18515 dynamic dispatching, etc.
18516
18517 @item
18518 All files prefixed with @file{^exp^EXP^} perform normalization and
18519 expansion of the intermediate representation (abstract syntax tree, or AST).
18520 these files use the same numbering scheme as the parser and semantics files.
18521 For example, the construction of record initialization procedures is done in
18522 @file{exp_ch3.adb}.
18523
18524 @item
18525 The files prefixed with @file{^bind^BIND^} implement the binder, which
18526 verifies the consistency of the compilation, determines an order of
18527 elaboration, and generates the bind file.
18528
18529 @item
18530 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18531 data structures used by the front-end.
18532
18533 @item
18534 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18535 the abstract syntax tree as produced by the parser.
18536
18537 @item
18538 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18539 all entities, computed during semantic analysis.
18540
18541 @item
18542 Library management issues are dealt with in files with prefix
18543 @file{^lib^LIB^}.
18544
18545 @item
18546 @findex Ada
18547 @cindex Annex A
18548 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18549 defined in Annex A.
18550
18551 @item
18552 @findex Interfaces
18553 @cindex Annex B
18554 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18555 defined in Annex B.
18556
18557 @item
18558 @findex System
18559 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18560 both language-defined children and GNAT run-time routines.
18561
18562 @item
18563 @findex GNAT
18564 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18565 general-purpose packages, fully documented in their specifications. All
18566 the other @file{.c} files are modifications of common @code{gcc} files.
18567 @end itemize
18568
18569 @node Getting Internal Debugging Information
18570 @section Getting Internal Debugging Information
18571
18572 @noindent
18573 Most compilers have internal debugging switches and modes. GNAT
18574 does also, except GNAT internal debugging switches and modes are not
18575 secret. A summary and full description of all the compiler and binder
18576 debug flags are in the file @file{debug.adb}. You must obtain the
18577 sources of the compiler to see the full detailed effects of these flags.
18578
18579 The switches that print the source of the program (reconstructed from
18580 the internal tree) are of general interest for user programs, as are the
18581 options to print
18582 the full internal tree, and the entity table (the symbol table
18583 information). The reconstructed source provides a readable version of the
18584 program after the front-end has completed analysis and  expansion,
18585 and is useful when studying the performance of specific constructs.
18586 For example, constraint checks are indicated, complex aggregates
18587 are replaced with loops and assignments, and tasking primitives
18588 are replaced with run-time calls.
18589
18590 @node Stack Traceback
18591 @section Stack Traceback
18592 @cindex traceback
18593 @cindex stack traceback
18594 @cindex stack unwinding
18595
18596 @noindent
18597 Traceback is a mechanism to display the sequence of subprogram calls that
18598 leads to a specified execution point in a program. Often (but not always)
18599 the execution point is an instruction at which an exception has been raised.
18600 This mechanism is also known as @i{stack unwinding} because it obtains
18601 its information by scanning the run-time stack and recovering the activation
18602 records of all active subprograms. Stack unwinding is one of the most
18603 important tools for program debugging.
18604
18605 The first entry stored in traceback corresponds to the deepest calling level,
18606 that is to say the subprogram currently executing the instruction
18607 from which we want to obtain the traceback.
18608
18609 Note that there is no runtime performance penalty when stack traceback
18610 is enabled, and no exception is raised during program execution.
18611
18612 @menu
18613 * Non-Symbolic Traceback::
18614 * Symbolic Traceback::
18615 @end menu
18616
18617 @node Non-Symbolic Traceback
18618 @subsection Non-Symbolic Traceback
18619 @cindex traceback, non-symbolic
18620
18621 @noindent
18622 Note: this feature is not supported on all platforms. See
18623 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18624 platforms.
18625
18626 @menu
18627 * Tracebacks From an Unhandled Exception::
18628 * Tracebacks From Exception Occurrences (non-symbolic)::
18629 * Tracebacks From Anywhere in a Program (non-symbolic)::
18630 @end menu
18631
18632 @node Tracebacks From an Unhandled Exception
18633 @subsubsection Tracebacks From an Unhandled Exception
18634
18635 @noindent
18636 A runtime non-symbolic traceback is a list of addresses of call instructions.
18637 To enable this feature you must use the @option{-E}
18638 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18639 of exception information. You can retrieve this information using the
18640 @code{addr2line} tool.
18641
18642 Here is a simple example:
18643
18644 @smallexample @c ada
18645 @cartouche
18646 procedure STB is
18647
18648    procedure P1 is
18649    begin
18650       raise Constraint_Error;
18651    end P1;
18652
18653    procedure P2 is
18654    begin
18655       P1;
18656    end P2;
18657
18658 begin
18659    P2;
18660 end STB;
18661 @end cartouche
18662 @end smallexample
18663
18664 @smallexample
18665 $ gnatmake stb -bargs -E
18666 $ stb
18667
18668 Execution terminated by unhandled exception
18669 Exception name: CONSTRAINT_ERROR
18670 Message: stb.adb:5
18671 Call stack traceback locations:
18672 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18673 @end smallexample
18674
18675 @noindent
18676 As we see the traceback lists a sequence of addresses for the unhandled
18677 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18678 guess that this exception come from procedure P1. To translate these
18679 addresses into the source lines where the calls appear, the
18680 @code{addr2line} tool, described below, is invaluable. The use of this tool
18681 requires the program to be compiled with debug information.
18682
18683 @smallexample
18684 $ gnatmake -g stb -bargs -E
18685 $ stb
18686
18687 Execution terminated by unhandled exception
18688 Exception name: CONSTRAINT_ERROR
18689 Message: stb.adb:5
18690 Call stack traceback locations:
18691 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18692
18693 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18694    0x4011f1 0x77e892a4
18695
18696 00401373 at d:/stb/stb.adb:5
18697 0040138B at d:/stb/stb.adb:10
18698 0040139C at d:/stb/stb.adb:14
18699 00401335 at d:/stb/b~stb.adb:104
18700 004011C4 at /build/.../crt1.c:200
18701 004011F1 at /build/.../crt1.c:222
18702 77E892A4 in ?? at ??:0
18703 @end smallexample
18704
18705 @noindent
18706 The @code{addr2line} tool has several other useful options:
18707
18708 @table @code
18709 @item --functions
18710 to get the function name corresponding to any location
18711
18712 @item --demangle=gnat
18713 to use the gnat decoding mode for the function names. Note that
18714 for binutils version 2.9.x the option is simply @option{--demangle}.
18715 @end table
18716
18717 @smallexample
18718 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18719    0x40139c 0x401335 0x4011c4 0x4011f1
18720
18721 00401373 in stb.p1 at d:/stb/stb.adb:5
18722 0040138B in stb.p2 at d:/stb/stb.adb:10
18723 0040139C in stb at d:/stb/stb.adb:14
18724 00401335 in main at d:/stb/b~stb.adb:104
18725 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18726 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18727 @end smallexample
18728
18729 @noindent
18730 From this traceback we can see that the exception was raised in
18731 @file{stb.adb} at line 5, which was reached from a procedure call in
18732 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
18733 which contains the call to the main program.
18734 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
18735 and the output will vary from platform to platform.
18736
18737 It is also possible to use @code{GDB} with these traceback addresses to debug
18738 the program. For example, we can break at a given code location, as reported
18739 in the stack traceback:
18740
18741 @smallexample
18742 $ gdb -nw stb
18743 @ifclear vms
18744 @noindent
18745 Furthermore, this feature is not implemented inside Windows DLL. Only
18746 the non-symbolic traceback is reported in this case.
18747 @end ifclear
18748
18749 (gdb) break *0x401373
18750 Breakpoint 1 at 0x401373: file stb.adb, line 5.
18751 @end smallexample
18752
18753 @noindent
18754 It is important to note that the stack traceback addresses
18755 do not change when debug information is included. This is particularly useful
18756 because it makes it possible to release software without debug information (to
18757 minimize object size), get a field report that includes a stack traceback
18758 whenever an internal bug occurs, and then be able to retrieve the sequence
18759 of calls with the same program compiled with debug information.
18760
18761 @node Tracebacks From Exception Occurrences (non-symbolic)
18762 @subsubsection Tracebacks From Exception Occurrences
18763
18764 @noindent
18765 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
18766 The stack traceback is attached to the exception information string, and can
18767 be retrieved in an exception handler within the Ada program, by means of the
18768 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
18769
18770 @smallexample @c ada
18771 with Ada.Text_IO;
18772 with Ada.Exceptions;
18773
18774 procedure STB is
18775
18776    use Ada;
18777    use Ada.Exceptions;
18778
18779    procedure P1 is
18780       K : Positive := 1;
18781    begin
18782       K := K - 1;
18783    exception
18784       when E : others =>
18785          Text_IO.Put_Line (Exception_Information (E));
18786    end P1;
18787
18788    procedure P2 is
18789    begin
18790       P1;
18791    end P2;
18792
18793 begin
18794    P2;
18795 end STB;
18796 @end smallexample
18797
18798 @noindent
18799 This program will output:
18800
18801 @smallexample
18802 $ stb
18803
18804 Exception name: CONSTRAINT_ERROR
18805 Message: stb.adb:12
18806 Call stack traceback locations:
18807 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
18808 @end smallexample
18809
18810 @node Tracebacks From Anywhere in a Program (non-symbolic)
18811 @subsubsection Tracebacks From Anywhere in a Program
18812
18813 @noindent
18814 It is also possible to retrieve a stack traceback from anywhere in a
18815 program. For this you need to
18816 use the @code{GNAT.Traceback} API. This package includes a procedure called
18817 @code{Call_Chain} that computes a complete stack traceback, as well as useful
18818 display procedures described below. It is not necessary to use the
18819 @option{-E gnatbind} option in this case, because the stack traceback mechanism
18820 is invoked explicitly.
18821
18822 @noindent
18823 In the following example we compute a traceback at a specific location in
18824 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
18825 convert addresses to strings:
18826
18827 @smallexample @c ada
18828 with Ada.Text_IO;
18829 with GNAT.Traceback;
18830 with GNAT.Debug_Utilities;
18831
18832 procedure STB is
18833
18834    use Ada;
18835    use GNAT;
18836    use GNAT.Traceback;
18837
18838    procedure P1 is
18839       TB  : Tracebacks_Array (1 .. 10);
18840       --  We are asking for a maximum of 10 stack frames.
18841       Len : Natural;
18842       --  Len will receive the actual number of stack frames returned.
18843    begin
18844       Call_Chain (TB, Len);
18845
18846       Text_IO.Put ("In STB.P1 : ");
18847
18848       for K in 1 .. Len loop
18849          Text_IO.Put (Debug_Utilities.Image (TB (K)));
18850          Text_IO.Put (' ');
18851       end loop;
18852
18853       Text_IO.New_Line;
18854    end P1;
18855
18856    procedure P2 is
18857    begin
18858       P1;
18859    end P2;
18860
18861 begin
18862    P2;
18863 end STB;
18864 @end smallexample
18865
18866 @smallexample
18867 $ gnatmake -g stb
18868 $ stb
18869
18870 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
18871 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
18872 @end smallexample
18873
18874 @noindent
18875 You can then get further information by invoking the @code{addr2line}
18876 tool as described earlier (note that the hexadecimal addresses
18877 need to be specified in C format, with a leading ``0x'').
18878
18879
18880 @node Symbolic Traceback
18881 @subsection Symbolic Traceback
18882 @cindex traceback, symbolic
18883
18884 @noindent
18885 A symbolic traceback is a stack traceback in which procedure names are
18886 associated with each code location.
18887
18888 @noindent
18889 Note that this feature is not supported on all platforms. See
18890 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
18891 list of currently supported platforms.
18892
18893 @noindent
18894 Note that the symbolic traceback requires that the program be compiled
18895 with debug information. If it is not compiled with debug information
18896 only the non-symbolic information will be valid.
18897
18898 @menu
18899 * Tracebacks From Exception Occurrences (symbolic)::
18900 * Tracebacks From Anywhere in a Program (symbolic)::
18901 @end menu
18902
18903 @node Tracebacks From Exception Occurrences (symbolic)
18904 @subsubsection Tracebacks From Exception Occurrences
18905
18906 @smallexample @c ada
18907 with Ada.Text_IO;
18908 with GNAT.Traceback.Symbolic;
18909
18910 procedure STB is
18911
18912    procedure P1 is
18913    begin
18914       raise Constraint_Error;
18915    end P1;
18916
18917    procedure P2 is
18918    begin
18919       P1;
18920    end P2;
18921
18922    procedure P3 is
18923    begin
18924       P2;
18925    end P3;
18926
18927 begin
18928    P3;
18929 exception
18930    when E : others =>
18931       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
18932 end STB;
18933 @end smallexample
18934
18935 @smallexample
18936 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
18937 $ stb
18938
18939 0040149F in stb.p1 at stb.adb:8
18940 004014B7 in stb.p2 at stb.adb:13
18941 004014CF in stb.p3 at stb.adb:18
18942 004015DD in ada.stb at stb.adb:22
18943 00401461 in main at b~stb.adb:168
18944 004011C4 in __mingw_CRTStartup at crt1.c:200
18945 004011F1 in mainCRTStartup at crt1.c:222
18946 77E892A4 in ?? at ??:0
18947 @end smallexample
18948
18949 @noindent
18950 In the above example the ``.\'' syntax in the @command{gnatmake} command
18951 is currently required by @command{addr2line} for files that are in
18952 the current working directory.
18953 Moreover, the exact sequence of linker options may vary from platform
18954 to platform.
18955 The above @option{-largs} section is for Windows platforms. By contrast,
18956 under Unix there is no need for the @option{-largs} section.
18957 Differences across platforms are due to details of linker implementation.
18958
18959 @node Tracebacks From Anywhere in a Program (symbolic)
18960 @subsubsection Tracebacks From Anywhere in a Program
18961
18962 @noindent
18963 It is possible to get a symbolic stack traceback
18964 from anywhere in a program, just as for non-symbolic tracebacks.
18965 The first step is to obtain a non-symbolic
18966 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
18967 information. Here is an example:
18968
18969 @smallexample @c ada
18970 with Ada.Text_IO;
18971 with GNAT.Traceback;
18972 with GNAT.Traceback.Symbolic;
18973
18974 procedure STB is
18975
18976    use Ada;
18977    use GNAT.Traceback;
18978    use GNAT.Traceback.Symbolic;
18979
18980    procedure P1 is
18981       TB  : Tracebacks_Array (1 .. 10);
18982       --  We are asking for a maximum of 10 stack frames.
18983       Len : Natural;
18984       --  Len will receive the actual number of stack frames returned.
18985    begin
18986       Call_Chain (TB, Len);
18987       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
18988    end P1;
18989
18990    procedure P2 is
18991    begin
18992       P1;
18993    end P2;
18994
18995 begin
18996    P2;
18997 end STB;
18998 @end smallexample
18999
19000 @ifset vms
19001 @node Compatibility with DEC Ada
19002 @chapter Compatibility with DEC Ada
19003 @cindex Compatibility
19004
19005 @noindent
19006 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19007 OpenVMS Alpha. GNAT achieves a high level of compatibility
19008 with DEC Ada, and it should generally be straightforward to port code
19009 from the DEC Ada environment to GNAT. However, there are a few language
19010 and implementation differences of which the user must be aware. These
19011 differences are discussed in this section. In
19012 addition, the operating environment and command structure for the
19013 compiler are different, and these differences are also discussed.
19014
19015 Note that this discussion addresses specifically the implementation
19016 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19017 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19018 GNAT always follows the Alpha implementation.
19019
19020 @menu
19021 * Ada 95 Compatibility::
19022 * Differences in the Definition of Package System::
19023 * Language-Related Features::
19024 * The Package STANDARD::
19025 * The Package SYSTEM::
19026 * Tasking and Task-Related Features::
19027 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19028 * Pragmas and Pragma-Related Features::
19029 * Library of Predefined Units::
19030 * Bindings::
19031 * Main Program Definition::
19032 * Implementation-Defined Attributes::
19033 * Compiler and Run-Time Interfacing::
19034 * Program Compilation and Library Management::
19035 * Input-Output::
19036 * Implementation Limits::
19037 * Tools::
19038 @end menu
19039
19040 @node Ada 95 Compatibility
19041 @section Ada 95 Compatibility
19042
19043 @noindent
19044 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19045 compiler. Ada 95 is almost completely upwards compatible
19046 with Ada 83, and therefore Ada 83 programs will compile
19047 and run under GNAT with
19048 no changes or only minor changes. The Ada 95 Reference
19049 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19050 incompatibilities.
19051
19052 GNAT provides the switch /83 on the GNAT COMPILE command,
19053 as well as the pragma ADA_83, to force the compiler to
19054 operate in Ada 83 mode. This mode does not guarantee complete
19055 conformance to Ada 83, but in practice is sufficient to
19056 eliminate most sources of incompatibilities.
19057 In particular, it eliminates the recognition of the
19058 additional Ada 95 keywords, so that their use as identifiers
19059 in Ada83 program is legal, and handles the cases of packages
19060 with optional bodies, and generics that instantiate unconstrained
19061 types without the use of @code{(<>)}.
19062
19063 @node Differences in the Definition of Package System
19064 @section Differences in the Definition of Package System
19065
19066 @noindent
19067 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19068 implementation-dependent declarations to package System. In normal mode,
19069 GNAT does not take advantage of this permission, and the version of System
19070 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19071
19072 However, DEC Ada adds an extensive set of declarations to package System,
19073 as fully documented in the DEC Ada manuals. To minimize changes required
19074 for programs that make use of these extensions, GNAT provides the pragma
19075 Extend_System for extending the definition of package System. By using:
19076
19077 @smallexample @c ada
19078 @group
19079 @cartouche
19080 pragma Extend_System (Aux_DEC);
19081 @end cartouche
19082 @end group
19083 @end smallexample
19084
19085 @noindent
19086 The set of definitions in System is extended to include those in package
19087 @code{System.Aux_DEC}.
19088 These definitions are incorporated directly into package
19089 System, as though they had been declared there in the first place. For a
19090 list of the declarations added, see the specification of this package,
19091 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19092 The pragma Extend_System is a configuration pragma, which means that
19093 it can be placed in the file @file{gnat.adc}, so that it will automatically
19094 apply to all subsequent compilations. See the section on Configuration
19095 Pragmas for further details.
19096
19097 An alternative approach that avoids the use of the non-standard
19098 Extend_System pragma is to add a context clause to the unit that
19099 references these facilities:
19100
19101 @smallexample @c ada
19102 @group
19103 @cartouche
19104 with System.Aux_DEC;
19105 use  System.Aux_DEC;
19106 @end cartouche
19107 @end group
19108 @end smallexample
19109
19110 @noindent
19111 The effect is not quite semantically identical to incorporating
19112 the declarations directly into package @code{System},
19113 but most programs will not notice a difference
19114 unless they use prefix notation (e.g. @code{System.Integer_8})
19115 to reference the
19116 entities directly in package @code{System}.
19117 For units containing such references,
19118 the prefixes must either be removed, or the pragma @code{Extend_System}
19119 must be used.
19120
19121 @node Language-Related Features
19122 @section Language-Related Features
19123
19124 @noindent
19125 The following sections highlight differences in types,
19126 representations of types, operations, alignment, and
19127 related topics.
19128
19129 @menu
19130 * Integer Types and Representations::
19131 * Floating-Point Types and Representations::
19132 * Pragmas Float_Representation and Long_Float::
19133 * Fixed-Point Types and Representations::
19134 * Record and Array Component Alignment::
19135 * Address Clauses::
19136 * Other Representation Clauses::
19137 @end menu
19138
19139 @node Integer Types and Representations
19140 @subsection Integer Types and Representations
19141
19142 @noindent
19143 The set of predefined integer types is identical in DEC Ada and GNAT.
19144 Furthermore the representation of these integer types is also identical,
19145 including the capability of size clauses forcing biased representation.
19146
19147 In addition,
19148 DEC Ada for OpenVMS Alpha systems has defined the
19149 following additional integer types in package System:
19150
19151 @itemize @bullet
19152
19153 @item
19154 INTEGER_8
19155
19156 @item
19157 INTEGER_16
19158
19159 @item
19160 INTEGER_32
19161
19162 @item
19163 INTEGER_64
19164
19165 @item
19166 LARGEST_INTEGER
19167 @end itemize
19168
19169 @noindent
19170 When using GNAT, the first four of these types may be obtained from the
19171 standard Ada 95 package @code{Interfaces}.
19172 Alternatively, by use of the pragma
19173 @code{Extend_System}, identical
19174 declarations can be referenced directly in package @code{System}.
19175 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19176
19177 @node Floating-Point Types and Representations
19178 @subsection Floating-Point Types and Representations
19179 @cindex Floating-Point types
19180
19181 @noindent
19182 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19183 Furthermore the representation of these floating-point
19184 types is also identical. One important difference is that the default
19185 representation for DEC Ada is VAX_Float, but the default representation
19186 for GNAT is IEEE.
19187
19188 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19189 @code{Float_Representation} as described in the DEC Ada documentation.
19190 For example, the declarations:
19191
19192 @smallexample @c ada
19193 @group
19194 @cartouche
19195 type F_Float is digits 6;
19196 pragma Float_Representation (VAX_Float, F_Float);
19197 @end cartouche
19198 @end group
19199 @end smallexample
19200
19201 @noindent
19202 declare a type F_Float that will be represented in VAX_Float format.
19203 This set of declarations actually appears in System.Aux_DEC, which provides
19204 the full set of additional floating-point declarations provided in
19205 the DEC Ada version of package
19206 System. This and similar declarations may be accessed in a user program
19207 by using pragma @code{Extend_System}. The use of this
19208 pragma, and the related pragma @code{Long_Float} is described in further
19209 detail in the following section.
19210
19211 @node Pragmas Float_Representation and Long_Float
19212 @subsection Pragmas Float_Representation and Long_Float
19213
19214 @noindent
19215 DEC Ada provides the pragma @code{Float_Representation}, which
19216 acts as a program library switch to allow control over
19217 the internal representation chosen for the predefined
19218 floating-point types declared in the package @code{Standard}.
19219 The format of this pragma is as follows:
19220
19221 @smallexample
19222 @group
19223 @cartouche
19224 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19225 @end cartouche
19226 @end group
19227 @end smallexample
19228
19229 @noindent
19230 This pragma controls the representation of floating-point
19231 types as follows:
19232
19233 @itemize @bullet
19234 @item
19235 @code{VAX_Float} specifies that floating-point
19236 types are represented by default with the VAX hardware types
19237 F-floating, D-floating, G-floating. Note that the H-floating
19238 type is available only on DIGITAL Vax systems, and is not available
19239 in either DEC Ada or GNAT for Alpha systems.
19240
19241 @item
19242 @code{IEEE_Float} specifies that floating-point
19243 types are represented by default with the IEEE single and
19244 double floating-point types.
19245 @end itemize
19246
19247 @noindent
19248 GNAT provides an identical implementation of the pragma
19249 @code{Float_Representation}, except that it functions as a
19250 configuration pragma, as defined by Ada 95. Note that the
19251 notion of configuration pragma corresponds closely to the
19252 DEC Ada notion of a program library switch.
19253
19254 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19255 from DEC Ada 83, where the default is VAX_Float. In addition, the
19256 predefined libraries in GNAT are built using IEEE_Float, so it is not
19257 advisable to change the format of numbers passed to standard library
19258 routines, and if necessary explicit type conversions may be needed.
19259
19260 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19261 and (given that it conforms to an international standard) potentially more
19262 portable. The situation in which VAX_Float may be useful is in interfacing
19263 to existing code and data that expects the use of VAX_Float. There are
19264 two possibilities here. If the requirement for the use of VAX_Float is
19265 localized, then the best approach is to use the predefined VAX_Float
19266 types in package @code{System}, as extended by
19267 @code{Extend_System}. For example, use @code{System.F_Float}
19268 to specify the 32-bit @code{F-Float} format.
19269
19270 Alternatively, if an entire program depends heavily on the use of
19271 the @code{VAX_Float} and in particular assumes that the types in
19272 package @code{Standard} are in @code{Vax_Float} format, then it
19273 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19274 This is done by using the GNAT LIBRARY command to rebuild the library, and
19275 then using the general form of the @code{Float_Representation}
19276 pragma to ensure that this default format is used throughout.
19277 The form of the GNAT LIBRARY command is:
19278
19279 @smallexample
19280 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19281 @end smallexample
19282
19283 @noindent
19284 where @i{file} contains the new configuration pragmas
19285 and @i{directory} is the directory to be created to contain
19286 the new library.
19287
19288 @noindent
19289 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19290 to allow control over the internal representation chosen
19291 for the predefined type @code{Long_Float} and for floating-point
19292 type declarations with digits specified in the range 7 .. 15.
19293 The format of this pragma is as follows:
19294
19295 @smallexample @c ada
19296 @cartouche
19297 pragma Long_Float (D_FLOAT | G_FLOAT);
19298 @end cartouche
19299 @end smallexample
19300
19301 @node Fixed-Point Types and Representations
19302 @subsection Fixed-Point Types and Representations
19303
19304 @noindent
19305 On DEC Ada for OpenVMS Alpha systems, rounding is
19306 away from zero for both positive and negative numbers.
19307 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19308
19309 On GNAT for OpenVMS Alpha, the results of operations
19310 on fixed-point types are in accordance with the Ada 95
19311 rules. In particular, results of operations on decimal
19312 fixed-point types are truncated.
19313
19314 @node Record and Array Component Alignment
19315 @subsection Record and Array Component Alignment
19316
19317 @noindent
19318 On DEC Ada for OpenVMS Alpha, all non composite components
19319 are aligned on natural boundaries. For example, 1-byte
19320 components are aligned on byte boundaries, 2-byte
19321 components on 2-byte boundaries, 4-byte components on 4-byte
19322 byte boundaries, and so on. The OpenVMS Alpha hardware
19323 runs more efficiently with naturally aligned data.
19324
19325 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19326 with DEC Ada for OpenVMS Alpha.
19327
19328 @node Address Clauses
19329 @subsection Address Clauses
19330
19331 @noindent
19332 In DEC Ada and GNAT, address clauses are supported for
19333 objects and imported subprograms.
19334 The predefined type @code{System.Address} is a private type
19335 in both compilers, with the same representation (it is simply
19336 a machine pointer). Addition, subtraction, and comparison
19337 operations are available in the standard Ada 95 package
19338 @code{System.Storage_Elements}, or in package @code{System}
19339 if it is extended to include @code{System.Aux_DEC} using a
19340 pragma @code{Extend_System} as previously described.
19341
19342 Note that code that with's both this extended package @code{System}
19343 and the package @code{System.Storage_Elements} should not @code{use}
19344 both packages, or ambiguities will result. In general it is better
19345 not to mix these two sets of facilities. The Ada 95 package was
19346 designed specifically to provide the kind of features that DEC Ada
19347 adds directly to package @code{System}.
19348
19349 GNAT is compatible with DEC Ada in its handling of address
19350 clauses, except for some limitations in
19351 the form of address clauses for composite objects with
19352 initialization. Such address clauses are easily replaced
19353 by the use of an explicitly-defined constant as described
19354 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19355 of declarations:
19356
19357 @smallexample @c ada
19358 @cartouche
19359 X, Y : Integer := Init_Func;
19360 Q : String (X .. Y) := "abc";
19361 ...
19362 for Q'Address use Compute_Address;
19363 @end cartouche
19364 @end smallexample
19365
19366 @noindent
19367 will be rejected by GNAT, since the address cannot be computed at the time
19368 that Q is declared. To achieve the intended effect, write instead:
19369
19370 @smallexample @c ada
19371 @group
19372 @cartouche
19373 X, Y : Integer := Init_Func;
19374 Q_Address : constant Address := Compute_Address;
19375 Q : String (X .. Y) := "abc";
19376 ...
19377 for Q'Address use Q_Address;
19378 @end cartouche
19379 @end group
19380 @end smallexample
19381
19382 @noindent
19383 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19384 backwards compatible with Ada 83. A fuller description of the restrictions
19385 on address specifications is found in the GNAT Reference Manual.
19386
19387 @node Other Representation Clauses
19388 @subsection Other Representation Clauses
19389
19390 @noindent
19391 GNAT supports in a compatible manner all the representation
19392 clauses supported by DEC Ada. In addition, it
19393 supports representation clause forms that are new in Ada 95
19394 including COMPONENT_SIZE and SIZE clauses for objects.
19395
19396 @node The Package STANDARD
19397 @section The Package STANDARD
19398
19399 @noindent
19400 The package STANDARD, as implemented by DEC Ada, is fully
19401 described in the Reference Manual for the Ada Programming
19402 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19403 Language Reference Manual. As implemented by GNAT, the
19404 package STANDARD is described in the Ada 95 Reference
19405 Manual.
19406
19407 In addition, DEC Ada supports the Latin-1 character set in
19408 the type CHARACTER. GNAT supports the Latin-1 character set
19409 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19410 the type WIDE_CHARACTER.
19411
19412 The floating-point types supported by GNAT are those
19413 supported by DEC Ada, but defaults are different, and are controlled by
19414 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19415
19416 @node The Package SYSTEM
19417 @section The Package SYSTEM
19418
19419 @noindent
19420 DEC Ada provides a system-specific version of the package
19421 SYSTEM for each platform on which the language ships.
19422 For the complete specification of the package SYSTEM, see
19423 Appendix F of the DEC Ada Language Reference Manual.
19424
19425 On DEC Ada, the package SYSTEM includes the following conversion functions:
19426 @itemize @bullet
19427 @item TO_ADDRESS(INTEGER)
19428
19429 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19430
19431 @item  TO_ADDRESS(universal_integer)
19432
19433 @item  TO_INTEGER(ADDRESS)
19434
19435 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19436
19437 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19438                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19439 @end itemize
19440
19441 @noindent
19442 By default, GNAT supplies a version of SYSTEM that matches
19443 the definition given in the Ada 95 Reference Manual.
19444 This
19445 is a subset of the DIGITAL system definitions, which is as
19446 close as possible to the original definitions. The only difference
19447 is that the definition of SYSTEM_NAME is different:
19448
19449 @smallexample @c ada
19450 @group
19451 @cartouche
19452 type Name is (SYSTEM_NAME_GNAT);
19453 System_Name : constant Name := SYSTEM_NAME_GNAT;
19454 @end cartouche
19455 @end group
19456 @end smallexample
19457
19458 @noindent
19459 Also, GNAT adds the new Ada 95 declarations for
19460 BIT_ORDER and DEFAULT_BIT_ORDER.
19461
19462 However, the use of the following pragma causes GNAT
19463 to extend the definition of package SYSTEM so that it
19464 encompasses the full set of DIGITAL-specific extensions,
19465 including the functions listed above:
19466
19467 @smallexample @c ada
19468 @cartouche
19469 pragma Extend_System (Aux_DEC);
19470 @end cartouche
19471 @end smallexample
19472
19473 @noindent
19474 The pragma Extend_System is a configuration pragma that
19475 is most conveniently placed in the @file{gnat.adc} file. See the
19476 GNAT Reference Manual for further details.
19477
19478 DEC Ada does not allow the recompilation of the package
19479 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19480 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19481 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19482 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19483 its single argument.
19484
19485 GNAT does permit the recompilation of package SYSTEM using
19486 a special switch (@option{-gnatg}) and this switch can be used if
19487 it is necessary to modify the definitions in SYSTEM. GNAT does
19488 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19489 or MEMORY_SIZE by any other means.
19490
19491 On GNAT systems, the pragma SYSTEM_NAME takes the
19492 enumeration literal SYSTEM_NAME_GNAT.
19493
19494 The definitions provided by the use of
19495
19496 @smallexample @c ada
19497 pragma Extend_System (AUX_Dec);
19498 @end smallexample
19499
19500 @noindent
19501 are virtually identical to those provided by the DEC Ada 83 package
19502 System. One important difference is that the name of the TO_ADDRESS
19503 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19504 See the GNAT Reference manual for a discussion of why this change was
19505 necessary.
19506
19507 @noindent
19508 The version of TO_ADDRESS taking a universal integer argument is in fact
19509 an extension to Ada 83 not strictly compatible with the reference manual.
19510 In GNAT, we are constrained to be exactly compatible with the standard,
19511 and this means we cannot provide this capability. In DEC Ada 83, the
19512 point of this definition is to deal with a call like:
19513
19514 @smallexample @c ada
19515 TO_ADDRESS (16#12777#);
19516 @end smallexample
19517
19518 @noindent
19519 Normally, according to the Ada 83 standard, one would expect this to be
19520 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19521 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19522 definition using universal_integer takes precedence.
19523
19524 In GNAT, since the version with universal_integer cannot be supplied, it is
19525 not possible to be 100% compatible. Since there are many programs using
19526 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19527 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19528 declarations provided in the GNAT version of AUX_Dec are:
19529
19530 @smallexample @c ada
19531 function To_Address (X : Integer) return Address;
19532 pragma Pure_Function (To_Address);
19533
19534 function To_Address_Long (X : Unsigned_Longword) return Address;
19535 pragma Pure_Function (To_Address_Long);
19536 @end smallexample
19537
19538 @noindent
19539 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19540 change the name to TO_ADDRESS_LONG.
19541
19542 @node Tasking and Task-Related Features
19543 @section Tasking and Task-Related Features
19544
19545 @noindent
19546 The concepts relevant to a comparison of tasking on GNAT
19547 and on DEC Ada for OpenVMS Alpha systems are discussed in
19548 the following sections.
19549
19550 For detailed information on concepts related to tasking in
19551 DEC Ada, see the DEC Ada Language Reference Manual and the
19552 relevant run-time reference manual.
19553
19554 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19555 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19556
19557 @noindent
19558 On OpenVMS Alpha systems, each Ada task (except a passive
19559 task) is implemented as a single stream of execution
19560 that is created and managed by the kernel. On these
19561 systems, DEC Ada tasking support is based on DECthreads,
19562 an implementation of the POSIX standard for threads.
19563
19564 Although tasks are implemented as threads, all tasks in
19565 an Ada program are part of the same process. As a result,
19566 resources such as open files and virtual memory can be
19567 shared easily among tasks. Having all tasks in one process
19568 allows better integration with the programming environment
19569 (the shell and the debugger, for example).
19570
19571 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19572 code that calls DECthreads routines can be used together.
19573 The interaction between Ada tasks and DECthreads routines
19574 can have some benefits. For example when on OpenVMS Alpha,
19575 DEC Ada can call C code that is already threaded.
19576 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19577 and Ada tasks are mapped to threads.
19578
19579 @menu
19580 * Assigning Task IDs::
19581 * Task IDs and Delays::
19582 * Task-Related Pragmas::
19583 * Scheduling and Task Priority::
19584 * The Task Stack::
19585 * External Interrupts::
19586 @end menu
19587
19588 @node Assigning Task IDs
19589 @subsection Assigning Task IDs
19590
19591 @noindent
19592 The DEC Ada Run-Time Library always assigns %TASK 1 to
19593 the environment task that executes the main program. On
19594 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19595 that have been created but are not yet activated.
19596
19597 On OpenVMS Alpha systems, task IDs are assigned at
19598 activation. On GNAT systems, task IDs are also assigned at
19599 task creation but do not have the same form or values as
19600 task ID values in DEC Ada. There is no null task, and the
19601 environment task does not have a specific task ID value.
19602
19603 @node Task IDs and Delays
19604 @subsection Task IDs and Delays
19605
19606 @noindent
19607 On OpenVMS Alpha systems, tasking delays are implemented
19608 using Timer System Services. The Task ID is used for the
19609 identification of the timer request (the REQIDT parameter).
19610 If Timers are used in the application take care not to use
19611 0 for the identification, because cancelling such a timer
19612 will cancel all timers and may lead to unpredictable results.
19613
19614 @node Task-Related Pragmas
19615 @subsection Task-Related Pragmas
19616
19617 @noindent
19618 Ada supplies the pragma TASK_STORAGE, which allows
19619 specification of the size of the guard area for a task
19620 stack. (The guard area forms an area of memory that has no
19621 read or write access and thus helps in the detection of
19622 stack overflow.) On OpenVMS Alpha systems, if the pragma
19623 TASK_STORAGE specifies a value of zero, a minimal guard
19624 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19625 area is created.
19626
19627 GNAT supplies the following task-related pragmas:
19628
19629 @itemize @bullet
19630 @item  TASK_INFO
19631
19632               This pragma appears within a task definition and
19633               applies to the task in which it appears. The argument
19634               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19635
19636 @item  TASK_STORAGE
19637
19638               GNAT implements pragma TASK_STORAGE in the same way as
19639               DEC Ada.
19640               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19641               SUPPRESS, and VOLATILE.
19642 @end itemize
19643 @node Scheduling and Task Priority
19644 @subsection Scheduling and Task Priority
19645
19646 @noindent
19647 DEC Ada implements the Ada language requirement that
19648 when two tasks are eligible for execution and they have
19649 different priorities, the lower priority task does not
19650 execute while the higher priority task is waiting. The DEC
19651 Ada Run-Time Library keeps a task running until either the
19652 task is suspended or a higher priority task becomes ready.
19653
19654 On OpenVMS Alpha systems, the default strategy is round-
19655 robin with preemption. Tasks of equal priority take turns
19656 at the processor. A task is run for a certain period of
19657 time and then placed at the rear of the ready queue for
19658 its priority level.
19659
19660 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19661 which can be used to enable or disable round-robin
19662 scheduling of tasks with the same priority.
19663 See the relevant DEC Ada run-time reference manual for
19664 information on using the pragmas to control DEC Ada task
19665 scheduling.
19666
19667 GNAT follows the scheduling rules of Annex D (real-time
19668 Annex) of the Ada 95 Reference Manual. In general, this
19669 scheduling strategy is fully compatible with DEC Ada
19670 although it provides some additional constraints (as
19671 fully documented in Annex D).
19672 GNAT implements time slicing control in a manner compatible with
19673 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19674 to the DEC Ada 83 pragma of the same name.
19675 Note that it is not possible to mix GNAT tasking and
19676 DEC Ada 83 tasking in the same program, since the two run times are
19677 not compatible.
19678
19679 @node The Task Stack
19680 @subsection The Task Stack
19681
19682 @noindent
19683 In DEC Ada, a task stack is allocated each time a
19684 non passive task is activated. As soon as the task is
19685 terminated, the storage for the task stack is deallocated.
19686 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19687 a default stack size is used. Also, regardless of the size
19688 specified, some additional space is allocated for task
19689 management purposes. On OpenVMS Alpha systems, at least
19690 one page is allocated.
19691
19692 GNAT handles task stacks in a similar manner. According to
19693 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
19694 an alternative method for controlling the task stack size.
19695 The specification of the attribute T'STORAGE_SIZE is also
19696 supported in a manner compatible with DEC Ada.
19697
19698 @node External Interrupts
19699 @subsection External Interrupts
19700
19701 @noindent
19702 On DEC Ada, external interrupts can be associated with task entries.
19703 GNAT is compatible with DEC Ada in its handling of external interrupts.
19704
19705 @node Pragmas and Pragma-Related Features
19706 @section Pragmas and Pragma-Related Features
19707
19708 @noindent
19709 Both DEC Ada and GNAT supply all language-defined pragmas
19710 as specified by the Ada 83 standard. GNAT also supplies all
19711 language-defined pragmas specified in the Ada 95 Reference Manual.
19712 In addition, GNAT implements the implementation-defined pragmas
19713 from DEC Ada 83.
19714
19715 @itemize @bullet
19716 @item  AST_ENTRY
19717
19718 @item  COMMON_OBJECT
19719
19720 @item  COMPONENT_ALIGNMENT
19721
19722 @item  EXPORT_EXCEPTION
19723
19724 @item  EXPORT_FUNCTION
19725
19726 @item  EXPORT_OBJECT
19727
19728 @item  EXPORT_PROCEDURE
19729
19730 @item  EXPORT_VALUED_PROCEDURE
19731
19732 @item  FLOAT_REPRESENTATION
19733
19734 @item  IDENT
19735
19736 @item  IMPORT_EXCEPTION
19737
19738 @item  IMPORT_FUNCTION
19739
19740 @item  IMPORT_OBJECT
19741
19742 @item  IMPORT_PROCEDURE
19743
19744 @item  IMPORT_VALUED_PROCEDURE
19745
19746 @item  INLINE_GENERIC
19747
19748 @item  INTERFACE_NAME
19749
19750 @item  LONG_FLOAT
19751
19752 @item  MAIN_STORAGE
19753
19754 @item  PASSIVE
19755
19756 @item  PSET_OBJECT
19757
19758 @item  SHARE_GENERIC
19759
19760 @item  SUPPRESS_ALL
19761
19762 @item  TASK_STORAGE
19763
19764 @item  TIME_SLICE
19765
19766 @item  TITLE
19767 @end itemize
19768
19769 @noindent
19770 These pragmas are all fully implemented, with the exception of @code{Title},
19771 @code{Passive}, and @code{Share_Generic}, which are
19772 recognized, but which have no
19773 effect in GNAT. The effect of @code{Passive} may be obtained by the
19774 use of protected objects in Ada 95. In GNAT, all generics are inlined.
19775
19776 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
19777 a separate subprogram specification which must appear before the
19778 subprogram body.
19779
19780 GNAT also supplies a number of implementation-defined pragmas as follows:
19781 @itemize @bullet
19782 @item  C_PASS_BY_COPY
19783
19784 @item  EXTEND_SYSTEM
19785
19786 @item  SOURCE_FILE_NAME
19787
19788 @item  UNSUPPRESS
19789
19790 @item  WARNINGS
19791
19792 @item  ABORT_DEFER
19793
19794 @item  ADA_83
19795
19796 @item  ADA_95
19797
19798 @item  ANNOTATE
19799
19800 @item  ASSERT
19801
19802 @item  CPP_CLASS
19803
19804 @item  CPP_CONSTRUCTOR
19805
19806 @item  CPP_DESTRUCTOR
19807
19808 @item  CPP_VIRTUAL
19809
19810 @item  CP_VTABLE
19811
19812 @item  DEBUG
19813
19814 @item  LINKER_ALIAS
19815
19816 @item  LINKER_SECTION
19817
19818 @item  MACHINE_ATTRIBUTE
19819
19820 @item  NO_RETURN
19821
19822 @item  PURE_FUNCTION
19823
19824 @item  SOURCE_REFERENCE
19825
19826 @item  TASK_INFO
19827
19828 @item  UNCHECKED_UNION
19829
19830 @item  UNIMPLEMENTED_UNIT
19831
19832 @item  UNIVERSAL_DATA
19833
19834 @item  WEAK_EXTERNAL
19835 @end itemize
19836
19837 @noindent
19838 For full details on these GNAT implementation-defined pragmas, see
19839 the GNAT Reference Manual.
19840
19841 @menu
19842 * Restrictions on the Pragma INLINE::
19843 * Restrictions on the Pragma INTERFACE::
19844 * Restrictions on the Pragma SYSTEM_NAME::
19845 @end menu
19846
19847 @node Restrictions on the Pragma INLINE
19848 @subsection Restrictions on the Pragma INLINE
19849
19850 @noindent
19851 DEC Ada applies the following restrictions to the pragma INLINE:
19852 @itemize @bullet
19853 @item  Parameters cannot be a task type.
19854
19855 @item  Function results cannot be task types, unconstrained
19856 array types, or unconstrained types with discriminants.
19857
19858 @item  Bodies cannot declare the following:
19859 @itemize @bullet
19860 @item  Subprogram body or stub (imported subprogram is allowed)
19861
19862 @item  Tasks
19863
19864 @item  Generic declarations
19865
19866 @item  Instantiations
19867
19868 @item  Exceptions
19869
19870 @item  Access types (types derived from access types allowed)
19871
19872 @item  Array or record types
19873
19874 @item  Dependent tasks
19875
19876 @item  Direct recursive calls of subprogram or containing
19877 subprogram, directly or via a renaming
19878
19879 @end itemize
19880 @end itemize
19881
19882 @noindent
19883 In GNAT, the only restriction on pragma INLINE is that the
19884 body must occur before the call if both are in the same
19885 unit, and the size must be appropriately small. There are
19886 no other specific restrictions which cause subprograms to
19887 be incapable of being inlined.
19888
19889 @node  Restrictions on the Pragma INTERFACE
19890 @subsection  Restrictions on the Pragma INTERFACE
19891
19892 @noindent
19893 The following lists and describes the restrictions on the
19894 pragma INTERFACE on DEC Ada and GNAT:
19895 @itemize @bullet
19896 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
19897 Default is the default on OpenVMS Alpha systems.
19898
19899 @item  Parameter passing: Language specifies default
19900 mechanisms but can be overridden with an EXPORT pragma.
19901
19902 @itemize @bullet
19903 @item  Ada: Use internal Ada rules.
19904
19905 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
19906 record or task type. Result cannot be a string, an
19907 array, or a record.
19908
19909 @item  Fortran: Parameters cannot be a task. Result cannot
19910 be a string, an array, or a record.
19911 @end itemize
19912 @end itemize
19913
19914 @noindent
19915 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
19916 record parameters for all languages.
19917
19918 @node  Restrictions on the Pragma SYSTEM_NAME
19919 @subsection  Restrictions on the Pragma SYSTEM_NAME
19920
19921 @noindent
19922 For DEC Ada for OpenVMS Alpha, the enumeration literal
19923 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
19924 literal for the type NAME is SYSTEM_NAME_GNAT.
19925
19926 @node  Library of Predefined Units
19927 @section  Library of Predefined Units
19928
19929 @noindent
19930 A library of predefined units is provided as part of the
19931 DEC Ada and GNAT implementations. DEC Ada does not provide
19932 the package MACHINE_CODE but instead recommends importing
19933 assembler code.
19934
19935 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
19936 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
19937 version. During GNAT installation, the DEC Ada Predefined
19938 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
19939 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
19940 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
19941 for details.
19942
19943 The GNAT RTL is contained in
19944 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
19945 the default search path is set up to find DECLIB units in preference
19946 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
19947 for example).
19948
19949 However, it is possible to change the default so that the
19950 reverse is true, or even to mix them using child package
19951 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
19952 is the package name, and the Ada units are available in the
19953 standard manner defined for Ada 95, that is to say as Ada.xxx. To
19954 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
19955 appropriately. For example, to change the default to use the Ada95
19956 versions do:
19957
19958 @smallexample
19959 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
19960                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19961 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
19962                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19963 @end smallexample
19964
19965 @menu
19966 * Changes to DECLIB::
19967 @end menu
19968
19969 @node Changes to DECLIB
19970 @subsection Changes to DECLIB
19971
19972 @noindent
19973 The changes made to the DEC Ada predefined library for GNAT and Ada 95
19974 compatibility are minor and include the following:
19975
19976 @itemize @bullet
19977 @item  Adjusting the location of pragmas and record representation
19978 clauses to obey Ada 95 rules
19979
19980 @item  Adding the proper notation to generic formal parameters
19981 that take unconstrained types in instantiation
19982
19983 @item  Adding pragma ELABORATE_BODY to package specifications
19984 that have package bodies not otherwise allowed
19985
19986 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
19987 @code{"PROTECTD"}.
19988 Currently these are found only in the STARLET package spec.
19989 @end itemize
19990
19991 @noindent
19992 None of the above changes is visible to users.
19993
19994 @node Bindings
19995 @section Bindings
19996
19997 @noindent
19998 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
19999 @itemize @bullet
20000
20001 @item  Command Language Interpreter (CLI interface)
20002
20003 @item  DECtalk Run-Time Library (DTK interface)
20004
20005 @item  Librarian utility routines (LBR interface)
20006
20007 @item  General Purpose Run-Time Library (LIB interface)
20008
20009 @item  Math Run-Time Library (MTH interface)
20010
20011 @item  National Character Set Run-Time Library (NCS interface)
20012
20013 @item  Compiled Code Support Run-Time Library (OTS interface)
20014
20015 @item  Parallel Processing Run-Time Library (PPL interface)
20016
20017 @item  Screen Management Run-Time Library (SMG interface)
20018
20019 @item  Sort Run-Time Library (SOR interface)
20020
20021 @item  String Run-Time Library (STR interface)
20022
20023 @item STARLET System Library
20024 @findex Starlet
20025
20026 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20027
20028 @item  X Windows Toolkit (XT interface)
20029
20030 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20031 @end itemize
20032
20033 @noindent
20034 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20035
20036 The X/Motif bindings used to build DECLIB are whatever versions are in the
20037 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20038 The build script will
20039 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20040 and @code{X_Lib}
20041 causing the default X/Motif sharable image libraries to be linked in. This
20042 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20043 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20044
20045 It may be necessary to edit these options files to update or correct the
20046 library names if, for example, the newer X/Motif bindings from
20047 @file{ADA$EXAMPLES}
20048 had been (previous to installing GNAT) copied and renamed to supersede the
20049 default @file{ADA$PREDEFINED} versions.
20050
20051 @menu
20052 * Shared Libraries and Options Files::
20053 * Interfaces to C::
20054 @end menu
20055
20056 @node Shared Libraries and Options Files
20057 @subsection Shared Libraries and Options Files
20058
20059 @noindent
20060 When using the DEC Ada
20061 predefined X and Motif bindings, the linking with their sharable images is
20062 done automatically by @command{GNAT LINK}.
20063 When using other X and Motif bindings, you need
20064 to add the corresponding sharable images to the command line for
20065 @code{GNAT LINK}. When linking with shared libraries, or with
20066 @file{.OPT} files, you must
20067 also add them to the command line for @command{GNAT LINK}.
20068
20069 A shared library to be used with GNAT is built in the same way as other
20070 libraries under VMS. The VMS Link command can be used in standard fashion.
20071
20072 @node Interfaces to C
20073 @subsection Interfaces to C
20074
20075 @noindent
20076 DEC Ada
20077 provides the following Ada types and operations:
20078
20079 @itemize @bullet
20080 @item C types package (C_TYPES)
20081
20082 @item C strings (C_TYPES.NULL_TERMINATED)
20083
20084 @item Other_types (SHORT_INT)
20085 @end itemize
20086
20087 @noindent
20088 Interfacing to C with GNAT, one can use the above approach
20089 described for DEC Ada or the facilities of Annex B of
20090 the Ada 95 Reference Manual (packages INTERFACES.C,
20091 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20092 information, see the section ``Interfacing to C'' in the
20093 @cite{GNAT Reference Manual}.
20094
20095 The @option{-gnatF} qualifier forces default and explicit
20096 @code{External_Name} parameters in pragmas Import and Export
20097 to be uppercased for compatibility with the default behavior
20098 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20099
20100 @node Main Program Definition
20101 @section Main Program Definition
20102
20103 @noindent
20104 The following section discusses differences in the
20105 definition of main programs on DEC Ada and GNAT.
20106 On DEC Ada, main programs are defined to meet the
20107 following conditions:
20108 @itemize @bullet
20109 @item  Procedure with no formal parameters (returns 0 upon
20110        normal completion)
20111
20112 @item  Procedure with no formal parameters (returns 42 when
20113        unhandled exceptions are raised)
20114
20115 @item  Function with no formal parameters whose returned value
20116        is of a discrete type
20117
20118 @item  Procedure with one OUT formal of a discrete type for
20119        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20120
20121 @end itemize
20122
20123 @noindent
20124 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20125 a main function or main procedure returns a discrete
20126 value whose size is less than 64 bits (32 on VAX systems),
20127 the value is zero- or sign-extended as appropriate.
20128 On GNAT, main programs are defined as follows:
20129 @itemize @bullet
20130 @item  Must be a non-generic, parameter-less subprogram that
20131 is either a procedure or function returning an Ada
20132 STANDARD.INTEGER (the predefined type)
20133
20134 @item  Cannot be a generic subprogram or an instantiation of a
20135 generic subprogram
20136 @end itemize
20137
20138 @node Implementation-Defined Attributes
20139 @section Implementation-Defined Attributes
20140
20141 @noindent
20142 GNAT provides all DEC Ada implementation-defined
20143 attributes.
20144
20145 @node Compiler and Run-Time Interfacing
20146 @section Compiler and Run-Time Interfacing
20147
20148 @noindent
20149 DEC Ada provides the following ways to pass options to the linker
20150 (ACS LINK):
20151 @itemize @bullet
20152 @item  /WAIT and /SUBMIT qualifiers
20153
20154 @item  /COMMAND qualifier
20155
20156 @item  /[NO]MAP qualifier
20157
20158 @item  /OUTPUT=file-spec
20159
20160 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20161 @end itemize
20162
20163 @noindent
20164 To pass options to the linker, GNAT provides the following
20165 switches:
20166
20167 @itemize @bullet
20168 @item   @option{/EXECUTABLE=exec-name}
20169
20170 @item   @option{/VERBOSE qualifier}
20171
20172 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20173 @end itemize
20174
20175 @noindent
20176 For more information on these switches, see
20177 @ref{Switches for gnatlink}.
20178 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20179 to control optimization. DEC Ada also supplies the
20180 following pragmas:
20181 @itemize @bullet
20182 @item  @code{OPTIMIZE}
20183
20184 @item  @code{INLINE}
20185
20186 @item  @code{INLINE_GENERIC}
20187
20188 @item  @code{SUPPRESS_ALL}
20189
20190 @item  @code{PASSIVE}
20191 @end itemize
20192
20193 @noindent
20194 In GNAT, optimization is controlled strictly by command
20195 line parameters, as described in the corresponding section of this guide.
20196 The DIGITAL pragmas for control of optimization are
20197 recognized but ignored.
20198
20199 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20200 the default is that optimization is turned on.
20201
20202 @node Program Compilation and Library Management
20203 @section Program Compilation and Library Management
20204
20205 @noindent
20206 DEC Ada and GNAT provide a comparable set of commands to
20207 build programs. DEC Ada also provides a program library,
20208 which is a concept that does not exist on GNAT. Instead,
20209 GNAT provides directories of sources that are compiled as
20210 needed.
20211
20212 The following table summarizes
20213 the DEC Ada commands and provides
20214 equivalent GNAT commands. In this table, some GNAT
20215 equivalents reflect the fact that GNAT does not use the
20216 concept of a program library. Instead, it uses a model
20217 in which collections of source and object files are used
20218 in a manner consistent with other languages like C and
20219 Fortran. Therefore, standard system file commands are used
20220 to manipulate these elements. Those GNAT commands are marked with
20221 an asterisk.
20222 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20223
20224 @need 1500
20225 @multitable @columnfractions .35 .65
20226
20227 @item @emph{DEC Ada Command}
20228 @tab @emph{GNAT Equivalent / Description}
20229
20230 @item @command{ADA}
20231 @tab @command{GNAT COMPILE}@*
20232 Invokes the compiler to compile one or more Ada source files.
20233
20234 @item @command{ACS ATTACH}@*
20235 @tab [No equivalent]@*
20236 Switches control of terminal from current process running the program
20237 library manager.
20238
20239 @item @command{ACS CHECK}
20240 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20241 Forms the execution closure of one
20242 or more compiled units and checks completeness and currency.
20243
20244 @item @command{ACS COMPILE}
20245 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20246 Forms the execution closure of one or
20247 more specified units, checks completeness and currency,
20248 identifies units that have revised source files, compiles same,
20249 and recompiles units that are or will become obsolete.
20250 Also completes incomplete generic instantiations.
20251
20252 @item @command{ACS COPY FOREIGN}
20253 @tab Copy (*)@*
20254 Copies a foreign object file into the program library as a
20255 library unit body.
20256
20257 @item @command{ACS COPY UNIT}
20258 @tab Copy (*)@*
20259 Copies a compiled unit from one program library to another.
20260
20261 @item @command{ACS CREATE LIBRARY}
20262 @tab Create /directory (*)@*
20263 Creates a program library.
20264
20265 @item @command{ACS CREATE SUBLIBRARY}
20266 @tab Create /directory (*)@*
20267 Creates a program sublibrary.
20268
20269 @item @command{ACS DELETE LIBRARY}
20270 @tab @*
20271 Deletes a program library and its contents.
20272
20273 @item @command{ACS DELETE SUBLIBRARY}
20274 @tab @*
20275 Deletes a program sublibrary and its contents.
20276
20277 @item @command{ACS DELETE UNIT}
20278 @tab Delete file (*)@*
20279 On OpenVMS systems, deletes one or more compiled units from
20280 the current program library.
20281
20282 @item @command{ACS DIRECTORY}
20283 @tab Directory (*)@*
20284 On OpenVMS systems, lists units contained in the current
20285 program library.
20286
20287 @item @command{ACS ENTER FOREIGN}
20288 @tab Copy (*)@*
20289 Allows the import of a foreign body as an Ada library
20290 specification and enters a reference to a pointer.
20291
20292 @item @command{ACS ENTER UNIT}
20293 @tab Copy (*)@*
20294 Enters a reference (pointer) from the current program library to
20295 a unit compiled into another program library.
20296
20297 @item @command{ACS EXIT}
20298 @tab [No equivalent]@*
20299 Exits from the program library manager.
20300
20301 @item @command{ACS EXPORT}
20302 @tab Copy (*)@*
20303 Creates an object file that contains system-specific object code
20304 for one or more units. With GNAT, object files can simply be copied
20305 into the desired directory.
20306
20307 @item @command{ACS EXTRACT SOURCE}
20308 @tab Copy (*)@*
20309 Allows access to the copied source file for each Ada compilation unit
20310
20311 @item @command{ACS HELP}
20312 @tab @command{HELP GNAT}@*
20313 Provides online help.
20314
20315 @item @command{ACS LINK}
20316 @tab @command{GNAT LINK}@*
20317 Links an object file containing Ada units into an executable file.
20318
20319 @item @command{ACS LOAD}
20320 @tab Copy (*)@*
20321 Loads (partially compiles) Ada units into the program library.
20322 Allows loading a program from a collection of files into a library
20323 without knowing the relationship among units.
20324
20325 @item @command{ACS MERGE}
20326 @tab Copy (*)@*
20327 Merges into the current program library, one or more units from
20328 another library where they were modified.
20329
20330 @item @command{ACS RECOMPILE}
20331 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20332 Recompiles from   external or copied source files any obsolete
20333 unit in the closure. Also, completes any incomplete generic
20334 instantiations.
20335
20336 @item @command{ACS REENTER}
20337 @tab @command{GNAT MAKE}@*
20338 Reenters current references to units compiled after last entered
20339 with the @command{ACS ENTER UNIT} command.
20340
20341 @item @command{ACS SET LIBRARY}
20342 @tab Set default (*)@*
20343 Defines a program library to be the compilation context as well
20344 as the target library for compiler output and commands in general.
20345
20346 @item @command{ACS SET PRAGMA}
20347 @tab Edit @file{gnat.adc} (*)@*
20348 Redefines specified  values of the library characteristics
20349 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20350 and @code{Float_Representation}.
20351
20352 @item @command{ACS SET SOURCE}
20353 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20354 Defines the source file search list for the @command{ACS COMPILE} command.
20355
20356 @item @command{ACS SHOW LIBRARY}
20357 @tab Directory (*)@*
20358 Lists information about one or more program libraries.
20359
20360 @item @command{ACS SHOW PROGRAM}
20361 @tab [No equivalent]@*
20362 Lists information about the execution closure of one or
20363 more units in the program library.
20364
20365 @item @command{ACS SHOW SOURCE}
20366 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20367 Shows the source file search used when compiling units.
20368
20369 @item @command{ACS SHOW VERSION}
20370 @tab Compile with @option{VERBOSE} option
20371 Displays the version number of the compiler and program library
20372 manager used.
20373
20374 @item @command{ACS SPAWN}
20375 @tab [No equivalent]@*
20376 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20377 command).
20378
20379 @item @command{ACS VERIFY}
20380 @tab [No equivalent]@*
20381 Performs a series of consistency checks on a program library to
20382 determine whether the library structure and library files are in
20383 valid form.
20384 @end multitable
20385
20386 @noindent
20387
20388 @node Input-Output
20389 @section Input-Output
20390
20391 @noindent
20392 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20393 Management Services (RMS) to perform operations on
20394 external files.
20395
20396 @noindent
20397 DEC Ada and GNAT predefine an identical set of input-
20398 output packages. To make the use of the
20399 generic TEXT_IO operations more convenient, DEC Ada
20400 provides predefined library packages that instantiate the
20401 integer and floating-point operations for the predefined
20402 integer and floating-point types as shown in the following table.
20403
20404 @multitable @columnfractions .45 .55
20405 @item @emph{Package Name} @tab Instantiation
20406
20407 @item @code{INTEGER_TEXT_IO}
20408 @tab @code{INTEGER_IO(INTEGER)}
20409
20410 @item @code{SHORT_INTEGER_TEXT_IO}
20411 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20412
20413 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20414 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20415
20416 @item @code{FLOAT_TEXT_IO}
20417 @tab @code{FLOAT_IO(FLOAT)}
20418
20419 @item @code{LONG_FLOAT_TEXT_IO}
20420 @tab @code{FLOAT_IO(LONG_FLOAT)}
20421 @end multitable
20422
20423 @noindent
20424 The DEC Ada predefined packages and their operations
20425 are implemented using OpenVMS Alpha files and input-
20426 output facilities. DEC Ada supports asynchronous input-
20427 output on OpenVMS Alpha. Familiarity with the following is
20428 recommended:
20429 @itemize @bullet
20430 @item  RMS file organizations and access methods
20431
20432 @item  OpenVMS file specifications and directories
20433
20434 @item  OpenVMS File Definition Language (FDL)
20435 @end itemize
20436
20437 @noindent
20438 GNAT provides I/O facilities that are completely
20439 compatible with DEC Ada. The distribution includes the
20440 standard DEC Ada versions of all I/O packages, operating
20441 in a manner compatible with DEC Ada. In particular, the
20442 following packages are by default the DEC Ada (Ada 83)
20443 versions of these packages rather than the renamings
20444 suggested in annex J of the Ada 95 Reference Manual:
20445 @itemize @bullet
20446 @item  @code{TEXT_IO}
20447
20448 @item  @code{SEQUENTIAL_IO}
20449
20450 @item  @code{DIRECT_IO}
20451 @end itemize
20452
20453 @noindent
20454 The use of the standard Ada 95 syntax for child packages (for
20455 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20456 packages, as defined in the Ada 95 Reference Manual.
20457 GNAT provides DIGITAL-compatible predefined instantiations
20458 of the @code{TEXT_IO} packages, and also
20459 provides the standard predefined instantiations required
20460 by the Ada 95 Reference Manual.
20461
20462 For further information on how GNAT interfaces to the file
20463 system or how I/O is implemented in programs written in
20464 mixed languages, see the chapter ``Implementation of the
20465 Standard I/O'' in the @cite{GNAT Reference Manual}.
20466 This chapter covers the following:
20467 @itemize @bullet
20468 @item  Standard I/O packages
20469
20470 @item  @code{FORM} strings
20471
20472 @item  @code{ADA.DIRECT_IO}
20473
20474 @item  @code{ADA.SEQUENTIAL_IO}
20475
20476 @item  @code{ADA.TEXT_IO}
20477
20478 @item  Stream pointer positioning
20479
20480 @item  Reading and writing non-regular files
20481
20482 @item  @code{GET_IMMEDIATE}
20483
20484 @item  Treating @code{TEXT_IO} files as streams
20485
20486 @item  Shared files
20487
20488 @item  Open modes
20489 @end itemize
20490
20491 @node Implementation Limits
20492 @section Implementation Limits
20493
20494 @noindent
20495 The following table lists implementation limits for DEC Ada
20496 and GNAT systems.
20497 @multitable @columnfractions .60 .20 .20
20498 @sp 1
20499 @item  @emph{Compilation Parameter}
20500 @tab   @emph{DEC Ada}
20501 @tab   @emph{GNAT}
20502 @sp 1
20503
20504 @item  In a subprogram or entry  declaration, maximum number of
20505        formal parameters that are of an unconstrained record type
20506 @tab   32
20507 @tab   No set limit
20508 @sp 1
20509
20510 @item  Maximum identifier length (number of characters)
20511 @tab   255
20512 @tab   255
20513 @sp 1
20514
20515 @item  Maximum number of characters in a source line
20516 @tab   255
20517 @tab   255
20518 @sp 1
20519
20520 @item  Maximum collection size   (number of bytes)
20521 @tab   2**31-1
20522 @tab   2**31-1
20523 @sp 1
20524
20525 @item  Maximum number of discriminants for a record type
20526 @tab   245
20527 @tab   No set limit
20528 @sp 1
20529
20530 @item  Maximum number of formal parameters in an entry or
20531        subprogram declaration
20532 @tab   246
20533 @tab    No set limit
20534 @sp 1
20535
20536 @item  Maximum number of dimensions in an array type
20537 @tab   255
20538 @tab   No set limit
20539 @sp 1
20540
20541 @item  Maximum number of library  units and subunits in a compilation.
20542 @tab   4095
20543 @tab   No set limit
20544 @sp 1
20545
20546 @item  Maximum number of library units and subunits in an execution.
20547 @tab   16383
20548 @tab   No set limit
20549 @sp 1
20550
20551 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20552        or @code{PSECT_OBJECT}
20553 @tab   32757
20554 @tab   No set limit
20555 @sp 1
20556
20557 @item  Maximum number of enumeration literals in an enumeration type
20558        definition
20559 @tab   65535
20560 @tab   No set limit
20561 @sp 1
20562
20563 @item  Maximum number of lines in a source file
20564 @tab   65534
20565 @tab   No set limit
20566 @sp 1
20567
20568 @item  Maximum number of bits in any object
20569 @tab   2**31-1
20570 @tab   2**31-1
20571 @sp 1
20572
20573 @item  Maximum size of the static portion of a stack frame (approximate)
20574 @tab   2**31-1
20575 @tab   2**31-1
20576 @end multitable
20577
20578 @node  Tools
20579 @section Tools
20580
20581 @end ifset
20582
20583
20584 @c **************************************
20585 @node Platform-Specific Information for the Run-Time Libraries
20586 @appendix Platform-Specific Information for the Run-Time Libraries
20587 @cindex Tasking and threads libraries
20588 @cindex Threads libraries and tasking
20589 @cindex Run-time libraries (platform-specific information)
20590
20591 @noindent
20592 The GNAT run-time implementation
20593 may vary with respect to both the underlying threads library and
20594 the exception handling scheme.
20595 For threads support, one or more of the following are supplied:
20596 @itemize @bullet
20597 @item @b{native threads library}, a binding to the thread package from
20598 the underlying operating system
20599
20600 @item @b{FSU threads library}, a binding to the Florida State University
20601 threads implementation, which complies fully with the requirements of Annex D
20602
20603 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20604 POSIX thread package
20605 @end itemize
20606
20607 @noindent
20608 For exception handling, either or both of two models are supplied:
20609 @itemize @bullet
20610 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20611 Most programs should experience a substantial speed improvement by
20612 being compiled with a ZCX run-time.
20613 This is especially true for
20614 tasking applications or applications with many exception handlers.}
20615 @cindex Zero-Cost Exceptions
20616 @cindex ZCX (Zero-Cost Exceptions)
20617 which uses binder-generated tables that
20618 are interrogated at run time to locate a handler
20619
20620 @item @b{setjmp / longjmp} (``SJLJ''),
20621 @cindex setjmp/longjmp Exception Model
20622 @cindex SJLJ (setjmp/longjmp Exception Model)
20623 which uses dynamically-set data to establish
20624 the set of handlers
20625 @end itemize
20626
20627 @noindent
20628 This appendix summarizes which combinations of threads and exception support
20629 are supplied on various GNAT platforms.
20630 It then shows how to select a particular library either
20631 permanently or temporarily,
20632 explains the properties of (and tradeoffs among) the various threads
20633 libraries, and provides some additional
20634 information about several specific platforms.
20635
20636 @menu
20637 * Summary of Run-Time Configurations::
20638 * Specifying a Run-Time Library::
20639 * Choosing between Native and FSU Threads Libraries::
20640 * Choosing the Scheduling Policy::
20641 * Solaris-Specific Considerations::
20642 * IRIX-Specific Considerations::
20643 * Linux-Specific Considerations::
20644 @end menu
20645
20646
20647 @node Summary of Run-Time Configurations
20648 @section Summary of Run-Time Configurations
20649
20650
20651 @multitable @columnfractions .30 .70
20652 @item @b{alpha-openvms}
20653 @item @code{@ @ }@i{rts-native (default)}
20654 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20655 @item @code{@ @ @ @ }Exceptions @tab ZCX
20656 @*
20657 @item @b{pa-hpux}
20658 @item @code{@ @ }@i{rts-native (default)}
20659 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20660 @item @code{@ @ @ @ }Exceptions @tab ZCX
20661 @*
20662 @item @code{@ @ }@i{rts-sjlj}
20663 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20664 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20665 @*
20666 @item @b{sparc-solaris}  @tab
20667 @item @code{@ @ }@i{rts-native (default)}
20668 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20669 @item @code{@ @ @ @ }Exceptions @tab ZCX
20670 @*
20671 @item @code{@ @ }@i{rts-fsu}    @tab
20672 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20673 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20674 @*
20675 @item @code{@ @ }@i{rts-m64}
20676 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20677 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20678 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20679 @item    @tab Use only on Solaris 8 or later.
20680 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20681 @*
20682 @item @code{@ @ }@i{rts-pthread}
20683 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20684 @item @code{@ @ @ @ }Exceptions @tab ZCX
20685 @*
20686 @item @code{@ @ }@i{rts-sjlj}
20687 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20688 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20689 @*
20690 @item @b{x86-linux}
20691 @item @code{@ @ }@i{rts-native (default)}
20692 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20693 @item @code{@ @ @ @ }Exceptions @tab ZCX
20694 @*
20695 @item @code{@ @ }@i{rts-fsu}
20696 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20697 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20698 @*
20699 @item @code{@ @ }@i{rts-sjlj}
20700 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20701 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20702 @*
20703 @item @b{x86-windows}
20704 @item @code{@ @ }@i{rts-native (default)}
20705 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
20706 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20707 @*
20708 @end multitable
20709
20710
20711
20712 @node Specifying a Run-Time Library
20713 @section Specifying a Run-Time Library
20714
20715 @noindent
20716 The @file{adainclude} subdirectory containing the sources of the GNAT
20717 run-time library, and the @file{adalib} subdirectory containing the
20718 @file{ALI} files and the static and/or shared GNAT library, are located
20719 in the gcc target-dependent area:
20720
20721 @smallexample
20722 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
20723 @end smallexample
20724
20725 @noindent
20726 As indicated above, on some platforms several run-time libraries are supplied.
20727 These libraries are installed in the target dependent area and
20728 contain a complete source and binary subdirectory. The detailed description
20729 below explains the differences between the different libraries in terms of
20730 their thread support.
20731
20732 The default run-time library (when GNAT is installed) is @emph{rts-native}.
20733 This default run time is selected by the means of soft links.
20734 For example on x86-linux:
20735
20736 @smallexample
20737 @group
20738  $(target-dir)
20739      |
20740      +--- adainclude----------+
20741      |                        |
20742      +--- adalib-----------+  |
20743      |                     |  |
20744      +--- rts-native       |  |
20745      |    |                |  |
20746      |    +--- adainclude <---+
20747      |    |                |
20748      |    +--- adalib <----+
20749      |
20750      +--- rts-fsu
20751      |    |
20752      |    +--- adainclude
20753      |    |
20754      |    +--- adalib
20755      |
20756      +--- rts-sjlj
20757           |
20758           +--- adainclude
20759           |
20760           +--- adalib
20761 @end group
20762 @end smallexample
20763
20764 @noindent
20765 If the @i{rts-fsu} library is to be selected on a permanent basis,
20766 these soft links can be modified with the following commands:
20767
20768 @smallexample
20769 $ cd $target
20770 $ rm -f adainclude adalib
20771 $ ln -s rts-fsu/adainclude adainclude
20772 $ ln -s rts-fsu/adalib adalib
20773 @end smallexample
20774
20775 @noindent
20776 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
20777 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
20778 @file{$target/ada_object_path}.
20779
20780 Selecting another run-time library temporarily can be
20781 achieved by the regular mechanism for GNAT object or source path selection:
20782
20783 @itemize @bullet
20784 @item
20785 Set the environment variables:
20786
20787 @smallexample
20788 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
20789 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
20790 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
20791 @end smallexample
20792
20793 @item
20794 Use @option{-aI$target/rts-fsu/adainclude}
20795 and @option{-aO$target/rts-fsu/adalib}
20796 on the @command{gnatmake} command line
20797
20798 @item
20799 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
20800 @cindex @option{--RTS} option
20801 @end itemize
20802
20803 @noindent
20804 You can similarly switch to @emph{rts-sjlj}.
20805
20806 @node Choosing between Native and FSU Threads Libraries
20807 @section Choosing between Native and FSU Threads Libraries
20808 @cindex Native threads library
20809 @cindex FSU threads library
20810
20811 @noindent
20812 Some GNAT implementations offer a choice between
20813 native threads and FSU threads.
20814
20815 @itemize @bullet
20816 @item
20817 The @emph{native threads} library correspond to the standard system threads
20818 implementation (e.g. LinuxThreads on GNU/Linux,
20819 @cindex LinuxThreads library
20820 POSIX threads on AIX, or
20821 Solaris threads on Solaris). When this option is chosen, GNAT provides
20822 a full and accurate implementation of the core language tasking model
20823 as described in Chapter 9 of the Ada Reference Manual,
20824 but might not (and probably does not) implement
20825 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
20826 @cindex Annex D (Real-Time Systems Annex) compliance
20827 @cindex Real-Time Systems Annex compliance
20828 Indeed, the reason that a choice of libraries is offered
20829 on a given target is because some of the
20830 ACATS tests for @w{Annex D} fail using the native threads library.
20831 As far as possible, this library is implemented
20832 in accordance with Ada semantics (e.g., modifying priorities as required
20833 to simulate ceiling locking),
20834 but there are often slight inaccuracies, most often in the area of
20835 absolutely respecting the priority rules on a single
20836 processor.
20837 Moreover, it is not possible in general to define the exact behavior,
20838 because the native threads implementations
20839 are not well enough documented.
20840
20841 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
20842 @cindex POSIX scheduling policies
20843 @cindex @code{SCHED_FIFO} scheduling policy
20844 native threads will provide a behavior very close to the @w{Annex D}
20845 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
20846 on some systems (in particular GNU/Linux and Solaris), you need to have root
20847 privileges to use the @code{SCHED_FIFO} policy.
20848
20849 @item
20850 The @emph{FSU threads} library provides a completely accurate implementation
20851 of @w{Annex D}.
20852 Thus, operating with this library, GNAT is 100% compliant with both the core
20853 and all @w{Annex D}
20854 requirements.
20855 The formal validations for implementations offering
20856 a choice of threads packages are always carried out using the FSU
20857 threads option.
20858 @end itemize
20859
20860 @noindent
20861 From these considerations, it might seem that FSU threads are the
20862 better choice,
20863 but that is by no means always the case. The FSU threads package
20864 operates with all Ada tasks appearing to the system to be a single
20865 thread. This is often considerably more efficient than operating
20866 with separate threads, since for example, switching between tasks
20867 can be accomplished without the (in some cases considerable)
20868 overhead of a context switch between two system threads. However,
20869 it means that you may well lose concurrency at the system
20870 level. Notably, some system operations (such as I/O) may block all
20871 tasks in a program and not just the calling task. More
20872 significantly, the FSU threads approach likely means you cannot
20873 take advantage of multiple processors, since for this you need
20874 separate threads (or even separate processes) to operate on
20875 different processors.
20876
20877 For most programs, the native threads library is
20878 usually the better choice. Use the FSU threads if absolute
20879 conformance to @w{Annex D} is important for your application, or if
20880 you find that the improved efficiency of FSU threads is significant to you.
20881
20882 Note also that to take full advantage of Florist and Glade, it is highly
20883 recommended that you use native threads.
20884
20885
20886 @node Choosing the Scheduling Policy
20887 @section Choosing the Scheduling Policy
20888
20889 @noindent
20890 When using a POSIX threads implementation, you have a choice of several
20891 scheduling policies: @code{SCHED_FIFO},
20892 @cindex @code{SCHED_FIFO} scheduling policy
20893 @code{SCHED_RR}
20894 @cindex @code{SCHED_RR} scheduling policy
20895 and @code{SCHED_OTHER}.
20896 @cindex @code{SCHED_OTHER} scheduling policy
20897 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
20898 or @code{SCHED_RR} requires special (e.g., root) privileges.
20899
20900 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
20901 @code{SCHED_FIFO},
20902 @cindex @code{SCHED_FIFO} scheduling policy
20903 you can use one of the following:
20904
20905 @itemize @bullet
20906 @item
20907 @code{pragma Time_Slice (0.0)}
20908 @cindex pragma Time_Slice
20909 @item
20910 the corresponding binder option @option{-T0}
20911 @cindex @option{-T0} option
20912 @item
20913 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
20914 @cindex pragma Task_Dispatching_Policy
20915 @end itemize
20916
20917 @noindent
20918 To specify @code{SCHED_RR},
20919 @cindex @code{SCHED_RR} scheduling policy
20920 you should use @code{pragma Time_Slice} with a
20921 value greater than @code{0.0}, or else use the corresponding @option{-T}
20922 binder option.
20923
20924
20925
20926 @node Solaris-Specific Considerations
20927 @section Solaris-Specific Considerations
20928 @cindex Solaris Sparc threads libraries
20929
20930 @noindent
20931 This section addresses some topics related to the various threads libraries
20932 on Sparc Solaris and then provides some information on building and
20933 debugging 64-bit applications.
20934
20935 @menu
20936 * Solaris Threads Issues::
20937 * Building and Debugging 64-bit Applications::
20938 @end menu
20939
20940
20941 @node Solaris Threads Issues
20942 @subsection Solaris Threads Issues
20943
20944 @noindent
20945 Starting with version 3.14, GNAT under Solaris comes with a new tasking
20946 run-time library based on POSIX threads --- @emph{rts-pthread}.
20947 @cindex rts-pthread threads library
20948 This run-time library has the advantage of being mostly shared across all
20949 POSIX-compliant thread implementations, and it also provides under
20950 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
20951 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
20952 and @code{PTHREAD_PRIO_PROTECT}
20953 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
20954 semantics that can be selected using the predefined pragma
20955 @code{Locking_Policy}
20956 @cindex pragma Locking_Policy (under rts-pthread)
20957 with respectively
20958 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
20959 @cindex @code{Inheritance_Locking} (under rts-pthread)
20960 @cindex @code{Ceiling_Locking} (under rts-pthread)
20961
20962 As explained above, the native run-time library is based on the Solaris thread
20963 library (@code{libthread}) and is the default library.
20964 The FSU run-time library is based on the FSU threads.
20965 @cindex FSU threads library
20966
20967 Starting with Solaris 2.5.1, when the Solaris threads library is used
20968 (this is the default), programs
20969 compiled with GNAT can automatically take advantage of
20970 and can thus execute on multiple processors.
20971 The user can alternatively specify a processor on which the program should run
20972 to emulate a single-processor system. The multiprocessor / uniprocessor choice
20973 is made by
20974 setting the environment variable @code{GNAT_PROCESSOR}
20975 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
20976 to one of the following:
20977
20978 @table @code
20979 @item -2
20980 Use the default configuration (run the program on all
20981          available processors) - this is the same as having
20982          @code{GNAT_PROCESSOR} unset
20983
20984 @item -1
20985 Let the run-time implementation choose one processor and run the program on
20986          that processor
20987
20988 @item 0 .. Last_Proc
20989 Run the program on the specified processor.
20990   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
20991 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
20992 @end table
20993
20994
20995 @node Building and Debugging 64-bit Applications
20996 @subsection Building and Debugging 64-bit Applications
20997
20998 @noindent
20999 In a 64-bit application, all the sources involved must be compiled with the
21000 @option{-m64} command-line option, and a specific GNAT library (compiled with
21001 this option) is required.
21002 The easiest way to build a 64bit application is to add
21003 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21004
21005 To debug these applications, dwarf-2 debug information is required, so you
21006 have to add @option{-gdwarf-2} to your gnatmake arguments.
21007 In addition, a special
21008 version of gdb, called @command{gdb64}, needs to be used.
21009
21010 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21011 amounts to:
21012
21013 @smallexample
21014      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21015      $ gdb64 hello
21016 @end smallexample
21017
21018
21019
21020 @node IRIX-Specific Considerations
21021 @section IRIX-Specific Considerations
21022 @cindex IRIX thread library
21023
21024 @noindent
21025 On SGI IRIX, the thread library depends on which compiler is used.
21026 The @emph{o32 ABI} compiler comes with a run-time library based on the
21027 user-level @code{athread}
21028 library. Thus kernel-level capabilities such as nonblocking system
21029 calls or time slicing can only be achieved reliably by specifying different
21030 @code{sprocs} via the pragma @code{Task_Info}
21031 @cindex pragma Task_Info (and IRIX threads)
21032 and the
21033 @code{System.Task_Info} package.
21034 @cindex @code{System.Task_Info} package (and IRIX threads)
21035 See the @cite{GNAT Reference Manual} for further information.
21036
21037 The @emph{n32 ABI} compiler comes with a run-time library based on the
21038 kernel POSIX threads and thus does not have the limitations mentioned above.
21039
21040
21041 @node Linux-Specific Considerations
21042 @section Linux-Specific Considerations
21043 @cindex Linux threads libraries
21044
21045 @noindent
21046 The default thread library under GNU/Linux has the following disadvantages
21047 compared to other native thread libraries:
21048
21049 @itemize @bullet
21050 @item The size of the task's stack is limited to 2 megabytes.
21051 @item  The signal model is not POSIX compliant, which means that to send a
21052   signal to the process, you need to send the signal to all threads,
21053   e.g. by using @code{killpg()}.
21054 @end itemize
21055
21056
21057
21058 @c *******************************
21059 @node Example of Binder Output File
21060 @appendix Example of Binder Output File
21061
21062 @noindent
21063 This Appendix displays the source code for @command{gnatbind}'s output
21064 file generated for a simple ``Hello World'' program.
21065 Comments have been added for clarification purposes.
21066
21067
21068 @smallexample @c adanocomment
21069 @iftex
21070 @leftskip=0cm
21071 @end iftex
21072 --  The package is called Ada_Main unless this name is actually used
21073 --  as a unit name in the partition, in which case some other unique
21074 --  name is used.
21075
21076 with System;
21077 package ada_main is
21078
21079    Elab_Final_Code : Integer;
21080    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21081
21082    --  The main program saves the parameters (argument count,
21083    --  argument values, environment pointer) in global variables
21084    --  for later access by other units including
21085    --  Ada.Command_Line.
21086
21087    gnat_argc : Integer;
21088    gnat_argv : System.Address;
21089    gnat_envp : System.Address;
21090
21091    --  The actual variables are stored in a library routine. This
21092    --  is useful for some shared library situations, where there
21093    --  are problems if variables are not in the library.
21094
21095    pragma Import (C, gnat_argc);
21096    pragma Import (C, gnat_argv);
21097    pragma Import (C, gnat_envp);
21098
21099    --  The exit status is similarly an external location
21100
21101    gnat_exit_status : Integer;
21102    pragma Import (C, gnat_exit_status);
21103
21104    GNAT_Version : constant String :=
21105                     "GNAT Version: 3.15w (20010315)";
21106    pragma Export (C, GNAT_Version, "__gnat_version");
21107
21108    --  This is the generated adafinal routine that performs
21109    --  finalization at the end of execution. In the case where
21110    --  Ada is the main program, this main program makes a call
21111    --  to adafinal at program termination.
21112
21113    procedure adafinal;
21114    pragma Export (C, adafinal, "adafinal");
21115
21116    --  This is the generated adainit routine that performs
21117    --  initialization at the start of execution. In the case
21118    --  where Ada is the main program, this main program makes
21119    --  a call to adainit at program startup.
21120
21121    procedure adainit;
21122    pragma Export (C, adainit, "adainit");
21123
21124    --  This routine is called at the start of execution. It is
21125    --  a dummy routine that is used by the debugger to breakpoint
21126    --  at the start of execution.
21127
21128    procedure Break_Start;
21129    pragma Import (C, Break_Start, "__gnat_break_start");
21130
21131    --  This is the actual generated main program (it would be
21132    --  suppressed if the no main program switch were used). As
21133    --  required by standard system conventions, this program has
21134    --  the external name main.
21135
21136    function main
21137      (argc : Integer;
21138       argv : System.Address;
21139       envp : System.Address)
21140       return Integer;
21141    pragma Export (C, main, "main");
21142
21143    --  The following set of constants give the version
21144    --  identification values for every unit in the bound
21145    --  partition. This identification is computed from all
21146    --  dependent semantic units, and corresponds to the
21147    --  string that would be returned by use of the
21148    --  Body_Version or Version attributes.
21149
21150    type Version_32 is mod 2 ** 32;
21151    u00001 : constant Version_32 := 16#7880BEB3#;
21152    u00002 : constant Version_32 := 16#0D24CBD0#;
21153    u00003 : constant Version_32 := 16#3283DBEB#;
21154    u00004 : constant Version_32 := 16#2359F9ED#;
21155    u00005 : constant Version_32 := 16#664FB847#;
21156    u00006 : constant Version_32 := 16#68E803DF#;
21157    u00007 : constant Version_32 := 16#5572E604#;
21158    u00008 : constant Version_32 := 16#46B173D8#;
21159    u00009 : constant Version_32 := 16#156A40CF#;
21160    u00010 : constant Version_32 := 16#033DABE0#;
21161    u00011 : constant Version_32 := 16#6AB38FEA#;
21162    u00012 : constant Version_32 := 16#22B6217D#;
21163    u00013 : constant Version_32 := 16#68A22947#;
21164    u00014 : constant Version_32 := 16#18CC4A56#;
21165    u00015 : constant Version_32 := 16#08258E1B#;
21166    u00016 : constant Version_32 := 16#367D5222#;
21167    u00017 : constant Version_32 := 16#20C9ECA4#;
21168    u00018 : constant Version_32 := 16#50D32CB6#;
21169    u00019 : constant Version_32 := 16#39A8BB77#;
21170    u00020 : constant Version_32 := 16#5CF8FA2B#;
21171    u00021 : constant Version_32 := 16#2F1EB794#;
21172    u00022 : constant Version_32 := 16#31AB6444#;
21173    u00023 : constant Version_32 := 16#1574B6E9#;
21174    u00024 : constant Version_32 := 16#5109C189#;
21175    u00025 : constant Version_32 := 16#56D770CD#;
21176    u00026 : constant Version_32 := 16#02F9DE3D#;
21177    u00027 : constant Version_32 := 16#08AB6B2C#;
21178    u00028 : constant Version_32 := 16#3FA37670#;
21179    u00029 : constant Version_32 := 16#476457A0#;
21180    u00030 : constant Version_32 := 16#731E1B6E#;
21181    u00031 : constant Version_32 := 16#23C2E789#;
21182    u00032 : constant Version_32 := 16#0F1BD6A1#;
21183    u00033 : constant Version_32 := 16#7C25DE96#;
21184    u00034 : constant Version_32 := 16#39ADFFA2#;
21185    u00035 : constant Version_32 := 16#571DE3E7#;
21186    u00036 : constant Version_32 := 16#5EB646AB#;
21187    u00037 : constant Version_32 := 16#4249379B#;
21188    u00038 : constant Version_32 := 16#0357E00A#;
21189    u00039 : constant Version_32 := 16#3784FB72#;
21190    u00040 : constant Version_32 := 16#2E723019#;
21191    u00041 : constant Version_32 := 16#623358EA#;
21192    u00042 : constant Version_32 := 16#107F9465#;
21193    u00043 : constant Version_32 := 16#6843F68A#;
21194    u00044 : constant Version_32 := 16#63305874#;
21195    u00045 : constant Version_32 := 16#31E56CE1#;
21196    u00046 : constant Version_32 := 16#02917970#;
21197    u00047 : constant Version_32 := 16#6CCBA70E#;
21198    u00048 : constant Version_32 := 16#41CD4204#;
21199    u00049 : constant Version_32 := 16#572E3F58#;
21200    u00050 : constant Version_32 := 16#20729FF5#;
21201    u00051 : constant Version_32 := 16#1D4F93E8#;
21202    u00052 : constant Version_32 := 16#30B2EC3D#;
21203    u00053 : constant Version_32 := 16#34054F96#;
21204    u00054 : constant Version_32 := 16#5A199860#;
21205    u00055 : constant Version_32 := 16#0E7F912B#;
21206    u00056 : constant Version_32 := 16#5760634A#;
21207    u00057 : constant Version_32 := 16#5D851835#;
21208
21209    --  The following Export pragmas export the version numbers
21210    --  with symbolic names ending in B (for body) or S
21211    --  (for spec) so that they can be located in a link. The
21212    --  information provided here is sufficient to track down
21213    --  the exact versions of units used in a given build.
21214
21215    pragma Export (C, u00001, "helloB");
21216    pragma Export (C, u00002, "system__standard_libraryB");
21217    pragma Export (C, u00003, "system__standard_libraryS");
21218    pragma Export (C, u00004, "adaS");
21219    pragma Export (C, u00005, "ada__text_ioB");
21220    pragma Export (C, u00006, "ada__text_ioS");
21221    pragma Export (C, u00007, "ada__exceptionsB");
21222    pragma Export (C, u00008, "ada__exceptionsS");
21223    pragma Export (C, u00009, "gnatS");
21224    pragma Export (C, u00010, "gnat__heap_sort_aB");
21225    pragma Export (C, u00011, "gnat__heap_sort_aS");
21226    pragma Export (C, u00012, "systemS");
21227    pragma Export (C, u00013, "system__exception_tableB");
21228    pragma Export (C, u00014, "system__exception_tableS");
21229    pragma Export (C, u00015, "gnat__htableB");
21230    pragma Export (C, u00016, "gnat__htableS");
21231    pragma Export (C, u00017, "system__exceptionsS");
21232    pragma Export (C, u00018, "system__machine_state_operationsB");
21233    pragma Export (C, u00019, "system__machine_state_operationsS");
21234    pragma Export (C, u00020, "system__machine_codeS");
21235    pragma Export (C, u00021, "system__storage_elementsB");
21236    pragma Export (C, u00022, "system__storage_elementsS");
21237    pragma Export (C, u00023, "system__secondary_stackB");
21238    pragma Export (C, u00024, "system__secondary_stackS");
21239    pragma Export (C, u00025, "system__parametersB");
21240    pragma Export (C, u00026, "system__parametersS");
21241    pragma Export (C, u00027, "system__soft_linksB");
21242    pragma Export (C, u00028, "system__soft_linksS");
21243    pragma Export (C, u00029, "system__stack_checkingB");
21244    pragma Export (C, u00030, "system__stack_checkingS");
21245    pragma Export (C, u00031, "system__tracebackB");
21246    pragma Export (C, u00032, "system__tracebackS");
21247    pragma Export (C, u00033, "ada__streamsS");
21248    pragma Export (C, u00034, "ada__tagsB");
21249    pragma Export (C, u00035, "ada__tagsS");
21250    pragma Export (C, u00036, "system__string_opsB");
21251    pragma Export (C, u00037, "system__string_opsS");
21252    pragma Export (C, u00038, "interfacesS");
21253    pragma Export (C, u00039, "interfaces__c_streamsB");
21254    pragma Export (C, u00040, "interfaces__c_streamsS");
21255    pragma Export (C, u00041, "system__file_ioB");
21256    pragma Export (C, u00042, "system__file_ioS");
21257    pragma Export (C, u00043, "ada__finalizationB");
21258    pragma Export (C, u00044, "ada__finalizationS");
21259    pragma Export (C, u00045, "system__finalization_rootB");
21260    pragma Export (C, u00046, "system__finalization_rootS");
21261    pragma Export (C, u00047, "system__finalization_implementationB");
21262    pragma Export (C, u00048, "system__finalization_implementationS");
21263    pragma Export (C, u00049, "system__string_ops_concat_3B");
21264    pragma Export (C, u00050, "system__string_ops_concat_3S");
21265    pragma Export (C, u00051, "system__stream_attributesB");
21266    pragma Export (C, u00052, "system__stream_attributesS");
21267    pragma Export (C, u00053, "ada__io_exceptionsS");
21268    pragma Export (C, u00054, "system__unsigned_typesS");
21269    pragma Export (C, u00055, "system__file_control_blockS");
21270    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21271    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21272
21273    -- BEGIN ELABORATION ORDER
21274    -- ada (spec)
21275    -- gnat (spec)
21276    -- gnat.heap_sort_a (spec)
21277    -- gnat.heap_sort_a (body)
21278    -- gnat.htable (spec)
21279    -- gnat.htable (body)
21280    -- interfaces (spec)
21281    -- system (spec)
21282    -- system.machine_code (spec)
21283    -- system.parameters (spec)
21284    -- system.parameters (body)
21285    -- interfaces.c_streams (spec)
21286    -- interfaces.c_streams (body)
21287    -- system.standard_library (spec)
21288    -- ada.exceptions (spec)
21289    -- system.exception_table (spec)
21290    -- system.exception_table (body)
21291    -- ada.io_exceptions (spec)
21292    -- system.exceptions (spec)
21293    -- system.storage_elements (spec)
21294    -- system.storage_elements (body)
21295    -- system.machine_state_operations (spec)
21296    -- system.machine_state_operations (body)
21297    -- system.secondary_stack (spec)
21298    -- system.stack_checking (spec)
21299    -- system.soft_links (spec)
21300    -- system.soft_links (body)
21301    -- system.stack_checking (body)
21302    -- system.secondary_stack (body)
21303    -- system.standard_library (body)
21304    -- system.string_ops (spec)
21305    -- system.string_ops (body)
21306    -- ada.tags (spec)
21307    -- ada.tags (body)
21308    -- ada.streams (spec)
21309    -- system.finalization_root (spec)
21310    -- system.finalization_root (body)
21311    -- system.string_ops_concat_3 (spec)
21312    -- system.string_ops_concat_3 (body)
21313    -- system.traceback (spec)
21314    -- system.traceback (body)
21315    -- ada.exceptions (body)
21316    -- system.unsigned_types (spec)
21317    -- system.stream_attributes (spec)
21318    -- system.stream_attributes (body)
21319    -- system.finalization_implementation (spec)
21320    -- system.finalization_implementation (body)
21321    -- ada.finalization (spec)
21322    -- ada.finalization (body)
21323    -- ada.finalization.list_controller (spec)
21324    -- ada.finalization.list_controller (body)
21325    -- system.file_control_block (spec)
21326    -- system.file_io (spec)
21327    -- system.file_io (body)
21328    -- ada.text_io (spec)
21329    -- ada.text_io (body)
21330    -- hello (body)
21331    -- END ELABORATION ORDER
21332
21333 end ada_main;
21334
21335 --  The following source file name pragmas allow the generated file
21336 --  names to be unique for different main programs. They are needed
21337 --  since the package name will always be Ada_Main.
21338
21339 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21340 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21341
21342 --  Generated package body for Ada_Main starts here
21343
21344 package body ada_main is
21345
21346    --  The actual finalization is performed by calling the
21347    --  library routine in System.Standard_Library.Adafinal
21348
21349    procedure Do_Finalize;
21350    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21351
21352    -------------
21353    -- adainit --
21354    -------------
21355
21356 @findex adainit
21357    procedure adainit is
21358
21359       --  These booleans are set to True once the associated unit has
21360       --  been elaborated. It is also used to avoid elaborating the
21361       --  same unit twice.
21362
21363       E040 : Boolean;
21364       pragma Import (Ada, E040, "interfaces__c_streams_E");
21365
21366       E008 : Boolean;
21367       pragma Import (Ada, E008, "ada__exceptions_E");
21368
21369       E014 : Boolean;
21370       pragma Import (Ada, E014, "system__exception_table_E");
21371
21372       E053 : Boolean;
21373       pragma Import (Ada, E053, "ada__io_exceptions_E");
21374
21375       E017 : Boolean;
21376       pragma Import (Ada, E017, "system__exceptions_E");
21377
21378       E024 : Boolean;
21379       pragma Import (Ada, E024, "system__secondary_stack_E");
21380
21381       E030 : Boolean;
21382       pragma Import (Ada, E030, "system__stack_checking_E");
21383
21384       E028 : Boolean;
21385       pragma Import (Ada, E028, "system__soft_links_E");
21386
21387       E035 : Boolean;
21388       pragma Import (Ada, E035, "ada__tags_E");
21389
21390       E033 : Boolean;
21391       pragma Import (Ada, E033, "ada__streams_E");
21392
21393       E046 : Boolean;
21394       pragma Import (Ada, E046, "system__finalization_root_E");
21395
21396       E048 : Boolean;
21397       pragma Import (Ada, E048, "system__finalization_implementation_E");
21398
21399       E044 : Boolean;
21400       pragma Import (Ada, E044, "ada__finalization_E");
21401
21402       E057 : Boolean;
21403       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21404
21405       E055 : Boolean;
21406       pragma Import (Ada, E055, "system__file_control_block_E");
21407
21408       E042 : Boolean;
21409       pragma Import (Ada, E042, "system__file_io_E");
21410
21411       E006 : Boolean;
21412       pragma Import (Ada, E006, "ada__text_io_E");
21413
21414       --  Set_Globals is a library routine that stores away the
21415       --  value of the indicated set of global values in global
21416       --  variables within the library.
21417
21418       procedure Set_Globals
21419         (Main_Priority            : Integer;
21420          Time_Slice_Value         : Integer;
21421          WC_Encoding              : Character;
21422          Locking_Policy           : Character;
21423          Queuing_Policy           : Character;
21424          Task_Dispatching_Policy  : Character;
21425          Adafinal                 : System.Address;
21426          Unreserve_All_Interrupts : Integer;
21427          Exception_Tracebacks     : Integer);
21428 @findex __gnat_set_globals
21429       pragma Import (C, Set_Globals, "__gnat_set_globals");
21430
21431       --  SDP_Table_Build is a library routine used to build the
21432       --  exception tables. See unit Ada.Exceptions in files
21433       --  a-except.ads/adb for full details of how zero cost
21434       --  exception handling works. This procedure, the call to
21435       --  it, and the two following tables are all omitted if the
21436       --  build is in longjmp/setjump exception mode.
21437
21438 @findex SDP_Table_Build
21439 @findex Zero Cost Exceptions
21440       procedure SDP_Table_Build
21441         (SDP_Addresses   : System.Address;
21442          SDP_Count       : Natural;
21443          Elab_Addresses  : System.Address;
21444          Elab_Addr_Count : Natural);
21445       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21446
21447       --  Table of Unit_Exception_Table addresses. Used for zero
21448       --  cost exception handling to build the top level table.
21449
21450       ST : aliased constant array (1 .. 23) of System.Address := (
21451         Hello'UET_Address,
21452         Ada.Text_Io'UET_Address,
21453         Ada.Exceptions'UET_Address,
21454         Gnat.Heap_Sort_A'UET_Address,
21455         System.Exception_Table'UET_Address,
21456         System.Machine_State_Operations'UET_Address,
21457         System.Secondary_Stack'UET_Address,
21458         System.Parameters'UET_Address,
21459         System.Soft_Links'UET_Address,
21460         System.Stack_Checking'UET_Address,
21461         System.Traceback'UET_Address,
21462         Ada.Streams'UET_Address,
21463         Ada.Tags'UET_Address,
21464         System.String_Ops'UET_Address,
21465         Interfaces.C_Streams'UET_Address,
21466         System.File_Io'UET_Address,
21467         Ada.Finalization'UET_Address,
21468         System.Finalization_Root'UET_Address,
21469         System.Finalization_Implementation'UET_Address,
21470         System.String_Ops_Concat_3'UET_Address,
21471         System.Stream_Attributes'UET_Address,
21472         System.File_Control_Block'UET_Address,
21473         Ada.Finalization.List_Controller'UET_Address);
21474
21475       --  Table of addresses of elaboration routines. Used for
21476       --  zero cost exception handling to make sure these
21477       --  addresses are included in the top level procedure
21478       --  address table.
21479
21480       EA : aliased constant array (1 .. 23) of System.Address := (
21481         adainit'Code_Address,
21482         Do_Finalize'Code_Address,
21483         Ada.Exceptions'Elab_Spec'Address,
21484         System.Exceptions'Elab_Spec'Address,
21485         Interfaces.C_Streams'Elab_Spec'Address,
21486         System.Exception_Table'Elab_Body'Address,
21487         Ada.Io_Exceptions'Elab_Spec'Address,
21488         System.Stack_Checking'Elab_Spec'Address,
21489         System.Soft_Links'Elab_Body'Address,
21490         System.Secondary_Stack'Elab_Body'Address,
21491         Ada.Tags'Elab_Spec'Address,
21492         Ada.Tags'Elab_Body'Address,
21493         Ada.Streams'Elab_Spec'Address,
21494         System.Finalization_Root'Elab_Spec'Address,
21495         Ada.Exceptions'Elab_Body'Address,
21496         System.Finalization_Implementation'Elab_Spec'Address,
21497         System.Finalization_Implementation'Elab_Body'Address,
21498         Ada.Finalization'Elab_Spec'Address,
21499         Ada.Finalization.List_Controller'Elab_Spec'Address,
21500         System.File_Control_Block'Elab_Spec'Address,
21501         System.File_Io'Elab_Body'Address,
21502         Ada.Text_Io'Elab_Spec'Address,
21503         Ada.Text_Io'Elab_Body'Address);
21504
21505    --  Start of processing for adainit
21506
21507    begin
21508
21509       --  Call SDP_Table_Build to build the top level procedure
21510       --  table for zero cost exception handling (omitted in
21511       --  longjmp/setjump mode).
21512
21513       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21514
21515       --  Call Set_Globals to record various information for
21516       --  this partition.  The values are derived by the binder
21517       --  from information stored in the ali files by the compiler.
21518
21519 @findex __gnat_set_globals
21520       Set_Globals
21521         (Main_Priority            => -1,
21522          --  Priority of main program, -1 if no pragma Priority used
21523
21524          Time_Slice_Value         => -1,
21525          --  Time slice from Time_Slice pragma, -1 if none used
21526
21527          WC_Encoding              => 'b',
21528          --  Wide_Character encoding used, default is brackets
21529
21530          Locking_Policy           => ' ',
21531          --  Locking_Policy used, default of space means not
21532          --  specified, otherwise it is the first character of
21533          --  the policy name.
21534
21535          Queuing_Policy           => ' ',
21536          --  Queuing_Policy used, default of space means not
21537          --  specified, otherwise it is the first character of
21538          --  the policy name.
21539
21540          Task_Dispatching_Policy  => ' ',
21541          --  Task_Dispatching_Policy used, default of space means
21542          --  not specified, otherwise first character of the
21543          --  policy name.
21544
21545          Adafinal                 => System.Null_Address,
21546          --  Address of Adafinal routine, not used anymore
21547
21548          Unreserve_All_Interrupts => 0,
21549          --  Set true if pragma Unreserve_All_Interrupts was used
21550
21551          Exception_Tracebacks     => 0);
21552          --  Indicates if exception tracebacks are enabled
21553
21554       Elab_Final_Code := 1;
21555
21556       --  Now we have the elaboration calls for all units in the partition.
21557       --  The Elab_Spec and Elab_Body attributes generate references to the
21558       --  implicit elaboration procedures generated by the compiler for
21559       --  each unit that requires elaboration.
21560
21561       if not E040 then
21562          Interfaces.C_Streams'Elab_Spec;
21563       end if;
21564       E040 := True;
21565       if not E008 then
21566          Ada.Exceptions'Elab_Spec;
21567       end if;
21568       if not E014 then
21569          System.Exception_Table'Elab_Body;
21570          E014 := True;
21571       end if;
21572       if not E053 then
21573          Ada.Io_Exceptions'Elab_Spec;
21574          E053 := True;
21575       end if;
21576       if not E017 then
21577          System.Exceptions'Elab_Spec;
21578          E017 := True;
21579       end if;
21580       if not E030 then
21581          System.Stack_Checking'Elab_Spec;
21582       end if;
21583       if not E028 then
21584          System.Soft_Links'Elab_Body;
21585          E028 := True;
21586       end if;
21587       E030 := True;
21588       if not E024 then
21589          System.Secondary_Stack'Elab_Body;
21590          E024 := True;
21591       end if;
21592       if not E035 then
21593          Ada.Tags'Elab_Spec;
21594       end if;
21595       if not E035 then
21596          Ada.Tags'Elab_Body;
21597          E035 := True;
21598       end if;
21599       if not E033 then
21600          Ada.Streams'Elab_Spec;
21601          E033 := True;
21602       end if;
21603       if not E046 then
21604          System.Finalization_Root'Elab_Spec;
21605       end if;
21606       E046 := True;
21607       if not E008 then
21608          Ada.Exceptions'Elab_Body;
21609          E008 := True;
21610       end if;
21611       if not E048 then
21612          System.Finalization_Implementation'Elab_Spec;
21613       end if;
21614       if not E048 then
21615          System.Finalization_Implementation'Elab_Body;
21616          E048 := True;
21617       end if;
21618       if not E044 then
21619          Ada.Finalization'Elab_Spec;
21620       end if;
21621       E044 := True;
21622       if not E057 then
21623          Ada.Finalization.List_Controller'Elab_Spec;
21624       end if;
21625       E057 := True;
21626       if not E055 then
21627          System.File_Control_Block'Elab_Spec;
21628          E055 := True;
21629       end if;
21630       if not E042 then
21631          System.File_Io'Elab_Body;
21632          E042 := True;
21633       end if;
21634       if not E006 then
21635          Ada.Text_Io'Elab_Spec;
21636       end if;
21637       if not E006 then
21638          Ada.Text_Io'Elab_Body;
21639          E006 := True;
21640       end if;
21641
21642       Elab_Final_Code := 0;
21643    end adainit;
21644
21645    --------------
21646    -- adafinal --
21647    --------------
21648
21649 @findex adafinal
21650    procedure adafinal is
21651    begin
21652       Do_Finalize;
21653    end adafinal;
21654
21655    ----------
21656    -- main --
21657    ----------
21658
21659    --  main is actually a function, as in the ANSI C standard,
21660    --  defined to return the exit status. The three parameters
21661    --  are the argument count, argument values and environment
21662    --  pointer.
21663
21664 @findex Main Program
21665    function main
21666      (argc : Integer;
21667       argv : System.Address;
21668       envp : System.Address)
21669       return Integer
21670    is
21671       --  The initialize routine performs low level system
21672       --  initialization using a standard library routine which
21673       --  sets up signal handling and performs any other
21674       --  required setup. The routine can be found in file
21675       --  a-init.c.
21676
21677 @findex __gnat_initialize
21678       procedure initialize;
21679       pragma Import (C, initialize, "__gnat_initialize");
21680
21681       --  The finalize routine performs low level system
21682       --  finalization using a standard library routine. The
21683       --  routine is found in file a-final.c and in the standard
21684       --  distribution is a dummy routine that does nothing, so
21685       --  really this is a hook for special user finalization.
21686
21687 @findex __gnat_finalize
21688       procedure finalize;
21689       pragma Import (C, finalize, "__gnat_finalize");
21690
21691       --  We get to the main program of the partition by using
21692       --  pragma Import because if we try to with the unit and
21693       --  call it Ada style, then not only do we waste time
21694       --  recompiling it, but also, we don't really know the right
21695       --  switches (e.g. identifier character set) to be used
21696       --  to compile it.
21697
21698       procedure Ada_Main_Program;
21699       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
21700
21701    --  Start of processing for main
21702
21703    begin
21704       --  Save global variables
21705
21706       gnat_argc := argc;
21707       gnat_argv := argv;
21708       gnat_envp := envp;
21709
21710       --  Call low level system initialization
21711
21712       Initialize;
21713
21714       --  Call our generated Ada initialization routine
21715
21716       adainit;
21717
21718       --  This is the point at which we want the debugger to get
21719       --  control
21720
21721       Break_Start;
21722
21723       --  Now we call the main program of the partition
21724
21725       Ada_Main_Program;
21726
21727       --  Perform Ada finalization
21728
21729       adafinal;
21730
21731       --  Perform low level system finalization
21732
21733       Finalize;
21734
21735       --  Return the proper exit status
21736       return (gnat_exit_status);
21737    end;
21738
21739 --  This section is entirely comments, so it has no effect on the
21740 --  compilation of the Ada_Main package. It provides the list of
21741 --  object files and linker options, as well as some standard
21742 --  libraries needed for the link. The gnatlink utility parses
21743 --  this b~hello.adb file to read these comment lines to generate
21744 --  the appropriate command line arguments for the call to the
21745 --  system linker. The BEGIN/END lines are used for sentinels for
21746 --  this parsing operation.
21747
21748 --  The exact file names will of course depend on the environment,
21749 --  host/target and location of files on the host system.
21750
21751 @findex Object file list
21752 -- BEGIN Object file/option list
21753    --   ./hello.o
21754    --   -L./
21755    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
21756    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
21757 -- END Object file/option list
21758
21759 end ada_main;
21760 @end smallexample
21761
21762 @noindent
21763 The Ada code in the above example is exactly what is generated by the
21764 binder. We have added comments to more clearly indicate the function
21765 of each part of the generated @code{Ada_Main} package.
21766
21767 The code is standard Ada in all respects, and can be processed by any
21768 tools that handle Ada. In particular, it is possible to use the debugger
21769 in Ada mode to debug the generated @code{Ada_Main} package. For example,
21770 suppose that for reasons that you do not understand, your program is crashing
21771 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
21772 you can place a breakpoint on the call:
21773
21774 @smallexample @c ada
21775 Ada.Text_Io'Elab_Body;
21776 @end smallexample
21777
21778 @noindent
21779 and trace the elaboration routine for this package to find out where
21780 the problem might be (more usually of course you would be debugging
21781 elaboration code in your own application).
21782
21783
21784 @node Elaboration Order Handling in GNAT
21785 @appendix Elaboration Order Handling in GNAT
21786 @cindex Order of elaboration
21787 @cindex Elaboration control
21788
21789 @menu
21790 * Elaboration Code in Ada 95::
21791 * Checking the Elaboration Order in Ada 95::
21792 * Controlling the Elaboration Order in Ada 95::
21793 * Controlling Elaboration in GNAT - Internal Calls::
21794 * Controlling Elaboration in GNAT - External Calls::
21795 * Default Behavior in GNAT - Ensuring Safety::
21796 * Treatment of Pragma Elaborate::
21797 * Elaboration Issues for Library Tasks::
21798 * Mixing Elaboration Models::
21799 * What to Do If the Default Elaboration Behavior Fails::
21800 * Elaboration for Access-to-Subprogram Values::
21801 * Summary of Procedures for Elaboration Control::
21802 * Other Elaboration Order Considerations::
21803 @end menu
21804
21805 @noindent
21806 This chapter describes the handling of elaboration code in Ada 95 and
21807 in GNAT, and discusses how the order of elaboration of program units can
21808 be controlled in GNAT, either automatically or with explicit programming
21809 features.
21810
21811 @node Elaboration Code in Ada 95
21812 @section Elaboration Code in Ada 95
21813
21814 @noindent
21815 Ada 95 provides rather general mechanisms for executing code at elaboration
21816 time, that is to say before the main program starts executing. Such code arises
21817 in three contexts:
21818
21819 @table @asis
21820 @item Initializers for variables.
21821 Variables declared at the library level, in package specs or bodies, can
21822 require initialization that is performed at elaboration time, as in:
21823 @smallexample @c ada
21824 @cartouche
21825 Sqrt_Half : Float := Sqrt (0.5);
21826 @end cartouche
21827 @end smallexample
21828
21829 @item Package initialization code
21830 Code in a @code{BEGIN-END} section at the outer level of a package body is
21831 executed as part of the package body elaboration code.
21832
21833 @item Library level task allocators
21834 Tasks that are declared using task allocators at the library level
21835 start executing immediately and hence can execute at elaboration time.
21836 @end table
21837
21838 @noindent
21839 Subprogram calls are possible in any of these contexts, which means that
21840 any arbitrary part of the program may be executed as part of the elaboration
21841 code. It is even possible to write a program which does all its work at
21842 elaboration time, with a null main program, although stylistically this
21843 would usually be considered an inappropriate way to structure
21844 a program.
21845
21846 An important concern arises in the context of elaboration code:
21847 we have to be sure that it is executed in an appropriate order. What we
21848 have is a series of elaboration code sections, potentially one section
21849 for each unit in the program. It is important that these execute
21850 in the correct order. Correctness here means that, taking the above
21851 example of the declaration of @code{Sqrt_Half},
21852 if some other piece of
21853 elaboration code references @code{Sqrt_Half},
21854 then it must run after the
21855 section of elaboration code that contains the declaration of
21856 @code{Sqrt_Half}.
21857
21858 There would never be any order of elaboration problem if we made a rule
21859 that whenever you @code{with} a unit, you must elaborate both the spec and body
21860 of that unit before elaborating the unit doing the @code{with}'ing:
21861
21862 @smallexample @c ada
21863 @group
21864 @cartouche
21865 with Unit_1;
21866 package Unit_2 is ...
21867 @end cartouche
21868 @end group
21869 @end smallexample
21870
21871 @noindent
21872 would require that both the body and spec of @code{Unit_1} be elaborated
21873 before the spec of @code{Unit_2}. However, a rule like that would be far too
21874 restrictive. In particular, it would make it impossible to have routines
21875 in separate packages that were mutually recursive.
21876
21877 You might think that a clever enough compiler could look at the actual
21878 elaboration code and determine an appropriate correct order of elaboration,
21879 but in the general case, this is not possible. Consider the following
21880 example.
21881
21882 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
21883 that references
21884 the variable @code{Sqrt_1}, which is declared in the elaboration code
21885 of the body of @code{Unit_1}:
21886
21887 @smallexample @c ada
21888 @cartouche
21889 Sqrt_1 : Float := Sqrt (0.1);
21890 @end cartouche
21891 @end smallexample
21892
21893 @noindent
21894 The elaboration code of the body of @code{Unit_1} also contains:
21895
21896 @smallexample @c ada
21897 @group
21898 @cartouche
21899 if expression_1 = 1 then
21900    Q := Unit_2.Func_2;
21901 end if;
21902 @end cartouche
21903 @end group
21904 @end smallexample
21905
21906 @noindent
21907 @code{Unit_2} is exactly parallel,
21908 it has a procedure @code{Func_2} that references
21909 the variable @code{Sqrt_2}, which is declared in the elaboration code of
21910 the body @code{Unit_2}:
21911
21912 @smallexample @c ada
21913 @cartouche
21914 Sqrt_2 : Float := Sqrt (0.1);
21915 @end cartouche
21916 @end smallexample
21917
21918 @noindent
21919 The elaboration code of the body of @code{Unit_2} also contains:
21920
21921 @smallexample @c ada
21922 @group
21923 @cartouche
21924 if expression_2 = 2 then
21925    Q := Unit_1.Func_1;
21926 end if;
21927 @end cartouche
21928 @end group
21929 @end smallexample
21930
21931 @noindent
21932 Now the question is, which of the following orders of elaboration is
21933 acceptable:
21934
21935 @smallexample
21936 @group
21937 Spec of Unit_1
21938 Spec of Unit_2
21939 Body of Unit_1
21940 Body of Unit_2
21941 @end group
21942 @end smallexample
21943
21944 @noindent
21945 or
21946
21947 @smallexample
21948 @group
21949 Spec of Unit_2
21950 Spec of Unit_1
21951 Body of Unit_2
21952 Body of Unit_1
21953 @end group
21954 @end smallexample
21955
21956 @noindent
21957 If you carefully analyze the flow here, you will see that you cannot tell
21958 at compile time the answer to this question.
21959 If @code{expression_1} is not equal to 1,
21960 and @code{expression_2} is not equal to 2,
21961 then either order is acceptable, because neither of the function calls is
21962 executed. If both tests evaluate to true, then neither order is acceptable
21963 and in fact there is no correct order.
21964
21965 If one of the two expressions is true, and the other is false, then one
21966 of the above orders is correct, and the other is incorrect. For example,
21967 if @code{expression_1} = 1 and @code{expression_2} /= 2,
21968 then the call to @code{Func_2}
21969 will occur, but not the call to @code{Func_1.}
21970 This means that it is essential
21971 to elaborate the body of @code{Unit_1} before
21972 the body of @code{Unit_2}, so the first
21973 order of elaboration is correct and the second is wrong.
21974
21975 By making @code{expression_1} and @code{expression_2}
21976 depend on input data, or perhaps
21977 the time of day, we can make it impossible for the compiler or binder
21978 to figure out which of these expressions will be true, and hence it
21979 is impossible to guarantee a safe order of elaboration at run time.
21980
21981 @node Checking the Elaboration Order in Ada 95
21982 @section Checking the Elaboration Order in Ada 95
21983
21984 @noindent
21985 In some languages that involve the same kind of elaboration problems,
21986 e.g. Java and C++, the programmer is expected to worry about these
21987 ordering problems himself, and it is common to
21988 write a program in which an incorrect elaboration order  gives
21989 surprising results, because it references variables before they
21990 are initialized.
21991 Ada 95 is designed to be a safe language, and a programmer-beware approach is
21992 clearly not sufficient. Consequently, the language provides three lines
21993 of defense:
21994
21995 @table @asis
21996 @item Standard rules
21997 Some standard rules restrict the possible choice of elaboration
21998 order. In particular, if you @code{with} a unit, then its spec is always
21999 elaborated before the unit doing the @code{with}. Similarly, a parent
22000 spec is always elaborated before the child spec, and finally
22001 a spec is always elaborated before its corresponding body.
22002
22003 @item Dynamic elaboration checks
22004 @cindex Elaboration checks
22005 @cindex Checks, elaboration
22006 Dynamic checks are made at run time, so that if some entity is accessed
22007 before it is elaborated (typically  by means of a subprogram call)
22008 then the exception (@code{Program_Error}) is raised.
22009
22010 @item Elaboration control
22011 Facilities are provided for the programmer to specify the desired order
22012 of elaboration.
22013 @end table
22014
22015 Let's look at these facilities in more detail. First, the rules for
22016 dynamic checking. One possible rule would be simply to say that the
22017 exception is raised if you access a variable which has not yet been
22018 elaborated. The trouble with this approach is that it could require
22019 expensive checks on every variable reference. Instead Ada 95 has two
22020 rules which are a little more restrictive, but easier to check, and
22021 easier to state:
22022
22023 @table @asis
22024 @item Restrictions on calls
22025 A subprogram can only be called at elaboration time if its body
22026 has been elaborated. The rules for elaboration given above guarantee
22027 that the spec of the subprogram has been elaborated before the
22028 call, but not the body. If this rule is violated, then the
22029 exception @code{Program_Error} is raised.
22030
22031 @item Restrictions on instantiations
22032 A generic unit can only be instantiated if the body of the generic
22033 unit has been elaborated. Again, the rules for elaboration given above
22034 guarantee that the spec of the generic unit has been elaborated
22035 before the instantiation, but not the body. If this rule is
22036 violated, then the exception @code{Program_Error} is raised.
22037 @end table
22038
22039 @noindent
22040 The idea is that if the body has been elaborated, then any variables
22041 it references must have been elaborated; by checking for the body being
22042 elaborated we guarantee that none of its references causes any
22043 trouble. As we noted above, this is a little too restrictive, because a
22044 subprogram that has no non-local references in its body may in fact be safe
22045 to call. However, it really would be unsafe to rely on this, because
22046 it would mean that the caller was aware of details of the implementation
22047 in the body. This goes against the basic tenets of Ada.
22048
22049 A plausible implementation can be described as follows.
22050 A Boolean variable is associated with each subprogram
22051 and each generic unit. This variable is initialized to False, and is set to
22052 True at the point body is elaborated. Every call or instantiation checks the
22053 variable, and raises @code{Program_Error} if the variable is False.
22054
22055 Note that one might think that it would be good enough to have one Boolean
22056 variable for each package, but that would not deal with cases of trying
22057 to call a body in the same package as the call
22058 that has not been elaborated yet.
22059 Of course a compiler may be able to do enough analysis to optimize away
22060 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22061 does such optimizations, but still the easiest conceptual model is to
22062 think of there being one variable per subprogram.
22063
22064 @node Controlling the Elaboration Order in Ada 95
22065 @section Controlling the Elaboration Order in Ada 95
22066
22067 @noindent
22068 In the previous section we discussed the rules in Ada 95 which ensure
22069 that @code{Program_Error} is raised if an incorrect elaboration order is
22070 chosen. This prevents erroneous executions, but we need mechanisms to
22071 specify a correct execution and avoid the exception altogether.
22072 To achieve this, Ada 95 provides a number of features for controlling
22073 the order of elaboration. We discuss these features in this section.
22074
22075 First, there are several ways of indicating to the compiler that a given
22076 unit has no elaboration problems:
22077
22078 @table @asis
22079 @item packages that do not require a body
22080 In Ada 95, a library package that does not require a body does not permit
22081 a body. This means that if we have a such a package, as in:
22082
22083 @smallexample @c ada
22084 @group
22085 @cartouche
22086 package Definitions is
22087    generic
22088       type m is new integer;
22089    package Subp is
22090       type a is array (1 .. 10) of m;
22091       type b is array (1 .. 20) of m;
22092    end Subp;
22093 end Definitions;
22094 @end cartouche
22095 @end group
22096 @end smallexample
22097
22098 @noindent
22099 A package that @code{with}'s @code{Definitions} may safely instantiate
22100 @code{Definitions.Subp} because the compiler can determine that there
22101 definitely is no package body to worry about in this case
22102
22103 @item pragma Pure
22104 @cindex pragma Pure
22105 @findex Pure
22106 Places sufficient restrictions on a unit to guarantee that
22107 no call to any subprogram in the unit can result in an
22108 elaboration problem. This means that the compiler does not need
22109 to worry about the point of elaboration of such units, and in
22110 particular, does not need to check any calls to any subprograms
22111 in this unit.
22112
22113 @item pragma Preelaborate
22114 @findex Preelaborate
22115 @cindex pragma Preelaborate
22116 This pragma places slightly less stringent restrictions on a unit than
22117 does pragma Pure,
22118 but these restrictions are still sufficient to ensure that there
22119 are no elaboration problems with any calls to the unit.
22120
22121 @item pragma Elaborate_Body
22122 @findex Elaborate_Body
22123 @cindex pragma Elaborate_Body
22124 This pragma requires that the body of a unit be elaborated immediately
22125 after its spec. Suppose a unit @code{A} has such a pragma,
22126 and unit @code{B} does
22127 a @code{with} of unit @code{A}. Recall that the standard rules require
22128 the spec of unit @code{A}
22129 to be elaborated before the @code{with}'ing unit; given the pragma in
22130 @code{A}, we also know that the body of @code{A}
22131 will be elaborated before @code{B}, so
22132 that calls to @code{A} are safe and do not need a check.
22133 @end table
22134
22135 @noindent
22136 Note that,
22137 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22138 the use of
22139 @code{Elaborate_Body} does not guarantee that the program is
22140 free of elaboration problems, because it may not be possible
22141 to satisfy the requested elaboration order.
22142 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22143 If a programmer
22144 marks @code{Unit_1} as @code{Elaborate_Body},
22145 and not @code{Unit_2,} then the order of
22146 elaboration will be:
22147
22148 @smallexample
22149 @group
22150 Spec of Unit_2
22151 Spec of Unit_1
22152 Body of Unit_1
22153 Body of Unit_2
22154 @end group
22155 @end smallexample
22156
22157 @noindent
22158 Now that means that the call to @code{Func_1} in @code{Unit_2}
22159 need not be checked,
22160 it must be safe. But the call to @code{Func_2} in
22161 @code{Unit_1} may still fail if
22162 @code{Expression_1} is equal to 1,
22163 and the programmer must still take
22164 responsibility for this not being the case.
22165
22166 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22167 eliminated, except for calls entirely within a body, which are
22168 in any case fully under programmer control. However, using the pragma
22169 everywhere is not always possible.
22170 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22171 we marked both of them as having pragma @code{Elaborate_Body}, then
22172 clearly there would be no possible elaboration order.
22173
22174 The above pragmas allow a server to guarantee safe use by clients, and
22175 clearly this is the preferable approach. Consequently a good rule in
22176 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22177 and if this is not possible,
22178 mark them as @code{Elaborate_Body} if possible.
22179 As we have seen, there are situations where neither of these
22180 three pragmas can be used.
22181 So we also provide methods for clients to control the
22182 order of elaboration of the servers on which they depend:
22183
22184 @table @asis
22185 @item pragma Elaborate (unit)
22186 @findex Elaborate
22187 @cindex pragma Elaborate
22188 This pragma is placed in the context clause, after a @code{with} clause,
22189 and it requires that the body of the named unit be elaborated before
22190 the unit in which the pragma occurs. The idea is to use this pragma
22191 if the current unit calls at elaboration time, directly or indirectly,
22192 some subprogram in the named unit.
22193
22194 @item pragma Elaborate_All (unit)
22195 @findex Elaborate_All
22196 @cindex pragma Elaborate_All
22197 This is a stronger version of the Elaborate pragma. Consider the
22198 following example:
22199
22200 @smallexample
22201 Unit A @code{with}'s unit B and calls B.Func in elab code
22202 Unit B @code{with}'s unit C, and B.Func calls C.Func
22203 @end smallexample
22204
22205 @noindent
22206 Now if we put a pragma @code{Elaborate (B)}
22207 in unit @code{A}, this ensures that the
22208 body of @code{B} is elaborated before the call, but not the
22209 body of @code{C}, so
22210 the call to @code{C.Func} could still cause @code{Program_Error} to
22211 be raised.
22212
22213 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22214 not only that the body of the named unit be elaborated before the
22215 unit doing the @code{with}, but also the bodies of all units that the
22216 named unit uses, following @code{with} links transitively. For example,
22217 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22218 then it requires
22219 not only that the body of @code{B} be elaborated before @code{A},
22220 but also the
22221 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22222 @end table
22223
22224 @noindent
22225 We are now in a position to give a usage rule in Ada 95 for avoiding
22226 elaboration problems, at least if dynamic dispatching and access to
22227 subprogram values are not used. We will handle these cases separately
22228 later.
22229
22230 The rule is simple. If a unit has elaboration code that can directly or
22231 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22232 a generic unit in a @code{with}'ed unit,
22233 then if the @code{with}'ed unit does not have
22234 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22235 a pragma @code{Elaborate_All}
22236 for the @code{with}'ed unit. By following this rule a client is
22237 assured that calls can be made without risk of an exception.
22238 If this rule is not followed, then a program may be in one of four
22239 states:
22240
22241 @table @asis
22242 @item No order exists
22243 No order of elaboration exists which follows the rules, taking into
22244 account any @code{Elaborate}, @code{Elaborate_All},
22245 or @code{Elaborate_Body} pragmas. In
22246 this case, an Ada 95 compiler must diagnose the situation at bind
22247 time, and refuse to build an executable program.
22248
22249 @item One or more orders exist, all incorrect
22250 One or more acceptable elaboration orders exists, and all of them
22251 generate an elaboration order problem. In this case, the binder
22252 can build an executable program, but @code{Program_Error} will be raised
22253 when the program is run.
22254
22255 @item Several orders exist, some right, some incorrect
22256 One or more acceptable elaboration orders exists, and some of them
22257 work, and some do not. The programmer has not controlled
22258 the order of elaboration, so the binder may or may not pick one of
22259 the correct orders, and the program may or may not raise an
22260 exception when it is run. This is the worst case, because it means
22261 that the program may fail when moved to another compiler, or even
22262 another version of the same compiler.
22263
22264 @item One or more orders exists, all correct
22265 One ore more acceptable elaboration orders exist, and all of them
22266 work. In this case the program runs successfully. This state of
22267 affairs can be guaranteed by following the rule we gave above, but
22268 may be true even if the rule is not followed.
22269 @end table
22270
22271 @noindent
22272 Note that one additional advantage of following our Elaborate_All rule
22273 is that the program continues to stay in the ideal (all orders OK) state
22274 even if maintenance
22275 changes some bodies of some subprograms. Conversely, if a program that does
22276 not follow this rule happens to be safe at some point, this state of affairs
22277 may deteriorate silently as a result of maintenance changes.
22278
22279 You may have noticed that the above discussion did not mention
22280 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22281 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22282 code in the body makes calls to some other unit, so it is still necessary
22283 to use @code{Elaborate_All} on such units.
22284
22285 @node Controlling Elaboration in GNAT - Internal Calls
22286 @section Controlling Elaboration in GNAT - Internal Calls
22287
22288 @noindent
22289 In the case of internal calls, i.e. calls within a single package, the
22290 programmer has full control over the order of elaboration, and it is up
22291 to the programmer to elaborate declarations in an appropriate order. For
22292 example writing:
22293
22294 @smallexample @c ada
22295 @group
22296 @cartouche
22297 function One return Float;
22298
22299 Q : Float := One;
22300
22301 function One return Float is
22302 begin
22303      return 1.0;
22304 end One;
22305 @end cartouche
22306 @end group
22307 @end smallexample
22308
22309 @noindent
22310 will obviously raise @code{Program_Error} at run time, because function
22311 One will be called before its body is elaborated. In this case GNAT will
22312 generate a warning that the call will raise @code{Program_Error}:
22313
22314 @smallexample
22315 @group
22316 @cartouche
22317  1. procedure y is
22318  2.    function One return Float;
22319  3.
22320  4.    Q : Float := One;
22321                     |
22322     >>> warning: cannot call "One" before body is elaborated
22323     >>> warning: Program_Error will be raised at run time
22324
22325  5.
22326  6.    function One return Float is
22327  7.    begin
22328  8.         return 1.0;
22329  9.    end One;
22330 10.
22331 11. begin
22332 12.    null;
22333 13. end;
22334 @end cartouche
22335 @end group
22336 @end smallexample
22337
22338 @noindent
22339 Note that in this particular case, it is likely that the call is safe, because
22340 the function @code{One} does not access any global variables.
22341 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22342 the contents of the body (think about the separate compilation case), so this
22343 is still wrong, as we discussed in the previous sections.
22344
22345 The error is easily corrected by rearranging the declarations so that the
22346 body of One appears before the declaration containing the call
22347 (note that in Ada 95,
22348 declarations can appear in any order, so there is no restriction that
22349 would prevent this reordering, and if we write:
22350
22351 @smallexample @c ada
22352 @group
22353 @cartouche
22354 function One return Float;
22355
22356 function One return Float is
22357 begin
22358      return 1.0;
22359 end One;
22360
22361 Q : Float := One;
22362 @end cartouche
22363 @end group
22364 @end smallexample
22365
22366 @noindent
22367 then all is well, no warning is generated, and no
22368 @code{Program_Error} exception
22369 will be raised.
22370 Things are more complicated when a chain of subprograms is executed:
22371
22372 @smallexample @c ada
22373 @group
22374 @cartouche
22375 function A return Integer;
22376 function B return Integer;
22377 function C return Integer;
22378
22379 function B return Integer is begin return A; end;
22380 function C return Integer is begin return B; end;
22381
22382 X : Integer := C;
22383
22384 function A return Integer is begin return 1; end;
22385 @end cartouche
22386 @end group
22387 @end smallexample
22388
22389 @noindent
22390 Now the call to @code{C}
22391 at elaboration time in the declaration of @code{X} is correct, because
22392 the body of @code{C} is already elaborated,
22393 and the call to @code{B} within the body of
22394 @code{C} is correct, but the call
22395 to @code{A} within the body of @code{B} is incorrect, because the body
22396 of @code{A} has not been elaborated, so @code{Program_Error}
22397 will be raised on the call to @code{A}.
22398 In this case GNAT will generate a
22399 warning that @code{Program_Error} may be
22400 raised at the point of the call. Let's look at the warning:
22401
22402 @smallexample
22403 @group
22404 @cartouche
22405  1. procedure x is
22406  2.    function A return Integer;
22407  3.    function B return Integer;
22408  4.    function C return Integer;
22409  5.
22410  6.    function B return Integer is begin return A; end;
22411                                                     |
22412     >>> warning: call to "A" before body is elaborated may
22413                  raise Program_Error
22414     >>> warning: "B" called at line 7
22415     >>> warning: "C" called at line 9
22416
22417  7.    function C return Integer is begin return B; end;
22418  8.
22419  9.    X : Integer := C;
22420 10.
22421 11.    function A return Integer is begin return 1; end;
22422 12.
22423 13. begin
22424 14.    null;
22425 15. end;
22426 @end cartouche
22427 @end group
22428 @end smallexample
22429
22430 @noindent
22431 Note that the message here says ``may raise'', instead of the direct case,
22432 where the message says ``will be raised''. That's because whether
22433 @code{A} is
22434 actually called depends in general on run-time flow of control.
22435 For example, if the body of @code{B} said
22436
22437 @smallexample @c ada
22438 @group
22439 @cartouche
22440 function B return Integer is
22441 begin
22442    if some-condition-depending-on-input-data then
22443       return A;
22444    else
22445       return 1;
22446    end if;
22447 end B;
22448 @end cartouche
22449 @end group
22450 @end smallexample
22451
22452 @noindent
22453 then we could not know until run time whether the incorrect call to A would
22454 actually occur, so @code{Program_Error} might
22455 or might not be raised. It is possible for a compiler to
22456 do a better job of analyzing bodies, to
22457 determine whether or not @code{Program_Error}
22458 might be raised, but it certainly
22459 couldn't do a perfect job (that would require solving the halting problem
22460 and is provably impossible), and because this is a warning anyway, it does
22461 not seem worth the effort to do the analysis. Cases in which it
22462 would be relevant are rare.
22463
22464 In practice, warnings of either of the forms given
22465 above will usually correspond to
22466 real errors, and should be examined carefully and eliminated.
22467 In the rare case where a warning is bogus, it can be suppressed by any of
22468 the following methods:
22469
22470 @itemize @bullet
22471 @item
22472 Compile with the @option{-gnatws} switch set
22473
22474 @item
22475 Suppress @code{Elaboration_Check} for the called subprogram
22476
22477 @item
22478 Use pragma @code{Warnings_Off} to turn warnings off for the call
22479 @end itemize
22480
22481 @noindent
22482 For the internal elaboration check case,
22483 GNAT by default generates the
22484 necessary run-time checks to ensure
22485 that @code{Program_Error} is raised if any
22486 call fails an elaboration check. Of course this can only happen if a
22487 warning has been issued as described above. The use of pragma
22488 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22489 some of these checks, meaning that it may be possible (but is not
22490 guaranteed) for a program to be able to call a subprogram whose body
22491 is not yet elaborated, without raising a @code{Program_Error} exception.
22492
22493 @node Controlling Elaboration in GNAT - External Calls
22494 @section Controlling Elaboration in GNAT - External Calls
22495
22496 @noindent
22497 The previous section discussed the case in which the execution of a
22498 particular thread of elaboration code occurred entirely within a
22499 single unit. This is the easy case to handle, because a programmer
22500 has direct and total control over the order of elaboration, and
22501 furthermore, checks need only be generated in cases which are rare
22502 and which the compiler can easily detect.
22503 The situation is more complex when separate compilation is taken into account.
22504 Consider the following:
22505
22506 @smallexample @c ada
22507 @cartouche
22508 @group
22509 package Math is
22510    function Sqrt (Arg : Float) return Float;
22511 end Math;
22512
22513 package body Math is
22514    function Sqrt (Arg : Float) return Float is
22515    begin
22516          ...
22517    end Sqrt;
22518 end Math;
22519 @end group
22520 @group
22521 with Math;
22522 package Stuff is
22523    X : Float := Math.Sqrt (0.5);
22524 end Stuff;
22525
22526 with Stuff;
22527 procedure Main is
22528 begin
22529    ...
22530 end Main;
22531 @end group
22532 @end cartouche
22533 @end smallexample
22534
22535 @noindent
22536 where @code{Main} is the main program. When this program is executed, the
22537 elaboration code must first be executed, and one of the jobs of the
22538 binder is to determine the order in which the units of a program are
22539 to be elaborated. In this case we have four units: the spec and body
22540 of @code{Math},
22541 the spec of @code{Stuff} and the body of @code{Main}).
22542 In what order should the four separate sections of elaboration code
22543 be executed?
22544
22545 There are some restrictions in the order of elaboration that the binder
22546 can choose. In particular, if unit U has a @code{with}
22547 for a package @code{X}, then you
22548 are assured that the spec of @code{X}
22549 is elaborated before U , but you are
22550 not assured that the body of @code{X}
22551 is elaborated before U.
22552 This means that in the above case, the binder is allowed to choose the
22553 order:
22554
22555 @smallexample
22556 spec of Math
22557 spec of Stuff
22558 body of Math
22559 body of Main
22560 @end smallexample
22561
22562 @noindent
22563 but that's not good, because now the call to @code{Math.Sqrt}
22564 that happens during
22565 the elaboration of the @code{Stuff}
22566 spec happens before the body of @code{Math.Sqrt} is
22567 elaborated, and hence causes @code{Program_Error} exception to be raised.
22568 At first glance, one might say that the binder is misbehaving, because
22569 obviously you want to elaborate the body of something you @code{with}
22570 first, but
22571 that is not a general rule that can be followed in all cases. Consider
22572
22573 @smallexample @c ada
22574 @group
22575 @cartouche
22576 package X is ...
22577
22578 package Y is ...
22579
22580 with X;
22581 package body Y is ...
22582
22583 with Y;
22584 package body X is ...
22585 @end cartouche
22586 @end group
22587 @end smallexample
22588
22589 @noindent
22590 This is a common arrangement, and, apart from the order of elaboration
22591 problems that might arise in connection with elaboration code, this works fine.
22592 A rule that says that you must first elaborate the body of anything you
22593 @code{with} cannot work in this case:
22594 the body of @code{X} @code{with}'s @code{Y},
22595 which means you would have to
22596 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22597 which means
22598 you have to elaborate the body of @code{X} first, but ... and we have a
22599 loop that cannot be broken.
22600
22601 It is true that the binder can in many cases guess an order of elaboration
22602 that is unlikely to cause a @code{Program_Error}
22603 exception to be raised, and it tries to do so (in the
22604 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22605 by default
22606 elaborate the body of @code{Math} right after its spec, so all will be well).
22607
22608 However, a program that blindly relies on the binder to be helpful can
22609 get into trouble, as we discussed in the previous sections, so
22610 GNAT
22611 provides a number of facilities for assisting the programmer in
22612 developing programs that are robust with respect to elaboration order.
22613
22614 @node Default Behavior in GNAT - Ensuring Safety
22615 @section Default Behavior in GNAT - Ensuring Safety
22616
22617 @noindent
22618 The default behavior in GNAT ensures elaboration safety. In its
22619 default mode GNAT implements the
22620 rule we previously described as the right approach. Let's restate it:
22621
22622 @itemize
22623 @item
22624 @emph{If a unit has elaboration code that can directly or indirectly make a
22625 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22626 in a @code{with}'ed unit, then if the @code{with}'ed unit
22627 does not have pragma @code{Pure} or
22628 @code{Preelaborate}, then the client should have an
22629 @code{Elaborate_All} for the @code{with}'ed unit.}
22630 @end itemize
22631
22632 @noindent
22633 By following this rule a client is assured that calls and instantiations
22634 can be made without risk of an exception.
22635
22636 In this mode GNAT traces all calls that are potentially made from
22637 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22638 pragmas.
22639 The advantage of this approach is that no elaboration problems
22640 are possible if the binder can find an elaboration order that is
22641 consistent with these implicit @code{Elaborate_All} pragmas. The
22642 disadvantage of this approach is that no such order may exist.
22643
22644 If the binder does not generate any diagnostics, then it means that it
22645 has found an elaboration order that is guaranteed to be safe. However,
22646 the binder may still be relying on implicitly generated
22647 @code{Elaborate_All} pragmas so portability to other compilers than
22648 GNAT is not guaranteed.
22649
22650 If it is important to guarantee portability, then the compilations should
22651 use the
22652 @option{-gnatwl}
22653 (warn on elaboration problems) switch. This will cause warning messages
22654 to be generated indicating the missing @code{Elaborate_All} pragmas.
22655 Consider the following source program:
22656
22657 @smallexample @c ada
22658 @group
22659 @cartouche
22660 with k;
22661 package j is
22662   m : integer := k.r;
22663 end;
22664 @end cartouche
22665 @end group
22666 @end smallexample
22667
22668 @noindent
22669 where it is clear that there
22670 should be a pragma @code{Elaborate_All}
22671 for unit @code{k}. An implicit pragma will be generated, and it is
22672 likely that the binder will be able to honor it. However, if you want
22673 to port this program to some other Ada compiler than GNAT.
22674 it is safer to include the pragma explicitly in the source. If this
22675 unit is compiled with the
22676 @option{-gnatwl}
22677 switch, then the compiler outputs a warning:
22678
22679 @smallexample
22680 @group
22681 @cartouche
22682 1. with k;
22683 2. package j is
22684 3.   m : integer := k.r;
22685                      |
22686    >>> warning: call to "r" may raise Program_Error
22687    >>> warning: missing pragma Elaborate_All for "k"
22688
22689 4. end;
22690 @end cartouche
22691 @end group
22692 @end smallexample
22693
22694 @noindent
22695 and these warnings can be used as a guide for supplying manually
22696 the missing pragmas. It is usually a bad idea to use this warning
22697 option during development. That's because it will warn you when
22698 you need to put in a pragma, but cannot warn you when it is time
22699 to take it out. So the use of pragma Elaborate_All may lead to
22700 unnecessary dependencies and even false circularities.
22701
22702 This default mode is more restrictive than the Ada Reference
22703 Manual, and it is possible to construct programs which will compile
22704 using the dynamic model described there, but will run into a
22705 circularity using the safer static model we have described.
22706
22707 Of course any Ada compiler must be able to operate in a mode
22708 consistent with the requirements of the Ada Reference Manual,
22709 and in particular must have the capability of implementing the
22710 standard dynamic model of elaboration with run-time checks.
22711
22712 In GNAT, this standard mode can be achieved either by the use of
22713 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
22714 command, or by the use of the configuration pragma:
22715
22716 @smallexample @c ada
22717 pragma Elaboration_Checks (RM);
22718 @end smallexample
22719
22720 @noindent
22721 Either approach will cause the unit affected to be compiled using the
22722 standard dynamic run-time elaboration checks described in the Ada
22723 Reference Manual. The static model is generally preferable, since it
22724 is clearly safer to rely on compile and link time checks rather than
22725 run-time checks. However, in the case of legacy code, it may be
22726 difficult to meet the requirements of the static model. This
22727 issue is further discussed in
22728 @ref{What to Do If the Default Elaboration Behavior Fails}.
22729
22730 Note that the static model provides a strict subset of the allowed
22731 behavior and programs of the Ada Reference Manual, so if you do
22732 adhere to the static model and no circularities exist,
22733 then you are assured that your program will
22734 work using the dynamic model, providing that you remove any
22735 pragma Elaborate statements from the source.
22736
22737 @node Treatment of Pragma Elaborate
22738 @section Treatment of Pragma Elaborate
22739 @cindex Pragma Elaborate
22740
22741 @noindent
22742 The use of @code{pragma Elaborate}
22743 should generally be avoided in Ada 95 programs.
22744 The reason for this is that there is no guarantee that transitive calls
22745 will be properly handled. Indeed at one point, this pragma was placed
22746 in Annex J (Obsolescent Features), on the grounds that it is never useful.
22747
22748 Now that's a bit restrictive. In practice, the case in which
22749 @code{pragma Elaborate} is useful is when the caller knows that there
22750 are no transitive calls, or that the called unit contains all necessary
22751 transitive @code{pragma Elaborate} statements, and legacy code often
22752 contains such uses.
22753
22754 Strictly speaking the static mode in GNAT should ignore such pragmas,
22755 since there is no assurance at compile time that the necessary safety
22756 conditions are met. In practice, this would cause GNAT to be incompatible
22757 with correctly written Ada 83 code that had all necessary
22758 @code{pragma Elaborate} statements in place. Consequently, we made the
22759 decision that GNAT in its default mode will believe that if it encounters
22760 a @code{pragma Elaborate} then the programmer knows what they are doing,
22761 and it will trust that no elaboration errors can occur.
22762
22763 The result of this decision is two-fold. First to be safe using the
22764 static mode, you should remove all @code{pragma Elaborate} statements.
22765 Second, when fixing circularities in existing code, you can selectively
22766 use @code{pragma Elaborate} statements to convince the static mode of
22767 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
22768 statement.
22769
22770 When using the static mode with @option{-gnatwl}, any use of
22771 @code{pragma Elaborate} will generate a warning about possible
22772 problems.
22773
22774 @node Elaboration Issues for Library Tasks
22775 @section Elaboration Issues for Library Tasks
22776 @cindex Library tasks, elaboration issues
22777 @cindex Elaboration of library tasks
22778
22779 @noindent
22780 In this section we examine special elaboration issues that arise for
22781 programs that declare library level tasks.
22782
22783 Generally the model of execution of an Ada program is that all units are
22784 elaborated, and then execution of the program starts. However, the
22785 declaration of library tasks definitely does not fit this model. The
22786 reason for this is that library tasks start as soon as they are declared
22787 (more precisely, as soon as the statement part of the enclosing package
22788 body is reached), that is to say before elaboration
22789 of the program is complete. This means that if such a task calls a
22790 subprogram, or an entry in another task, the callee may or may not be
22791 elaborated yet, and in the standard
22792 Reference Manual model of dynamic elaboration checks, you can even
22793 get timing dependent Program_Error exceptions, since there can be
22794 a race between the elaboration code and the task code.
22795
22796 The static model of elaboration in GNAT seeks to avoid all such
22797 dynamic behavior, by being conservative, and the conservative
22798 approach in this particular case is to assume that all the code
22799 in a task body is potentially executed at elaboration time if
22800 a task is declared at the library level.
22801
22802 This can definitely result in unexpected circularities. Consider
22803 the following example
22804
22805 @smallexample @c ada
22806 package Decls is
22807   task Lib_Task is
22808      entry Start;
22809   end Lib_Task;
22810
22811   type My_Int is new Integer;
22812
22813   function Ident (M : My_Int) return My_Int;
22814 end Decls;
22815
22816 with Utils;
22817 package body Decls is
22818   task body Lib_Task is
22819   begin
22820      accept Start;
22821      Utils.Put_Val (2);
22822   end Lib_Task;
22823
22824   function Ident (M : My_Int) return My_Int is
22825   begin
22826      return M;
22827   end Ident;
22828 end Decls;
22829
22830 with Decls;
22831 package Utils is
22832   procedure Put_Val (Arg : Decls.My_Int);
22833 end Utils;
22834
22835 with Text_IO;
22836 package body Utils is
22837   procedure Put_Val (Arg : Decls.My_Int) is
22838   begin
22839      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
22840   end Put_Val;
22841 end Utils;
22842
22843 with Decls;
22844 procedure Main is
22845 begin
22846    Decls.Lib_Task.Start;
22847 end;
22848 @end smallexample
22849
22850 @noindent
22851 If the above example is compiled in the default static elaboration
22852 mode, then a circularity occurs. The circularity comes from the call
22853 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
22854 this call occurs in elaboration code, we need an implicit pragma
22855 @code{Elaborate_All} for @code{Utils}. This means that not only must
22856 the spec and body of @code{Utils} be elaborated before the body
22857 of @code{Decls}, but also the spec and body of any unit that is
22858 @code{with'ed} by the body of @code{Utils} must also be elaborated before
22859 the body of @code{Decls}. This is the transitive implication of
22860 pragma @code{Elaborate_All} and it makes sense, because in general
22861 the body of @code{Put_Val} might have a call to something in a
22862 @code{with'ed} unit.
22863
22864 In this case, the body of Utils (actually its spec) @code{with's}
22865 @code{Decls}. Unfortunately this means that the body of @code{Decls}
22866 must be elaborated before itself, in case there is a call from the
22867 body of @code{Utils}.
22868
22869 Here is the exact chain of events we are worrying about:
22870
22871 @enumerate
22872 @item
22873 In the body of @code{Decls} a call is made from within the body of a library
22874 task to a subprogram in the package @code{Utils}. Since this call may
22875 occur at elaboration time (given that the task is activated at elaboration
22876 time), we have to assume the worst, i.e. that the
22877 call does happen at elaboration time.
22878
22879 @item
22880 This means that the body and spec of @code{Util} must be elaborated before
22881 the body of @code{Decls} so that this call does not cause an access before
22882 elaboration.
22883
22884 @item
22885 Within the body of @code{Util}, specifically within the body of
22886 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
22887 by this package.
22888
22889 @item
22890 One such @code{with}'ed package is package @code{Decls}, so there
22891 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
22892 In fact there is such a call in this example, but we would have to
22893 assume that there was such a call even if it were not there, since
22894 we are not supposed to write the body of @code{Decls} knowing what
22895 is in the body of @code{Utils}; certainly in the case of the
22896 static elaboration model, the compiler does not know what is in
22897 other bodies and must assume the worst.
22898
22899 @item
22900 This means that the spec and body of @code{Decls} must also be
22901 elaborated before we elaborate the unit containing the call, but
22902 that unit is @code{Decls}! This means that the body of @code{Decls}
22903 must be elaborated before itself, and that's a circularity.
22904 @end enumerate
22905
22906 @noindent
22907 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
22908 the body of @code{Decls} you will get a true Ada Reference Manual
22909 circularity that makes the program illegal.
22910
22911 In practice, we have found that problems with the static model of
22912 elaboration in existing code often arise from library tasks, so
22913 we must address this particular situation.
22914
22915 Note that if we compile and run the program above, using the dynamic model of
22916 elaboration (that is to say use the @option{-gnatE} switch),
22917 then it compiles, binds,
22918 links, and runs, printing the expected result of 2. Therefore in some sense
22919 the circularity here is only apparent, and we need to capture
22920 the properties of this program that  distinguish it from other library-level
22921 tasks that have real elaboration problems.
22922
22923 We have four possible answers to this question:
22924
22925 @itemize @bullet
22926
22927 @item
22928 Use the dynamic model of elaboration.
22929
22930 If we use the @option{-gnatE} switch, then as noted above, the program works.
22931 Why is this? If we examine the task body, it is apparent that the task cannot
22932 proceed past the
22933 @code{accept} statement until after elaboration has been completed, because
22934 the corresponding entry call comes from the main program, not earlier.
22935 This is why the dynamic model works here. But that's really giving
22936 up on a precise analysis, and we prefer to take this approach only if we cannot
22937 solve the
22938 problem in any other manner. So let us examine two ways to reorganize
22939 the program to avoid the potential elaboration problem.
22940
22941 @item
22942 Split library tasks into separate packages.
22943
22944 Write separate packages, so that library tasks are isolated from
22945 other declarations as much as possible. Let us look at a variation on
22946 the above program.
22947
22948 @smallexample @c ada
22949 package Decls1 is
22950   task Lib_Task is
22951      entry Start;
22952   end Lib_Task;
22953 end Decls1;
22954
22955 with Utils;
22956 package body Decls1 is
22957   task body Lib_Task is
22958   begin
22959      accept Start;
22960      Utils.Put_Val (2);
22961   end Lib_Task;
22962 end Decls1;
22963
22964 package Decls2 is
22965   type My_Int is new Integer;
22966   function Ident (M : My_Int) return My_Int;
22967 end Decls2;
22968
22969 with Utils;
22970 package body Decls2 is
22971   function Ident (M : My_Int) return My_Int is
22972   begin
22973      return M;
22974   end Ident;
22975 end Decls2;
22976
22977 with Decls2;
22978 package Utils is
22979   procedure Put_Val (Arg : Decls2.My_Int);
22980 end Utils;
22981
22982 with Text_IO;
22983 package body Utils is
22984   procedure Put_Val (Arg : Decls2.My_Int) is
22985   begin
22986      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
22987   end Put_Val;
22988 end Utils;
22989
22990 with Decls1;
22991 procedure Main is
22992 begin
22993    Decls1.Lib_Task.Start;
22994 end;
22995 @end smallexample
22996
22997 @noindent
22998 All we have done is to split @code{Decls} into two packages, one
22999 containing the library task, and one containing everything else. Now
23000 there is no cycle, and the program compiles, binds, links and executes
23001 using the default static model of elaboration.
23002
23003 @item
23004 Declare separate task types.
23005
23006 A significant part of the problem arises because of the use of the
23007 single task declaration form. This means that the elaboration of
23008 the task type, and the elaboration of the task itself (i.e. the
23009 creation of the task) happen at the same time. A good rule
23010 of style in Ada 95 is to always create explicit task types. By
23011 following the additional step of placing task objects in separate
23012 packages from the task type declaration, many elaboration problems
23013 are avoided. Here is another modified example of the example program:
23014
23015 @smallexample @c ada
23016 package Decls is
23017   task type Lib_Task_Type is
23018      entry Start;
23019   end Lib_Task_Type;
23020
23021   type My_Int is new Integer;
23022
23023   function Ident (M : My_Int) return My_Int;
23024 end Decls;
23025
23026 with Utils;
23027 package body Decls is
23028   task body Lib_Task_Type is
23029   begin
23030      accept Start;
23031      Utils.Put_Val (2);
23032   end Lib_Task_Type;
23033
23034   function Ident (M : My_Int) return My_Int is
23035   begin
23036      return M;
23037   end Ident;
23038 end Decls;
23039
23040 with Decls;
23041 package Utils is
23042   procedure Put_Val (Arg : Decls.My_Int);
23043 end Utils;
23044
23045 with Text_IO;
23046 package body Utils is
23047   procedure Put_Val (Arg : Decls.My_Int) is
23048   begin
23049      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23050   end Put_Val;
23051 end Utils;
23052
23053 with Decls;
23054 package Declst is
23055    Lib_Task : Decls.Lib_Task_Type;
23056 end Declst;
23057
23058 with Declst;
23059 procedure Main is
23060 begin
23061    Declst.Lib_Task.Start;
23062 end;
23063 @end smallexample
23064
23065 @noindent
23066 What we have done here is to replace the @code{task} declaration in
23067 package @code{Decls} with a @code{task type} declaration. Then we
23068 introduce a separate package @code{Declst} to contain the actual
23069 task object. This separates the elaboration issues for
23070 the @code{task type}
23071 declaration, which causes no trouble, from the elaboration issues
23072 of the task object, which is also unproblematic, since it is now independent
23073 of the elaboration of  @code{Utils}.
23074 This separation of concerns also corresponds to
23075 a generally sound engineering principle of separating declarations
23076 from instances. This version of the program also compiles, binds, links,
23077 and executes, generating the expected output.
23078
23079 @item
23080 Use No_Entry_Calls_In_Elaboration_Code restriction.
23081 @cindex No_Entry_Calls_In_Elaboration_Code
23082
23083 The previous two approaches described how a program can be restructured
23084 to avoid the special problems caused by library task bodies. in practice,
23085 however, such restructuring may be difficult to apply to existing legacy code,
23086 so we must consider solutions that do not require massive rewriting.
23087
23088 Let us consider more carefully why our original sample program works
23089 under the dynamic model of elaboration. The reason is that the code
23090 in the task body blocks immediately on the @code{accept}
23091 statement. Now of course there is nothing to prohibit elaboration
23092 code from making entry calls (for example from another library level task),
23093 so we cannot tell in isolation that
23094 the task will not execute the accept statement  during elaboration.
23095
23096 However, in practice it is very unusual to see elaboration code
23097 make any entry calls, and the pattern of tasks starting
23098 at elaboration time and then immediately blocking on @code{accept} or
23099 @code{select} statements is very common. What this means is that
23100 the compiler is being too pessimistic when it analyzes the
23101 whole package body as though it might be executed at elaboration
23102 time.
23103
23104 If we know that the elaboration code contains no entry calls, (a very safe
23105 assumption most of the time, that could almost be made the default
23106 behavior), then we can compile all units of the program under control
23107 of the following configuration pragma:
23108
23109 @smallexample
23110 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23111 @end smallexample
23112
23113 @noindent
23114 This pragma can be placed in the @file{gnat.adc} file in the usual
23115 manner. If we take our original unmodified program and compile it
23116 in the presence of a @file{gnat.adc} containing the above pragma,
23117 then once again, we can compile, bind, link, and execute, obtaining
23118 the expected result. In the presence of this pragma, the compiler does
23119 not trace calls in a task body, that appear after the first @code{accept}
23120 or @code{select} statement, and therefore does not report a potential
23121 circularity in the original program.
23122
23123 The compiler will check to the extent it can that the above
23124 restriction is not violated, but it is not always possible to do a
23125 complete check at compile time, so it is important to use this
23126 pragma only if the stated restriction is in fact met, that is to say
23127 no task receives an entry call before elaboration of all units is completed.
23128
23129 @end itemize
23130
23131 @node Mixing Elaboration Models
23132 @section Mixing Elaboration Models
23133 @noindent
23134 So far, we have assumed that the entire program is either compiled
23135 using the dynamic model or static model, ensuring consistency. It
23136 is possible to mix the two models, but rules have to be followed
23137 if this mixing is done to ensure that elaboration checks are not
23138 omitted.
23139
23140 The basic rule is that @emph{a unit compiled with the static model cannot
23141 be @code{with'ed} by a unit compiled with the dynamic model}. The
23142 reason for this is that in the static model, a unit assumes that
23143 its clients guarantee to use (the equivalent of) pragma
23144 @code{Elaborate_All} so that no elaboration checks are required
23145 in inner subprograms, and this assumption is violated if the
23146 client is compiled with dynamic checks.
23147
23148 The precise rule is as follows. A unit that is compiled with dynamic
23149 checks can only @code{with} a unit that meets at least one of the
23150 following criteria:
23151
23152 @itemize @bullet
23153
23154 @item
23155 The @code{with'ed} unit is itself compiled with dynamic elaboration
23156 checks (that is with the @option{-gnatE} switch.
23157
23158 @item
23159 The @code{with'ed} unit is an internal GNAT implementation unit from
23160 the System, Interfaces, Ada, or GNAT hierarchies.
23161
23162 @item
23163 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23164
23165 @item
23166 The @code{with'ing} unit (that is the client) has an explicit pragma
23167 @code{Elaborate_All} for the @code{with'ed} unit.
23168
23169 @end itemize
23170
23171 @noindent
23172 If this rule is violated, that is if a unit with dynamic elaboration
23173 checks @code{with's} a unit that does not meet one of the above four
23174 criteria, then the binder (@code{gnatbind}) will issue a warning
23175 similar to that in the following example:
23176
23177 @smallexample
23178 warning: "x.ads" has dynamic elaboration checks and with's
23179 warning:   "y.ads" which has static elaboration checks
23180 @end smallexample
23181
23182 @noindent
23183 These warnings indicate that the rule has been violated, and that as a result
23184 elaboration checks may be missed in the resulting executable file.
23185 This warning may be suppressed using the @option{-ws} binder switch
23186 in the usual manner.
23187
23188 One useful application of this mixing rule is in the case of a subsystem
23189 which does not itself @code{with} units from the remainder of the
23190 application. In this case, the entire subsystem can be compiled with
23191 dynamic checks to resolve a circularity in the subsystem, while
23192 allowing the main application that uses this subsystem to be compiled
23193 using the more reliable default static model.
23194
23195 @node What to Do If the Default Elaboration Behavior Fails
23196 @section What to Do If the Default Elaboration Behavior Fails
23197
23198 @noindent
23199 If the binder cannot find an acceptable order, it outputs detailed
23200 diagnostics. For example:
23201 @smallexample
23202 @group
23203 @iftex
23204 @leftskip=0cm
23205 @end iftex
23206 error: elaboration circularity detected
23207 info:   "proc (body)" must be elaborated before "pack (body)"
23208 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23209 info:     recompile "pack (body)" with -gnatwl
23210 info:                             for full details
23211 info:       "proc (body)"
23212 info:         is needed by its spec:
23213 info:       "proc (spec)"
23214 info:         which is withed by:
23215 info:       "pack (body)"
23216 info:  "pack (body)" must be elaborated before "proc (body)"
23217 info:     reason: pragma Elaborate in unit "proc (body)"
23218 @end group
23219
23220 @end smallexample
23221
23222 @noindent
23223 In this case we have a cycle that the binder cannot break. On the one
23224 hand, there is an explicit pragma Elaborate in @code{proc} for
23225 @code{pack}. This means that the body of @code{pack} must be elaborated
23226 before the body of @code{proc}. On the other hand, there is elaboration
23227 code in @code{pack} that calls a subprogram in @code{proc}. This means
23228 that for maximum safety, there should really be a pragma
23229 Elaborate_All in @code{pack} for @code{proc} which would require that
23230 the body of @code{proc} be elaborated before the body of
23231 @code{pack}. Clearly both requirements cannot be satisfied.
23232 Faced with a circularity of this kind, you have three different options.
23233
23234 @table @asis
23235 @item Fix the program
23236 The most desirable option from the point of view of long-term maintenance
23237 is to rearrange the program so that the elaboration problems are avoided.
23238 One useful technique is to place the elaboration code into separate
23239 child packages. Another is to move some of the initialization code to
23240 explicitly called subprograms, where the program controls the order
23241 of initialization explicitly. Although this is the most desirable option,
23242 it may be impractical and involve too much modification, especially in
23243 the case of complex legacy code.
23244
23245 @item Perform dynamic checks
23246 If the compilations are done using the
23247 @option{-gnatE}
23248 (dynamic elaboration check) switch, then GNAT behaves in
23249 a quite different manner. Dynamic checks are generated for all calls
23250 that could possibly result in raising an exception. With this switch,
23251 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23252 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23253 The binder will generate an executable program that may or may not
23254 raise @code{Program_Error}, and then it is the programmer's job to ensure
23255 that it does not raise an exception. Note that it is important to
23256 compile all units with the switch, it cannot be used selectively.
23257
23258 @item Suppress checks
23259 The drawback of dynamic checks is that they generate a
23260 significant overhead at run time, both in space and time. If you
23261 are absolutely sure that your program cannot raise any elaboration
23262 exceptions, and you still want to use the dynamic elaboration model,
23263 then you can use the configuration pragma
23264 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23265 example this pragma could be placed in the @file{gnat.adc} file.
23266
23267 @item Suppress checks selectively
23268 When you know that certain calls in elaboration code cannot possibly
23269 lead to an elaboration error, and the binder nevertheless generates warnings
23270 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23271 circularities, it is possible to remove those warnings locally and obtain
23272 a program that will bind. Clearly this can be unsafe, and it is the
23273 responsibility of the programmer to make sure that the resulting program has
23274 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23275 be used with different granularity to suppress warnings and break
23276 elaboration circularities:
23277
23278 @itemize @bullet
23279 @item
23280 Place the pragma that names the called subprogram in the declarative part
23281 that contains the call.
23282
23283 @item
23284 Place the pragma in the declarative part, without naming an entity. This
23285 disables warnings on all calls in the corresponding  declarative region.
23286
23287 @item
23288 Place the pragma in the package spec that declares the called subprogram,
23289 and name the subprogram. This disables warnings on all elaboration calls to
23290 that subprogram.
23291
23292 @item
23293 Place the pragma in the package spec that declares the called subprogram,
23294 without naming any entity. This disables warnings on all elaboration calls to
23295 all subprograms declared in this spec.
23296
23297 @item Use Pragma Elaborate
23298 As previously described in section @xref{Treatment of Pragma Elaborate},
23299 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23300 that no elaboration checks are required on calls to the designated unit.
23301 There may be cases in which the caller knows that no transitive calls
23302 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23303 case where @code{pragma Elaborate_All} would cause a circularity.
23304 @end itemize
23305
23306 @noindent
23307 These five cases are listed in order of decreasing safety, and therefore
23308 require increasing programmer care in their application. Consider the
23309 following program:
23310
23311 @smallexample @c adanocomment
23312 package Pack1 is
23313   function F1 return Integer;
23314   X1 : Integer;
23315 end Pack1;
23316
23317 package Pack2 is
23318   function F2 return Integer;
23319   function Pure (x : integer) return integer;
23320   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23321   --  pragma Suppress (Elaboration_Check);              -- (4)
23322 end Pack2;
23323
23324 with Pack2;
23325 package body Pack1 is
23326   function F1 return Integer is
23327   begin
23328     return 100;
23329   end F1;
23330   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23331 begin
23332   declare
23333     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23334     --  pragma Suppress(Elaboration_Check);             -- (2)
23335   begin
23336     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23337   end;
23338 end Pack1;
23339
23340 with Pack1;
23341 package body Pack2 is
23342   function F2 return Integer is
23343   begin
23344      return Pack1.F1;
23345   end F2;
23346   function Pure (x : integer) return integer is
23347   begin
23348      return x ** 3 - 3 * x;
23349   end;
23350 end Pack2;
23351
23352 with Pack1, Ada.Text_IO;
23353 procedure Proc3 is
23354 begin
23355   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23356 end Proc3;
23357 @end smallexample
23358 In the absence of any pragmas, an attempt to bind this program produces
23359 the following diagnostics:
23360 @smallexample
23361 @group
23362 @iftex
23363 @leftskip=.5cm
23364 @end iftex
23365 error: elaboration circularity detected
23366 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23367 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23368 info:       recompile "pack1 (body)" with -gnatwl for full details
23369 info:          "pack1 (body)"
23370 info:             must be elaborated along with its spec:
23371 info:          "pack1 (spec)"
23372 info:             which is withed by:
23373 info:          "pack2 (body)"
23374 info:             which must be elaborated along with its spec:
23375 info:          "pack2 (spec)"
23376 info:             which is withed by:
23377 info:          "pack1 (body)"
23378 @end group
23379 @end smallexample
23380 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23381 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23382 F2 is safe, even though F2 calls F1, because the call appears after the
23383 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23384 remove the warning on the call. It is also possible to use pragma (2)
23385 because there are no other potentially unsafe calls in the block.
23386
23387 @noindent
23388 The call to @code{Pure} is safe because this function does not depend on the
23389 state of @code{Pack2}. Therefore any call to this function is safe, and it
23390 is correct to place pragma (3) in the corresponding package spec.
23391
23392 @noindent
23393 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23394 warnings on all calls to functions declared therein. Note that this is not
23395 necessarily safe, and requires more detailed examination of the subprogram
23396 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23397 be already elaborated.
23398 @end table
23399
23400 @noindent
23401 It is hard to generalize on which of these four approaches should be
23402 taken. Obviously if it is possible to fix the program so that the default
23403 treatment works, this is preferable, but this may not always be practical.
23404 It is certainly simple enough to use
23405 @option{-gnatE}
23406 but the danger in this case is that, even if the GNAT binder
23407 finds a correct elaboration order, it may not always do so,
23408 and certainly a binder from another Ada compiler might not. A
23409 combination of testing and analysis (for which the warnings generated
23410 with the
23411 @option{-gnatwl}
23412 switch can be useful) must be used to ensure that the program is free
23413 of errors. One switch that is useful in this testing is the
23414 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23415 switch for
23416 @code{gnatbind}.
23417 Normally the binder tries to find an order that has the best chance of
23418 of avoiding elaboration problems. With this switch, the binder
23419 plays a devil's advocate role, and tries to choose the order that
23420 has the best chance of failing. If your program works even with this
23421 switch, then it has a better chance of being error free, but this is still
23422 not a guarantee.
23423
23424 For an example of this approach in action, consider the C-tests (executable
23425 tests) from the ACVC suite. If these are compiled and run with the default
23426 treatment, then all but one of them succeed without generating any error
23427 diagnostics from the binder. However, there is one test that fails, and
23428 this is not surprising, because the whole point of this test is to ensure
23429 that the compiler can handle cases where it is impossible to determine
23430 a correct order statically, and it checks that an exception is indeed
23431 raised at run time.
23432
23433 This one test must be compiled and run using the
23434 @option{-gnatE}
23435 switch, and then it passes. Alternatively, the entire suite can
23436 be run using this switch. It is never wrong to run with the dynamic
23437 elaboration switch if your code is correct, and we assume that the
23438 C-tests are indeed correct (it is less efficient, but efficiency is
23439 not a factor in running the ACVC tests.)
23440
23441 @node Elaboration for Access-to-Subprogram Values
23442 @section Elaboration for Access-to-Subprogram Values
23443 @cindex Access-to-subprogram
23444
23445 @noindent
23446 The introduction of access-to-subprogram types in Ada 95 complicates
23447 the handling of elaboration. The trouble is that it becomes
23448 impossible to tell at compile time which procedure
23449 is being called. This means that it is not possible for the binder
23450 to analyze the elaboration requirements in this case.
23451
23452 If at the point at which the access value is created
23453 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23454 the body of the subprogram is
23455 known to have been elaborated, then the access value is safe, and its use
23456 does not require a check. This may be achieved by appropriate arrangement
23457 of the order of declarations if the subprogram is in the current unit,
23458 or, if the subprogram is in another unit, by using pragma
23459 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23460 on the referenced unit.
23461
23462 If the referenced body is not known to have been elaborated at the point
23463 the access value is created, then any use of the access value must do a
23464 dynamic check, and this dynamic check will fail and raise a
23465 @code{Program_Error} exception if the body has not been elaborated yet.
23466 GNAT will generate the necessary checks, and in addition, if the
23467 @option{-gnatwl}
23468 switch is set, will generate warnings that such checks are required.
23469
23470 The use of dynamic dispatching for tagged types similarly generates
23471 a requirement for dynamic checks, and premature calls to any primitive
23472 operation of a tagged type before the body of the operation has been
23473 elaborated, will result in the raising of @code{Program_Error}.
23474
23475 @node Summary of Procedures for Elaboration Control
23476 @section Summary of Procedures for Elaboration Control
23477 @cindex Elaboration control
23478
23479 @noindent
23480 First, compile your program with the default options, using none of
23481 the special elaboration control switches. If the binder successfully
23482 binds your program, then you can be confident that, apart from issues
23483 raised by the use of access-to-subprogram types and dynamic dispatching,
23484 the program is free of elaboration errors. If it is important that the
23485 program be portable, then use the
23486 @option{-gnatwl}
23487 switch to generate warnings about missing @code{Elaborate_All}
23488 pragmas, and supply the missing pragmas.
23489
23490 If the program fails to bind using the default static elaboration
23491 handling, then you can fix the program to eliminate the binder
23492 message, or recompile the entire program with the
23493 @option{-gnatE} switch to generate dynamic elaboration checks,
23494 and, if you are sure there really are no elaboration problems,
23495 use a global pragma @code{Suppress (Elaboration_Check)}.
23496
23497 @node Other Elaboration Order Considerations
23498 @section Other Elaboration Order Considerations
23499 @noindent
23500 This section has been entirely concerned with the issue of finding a valid
23501 elaboration order, as defined by the Ada Reference Manual. In a case
23502 where several elaboration orders are valid, the task is to find one
23503 of the possible valid elaboration orders (and the static model in GNAT
23504 will ensure that this is achieved).
23505
23506 The purpose of the elaboration rules in the Ada Reference Manual is to
23507 make sure that no entity is accessed before it has been elaborated. For
23508 a subprogram, this means that the spec and body must have been elaborated
23509 before the subprogram is called. For an object, this means that the object
23510 must have been elaborated before its value is read or written. A violation
23511 of either of these two requirements is an access before elaboration order,
23512 and this section has been all about avoiding such errors.
23513
23514 In the case where more than one order of elaboration is possible, in the
23515 sense that access before elaboration errors are avoided, then any one of
23516 the orders is ``correct'' in the sense that it meets the requirements of
23517 the Ada Reference Manual, and no such error occurs.
23518
23519 However, it may be the case for a given program, that there are
23520 constraints on the order of elaboration that come not from consideration
23521 of avoiding elaboration errors, but rather from extra-lingual logic
23522 requirements. Consider this example:
23523
23524 @smallexample @c ada
23525 with Init_Constants;
23526 package Constants is
23527    X : Integer := 0;
23528    Y : Integer := 0;
23529 end Constants;
23530
23531 package Init_Constants is
23532    procedure P; -- require a body
23533 end Init_Constants;
23534
23535 with Constants;
23536 package body Init_Constants is
23537    procedure P is begin null; end;
23538 begin
23539    Constants.X := 3;
23540    Constants.Y := 4;
23541 end Init_Constants;
23542
23543 with Constants;
23544 package Calc is
23545    Z : Integer := Constants.X + Constants.Y;
23546 end Calc;
23547
23548 with Calc;
23549 with Text_IO; use Text_IO;
23550 procedure Main is
23551 begin
23552    Put_Line (Calc.Z'Img);
23553 end Main;
23554 @end smallexample
23555
23556 @noindent
23557 In this example, there is more than one valid order of elaboration. For
23558 example both the following are correct orders:
23559
23560 @smallexample
23561 Init_Constants spec
23562 Constants spec
23563 Calc spec
23564 Init_Constants body
23565 Main body
23566
23567   and
23568
23569 Init_Constants spec
23570 Init_Constants body
23571 Constants spec
23572 Calc spec
23573 Main body
23574 @end smallexample
23575
23576 @noindent
23577 There is no language rule to prefer one or the other, both are correct
23578 from an order of elaboration point of view. But the programmatic effects
23579 of the two orders are very different. In the first, the elaboration routine
23580 of @code{Calc} initializes @code{Z} to zero, and then the main program
23581 runs with this value of zero. But in the second order, the elaboration
23582 routine of @code{Calc} runs after the body of Init_Constants has set
23583 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23584 runs.
23585
23586 One could perhaps by applying pretty clever non-artificial intelligence
23587 to the situation guess that it is more likely that the second order of
23588 elaboration is the one desired, but there is no formal linguistic reason
23589 to prefer one over the other. In fact in this particular case, GNAT will
23590 prefer the second order, because of the rule that bodies are elaborated
23591 as soon as possible, but it's just luck that this is what was wanted
23592 (if indeed the second order was preferred).
23593
23594 If the program cares about the order of elaboration routines in a case like
23595 this, it is important to specify the order required. In this particular
23596 case, that could have been achieved by adding to the spec of Calc:
23597
23598 @smallexample @c ada
23599 pragma Elaborate_All (Constants);
23600 @end smallexample
23601
23602 @noindent
23603 which requires that the body (if any) and spec of @code{Constants},
23604 as well as the body and spec of any unit @code{with}'ed by
23605 @code{Constants} be elaborated before @code{Calc} is elaborated.
23606
23607 Clearly no automatic method can always guess which alternative you require,
23608 and if you are working with legacy code that had constraints of this kind
23609 which were not properly specified by adding @code{Elaborate} or
23610 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23611 compilers can choose different orders.
23612
23613 The @code{gnatbind}
23614 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23615 out problems. This switch causes bodies to be elaborated as late as possible
23616 instead of as early as possible. In the example above, it would have forced
23617 the choice of the first elaboration order. If you get different results
23618 when using this switch, and particularly if one set of results is right,
23619 and one is wrong as far as you are concerned, it shows that you have some
23620 missing @code{Elaborate} pragmas. For the example above, we have the
23621 following output:
23622
23623 @smallexample
23624 gnatmake -f -q main
23625 main
23626  7
23627 gnatmake -f -q main -bargs -p
23628 main
23629  0
23630 @end smallexample
23631
23632 @noindent
23633 It is of course quite unlikely that both these results are correct, so
23634 it is up to you in a case like this to investigate the source of the
23635 difference, by looking at the two elaboration orders that are chosen,
23636 and figuring out which is correct, and then adding the necessary
23637 @code{Elaborate_All} pragmas to ensure the desired order.
23638
23639
23640 @node Inline Assembler
23641 @appendix Inline Assembler
23642
23643 @noindent
23644 If you need to write low-level software that interacts directly
23645 with the hardware, Ada provides two ways to incorporate assembly
23646 language code into your program.  First, you can import and invoke
23647 external routines written in assembly language, an Ada feature fully
23648 supported by GNAT.  However, for small sections of code it may be simpler
23649 or more efficient to include assembly language statements directly
23650 in your Ada source program, using the facilities of the implementation-defined
23651 package @code{System.Machine_Code}, which incorporates the gcc
23652 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23653 including the following:
23654
23655 @itemize @bullet
23656 @item No need to use non-Ada tools
23657 @item Consistent interface over different targets
23658 @item Automatic usage of the proper calling conventions
23659 @item Access to Ada constants and variables
23660 @item Definition of intrinsic routines
23661 @item Possibility of inlining a subprogram comprising assembler code
23662 @item Code optimizer can take Inline Assembler code into account
23663 @end itemize
23664
23665 This chapter presents a series of examples to show you how to use
23666 the Inline Assembler.  Although it focuses on the Intel x86,
23667 the general approach applies also to other processors.
23668 It is assumed that you are familiar with Ada
23669 and with assembly language programming.
23670
23671 @menu
23672 * Basic Assembler Syntax::
23673 * A Simple Example of Inline Assembler::
23674 * Output Variables in Inline Assembler::
23675 * Input Variables in Inline Assembler::
23676 * Inlining Inline Assembler Code::
23677 * Other Asm Functionality::
23678 * A Complete Example::
23679 @end menu
23680
23681 @c ---------------------------------------------------------------------------
23682 @node Basic Assembler Syntax
23683 @section Basic Assembler Syntax
23684
23685 @noindent
23686 The assembler used by GNAT and gcc is based not on the Intel assembly
23687 language, but rather on a language that descends from the AT&T Unix
23688 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
23689 The following table summarizes the main features of @emph{as} syntax
23690 and points out the differences from the Intel conventions.
23691 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
23692 pre-processor) documentation for further information.
23693
23694 @table @asis
23695 @item Register names
23696 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
23697 @*
23698 Intel: No extra punctuation; for example @code{eax}
23699
23700 @item Immediate operand
23701 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
23702 @*
23703 Intel: No extra punctuation; for example @code{4}
23704
23705 @item Address
23706 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
23707 @*
23708 Intel: No extra punctuation; for example @code{loc}
23709
23710 @item Memory contents
23711 gcc / @emph{as}: No extra punctuation; for example @code{loc}
23712 @*
23713 Intel: Square brackets; for example @code{[loc]}
23714
23715 @item Register contents
23716 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
23717 @*
23718 Intel: Square brackets; for example @code{[eax]}
23719
23720 @item Hexadecimal numbers
23721 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
23722 @*
23723 Intel: Trailing ``h''; for example @code{A0h}
23724
23725 @item Operand size
23726 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
23727 a 16-bit word
23728 @*
23729 Intel: Implicit, deduced by assembler; for example @code{mov}
23730
23731 @item Instruction repetition
23732 gcc / @emph{as}: Split into two lines; for example
23733 @*
23734 @code{rep}
23735 @*
23736 @code{stosl}
23737 @*
23738 Intel: Keep on one line; for example @code{rep stosl}
23739
23740 @item Order of operands
23741 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
23742 @*
23743 Intel: Destination first; for example @code{mov eax, 4}
23744 @end table
23745
23746 @c ---------------------------------------------------------------------------
23747 @node A Simple Example of Inline Assembler
23748 @section A Simple Example of Inline Assembler
23749
23750 @noindent
23751 The following example will generate a single assembly language statement,
23752 @code{nop}, which does nothing.  Despite its lack of run-time effect,
23753 the example will be useful in illustrating the basics of
23754 the Inline Assembler facility.
23755
23756 @smallexample @c ada
23757 @group
23758 with System.Machine_Code; use System.Machine_Code;
23759 procedure Nothing is
23760 begin
23761    Asm ("nop");
23762 end Nothing;
23763 @end group
23764 @end smallexample
23765
23766 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
23767 here it takes one parameter, a @emph{template string} that must be a static
23768 expression and that will form the generated instruction.
23769 @code{Asm} may be regarded as a compile-time procedure that parses
23770 the template string and additional parameters (none here),
23771 from which it generates a sequence of assembly language instructions.
23772
23773 The examples in this chapter will illustrate several of the forms
23774 for invoking @code{Asm}; a complete specification of the syntax
23775 is found in the @cite{GNAT Reference Manual}.
23776
23777 Under the standard GNAT conventions, the @code{Nothing} procedure
23778 should be in a file named @file{nothing.adb}.
23779 You can build the executable in the usual way:
23780 @smallexample
23781 gnatmake nothing
23782 @end smallexample
23783 However, the interesting aspect of this example is not its run-time behavior
23784 but rather the generated assembly code.
23785 To see this output, invoke the compiler as follows:
23786 @smallexample
23787    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
23788 @end smallexample
23789 where the options are:
23790
23791 @table @code
23792 @item -c
23793 compile only (no bind or link)
23794 @item -S
23795 generate assembler listing
23796 @item -fomit-frame-pointer
23797 do not set up separate stack frames
23798 @item -gnatp
23799 do not add runtime checks
23800 @end table
23801
23802 This gives a human-readable assembler version of the code. The resulting
23803 file will have the same name as the Ada source file, but with a @code{.s}
23804 extension. In our example, the file @file{nothing.s} has the following
23805 contents:
23806
23807 @smallexample
23808 @group
23809 .file "nothing.adb"
23810 gcc2_compiled.:
23811 ___gnu_compiled_ada:
23812 .text
23813    .align 4
23814 .globl __ada_nothing
23815 __ada_nothing:
23816 #APP
23817    nop
23818 #NO_APP
23819    jmp L1
23820    .align 2,0x90
23821 L1:
23822    ret
23823 @end group
23824 @end smallexample
23825
23826 The assembly code you included is clearly indicated by
23827 the compiler, between the @code{#APP} and @code{#NO_APP}
23828 delimiters. The character before the 'APP' and 'NOAPP'
23829 can differ on different targets. For example, GNU/Linux uses '#APP' while
23830 on NT you will see '/APP'.
23831
23832 If you make a mistake in your assembler code (such as using the
23833 wrong size modifier, or using a wrong operand for the instruction) GNAT
23834 will report this error in a temporary file, which will be deleted when
23835 the compilation is finished.  Generating an assembler file will help
23836 in such cases, since you can assemble this file separately using the
23837 @emph{as} assembler that comes with gcc.
23838
23839 Assembling the file using the command
23840
23841 @smallexample
23842 as @file{nothing.s}
23843 @end smallexample
23844 @noindent
23845 will give you error messages whose lines correspond to the assembler
23846 input file, so you can easily find and correct any mistakes you made.
23847 If there are no errors, @emph{as} will generate an object file
23848 @file{nothing.out}.
23849
23850 @c ---------------------------------------------------------------------------
23851 @node Output Variables in Inline Assembler
23852 @section Output Variables in Inline Assembler
23853
23854 @noindent
23855 The examples in this section, showing how to access the processor flags,
23856 illustrate how to specify the destination operands for assembly language
23857 statements.
23858
23859 @smallexample @c ada
23860 @group
23861 with Interfaces; use Interfaces;
23862 with Ada.Text_IO; use Ada.Text_IO;
23863 with System.Machine_Code; use System.Machine_Code;
23864 procedure Get_Flags is
23865    Flags : Unsigned_32;
23866    use ASCII;
23867 begin
23868    Asm ("pushfl"          & LF & HT & -- push flags on stack
23869         "popl %%eax"      & LF & HT & -- load eax with flags
23870         "movl %%eax, %0",             -- store flags in variable
23871         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23872    Put_Line ("Flags register:" & Flags'Img);
23873 end Get_Flags;
23874 @end group
23875 @end smallexample
23876
23877 In order to have a nicely aligned assembly listing, we have separated
23878 multiple assembler statements in the Asm template string with linefeed
23879 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
23880 The resulting section of the assembly output file is:
23881
23882 @smallexample
23883 @group
23884 #APP
23885    pushfl
23886    popl %eax
23887    movl %eax, -40(%ebp)
23888 #NO_APP
23889 @end group
23890 @end smallexample
23891
23892 It would have been legal to write the Asm invocation as:
23893
23894 @smallexample
23895 Asm ("pushfl popl %%eax movl %%eax, %0")
23896 @end smallexample
23897
23898 but in the generated assembler file, this would come out as:
23899
23900 @smallexample
23901 #APP
23902    pushfl popl %eax movl %eax, -40(%ebp)
23903 #NO_APP
23904 @end smallexample
23905
23906 which is not so convenient for the human reader.
23907
23908 We use Ada comments
23909 at the end of each line to explain what the assembler instructions
23910 actually do.  This is a useful convention.
23911
23912 When writing Inline Assembler instructions, you need to precede each register
23913 and variable name with a percent sign.  Since the assembler already requires
23914 a percent sign at the beginning of a register name, you need two consecutive
23915 percent signs for such names in the Asm template string, thus @code{%%eax}.
23916 In the generated assembly code, one of the percent signs will be stripped off.
23917
23918 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
23919 variables: operands you later define using @code{Input} or @code{Output}
23920 parameters to @code{Asm}.
23921 An output variable is illustrated in
23922 the third statement in the Asm template string:
23923 @smallexample
23924 movl %%eax, %0
23925 @end smallexample
23926 The intent is to store the contents of the eax register in a variable that can
23927 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
23928 necessarily work, since the compiler might optimize by using a register
23929 to hold Flags, and the expansion of the @code{movl} instruction would not be
23930 aware of this optimization.  The solution is not to store the result directly
23931 but rather to advise the compiler to choose the correct operand form;
23932 that is the purpose of the @code{%0} output variable.
23933
23934 Information about the output variable is supplied in the @code{Outputs}
23935 parameter to @code{Asm}:
23936 @smallexample
23937 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23938 @end smallexample
23939
23940 The output is defined by the @code{Asm_Output} attribute of the target type;
23941 the general format is
23942 @smallexample
23943 Type'Asm_Output (constraint_string, variable_name)
23944 @end smallexample
23945
23946 The constraint string directs the compiler how
23947 to store/access the associated variable.  In the example
23948 @smallexample
23949 Unsigned_32'Asm_Output ("=m", Flags);
23950 @end smallexample
23951 the @code{"m"} (memory) constraint tells the compiler that the variable
23952 @code{Flags} should be stored in a memory variable, thus preventing
23953 the optimizer from keeping it in a register.  In contrast,
23954 @smallexample
23955 Unsigned_32'Asm_Output ("=r", Flags);
23956 @end smallexample
23957 uses the @code{"r"} (register) constraint, telling the compiler to
23958 store the variable in a register.
23959
23960 If the constraint is preceded by the equal character (@strong{=}), it tells
23961 the compiler that the variable will be used to store data into it.
23962
23963 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
23964 allowing the optimizer to choose whatever it deems best.
23965
23966 There are a fairly large number of constraints, but the ones that are
23967 most useful (for the Intel x86 processor) are the following:
23968
23969 @table @code
23970 @item =
23971 output constraint
23972 @item g
23973 global (i.e. can be stored anywhere)
23974 @item m
23975 in memory
23976 @item I
23977 a constant
23978 @item a
23979 use eax
23980 @item b
23981 use ebx
23982 @item c
23983 use ecx
23984 @item d
23985 use edx
23986 @item S
23987 use esi
23988 @item D
23989 use edi
23990 @item r
23991 use one of eax, ebx, ecx or edx
23992 @item q
23993 use one of eax, ebx, ecx, edx, esi or edi
23994 @end table
23995
23996 The full set of constraints is described in the gcc and @emph{as}
23997 documentation; note that it is possible to combine certain constraints
23998 in one constraint string.
23999
24000 You specify the association of an output variable with an assembler operand
24001 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24002 integer.  Thus in
24003 @smallexample @c ada
24004 @group
24005 Asm ("pushfl"          & LF & HT & -- push flags on stack
24006      "popl %%eax"      & LF & HT & -- load eax with flags
24007      "movl %%eax, %0",             -- store flags in variable
24008      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24009 @end group
24010 @end smallexample
24011 @noindent
24012 @code{%0} will be replaced in the expanded code by the appropriate operand,
24013 whatever
24014 the compiler decided for the @code{Flags} variable.
24015
24016 In general, you may have any number of output variables:
24017 @itemize @bullet
24018 @item
24019 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24020 @item
24021 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24022 of @code{Asm_Output} attributes
24023 @end itemize
24024
24025 For example:
24026 @smallexample @c ada
24027 @group
24028 Asm ("movl %%eax, %0" & LF & HT &
24029      "movl %%ebx, %1" & LF & HT &
24030      "movl %%ecx, %2",
24031      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24032                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24033                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24034 @end group
24035 @end smallexample
24036 @noindent
24037 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24038 in the Ada program.
24039
24040 As a variation on the @code{Get_Flags} example, we can use the constraints
24041 string to direct the compiler to store the eax register into the @code{Flags}
24042 variable, instead of including the store instruction explicitly in the
24043 @code{Asm} template string:
24044
24045 @smallexample @c ada
24046 @group
24047 with Interfaces; use Interfaces;
24048 with Ada.Text_IO; use Ada.Text_IO;
24049 with System.Machine_Code; use System.Machine_Code;
24050 procedure Get_Flags_2 is
24051    Flags : Unsigned_32;
24052    use ASCII;
24053 begin
24054    Asm ("pushfl"      & LF & HT & -- push flags on stack
24055         "popl %%eax",             -- save flags in eax
24056         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24057    Put_Line ("Flags register:" & Flags'Img);
24058 end Get_Flags_2;
24059 @end group
24060 @end smallexample
24061
24062 @noindent
24063 The @code{"a"} constraint tells the compiler that the @code{Flags}
24064 variable will come from the eax register. Here is the resulting code:
24065
24066 @smallexample
24067 @group
24068 #APP
24069    pushfl
24070    popl %eax
24071 #NO_APP
24072    movl %eax,-40(%ebp)
24073 @end group
24074 @end smallexample
24075
24076 @noindent
24077 The compiler generated the store of eax into Flags after
24078 expanding the assembler code.
24079
24080 Actually, there was no need to pop the flags into the eax register;
24081 more simply, we could just pop the flags directly into the program variable:
24082
24083 @smallexample @c ada
24084 @group
24085 with Interfaces; use Interfaces;
24086 with Ada.Text_IO; use Ada.Text_IO;
24087 with System.Machine_Code; use System.Machine_Code;
24088 procedure Get_Flags_3 is
24089    Flags : Unsigned_32;
24090    use ASCII;
24091 begin
24092    Asm ("pushfl"  & LF & HT & -- push flags on stack
24093         "pop %0",             -- save flags in Flags
24094         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24095    Put_Line ("Flags register:" & Flags'Img);
24096 end Get_Flags_3;
24097 @end group
24098 @end smallexample
24099
24100 @c ---------------------------------------------------------------------------
24101 @node Input Variables in Inline Assembler
24102 @section Input Variables in Inline Assembler
24103
24104 @noindent
24105 The example in this section illustrates how to specify the source operands
24106 for assembly language statements.
24107 The program simply increments its input value by 1:
24108
24109 @smallexample @c ada
24110 @group
24111 with Interfaces; use Interfaces;
24112 with Ada.Text_IO; use Ada.Text_IO;
24113 with System.Machine_Code; use System.Machine_Code;
24114 procedure Increment is
24115
24116    function Incr (Value : Unsigned_32) return Unsigned_32 is
24117       Result : Unsigned_32;
24118    begin
24119       Asm ("incl %0",
24120            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24121            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24122       return Result;
24123    end Incr;
24124
24125    Value : Unsigned_32;
24126
24127 begin
24128    Value := 5;
24129    Put_Line ("Value before is" & Value'Img);
24130    Value := Incr (Value);
24131    Put_Line ("Value after is" & Value'Img);
24132 end Increment;
24133 @end group
24134 @end smallexample
24135
24136 The @code{Outputs} parameter to @code{Asm} specifies
24137 that the result will be in the eax register and that it is to be stored
24138 in the @code{Result} variable.
24139
24140 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24141 but with an @code{Asm_Input} attribute.
24142 The @code{"="} constraint, indicating an output value, is not present.
24143
24144 You can have multiple input variables, in the same way that you can have more
24145 than one output variable.
24146
24147 The parameter count (%0, %1) etc, now starts at the first input
24148 statement, and continues with the output statements.
24149 When both parameters use the same variable, the
24150 compiler will treat them as the same %n operand, which is the case here.
24151
24152 Just as the @code{Outputs} parameter causes the register to be stored into the
24153 target variable after execution of the assembler statements, so does the
24154 @code{Inputs} parameter cause its variable to be loaded into the register
24155 before execution of the assembler statements.
24156
24157 Thus the effect of the @code{Asm} invocation is:
24158 @enumerate
24159 @item load the 32-bit value of @code{Value} into eax
24160 @item execute the @code{incl %eax} instruction
24161 @item store the contents of eax into the @code{Result} variable
24162 @end enumerate
24163
24164 The resulting assembler file (with @option{-O2} optimization) contains:
24165 @smallexample
24166 @group
24167 _increment__incr.1:
24168    subl $4,%esp
24169    movl 8(%esp),%eax
24170 #APP
24171    incl %eax
24172 #NO_APP
24173    movl %eax,%edx
24174    movl %ecx,(%esp)
24175    addl $4,%esp
24176    ret
24177 @end group
24178 @end smallexample
24179
24180 @c ---------------------------------------------------------------------------
24181 @node Inlining Inline Assembler Code
24182 @section Inlining Inline Assembler Code
24183
24184 @noindent
24185 For a short subprogram such as the @code{Incr} function in the previous
24186 section, the overhead of the call and return (creating / deleting the stack
24187 frame) can be significant, compared to the amount of code in the subprogram
24188 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24189 which directs the compiler to expand invocations of the subprogram at the
24190 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24191 Here is the resulting program:
24192
24193 @smallexample @c ada
24194 @group
24195 with Interfaces; use Interfaces;
24196 with Ada.Text_IO; use Ada.Text_IO;
24197 with System.Machine_Code; use System.Machine_Code;
24198 procedure Increment_2 is
24199
24200    function Incr (Value : Unsigned_32) return Unsigned_32 is
24201       Result : Unsigned_32;
24202    begin
24203       Asm ("incl %0",
24204            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24205            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24206       return Result;
24207    end Incr;
24208    pragma Inline (Increment);
24209
24210    Value : Unsigned_32;
24211
24212 begin
24213    Value := 5;
24214    Put_Line ("Value before is" & Value'Img);
24215    Value := Increment (Value);
24216    Put_Line ("Value after is" & Value'Img);
24217 end Increment_2;
24218 @end group
24219 @end smallexample
24220
24221 Compile the program with both optimization (@option{-O2}) and inlining
24222 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24223
24224 The @code{Incr} function is still compiled as usual, but at the
24225 point in @code{Increment} where our function used to be called:
24226
24227 @smallexample
24228 @group
24229 pushl %edi
24230 call _increment__incr.1
24231 @end group
24232 @end smallexample
24233
24234 @noindent
24235 the code for the function body directly appears:
24236
24237 @smallexample
24238 @group
24239 movl %esi,%eax
24240 #APP
24241    incl %eax
24242 #NO_APP
24243    movl %eax,%edx
24244 @end group
24245 @end smallexample
24246
24247 @noindent
24248 thus saving the overhead of stack frame setup and an out-of-line call.
24249
24250 @c ---------------------------------------------------------------------------
24251 @node Other Asm Functionality
24252 @section Other @code{Asm} Functionality
24253
24254 @noindent
24255 This section describes two important parameters to the @code{Asm}
24256 procedure: @code{Clobber}, which identifies register usage;
24257 and @code{Volatile}, which inhibits unwanted optimizations.
24258
24259 @menu
24260 * The Clobber Parameter::
24261 * The Volatile Parameter::
24262 @end menu
24263
24264 @c ---------------------------------------------------------------------------
24265 @node The Clobber Parameter
24266 @subsection The @code{Clobber} Parameter
24267
24268 @noindent
24269 One of the dangers of intermixing assembly language and a compiled language
24270 such as Ada is that the compiler needs to be aware of which registers are
24271 being used by the assembly code.  In some cases, such as the earlier examples,
24272 the constraint string is sufficient to indicate register usage (e.g.,
24273 @code{"a"} for
24274 the eax register).  But more generally, the compiler needs an explicit
24275 identification of the registers that are used by the Inline Assembly
24276 statements.
24277
24278 Using a register that the compiler doesn't know about
24279 could be a side effect of an instruction (like @code{mull}
24280 storing its result in both eax and edx).
24281 It can also arise from explicit register usage in your
24282 assembly code; for example:
24283 @smallexample
24284 @group
24285 Asm ("movl %0, %%ebx" & LF & HT &
24286      "movl %%ebx, %1",
24287      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24288      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24289 @end group
24290 @end smallexample
24291 @noindent
24292 where the compiler (since it does not analyze the @code{Asm} template string)
24293 does not know you are using the ebx register.
24294
24295 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24296 to identify the registers that will be used by your assembly code:
24297
24298 @smallexample
24299 @group
24300 Asm ("movl %0, %%ebx" & LF & HT &
24301      "movl %%ebx, %1",
24302      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24303      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24304      Clobber => "ebx");
24305 @end group
24306 @end smallexample
24307
24308 The Clobber parameter is a static string expression specifying the
24309 register(s) you are using.  Note that register names are @emph{not} prefixed
24310 by a percent sign. Also, if more than one register is used then their names
24311 are separated by commas; e.g., @code{"eax, ebx"}
24312
24313 The @code{Clobber} parameter has several additional uses:
24314 @enumerate
24315 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24316 @item Use ``register'' name @code{memory} if you changed a memory location
24317 @end enumerate
24318
24319 @c ---------------------------------------------------------------------------
24320 @node The Volatile Parameter
24321 @subsection The @code{Volatile} Parameter
24322 @cindex Volatile parameter
24323
24324 @noindent
24325 Compiler optimizations in the presence of Inline Assembler may sometimes have
24326 unwanted effects.  For example, when an @code{Asm} invocation with an input
24327 variable is inside a loop, the compiler might move the loading of the input
24328 variable outside the loop, regarding it as a one-time initialization.
24329
24330 If this effect is not desired, you can disable such optimizations by setting
24331 the @code{Volatile} parameter to @code{True}; for example:
24332
24333 @smallexample @c ada
24334 @group
24335 Asm ("movl %0, %%ebx" & LF & HT &
24336      "movl %%ebx, %1",
24337      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24338      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24339      Clobber  => "ebx",
24340      Volatile => True);
24341 @end group
24342 @end smallexample
24343
24344 By default, @code{Volatile} is set to @code{False} unless there is no
24345 @code{Outputs} parameter.
24346
24347 Although setting @code{Volatile} to @code{True} prevents unwanted
24348 optimizations, it will also disable other optimizations that might be
24349 important for efficiency. In general, you should set @code{Volatile}
24350 to @code{True} only if the compiler's optimizations have created
24351 problems.
24352
24353 @c ---------------------------------------------------------------------------
24354 @node A Complete Example
24355 @section A Complete Example
24356
24357 @noindent
24358 This section contains a complete program illustrating a realistic usage
24359 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24360 @code{Check_CPU} and a package @code{Intel_CPU}.
24361 The package declares a collection of functions that detect the properties
24362 of the 32-bit x86 processor that is running the program.
24363 The main procedure invokes these functions and displays the information.
24364
24365 The Intel_CPU package could be enhanced by adding functions to
24366 detect the type of x386 co-processor, the processor caching options and
24367 special operations such as the SIMD extensions.
24368
24369 Although the Intel_CPU package has been written for 32-bit Intel
24370 compatible CPUs, it is OS neutral. It has been tested on DOS,
24371 Windows/NT and GNU/Linux.
24372
24373 @menu
24374 * Check_CPU Procedure::
24375 * Intel_CPU Package Specification::
24376 * Intel_CPU Package Body::
24377 @end menu
24378
24379 @c ---------------------------------------------------------------------------
24380 @node Check_CPU Procedure
24381 @subsection @code{Check_CPU} Procedure
24382 @cindex Check_CPU procedure
24383
24384 @smallexample @c adanocomment
24385 ---------------------------------------------------------------------
24386 --                                                                 --
24387 --  Uses the Intel_CPU package to identify the CPU the program is  --
24388 --  running on, and some of the features it supports.              --
24389 --                                                                 --
24390 ---------------------------------------------------------------------
24391
24392 with Intel_CPU;                     --  Intel CPU detection functions
24393 with Ada.Text_IO;                   --  Standard text I/O
24394 with Ada.Command_Line;              --  To set the exit status
24395
24396 procedure Check_CPU is
24397
24398    Type_Found : Boolean := False;
24399    --  Flag to indicate that processor was identified
24400
24401    Features   : Intel_CPU.Processor_Features;
24402    --  The processor features
24403
24404    Signature  : Intel_CPU.Processor_Signature;
24405    --  The processor type signature
24406
24407 begin
24408
24409    -----------------------------------
24410    --  Display the program banner.  --
24411    -----------------------------------
24412
24413    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24414                          ": check Intel CPU version and features, v1.0");
24415    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24416    Ada.Text_IO.New_Line;
24417
24418    -----------------------------------------------------------------------
24419    --  We can safely start with the assumption that we are on at least  --
24420    --  a x386 processor. If the CPUID instruction is present, then we   --
24421    --  have a later processor type.                                     --
24422    -----------------------------------------------------------------------
24423
24424    if Intel_CPU.Has_CPUID = False then
24425
24426       --  No CPUID instruction, so we assume this is indeed a x386
24427       --  processor. We can still check if it has a FP co-processor.
24428       if Intel_CPU.Has_FPU then
24429          Ada.Text_IO.Put_Line
24430            ("x386-type processor with a FP co-processor");
24431       else
24432          Ada.Text_IO.Put_Line
24433            ("x386-type processor without a FP co-processor");
24434       end if;  --  check for FPU
24435
24436       --  Program done
24437       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24438       return;
24439
24440    end if;  --  check for CPUID
24441
24442    -----------------------------------------------------------------------
24443    --  If CPUID is supported, check if this is a true Intel processor,  --
24444    --  if it is not, display a warning.                                 --
24445    -----------------------------------------------------------------------
24446
24447    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24448       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24449       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24450    end if;  --  check if Intel
24451
24452    ----------------------------------------------------------------------
24453    --  With the CPUID instruction present, we can assume at least a    --
24454    --  x486 processor. If the CPUID support level is < 1 then we have  --
24455    --  to leave it at that.                                            --
24456    ----------------------------------------------------------------------
24457
24458    if Intel_CPU.CPUID_Level < 1 then
24459
24460       --  Ok, this is a x486 processor. we still can get the Vendor ID
24461       Ada.Text_IO.Put_Line ("x486-type processor");
24462       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24463
24464       --  We can also check if there is a FPU present
24465       if Intel_CPU.Has_FPU then
24466          Ada.Text_IO.Put_Line ("Floating-Point support");
24467       else
24468          Ada.Text_IO.Put_Line ("No Floating-Point support");
24469       end if;  --  check for FPU
24470
24471       --  Program done
24472       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24473       return;
24474
24475    end if;  --  check CPUID level
24476
24477    ---------------------------------------------------------------------
24478    --  With a CPUID level of 1 we can use the processor signature to  --
24479    --  determine it's exact type.                                     --
24480    ---------------------------------------------------------------------
24481
24482    Signature := Intel_CPU.Signature;
24483
24484    ----------------------------------------------------------------------
24485    --  Ok, now we go into a lot of messy comparisons to get the        --
24486    --  processor type. For clarity, no attememt to try to optimize the --
24487    --  comparisons has been made. Note that since Intel_CPU does not   --
24488    --  support getting cache info, we cannot distinguish between P5    --
24489    --  and Celeron types yet.                                          --
24490    ----------------------------------------------------------------------
24491
24492    --  x486SL
24493    if Signature.Processor_Type = 2#00#   and
24494      Signature.Family          = 2#0100# and
24495      Signature.Model           = 2#0100# then
24496       Type_Found := True;
24497       Ada.Text_IO.Put_Line ("x486SL processor");
24498    end if;
24499
24500    --  x486DX2 Write-Back
24501    if Signature.Processor_Type = 2#00#   and
24502      Signature.Family          = 2#0100# and
24503      Signature.Model           = 2#0111# then
24504       Type_Found := True;
24505       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24506    end if;
24507
24508    --  x486DX4
24509    if Signature.Processor_Type = 2#00#   and
24510      Signature.Family          = 2#0100# and
24511      Signature.Model           = 2#1000# then
24512       Type_Found := True;
24513       Ada.Text_IO.Put_Line ("x486DX4 processor");
24514    end if;
24515
24516    --  x486DX4 Overdrive
24517    if Signature.Processor_Type = 2#01#   and
24518      Signature.Family          = 2#0100# and
24519      Signature.Model           = 2#1000# then
24520       Type_Found := True;
24521       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24522    end if;
24523
24524    --  Pentium (60, 66)
24525    if Signature.Processor_Type = 2#00#   and
24526      Signature.Family          = 2#0101# and
24527      Signature.Model           = 2#0001# then
24528       Type_Found := True;
24529       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24530    end if;
24531
24532    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24533    if Signature.Processor_Type = 2#00#   and
24534      Signature.Family          = 2#0101# and
24535      Signature.Model           = 2#0010# then
24536       Type_Found := True;
24537       Ada.Text_IO.Put_Line
24538         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24539    end if;
24540
24541    --  Pentium OverDrive (60, 66)
24542    if Signature.Processor_Type = 2#01#   and
24543      Signature.Family          = 2#0101# and
24544      Signature.Model           = 2#0001# then
24545       Type_Found := True;
24546       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24547    end if;
24548
24549    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24550    if Signature.Processor_Type = 2#01#   and
24551      Signature.Family          = 2#0101# and
24552      Signature.Model           = 2#0010# then
24553       Type_Found := True;
24554       Ada.Text_IO.Put_Line
24555         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24556    end if;
24557
24558    --  Pentium OverDrive processor for x486 processor-based systems
24559    if Signature.Processor_Type = 2#01#   and
24560      Signature.Family          = 2#0101# and
24561      Signature.Model           = 2#0011# then
24562       Type_Found := True;
24563       Ada.Text_IO.Put_Line
24564         ("Pentium OverDrive processor for x486 processor-based systems");
24565    end if;
24566
24567    --  Pentium processor with MMX technology (166, 200)
24568    if Signature.Processor_Type = 2#00#   and
24569      Signature.Family          = 2#0101# and
24570      Signature.Model           = 2#0100# then
24571       Type_Found := True;
24572       Ada.Text_IO.Put_Line
24573         ("Pentium processor with MMX technology (166, 200)");
24574    end if;
24575
24576    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24577    if Signature.Processor_Type = 2#01#   and
24578      Signature.Family          = 2#0101# and
24579      Signature.Model           = 2#0100# then
24580       Type_Found := True;
24581       Ada.Text_IO.Put_Line
24582         ("Pentium OverDrive processor with MMX " &
24583          "technology for Pentium processor (75, 90, 100, 120, 133)");
24584    end if;
24585
24586    --  Pentium Pro processor
24587    if Signature.Processor_Type = 2#00#   and
24588      Signature.Family          = 2#0110# and
24589      Signature.Model           = 2#0001# then
24590       Type_Found := True;
24591       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24592    end if;
24593
24594    --  Pentium II processor, model 3
24595    if Signature.Processor_Type = 2#00#   and
24596      Signature.Family          = 2#0110# and
24597      Signature.Model           = 2#0011# then
24598       Type_Found := True;
24599       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24600    end if;
24601
24602    --  Pentium II processor, model 5 or Celeron processor
24603    if Signature.Processor_Type = 2#00#   and
24604      Signature.Family          = 2#0110# and
24605      Signature.Model           = 2#0101# then
24606       Type_Found := True;
24607       Ada.Text_IO.Put_Line
24608         ("Pentium II processor, model 5 or Celeron processor");
24609    end if;
24610
24611    --  Pentium Pro OverDrive processor
24612    if Signature.Processor_Type = 2#01#   and
24613      Signature.Family          = 2#0110# and
24614      Signature.Model           = 2#0011# then
24615       Type_Found := True;
24616       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24617    end if;
24618
24619    --  If no type recognized, we have an unknown. Display what
24620    --  we _do_ know
24621    if Type_Found = False then
24622       Ada.Text_IO.Put_Line ("Unknown processor");
24623    end if;
24624
24625    -----------------------------------------
24626    --  Display processor stepping level.  --
24627    -----------------------------------------
24628
24629    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24630
24631    ---------------------------------
24632    --  Display vendor ID string.  --
24633    ---------------------------------
24634
24635    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24636
24637    ------------------------------------
24638    --  Get the processors features.  --
24639    ------------------------------------
24640
24641    Features := Intel_CPU.Features;
24642
24643    -----------------------------
24644    --  Check for a FPU unit.  --
24645    -----------------------------
24646
24647    if Features.FPU = True then
24648       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24649    else
24650       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24651    end if;  --  check for FPU
24652
24653    --------------------------------
24654    --  List processor features.  --
24655    --------------------------------
24656
24657    Ada.Text_IO.Put_Line ("Supported features: ");
24658
24659    --  Virtual Mode Extension
24660    if Features.VME = True then
24661       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24662    end if;
24663
24664    --  Debugging Extension
24665    if Features.DE = True then
24666       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24667    end if;
24668
24669    --  Page Size Extension
24670    if Features.PSE = True then
24671       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24672    end if;
24673
24674    --  Time Stamp Counter
24675    if Features.TSC = True then
24676       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
24677    end if;
24678
24679    --  Model Specific Registers
24680    if Features.MSR = True then
24681       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
24682    end if;
24683
24684    --  Physical Address Extension
24685    if Features.PAE = True then
24686       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
24687    end if;
24688
24689    --  Machine Check Extension
24690    if Features.MCE = True then
24691       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
24692    end if;
24693
24694    --  CMPXCHG8 instruction supported
24695    if Features.CX8 = True then
24696       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
24697    end if;
24698
24699    --  on-chip APIC hardware support
24700    if Features.APIC = True then
24701       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
24702    end if;
24703
24704    --  Fast System Call
24705    if Features.SEP = True then
24706       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
24707    end if;
24708
24709    --  Memory Type Range Registers
24710    if Features.MTRR = True then
24711       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
24712    end if;
24713
24714    --  Page Global Enable
24715    if Features.PGE = True then
24716       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
24717    end if;
24718
24719    --  Machine Check Architecture
24720    if Features.MCA = True then
24721       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
24722    end if;
24723
24724    --  Conditional Move Instruction Supported
24725    if Features.CMOV = True then
24726       Ada.Text_IO.Put_Line
24727         ("    CMOV   - Conditional Move Instruction Supported");
24728    end if;
24729
24730    --  Page Attribute Table
24731    if Features.PAT = True then
24732       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
24733    end if;
24734
24735    --  36-bit Page Size Extension
24736    if Features.PSE_36 = True then
24737       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
24738    end if;
24739
24740    --  MMX technology supported
24741    if Features.MMX = True then
24742       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
24743    end if;
24744
24745    --  Fast FP Save and Restore
24746    if Features.FXSR = True then
24747       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
24748    end if;
24749
24750    ---------------------
24751    --  Program done.  --
24752    ---------------------
24753
24754    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24755
24756 exception
24757
24758    when others =>
24759       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
24760       raise;
24761
24762 end Check_CPU;
24763 @end smallexample
24764
24765 @c ---------------------------------------------------------------------------
24766 @node Intel_CPU Package Specification
24767 @subsection @code{Intel_CPU} Package Specification
24768 @cindex Intel_CPU package specification
24769
24770 @smallexample @c adanocomment
24771 -------------------------------------------------------------------------
24772 --                                                                     --
24773 --  file: intel_cpu.ads                                                --
24774 --                                                                     --
24775 --           *********************************************             --
24776 --           * WARNING: for 32-bit Intel processors only *             --
24777 --           *********************************************             --
24778 --                                                                     --
24779 --  This package contains a number of subprograms that are useful in   --
24780 --  determining the Intel x86 CPU (and the features it supports) on    --
24781 --  which the program is running.                                      --
24782 --                                                                     --
24783 --  The package is based upon the information given in the Intel       --
24784 --  Application Note AP-485: "Intel Processor Identification and the   --
24785 --  CPUID Instruction" as of April 1998. This application note can be  --
24786 --  found on www.intel.com.                                            --
24787 --                                                                     --
24788 --  It currently deals with 32-bit processors only, will not detect    --
24789 --  features added after april 1998, and does not guarantee proper     --
24790 --  results on Intel-compatible processors.                            --
24791 --                                                                     --
24792 --  Cache info and x386 fpu type detection are not supported.          --
24793 --                                                                     --
24794 --  This package does not use any privileged instructions, so should   --
24795 --  work on any OS running on a 32-bit Intel processor.                --
24796 --                                                                     --
24797 -------------------------------------------------------------------------
24798
24799 with Interfaces;             use Interfaces;
24800 --  for using unsigned types
24801
24802 with System.Machine_Code;    use System.Machine_Code;
24803 --  for using inline assembler code
24804
24805 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
24806 --  for inserting control characters
24807
24808 package Intel_CPU is
24809
24810    ----------------------
24811    --  Processor bits  --
24812    ----------------------
24813
24814    subtype Num_Bits is Natural range 0 .. 31;
24815    --  the number of processor bits (32)
24816
24817    --------------------------
24818    --  Processor register  --
24819    --------------------------
24820
24821    --  define a processor register type for easy access to
24822    --  the individual bits
24823
24824    type Processor_Register is array (Num_Bits) of Boolean;
24825    pragma Pack (Processor_Register);
24826    for Processor_Register'Size use 32;
24827
24828    -------------------------
24829    --  Unsigned register  --
24830    -------------------------
24831
24832    --  define a processor register type for easy access to
24833    --  the individual bytes
24834
24835    type Unsigned_Register is
24836       record
24837          L1 : Unsigned_8;
24838          H1 : Unsigned_8;
24839          L2 : Unsigned_8;
24840          H2 : Unsigned_8;
24841       end record;
24842
24843    for Unsigned_Register use
24844       record
24845          L1 at 0 range  0 ..  7;
24846          H1 at 0 range  8 .. 15;
24847          L2 at 0 range 16 .. 23;
24848          H2 at 0 range 24 .. 31;
24849       end record;
24850
24851    for Unsigned_Register'Size use 32;
24852
24853    ---------------------------------
24854    --  Intel processor vendor ID  --
24855    ---------------------------------
24856
24857    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
24858    --  indicates an Intel manufactured processor
24859
24860    ------------------------------------
24861    --  Processor signature register  --
24862    ------------------------------------
24863
24864    --  a register type to hold the processor signature
24865
24866    type Processor_Signature is
24867       record
24868          Stepping       : Natural range 0 .. 15;
24869          Model          : Natural range 0 .. 15;
24870          Family         : Natural range 0 .. 15;
24871          Processor_Type : Natural range 0 .. 3;
24872          Reserved       : Natural range 0 .. 262143;
24873       end record;
24874
24875    for Processor_Signature use
24876       record
24877          Stepping       at 0 range  0 ..  3;
24878          Model          at 0 range  4 ..  7;
24879          Family         at 0 range  8 .. 11;
24880          Processor_Type at 0 range 12 .. 13;
24881          Reserved       at 0 range 14 .. 31;
24882       end record;
24883
24884    for Processor_Signature'Size use 32;
24885
24886    -----------------------------------
24887    --  Processor features register  --
24888    -----------------------------------
24889
24890    --  a processor register to hold the processor feature flags
24891
24892    type Processor_Features is
24893       record
24894          FPU    : Boolean;                --  floating point unit on chip
24895          VME    : Boolean;                --  virtual mode extension
24896          DE     : Boolean;                --  debugging extension
24897          PSE    : Boolean;                --  page size extension
24898          TSC    : Boolean;                --  time stamp counter
24899          MSR    : Boolean;                --  model specific registers
24900          PAE    : Boolean;                --  physical address extension
24901          MCE    : Boolean;                --  machine check extension
24902          CX8    : Boolean;                --  cmpxchg8 instruction
24903          APIC   : Boolean;                --  on-chip apic hardware
24904          Res_1  : Boolean;                --  reserved for extensions
24905          SEP    : Boolean;                --  fast system call
24906          MTRR   : Boolean;                --  memory type range registers
24907          PGE    : Boolean;                --  page global enable
24908          MCA    : Boolean;                --  machine check architecture
24909          CMOV   : Boolean;                --  conditional move supported
24910          PAT    : Boolean;                --  page attribute table
24911          PSE_36 : Boolean;                --  36-bit page size extension
24912          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
24913          MMX    : Boolean;                --  MMX technology supported
24914          FXSR   : Boolean;                --  fast FP save and restore
24915          Res_3  : Natural range 0 .. 127; --  reserved for extensions
24916       end record;
24917
24918    for Processor_Features use
24919       record
24920          FPU    at 0 range  0 ..  0;
24921          VME    at 0 range  1 ..  1;
24922          DE     at 0 range  2 ..  2;
24923          PSE    at 0 range  3 ..  3;
24924          TSC    at 0 range  4 ..  4;
24925          MSR    at 0 range  5 ..  5;
24926          PAE    at 0 range  6 ..  6;
24927          MCE    at 0 range  7 ..  7;
24928          CX8    at 0 range  8 ..  8;
24929          APIC   at 0 range  9 ..  9;
24930          Res_1  at 0 range 10 .. 10;
24931          SEP    at 0 range 11 .. 11;
24932          MTRR   at 0 range 12 .. 12;
24933          PGE    at 0 range 13 .. 13;
24934          MCA    at 0 range 14 .. 14;
24935          CMOV   at 0 range 15 .. 15;
24936          PAT    at 0 range 16 .. 16;
24937          PSE_36 at 0 range 17 .. 17;
24938          Res_2  at 0 range 18 .. 22;
24939          MMX    at 0 range 23 .. 23;
24940          FXSR   at 0 range 24 .. 24;
24941          Res_3  at 0 range 25 .. 31;
24942       end record;
24943
24944    for Processor_Features'Size use 32;
24945
24946    -------------------
24947    --  Subprograms  --
24948    -------------------
24949
24950    function Has_FPU return Boolean;
24951    --  return True if a FPU is found
24952    --  use only if CPUID is not supported
24953
24954    function Has_CPUID return Boolean;
24955    --  return True if the processor supports the CPUID instruction
24956
24957    function CPUID_Level return Natural;
24958    --  return the CPUID support level (0, 1 or 2)
24959    --  can only be called if the CPUID instruction is supported
24960
24961    function Vendor_ID return String;
24962    --  return the processor vendor identification string
24963    --  can only be called if the CPUID instruction is supported
24964
24965    function Signature return Processor_Signature;
24966    --  return the processor signature
24967    --  can only be called if the CPUID instruction is supported
24968
24969    function Features return Processor_Features;
24970    --  return the processors features
24971    --  can only be called if the CPUID instruction is supported
24972
24973 private
24974
24975    ------------------------
24976    --  EFLAGS bit names  --
24977    ------------------------
24978
24979    ID_Flag : constant Num_Bits := 21;
24980    --  ID flag bit
24981
24982 end Intel_CPU;
24983 @end smallexample
24984
24985 @c ---------------------------------------------------------------------------
24986 @node Intel_CPU Package Body
24987 @subsection @code{Intel_CPU} Package Body
24988 @cindex Intel_CPU package body
24989
24990 @smallexample @c adanocomment
24991 package body Intel_CPU is
24992
24993    ---------------------------
24994    --  Detect FPU presence  --
24995    ---------------------------
24996
24997    --  There is a FPU present if we can set values to the FPU Status
24998    --  and Control Words.
24999
25000    function Has_FPU return Boolean is
25001
25002       Register : Unsigned_16;
25003       --  processor register to store a word
25004
25005    begin
25006
25007       --  check if we can change the status word
25008       Asm (
25009
25010            --  the assembler code
25011            "finit"              & LF & HT &    --  reset status word
25012            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25013            "fnstsw %0"          & LF & HT &    --  save status word
25014            "movw %%ax, %0",                    --  store status word
25015
25016            --  output stored in Register
25017            --  register must be a memory location
25018            Outputs => Unsigned_16'Asm_output ("=m", Register),
25019
25020            --  tell compiler that we used eax
25021            Clobber => "eax");
25022
25023       --  if the status word is zero, there is no FPU
25024       if Register = 0 then
25025          return False;   --  no status word
25026       end if;  --  check status word value
25027
25028       --  check if we can get the control word
25029       Asm (
25030
25031            --  the assembler code
25032            "fnstcw %0",   --  save the control word
25033
25034            --  output into Register
25035            --  register must be a memory location
25036            Outputs => Unsigned_16'Asm_output ("=m", Register));
25037
25038       --  check the relevant bits
25039       if (Register and 16#103F#) /= 16#003F# then
25040          return False;   --  no control word
25041       end if;  --  check control word value
25042
25043       --  FPU found
25044       return True;
25045
25046    end Has_FPU;
25047
25048    --------------------------------
25049    --  Detect CPUID instruction  --
25050    --------------------------------
25051
25052    --  The processor supports the CPUID instruction if it is possible
25053    --  to change the value of ID flag bit in the EFLAGS register.
25054
25055    function Has_CPUID return Boolean is
25056
25057       Original_Flags, Modified_Flags : Processor_Register;
25058       --  EFLAG contents before and after changing the ID flag
25059
25060    begin
25061
25062       --  try flipping the ID flag in the EFLAGS register
25063       Asm (
25064
25065            --  the assembler code
25066            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25067            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25068            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25069            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25070            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25071            "popfl"                & LF & HT &     --  load EFLAGS register
25072            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25073            "pop %1",                              --  save EFLAGS content
25074
25075            --  output values, may be anything
25076            --  Original_Flags is %0
25077            --  Modified_Flags is %1
25078            Outputs =>
25079               (Processor_Register'Asm_output ("=g", Original_Flags),
25080                Processor_Register'Asm_output ("=g", Modified_Flags)),
25081
25082            --  tell compiler eax is destroyed
25083            Clobber => "eax");
25084
25085       --  check if CPUID is supported
25086       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25087          return True;   --  ID flag was modified
25088       else
25089          return False;  --  ID flag unchanged
25090       end if;  --  check for CPUID
25091
25092    end Has_CPUID;
25093
25094    -------------------------------
25095    --  Get CPUID support level  --
25096    -------------------------------
25097
25098    function CPUID_Level return Natural is
25099
25100       Level : Unsigned_32;
25101       --  returned support level
25102
25103    begin
25104
25105       --  execute CPUID, storing the results in the Level register
25106       Asm (
25107
25108            --  the assembler code
25109            "cpuid",    --  execute CPUID
25110
25111            --  zero is stored in eax
25112            --  returning the support level in eax
25113            Inputs => Unsigned_32'Asm_input ("a", 0),
25114
25115            --  eax is stored in Level
25116            Outputs => Unsigned_32'Asm_output ("=a", Level),
25117
25118            --  tell compiler ebx, ecx and edx registers are destroyed
25119            Clobber => "ebx, ecx, edx");
25120
25121       --  return the support level
25122       return Natural (Level);
25123
25124    end CPUID_Level;
25125
25126    --------------------------------
25127    --  Get CPU Vendor ID String  --
25128    --------------------------------
25129
25130    --  The vendor ID string is returned in the ebx, ecx and edx register
25131    --  after executing the CPUID instruction with eax set to zero.
25132    --  In case of a true Intel processor the string returned is
25133    --  "GenuineIntel"
25134
25135    function Vendor_ID return String is
25136
25137       Ebx, Ecx, Edx : Unsigned_Register;
25138       --  registers containing the vendor ID string
25139
25140       Vendor_ID : String (1 .. 12);
25141       -- the vendor ID string
25142
25143    begin
25144
25145       --  execute CPUID, storing the results in the processor registers
25146       Asm (
25147
25148            --  the assembler code
25149            "cpuid",    --  execute CPUID
25150
25151            --  zero stored in eax
25152            --  vendor ID string returned in ebx, ecx and edx
25153            Inputs => Unsigned_32'Asm_input ("a", 0),
25154
25155            --  ebx is stored in Ebx
25156            --  ecx is stored in Ecx
25157            --  edx is stored in Edx
25158            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25159                        Unsigned_Register'Asm_output ("=c", Ecx),
25160                        Unsigned_Register'Asm_output ("=d", Edx)));
25161
25162       --  now build the vendor ID string
25163       Vendor_ID( 1) := Character'Val (Ebx.L1);
25164       Vendor_ID( 2) := Character'Val (Ebx.H1);
25165       Vendor_ID( 3) := Character'Val (Ebx.L2);
25166       Vendor_ID( 4) := Character'Val (Ebx.H2);
25167       Vendor_ID( 5) := Character'Val (Edx.L1);
25168       Vendor_ID( 6) := Character'Val (Edx.H1);
25169       Vendor_ID( 7) := Character'Val (Edx.L2);
25170       Vendor_ID( 8) := Character'Val (Edx.H2);
25171       Vendor_ID( 9) := Character'Val (Ecx.L1);
25172       Vendor_ID(10) := Character'Val (Ecx.H1);
25173       Vendor_ID(11) := Character'Val (Ecx.L2);
25174       Vendor_ID(12) := Character'Val (Ecx.H2);
25175
25176       --  return string
25177       return Vendor_ID;
25178
25179    end Vendor_ID;
25180
25181    -------------------------------
25182    --  Get processor signature  --
25183    -------------------------------
25184
25185    function Signature return Processor_Signature is
25186
25187       Result : Processor_Signature;
25188       --  processor signature returned
25189
25190    begin
25191
25192       --  execute CPUID, storing the results in the Result variable
25193       Asm (
25194
25195            --  the assembler code
25196            "cpuid",    --  execute CPUID
25197
25198            --  one is stored in eax
25199            --  processor signature returned in eax
25200            Inputs => Unsigned_32'Asm_input ("a", 1),
25201
25202            --  eax is stored in Result
25203            Outputs => Processor_Signature'Asm_output ("=a", Result),
25204
25205            --  tell compiler that ebx, ecx and edx are also destroyed
25206            Clobber => "ebx, ecx, edx");
25207
25208       --  return processor signature
25209       return Result;
25210
25211    end Signature;
25212
25213    ------------------------------
25214    --  Get processor features  --
25215    ------------------------------
25216
25217    function Features return Processor_Features is
25218
25219       Result : Processor_Features;
25220       --  processor features returned
25221
25222    begin
25223
25224       --  execute CPUID, storing the results in the Result variable
25225       Asm (
25226
25227            --  the assembler code
25228            "cpuid",    --  execute CPUID
25229
25230            --  one stored in eax
25231            --  processor features returned in edx
25232            Inputs => Unsigned_32'Asm_input ("a", 1),
25233
25234            --  edx is stored in Result
25235            Outputs => Processor_Features'Asm_output ("=d", Result),
25236
25237            --  tell compiler that ebx and ecx are also destroyed
25238            Clobber => "ebx, ecx");
25239
25240       --  return processor signature
25241       return Result;
25242
25243    end Features;
25244
25245 end Intel_CPU;
25246 @end smallexample
25247 @c END OF INLINE ASSEMBLER CHAPTER
25248 @c ===============================
25249
25250
25251
25252 @c ***********************************
25253 @c * Compatibility and Porting Guide *
25254 @c ***********************************
25255 @node Compatibility and Porting Guide
25256 @appendix Compatibility and Porting Guide
25257
25258 @noindent
25259 This chapter describes the compatibility issues that may arise between
25260 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25261 can expedite porting
25262 applications developed in other Ada environments.
25263
25264 @menu
25265 * Compatibility with Ada 83::
25266 * Implementation-dependent characteristics::
25267 * Compatibility with DEC Ada 83::
25268 * Compatibility with Other Ada 95 Systems::
25269 * Representation Clauses::
25270 @end menu
25271
25272 @node Compatibility with Ada 83
25273 @section Compatibility with Ada 83
25274 @cindex Compatibility (between Ada 83 and Ada 95)
25275
25276 @noindent
25277 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25278 particular, the design intention is that the difficulties associated
25279 with moving from Ada 83 to Ada 95 should be no greater than those
25280 that occur when moving from one Ada 83 system to another.
25281
25282 However, there are a number of points at which there are minor
25283 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25284 full details of these issues,
25285 and should be consulted for a complete treatment.
25286 In practice the
25287 following subsections treat the most likely issues to be encountered.
25288
25289 @menu
25290 * Legal Ada 83 programs that are illegal in Ada 95::
25291 * More deterministic semantics::
25292 * Changed semantics::
25293 * Other language compatibility issues::
25294 @end menu
25295
25296 @node Legal Ada 83 programs that are illegal in Ada 95
25297 @subsection Legal Ada 83 programs that are illegal in Ada 95
25298
25299 @table @asis
25300 @item Character literals
25301 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25302 @code{Wide_Character} as a new predefined character type, some uses of
25303 character literals that were legal in Ada 83 are illegal in Ada 95.
25304 For example:
25305 @smallexample @c ada
25306    for Char in 'A' .. 'Z' loop ... end loop;
25307 @end smallexample
25308 @noindent
25309 The problem is that @code{'A'} and @code{'Z'} could be from either
25310 @code{Character} or @code{Wide_Character}.  The simplest correction
25311 is to make the type explicit; e.g.:
25312 @smallexample @c ada
25313    for Char in Character range 'A' .. 'Z' loop ... end loop;
25314 @end smallexample
25315
25316 @item New reserved words
25317 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25318 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25319 Existing Ada 83 code using any of these identifiers must be edited to
25320 use some alternative name.
25321
25322 @item Freezing rules
25323 The rules in Ada 95 are slightly different with regard to the point at
25324 which entities are frozen, and representation pragmas and clauses are
25325 not permitted past the freeze point.  This shows up most typically in
25326 the form of an error message complaining that a representation item
25327 appears too late, and the appropriate corrective action is to move
25328 the item nearer to the declaration of the entity to which it refers.
25329
25330 A particular case is that representation pragmas
25331 @ifset vms
25332 (including the
25333 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25334 @end ifset
25335 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25336 declaration must be introduced to which the pragma can be applied.
25337
25338 @item Optional bodies for library packages
25339 In Ada 83, a package that did not require a package body was nevertheless
25340 allowed to have one.  This lead to certain surprises in compiling large
25341 systems (situations in which the body could be unexpectedly ignored by the
25342 binder).  In Ada 95, if a package does not require a body then it is not
25343 permitted to have a body.  To fix this problem, simply remove a redundant
25344 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25345 into the spec that makes the body required.  One approach is to add a private
25346 part to the package declaration (if necessary), and define a parameterless
25347 procedure called @code{Requires_Body}, which must then be given a dummy
25348 procedure body in the package body, which then becomes required.
25349 Another approach (assuming that this does not introduce elaboration
25350 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25351 since one effect of this pragma is to require the presence of a package body.
25352
25353 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25354 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25355 @code{Constraint_Error}.
25356 This means that it is illegal to have separate exception handlers for
25357 the two exceptions.  The fix is simply to remove the handler for the
25358 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25359 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25360
25361 @item Indefinite subtypes in generics
25362 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25363 as the actual for a generic formal private type, but then the instantiation
25364 would be illegal if there were any instances of declarations of variables
25365 of this type in the generic body.  In Ada 95, to avoid this clear violation
25366 of the methodological principle known as the ``contract model'',
25367 the generic declaration explicitly indicates whether
25368 or not such instantiations are permitted.  If a generic formal parameter
25369 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25370 type name, then it can be instantiated with indefinite types, but no
25371 stand-alone variables can be declared of this type.  Any attempt to declare
25372 such a variable will result in an illegality at the time the generic is
25373 declared.  If the @code{(<>)} notation is not used, then it is illegal
25374 to instantiate the generic with an indefinite type.
25375 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25376 It will show up as a compile time error, and
25377 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25378 @end table
25379
25380 @node More deterministic semantics
25381 @subsection More deterministic semantics
25382
25383 @table @asis
25384 @item Conversions
25385 Conversions from real types to integer types round away from 0.  In Ada 83
25386 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25387 implementation freedom was intended to support unbiased rounding in
25388 statistical applications, but in practice it interfered with portability.
25389 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25390 is required.  Numeric code may be affected by this change in semantics.
25391 Note, though, that this issue is no worse than already existed in Ada 83
25392 when porting code from one vendor to another.
25393
25394 @item Tasking
25395 The Real-Time Annex introduces a set of policies that define the behavior of
25396 features that were implementation dependent in Ada 83, such as the order in
25397 which open select branches are executed.
25398 @end table
25399
25400 @node Changed semantics
25401 @subsection Changed semantics
25402
25403 @noindent
25404 The worst kind of incompatibility is one where a program that is legal in
25405 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25406 possible in Ada 83.  Fortunately this is extremely rare, but the one
25407 situation that you should be alert to is the change in the predefined type
25408 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25409
25410 @table @asis
25411 @item range of @code{Character}
25412 The range of @code{Standard.Character} is now the full 256 characters
25413 of Latin-1, whereas in most Ada 83 implementations it was restricted
25414 to 128 characters. Although some of the effects of
25415 this change will be manifest in compile-time rejection of legal
25416 Ada 83 programs it is possible for a working Ada 83 program to have
25417 a different effect in Ada 95, one that was not permitted in Ada 83.
25418 As an example, the expression
25419 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25420 delivers @code{255} as its value.
25421 In general, you should look at the logic of any
25422 character-processing Ada 83 program and see whether it needs to be adapted
25423 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25424 character handling package that may be relevant if code needs to be adapted
25425 to account for the additional Latin-1 elements.
25426 The desirable fix is to
25427 modify the program to accommodate the full character set, but in some cases
25428 it may be convenient to define a subtype or derived type of Character that
25429 covers only the restricted range.
25430 @cindex Latin-1
25431 @end table
25432
25433 @node Other language compatibility issues
25434 @subsection Other language compatibility issues
25435 @table @asis
25436 @item @option{-gnat83 switch}
25437 All implementations of GNAT provide a switch that causes GNAT to operate
25438 in Ada 83 mode.  In this mode, some but not all compatibility problems
25439 of the type described above are handled automatically.  For example, the
25440 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25441 However,
25442 in practice, it is usually advisable to make the necessary modifications
25443 to the program to remove the need for using this switch.
25444 See @ref{Compiling Ada 83 Programs}.
25445
25446 @item Support for removed Ada 83 pragmas and attributes
25447 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25448 generally because they have been replaced by other mechanisms.  Ada 95
25449 compilers are allowed, but not required, to implement these missing
25450 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25451 such pragmas and attributes, eliminating this compatibility concern.  These
25452 include @code{pragma Interface} and the floating point type attributes
25453 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25454 @end table
25455
25456
25457 @node Implementation-dependent characteristics
25458 @section Implementation-dependent characteristics
25459 @noindent
25460 Although the Ada language defines the semantics of each construct as
25461 precisely as practical, in some situations (for example for reasons of
25462 efficiency, or where the effect is heavily dependent on the host or target
25463 platform) the implementation is allowed some freedom.  In porting Ada 83
25464 code to GNAT, you need to be aware of whether / how the existing code
25465 exercised such implementation dependencies.  Such characteristics fall into
25466 several categories, and GNAT offers specific support in assisting the
25467 transition from certain Ada 83 compilers.
25468
25469 @menu
25470 * Implementation-defined pragmas::
25471 * Implementation-defined attributes::
25472 * Libraries::
25473 * Elaboration order::
25474 * Target-specific aspects::
25475 @end menu
25476
25477
25478 @node Implementation-defined pragmas
25479 @subsection Implementation-defined pragmas
25480
25481 @noindent
25482 Ada compilers are allowed to supplement the language-defined pragmas, and
25483 these are a potential source of non-portability.  All GNAT-defined pragmas
25484 are described in the GNAT Reference Manual, and these include several that
25485 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25486 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25487 For
25488 compatibility with DEC Ada 83, GNAT supplies the pragmas
25489 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25490 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25491 and @code{Volatile}.
25492 Other relevant pragmas include @code{External} and @code{Link_With}.
25493 Some vendor-specific
25494 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25495 recognized, thus
25496 avoiding compiler rejection of units that contain such pragmas; they are not
25497 relevant in a GNAT context and hence are not otherwise implemented.
25498
25499 @node Implementation-defined attributes
25500 @subsection Implementation-defined attributes
25501
25502 Analogous to pragmas, the set of attributes may be extended by an
25503 implementation.  All GNAT-defined attributes are described in the
25504 @cite{GNAT Reference Manual}, and these include several that are specifically
25505 intended
25506 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25507 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25508 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25509 @code{Type_Class}.
25510
25511 @node Libraries
25512 @subsection Libraries
25513 @noindent
25514 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25515 code uses vendor-specific libraries then there are several ways to manage
25516 this in Ada 95:
25517 @enumerate
25518 @item
25519 If the source code for the libraries (specifications and bodies) are
25520 available, then the libraries can be migrated in the same way as the
25521 application.
25522 @item
25523 If the source code for the specifications but not the bodies are
25524 available, then you can reimplement the bodies.
25525 @item
25526 Some new Ada 95 features obviate the need for library support.  For
25527 example most Ada 83 vendors supplied a package for unsigned integers.  The
25528 Ada 95 modular type feature is the preferred way to handle this need, so
25529 instead of migrating or reimplementing the unsigned integer package it may
25530 be preferable to retrofit the application using modular types.
25531 @end enumerate
25532
25533 @node Elaboration order
25534 @subsection Elaboration order
25535 @noindent
25536 The implementation can choose any elaboration order consistent with the unit
25537 dependency relationship.  This freedom means that some orders can result in
25538 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25539 to invoke a subprogram its body has been elaborated, or to instantiate a
25540 generic before the generic body has been elaborated.  By default GNAT
25541 attempts to choose a safe order (one that will not encounter access before
25542 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25543 needed.  However, this can lead to the creation of elaboration circularities
25544 and a resulting rejection of the program by gnatbind.  This issue is
25545 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25546 In brief, there are several
25547 ways to deal with this situation:
25548
25549 @itemize @bullet
25550 @item
25551 Modify the program to eliminate the circularities, e.g. by moving
25552 elaboration-time code into explicitly-invoked procedures
25553 @item
25554 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25555 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25556 @code{Elaborate_All}
25557 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25558 (by selectively suppressing elaboration checks via pragma
25559 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25560 @end itemize
25561
25562 @node Target-specific aspects
25563 @subsection Target-specific aspects
25564 @noindent
25565 Low-level applications need to deal with machine addresses, data
25566 representations, interfacing with assembler code, and similar issues.  If
25567 such an Ada 83 application is being ported to different target hardware (for
25568 example where the byte endianness has changed) then you will need to
25569 carefully examine the program logic; the porting effort will heavily depend
25570 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25571 incompatible with typical Ada 83 compiler practices regarding implicit
25572 packing, the meaning of the Size attribute, and the size of access values.
25573 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25574
25575
25576 @node Compatibility with Other Ada 95 Systems
25577 @section Compatibility with Other Ada 95 Systems
25578
25579 @noindent
25580 Providing that programs avoid the use of implementation dependent and
25581 implementation defined features of Ada 95, as documented in the Ada 95
25582 reference manual, there should be a high degree of portability between
25583 GNAT and other Ada 95 systems.  The following are specific items which
25584 have proved troublesome in moving GNAT programs to other Ada 95
25585 compilers, but do not affect porting code to GNAT@.
25586
25587 @table @asis
25588 @item Ada 83 Pragmas and Attributes
25589 Ada 95 compilers are allowed, but not required, to implement the missing
25590 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25591 GNAT implements all such pragmas and attributes, eliminating this as
25592 a compatibility concern, but some other Ada 95 compilers reject these
25593 pragmas and attributes.
25594
25595 @item Special-needs Annexes
25596 GNAT implements the full set of special needs annexes.  At the
25597 current time, it is the only Ada 95 compiler to do so.  This means that
25598 programs making use of these features may not be portable to other Ada
25599 95 compilation systems.
25600
25601 @item Representation Clauses
25602 Some other Ada 95 compilers implement only the minimal set of
25603 representation clauses required by the Ada 95 reference manual.  GNAT goes
25604 far beyond this minimal set, as described in the next section.
25605 @end table
25606
25607 @node Representation Clauses
25608 @section Representation Clauses
25609
25610 @noindent
25611 The Ada 83 reference manual was quite vague in describing both the minimal
25612 required implementation of representation clauses, and also their precise
25613 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25614 set of capabilities required in Ada 95 is quite limited.
25615
25616 GNAT implements the full required set of capabilities described in the
25617 Ada 95 reference manual, but also goes much beyond this, and in particular
25618 an effort has been made to be compatible with existing Ada 83 usage to the
25619 greatest extent possible.
25620
25621 A few cases exist in which Ada 83 compiler behavior is incompatible with
25622 requirements in the Ada 95 reference manual.  These are instances of
25623 intentional or accidental dependence on specific implementation dependent
25624 characteristics of these Ada 83 compilers.  The following is a list of
25625 the cases most likely to arise in existing legacy Ada 83 code.
25626
25627 @table @asis
25628 @item Implicit Packing
25629 Some Ada 83 compilers allowed a Size specification to cause implicit
25630 packing of an array or record.  This could cause expensive implicit
25631 conversions for change of representation in the presence of derived
25632 types, and the Ada design intends to avoid this possibility.
25633 Subsequent AI's were issued to make it clear that such implicit
25634 change of representation in response to a Size clause is inadvisable,
25635 and this recommendation is represented explicitly in the Ada 95 RM
25636 as implementation advice that is followed by GNAT@.
25637 The problem will show up as an error
25638 message rejecting the size clause.  The fix is simply to provide
25639 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25640 a Component_Size clause.
25641
25642 @item Meaning of Size Attribute
25643 The Size attribute in Ada 95 for discrete types is defined as being the
25644 minimal number of bits required to hold values of the type.  For example,
25645 on a 32-bit machine, the size of Natural will typically be 31 and not
25646 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25647 some 32 in this situation.  This problem will usually show up as a compile
25648 time error, but not always.  It is a good idea to check all uses of the
25649 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25650 Object_Size can provide a useful way of duplicating the behavior of
25651 some Ada 83 compiler systems.
25652
25653 @item Size of Access Types
25654 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25655 and that therefore it will be the same size as a System.Address value.  This
25656 assumption is true for GNAT in most cases with one exception.  For the case of
25657 a pointer to an unconstrained array type (where the bounds may vary from one
25658 value of the access type to another), the default is to use a ``fat pointer'',
25659 which is represented as two separate pointers, one to the bounds, and one to
25660 the array.  This representation has a number of advantages, including improved
25661 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25662 code which makes the assumption that, for example, pointers fit in 32 bits on
25663 a machine with 32-bit addressing.
25664
25665 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25666 access types in this case (where the designated type is an unconstrained array
25667 type).  These thin pointers are indeed the same size as a System.Address value.
25668 To specify a thin pointer, use a size clause for the type, for example:
25669
25670 @smallexample @c ada
25671 type X is access all String;
25672 for X'Size use Standard'Address_Size;
25673 @end smallexample
25674
25675 @noindent
25676 which will cause the type X to be represented using a single pointer.
25677 When using this representation, the bounds are right behind the array.
25678 This representation is slightly less efficient, and does not allow quite
25679 such flexibility in the use of foreign pointers or in using the
25680 Unrestricted_Access attribute to create pointers to non-aliased objects.
25681 But for any standard portable use of the access type it will work in
25682 a functionally correct manner and allow porting of existing code.
25683 Note that another way of forcing a thin pointer representation
25684 is to use a component size clause for the element size in an array,
25685 or a record representation clause for an access field in a record.
25686 @end table
25687
25688 @node Compatibility with DEC Ada 83
25689 @section Compatibility with DEC Ada 83
25690
25691 @noindent
25692 The VMS version of GNAT fully implements all the pragmas and attributes
25693 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25694 libraries, including Starlet.  In addition, data layouts and parameter
25695 passing conventions are highly compatible.  This means that porting
25696 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25697 most other porting efforts.  The following are some of the most
25698 significant differences between GNAT and DEC Ada 83.
25699
25700 @table @asis
25701 @item Default floating-point representation
25702 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25703 it is VMS format.  GNAT does implement the necessary pragmas
25704 (Long_Float, Float_Representation) for changing this default.
25705
25706 @item System
25707 The package System in GNAT exactly corresponds to the definition in the
25708 Ada 95 reference manual, which means that it excludes many of the
25709 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25710 that contains the additional definitions, and a special pragma,
25711 Extend_System allows this package to be treated transparently as an
25712 extension of package System.
25713
25714 @item To_Address
25715 The definitions provided by Aux_DEC are exactly compatible with those
25716 in the DEC Ada 83 version of System, with one exception.
25717 DEC Ada provides the following declarations:
25718
25719 @smallexample @c ada
25720 TO_ADDRESS (INTEGER)
25721 TO_ADDRESS (UNSIGNED_LONGWORD)
25722 TO_ADDRESS (universal_integer)
25723 @end smallexample
25724
25725 @noindent
25726 The version of TO_ADDRESS taking a universal integer argument is in fact
25727 an extension to Ada 83 not strictly compatible with the reference manual.
25728 In GNAT, we are constrained to be exactly compatible with the standard,
25729 and this means we cannot provide this capability.  In DEC Ada 83, the
25730 point of this definition is to deal with a call like:
25731
25732 @smallexample @c ada
25733 TO_ADDRESS (16#12777#);
25734 @end smallexample
25735
25736 @noindent
25737 Normally, according to the Ada 83 standard, one would expect this to be
25738 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25739 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25740 definition using universal_integer takes precedence.
25741
25742 In GNAT, since the version with universal_integer cannot be supplied, it is
25743 not possible to be 100% compatible.  Since there are many programs using
25744 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25745 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25746 declarations provided in the GNAT version of AUX_Dec are:
25747
25748 @smallexample @c ada
25749 function To_Address (X : Integer) return Address;
25750 pragma Pure_Function (To_Address);
25751
25752 function To_Address_Long (X : Unsigned_Longword)
25753  return Address;
25754 pragma Pure_Function (To_Address_Long);
25755 @end smallexample
25756
25757 @noindent
25758 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25759 change the name to TO_ADDRESS_LONG@.
25760
25761 @item Task_Id values
25762 The Task_Id values assigned will be different in the two systems, and GNAT
25763 does not provide a specified value for the Task_Id of the environment task,
25764 which in GNAT is treated like any other declared task.
25765 @end table
25766
25767 For full details on these and other less significant compatibility issues,
25768 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25769 Overview and Comparison on DIGITAL Platforms}.
25770
25771 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25772 attributes are recognized, although only a subset of them can sensibly
25773 be implemented.  The description of pragmas in this reference manual
25774 indicates whether or not they are applicable to non-VMS systems.
25775
25776
25777
25778 @ifset unw
25779 @node Microsoft Windows Topics
25780 @appendix Microsoft Windows Topics
25781 @cindex Windows NT
25782 @cindex Windows 95
25783 @cindex Windows 98
25784
25785 @noindent
25786 This chapter describes topics that are specific to the Microsoft Windows
25787 platforms (NT, 2000, and XP Professional).
25788
25789 @menu
25790 * Using GNAT on Windows::
25791 * Using a network installation of GNAT::
25792 * CONSOLE and WINDOWS subsystems::
25793 * Temporary Files::
25794 * Mixed-Language Programming on Windows::
25795 * Windows Calling Conventions::
25796 * Introduction to Dynamic Link Libraries (DLLs)::
25797 * Using DLLs with GNAT::
25798 * Building DLLs with GNAT::
25799 * GNAT and Windows Resources::
25800 * Debugging a DLL::
25801 * GNAT and COM/DCOM Objects::
25802 @end menu
25803
25804 @node Using GNAT on Windows
25805 @section Using GNAT on Windows
25806
25807 @noindent
25808 One of the strengths of the GNAT technology is that its tool set
25809 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
25810 @code{gdb} debugger, etc.) is used in the same way regardless of the
25811 platform.
25812
25813 On Windows this tool set is complemented by a number of Microsoft-specific
25814 tools that have been provided to facilitate interoperability with Windows
25815 when this is required. With these tools:
25816
25817 @itemize @bullet
25818
25819 @item
25820 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
25821 subsystems.
25822
25823 @item
25824 You can use any Dynamically Linked Library (DLL) in your Ada code (both
25825 relocatable and non-relocatable DLLs are supported).
25826
25827 @item
25828 You can build Ada DLLs for use in other applications. These applications
25829 can be written in a language other than Ada (e.g., C, C++, etc). Again both
25830 relocatable and non-relocatable Ada DLLs are supported.
25831
25832 @item
25833 You can include Windows resources in your Ada application.
25834
25835 @item
25836 You can use or create COM/DCOM objects.
25837 @end itemize
25838
25839 @noindent
25840 Immediately below are listed all known general GNAT-for-Windows restrictions.
25841 Other restrictions about specific features like Windows Resources and DLLs
25842 are listed in separate sections below.
25843
25844 @itemize @bullet
25845
25846 @item
25847 It is not possible to use @code{GetLastError} and @code{SetLastError}
25848 when tasking, protected records, or exceptions are used. In these
25849 cases, in order to implement Ada semantics, the GNAT run-time system
25850 calls certain Win32 routines that set the last error variable to 0 upon
25851 success. It should be possible to use @code{GetLastError} and
25852 @code{SetLastError} when tasking, protected record, and exception
25853 features are not used, but it is not guaranteed to work.
25854
25855 @item
25856 It is not possible to link against Microsoft libraries except for
25857 import libraries. The library must be built to be compatible with
25858 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
25859 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
25860 not be compatible with the GNAT runtime. Even if the library is
25861 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
25862
25863 @item
25864 When the compilation environment is located on FAT32 drives, users may
25865 experience recompilations of the source files that have not changed if
25866 Daylight Saving Time (DST) state has changed since the last time files
25867 were compiled. NTFS drives do not have this problem.
25868
25869 @item
25870 No components of the GNAT toolset use any entries in the Windows
25871 registry. The only entries that can be created are file associations and
25872 PATH settings, provided the user has chosen to create them at installation
25873 time, as well as some minimal book-keeping information needed to correctly
25874 uninstall or integrate different GNAT products.
25875 @end itemize
25876
25877 @node Using a network installation of GNAT
25878 @section Using a network installation of GNAT
25879
25880 @noindent
25881 Make sure the system on which GNAT is installed is accessible from the
25882 current machine, i.e. the install location is shared over the network.
25883 Shared resources are accessed on Windows by means of UNC paths, which
25884 have the format @code{\\server\sharename\path}
25885
25886 In order to use such a network installation, simply add the UNC path of the
25887 @file{bin} directory of your GNAT installation in front of your PATH. For
25888 example, if GNAT is installed in @file{\GNAT} directory of a share location
25889 called @file{c-drive} on a machine @file{LOKI}, the following command will
25890 make it available:
25891
25892 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
25893
25894 Be aware that every compilation using the network installation results in the
25895 transfer of large amounts of data across the network and will likely cause
25896 serious performance penalty.
25897
25898 @node CONSOLE and WINDOWS subsystems
25899 @section CONSOLE and WINDOWS subsystems
25900 @cindex CONSOLE Subsystem
25901 @cindex WINDOWS Subsystem
25902 @cindex -mwindows
25903
25904 @noindent
25905 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
25906 (which is the default subsystem) will always create a console when
25907 launching the application. This is not something desirable when the
25908 application has a Windows GUI. To get rid of this console the
25909 application must be using the @code{WINDOWS} subsystem. To do so
25910 the @option{-mwindows} linker option must be specified.
25911
25912 @smallexample
25913 $ gnatmake winprog -largs -mwindows
25914 @end smallexample
25915
25916 @node Temporary Files
25917 @section Temporary Files
25918 @cindex Temporary files
25919
25920 @noindent
25921 It is possible to control where temporary files gets created by setting
25922 the TMP environment variable. The file will be created:
25923
25924 @itemize
25925 @item Under the directory pointed to by the TMP environment variable if
25926 this directory exists.
25927
25928 @item Under c:\temp, if the TMP environment variable is not set (or not
25929 pointing to a directory) and if this directory exists.
25930
25931 @item Under the current working directory otherwise.
25932 @end itemize
25933
25934 @noindent
25935 This allows you to determine exactly where the temporary
25936 file will be created. This is particularly useful in networked
25937 environments where you may not have write access to some
25938 directories.
25939
25940 @node Mixed-Language Programming on Windows
25941 @section Mixed-Language Programming on Windows
25942
25943 @noindent
25944 Developing pure Ada applications on Windows is no different than on
25945 other GNAT-supported platforms. However, when developing or porting an
25946 application that contains a mix of Ada and C/C++, the choice of your
25947 Windows C/C++ development environment conditions your overall
25948 interoperability strategy.
25949
25950 If you use @code{gcc} to compile the non-Ada part of your application,
25951 there are no Windows-specific restrictions that affect the overall
25952 interoperability with your Ada code. If you plan to use
25953 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
25954 the following limitations:
25955
25956 @itemize @bullet
25957 @item
25958 You cannot link your Ada code with an object or library generated with
25959 Microsoft tools if these use the @code{.tls} section (Thread Local
25960 Storage section) since the GNAT linker does not yet support this section.
25961
25962 @item
25963 You cannot link your Ada code with an object or library generated with
25964 Microsoft tools if these use I/O routines other than those provided in
25965 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
25966 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
25967 libraries can cause a conflict with @code{msvcrt.dll} services. For
25968 instance Visual C++ I/O stream routines conflict with those in
25969 @code{msvcrt.dll}.
25970 @end itemize
25971
25972 @noindent
25973 If you do want to use the Microsoft tools for your non-Ada code and hit one
25974 of the above limitations, you have two choices:
25975
25976 @enumerate
25977 @item
25978 Encapsulate your non Ada code in a DLL to be linked with your Ada
25979 application. In this case, use the Microsoft or whatever environment to
25980 build the DLL and use GNAT to build your executable
25981 (@pxref{Using DLLs with GNAT}).
25982
25983 @item
25984 Or you can encapsulate your Ada code in a DLL to be linked with the
25985 other part of your application. In this case, use GNAT to build the DLL
25986 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
25987 environment to build your executable.
25988 @end enumerate
25989
25990 @node Windows Calling Conventions
25991 @section Windows Calling Conventions
25992 @findex Stdcall
25993 @findex APIENTRY
25994
25995 @menu
25996 * C Calling Convention::
25997 * Stdcall Calling Convention::
25998 * DLL Calling Convention::
25999 @end menu
26000
26001 @noindent
26002 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26003 (callee), there are several ways to push @code{G}'s parameters on the
26004 stack and there are several possible scenarios to clean up the stack
26005 upon @code{G}'s return. A calling convention is an agreed upon software
26006 protocol whereby the responsibilities between the caller (@code{F}) and
26007 the callee (@code{G}) are clearly defined. Several calling conventions
26008 are available for Windows:
26009
26010 @itemize @bullet
26011 @item
26012 @code{C} (Microsoft defined)
26013
26014 @item
26015 @code{Stdcall} (Microsoft defined)
26016
26017 @item
26018 @code{DLL} (GNAT specific)
26019 @end itemize
26020
26021 @node C Calling Convention
26022 @subsection @code{C} Calling Convention
26023
26024 @noindent
26025 This is the default calling convention used when interfacing to C/C++
26026 routines compiled with either @code{gcc} or Microsoft Visual C++.
26027
26028 In the @code{C} calling convention subprogram parameters are pushed on the
26029 stack by the caller from right to left. The caller itself is in charge of
26030 cleaning up the stack after the call. In addition, the name of a routine
26031 with @code{C} calling convention is mangled by adding a leading underscore.
26032
26033 The name to use on the Ada side when importing (or exporting) a routine
26034 with @code{C} calling convention is the name of the routine. For
26035 instance the C function:
26036
26037 @smallexample
26038 int get_val (long);
26039 @end smallexample
26040
26041 @noindent
26042 should be imported from Ada as follows:
26043
26044 @smallexample @c ada
26045 @group
26046 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26047 pragma Import (C, Get_Val, External_Name => "get_val");
26048 @end group
26049 @end smallexample
26050
26051 @noindent
26052 Note that in this particular case the @code{External_Name} parameter could
26053 have been omitted since, when missing, this parameter is taken to be the
26054 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26055 is missing, as in the above example, this parameter is set to be the
26056 @code{External_Name} with a leading underscore.
26057
26058 When importing a variable defined in C, you should always use the @code{C}
26059 calling convention unless the object containing the variable is part of a
26060 DLL (in which case you should use the @code{DLL} calling convention,
26061 @pxref{DLL Calling Convention}).
26062
26063 @node Stdcall Calling Convention
26064 @subsection @code{Stdcall} Calling Convention
26065
26066 @noindent
26067 This convention, which was the calling convention used for Pascal
26068 programs, is used by Microsoft for all the routines in the Win32 API for
26069 efficiency reasons. It must be used to import any routine for which this
26070 convention was specified.
26071
26072 In the @code{Stdcall} calling convention subprogram parameters are pushed
26073 on the stack by the caller from right to left. The callee (and not the
26074 caller) is in charge of cleaning the stack on routine exit. In addition,
26075 the name of a routine with @code{Stdcall} calling convention is mangled by
26076 adding a leading underscore (as for the @code{C} calling convention) and a
26077 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26078 bytes) of the parameters passed to the routine.
26079
26080 The name to use on the Ada side when importing a C routine with a
26081 @code{Stdcall} calling convention is the name of the C routine. The leading
26082 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26083 the compiler. For instance the Win32 function:
26084
26085 @smallexample
26086 @b{APIENTRY} int get_val (long);
26087 @end smallexample
26088
26089 @noindent
26090 should be imported from Ada as follows:
26091
26092 @smallexample @c ada
26093 @group
26094 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26095 pragma Import (Stdcall, Get_Val);
26096 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26097 @end group
26098 @end smallexample
26099
26100 @noindent
26101 As for the @code{C} calling convention, when the @code{External_Name}
26102 parameter is missing, it is taken to be the name of the Ada entity in lower
26103 case. If instead of writing the above import pragma you write:
26104
26105 @smallexample @c ada
26106 @group
26107 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26108 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26109 @end group
26110 @end smallexample
26111
26112 @noindent
26113 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26114 of specifying the @code{External_Name} parameter you specify the
26115 @code{Link_Name} as in the following example:
26116
26117 @smallexample @c ada
26118 @group
26119 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26120 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26121 @end group
26122 @end smallexample
26123
26124 @noindent
26125 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26126 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26127 added at the end of the @code{Link_Name} by the compiler.
26128
26129 @noindent
26130 Note, that in some special cases a DLL's entry point name lacks a trailing
26131 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26132 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26133 to handle those cases (see the description of the switches in
26134 @pxref{Using gnatdll} section).
26135
26136 @node DLL Calling Convention
26137 @subsection @code{DLL} Calling Convention
26138
26139 @noindent
26140 This convention, which is GNAT-specific, must be used when you want to
26141 import in Ada a variables defined in a DLL. For functions and procedures
26142 this convention is equivalent to the @code{Stdcall} convention. As an
26143 example, if a DLL contains a variable defined as:
26144
26145 @smallexample
26146 int my_var;
26147 @end smallexample
26148
26149 @noindent
26150 then, to access this variable from Ada you should write:
26151
26152 @smallexample @c ada
26153 @group
26154 My_Var : Interfaces.C.int;
26155 pragma Import (DLL, My_Var);
26156 @end group
26157 @end smallexample
26158
26159 The remarks concerning the @code{External_Name} and @code{Link_Name}
26160 parameters given in the previous sections equally apply to the @code{DLL}
26161 calling convention.
26162
26163 @node Introduction to Dynamic Link Libraries (DLLs)
26164 @section Introduction to Dynamic Link Libraries (DLLs)
26165 @findex DLL
26166
26167 @noindent
26168 A Dynamically Linked Library (DLL) is a library that can be shared by
26169 several applications running under Windows. A DLL can contain any number of
26170 routines and variables.
26171
26172 One advantage of DLLs is that you can change and enhance them without
26173 forcing all the applications that depend on them to be relinked or
26174 recompiled. However, you should be aware than all calls to DLL routines are
26175 slower since, as you will understand below, such calls are indirect.
26176
26177 To illustrate the remainder of this section, suppose that an application
26178 wants to use the services of a DLL @file{API.dll}. To use the services
26179 provided by @file{API.dll} you must statically link against an import
26180 library which contains a jump table with an entry for each routine and
26181 variable exported by the DLL. In the Microsoft world this import library is
26182 called @file{API.lib}. When using GNAT this import library is called either
26183 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26184
26185 After you have statically linked your application with the import library
26186 and you run your application, here is what happens:
26187
26188 @enumerate
26189 @item
26190 Your application is loaded into memory.
26191
26192 @item
26193 The DLL @file{API.dll} is mapped into the address space of your
26194 application. This means that:
26195
26196 @itemize @bullet
26197 @item
26198 The DLL will use the stack of the calling thread.
26199
26200 @item
26201 The DLL will use the virtual address space of the calling process.
26202
26203 @item
26204 The DLL will allocate memory from the virtual address space of the calling
26205 process.
26206
26207 @item
26208 Handles (pointers) can be safely exchanged between routines in the DLL
26209 routines and routines in the application using the DLL.
26210 @end itemize
26211
26212 @item
26213 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
26214 part of your application are initialized with the addresses of the routines
26215 and variables in @file{API.dll}.
26216
26217 @item
26218 If present in @file{API.dll}, routines @code{DllMain} or
26219 @code{DllMainCRTStartup} are invoked. These routines typically contain
26220 the initialization code needed for the well-being of the routines and
26221 variables exported by the DLL.
26222 @end enumerate
26223
26224 @noindent
26225 There is an additional point which is worth mentioning. In the Windows
26226 world there are two kind of DLLs: relocatable and non-relocatable
26227 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26228 in the target application address space. If the addresses of two
26229 non-relocatable DLLs overlap and these happen to be used by the same
26230 application, a conflict will occur and the application will run
26231 incorrectly. Hence, when possible, it is always preferable to use and
26232 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26233 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26234 User's Guide) removes the debugging symbols from the DLL but the DLL can
26235 still be relocated.
26236
26237 As a side note, an interesting difference between Microsoft DLLs and
26238 Unix shared libraries, is the fact that on most Unix systems all public
26239 routines are exported by default in a Unix shared library, while under
26240 Windows the exported routines must be listed explicitly in a definition
26241 file (@pxref{The Definition File}).
26242
26243 @node Using DLLs with GNAT
26244 @section Using DLLs with GNAT
26245
26246 @menu
26247 * Creating an Ada Spec for the DLL Services::
26248 * Creating an Import Library::
26249 @end menu
26250
26251 @noindent
26252 To use the services of a DLL, say @file{API.dll}, in your Ada application
26253 you must have:
26254
26255 @enumerate
26256 @item
26257 The Ada spec for the routines and/or variables you want to access in
26258 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26259 header files provided with the DLL.
26260
26261 @item
26262 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26263 mentioned an import library is a statically linked library containing the
26264 import table which will be filled at load time to point to the actual
26265 @file{API.dll} routines. Sometimes you don't have an import library for the
26266 DLL you want to use. The following sections will explain how to build one.
26267
26268 @item
26269 The actual DLL, @file{API.dll}.
26270 @end enumerate
26271
26272 @noindent
26273 Once you have all the above, to compile an Ada application that uses the
26274 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26275 you simply issue the command
26276
26277 @smallexample
26278 $ gnatmake my_ada_app -largs -lAPI
26279 @end smallexample
26280
26281 @noindent
26282 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26283 tells the GNAT linker to look first for a library named @file{API.lib}
26284 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26285 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26286 contains the following pragma
26287
26288 @smallexample @c ada
26289 pragma Linker_Options ("-lAPI");
26290 @end smallexample
26291
26292 @noindent
26293 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26294 command.
26295
26296 If any one of the items above is missing you will have to create it
26297 yourself. The following sections explain how to do so using as an
26298 example a fictitious DLL called @file{API.dll}.
26299
26300 @node Creating an Ada Spec for the DLL Services
26301 @subsection Creating an Ada Spec for the DLL Services
26302
26303 @noindent
26304 A DLL typically comes with a C/C++ header file which provides the
26305 definitions of the routines and variables exported by the DLL. The Ada
26306 equivalent of this header file is a package spec that contains definitions
26307 for the imported entities. If the DLL you intend to use does not come with
26308 an Ada spec you have to generate one such spec yourself. For example if
26309 the header file of @file{API.dll} is a file @file{api.h} containing the
26310 following two definitions:
26311
26312 @smallexample
26313 @group
26314 @cartouche
26315 int some_var;
26316 int get (char *);
26317 @end cartouche
26318 @end group
26319 @end smallexample
26320
26321 @noindent
26322 then the equivalent Ada spec could be:
26323
26324 @smallexample @c ada
26325 @group
26326 @cartouche
26327 with Interfaces.C.Strings;
26328 package API is
26329    use Interfaces;
26330
26331    Some_Var : C.int;
26332    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26333
26334 private
26335    pragma Import (C, Get);
26336    pragma Import (DLL, Some_Var);
26337 end API;
26338 @end cartouche
26339 @end group
26340 @end smallexample
26341
26342 @noindent
26343 Note that a variable is @strong{always imported with a DLL convention}. A
26344 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26345 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26346 (@pxref{Windows Calling Conventions}).
26347
26348 @node Creating an Import Library
26349 @subsection Creating an Import Library
26350 @cindex Import library
26351
26352 @menu
26353 * The Definition File::
26354 * GNAT-Style Import Library::
26355 * Microsoft-Style Import Library::
26356 @end menu
26357
26358 @noindent
26359 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26360 import library @file{libAPI.a} is available with @file{API.dll} you
26361 can skip this section. Otherwise read on.
26362
26363 @node The Definition File
26364 @subsubsection The Definition File
26365 @cindex Definition file
26366 @findex .def
26367
26368 @noindent
26369 As previously mentioned, and unlike Unix systems, the list of symbols
26370 that are exported from a DLL must be provided explicitly in Windows.
26371 The main goal of a definition file is precisely that: list the symbols
26372 exported by a DLL. A definition file (usually a file with a @code{.def}
26373 suffix) has the following structure:
26374
26375 @smallexample
26376 @group
26377 @cartouche
26378 [LIBRARY @i{name}]
26379 [DESCRIPTION @i{string}]
26380 EXPORTS
26381    @i{symbol1}
26382    @i{symbol2}
26383    ...
26384 @end cartouche
26385 @end group
26386 @end smallexample
26387
26388 @table @code
26389 @item LIBRARY @i{name}
26390 This section, which is optional, gives the name of the DLL.
26391
26392 @item DESCRIPTION @i{string}
26393 This section, which is optional, gives a description string that will be
26394 embedded in the import library.
26395
26396 @item EXPORTS
26397 This section gives the list of exported symbols (procedures, functions or
26398 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26399 section of @file{API.def} looks like:
26400
26401 @smallexample
26402 @group
26403 @cartouche
26404 EXPORTS
26405    some_var
26406    get
26407 @end cartouche
26408 @end group
26409 @end smallexample
26410 @end table
26411
26412 @noindent
26413 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26414 (@pxref{Windows Calling Conventions}) for a Stdcall
26415 calling convention function in the exported symbols list.
26416
26417 @noindent
26418 There can actually be other sections in a definition file, but these
26419 sections are not relevant to the discussion at hand.
26420
26421 @node GNAT-Style Import Library
26422 @subsubsection GNAT-Style Import Library
26423
26424 @noindent
26425 To create a static import library from @file{API.dll} with the GNAT tools
26426 you should proceed as follows:
26427
26428 @enumerate
26429 @item
26430 Create the definition file @file{API.def} (@pxref{The Definition File}).
26431 For that use the @code{dll2def} tool as follows:
26432
26433 @smallexample
26434 $ dll2def API.dll > API.def
26435 @end smallexample
26436
26437 @noindent
26438 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26439 to standard output the list of entry points in the DLL. Note that if
26440 some routines in the DLL have the @code{Stdcall} convention
26441 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26442 suffix then you'll have to edit @file{api.def} to add it.
26443
26444 @noindent
26445 Here are some hints to find the right @code{@@}@i{nn} suffix.
26446
26447 @enumerate
26448 @item
26449 If you have the Microsoft import library (.lib), it is possible to get
26450 the right symbols by using Microsoft @code{dumpbin} tool (see the
26451 corresponding Microsoft documentation for further details).
26452
26453 @smallexample
26454 $ dumpbin /exports api.lib
26455 @end smallexample
26456
26457 @item
26458 If you have a message about a missing symbol at link time the compiler
26459 tells you what symbol is expected. You just have to go back to the
26460 definition file and add the right suffix.
26461 @end enumerate
26462
26463 @item
26464 Build the import library @code{libAPI.a}, using @code{gnatdll}
26465 (@pxref{Using gnatdll}) as follows:
26466
26467 @smallexample
26468 $ gnatdll -e API.def -d API.dll
26469 @end smallexample
26470
26471 @noindent
26472 @code{gnatdll} takes as input a definition file @file{API.def} and the
26473 name of the DLL containing the services listed in the definition file
26474 @file{API.dll}. The name of the static import library generated is
26475 computed from the name of the definition file as follows: if the
26476 definition file name is @i{xyz}@code{.def}, the import library name will
26477 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26478 @option{-e} could have been removed because the name of the definition
26479 file (before the ``@code{.def}'' suffix) is the same as the name of the
26480 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26481 @end enumerate
26482
26483 @node Microsoft-Style Import Library
26484 @subsubsection Microsoft-Style Import Library
26485
26486 @noindent
26487 With GNAT you can either use a GNAT-style or Microsoft-style import
26488 library. A Microsoft import library is needed only if you plan to make an
26489 Ada DLL available to applications developed with Microsoft
26490 tools (@pxref{Mixed-Language Programming on Windows}).
26491
26492 To create a Microsoft-style import library for @file{API.dll} you
26493 should proceed as follows:
26494
26495 @enumerate
26496 @item
26497 Create the definition file @file{API.def} from the DLL. For this use either
26498 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26499 tool (see the corresponding Microsoft documentation for further details).
26500
26501 @item
26502 Build the actual import library using Microsoft's @code{lib} utility:
26503
26504 @smallexample
26505 $ lib -machine:IX86 -def:API.def -out:API.lib
26506 @end smallexample
26507
26508 @noindent
26509 If you use the above command the definition file @file{API.def} must
26510 contain a line giving the name of the DLL:
26511
26512 @smallexample
26513 LIBRARY      "API"
26514 @end smallexample
26515
26516 @noindent
26517 See the Microsoft documentation for further details about the usage of
26518 @code{lib}.
26519 @end enumerate
26520
26521 @node Building DLLs with GNAT
26522 @section Building DLLs with GNAT
26523 @cindex DLLs, building
26524
26525 @menu
26526 * Limitations When Using Ada DLLs from Ada::
26527 * Exporting Ada Entities::
26528 * Ada DLLs and Elaboration::
26529 * Ada DLLs and Finalization::
26530 * Creating a Spec for Ada DLLs::
26531 * Creating the Definition File::
26532 * Using gnatdll::
26533 @end menu
26534
26535 @noindent
26536 This section explains how to build DLLs containing Ada code. These DLLs
26537 will be referred to as Ada DLLs in the remainder of this section.
26538
26539 The steps required to build an Ada DLL that is to be used by Ada as well as
26540 non-Ada applications are as follows:
26541
26542 @enumerate
26543 @item
26544 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26545 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26546 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26547 skip this step if you plan to use the Ada DLL only from Ada applications.
26548
26549 @item
26550 Your Ada code must export an initialization routine which calls the routine
26551 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26552 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26553 routine exported by the Ada DLL must be invoked by the clients of the DLL
26554 to initialize the DLL.
26555
26556 @item
26557 When useful, the DLL should also export a finalization routine which calls
26558 routine @code{adafinal} generated by @code{gnatbind} to perform the
26559 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26560 The finalization routine exported by the Ada DLL must be invoked by the
26561 clients of the DLL when the DLL services are no further needed.
26562
26563 @item
26564 You must provide a spec for the services exported by the Ada DLL in each
26565 of the programming languages to which you plan to make the DLL available.
26566
26567 @item
26568 You must provide a definition file listing the exported entities
26569 (@pxref{The Definition File}).
26570
26571 @item
26572 Finally you must use @code{gnatdll} to produce the DLL and the import
26573 library (@pxref{Using gnatdll}).
26574 @end enumerate
26575
26576 @noindent
26577 Note that a relocatable DLL stripped using the @code{strip} binutils
26578 tool will not be relocatable anymore. To build a DLL without debug
26579 information pass @code{-largs -s} to @code{gnatdll}.
26580
26581 @node Limitations When Using Ada DLLs from Ada
26582 @subsection Limitations When Using Ada DLLs from Ada
26583
26584 @noindent
26585 When using Ada DLLs from Ada applications there is a limitation users
26586 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26587 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26588 each Ada DLL includes the services of the GNAT run time that are necessary
26589 to the Ada code inside the DLL. As a result, when an Ada program uses an
26590 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26591 one in the main program.
26592
26593 It is therefore not possible to exchange GNAT run-time objects between the
26594 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26595 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26596 types, etc.
26597
26598 It is completely safe to exchange plain elementary, array or record types,
26599 Windows object handles, etc.
26600
26601 @node Exporting Ada Entities
26602 @subsection Exporting Ada Entities
26603 @cindex Export table
26604
26605 @noindent
26606 Building a DLL is a way to encapsulate a set of services usable from any
26607 application. As a result, the Ada entities exported by a DLL should be
26608 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26609 any Ada name mangling. Please note that the @code{Stdcall} convention
26610 should only be used for subprograms, not for variables. As an example here
26611 is an Ada package @code{API}, spec and body, exporting two procedures, a
26612 function, and a variable:
26613
26614 @smallexample @c ada
26615 @group
26616 @cartouche
26617 with Interfaces.C; use Interfaces;
26618 package API is
26619    Count : C.int := 0;
26620    function Factorial (Val : C.int) return C.int;
26621
26622    procedure Initialize_API;
26623    procedure Finalize_API;
26624    --  Initialization & Finalization routines. More in the next section.
26625 private
26626    pragma Export (C, Initialize_API);
26627    pragma Export (C, Finalize_API);
26628    pragma Export (C, Count);
26629    pragma Export (C, Factorial);
26630 end API;
26631 @end cartouche
26632 @end group
26633 @end smallexample
26634
26635 @smallexample @c ada
26636 @group
26637 @cartouche
26638 package body API is
26639    function Factorial (Val : C.int) return C.int is
26640       Fact : C.int := 1;
26641    begin
26642       Count := Count + 1;
26643       for K in 1 .. Val loop
26644          Fact := Fact * K;
26645       end loop;
26646       return Fact;
26647    end Factorial;
26648
26649    procedure Initialize_API is
26650       procedure Adainit;
26651       pragma Import (C, Adainit);
26652    begin
26653       Adainit;
26654    end Initialize_API;
26655
26656    procedure Finalize_API is
26657       procedure Adafinal;
26658       pragma Import (C, Adafinal);
26659    begin
26660       Adafinal;
26661    end Finalize_API;
26662 end API;
26663 @end cartouche
26664 @end group
26665 @end smallexample
26666
26667 @noindent
26668 If the Ada DLL you are building will only be used by Ada applications
26669 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26670 convention. As an example, the previous package could be written as
26671 follows:
26672
26673 @smallexample @c ada
26674 @group
26675 @cartouche
26676 package API is
26677    Count : Integer := 0;
26678    function Factorial (Val : Integer) return Integer;
26679
26680    procedure Initialize_API;
26681    procedure Finalize_API;
26682    --  Initialization and Finalization routines.
26683 end API;
26684 @end cartouche
26685 @end group
26686 @end smallexample
26687
26688 @smallexample @c ada
26689 @group
26690 @cartouche
26691 package body API is
26692    function Factorial (Val : Integer) return Integer is
26693       Fact : Integer := 1;
26694    begin
26695       Count := Count + 1;
26696       for K in 1 .. Val loop
26697          Fact := Fact * K;
26698       end loop;
26699       return Fact;
26700    end Factorial;
26701
26702    ...
26703    --  The remainder of this package body is unchanged.
26704 end API;
26705 @end cartouche
26706 @end group
26707 @end smallexample
26708
26709 @noindent
26710 Note that if you do not export the Ada entities with a @code{C} or
26711 @code{Stdcall} convention you will have to provide the mangled Ada names
26712 in the definition file of the Ada DLL
26713 (@pxref{Creating the Definition File}).
26714
26715 @node Ada DLLs and Elaboration
26716 @subsection Ada DLLs and Elaboration
26717 @cindex DLLs and elaboration
26718
26719 @noindent
26720 The DLL that you are building contains your Ada code as well as all the
26721 routines in the Ada library that are needed by it. The first thing a
26722 user of your DLL must do is elaborate the Ada code
26723 (@pxref{Elaboration Order Handling in GNAT}).
26724
26725 To achieve this you must export an initialization routine
26726 (@code{Initialize_API} in the previous example), which must be invoked
26727 before using any of the DLL services. This elaboration routine must call
26728 the Ada elaboration routine @code{adainit} generated by the GNAT binder
26729 (@pxref{Binding with Non-Ada Main Programs}). See the body of
26730 @code{Initialize_Api} for an example. Note that the GNAT binder is
26731 automatically invoked during the DLL build process by the @code{gnatdll}
26732 tool (@pxref{Using gnatdll}).
26733
26734 When a DLL is loaded, Windows systematically invokes a routine called
26735 @code{DllMain}. It would therefore be possible to call @code{adainit}
26736 directly from @code{DllMain} without having to provide an explicit
26737 initialization routine. Unfortunately, it is not possible to call
26738 @code{adainit} from the @code{DllMain} if your program has library level
26739 tasks because access to the @code{DllMain} entry point is serialized by
26740 the system (that is, only a single thread can execute ``through'' it at a
26741 time), which means that the GNAT run time will deadlock waiting for the
26742 newly created task to complete its initialization.
26743
26744 @node Ada DLLs and Finalization
26745 @subsection Ada DLLs and Finalization
26746 @cindex DLLs and finalization
26747
26748 @noindent
26749 When the services of an Ada DLL are no longer needed, the client code should
26750 invoke the DLL finalization routine, if available. The DLL finalization
26751 routine is in charge of releasing all resources acquired by the DLL. In the
26752 case of the Ada code contained in the DLL, this is achieved by calling
26753 routine @code{adafinal} generated by the GNAT binder
26754 (@pxref{Binding with Non-Ada Main Programs}).
26755 See the body of @code{Finalize_Api} for an
26756 example. As already pointed out the GNAT binder is automatically invoked
26757 during the DLL build process by the @code{gnatdll} tool
26758 (@pxref{Using gnatdll}).
26759
26760 @node Creating a Spec for Ada DLLs
26761 @subsection Creating a Spec for Ada DLLs
26762
26763 @noindent
26764 To use the services exported by the Ada DLL from another programming
26765 language (e.g. C), you have to translate the specs of the exported Ada
26766 entities in that language. For instance in the case of @code{API.dll},
26767 the corresponding C header file could look like:
26768
26769 @smallexample
26770 @group
26771 @cartouche
26772 extern int *_imp__count;
26773 #define count (*_imp__count)
26774 int factorial (int);
26775 @end cartouche
26776 @end group
26777 @end smallexample
26778
26779 @noindent
26780 It is important to understand that when building an Ada DLL to be used by
26781 other Ada applications, you need two different specs for the packages
26782 contained in the DLL: one for building the DLL and the other for using
26783 the DLL. This is because the @code{DLL} calling convention is needed to
26784 use a variable defined in a DLL, but when building the DLL, the variable
26785 must have either the @code{Ada} or @code{C} calling convention. As an
26786 example consider a DLL comprising the following package @code{API}:
26787
26788 @smallexample @c ada
26789 @group
26790 @cartouche
26791 package API is
26792    Count : Integer := 0;
26793    ...
26794    --  Remainder of the package omitted.
26795 end API;
26796 @end cartouche
26797 @end group
26798 @end smallexample
26799
26800 @noindent
26801 After producing a DLL containing package @code{API}, the spec that
26802 must be used to import @code{API.Count} from Ada code outside of the
26803 DLL is:
26804
26805 @smallexample @c ada
26806 @group
26807 @cartouche
26808 package API is
26809    Count : Integer;
26810    pragma Import (DLL, Count);
26811 end API;
26812 @end cartouche
26813 @end group
26814 @end smallexample
26815
26816 @node Creating the Definition File
26817 @subsection Creating the Definition File
26818
26819 @noindent
26820 The definition file is the last file needed to build the DLL. It lists
26821 the exported symbols. As an example, the definition file for a DLL
26822 containing only package @code{API} (where all the entities are exported
26823 with a @code{C} calling convention) is:
26824
26825 @smallexample
26826 @group
26827 @cartouche
26828 EXPORTS
26829     count
26830     factorial
26831     finalize_api
26832     initialize_api
26833 @end cartouche
26834 @end group
26835 @end smallexample
26836
26837 @noindent
26838 If the @code{C} calling convention is missing from package @code{API},
26839 then the definition file contains the mangled Ada names of the above
26840 entities, which in this case are:
26841
26842 @smallexample
26843 @group
26844 @cartouche
26845 EXPORTS
26846     api__count
26847     api__factorial
26848     api__finalize_api
26849     api__initialize_api
26850 @end cartouche
26851 @end group
26852 @end smallexample
26853
26854 @node Using gnatdll
26855 @subsection Using @code{gnatdll}
26856 @findex gnatdll
26857
26858 @menu
26859 * gnatdll Example::
26860 * gnatdll behind the Scenes::
26861 * Using dlltool::
26862 @end menu
26863
26864 @noindent
26865 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
26866 and non-Ada sources that make up your DLL have been compiled.
26867 @code{gnatdll} is actually in charge of two distinct tasks: build the
26868 static import library for the DLL and the actual DLL. The form of the
26869 @code{gnatdll} command is
26870
26871 @smallexample
26872 @cartouche
26873 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
26874 @end cartouche
26875 @end smallexample
26876
26877 @noindent
26878 where @i{list-of-files} is a list of ALI and object files. The object
26879 file list must be the exact list of objects corresponding to the non-Ada
26880 sources whose services are to be included in the DLL. The ALI file list
26881 must be the exact list of ALI files for the corresponding Ada sources
26882 whose services are to be included in the DLL. If @i{list-of-files} is
26883 missing, only the static import library is generated.
26884
26885 @noindent
26886 You may specify any of the following switches to @code{gnatdll}:
26887
26888 @table @code
26889 @item -a[@var{address}]
26890 @cindex @option{-a} (@code{gnatdll})
26891 Build a non-relocatable DLL at @var{address}. If @var{address} is not
26892 specified the default address @var{0x11000000} will be used. By default,
26893 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
26894 advise the reader to build relocatable DLL.
26895
26896 @item -b @var{address}
26897 @cindex @option{-b} (@code{gnatdll})
26898 Set the relocatable DLL base address. By default the address is
26899 @var{0x11000000}.
26900
26901 @item -bargs @var{opts}
26902 @cindex @option{-bargs} (@code{gnatdll})
26903 Binder options. Pass @var{opts} to the binder.
26904
26905 @item -d @var{dllfile}
26906 @cindex @option{-d} (@code{gnatdll})
26907 @var{dllfile} is the name of the DLL. This switch must be present for
26908 @code{gnatdll} to do anything. The name of the generated import library is
26909 obtained algorithmically from @var{dllfile} as shown in the following
26910 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
26911 @code{libxyz.a}. The name of the definition file to use (if not specified
26912 by option @option{-e}) is obtained algorithmically from @var{dllfile}
26913 as shown in the following example:
26914 if @var{dllfile} is @code{xyz.dll}, the definition
26915 file used is @code{xyz.def}.
26916
26917 @item -e @var{deffile}
26918 @cindex @option{-e} (@code{gnatdll})
26919 @var{deffile} is the name of the definition file.
26920
26921 @item -g
26922 @cindex @option{-g} (@code{gnatdll})
26923 Generate debugging information. This information is stored in the object
26924 file and copied from there to the final DLL file by the linker,
26925 where it can be read by the debugger. You must use the
26926 @option{-g} switch if you plan on using the debugger or the symbolic
26927 stack traceback.
26928
26929 @item -h
26930 @cindex @option{-h} (@code{gnatdll})
26931 Help mode. Displays @code{gnatdll} switch usage information.
26932
26933 @item -Idir
26934 @cindex @option{-I} (@code{gnatdll})
26935 Direct @code{gnatdll} to search the @var{dir} directory for source and
26936 object files needed to build the DLL.
26937 (@pxref{Search Paths and the Run-Time Library (RTL)}).
26938
26939 @item -k
26940 @cindex @option{-k} (@code{gnatdll})
26941 Removes the @code{@@}@i{nn} suffix from the import library's exported
26942 names. You must specified this option if you want to use a
26943 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
26944 has been removed. This is the case for most of the Windows NT DLL for
26945 example. This option has no effect when @option{-n} option is specified.
26946
26947 @item -l @var{file}
26948 @cindex @option{-l} (@code{gnatdll})
26949 The list of ALI and object files used to build the DLL are listed in
26950 @var{file}, instead of being given in the command line. Each line in
26951 @var{file} contains the name of an ALI or object file.
26952
26953 @item -n
26954 @cindex @option{-n} (@code{gnatdll})
26955 No Import. Do not create the import library.
26956
26957 @item -q
26958 @cindex @option{-q} (@code{gnatdll})
26959 Quiet mode. Do not display unnecessary messages.
26960
26961 @item -v
26962 @cindex @option{-v} (@code{gnatdll})
26963 Verbose mode. Display extra information.
26964
26965 @item -largs @var{opts}
26966 @cindex @option{-largs} (@code{gnatdll})
26967 Linker options. Pass @var{opts} to the linker.
26968 @end table
26969
26970 @node gnatdll Example
26971 @subsubsection @code{gnatdll} Example
26972
26973 @noindent
26974 As an example the command to build a relocatable DLL from @file{api.adb}
26975 once @file{api.adb} has been compiled and @file{api.def} created is
26976
26977 @smallexample
26978 $ gnatdll -d api.dll api.ali
26979 @end smallexample
26980
26981 @noindent
26982 The above command creates two files: @file{libapi.a} (the import
26983 library) and @file{api.dll} (the actual DLL). If you want to create
26984 only the DLL, just type:
26985
26986 @smallexample
26987 $ gnatdll -d api.dll -n api.ali
26988 @end smallexample
26989
26990 @noindent
26991 Alternatively if you want to create just the import library, type:
26992
26993 @smallexample
26994 $ gnatdll -d api.dll
26995 @end smallexample
26996
26997 @node gnatdll behind the Scenes
26998 @subsubsection @code{gnatdll} behind the Scenes
26999
27000 @noindent
27001 This section details the steps involved in creating a DLL. @code{gnatdll}
27002 does these steps for you. Unless you are interested in understanding what
27003 goes on behind the scenes, you should skip this section.
27004
27005 We use the previous example of a DLL containing the Ada package @code{API},
27006 to illustrate the steps necessary to build a DLL. The starting point is a
27007 set of objects that will make up the DLL and the corresponding ALI
27008 files. In the case of this example this means that @file{api.o} and
27009 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27010 the following:
27011
27012 @enumerate
27013 @item
27014 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27015 the information necessary to generate relocation information for the
27016 DLL.
27017
27018 @smallexample
27019 @group
27020 $ gnatbind -n api
27021 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27022 @end group
27023 @end smallexample
27024
27025 @noindent
27026 In addition to the base file, the @code{gnatlink} command generates an
27027 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27028 asks @code{gnatlink} to generate the routines @code{DllMain} and
27029 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27030 is loaded into memory.
27031
27032 @item
27033 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27034 export table (@file{api.exp}). The export table contains the relocation
27035 information in a form which can be used during the final link to ensure
27036 that the Windows loader is able to place the DLL anywhere in memory.
27037
27038 @smallexample
27039 @group
27040 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27041           --output-exp api.exp
27042 @end group
27043 @end smallexample
27044
27045 @item
27046 @code{gnatdll} builds the base file using the new export table. Note that
27047 @code{gnatbind} must be called once again since the binder generated file
27048 has been deleted during the previous call to @code{gnatlink}.
27049
27050 @smallexample
27051 @group
27052 $ gnatbind -n api
27053 $ gnatlink api -o api.jnk api.exp -mdll
27054       -Wl,--base-file,api.base
27055 @end group
27056 @end smallexample
27057
27058 @item
27059 @code{gnatdll} builds the new export table using the new base file and
27060 generates the DLL import library @file{libAPI.a}.
27061
27062 @smallexample
27063 @group
27064 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27065           --output-exp api.exp --output-lib libAPI.a
27066 @end group
27067 @end smallexample
27068
27069 @item
27070 Finally @code{gnatdll} builds the relocatable DLL using the final export
27071 table.
27072
27073 @smallexample
27074 @group
27075 $ gnatbind -n api
27076 $ gnatlink api api.exp -o api.dll -mdll
27077 @end group
27078 @end smallexample
27079 @end enumerate
27080
27081 @node Using dlltool
27082 @subsubsection Using @code{dlltool}
27083
27084 @noindent
27085 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27086 DLLs and static import libraries. This section summarizes the most
27087 common @code{dlltool} switches. The form of the @code{dlltool} command
27088 is
27089
27090 @smallexample
27091 $ dlltool [@var{switches}]
27092 @end smallexample
27093
27094 @noindent
27095 @code{dlltool} switches include:
27096
27097 @table @option
27098 @item --base-file @var{basefile}
27099 @cindex @option{--base-file} (@command{dlltool})
27100 Read the base file @var{basefile} generated by the linker. This switch
27101 is used to create a relocatable DLL.
27102
27103 @item --def @var{deffile}
27104 @cindex @option{--def} (@command{dlltool})
27105 Read the definition file.
27106
27107 @item --dllname @var{name}
27108 @cindex @option{--dllname} (@command{dlltool})
27109 Gives the name of the DLL. This switch is used to embed the name of the
27110 DLL in the static import library generated by @code{dlltool} with switch
27111 @option{--output-lib}.
27112
27113 @item -k
27114 @cindex @option{-k} (@command{dlltool})
27115 Kill @code{@@}@i{nn} from exported names
27116 (@pxref{Windows Calling Conventions}
27117 for a discussion about @code{Stdcall}-style symbols.
27118
27119 @item --help
27120 @cindex @option{--help} (@command{dlltool})
27121 Prints the @code{dlltool} switches with a concise description.
27122
27123 @item --output-exp @var{exportfile}
27124 @cindex @option{--output-exp} (@command{dlltool})
27125 Generate an export file @var{exportfile}. The export file contains the
27126 export table (list of symbols in the DLL) and is used to create the DLL.
27127
27128 @item --output-lib @i{libfile}
27129 @cindex @option{--output-lib} (@command{dlltool})
27130 Generate a static import library @var{libfile}.
27131
27132 @item -v
27133 @cindex @option{-v} (@command{dlltool})
27134 Verbose mode.
27135
27136 @item --as @i{assembler-name}
27137 @cindex @option{--as} (@command{dlltool})
27138 Use @i{assembler-name} as the assembler. The default is @code{as}.
27139 @end table
27140
27141 @node GNAT and Windows Resources
27142 @section GNAT and Windows Resources
27143 @cindex Resources, windows
27144
27145 @menu
27146 * Building Resources::
27147 * Compiling Resources::
27148 * Using Resources::
27149 @end menu
27150
27151 @noindent
27152 Resources are an easy way to add Windows specific objects to your
27153 application. The objects that can be added as resources include:
27154
27155 @itemize @bullet
27156 @item
27157 menus
27158
27159 @item
27160 accelerators
27161
27162 @item
27163 dialog boxes
27164
27165 @item
27166 string tables
27167
27168 @item
27169 bitmaps
27170
27171 @item
27172 cursors
27173
27174 @item
27175 icons
27176
27177 @item
27178 fonts
27179 @end itemize
27180
27181 @noindent
27182 This section explains how to build, compile and use resources.
27183
27184 @node Building Resources
27185 @subsection Building Resources
27186 @cindex Resources, building
27187
27188 @noindent
27189 A resource file is an ASCII file. By convention resource files have an
27190 @file{.rc} extension.
27191 The easiest way to build a resource file is to use Microsoft tools
27192 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27193 @code{dlgedit.exe} to build dialogs.
27194 It is always possible to build an @file{.rc} file yourself by writing a
27195 resource script.
27196
27197 It is not our objective to explain how to write a resource file. A
27198 complete description of the resource script language can be found in the
27199 Microsoft documentation.
27200
27201 @node Compiling Resources
27202 @subsection Compiling Resources
27203 @findex rc
27204 @findex windres
27205 @cindex Resources, compiling
27206
27207 @noindent
27208 This section describes how to build a GNAT-compatible (COFF) object file
27209 containing the resources. This is done using the Resource Compiler
27210 @code{windres} as follows:
27211
27212 @smallexample
27213 $ windres -i myres.rc -o myres.o
27214 @end smallexample
27215
27216 @noindent
27217 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27218 file. You can specify an alternate preprocessor (usually named
27219 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27220 parameter. A list of all possible options may be obtained by entering
27221 the command @code{windres} @option{--help}.
27222
27223 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27224 to produce a @file{.res} file (binary resource file). See the
27225 corresponding Microsoft documentation for further details. In this case
27226 you need to use @code{windres} to translate the @file{.res} file to a
27227 GNAT-compatible object file as follows:
27228
27229 @smallexample
27230 $ windres -i myres.res -o myres.o
27231 @end smallexample
27232
27233 @node Using Resources
27234 @subsection Using Resources
27235 @cindex Resources, using
27236
27237 @noindent
27238 To include the resource file in your program just add the
27239 GNAT-compatible object file for the resource(s) to the linker
27240 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27241 option:
27242
27243 @smallexample
27244 $ gnatmake myprog -largs myres.o
27245 @end smallexample
27246
27247 @node Debugging a DLL
27248 @section Debugging a DLL
27249 @cindex DLL debugging
27250
27251 @menu
27252 * Program and DLL Both Built with GCC/GNAT::
27253 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27254 @end menu
27255
27256 @noindent
27257 Debugging a DLL is similar to debugging a standard program. But
27258 we have to deal with two different executable parts: the DLL and the
27259 program that uses it. We have the following four possibilities:
27260
27261 @enumerate 1
27262 @item
27263 The program and the DLL are built with @code{GCC/GNAT}.
27264 @item
27265 The program is built with foreign tools and the DLL is built with
27266 @code{GCC/GNAT}.
27267 @item
27268 The program is built with @code{GCC/GNAT} and the DLL is built with
27269 foreign tools.
27270 @item
27271 @end enumerate
27272
27273 @noindent
27274 In this section we address only cases one and two above.
27275 There is no point in trying to debug
27276 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27277 information in it. To do so you must use a debugger compatible with the
27278 tools suite used to build the DLL.
27279
27280 @node Program and DLL Both Built with GCC/GNAT
27281 @subsection Program and DLL Both Built with GCC/GNAT
27282
27283 @noindent
27284 This is the simplest case. Both the DLL and the program have @code{GDB}
27285 compatible debugging information. It is then possible to break anywhere in
27286 the process. Let's suppose here that the main procedure is named
27287 @code{ada_main} and that in the DLL there is an entry point named
27288 @code{ada_dll}.
27289
27290 @noindent
27291 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27292 program must have been built with the debugging information (see GNAT -g
27293 switch). Here are the step-by-step instructions for debugging it:
27294
27295 @enumerate 1
27296 @item Launch @code{GDB} on the main program.
27297
27298 @smallexample
27299 $ gdb -nw ada_main
27300 @end smallexample
27301
27302 @item Break on the main procedure and run the program.
27303
27304 @smallexample
27305 (gdb) break ada_main
27306 (gdb) run
27307 @end smallexample
27308
27309 @noindent
27310 This step is required to be able to set a breakpoint inside the DLL. As long
27311 as the program is not run, the DLL is not loaded. This has the
27312 consequence that the DLL debugging information is also not loaded, so it is not
27313 possible to set a breakpoint in the DLL.
27314
27315 @item Set a breakpoint inside the DLL
27316
27317 @smallexample
27318 (gdb) break ada_dll
27319 (gdb) run
27320 @end smallexample
27321
27322 @end enumerate
27323
27324 @noindent
27325 At this stage a breakpoint is set inside the DLL. From there on
27326 you can use the standard approach to debug the whole program
27327 (@pxref{Running and Debugging Ada Programs}).
27328
27329 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27330 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27331
27332 @menu
27333 * Debugging the DLL Directly::
27334 * Attaching to a Running Process::
27335 @end menu
27336
27337 @noindent
27338 In this case things are slightly more complex because it is not possible to
27339 start the main program and then break at the beginning to load the DLL and the
27340 associated DLL debugging information. It is not possible to break at the
27341 beginning of the program because there is no @code{GDB} debugging information,
27342 and therefore there is no direct way of getting initial control. This
27343 section addresses this issue by describing some methods that can be used
27344 to break somewhere in the DLL to debug it.
27345
27346 @noindent
27347 First suppose that the main procedure is named @code{main} (this is for
27348 example some C code built with Microsoft Visual C) and that there is a
27349 DLL named @code{test.dll} containing an Ada entry point named
27350 @code{ada_dll}.
27351
27352 @noindent
27353 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27354 been built with debugging information (see GNAT -g option).
27355
27356 @node Debugging the DLL Directly
27357 @subsubsection Debugging the DLL Directly
27358
27359 @enumerate 1
27360 @item
27361 Launch the debugger on the DLL.
27362
27363 @smallexample
27364 $ gdb -nw test.dll
27365 @end smallexample
27366
27367 @item Set a breakpoint on a DLL subroutine.
27368
27369 @smallexample
27370 (gdb) break ada_dll
27371 @end smallexample
27372
27373 @item
27374 Specify the executable file to @code{GDB}.
27375
27376 @smallexample
27377 (gdb) exec-file main.exe
27378 @end smallexample
27379
27380 @item
27381 Run the program.
27382
27383 @smallexample
27384 (gdb) run
27385 @end smallexample
27386
27387 @noindent
27388 This will run the program until it reaches the breakpoint that has been
27389 set. From that point you can use the standard way to debug a program
27390 as described in (@pxref{Running and Debugging Ada Programs}).
27391
27392 @end enumerate
27393
27394 @noindent
27395 It is also possible to debug the DLL by attaching to a running process.
27396
27397 @node Attaching to a Running Process
27398 @subsubsection Attaching to a Running Process
27399 @cindex DLL debugging, attach to process
27400
27401 @noindent
27402 With @code{GDB} it is always possible to debug a running process by
27403 attaching to it. It is possible to debug a DLL this way. The limitation
27404 of this approach is that the DLL must run long enough to perform the
27405 attach operation. It may be useful for instance to insert a time wasting
27406 loop in the code of the DLL to meet this criterion.
27407
27408 @enumerate 1
27409
27410 @item Launch the main program @file{main.exe}.
27411
27412 @smallexample
27413 $ main
27414 @end smallexample
27415
27416 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27417 that the process PID for @file{main.exe} is 208.
27418
27419 @item Launch gdb.
27420
27421 @smallexample
27422 $ gdb -nw
27423 @end smallexample
27424
27425 @item Attach to the running process to be debugged.
27426
27427 @smallexample
27428 (gdb) attach 208
27429 @end smallexample
27430
27431 @item Load the process debugging information.
27432
27433 @smallexample
27434 (gdb) symbol-file main.exe
27435 @end smallexample
27436
27437 @item Break somewhere in the DLL.
27438
27439 @smallexample
27440 (gdb) break ada_dll
27441 @end smallexample
27442
27443 @item Continue process execution.
27444
27445 @smallexample
27446 (gdb) continue
27447 @end smallexample
27448
27449 @end enumerate
27450
27451 @noindent
27452 This last step will resume the process execution, and stop at
27453 the breakpoint we have set. From there you can use the standard
27454 approach to debug a program as described in
27455 (@pxref{Running and Debugging Ada Programs}).
27456
27457 @node GNAT and COM/DCOM Objects
27458 @section GNAT and COM/DCOM Objects
27459 @findex COM
27460 @findex DCOM
27461
27462 @noindent
27463 This section is temporarily left blank.
27464
27465 @end ifset
27466
27467
27468 @c **********************************
27469 @c * GNU Free Documentation License *
27470 @c **********************************
27471 @include fdl.texi
27472 @c GNU Free Documentation License
27473
27474 @node Index,,GNU Free Documentation License, Top
27475 @unnumbered Index
27476
27477 @printindex cp
27478
27479 @contents
27480 @c Put table of contents at end, otherwise it precedes the "title page" in
27481 @c the .txt version
27482 @c Edit the pdf file to move the contents to the beginning, after the title
27483 @c page
27484
27485 @bye