OSDN Git Service

* langhooks.h (estimate_num_insns, pushlevel, poplevel, set_block,
[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 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
83
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
87
88 @ifset vms
89 @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha
90 @dircategory GNU Ada tools
91 @direntry
92 * GNAT User's Guide (gnat_ugn_vms) for Native Platforms / OpenVMS Alpha
93 @end direntry
94 @end ifset
95
96 @ifset unw
97 @settitle GNAT User's Guide for Native Platforms / Unix and Windows
98 @direntry
99 * GNAT User's Guide (gnat_ugn_unw) for Native Platforms / Unix and Windows
100 @end direntry
101 @end ifset
102
103 @include gcc-common.texi
104
105 @setchapternewpage odd
106 @syncodeindex fn cp
107 @c %**end of header
108
109 @copying
110 Copyright @copyright{} 1995-2004, Free Software Foundation
111
112 Permission is granted to copy, distribute and/or modify this document
113 under the terms of the GNU Free Documentation License, Version 1.2
114 or any later version published by the Free Software Foundation;
115 with the Invariant Sections being ``GNU Free Documentation License'', with the
116 Front-Cover Texts being
117 @ifset vms
118 ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'',
119 @end ifset
120 @ifset unw
121 ``GNAT User's Guide for Native Platforms / Unix and Windows'',
122 @end ifset
123 and with no Back-Cover Texts.
124 A copy of the license is included in the section entitled
125 ``GNU Free Documentation License''.
126 @end copying
127
128 @titlepage
129
130 @title GNAT User's Guide
131 @center @titlefont{for Native Platforms}
132 @sp 1
133
134 @flushright
135 @ifset unw
136 @titlefont{@i{Unix and Windows}}
137 @end ifset
138 @ifset vms
139 @titlefont{@i{OpenVMS Alpha}}
140 @end ifset
141 @end flushright
142 @sp 2
143
144 @subtitle GNAT, The GNU Ada 95 Compiler
145 @subtitle GCC version @value{version-GCC}
146
147 @author Ada Core Technologies, Inc.
148
149 @page
150 @vskip 0pt plus 1filll
151
152 @insertcopying
153
154 @end titlepage
155
156
157 @ifnottex
158 @node Top, About This Guide, (dir), (dir)
159 @top GNAT User's Guide
160
161 @ifset vms
162 @noindent
163 GNAT User's Guide for Native Platforms / OpenVMS Alpha
164 @end ifset
165
166 @ifset unw
167 @noindent
168 GNAT User's Guide for Native Platforms / Unix and Windows
169 @end ifset
170
171 @noindent
172 GNAT, The GNU Ada 95 Compiler@*
173 GCC version @value{version-GCC}@*
174
175 @noindent
176 Ada Core Technologies, Inc.@*
177
178 @menu
179 * About This Guide::
180 * Getting Started with GNAT::
181 * The GNAT Compilation Model::
182 * Compiling Using gcc::
183 * Binding Using gnatbind::
184 * Linking Using gnatlink::
185 * The GNAT Make Program gnatmake::
186 * Improving Performance::
187 * Renaming Files Using gnatchop::
188 * Configuration Pragmas::
189 * Handling Arbitrary File Naming Conventions Using gnatname::
190 * GNAT Project Manager::
191 * The Cross-Referencing Tools gnatxref and gnatfind::
192 * The GNAT Pretty-Printer gnatpp::
193 * File Name Krunching Using gnatkr::
194 * Preprocessing Using gnatprep::
195 @ifset vms
196 * The GNAT Run-Time Library Builder gnatlbr::
197 @end ifset
198 * The GNAT Library Browser gnatls::
199 * Cleaning Up Using gnatclean::
200 @ifclear vms
201 * GNAT and Libraries::
202 * Using the GNU make Utility::
203 @end ifclear
204 * Finding Memory Problems::
205 * Creating Sample Bodies Using gnatstub::
206 * Other Utility Programs::
207 * Running and Debugging Ada Programs::
208 @ifset vms
209 * Compatibility with DEC Ada::
210 @end ifset
211 * Platform-Specific Information for the Run-Time Libraries::
212 * Example of Binder Output File::
213 * Elaboration Order Handling in GNAT::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 @ifset unw
217 * Microsoft Windows Topics::
218 @end ifset
219 * GNU Free Documentation License::
220 * Index::
221
222  --- The Detailed Node Listing ---
223
224 About This Guide
225
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
229 * Conventions::
230
231 Getting Started with GNAT
232
233 * Running GNAT::
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
237 @ifset vms
238 * Editing with Emacs::
239 @end ifset
240 @ifclear vms
241 * Introduction to GPS::
242 * Introduction to Glide and GVD::
243 @end ifclear
244
245 The GNAT Compilation Model
246
247 * Source Representation::
248 * Foreign Language Representation::
249 * File Naming Rules::
250 * Using Other File Names::
251 * Alternative File Naming Schemes::
252 * Generating Object Files::
253 * Source Dependencies::
254 * The Ada Library Information Files::
255 * Binding an Ada Program::
256 * Mixed Language Programming::
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
259 * Comparison between GNAT and Conventional Ada Library Models::
260 @ifset vms
261 * Placement of temporary files::
262 @end ifset
263
264 Foreign Language Representation
265
266 * Latin-1::
267 * Other 8-Bit Codes::
268 * Wide Character Encodings::
269
270 Compiling Ada Programs With gcc
271
272 * Compiling Programs::
273 * Switches for gcc::
274 * Search Paths and the Run-Time Library (RTL)::
275 * Order of Compilation Issues::
276 * Examples::
277
278 Switches for gcc
279
280 * Output and Error Message Control::
281 * Warning Message Control::
282 * Debugging and Assertion Control::
283 * Validity Checking::
284 * Style Checking::
285 * Run-Time Checks::
286 * Stack Overflow Checking::
287 * Using gcc for Syntax Checking::
288 * Using gcc for Semantic Checking::
289 * Compiling Ada 83 Programs::
290 * Character Set Control::
291 * File Naming Control::
292 * Subprogram Inlining Control::
293 * Auxiliary Output Control::
294 * Debugging Control::
295 * Exception Handling Control::
296 * Units to Sources Mapping Files::
297 * Integrated Preprocessing::
298 @ifset vms
299 * Return Codes::
300 @end ifset
301
302 Binding Ada Programs With gnatbind
303
304 * Running gnatbind::
305 * Switches for gnatbind::
306 * Command-Line Access::
307 * Search Paths for gnatbind::
308 * Examples of gnatbind Usage::
309
310 Switches for gnatbind
311
312 * Consistency-Checking Modes::
313 * Binder Error Message Control::
314 * Elaboration Control::
315 * Output Control::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
318
319 Linking Using gnatlink
320
321 * Running gnatlink::
322 * Switches for gnatlink::
323 * Setting Stack Size from gnatlink::
324 * Setting Heap Size from gnatlink::
325
326 The GNAT Make Program gnatmake
327
328 * Running gnatmake::
329 * Switches for gnatmake::
330 * Mode Switches for gnatmake::
331 * Notes on the Command Line::
332 * How gnatmake Works::
333 * Examples of gnatmake Usage::
334
335
336 Improving Performance
337 * Performance Considerations::
338 * Reducing the Size of Ada Executables with gnatelim::
339
340 Performance Considerations
341 * Controlling Run-Time Checks::
342 * Use of Restrictions::
343 * Optimization Levels::
344 * Debugging Optimized Code::
345 * Inlining of Subprograms::
346 * Optimization and Strict Aliasing::
347 @ifset vms
348 * Coverage Analysis::
349 @end ifset
350
351 Reducing the Size of Ada Executables with gnatelim
352 * About gnatelim::
353 * Running gnatelim::
354 * Correcting the List of Eliminate Pragmas::
355 * Making Your Executables Smaller::
356 * Summary of the gnatelim Usage Cycle::
357
358 Renaming Files Using gnatchop
359
360 * Handling Files with Multiple Units::
361 * Operating gnatchop in Compilation Mode::
362 * Command Line for gnatchop::
363 * Switches for gnatchop::
364 * Examples of gnatchop Usage::
365
366 Configuration Pragmas
367
368 * Handling of Configuration Pragmas::
369 * The Configuration Pragmas Files::
370
371 Handling Arbitrary File Naming Conventions Using gnatname
372
373 * Arbitrary File Naming Conventions::
374 * Running gnatname::
375 * Switches for gnatname::
376 * Examples of gnatname Usage::
377
378 GNAT Project Manager
379
380 * Introduction::
381 * Examples of Project Files::
382 * Project File Syntax::
383 * Objects and Sources in Project Files::
384 * Importing Projects::
385 * Project Extension::
386 * External References in Project Files::
387 * Packages in Project Files::
388 * Variables from Imported Projects::
389 * Naming Schemes::
390 * Library Projects::
391 * Using Third-Party Libraries through Projects::
392 * Stand-alone Library Projects::
393 * Switches Related to Project Files::
394 * Tools Supporting Project Files::
395 * An Extended Example::
396 * Project File Complete Syntax::
397
398
399 The Cross-Referencing Tools gnatxref and gnatfind
400
401 * gnatxref Switches::
402 * gnatfind Switches::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
407
408
409 The GNAT Pretty-Printer gnatpp
410
411 * Switches for gnatpp::
412 * Formatting Rules::
413
414
415 File Name Krunching Using gnatkr
416
417 * About gnatkr::
418 * Using gnatkr::
419 * Krunching Method::
420 * Examples of gnatkr Usage::
421
422 Preprocessing Using gnatprep
423
424 * Using gnatprep::
425 * Switches for gnatprep::
426 * Form of Definitions File::
427 * Form of Input Text for gnatprep::
428
429 @ifset vms
430 The GNAT Run-Time Library Builder gnatlbr
431
432 * Running gnatlbr::
433 * Switches for gnatlbr::
434 * Examples of gnatlbr Usage::
435 @end ifset
436
437 The GNAT Library Browser gnatls
438
439 * Running gnatls::
440 * Switches for gnatls::
441 * Examples of gnatls Usage::
442
443 Cleaning Up Using gnatclean
444
445 * Running gnatclean::
446 * Switches for gnatclean::
447 * Examples of gnatclean Usage::
448
449 @ifclear vms
450
451 GNAT and Libraries
452
453 * Introduction to Libraries in GNAT::
454 * General Ada Libraries::
455 * Stand-alone Ada Libraries::
456 * Rebuilding the GNAT Run-Time Library::
457
458 Using the GNU make Utility
459
460 * Using gnatmake in a Makefile::
461 * Automatically Creating a List of Directories::
462 * Generating the Command Line Switches::
463 * Overcoming Command Line Length Limits::
464 @end ifclear
465
466 Finding Memory Problems
467
468 @ifclear vms
469 * The gnatmem Tool::
470 @end ifclear
471 * The GNAT Debug Pool Facility::
472
473 @ifclear vms
474 The gnatmem Tool
475
476 * Running gnatmem::
477 * Switches for gnatmem::
478 * Example of gnatmem Usage::
479 @end ifclear
480
481 The GNAT Debug Pool Facility
482
483 Creating Sample Bodies Using gnatstub
484
485 * Running gnatstub::
486 * Switches for gnatstub::
487
488 Other Utility Programs
489
490 * Using Other Utility Programs with GNAT::
491 * The External Symbol Naming Scheme of GNAT::
492 @ifclear vms
493 * Ada Mode for Glide::
494 @end ifclear
495 * Converting Ada Files to html with gnathtml::
496
497 Running and Debugging Ada Programs
498
499 * The GNAT Debugger GDB::
500 * Running GDB::
501 * Introduction to GDB Commands::
502 * Using Ada Expressions::
503 * Calling User-Defined Subprograms::
504 * Using the Next Command in a Function::
505 * Ada Exceptions::
506 * Ada Tasks::
507 * Debugging Generic Units::
508 * GNAT Abnormal Termination or Failure to Terminate::
509 * Naming Conventions for GNAT Source Files::
510 * Getting Internal Debugging Information::
511 * Stack Traceback::
512
513 @ifset vms
514 * LSE::
515 @end ifset
516
517 @ifset vms
518 Compatibility with DEC Ada
519
520 * Ada 95 Compatibility::
521 * Differences in the Definition of Package System::
522 * Language-Related Features::
523 * The Package STANDARD::
524 * The Package SYSTEM::
525 * Tasking and Task-Related Features::
526 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
527 * Pragmas and Pragma-Related Features::
528 * Library of Predefined Units::
529 * Bindings::
530 * Main Program Definition::
531 * Implementation-Defined Attributes::
532 * Compiler and Run-Time Interfacing::
533 * Program Compilation and Library Management::
534 * Input-Output::
535 * Implementation Limits::
536 * Tools::
537
538 Language-Related Features
539
540 * Integer Types and Representations::
541 * Floating-Point Types and Representations::
542 * Pragmas Float_Representation and Long_Float::
543 * Fixed-Point Types and Representations::
544 * Record and Array Component Alignment::
545 * Address Clauses::
546 * Other Representation Clauses::
547
548 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
549
550 * Assigning Task IDs::
551 * Task IDs and Delays::
552 * Task-Related Pragmas::
553 * Scheduling and Task Priority::
554 * The Task Stack::
555 * External Interrupts::
556
557 Pragmas and Pragma-Related Features
558
559 * Restrictions on the Pragma INLINE::
560 * Restrictions on the Pragma INTERFACE::
561 * Restrictions on the Pragma SYSTEM_NAME::
562
563 Library of Predefined Units
564
565 * Changes to DECLIB::
566
567 Bindings
568
569 * Shared Libraries and Options Files::
570 * Interfaces to C::
571 @end ifset
572
573 Platform-Specific Information for the Run-Time Libraries
574
575 * Summary of Run-Time Configurations::
576 * Specifying a Run-Time Library::
577 * Choosing between Native and FSU Threads Libraries::
578 * Choosing the Scheduling Policy::
579 * Solaris-Specific Considerations::
580 * IRIX-Specific Considerations::
581 * Linux-Specific Considerations::
582 * AIX-Specific Considerations::
583
584 Example of Binder Output File
585
586 Elaboration Order Handling in GNAT
587
588 * Elaboration Code in Ada 95::
589 * Checking the Elaboration Order in Ada 95::
590 * Controlling the Elaboration Order in Ada 95::
591 * Controlling Elaboration in GNAT - Internal Calls::
592 * Controlling Elaboration in GNAT - External Calls::
593 * Default Behavior in GNAT - Ensuring Safety::
594 * Treatment of Pragma Elaborate::
595 * Elaboration Issues for Library Tasks::
596 * Mixing Elaboration Models::
597 * What to Do If the Default Elaboration Behavior Fails::
598 * Elaboration for Access-to-Subprogram Values::
599 * Summary of Procedures for Elaboration Control::
600 * Other Elaboration Order Considerations::
601
602 Inline Assembler
603
604 * Basic Assembler Syntax::
605 * A Simple Example of Inline Assembler::
606 * Output Variables in Inline Assembler::
607 * Input Variables in Inline Assembler::
608 * Inlining Inline Assembler Code::
609 * Other Asm Functionality::
610 * A Complete Example::
611
612 Compatibility and Porting Guide
613
614 * Compatibility with Ada 83::
615 * Implementation-dependent characteristics::
616 * Compatibility with DEC Ada 83::
617 * Compatibility with Other Ada 95 Systems::
618 * Representation Clauses::
619
620 @ifset unw
621 Microsoft Windows Topics
622
623 * Using GNAT on Windows::
624 * CONSOLE and WINDOWS subsystems::
625 * Temporary Files::
626 * Mixed-Language Programming on Windows::
627 * Windows Calling Conventions::
628 * Introduction to Dynamic Link Libraries (DLLs)::
629 * Using DLLs with GNAT::
630 * Building DLLs with GNAT::
631 * GNAT and Windows Resources::
632 * Debugging a DLL::
633 * GNAT and COM/DCOM Objects::
634 @end ifset
635
636
637 * Index::
638 @end menu
639 @end ifnottex
640
641 @node About This Guide
642 @unnumbered About This Guide
643
644 @noindent
645 @ifset vms
646 This guide describes the use of of GNAT, a full language compiler for the Ada
647 95 programming language, implemented on HP OpenVMS Alpha platforms.
648 @end ifset
649 @ifclear vms
650 This guide describes the use of GNAT, a compiler and software development
651 toolset for the full Ada 95 programming language.
652 @end ifclear
653 It describes the features of the compiler and tools, and details
654 how to use them to build Ada 95 applications.
655
656 @menu
657 * What This Guide Contains::
658 * What You Should Know before Reading This Guide::
659 * Related Information::
660 * Conventions::
661 @end menu
662
663 @node What This Guide Contains
664 @unnumberedsec What This Guide Contains
665
666 @noindent
667 This guide contains the following chapters:
668 @itemize @bullet
669
670 @item
671 @ref{Getting Started with GNAT}, describes how to get started compiling
672 and running Ada programs with the GNAT Ada programming environment.
673 @item
674 @ref{The GNAT Compilation Model}, describes the compilation model used
675 by GNAT.
676
677 @item
678 @ref{Compiling Using gcc}, describes how to compile
679 Ada programs with @code{gcc}, the Ada compiler.
680
681 @item
682 @ref{Binding Using gnatbind}, describes how to
683 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
684 utility.
685
686 @item
687 @ref{Linking Using gnatlink},
688 describes @code{gnatlink}, a
689 program that provides for linking using the GNAT run-time library to
690 construct a program. @code{gnatlink} can also incorporate foreign language
691 object units into the executable.
692
693 @item
694 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
695 utility that automatically determines the set of sources
696 needed by an Ada compilation unit, and executes the necessary compilations
697 binding and link.
698
699 @item
700 @ref{Improving Performance}, shows various techniques for making your
701 Ada program run faster or take less space.
702 It discusses the effect of the compiler's optimization switch and
703 also describes the @command{gnatelim} tool.
704
705 @item
706 @ref{Renaming Files Using gnatchop}, describes
707 @code{gnatchop}, a utility that allows you to preprocess a file that
708 contains Ada source code, and split it into one or more new files, one
709 for each compilation unit.
710
711 @item
712 @ref{Configuration Pragmas}, describes the configuration pragmas
713 handled by GNAT.
714
715 @item
716 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
717 shows how to override the default GNAT file naming conventions,
718 either for an individual unit or globally.
719
720 @item
721 @ref{GNAT Project Manager}, describes how to use project files
722 to organize large projects.
723
724 @item
725 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
726 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
727 way to navigate through sources.
728
729 @item
730 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
731 version of an Ada source file with control over casing, indentation,
732 comment placement, and other elements of program presentation style.
733
734
735 @item
736 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
737 file name krunching utility, used to handle shortened
738 file names on operating systems with a limit on the length of names.
739
740 @item
741 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
742 preprocessor utility that allows a single source file to be used to
743 generate multiple or parameterized source files, by means of macro
744 substitution.
745
746 @ifset vms
747 @item
748 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
749 a tool for rebuilding the GNAT run time with user-supplied
750 configuration pragmas.
751 @end ifset
752
753 @item
754 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
755 utility that displays information about compiled units, including dependences
756 on the corresponding sources files, and consistency of compilations.
757
758 @item
759 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
760 to delete files that are produced by the compiler, binder and linker.
761
762 @ifclear vms
763 @item
764 @ref{GNAT and Libraries}, describes the process of creating and using
765 Libraries with GNAT. It also describes how to recompile the GNAT run-time
766 library.
767
768 @item
769 @ref{Using the GNU make Utility}, describes some techniques for using
770 the GNAT toolset in Makefiles.
771 @end ifclear
772
773 @item
774 @ref{Finding Memory Problems}, describes
775 @ifclear vms
776 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
777 and helps detect ``memory leaks'', and
778 @end ifclear
779 the GNAT Debug Pool facility, which helps detect incorrect memory references.
780
781 @item
782 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
783 a utility that generates empty but compilable bodies for library units.
784
785 @item
786 @ref{Other Utility Programs}, discusses several other GNAT utilities,
787 including @code{gnathtml}.
788
789 @item
790 @ref{Running and Debugging Ada Programs}, describes how to run and debug
791 Ada programs.
792
793 @ifset vms
794 @item
795 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
796 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
797 developed by Digital Equipment Corporation and currently supported by HP.}
798 for OpenVMS Alpha.
799 @end ifset
800
801 @item
802 @ref{Platform-Specific Information for the Run-Time Libraries},
803 describes the various run-time
804 libraries supported by GNAT on various platforms and explains how to
805 choose a particular library.
806
807 @item
808 @ref{Example of Binder Output File}, shows the source code for the binder
809 output file for a sample program.
810
811 @item
812 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
813 you deal with elaboration order issues.
814
815 @item
816 @ref{Inline Assembler}, shows how to use the inline assembly facility
817 in an Ada program.
818
819 @item
820 @ref{Compatibility and Porting Guide}, includes sections on compatibility
821 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
822 in porting code from other environments.
823
824 @ifset unw
825 @item
826 @ref{Microsoft Windows Topics}, presents information relevant to the
827 Microsoft Windows platform.
828 @end ifset
829 @end itemize
830
831
832 @c *************************************************
833 @node What You Should Know before Reading This Guide
834 @c *************************************************
835 @unnumberedsec What You Should Know before Reading This Guide
836
837 @cindex Ada 95 Language Reference Manual
838 @noindent
839 This user's guide assumes that you are familiar with Ada 95 language, as
840 described in the International Standard ANSI/ISO/IEC-8652:1995, January
841 1995.
842
843 @node Related Information
844 @unnumberedsec Related Information
845
846 @noindent
847 For further information about related tools, refer to the following
848 documents:
849
850 @itemize @bullet
851 @item
852 @cite{GNAT Reference Manual}, which contains all reference
853 material for the GNAT implementation of Ada 95.
854
855 @ifset unw
856 @item
857 @cite{Using the GNAT Programming System}, which describes the GPS
858 integrated development environment.
859
860 @item
861 @cite{GNAT Programming System Tutorial}, which introduces the
862 main GPS features through examples.
863 @end ifset
864
865 @item
866 @cite{Ada 95 Language Reference Manual}, which contains all reference
867 material for the Ada 95 programming language.
868
869 @item
870 @cite{Debugging with GDB}
871 @ifset vms
872 , located in the GNU:[DOCS] directory,
873 @end ifset
874 contains all details on the use of the GNU source-level debugger.
875
876 @item
877 @cite{GNU Emacs Manual}
878 @ifset vms
879 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
880 @end ifset
881 contains full information on the extensible editor and programming
882 environment Emacs.
883
884 @end itemize
885
886 @c **************
887 @node Conventions
888 @unnumberedsec Conventions
889 @cindex Conventions
890 @cindex Typographical conventions
891
892 @noindent
893 Following are examples of the typographical and graphic conventions used
894 in this guide:
895
896 @itemize @bullet
897 @item
898 @code{Functions}, @code{utility program names}, @code{standard names},
899 and @code{classes}.
900
901 @item
902 @samp{Option flags}
903
904 @item
905 @file{File Names}, @file{button names}, and @file{field names}.
906
907 @item
908 @var{Variables}.
909
910 @item
911 @emph{Emphasis}.
912
913 @item
914 [optional information or parameters]
915
916 @item
917 Examples are described by text
918 @smallexample
919 and then shown this way.
920 @end smallexample
921 @end itemize
922
923 @noindent
924 Commands that are entered by the user are preceded in this manual by the
925 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
926 uses this sequence as a prompt, then the commands will appear exactly as
927 you see them in the manual. If your system uses some other prompt, then
928 the command will appear with the @code{$} replaced by whatever prompt
929 character you are using.
930
931 @ifset unw
932 Full file names are shown with the ``@code{/}'' character
933 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
934 If you are using GNAT on a Windows platform, please note that
935 the ``@code{\}'' character should be used instead.
936 @end ifset
937
938
939
940 @c ****************************
941 @node Getting Started with GNAT
942 @chapter Getting Started with GNAT
943
944 @noindent
945 This chapter describes some simple ways of using GNAT to build
946 executable Ada programs.
947 @ifset unw
948 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
949 show how to use the command line environment.
950 @ref{Introduction to Glide and GVD}, provides a brief
951 introduction to the visually-oriented IDE for GNAT.
952 Supplementing Glide on some platforms is GPS, the
953 GNAT Programming System, which offers a richer graphical
954 ``look and feel'', enhanced configurability, support for
955 development in other programming language, comprehensive
956 browsing features, and many other capabilities.
957 For information on GPS please refer to
958 @cite{Using the GNAT Programming System}.
959 @end ifset
960
961 @menu
962 * Running GNAT::
963 * Running a Simple Ada Program::
964 * Running a Program with Multiple Units::
965 * Using the gnatmake Utility::
966 @ifset vms
967 * Editing with Emacs::
968 @end ifset
969 @ifclear vms
970 * Introduction to GPS::
971 * Introduction to Glide and GVD::
972 @end ifclear
973 @end menu
974
975 @node Running GNAT
976 @section Running GNAT
977
978 @noindent
979 Three steps are needed to create an executable file from an Ada source
980 file:
981
982 @enumerate
983 @item
984 The source file(s) must be compiled.
985 @item
986 The file(s) must be bound using the GNAT binder.
987 @item
988 All appropriate object files must be linked to produce an executable.
989 @end enumerate
990
991 @noindent
992 All three steps are most commonly handled by using the @code{gnatmake}
993 utility program that, given the name of the main program, automatically
994 performs the necessary compilation, binding and linking steps.
995
996
997 @node Running a Simple Ada Program
998 @section Running a Simple Ada Program
999
1000 @noindent
1001 Any text editor may be used to prepare an Ada program.
1002 @ifclear vms
1003 If @code{Glide} is
1004 used, the optional Ada mode may be helpful in laying out the program.
1005 @end ifclear
1006 The
1007 program text is a normal text file. We will suppose in our initial
1008 example that you have used your editor to prepare the following
1009 standard format text file:
1010
1011 @smallexample @c ada
1012 @cartouche
1013 with Ada.Text_IO; use Ada.Text_IO;
1014 procedure Hello is
1015 begin
1016    Put_Line ("Hello WORLD!");
1017 end Hello;
1018 @end cartouche
1019 @end smallexample
1020
1021 @noindent
1022 This file should be named @file{hello.adb}.
1023 With the normal default file naming conventions, GNAT requires
1024 that each file
1025 contain a single compilation unit whose file name is the
1026 unit name,
1027 with periods replaced by hyphens; the
1028 extension is @file{ads} for a
1029 spec and @file{adb} for a body.
1030 You can override this default file naming convention by use of the
1031 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1032 Alternatively, if you want to rename your files according to this default
1033 convention, which is probably more convenient if you will be using GNAT
1034 for all your compilations, then the @code{gnatchop} utility
1035 can be used to generate correctly-named source files
1036 (@pxref{Renaming Files Using gnatchop}).
1037
1038 You can compile the program using the following command (@code{$} is used
1039 as the command prompt in the examples in this document):
1040
1041 @smallexample
1042 $ gcc -c hello.adb
1043 @end smallexample
1044
1045 @noindent
1046 @code{gcc} is the command used to run the compiler. This compiler is
1047 capable of compiling programs in several languages, including Ada 95 and
1048 C. It assumes that you have given it an Ada program if the file extension is
1049 either @file{.ads} or @file{.adb}, and it will then call
1050 the GNAT compiler to compile the specified file.
1051
1052 @ifclear vms
1053 The @option{-c} switch is required. It tells @command{gcc} to only do a
1054 compilation. (For C programs, @command{gcc} can also do linking, but this
1055 capability is not used directly for Ada programs, so the @option{-c}
1056 switch must always be present.)
1057 @end ifclear
1058
1059 This compile command generates a file
1060 @file{hello.o}, which is the object
1061 file corresponding to your Ada program. It also generates
1062 an ``Ada Library Information'' file @file{hello.ali},
1063 which contains additional information used to check
1064 that an Ada program is consistent.
1065 To build an executable file,
1066 use @code{gnatbind} to bind the program
1067 and @code{gnatlink} to link it. The
1068 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1069 @file{ALI} file, but the default extension of @file{.ali} can
1070 be omitted. This means that in the most common case, the argument
1071 is simply the name of the main program:
1072
1073 @smallexample
1074 $ gnatbind hello
1075 $ gnatlink hello
1076 @end smallexample
1077
1078 @noindent
1079 A simpler method of carrying out these steps is to use
1080 @command{gnatmake},
1081 a master program that invokes all the required
1082 compilation, binding and linking tools in the correct order. In particular,
1083 @command{gnatmake} automatically recompiles any sources that have been
1084 modified since they were last compiled, or sources that depend
1085 on such modified sources, so that ``version skew'' is avoided.
1086 @cindex Version skew (avoided by @command{gnatmake})
1087
1088 @smallexample
1089 $ gnatmake hello.adb
1090 @end smallexample
1091
1092 @noindent
1093 The result is an executable program called @file{hello}, which can be
1094 run by entering:
1095
1096 @c The following should be removed (BMB 2001-01-23)
1097 @c @smallexample
1098 @c $ ^./hello^$ RUN HELLO^
1099 @c @end smallexample
1100
1101 @smallexample
1102 $ hello
1103 @end smallexample
1104
1105 @noindent
1106 assuming that the current directory is on the search path
1107 for executable programs.
1108
1109 @noindent
1110 and, if all has gone well, you will see
1111
1112 @smallexample
1113 Hello WORLD!
1114 @end smallexample
1115
1116 @noindent
1117 appear in response to this command.
1118
1119
1120 @c ****************************************
1121 @node Running a Program with Multiple Units
1122 @section Running a Program with Multiple Units
1123
1124 @noindent
1125 Consider a slightly more complicated example that has three files: a
1126 main program, and the spec and body of a package:
1127
1128 @smallexample @c ada
1129 @cartouche
1130 @group
1131 package Greetings is
1132    procedure Hello;
1133    procedure Goodbye;
1134 end Greetings;
1135
1136 with Ada.Text_IO; use Ada.Text_IO;
1137 package body Greetings is
1138    procedure Hello is
1139    begin
1140       Put_Line ("Hello WORLD!");
1141    end Hello;
1142
1143    procedure Goodbye is
1144    begin
1145       Put_Line ("Goodbye WORLD!");
1146    end Goodbye;
1147 end Greetings;
1148 @end group
1149
1150 @group
1151 with Greetings;
1152 procedure Gmain is
1153 begin
1154    Greetings.Hello;
1155    Greetings.Goodbye;
1156 end Gmain;
1157 @end group
1158 @end cartouche
1159 @end smallexample
1160
1161 @noindent
1162 Following the one-unit-per-file rule, place this program in the
1163 following three separate files:
1164
1165 @table @file
1166 @item greetings.ads
1167 spec of package @code{Greetings}
1168
1169 @item greetings.adb
1170 body of package @code{Greetings}
1171
1172 @item gmain.adb
1173 body of main program
1174 @end table
1175
1176 @noindent
1177 To build an executable version of
1178 this program, we could use four separate steps to compile, bind, and link
1179 the program, as follows:
1180
1181 @smallexample
1182 $ gcc -c gmain.adb
1183 $ gcc -c greetings.adb
1184 $ gnatbind gmain
1185 $ gnatlink gmain
1186 @end smallexample
1187
1188 @noindent
1189 Note that there is no required order of compilation when using GNAT.
1190 In particular it is perfectly fine to compile the main program first.
1191 Also, it is not necessary to compile package specs in the case where
1192 there is an accompanying body; you only need to compile the body. If you want
1193 to submit these files to the compiler for semantic checking and not code
1194 generation, then use the
1195 @option{-gnatc} switch:
1196
1197 @smallexample
1198 $ gcc -c greetings.ads -gnatc
1199 @end smallexample
1200
1201 @noindent
1202 Although the compilation can be done in separate steps as in the
1203 above example, in practice it is almost always more convenient
1204 to use the @code{gnatmake} tool. All you need to know in this case
1205 is the name of the main program's source file. The effect of the above four
1206 commands can be achieved with a single one:
1207
1208 @smallexample
1209 $ gnatmake gmain.adb
1210 @end smallexample
1211
1212 @noindent
1213 In the next section we discuss the advantages of using @code{gnatmake} in
1214 more detail.
1215
1216 @c *****************************
1217 @node Using the gnatmake Utility
1218 @section Using the @command{gnatmake} Utility
1219
1220 @noindent
1221 If you work on a program by compiling single components at a time using
1222 @code{gcc}, you typically keep track of the units you modify. In order to
1223 build a consistent system, you compile not only these units, but also any
1224 units that depend on the units you have modified.
1225 For example, in the preceding case,
1226 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1227 you edit @file{greetings.ads}, you must recompile both
1228 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1229 units that depend on @file{greetings.ads}.
1230
1231 @code{gnatbind} will warn you if you forget one of these compilation
1232 steps, so that it is impossible to generate an inconsistent program as a
1233 result of forgetting to do a compilation. Nevertheless it is tedious and
1234 error-prone to keep track of dependencies among units.
1235 One approach to handle the dependency-bookkeeping is to use a
1236 makefile. However, makefiles present maintenance problems of their own:
1237 if the dependencies change as you change the program, you must make
1238 sure that the makefile is kept up-to-date manually, which is also an
1239 error-prone process.
1240
1241 The @code{gnatmake} utility takes care of these details automatically.
1242 Invoke it using either one of the following forms:
1243
1244 @smallexample
1245 $ gnatmake gmain.adb
1246 $ gnatmake ^gmain^GMAIN^
1247 @end smallexample
1248
1249 @noindent
1250 The argument is the name of the file containing the main program;
1251 you may omit the extension. @code{gnatmake}
1252 examines the environment, automatically recompiles any files that need
1253 recompiling, and binds and links the resulting set of object files,
1254 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1255 In a large program, it
1256 can be extremely helpful to use @code{gnatmake}, because working out by hand
1257 what needs to be recompiled can be difficult.
1258
1259 Note that @code{gnatmake}
1260 takes into account all the Ada 95 rules that
1261 establish dependencies among units. These include dependencies that result
1262 from inlining subprogram bodies, and from
1263 generic instantiation. Unlike some other
1264 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1265 found by the compiler on a previous compilation, which may possibly
1266 be wrong when sources change. @code{gnatmake} determines the exact set of
1267 dependencies from scratch each time it is run.
1268
1269 @ifset vms
1270 @node Editing with Emacs
1271 @section Editing with Emacs
1272 @cindex Emacs
1273
1274 @noindent
1275 Emacs is an extensible self-documenting text editor that is available in a
1276 separate VMSINSTAL kit.
1277
1278 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1279 click on the Emacs Help menu and run the Emacs Tutorial.
1280 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1281 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1282
1283 Documentation on Emacs and other tools is available in Emacs under the
1284 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1285 use the middle mouse button to select a topic (e.g. Emacs).
1286
1287 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1288 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1289 get to the Emacs manual.
1290 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1291 prompt.
1292
1293 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1294 which is sufficiently extensible to provide for a complete programming
1295 environment and shell for the sophisticated user.
1296 @end ifset
1297
1298 @ifclear vms
1299 @node Introduction to GPS
1300 @section Introduction to GPS
1301 @cindex GPS (GNAT Programming System)
1302 @cindex GNAT Programming System (GPS)
1303 @noindent
1304 Although the command line interface (@command{gnatmake}, etc.) alone
1305 is sufficient, a graphical Interactive Development
1306 Environment can make it easier for you to compose, navigate, and debug
1307 programs.  This section describes the main features of GPS
1308 (``GNAT Programming System''), the GNAT graphical IDE.
1309 You will see how to use GPS to build and debug an executable, and
1310 you will also learn some of the basics of the GNAT ``project'' facility.
1311
1312 GPS enables you to do much more than is presented here;
1313 e.g., you can produce a call graph, interface to a third-party
1314 Version Control System, and inspect the generated assembly language
1315 for a program.
1316 Indeed, GPS also supports languages other than Ada.
1317 Such additional information, and an explanation of all of the GPS menu
1318 items. may be found in the on-line help, which includes
1319 a user's guide and a tutorial (these are also accessible from the GNAT
1320 startup menu).
1321
1322 @menu
1323 * Building a New Program with GPS::
1324 * Simple Debugging with GPS::
1325 @end menu
1326
1327
1328 @node Building a New Program with GPS
1329 @subsection Building a New Program with GPS
1330 @noindent
1331 GPS invokes the GNAT compilation tools using information
1332 contained in a @emph{project} (also known as a @emph{project file}):
1333 a collection of properties such
1334 as source directories, identities of main subprograms, tool switches, etc.,
1335 and their associated values.
1336 (See @ref{GNAT Project Manager}, for details.)
1337 In order to run GPS, you will need to either create a new project
1338 or else open an existing one.
1339
1340 This section will explain how you can use GPS to create a project,
1341 to associate Ada source files with a project, and to build and run
1342 programs.
1343
1344 @enumerate
1345 @item @emph{Creating a project}
1346
1347 Invoke GPS, either from the command line or the platform's IDE.
1348 After it starts, GPS will display a ``Welcome'' screen with three
1349 radio buttons:
1350
1351 @itemize @bullet
1352 @item
1353 @code{Start with default project in directory}
1354
1355 @item
1356 @code{Create new project with wizard}
1357
1358 @item
1359 @code{Open existing project}
1360 @end itemize
1361
1362 @noindent
1363 Select @code{Create new project with wizard} and press @code{OK}.
1364 A new window will appear.  In the text box labeled with
1365 @code{Enter the name of the project to create}, type @file{sample}
1366 as the project name.
1367 In the next box, browse to choose the directory in which you
1368 would like to create the project file.
1369 After selecting an appropriate directory, press @code{Forward}.
1370
1371 A window will appear with the title
1372 @code{Version Control System Configuration}.
1373 Simply press @code{Forward}.
1374
1375 A window will appear with the title
1376 @code{Please select the source directories for this project}.
1377 The directory that you specified for the project file will be selected
1378 by default as the one to use for sources; simply press @code{Forward}.
1379
1380 A window will appear with the title
1381 @code{Please select the build directory for this project}.
1382 The directory that you specified for the project file will be selected
1383 by default for object files and executables;
1384 simply press @code{Forward}.
1385
1386 A window will appear with the title
1387 @code{Please select the main units for this project}.
1388 You will supply this information later, after creating the source file.
1389 Simply press @code{Forward} for now.
1390
1391 A window will appear with the title
1392 @code{Please select the switches to build the project}.
1393 Press @code{Apply}.  This will create a project file named
1394 @file{sample.prj} in the directory that you had specified.
1395
1396 @item @emph{Creating and saving the source file}
1397
1398 After you create the new project, a GPS window will appear, which is
1399 partitioned into two main sections:
1400
1401 @itemize @bullet
1402 @item
1403 A @emph{Workspace area}, initially greyed out, which you will use for
1404 creating and editing source files
1405
1406 @item
1407 Directly below, a @emph{Messages area}, which initially displays a
1408 ``Welcome'' message.
1409 (If the Messages area is not visible, drag its border upward to expand it.)
1410 @end itemize
1411
1412 @noindent
1413 Select @code{File} on the menu bar, and then the @code{New} command.
1414 The Workspace area will become white, and you can now
1415 enter the source program explicitly.
1416 Type the following text
1417
1418 @smallexample @c ada
1419 @group
1420 with Ada.Text_IO; use Ada.Text_IO;
1421 procedure Hello is
1422 begin
1423   Put_Line("Hello from GPS!");
1424 end Hello;
1425 @end group
1426 @end smallexample
1427
1428 @noindent
1429 Select @code{File}, then @code{Save As}, and enter the source file name
1430 @file{hello.adb}.
1431 The file will be saved in the same directory you specified as the
1432 location of the default project file.
1433
1434
1435 @item @emph{Updating the project file}
1436
1437 You need to add the new source file to the project.
1438 To do this, select
1439 the @code{Project} menu and then @code{Edit project properties}.
1440 Click the @code{Main files} tab on the left, and then the
1441 @code{Add} button.
1442 Choose @file{hello.adb} from the list, and press @code{Open}.
1443 The project settings window will reflect this action.
1444 Click @code{OK}.
1445
1446 @item @emph{Building and running the program}
1447
1448 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1449 and select @file{hello.adb}.
1450 The Messages window will display the resulting invocations of @command{gcc},
1451 @command{gnatbind}, and @command{gnatlink}
1452 (reflecting the default switch settings from the
1453 project file that you created) and then a ``successful compilation/build''
1454 message.
1455
1456 To run the program, choose the @code{Build} menu, then @code{Run}, and
1457 select @command{hello}.
1458 An @emph{Arguments Selection} window will appear.
1459 There are no command line arguments, so just click @code{OK}.
1460
1461 The Messages window will now display the program's output (the string
1462 @code{Hello from GPS}), and at the bottom of the GPS window a status
1463 update is displayed (@code{Run: hello}).
1464 Close the GPS window (or select @code{File}, then @code{Exit}) to
1465 terminate this GPS session.
1466 @end enumerate
1467
1468
1469
1470 @node Simple Debugging with GPS
1471 @subsection Simple Debugging with GPS
1472 @noindent
1473 This section illustrates basic debugging techniques (setting breakpoints,
1474 examining/modifying variables, single stepping).
1475
1476 @enumerate
1477 @item @emph{Opening a project}
1478
1479 Start GPS and select @code{Open existing project}; browse to
1480 specify the project file @file{sample.prj} that you had created in the
1481 earlier example.
1482
1483 @item @emph{Creating a source file}
1484
1485 Select @code{File}, then @code{New}, and type in the following program:
1486
1487 @smallexample @c ada
1488 @group
1489 with Ada.Text_IO; use Ada.Text_IO;
1490 procedure Example is
1491    Line : String (1..80);
1492    N    : Natural;
1493 begin
1494    Put_Line("Type a line of text at each prompt; an empty line to exit");
1495    loop
1496       Put(": ");
1497       Get_Line (Line, N);
1498       Put_Line (Line (1..N) );
1499       exit when N=0;
1500    end loop;
1501 end Example;
1502 @end group
1503 @end smallexample
1504
1505 @noindent
1506 Select @code{File}, then @code{Save as}, and enter the file name
1507 @file{example.adb}.
1508
1509 @item @emph{Updating the project file}
1510
1511 Add @code{Example} as a new main unit for the project:
1512 @enumerate a
1513 @item
1514 Select @code{Project}, then @code{Edit Project Properties}.
1515
1516 @item
1517 Select the @code{Main files} tab, click @code{Add}, then
1518 select the file @file{example.adb} from the list, and
1519 click @code{Open}.
1520 You will see the file name appear in the list of main units
1521
1522 @item
1523 Click @code{OK}
1524 @end enumerate
1525
1526 @item @emph{Building/running the executable}
1527
1528 To build the executable
1529 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1530
1531 Run the program to see its effect (in the Messages area).
1532 Each line that you enter is displayed; an empty line will
1533 cause the loop to exit and the program to terminate.
1534
1535 @item @emph{Debugging the program}
1536
1537 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1538 which are required for debugging, are on by default when you create
1539 a new project.
1540 Thus unless you intentionally remove these settings, you will be able
1541 to debug any program that you develop using GPS.
1542
1543 @enumerate a
1544 @item @emph{Initializing}
1545
1546 Select @code{Debug}, then @code{Initialize}, then @file{example}
1547
1548 @item @emph{Setting a breakpoint}
1549
1550 After performing the initialization step, you will observe a small
1551 icon to the right of each line number.
1552 This serves as a toggle for breakpoints; clicking the icon will
1553 set a breakpoint at the corresponding line (the icon will change to
1554 a red circle with an ``x''), and clicking it again
1555 will remove the breakpoint / reset the icon.
1556
1557 For purposes of this example, set a breakpoint at line 10 (the
1558 statement @code{Put_Line@ (Line@ (1..N));}
1559
1560 @item @emph{Starting program execution}
1561
1562 Select @code{Debug}, then @code{Run}.  When the
1563 @code{Program Arguments} window appears, click @code{OK}.
1564 A console window will appear; enter some line of text,
1565 e.g. @code{abcde}, at the prompt.
1566 The program will pause execution when it gets to the
1567 breakpoint, and the corresponding line is highlighted.
1568
1569 @item @emph{Examining a variable}
1570
1571 Move the mouse over one of the occurrences of the variable @code{N}.
1572 You will see the value (5) displayed, in ``tool tip'' fashion.
1573 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1574 You will see information about @code{N} appear in the @code{Debugger Data}
1575 pane, showing the value as 5.
1576
1577
1578 @item @emph{Assigning a new value to a variable}
1579
1580 Right click on the @code{N} in the @code{Debugger Data} pane, and
1581 select @code{Set value of N}.
1582 When the input window appears, enter the value @code{4} and click
1583 @code{OK}.
1584 This value does not automatically appear in the @code{Debugger Data}
1585 pane; to see it, right click again on the @code{N} in the
1586 @code{Debugger Data} pane and select @code{Update value}.
1587 The new value, 4, will appear in red.
1588
1589 @item @emph{Single stepping}
1590
1591 Select @code{Debug}, then @code{Next}.
1592 This will cause the next statement to be executed, in this case the
1593 call of @code{Put_Line} with the string slice.
1594 Notice in the console window that the displayed string is simply
1595 @code{abcd} and not @code{abcde} which you had entered.
1596 This is because the upper bound of the slice is now 4 rather than 5.
1597
1598 @item @emph{Removing a breakpoint}
1599
1600 Toggle the breakpoint icon at line 10.
1601
1602 @item @emph{Resuming execution from a breakpoint}
1603
1604 Select @code{Debug}, then @code{Continue}.
1605 The program will reach the next iteration of the loop, and
1606 wait for input after displaying the prompt.
1607 This time, just hit the @kbd{Enter} key.
1608 The value of @code{N} will be 0, and the program will terminate.
1609 The console window will disappear.
1610 @end enumerate
1611 @end enumerate
1612
1613
1614 @node Introduction to Glide and GVD
1615 @section Introduction to Glide and GVD
1616 @cindex Glide
1617 @cindex GVD
1618 @noindent
1619 This section describes the main features of Glide,
1620 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1621 the GNU Visual Debugger.
1622 These tools may be present in addition to, or in place of, GPS on some
1623 platforms.
1624 Additional information on Glide and GVD may be found
1625 in the on-line help for these tools.
1626
1627 @menu
1628 * Building a New Program with Glide::
1629 * Simple Debugging with GVD::
1630 * Other Glide Features::
1631 @end menu
1632
1633 @node Building a New Program with Glide
1634 @subsection Building a New Program with Glide
1635 @noindent
1636 The simplest way to invoke Glide is to enter @command{glide}
1637 at the command prompt.  It will generally be useful to issue this
1638 as a background command, thus allowing you to continue using
1639 your command window for other purposes while Glide is running:
1640
1641 @smallexample
1642 $ glide&
1643 @end smallexample
1644
1645 @noindent
1646 Glide will start up with an initial screen displaying the top-level menu items
1647 as well as some other information.  The menu selections are as follows
1648 @itemize @bullet
1649 @item @code{Buffers}
1650 @item @code{Files}
1651 @item @code{Tools}
1652 @item @code{Edit}
1653 @item @code{Search}
1654 @item @code{Mule}
1655 @item @code{Glide}
1656 @item @code{Help}
1657 @end itemize
1658
1659 @noindent
1660 For this introductory example, you will need to create a new Ada source file.
1661 First, select the @code{Files} menu.  This will pop open a menu with around
1662 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1663 Depending on the platform, you may see a pop-up window where you can browse
1664 to an appropriate directory and then enter the file name, or else simply
1665 see a line at the bottom of the Glide window where you can likewise enter
1666 the file name.  Note that in Glide, when you attempt to open a non-existent
1667 file, the effect is to create a file with that name.  For this example enter
1668 @file{hello.adb} as the name of the file.
1669
1670 A new buffer will now appear, occupying the entire Glide window,
1671 with the file name at the top.  The menu selections are slightly different
1672 from the ones you saw on the opening screen; there is an @code{Entities} item,
1673 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1674 the file extension to identify the source language, so @file{adb} indicates
1675 an Ada source file.
1676
1677 You will enter some of the source program lines explicitly,
1678 and use the syntax-oriented template mechanism to enter other lines.
1679 First, type the following text:
1680 @smallexample
1681 with Ada.Text_IO; use Ada.Text_IO;
1682 procedure Hello is
1683 begin
1684 @end smallexample
1685
1686 @noindent
1687 Observe that Glide uses different colors to distinguish reserved words from
1688 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1689 automatically indented in anticipation of declarations.  When you enter
1690 @code{begin}, Glide recognizes that there are no declarations and thus places
1691 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1692 indented, where the statement(s) will be placed.
1693
1694 The main part of the program will be a @code{for} loop.  Instead of entering
1695 the text explicitly, however, use a statement template.  Select the @code{Ada}
1696 item on the top menu bar, move the mouse to the @code{Statements} item,
1697 and you will see a large selection of alternatives.  Choose @code{for loop}.
1698 You will be prompted (at the bottom of the buffer) for a loop name;
1699 simply press the @key{Enter} key since a loop name is not needed.
1700 You should see the beginning of a @code{for} loop appear in the source
1701 program window.  You will now be prompted for the name of the loop variable;
1702 enter a line with the identifier @code{ind} (lower case).  Note that,
1703 by default, Glide capitalizes the name (you can override such behavior
1704 if you wish, although this is outside the scope of this introduction).
1705 Next, Glide prompts you for the loop range; enter a line containing
1706 @code{1..5} and you will see this also appear in the source program,
1707 together with the remaining elements of the @code{for} loop syntax.
1708
1709 Next enter the statement (with an intentional error, a missing semicolon)
1710 that will form the body of the loop:
1711 @smallexample
1712 Put_Line("Hello, World" & Integer'Image(I))
1713 @end smallexample
1714
1715 @noindent
1716 Finally, type @code{end Hello;} as the last line in the program.
1717 Now save the file: choose the @code{File} menu item, and then the
1718 @code{Save buffer} selection.  You will see a message at the bottom
1719 of the buffer confirming that the file has been saved.
1720
1721 You are now ready to attempt to build the program.  Select the @code{Ada}
1722 item from the top menu bar.  Although we could choose simply to compile
1723 the file, we will instead attempt to do a build (which invokes
1724 @command{gnatmake}) since, if the compile is successful, we want to build
1725 an executable.  Thus select @code{Ada build}.  This will fail because of the
1726 compilation error, and you will notice that the Glide window has been split:
1727 the top window contains the source file, and the bottom window contains the
1728 output from the GNAT tools. Glide allows you to navigate from a compilation
1729 error to the source file position corresponding to the error: click the
1730 middle mouse button (or simultaneously press the left and right buttons,
1731 on a two-button mouse) on the diagnostic line in the tool window.  The
1732 focus will shift to the source window, and the cursor will be positioned
1733 on the character at which the error was detected.
1734
1735 Correct the error: type in a semicolon to terminate the statement.
1736 Although you can again save the file explicitly, you can also simply invoke
1737 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1738 This time the build will succeed; the tool output window shows you the
1739 options that are supplied by default.  The GNAT tools' output (e.g.
1740 object and ALI files, executable) will go in the directory from which
1741 Glide was launched.
1742
1743 To execute the program, choose @code{Ada} and then @code{Run}.
1744 You should see the program's output displayed in the bottom window:
1745
1746 @smallexample
1747 Hello, world 1
1748 Hello, world 2
1749 Hello, world 3
1750 Hello, world 4
1751 Hello, world 5
1752 @end smallexample
1753
1754 @node Simple Debugging with GVD
1755 @subsection Simple Debugging with GVD
1756
1757 @noindent
1758 This section describes how to set breakpoints, examine/modify variables,
1759 and step through execution.
1760
1761 In order to enable debugging, you need to pass the @option{-g} switch
1762 to both the compiler and to @command{gnatlink}.  If you are using
1763 the command line, passing @option{-g} to @command{gnatmake} will have
1764 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1765 by issuing the command:
1766
1767 @smallexample
1768 $ gvd hello
1769 @end smallexample
1770
1771 @noindent
1772 If you are using Glide, then @option{-g} is passed to the relevant tools
1773 by default when you do a build.  Start the debugger by selecting the
1774 @code{Ada} menu item, and then @code{Debug}.
1775
1776 GVD comes up in a multi-part window.  One pane shows the names of files
1777 comprising your executable; another pane shows the source code of the current
1778 unit (initially your main subprogram), another pane shows the debugger output
1779 and user interactions, and the fourth pane (the data canvas at the top
1780 of the window) displays data objects that you have selected.
1781
1782 To the left of the source file pane, you will notice green dots adjacent
1783 to some lines.  These are lines for which object code exists and where
1784 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1785 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1786 in a red circle.  Clicking the circle toggles the breakpoint off,
1787 and the red circle is replaced by the green dot.
1788
1789 For this example, set a breakpoint at the statement where @code{Put_Line}
1790 is invoked.
1791
1792 Start program execution by selecting the @code{Run} button on the top menu bar.
1793 (The @code{Start} button will also start your program, but it will
1794 cause program execution to break at the entry to your main subprogram.)
1795 Evidence of reaching the breakpoint will appear: the source file line will be
1796 highlighted, and the debugger interactions pane will display
1797 a relevant message.
1798
1799 You can examine the values of variables in several ways.  Move the mouse
1800 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1801 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1802 and select @code{Display Ind}; a box showing the variable's name and value
1803 will appear in the data canvas.
1804
1805 Although a loop index is a constant with respect to Ada semantics,
1806 you can change its value in the debugger.  Right-click in the box
1807 for @code{Ind}, and select the @code{Set Value of Ind} item.
1808 Enter @code{2} as the new value, and press @command{OK}.
1809 The box for @code{Ind} shows the update.
1810
1811 Press the @code{Step} button on the top menu bar; this will step through
1812 one line of program text (the invocation of @code{Put_Line}), and you can
1813 observe the effect of having modified @code{Ind} since the value displayed
1814 is @code{2}.
1815
1816 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1817 button.  You will see the remaining output lines displayed in the debugger
1818 interaction window, along with a message confirming normal program
1819 termination.
1820
1821 @node Other Glide Features
1822 @subsection Other Glide Features
1823
1824 @noindent
1825 You may have observed that some of the menu selections contain abbreviations;
1826 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1827 These are @emph{shortcut keys} that you can use instead of selecting
1828 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1829 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1830 of selecting @code{Files} and then @code{Open file...}.
1831
1832 To abort a Glide command, type @key{Ctrl-g}.
1833
1834 If you want Glide to start with an existing source file, you can either
1835 launch Glide as above and then open the file via @code{Files} @result{}
1836 @code{Open file...}, or else simply pass the name of the source file
1837 on the command line:
1838
1839 @smallexample
1840 $ glide hello.adb&
1841 @end smallexample
1842
1843 @noindent
1844 While you are using Glide, a number of @emph{buffers} exist.
1845 You create some explicitly; e.g., when you open/create a file.
1846 Others arise as an effect of the commands that you issue; e.g., the buffer
1847 containing the output of the tools invoked during a build.  If a buffer
1848 is hidden, you can bring it into a visible window by first opening
1849 the @code{Buffers} menu and then selecting the desired entry.
1850
1851 If a buffer occupies only part of the Glide screen and you want to expand it
1852 to fill the entire screen, then click in the buffer and then select
1853 @code{Files} @result{} @code{One Window}.
1854
1855 If a window is occupied by one buffer and you want to split the window
1856 to bring up a second buffer, perform the following steps:
1857 @itemize @bullet
1858 @item Select @code{Files} @result{} @code{Split Window};
1859 this will produce two windows each of which holds the original buffer
1860 (these are not copies, but rather different views of the same buffer contents)
1861
1862 @item With the focus in one of the windows,
1863 select the desired buffer from the @code{Buffers} menu
1864 @end itemize
1865
1866 @noindent
1867 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1868 @end ifclear
1869
1870 @node The GNAT Compilation Model
1871 @chapter The GNAT Compilation Model
1872 @cindex GNAT compilation model
1873 @cindex Compilation model
1874
1875 @menu
1876 * Source Representation::
1877 * Foreign Language Representation::
1878 * File Naming Rules::
1879 * Using Other File Names::
1880 * Alternative File Naming Schemes::
1881 * Generating Object Files::
1882 * Source Dependencies::
1883 * The Ada Library Information Files::
1884 * Binding an Ada Program::
1885 * Mixed Language Programming::
1886 * Building Mixed Ada & C++ Programs::
1887 * Comparison between GNAT and C/C++ Compilation Models::
1888 * Comparison between GNAT and Conventional Ada Library Models::
1889 @ifset vms
1890 * Placement of temporary files::
1891 @end ifset
1892 @end menu
1893
1894 @noindent
1895 This chapter describes the compilation model used by GNAT. Although
1896 similar to that used by other languages, such as C and C++, this model
1897 is substantially different from the traditional Ada compilation models,
1898 which are based on a library. The model is initially described without
1899 reference to the library-based model. If you have not previously used an
1900 Ada compiler, you need only read the first part of this chapter. The
1901 last section describes and discusses the differences between the GNAT
1902 model and the traditional Ada compiler models. If you have used other
1903 Ada compilers, this section will help you to understand those
1904 differences, and the advantages of the GNAT model.
1905
1906 @node Source Representation
1907 @section Source Representation
1908 @cindex Latin-1
1909
1910 @noindent
1911 Ada source programs are represented in standard text files, using
1912 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1913 7-bit ASCII set, plus additional characters used for
1914 representing foreign languages (@pxref{Foreign Language Representation}
1915 for support of non-USA character sets). The format effector characters
1916 are represented using their standard ASCII encodings, as follows:
1917
1918 @table @code
1919 @item VT
1920 @findex VT
1921 Vertical tab, @code{16#0B#}
1922
1923 @item HT
1924 @findex HT
1925 Horizontal tab, @code{16#09#}
1926
1927 @item CR
1928 @findex CR
1929 Carriage return, @code{16#0D#}
1930
1931 @item LF
1932 @findex LF
1933 Line feed, @code{16#0A#}
1934
1935 @item FF
1936 @findex FF
1937 Form feed, @code{16#0C#}
1938 @end table
1939
1940 @noindent
1941 Source files are in standard text file format. In addition, GNAT will
1942 recognize a wide variety of stream formats, in which the end of physical
1943 physical lines is marked by any of the following sequences:
1944 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1945 in accommodating files that are imported from other operating systems.
1946
1947 @cindex End of source file
1948 @cindex Source file, end
1949 @findex SUB
1950 The end of a source file is normally represented by the physical end of
1951 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1952 recognized as signalling the end of the source file. Again, this is
1953 provided for compatibility with other operating systems where this
1954 code is used to represent the end of file.
1955
1956 Each file contains a single Ada compilation unit, including any pragmas
1957 associated with the unit. For example, this means you must place a
1958 package declaration (a package @dfn{spec}) and the corresponding body in
1959 separate files. An Ada @dfn{compilation} (which is a sequence of
1960 compilation units) is represented using a sequence of files. Similarly,
1961 you will place each subunit or child unit in a separate file.
1962
1963 @node Foreign Language Representation
1964 @section Foreign Language Representation
1965
1966 @noindent
1967 GNAT supports the standard character sets defined in Ada 95 as well as
1968 several other non-standard character sets for use in localized versions
1969 of the compiler (@pxref{Character Set Control}).
1970 @menu
1971 * Latin-1::
1972 * Other 8-Bit Codes::
1973 * Wide Character Encodings::
1974 @end menu
1975
1976 @node Latin-1
1977 @subsection Latin-1
1978 @cindex Latin-1
1979
1980 @noindent
1981 The basic character set is Latin-1. This character set is defined by ISO
1982 standard 8859, part 1. The lower half (character codes @code{16#00#}
1983 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1984 is used to represent additional characters. These include extended letters
1985 used by European languages, such as French accents, the vowels with umlauts
1986 used in German, and the extra letter A-ring used in Swedish.
1987
1988 @findex Ada.Characters.Latin_1
1989 For a complete list of Latin-1 codes and their encodings, see the source
1990 file of library unit @code{Ada.Characters.Latin_1} in file
1991 @file{a-chlat1.ads}.
1992 You may use any of these extended characters freely in character or
1993 string literals. In addition, the extended characters that represent
1994 letters can be used in identifiers.
1995
1996 @node Other 8-Bit Codes
1997 @subsection Other 8-Bit Codes
1998
1999 @noindent
2000 GNAT also supports several other 8-bit coding schemes:
2001
2002 @table @asis
2003 @item ISO 8859-2 (Latin-2)
2004 @cindex Latin-2
2005 @cindex ISO 8859-2
2006 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2008
2009 @item ISO 8859-3 (Latin-3)
2010 @cindex Latin-3
2011 @cindex ISO 8859-3
2012 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2014
2015 @item ISO 8859-4 (Latin-4)
2016 @cindex Latin-4
2017 @cindex ISO 8859-4
2018 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2019 equivalence.
2020
2021 @item ISO 8859-5 (Cyrillic)
2022 @cindex ISO 8859-5
2023 @cindex Cyrillic
2024 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2025 lowercase equivalence.
2026
2027 @item ISO 8859-15 (Latin-9)
2028 @cindex ISO 8859-15
2029 @cindex Latin-9
2030 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2031 lowercase equivalence
2032
2033 @item IBM PC (code page 437)
2034 @cindex code page 437
2035 This code page is the normal default for PCs in the U.S. It corresponds
2036 to the original IBM PC character set. This set has some, but not all, of
2037 the extended Latin-1 letters, but these letters do not have the same
2038 encoding as Latin-1. In this mode, these letters are allowed in
2039 identifiers with uppercase and lowercase equivalence.
2040
2041 @item IBM PC (code page 850)
2042 @cindex code page 850
2043 This code page is a modification of 437 extended to include all the
2044 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2045 mode, all these letters are allowed in identifiers with uppercase and
2046 lowercase equivalence.
2047
2048 @item Full Upper 8-bit
2049 Any character in the range 80-FF allowed in identifiers, and all are
2050 considered distinct. In other words, there are no uppercase and lowercase
2051 equivalences in this range. This is useful in conjunction with
2052 certain encoding schemes used for some foreign character sets (e.g.
2053 the typical method of representing Chinese characters on the PC).
2054
2055 @item No Upper-Half
2056 No upper-half characters in the range 80-FF are allowed in identifiers.
2057 This gives Ada 83 compatibility for identifier names.
2058 @end table
2059
2060 @noindent
2061 For precise data on the encodings permitted, and the uppercase and lowercase
2062 equivalences that are recognized, see the file @file{csets.adb} in
2063 the GNAT compiler sources. You will need to obtain a full source release
2064 of GNAT to obtain this file.
2065
2066 @node Wide Character Encodings
2067 @subsection Wide Character Encodings
2068
2069 @noindent
2070 GNAT allows wide character codes to appear in character and string
2071 literals, and also optionally in identifiers, by means of the following
2072 possible encoding schemes:
2073
2074 @table @asis
2075
2076 @item Hex Coding
2077 In this encoding, a wide character is represented by the following five
2078 character sequence:
2079
2080 @smallexample
2081 ESC a b c d
2082 @end smallexample
2083
2084 @noindent
2085 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2086 characters (using uppercase letters) of the wide character code. For
2087 example, ESC A345 is used to represent the wide character with code
2088 @code{16#A345#}.
2089 This scheme is compatible with use of the full Wide_Character set.
2090
2091 @item Upper-Half Coding
2092 @cindex Upper-Half Coding
2093 The wide character with encoding @code{16#abcd#} where the upper bit is on
2094 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2095 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2096 character, but is not required to be in the upper half. This method can
2097 be also used for shift-JIS or EUC, where the internal coding matches the
2098 external coding.
2099
2100 @item Shift JIS Coding
2101 @cindex Shift JIS Coding
2102 A wide character is represented by a two-character sequence,
2103 @code{16#ab#} and
2104 @code{16#cd#}, with the restrictions described for upper-half encoding as
2105 described above. The internal character code is the corresponding JIS
2106 character according to the standard algorithm for Shift-JIS
2107 conversion. Only characters defined in the JIS code set table can be
2108 used with this encoding method.
2109
2110 @item EUC Coding
2111 @cindex EUC Coding
2112 A wide character is represented by a two-character sequence
2113 @code{16#ab#} and
2114 @code{16#cd#}, with both characters being in the upper half. The internal
2115 character code is the corresponding JIS character according to the EUC
2116 encoding algorithm. Only characters defined in the JIS code set table
2117 can be used with this encoding method.
2118
2119 @item UTF-8 Coding
2120 A wide character is represented using
2121 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2122 10646-1/Am.2. Depending on the character value, the representation
2123 is a one, two, or three byte sequence:
2124 @smallexample
2125 @iftex
2126 @leftskip=.7cm
2127 @end iftex
2128 16#0000#-16#007f#: 2#0xxxxxxx#
2129 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2130 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2131
2132 @end smallexample
2133
2134 @noindent
2135 where the xxx bits correspond to the left-padded bits of the
2136 16-bit character value. Note that all lower half ASCII characters
2137 are represented as ASCII bytes and all upper half characters and
2138 other wide characters are represented as sequences of upper-half
2139 (The full UTF-8 scheme allows for encoding 31-bit characters as
2140 6-byte sequences, but in this implementation, all UTF-8 sequences
2141 of four or more bytes length will be treated as illegal).
2142 @item Brackets Coding
2143 In this encoding, a wide character is represented by the following eight
2144 character sequence:
2145
2146 @smallexample
2147 [ " a b c d " ]
2148 @end smallexample
2149
2150 @noindent
2151 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2152 characters (using uppercase letters) of the wide character code. For
2153 example, [``A345''] is used to represent the wide character with code
2154 @code{16#A345#}. It is also possible (though not required) to use the
2155 Brackets coding for upper half characters. For example, the code
2156 @code{16#A3#} can be represented as @code{[``A3'']}.
2157
2158 This scheme is compatible with use of the full Wide_Character set,
2159 and is also the method used for wide character encoding in the standard
2160 ACVC (Ada Compiler Validation Capability) test suite distributions.
2161
2162 @end table
2163
2164 @noindent
2165 Note: Some of these coding schemes do not permit the full use of the
2166 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2167 use of the upper half of the Latin-1 set.
2168
2169 @node File Naming Rules
2170 @section File Naming Rules
2171
2172 @noindent
2173 The default file name is determined by the name of the unit that the
2174 file contains. The name is formed by taking the full expanded name of
2175 the unit and replacing the separating dots with hyphens and using
2176 ^lowercase^uppercase^ for all letters.
2177
2178 An exception arises if the file name generated by the above rules starts
2179 with one of the characters
2180 @ifset vms
2181 A,G,I, or S,
2182 @end ifset
2183 @ifclear vms
2184 a,g,i, or s,
2185 @end ifclear
2186 and the second character is a
2187 minus. In this case, the character ^tilde^dollar sign^ is used in place
2188 of the minus. The reason for this special rule is to avoid clashes with
2189 the standard names for child units of the packages System, Ada,
2190 Interfaces, and GNAT, which use the prefixes
2191 @ifset vms
2192 S- A- I- and G-
2193 @end ifset
2194 @ifclear vms
2195 s- a- i- and g-
2196 @end ifclear
2197 respectively.
2198
2199 The file extension is @file{.ads} for a spec and
2200 @file{.adb} for a body. The following list shows some
2201 examples of these rules.
2202
2203 @table @file
2204 @item main.ads
2205 Main (spec)
2206 @item main.adb
2207 Main (body)
2208 @item arith_functions.ads
2209 Arith_Functions (package spec)
2210 @item arith_functions.adb
2211 Arith_Functions (package body)
2212 @item func-spec.ads
2213 Func.Spec (child package spec)
2214 @item func-spec.adb
2215 Func.Spec (child package body)
2216 @item main-sub.adb
2217 Sub (subunit of Main)
2218 @item ^a~bad.adb^A$BAD.ADB^
2219 A.Bad (child package body)
2220 @end table
2221
2222 @noindent
2223 Following these rules can result in excessively long
2224 file names if corresponding
2225 unit names are long (for example, if child units or subunits are
2226 heavily nested). An option is available to shorten such long file names
2227 (called file name ``krunching''). This may be particularly useful when
2228 programs being developed with GNAT are to be used on operating systems
2229 with limited file name lengths. @xref{Using gnatkr}.
2230
2231 Of course, no file shortening algorithm can guarantee uniqueness over
2232 all possible unit names; if file name krunching is used, it is your
2233 responsibility to ensure no name clashes occur. Alternatively you
2234 can specify the exact file names that you want used, as described
2235 in the next section. Finally, if your Ada programs are migrating from a
2236 compiler with a different naming convention, you can use the gnatchop
2237 utility to produce source files that follow the GNAT naming conventions.
2238 (For details @pxref{Renaming Files Using gnatchop}.)
2239
2240 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2241 systems, case is not significant. So for example on @code{Windows XP}
2242 if the canonical name is @code{main-sub.adb}, you can use the file name
2243 @code{Main-Sub.adb} instead. However, case is significant for other
2244 operating systems, so for example, if you want to use other than
2245 canonically cased file names on a Unix system, you need to follow
2246 the procedures described in the next section.
2247
2248 @node Using Other File Names
2249 @section Using Other File Names
2250 @cindex File names
2251
2252 @noindent
2253 In the previous section, we have described the default rules used by
2254 GNAT to determine the file name in which a given unit resides. It is
2255 often convenient to follow these default rules, and if you follow them,
2256 the compiler knows without being explicitly told where to find all
2257 the files it needs.
2258
2259 However, in some cases, particularly when a program is imported from
2260 another Ada compiler environment, it may be more convenient for the
2261 programmer to specify which file names contain which units. GNAT allows
2262 arbitrary file names to be used by means of the Source_File_Name pragma.
2263 The form of this pragma is as shown in the following examples:
2264 @cindex Source_File_Name pragma
2265
2266 @smallexample @c ada
2267 @cartouche
2268 pragma Source_File_Name (My_Utilities.Stacks,
2269   Spec_File_Name => "myutilst_a.ada");
2270 pragma Source_File_name (My_Utilities.Stacks,
2271   Body_File_Name => "myutilst.ada");
2272 @end cartouche
2273 @end smallexample
2274
2275 @noindent
2276 As shown in this example, the first argument for the pragma is the unit
2277 name (in this example a child unit). The second argument has the form
2278 of a named association. The identifier
2279 indicates whether the file name is for a spec or a body;
2280 the file name itself is given by a string literal.
2281
2282 The source file name pragma is a configuration pragma, which means that
2283 normally it will be placed in the @file{gnat.adc}
2284 file used to hold configuration
2285 pragmas that apply to a complete compilation environment.
2286 For more details on how the @file{gnat.adc} file is created and used
2287 @pxref{Handling of Configuration Pragmas}
2288 @cindex @file{gnat.adc}
2289
2290 @ifclear vms
2291 GNAT allows completely arbitrary file names to be specified using the
2292 source file name pragma. However, if the file name specified has an
2293 extension other than @file{.ads} or @file{.adb} it is necessary to use
2294 a special syntax when compiling the file. The name in this case must be
2295 preceded by the special sequence @code{-x} followed by a space and the name
2296 of the language, here @code{ada}, as in:
2297
2298 @smallexample
2299 $ gcc -c -x ada peculiar_file_name.sim
2300 @end smallexample
2301 @end ifclear
2302
2303 @noindent
2304 @code{gnatmake} handles non-standard file names in the usual manner (the
2305 non-standard file name for the main program is simply used as the
2306 argument to gnatmake). Note that if the extension is also non-standard,
2307 then it must be included in the gnatmake command, it may not be omitted.
2308
2309 @node Alternative File Naming Schemes
2310 @section Alternative File Naming Schemes
2311 @cindex File naming schemes, alternative
2312 @cindex File names
2313
2314 In the previous section, we described the use of the @code{Source_File_Name}
2315 pragma to allow arbitrary names to be assigned to individual source files.
2316 However, this approach requires one pragma for each file, and especially in
2317 large systems can result in very long @file{gnat.adc} files, and also create
2318 a maintenance problem.
2319
2320 GNAT also provides a facility for specifying systematic file naming schemes
2321 other than the standard default naming scheme previously described. An
2322 alternative scheme for naming is specified by the use of
2323 @code{Source_File_Name} pragmas having the following format:
2324 @cindex Source_File_Name pragma
2325
2326 @smallexample @c ada
2327 pragma Source_File_Name (
2328    Spec_File_Name  => FILE_NAME_PATTERN
2329  [,Casing          => CASING_SPEC]
2330  [,Dot_Replacement => STRING_LITERAL]);
2331
2332 pragma Source_File_Name (
2333    Body_File_Name  => FILE_NAME_PATTERN
2334  [,Casing          => CASING_SPEC]
2335  [,Dot_Replacement => STRING_LITERAL]);
2336
2337 pragma Source_File_Name (
2338    Subunit_File_Name  => FILE_NAME_PATTERN
2339  [,Casing             => CASING_SPEC]
2340  [,Dot_Replacement    => STRING_LITERAL]);
2341
2342 FILE_NAME_PATTERN ::= STRING_LITERAL
2343 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2344 @end smallexample
2345
2346 @noindent
2347 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2348 It contains a single asterisk character, and the unit name is substituted
2349 systematically for this asterisk. The optional parameter
2350 @code{Casing} indicates
2351 whether the unit name is to be all upper-case letters, all lower-case letters,
2352 or mixed-case. If no
2353 @code{Casing} parameter is used, then the default is all
2354 ^lower-case^upper-case^.
2355
2356 The optional @code{Dot_Replacement} string is used to replace any periods
2357 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2358 argument is used then separating dots appear unchanged in the resulting
2359 file name.
2360 Although the above syntax indicates that the
2361 @code{Casing} argument must appear
2362 before the @code{Dot_Replacement} argument, but it
2363 is also permissible to write these arguments in the opposite order.
2364
2365 As indicated, it is possible to specify different naming schemes for
2366 bodies, specs, and subunits. Quite often the rule for subunits is the
2367 same as the rule for bodies, in which case, there is no need to give
2368 a separate @code{Subunit_File_Name} rule, and in this case the
2369 @code{Body_File_name} rule is used for subunits as well.
2370
2371 The separate rule for subunits can also be used to implement the rather
2372 unusual case of a compilation environment (e.g. a single directory) which
2373 contains a subunit and a child unit with the same unit name. Although
2374 both units cannot appear in the same partition, the Ada Reference Manual
2375 allows (but does not require) the possibility of the two units coexisting
2376 in the same environment.
2377
2378 The file name translation works in the following steps:
2379
2380 @itemize @bullet
2381
2382 @item
2383 If there is a specific @code{Source_File_Name} pragma for the given unit,
2384 then this is always used, and any general pattern rules are ignored.
2385
2386 @item
2387 If there is a pattern type @code{Source_File_Name} pragma that applies to
2388 the unit, then the resulting file name will be used if the file exists. If
2389 more than one pattern matches, the latest one will be tried first, and the
2390 first attempt resulting in a reference to a file that exists will be used.
2391
2392 @item
2393 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2394 for which the corresponding file exists, then the standard GNAT default
2395 naming rules are used.
2396
2397 @end itemize
2398
2399 @noindent
2400 As an example of the use of this mechanism, consider a commonly used scheme
2401 in which file names are all lower case, with separating periods copied
2402 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2403 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2404 two pragmas appear:
2405
2406 @smallexample @c ada
2407 pragma Source_File_Name
2408   (Spec_File_Name => "*.1.ada");
2409 pragma Source_File_Name
2410   (Body_File_Name => "*.2.ada");
2411 @end smallexample
2412
2413 @noindent
2414 The default GNAT scheme is actually implemented by providing the following
2415 default pragmas internally:
2416
2417 @smallexample @c ada
2418 pragma Source_File_Name
2419   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2420 pragma Source_File_Name
2421   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2422 @end smallexample
2423
2424 @noindent
2425 Our final example implements a scheme typically used with one of the
2426 Ada 83 compilers, where the separator character for subunits was ``__''
2427 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2428 by adding @file{.ADA}, and subunits by
2429 adding @file{.SEP}. All file names were
2430 upper case. Child units were not present of course since this was an
2431 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2432 the same double underscore separator for child units.
2433
2434 @smallexample @c ada
2435 pragma Source_File_Name
2436   (Spec_File_Name => "*_.ADA",
2437    Dot_Replacement => "__",
2438    Casing = Uppercase);
2439 pragma Source_File_Name
2440   (Body_File_Name => "*.ADA",
2441    Dot_Replacement => "__",
2442    Casing = Uppercase);
2443 pragma Source_File_Name
2444   (Subunit_File_Name => "*.SEP",
2445    Dot_Replacement => "__",
2446    Casing = Uppercase);
2447 @end smallexample
2448
2449 @node Generating Object Files
2450 @section Generating Object Files
2451
2452 @noindent
2453 An Ada program consists of a set of source files, and the first step in
2454 compiling the program is to generate the corresponding object files.
2455 These are generated by compiling a subset of these source files.
2456 The files you need to compile are the following:
2457
2458 @itemize @bullet
2459 @item
2460 If a package spec has no body, compile the package spec to produce the
2461 object file for the package.
2462
2463 @item
2464 If a package has both a spec and a body, compile the body to produce the
2465 object file for the package. The source file for the package spec need
2466 not be compiled in this case because there is only one object file, which
2467 contains the code for both the spec and body of the package.
2468
2469 @item
2470 For a subprogram, compile the subprogram body to produce the object file
2471 for the subprogram. The spec, if one is present, is as usual in a
2472 separate file, and need not be compiled.
2473
2474 @item
2475 @cindex Subunits
2476 In the case of subunits, only compile the parent unit. A single object
2477 file is generated for the entire subunit tree, which includes all the
2478 subunits.
2479
2480 @item
2481 Compile child units independently of their parent units
2482 (though, of course, the spec of all the ancestor unit must be present in order
2483 to compile a child unit).
2484
2485 @item
2486 @cindex Generics
2487 Compile generic units in the same manner as any other units. The object
2488 files in this case are small dummy files that contain at most the
2489 flag used for elaboration checking. This is because GNAT always handles generic
2490 instantiation by means of macro expansion. However, it is still necessary to
2491 compile generic units, for dependency checking and elaboration purposes.
2492 @end itemize
2493
2494 @noindent
2495 The preceding rules describe the set of files that must be compiled to
2496 generate the object files for a program. Each object file has the same
2497 name as the corresponding source file, except that the extension is
2498 @file{.o} as usual.
2499
2500 You may wish to compile other files for the purpose of checking their
2501 syntactic and semantic correctness. For example, in the case where a
2502 package has a separate spec and body, you would not normally compile the
2503 spec. However, it is convenient in practice to compile the spec to make
2504 sure it is error-free before compiling clients of this spec, because such
2505 compilations will fail if there is an error in the spec.
2506
2507 GNAT provides an option for compiling such files purely for the
2508 purposes of checking correctness; such compilations are not required as
2509 part of the process of building a program. To compile a file in this
2510 checking mode, use the @option{-gnatc} switch.
2511
2512 @node Source Dependencies
2513 @section Source Dependencies
2514
2515 @noindent
2516 A given object file clearly depends on the source file which is compiled
2517 to produce it. Here we are using @dfn{depends} in the sense of a typical
2518 @code{make} utility; in other words, an object file depends on a source
2519 file if changes to the source file require the object file to be
2520 recompiled.
2521 In addition to this basic dependency, a given object may depend on
2522 additional source files as follows:
2523
2524 @itemize @bullet
2525 @item
2526 If a file being compiled @code{with}'s a unit @var{X}, the object file
2527 depends on the file containing the spec of unit @var{X}. This includes
2528 files that are @code{with}'ed implicitly either because they are parents
2529 of @code{with}'ed child units or they are run-time units required by the
2530 language constructs used in a particular unit.
2531
2532 @item
2533 If a file being compiled instantiates a library level generic unit, the
2534 object file depends on both the spec and body files for this generic
2535 unit.
2536
2537 @item
2538 If a file being compiled instantiates a generic unit defined within a
2539 package, the object file depends on the body file for the package as
2540 well as the spec file.
2541
2542 @item
2543 @findex Inline
2544 @cindex @option{-gnatn} switch
2545 If a file being compiled contains a call to a subprogram for which
2546 pragma @code{Inline} applies and inlining is activated with the
2547 @option{-gnatn} switch, the object file depends on the file containing the
2548 body of this subprogram as well as on the file containing the spec. Note
2549 that for inlining to actually occur as a result of the use of this switch,
2550 it is necessary to compile in optimizing mode.
2551
2552 @cindex @option{-gnatN} switch
2553 The use of @option{-gnatN} activates a more extensive inlining optimization
2554 that is performed by the front end of the compiler. This inlining does
2555 not require that the code generation be optimized. Like @option{-gnatn},
2556 the use of this switch generates additional dependencies.
2557 Note that
2558 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2559 to specify both options.
2560
2561 @item
2562 If an object file O  depends on the proper body of a subunit through inlining
2563 or instantiation, it depends on the parent unit of the subunit. This means that
2564 any modification of the parent unit or one of its subunits affects the
2565 compilation of O.
2566
2567 @item
2568 The object file for a parent unit depends on all its subunit body files.
2569
2570 @item
2571 The previous two rules meant that for purposes of computing dependencies and
2572 recompilation, a body and all its subunits are treated as an indivisible whole.
2573
2574 @noindent
2575 These rules are applied transitively: if unit @code{A} @code{with}'s
2576 unit @code{B}, whose elaboration calls an inlined procedure in package
2577 @code{C}, the object file for unit @code{A} will depend on the body of
2578 @code{C}, in file @file{c.adb}.
2579
2580 The set of dependent files described by these rules includes all the
2581 files on which the unit is semantically dependent, as described in the
2582 Ada 95 Language Reference Manual. However, it is a superset of what the
2583 ARM describes, because it includes generic, inline, and subunit dependencies.
2584
2585 An object file must be recreated by recompiling the corresponding source
2586 file if any of the source files on which it depends are modified. For
2587 example, if the @code{make} utility is used to control compilation,
2588 the rule for an Ada object file must mention all the source files on
2589 which the object file depends, according to the above definition.
2590 The determination of the necessary
2591 recompilations is done automatically when one uses @code{gnatmake}.
2592 @end itemize
2593
2594 @node The Ada Library Information Files
2595 @section The Ada Library Information Files
2596 @cindex Ada Library Information files
2597 @cindex @file{ALI} files
2598
2599 @noindent
2600 Each compilation actually generates two output files. The first of these
2601 is the normal object file that has a @file{.o} extension. The second is a
2602 text file containing full dependency information. It has the same
2603 name as the source file, but an @file{.ali} extension.
2604 This file is known as the Ada Library Information (@file{ALI}) file.
2605 The following information is contained in the @file{ALI} file.
2606
2607 @itemize @bullet
2608 @item
2609 Version information (indicates which version of GNAT was used to compile
2610 the unit(s) in question)
2611
2612 @item
2613 Main program information (including priority and time slice settings,
2614 as well as the wide character encoding used during compilation).
2615
2616 @item
2617 List of arguments used in the @code{gcc} command for the compilation
2618
2619 @item
2620 Attributes of the unit, including configuration pragmas used, an indication
2621 of whether the compilation was successful, exception model used etc.
2622
2623 @item
2624 A list of relevant restrictions applying to the unit (used for consistency)
2625 checking.
2626
2627 @item
2628 Categorization information (e.g. use of pragma @code{Pure}).
2629
2630 @item
2631 Information on all @code{with}'ed units, including presence of
2632 @code{Elaborate} or @code{Elaborate_All} pragmas.
2633
2634 @item
2635 Information from any @code{Linker_Options} pragmas used in the unit
2636
2637 @item
2638 Information on the use of @code{Body_Version} or @code{Version}
2639 attributes in the unit.
2640
2641 @item
2642 Dependency information. This is a list of files, together with
2643 time stamp and checksum information. These are files on which
2644 the unit depends in the sense that recompilation is required
2645 if any of these units are modified.
2646
2647 @item
2648 Cross-reference data. Contains information on all entities referenced
2649 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2650 provide cross-reference information.
2651
2652 @end itemize
2653
2654 @noindent
2655 For a full detailed description of the format of the @file{ALI} file,
2656 see the source of the body of unit @code{Lib.Writ}, contained in file
2657 @file{lib-writ.adb} in the GNAT compiler sources.
2658
2659 @node Binding an Ada Program
2660 @section Binding an Ada Program
2661
2662 @noindent
2663 When using languages such as C and C++, once the source files have been
2664 compiled the only remaining step in building an executable program
2665 is linking the object modules together. This means that it is possible to
2666 link an inconsistent version of a program, in which two units have
2667 included different versions of the same header.
2668
2669 The rules of Ada do not permit such an inconsistent program to be built.
2670 For example, if two clients have different versions of the same package,
2671 it is illegal to build a program containing these two clients.
2672 These rules are enforced by the GNAT binder, which also determines an
2673 elaboration order consistent with the Ada rules.
2674
2675 The GNAT binder is run after all the object files for a program have
2676 been created. It is given the name of the main program unit, and from
2677 this it determines the set of units required by the program, by reading the
2678 corresponding ALI files. It generates error messages if the program is
2679 inconsistent or if no valid order of elaboration exists.
2680
2681 If no errors are detected, the binder produces a main program, in Ada by
2682 default, that contains calls to the elaboration procedures of those
2683 compilation unit that require them, followed by
2684 a call to the main program. This Ada program is compiled to generate the
2685 object file for the main program. The name of
2686 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2687 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2688 main program unit.
2689
2690 Finally, the linker is used to build the resulting executable program,
2691 using the object from the main program from the bind step as well as the
2692 object files for the Ada units of the program.
2693
2694 @node Mixed Language Programming
2695 @section Mixed Language Programming
2696 @cindex Mixed Language Programming
2697
2698 @noindent
2699 This section describes how to develop a mixed-language program,
2700 specifically one that comprises units in both Ada and C.
2701
2702 @menu
2703 * Interfacing to C::
2704 * Calling Conventions::
2705 @end menu
2706
2707 @node Interfacing to C
2708 @subsection Interfacing to C
2709 @noindent
2710 Interfacing Ada with a foreign language such as C involves using
2711 compiler directives to import and/or export entity definitions in each
2712 language---using @code{extern} statements in C, for instance, and the
2713 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2714 a full treatment of these topics, read Appendix B, section 1 of the Ada
2715 95 Language Reference Manual.
2716
2717 There are two ways to build a program using GNAT that contains some Ada
2718 sources and some foreign language sources, depending on whether or not
2719 the main subprogram is written in Ada.  Here is a source example with
2720 the main subprogram in Ada:
2721
2722 @smallexample
2723 /* file1.c */
2724 #include <stdio.h>
2725
2726 void print_num (int num)
2727 @{
2728   printf ("num is %d.\n", num);
2729   return;
2730 @}
2731
2732 /* file2.c */
2733
2734 /* num_from_Ada is declared in my_main.adb */
2735 extern int num_from_Ada;
2736
2737 int get_num (void)
2738 @{
2739   return num_from_Ada;
2740 @}
2741 @end smallexample
2742
2743 @smallexample @c ada
2744 --  my_main.adb
2745 procedure My_Main is
2746
2747    --  Declare then export an Integer entity called num_from_Ada
2748    My_Num : Integer := 10;
2749    pragma Export (C, My_Num, "num_from_Ada");
2750
2751    --  Declare an Ada function spec for Get_Num, then use
2752    --  C function get_num for the implementation.
2753    function Get_Num return Integer;
2754    pragma Import (C, Get_Num, "get_num");
2755
2756    --  Declare an Ada procedure spec for Print_Num, then use
2757    --  C function print_num for the implementation.
2758    procedure Print_Num (Num : Integer);
2759    pragma Import (C, Print_Num, "print_num");
2760
2761 begin
2762    Print_Num (Get_Num);
2763 end My_Main;
2764 @end smallexample
2765
2766 @enumerate
2767 @item
2768 To build this example, first compile the foreign language files to
2769 generate object files:
2770 @smallexample
2771 gcc -c file1.c
2772 gcc -c file2.c
2773 @end smallexample
2774
2775 @item
2776 Then, compile the Ada units to produce a set of object files and ALI
2777 files:
2778 @smallexample
2779 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2780 @end smallexample
2781
2782 @item
2783 Run the Ada binder on the Ada main program:
2784 @smallexample
2785 gnatbind my_main.ali
2786 @end smallexample
2787
2788 @item
2789 Link the Ada main program, the Ada objects and the other language
2790 objects:
2791 @smallexample
2792 gnatlink my_main.ali file1.o file2.o
2793 @end smallexample
2794 @end enumerate
2795
2796 The last three steps can be grouped in a single command:
2797 @smallexample
2798 gnatmake my_main.adb -largs file1.o file2.o
2799 @end smallexample
2800
2801 @cindex Binder output file
2802 @noindent
2803 If the main program is in a language other than Ada, then you may have
2804 more than one entry point into the Ada subsystem. You must use a special
2805 binder option to generate callable routines that initialize and
2806 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2807 Calls to the initialization and finalization routines must be inserted
2808 in the main program, or some other appropriate point in the code. The
2809 call to initialize the Ada units must occur before the first Ada
2810 subprogram is called, and the call to finalize the Ada units must occur
2811 after the last Ada subprogram returns. The binder will place the
2812 initialization and finalization subprograms into the
2813 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2814 sources.  To illustrate, we have the following example:
2815
2816 @smallexample
2817 /* main.c */
2818 extern void adainit (void);
2819 extern void adafinal (void);
2820 extern int add (int, int);
2821 extern int sub (int, int);
2822
2823 int main (int argc, char *argv[])
2824 @{
2825   int a = 21, b = 7;
2826
2827   adainit();
2828
2829   /* Should print "21 + 7 = 28" */
2830   printf ("%d + %d = %d\n", a, b, add (a, b));
2831   /* Should print "21 - 7 = 14" */
2832   printf ("%d - %d = %d\n", a, b, sub (a, b));
2833
2834   adafinal();
2835 @}
2836 @end smallexample
2837
2838 @smallexample @c ada
2839 --  unit1.ads
2840 package Unit1 is
2841    function Add (A, B : Integer) return Integer;
2842    pragma Export (C, Add, "add");
2843 end Unit1;
2844
2845 --  unit1.adb
2846 package body Unit1 is
2847    function Add (A, B : Integer) return Integer is
2848    begin
2849       return A + B;
2850    end Add;
2851 end Unit1;
2852
2853 --  unit2.ads
2854 package Unit2 is
2855    function Sub (A, B : Integer) return Integer;
2856    pragma Export (C, Sub, "sub");
2857 end Unit2;
2858
2859 --  unit2.adb
2860 package body Unit2 is
2861    function Sub (A, B : Integer) return Integer is
2862    begin
2863       return A - B;
2864    end Sub;
2865 end Unit2;
2866 @end smallexample
2867
2868 @enumerate
2869 @item
2870 The build procedure for this application is similar to the last
2871 example's.  First, compile the foreign language files to generate object
2872 files:
2873 @smallexample
2874 gcc -c main.c
2875 @end smallexample
2876
2877 @item
2878 Next, compile the Ada units to produce a set of object files and ALI
2879 files:
2880 @smallexample
2881 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2882 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2883 @end smallexample
2884
2885 @item
2886 Run the Ada binder on every generated ALI file.  Make sure to use the
2887 @option{-n} option to specify a foreign main program:
2888 @smallexample
2889 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2890 @end smallexample
2891
2892 @item
2893 Link the Ada main program, the Ada objects and the foreign language
2894 objects. You need only list the last ALI file here:
2895 @smallexample
2896 gnatlink unit2.ali main.o -o exec_file
2897 @end smallexample
2898
2899 This procedure yields a binary executable called @file{exec_file}.
2900 @end enumerate
2901
2902 @node Calling Conventions
2903 @subsection Calling Conventions
2904 @cindex Foreign Languages
2905 @cindex Calling Conventions
2906 GNAT follows standard calling sequence conventions and will thus interface
2907 to any other language that also follows these conventions. The following
2908 Convention identifiers are recognized by GNAT:
2909
2910 @table @code
2911 @cindex Interfacing to Ada
2912 @cindex Other Ada compilers
2913 @cindex Convention Ada
2914 @item Ada
2915 This indicates that the standard Ada calling sequence will be
2916 used and all Ada data items may be passed without any limitations in the
2917 case where GNAT is used to generate both the caller and callee. It is also
2918 possible to mix GNAT generated code and code generated by another Ada
2919 compiler. In this case, the data types should be restricted to simple
2920 cases, including primitive types. Whether complex data types can be passed
2921 depends on the situation. Probably it is safe to pass simple arrays, such
2922 as arrays of integers or floats. Records may or may not work, depending
2923 on whether both compilers lay them out identically. Complex structures
2924 involving variant records, access parameters, tasks, or protected types,
2925 are unlikely to be able to be passed.
2926
2927 Note that in the case of GNAT running
2928 on a platform that supports DEC Ada 83, a higher degree of compatibility
2929 can be guaranteed, and in particular records are layed out in an identical
2930 manner in the two compilers. Note also that if output from two different
2931 compilers is mixed, the program is responsible for dealing with elaboration
2932 issues. Probably the safest approach is to write the main program in the
2933 version of Ada other than GNAT, so that it takes care of its own elaboration
2934 requirements, and then call the GNAT-generated adainit procedure to ensure
2935 elaboration of the GNAT components. Consult the documentation of the other
2936 Ada compiler for further details on elaboration.
2937
2938 However, it is not possible to mix the tasking run time of GNAT and
2939 DEC Ada 83, All the tasking operations must either be entirely within
2940 GNAT compiled sections of the program, or entirely within DEC Ada 83
2941 compiled sections of the program.
2942
2943 @cindex Interfacing to Assembly
2944 @cindex Convention Assembler
2945 @item Assembler
2946 Specifies assembler as the convention. In practice this has the
2947 same effect as convention Ada (but is not equivalent in the sense of being
2948 considered the same convention).
2949
2950 @cindex Convention Asm
2951 @findex Asm
2952 @item Asm
2953 Equivalent to Assembler.
2954
2955 @cindex Interfacing to COBOL
2956 @cindex Convention COBOL
2957 @findex COBOL
2958 @item COBOL
2959 Data will be passed according to the conventions described
2960 in section B.4 of the Ada 95 Reference Manual.
2961
2962 @findex C
2963 @cindex Interfacing to C
2964 @cindex Convention C
2965 @item C
2966 Data will be passed according to the conventions described
2967 in section B.3 of the Ada 95 Reference Manual.
2968
2969 @findex C varargs function
2970 @cindex Intefacing to C varargs function
2971 @cindex varargs function intefacs
2972 @item C varargs function
2973 In C, @code{varargs} allows a function to take a variable number of
2974 arguments. There is no direct equivalent in this to Ada. One
2975 approach that can be used is to create a C wrapper for each
2976 different profile and then interface to this C wrapper. For
2977 example, to print an @code{int} value using @code{printf},
2978 create a C function @code{printfi} that takes two arguments, a
2979 pointer to a string and an int, and calls @code{printf}.
2980 Then in the Ada program, use pragma @code{Import} to
2981 interface to printfi.
2982
2983 It may work on some platforms to directly interface to
2984 a @code{varargs} function by providing a specific Ada profile
2985 for a a particular call. However, this does not work on
2986 all platforms, since there is no guarantee that the
2987 calling sequence for a two argument normal C function
2988 is the same as for calling a @code{varargs} C function with
2989 the same two arguments.
2990
2991 @cindex Convention Default
2992 @findex Default
2993 @item Default
2994 Equivalent to C.
2995
2996 @cindex Convention External
2997 @findex External
2998 @item External
2999 Equivalent to C.
3000
3001 @findex C++
3002 @cindex Interfacing to C++
3003 @cindex Convention C++
3004 @item CPP
3005 This stands for C++. For most purposes this is identical to C.
3006 See the separate description of the specialized GNAT pragmas relating to
3007 C++ interfacing for further details.
3008
3009 @findex Fortran
3010 @cindex Interfacing to Fortran
3011 @cindex Convention Fortran
3012 @item Fortran
3013 Data will be passed according to the conventions described
3014 in section B.5 of the Ada 95 Reference Manual.
3015
3016 @item Intrinsic
3017 This applies to an intrinsic operation, as defined in the Ada 95
3018 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3019 this means that the body of the subprogram is provided by the compiler itself,
3020 usually by means of an efficient code sequence, and that the user does not
3021 supply an explicit body for it. In an application program, the pragma can
3022 only be applied to the following two sets of names, which the GNAT compiler
3023 recognizes.
3024
3025 @itemize @bullet
3026 @item
3027 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3028 Arithmetic.  The corresponding subprogram declaration must have
3029 two formal parameters. The
3030 first one must be a signed integer type or a modular type with a binary
3031 modulus, and the second parameter must be of type Natural.
3032 The return type must be the same as the type of the first argument. The size
3033 of this type can only be 8, 16, 32, or 64.
3034 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3035 The corresponding operator declaration must have parameters and result type
3036 that have the same root numeric type (for example, all three are long_float
3037 types). This simplifies the definition of operations that use type checking
3038 to perform dimensional checks:
3039
3040 @smallexample @c ada
3041 type Distance is new Long_Float;
3042 type Time     is new Long_Float;
3043 type Velocity is new Long_Float;
3044 function "/" (D : Distance; T : Time)
3045   return Velocity;
3046 pragma Import (Intrinsic, "/");
3047 @end smallexample
3048
3049 @noindent
3050 This common idiom is often programmed with a generic definition and an
3051 explicit body. The pragma makes it simpler to introduce such declarations.
3052 It incurs no overhead in compilation time or code size, because it is
3053 implemented as a single machine instruction.
3054 @end itemize
3055 @noindent
3056
3057 @ifset unw
3058 @findex Stdcall
3059 @cindex Convention Stdcall
3060 @item Stdcall
3061 This is relevant only to NT/Win95 implementations of GNAT,
3062 and specifies that the Stdcall calling sequence will be used, as defined
3063 by the NT API.
3064
3065 @findex DLL
3066 @cindex Convention DLL
3067 @item DLL
3068 This is equivalent to Stdcall.
3069
3070 @findex Win32
3071 @cindex Convention Win32
3072 @item Win32
3073 This is equivalent to Stdcall.
3074 @end ifset
3075
3076 @findex Stubbed
3077 @cindex Convention Stubbed
3078 @item Stubbed
3079 This is a special convention that indicates that the compiler
3080 should provide a stub body that raises @code{Program_Error}.
3081 @end table
3082
3083 @noindent
3084 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3085 that can be used to parametrize conventions and allow additional synonyms
3086 to be specified. For example if you have legacy code in which the convention
3087 identifier Fortran77 was used for Fortran, you can use the configuration
3088 pragma:
3089
3090 @smallexample @c ada
3091 pragma Convention_Identifier (Fortran77, Fortran);
3092 @end smallexample
3093
3094 @noindent
3095 And from now on the identifier Fortran77 may be used as a convention
3096 identifier (for example in an @code{Import} pragma) with the same
3097 meaning as Fortran.
3098
3099 @node Building Mixed Ada & C++ Programs
3100 @section Building Mixed Ada & C++ Programs
3101
3102 @noindent
3103 A programmer inexperienced with mixed-language development may find that
3104 building an application containing both Ada and C++ code can be a
3105 challenge. As a matter of fact, interfacing with C++ has not been
3106 standardized in the Ada 95 Reference Manual due to the immaturity of --
3107 and lack of standards for -- C++ at the time. This section gives a few
3108 hints that should make this task easier. The first section addresses
3109 the differences regarding interfacing with C. The second section
3110 looks into the delicate problem of linking the complete application from
3111 its Ada and C++ parts. The last section gives some hints on how the GNAT
3112 run time can be adapted in order to allow inter-language dispatching
3113 with a new C++ compiler.
3114
3115 @menu
3116 * Interfacing to C++::
3117 * Linking a Mixed C++ & Ada Program::
3118 * A Simple Example::
3119 * Adapting the Run Time to a New C++ Compiler::
3120 @end menu
3121
3122 @node Interfacing to C++
3123 @subsection Interfacing to C++
3124
3125 @noindent
3126 GNAT supports interfacing with C++ compilers generating code that is
3127 compatible with the standard Application Binary Interface of the given
3128 platform.
3129
3130 @noindent
3131 Interfacing can be done at 3 levels: simple data, subprograms, and
3132 classes. In the first two cases, GNAT offers a specific @var{Convention
3133 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3134 the names of subprograms, and currently, GNAT does not provide any help
3135 to solve the demangling problem. This problem can be addressed in two
3136 ways:
3137 @itemize @bullet
3138 @item
3139 by modifying the C++ code in order to force a C convention using
3140 the @code{extern "C"} syntax.
3141
3142 @item
3143 by figuring out the mangled name and use it as the Link_Name argument of
3144 the pragma import.
3145 @end itemize
3146
3147 @noindent
3148 Interfacing at the class level can be achieved by using the GNAT specific
3149 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3150 Reference Manual for additional information.
3151
3152 @node Linking a Mixed C++ & Ada Program
3153 @subsection Linking a Mixed C++ & Ada Program
3154
3155 @noindent
3156 Usually the linker of the C++ development system must be used to link
3157 mixed applications because most C++ systems will resolve elaboration
3158 issues (such as calling constructors on global class instances)
3159 transparently during the link phase. GNAT has been adapted to ease the
3160 use of a foreign linker for the last phase. Three cases can be
3161 considered:
3162 @enumerate
3163
3164 @item
3165 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3166 The C++ linker can simply be called by using the C++ specific driver
3167 called @code{c++}. Note that this setup is not very common because it
3168 may involve recompiling the whole GCC tree from sources, which makes it
3169 harder to upgrade the compilation system for one language without
3170 destabilizing the other.
3171
3172 @smallexample
3173 $ c++ -c file1.C
3174 $ c++ -c file2.C
3175 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3176 @end smallexample
3177
3178 @item
3179 Using GNAT and G++ from two different GCC installations: If both
3180 compilers are on the PATH, the previous method may be used. It is
3181 important to note that environment variables such as C_INCLUDE_PATH,
3182 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3183 at the same time and may make one of the two compilers operate
3184 improperly if set during invocation of the wrong compiler.  It is also
3185 very important that the linker uses the proper @file{libgcc.a} GCC
3186 library -- that is, the one from the C++ compiler installation. The
3187 implicit link command as suggested in the gnatmake command from the
3188 former example can be replaced by an explicit link command with the
3189 full-verbosity option in order to verify which library is used:
3190 @smallexample
3191 $ gnatbind ada_unit
3192 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3193 @end smallexample
3194 If there is a problem due to interfering environment variables, it can
3195 be worked around by using an intermediate script. The following example
3196 shows the proper script to use when GNAT has not been installed at its
3197 default location and g++ has been installed at its default location:
3198
3199 @smallexample
3200 $ cat ./my_script
3201 #!/bin/sh
3202 unset BINUTILS_ROOT
3203 unset GCC_ROOT
3204 c++ $*
3205 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3206 @end smallexample
3207
3208 @item
3209 Using a non-GNU C++ compiler: The commands previously described can be
3210 used to insure that the C++ linker is used. Nonetheless, you need to add
3211 the path to libgcc explicitly, since some libraries needed by GNAT are
3212 located in this directory:
3213
3214 @smallexample
3215 $ cat ./my_script
3216 #!/bin/sh
3217 CC $* `gcc -print-libgcc-file-name`
3218 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3219 @end smallexample
3220
3221 Where CC is the name of the non-GNU C++ compiler.
3222
3223 @end enumerate
3224
3225 @node A Simple Example
3226 @subsection  A Simple Example
3227 @noindent
3228 The following example, provided as part of the GNAT examples, shows how
3229 to achieve procedural interfacing between Ada and C++ in both
3230 directions. The C++ class A has two methods. The first method is exported
3231 to Ada by the means of an extern C wrapper function. The second method
3232 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3233 a limited record with a layout comparable to the C++ class. The Ada
3234 subprogram, in turn, calls the C++ method. So, starting from the C++
3235 main program, the process passes back and forth between the two
3236 languages.
3237
3238 @noindent
3239 Here are the compilation commands:
3240 @smallexample
3241 $ gnatmake -c simple_cpp_interface
3242 $ c++ -c cpp_main.C
3243 $ c++ -c ex7.C
3244 $ gnatbind -n simple_cpp_interface
3245 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3246       -lstdc++ ex7.o cpp_main.o
3247 @end smallexample
3248
3249 @noindent
3250 Here are the corresponding sources:
3251 @smallexample
3252
3253 //cpp_main.C
3254
3255 #include "ex7.h"
3256
3257 extern "C" @{
3258   void adainit (void);
3259   void adafinal (void);
3260   void method1 (A *t);
3261 @}
3262
3263 void method1 (A *t)
3264 @{
3265   t->method1 ();
3266 @}
3267
3268 int main ()
3269 @{
3270   A obj;
3271   adainit ();
3272   obj.method2 (3030);
3273   adafinal ();
3274 @}
3275
3276 //ex7.h
3277
3278 class Origin @{
3279  public:
3280   int o_value;
3281 @};
3282 class A : public Origin @{
3283  public:
3284   void method1 (void);
3285   virtual void method2 (int v);
3286   A();
3287   int   a_value;
3288 @};
3289
3290 //ex7.C
3291
3292 #include "ex7.h"
3293 #include <stdio.h>
3294
3295 extern "C" @{ void ada_method2 (A *t, int v);@}
3296
3297 void A::method1 (void)
3298 @{
3299   a_value = 2020;
3300   printf ("in A::method1, a_value = %d \n",a_value);
3301
3302 @}
3303
3304 void A::method2 (int v)
3305 @{
3306    ada_method2 (this, v);
3307    printf ("in A::method2, a_value = %d \n",a_value);
3308
3309 @}
3310
3311 A::A(void)
3312 @{
3313    a_value = 1010;
3314   printf ("in A::A, a_value = %d \n",a_value);
3315 @}
3316
3317 -- Ada sources
3318 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3319
3320    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3321    @b{begin}
3322       Method1 (This);
3323       This.A_Value := V;
3324    @b{end} Ada_Method2;
3325
3326 @b{end} Simple_Cpp_Interface;
3327
3328 @b{package} Simple_Cpp_Interface @b{is}
3329    @b{type} A @b{is} @b{limited}
3330       @b{record}
3331          O_Value : Integer;
3332          A_Value : Integer;
3333       @b{end} @b{record};
3334    @b{pragma} Convention (C, A);
3335
3336    @b{procedure} Method1 (This : @b{in} @b{out} A);
3337    @b{pragma} Import (C, Method1);
3338
3339    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3340    @b{pragma} Export (C, Ada_Method2);
3341
3342 @b{end} Simple_Cpp_Interface;
3343 @end smallexample
3344
3345 @node Adapting the Run Time to a New C++ Compiler
3346 @subsection Adapting the Run Time to a New C++ Compiler
3347 @noindent
3348 GNAT offers the capability to derive Ada 95 tagged types directly from
3349 preexisting C++ classes and . See ``Interfacing with C++'' in the
3350 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3351 such a goal
3352 has been made user configurable through a GNAT library unit
3353 @code{Interfaces.CPP}. The default version of this file is adapted to
3354 the GNU C++ compiler. Internal knowledge of the virtual
3355 table layout used by the new C++ compiler is needed to configure
3356 properly this unit. The Interface of this unit is known by the compiler
3357 and cannot be changed except for the value of the constants defining the
3358 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3359 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3360 of this unit for more details.
3361
3362 @node Comparison between GNAT and C/C++ Compilation Models
3363 @section Comparison between GNAT and C/C++ Compilation Models
3364
3365 @noindent
3366 The GNAT model of compilation is close to the C and C++ models. You can
3367 think of Ada specs as corresponding to header files in C. As in C, you
3368 don't need to compile specs; they are compiled when they are used. The
3369 Ada @code{with} is similar in effect to the @code{#include} of a C
3370 header.
3371
3372 One notable difference is that, in Ada, you may compile specs separately
3373 to check them for semantic and syntactic accuracy. This is not always
3374 possible with C headers because they are fragments of programs that have
3375 less specific syntactic or semantic rules.
3376
3377 The other major difference is the requirement for running the binder,
3378 which performs two important functions. First, it checks for
3379 consistency. In C or C++, the only defense against assembling
3380 inconsistent programs lies outside the compiler, in a makefile, for
3381 example. The binder satisfies the Ada requirement that it be impossible
3382 to construct an inconsistent program when the compiler is used in normal
3383 mode.
3384
3385 @cindex Elaboration order control
3386 The other important function of the binder is to deal with elaboration
3387 issues. There are also elaboration issues in C++ that are handled
3388 automatically. This automatic handling has the advantage of being
3389 simpler to use, but the C++ programmer has no control over elaboration.
3390 Where @code{gnatbind} might complain there was no valid order of
3391 elaboration, a C++ compiler would simply construct a program that
3392 malfunctioned at run time.
3393
3394 @node Comparison between GNAT and Conventional Ada Library Models
3395 @section Comparison between GNAT and Conventional Ada Library Models
3396
3397 @noindent
3398 This section is intended to be useful to Ada programmers who have
3399 previously used an Ada compiler implementing the traditional Ada library
3400 model, as described in the Ada 95 Language Reference Manual. If you
3401 have not used such a system, please go on to the next section.
3402
3403 @cindex GNAT library
3404 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3405 source files themselves acts as the library. Compiling Ada programs does
3406 not generate any centralized information, but rather an object file and
3407 a ALI file, which are of interest only to the binder and linker.
3408 In a traditional system, the compiler reads information not only from
3409 the source file being compiled, but also from the centralized library.
3410 This means that the effect of a compilation depends on what has been
3411 previously compiled. In particular:
3412
3413 @itemize @bullet
3414 @item
3415 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3416 to the version of the unit most recently compiled into the library.
3417
3418 @item
3419 Inlining is effective only if the necessary body has already been
3420 compiled into the library.
3421
3422 @item
3423 Compiling a unit may obsolete other units in the library.
3424 @end itemize
3425
3426 @noindent
3427 In GNAT, compiling one unit never affects the compilation of any other
3428 units because the compiler reads only source files. Only changes to source
3429 files can affect the results of a compilation. In particular:
3430
3431 @itemize @bullet
3432 @item
3433 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3434 to the source version of the unit that is currently accessible to the
3435 compiler.
3436
3437 @item
3438 @cindex Inlining
3439 Inlining requires the appropriate source files for the package or
3440 subprogram bodies to be available to the compiler. Inlining is always
3441 effective, independent of the order in which units are complied.
3442
3443 @item
3444 Compiling a unit never affects any other compilations. The editing of
3445 sources may cause previous compilations to be out of date if they
3446 depended on the source file being modified.
3447 @end itemize
3448
3449 @noindent
3450 The most important result of these differences is that order of compilation
3451 is never significant in GNAT. There is no situation in which one is
3452 required to do one compilation before another. What shows up as order of
3453 compilation requirements in the traditional Ada library becomes, in
3454 GNAT, simple source dependencies; in other words, there is only a set
3455 of rules saying what source files must be present when a file is
3456 compiled.
3457
3458 @ifset vms
3459 @node Placement of temporary files
3460 @section Placement of temporary files
3461 @cindex Temporary files (user control over placement)
3462
3463 @noindent
3464 GNAT creates temporary files in the directory designated by the environment
3465 variable @env{TMPDIR}.
3466 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3467 for detailed information on how environment variables are resolved.
3468 For most users the easiest way to make use of this feature is to simply
3469 define @env{TMPDIR} as a job level logical name).
3470 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3471 for compiler temporary files, then you can include something like the
3472 following command in your @file{LOGIN.COM} file:
3473
3474 @smallexample
3475 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3476 @end smallexample
3477
3478 @noindent
3479 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3480 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3481 designated by @env{TEMP}.
3482 If none of these environment variables are defined then GNAT uses the
3483 directory designated by the logical name @code{SYS$SCRATCH:}
3484 (by default the user's home directory). If all else fails
3485 GNAT uses the current directory for temporary files.
3486 @end ifset
3487
3488
3489 @c *************************
3490 @node Compiling Using gcc
3491 @chapter Compiling Using @code{gcc}
3492
3493 @noindent
3494 This chapter discusses how to compile Ada programs using the @code{gcc}
3495 command. It also describes the set of switches
3496 that can be used to control the behavior of the compiler.
3497 @menu
3498 * Compiling Programs::
3499 * Switches for gcc::
3500 * Search Paths and the Run-Time Library (RTL)::
3501 * Order of Compilation Issues::
3502 * Examples::
3503 @end menu
3504
3505 @node Compiling Programs
3506 @section Compiling Programs
3507
3508 @noindent
3509 The first step in creating an executable program is to compile the units
3510 of the program using the @code{gcc} command. You must compile the
3511 following files:
3512
3513 @itemize @bullet
3514 @item
3515 the body file (@file{.adb}) for a library level subprogram or generic
3516 subprogram
3517
3518 @item
3519 the spec file (@file{.ads}) for a library level package or generic
3520 package that has no body
3521
3522 @item
3523 the body file (@file{.adb}) for a library level package
3524 or generic package that has a body
3525
3526 @end itemize
3527
3528 @noindent
3529 You need @emph{not} compile the following files
3530
3531 @itemize @bullet
3532
3533 @item
3534 the spec of a library unit which has a body
3535
3536 @item
3537 subunits
3538 @end itemize
3539
3540 @noindent
3541 because they are compiled as part of compiling related units. GNAT
3542 package specs
3543 when the corresponding body is compiled, and subunits when the parent is
3544 compiled.
3545
3546 @cindex cannot generate code
3547 If you attempt to compile any of these files, you will get one of the
3548 following error messages (where fff is the name of the file you compiled):
3549
3550 @smallexample
3551 cannot generate code for file @var{fff} (package spec)
3552 to check package spec, use -gnatc
3553
3554 cannot generate code for file @var{fff} (missing subunits)
3555 to check parent unit, use -gnatc
3556
3557 cannot generate code for file @var{fff} (subprogram spec)
3558 to check subprogram spec, use -gnatc
3559
3560 cannot generate code for file @var{fff} (subunit)
3561 to check subunit, use -gnatc
3562 @end smallexample
3563
3564 @noindent
3565 As indicated by the above error messages, if you want to submit
3566 one of these files to the compiler to check for correct semantics
3567 without generating code, then use the @option{-gnatc} switch.
3568
3569 The basic command for compiling a file containing an Ada unit is
3570
3571 @smallexample
3572 $ gcc -c [@var{switches}] @file{file name}
3573 @end smallexample
3574
3575 @noindent
3576 where @var{file name} is the name of the Ada file (usually
3577 having an extension
3578 @file{.ads} for a spec or @file{.adb} for a body).
3579 @ifclear vms
3580 You specify the
3581 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3582 @end ifclear
3583 The result of a successful compilation is an object file, which has the
3584 same name as the source file but an extension of @file{.o} and an Ada
3585 Library Information (ALI) file, which also has the same name as the
3586 source file, but with @file{.ali} as the extension. GNAT creates these
3587 two output files in the current directory, but you may specify a source
3588 file in any directory using an absolute or relative path specification
3589 containing the directory information.
3590
3591 @findex gnat1
3592 @code{gcc} is actually a driver program that looks at the extensions of
3593 the file arguments and loads the appropriate compiler. For example, the
3594 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3595 These programs are in directories known to the driver program (in some
3596 configurations via environment variables you set), but need not be in
3597 your path. The @code{gcc} driver also calls the assembler and any other
3598 utilities needed to complete the generation of the required object
3599 files.
3600
3601 It is possible to supply several file names on the same @code{gcc}
3602 command. This causes @code{gcc} to call the appropriate compiler for
3603 each file. For example, the following command lists three separate
3604 files to be compiled:
3605
3606 @smallexample
3607 $ gcc -c x.adb y.adb z.c
3608 @end smallexample
3609
3610 @noindent
3611 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3612 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3613 The compiler generates three object files @file{x.o}, @file{y.o} and
3614 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3615 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3616 @ifclear vms
3617 except for
3618 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3619 @end ifclear
3620
3621 @node Switches for gcc
3622 @section Switches for @code{gcc}
3623
3624 @noindent
3625 The @code{gcc} command accepts switches that control the
3626 compilation process. These switches are fully described in this section.
3627 First we briefly list all the switches, in alphabetical order, then we
3628 describe the switches in more detail in functionally grouped sections.
3629
3630 @menu
3631 * Output and Error Message Control::
3632 * Warning Message Control::
3633 * Debugging and Assertion Control::
3634 * Validity Checking::
3635 * Style Checking::
3636 * Run-Time Checks::
3637 * Stack Overflow Checking::
3638 * Using gcc for Syntax Checking::
3639 * Using gcc for Semantic Checking::
3640 * Compiling Ada 83 Programs::
3641 * Character Set Control::
3642 * File Naming Control::
3643 * Subprogram Inlining Control::
3644 * Auxiliary Output Control::
3645 * Debugging Control::
3646 * Exception Handling Control::
3647 * Units to Sources Mapping Files::
3648 * Integrated Preprocessing::
3649 * Code Generation Control::
3650 @ifset vms
3651 * Return Codes::
3652 @end ifset
3653 @end menu
3654
3655 @table @option
3656 @c !sort!
3657 @ifclear vms
3658 @cindex @option{-b} (@code{gcc})
3659 @item -b @var{target}
3660 Compile your program to run on @var{target}, which is the name of a
3661 system configuration. You must have a GNAT cross-compiler built if
3662 @var{target} is not the same as your host system.
3663
3664 @item -B@var{dir}
3665 @cindex @option{-B} (@code{gcc})
3666 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3667 from @var{dir} instead of the default location. Only use this switch
3668 when multiple versions of the GNAT compiler are available. See the
3669 @code{gcc} manual page for further details. You would normally use the
3670 @option{-b} or @option{-V} switch instead.
3671
3672 @item -c
3673 @cindex @option{-c} (@code{gcc})
3674 Compile. Always use this switch when compiling Ada programs.
3675
3676 Note: for some other languages when using @code{gcc}, notably in
3677 the case of C and C++, it is possible to use
3678 use @code{gcc} without a @option{-c} switch to
3679 compile and link in one step. In the case of GNAT, you
3680 cannot use this approach, because the binder must be run
3681 and @code{gcc} cannot be used to run the GNAT binder.
3682 @end ifclear
3683
3684 @item -fno-inline
3685 @cindex @option{-fno-inline} (@code{gcc})
3686 Suppresses all back-end inlining, even if other optimization or inlining
3687 switches are set.
3688 This includes suppression of inlining that results
3689 from the use of the pragma @code{Inline_Always}.
3690 See also @option{-gnatn} and @option{-gnatN}.
3691
3692 @item -fno-strict-aliasing
3693 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3694 Causes the compiler to avoid assumptions regarding non-aliasing
3695 of objects of different types. See section
3696 @pxref{Optimization and Strict Aliasing} for details.
3697
3698 @item -fstack-check
3699 @cindex @option{-fstack-check} (@code{gcc})
3700 Activates stack checking.
3701 See @ref{Stack Overflow Checking} for details of the use of this option.
3702
3703 @item ^-g^/DEBUG^
3704 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3705 Generate debugging information. This information is stored in the object
3706 file and copied from there to the final executable file by the linker,
3707 where it can be read by the debugger. You must use the
3708 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3709
3710 @item -gnat83
3711 @cindex @option{-gnat83} (@code{gcc})
3712 Enforce Ada 83 restrictions.
3713
3714 @item -gnata
3715 @cindex @option{-gnata} (@code{gcc})
3716 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3717 activated.
3718
3719 @item -gnatA
3720 @cindex @option{-gnatA} (@code{gcc})
3721 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3722 it will be ignored.
3723
3724 @item -gnatb
3725 @cindex @option{-gnatb} (@code{gcc})
3726 Generate brief messages to @file{stderr} even if verbose mode set.
3727
3728 @item -gnatc
3729 @cindex @option{-gnatc} (@code{gcc})
3730 Check syntax and semantics only (no code generation attempted).
3731
3732 @item -gnatd
3733 @cindex @option{-gnatd} (@code{gcc})
3734 Specify debug options for the compiler. The string of characters after
3735 the @option{-gnatd} specify the specific debug options. The possible
3736 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3737 compiler source file @file{debug.adb} for details of the implemented
3738 debug options. Certain debug options are relevant to applications
3739 programmers, and these are documented at appropriate points in this
3740 users guide.
3741
3742 @item -gnatD
3743 @cindex @option{-gnatD} (@code{gcc})
3744 Create expanded source files for source level debugging. This switch
3745 also suppress generation of cross-reference information
3746 (see @option{-gnatx}).
3747
3748 @item -gnatec=@var{path}
3749 @cindex @option{-gnatec} (@code{gcc})
3750 Specify a configuration pragma file
3751 @ifclear vms
3752 (the equal sign is optional)
3753 @end ifclear
3754 (see @ref{The Configuration Pragmas Files}).
3755
3756 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3757 @cindex @option{-gnateD} (@code{gcc})
3758 Defines a symbol, associated with value, for preprocessing.
3759 (see @ref{Integrated Preprocessing})
3760
3761 @item -gnatef
3762 @cindex @option{-gnatef} (@code{gcc})
3763 Display full source path name in brief error messages.
3764
3765 @item -gnatem=@var{path}
3766 @cindex @option{-gnatem} (@code{gcc})
3767 Specify a mapping file
3768 @ifclear vms
3769 (the equal sign is optional)
3770 @end ifclear
3771 (see @ref{Units to Sources Mapping Files}).
3772
3773 @item -gnatep=@var{file}
3774 @cindex @option{-gnatep} (@code{gcc})
3775 Specify a preprocessing data file
3776 @ifclear vms
3777 (the equal sign is optional)
3778 @end ifclear
3779 (see @ref{Integrated Preprocessing}).
3780
3781 @item -gnatE
3782 @cindex @option{-gnatE} (@code{gcc})
3783 Full dynamic elaboration checks.
3784
3785 @item -gnatf
3786 @cindex @option{-gnatf} (@code{gcc})
3787 Full errors. Multiple errors per line, all undefined references, do not
3788 attempt to suppress cascaded errors.
3789
3790 @item -gnatF
3791 @cindex @option{-gnatF} (@code{gcc})
3792 Externals names are folded to all uppercase.
3793
3794 @item -gnatg
3795 @cindex @option{-gnatg} (@code{gcc})
3796 Internal GNAT implementation mode. This should not be used for
3797 applications programs, it is intended only for use by the compiler
3798 and its run-time library. For documentation, see the GNAT sources.
3799 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3800 are generated on unreferenced entities, and all warnings are treated
3801 as errors.
3802
3803 @item -gnatG
3804 @cindex @option{-gnatG} (@code{gcc})
3805 List generated expanded code in source form.
3806
3807 @item ^-gnath^/HELP^
3808 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3809 Output usage information. The output is written to @file{stdout}.
3810
3811 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3812 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3813 Identifier character set
3814 @ifclear vms
3815 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3816 @end ifclear
3817 @ifset vms
3818 For details of the possible selections for @var{c},
3819 see @xref{Character Set Control}.
3820 @end ifset
3821
3822 @item -gnatk=@var{n}
3823 @cindex @option{-gnatk} (@code{gcc})
3824 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3825
3826 @item -gnatl
3827 @cindex @option{-gnatl} (@code{gcc})
3828 Output full source listing with embedded error messages.
3829
3830 @item -gnatL
3831 @cindex @option{-gnatL} (@code{gcc})
3832 Use the longjmp/setjmp method for exception handling
3833
3834 @item -gnatm=@var{n}
3835 @cindex @option{-gnatm} (@code{gcc})
3836 Limit number of detected error or warning messages to @var{n}
3837 where @var{n} is in the range 1..999_999. The default setting if
3838 no switch is given is 9999. Compilation is terminated if this
3839 limit is exceeded.
3840
3841 @item -gnatn
3842 @cindex @option{-gnatn} (@code{gcc})
3843 Activate inlining for subprograms for which
3844 pragma @code{inline} is specified. This inlining is performed
3845 by the GCC back-end.
3846
3847 @item -gnatN
3848 @cindex @option{-gnatN} (@code{gcc})
3849 Activate front end inlining for subprograms for which
3850 pragma @code{Inline} is specified. This inlining is performed
3851 by the front end and will be visible in the
3852 @option{-gnatG} output.
3853 In some cases, this has proved more effective than the back end
3854 inlining resulting from the use of
3855 @option{-gnatn}.
3856 Note that
3857 @option{-gnatN} automatically implies
3858 @option{-gnatn} so it is not necessary
3859 to specify both options. There are a few cases that the back-end inlining
3860 catches that cannot be dealt with in the front-end.
3861
3862 @item -gnato
3863 @cindex @option{-gnato} (@code{gcc})
3864 Enable numeric overflow checking (which is not normally enabled by
3865 default). Not that division by zero is a separate check that is not
3866 controlled by this switch (division by zero checking is on by default).
3867
3868 @item -gnatp
3869 @cindex @option{-gnatp} (@code{gcc})
3870 Suppress all checks.
3871
3872 @item -gnatP
3873 @cindex @option{-gnatP} (@code{gcc})
3874 Enable polling. This is required on some systems (notably Windows NT) to
3875 obtain asynchronous abort and asynchronous transfer of control capability.
3876 See the description of pragma Polling in the GNAT Reference Manual for
3877 full details.
3878
3879 @item -gnatq
3880 @cindex @option{-gnatq} (@code{gcc})
3881 Don't quit; try semantics, even if parse errors.
3882
3883 @item -gnatQ
3884 @cindex @option{-gnatQ} (@code{gcc})
3885 Don't quit; generate @file{ALI} and tree files even if illegalities.
3886
3887 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3888 @cindex @option{-gnatR} (@code{gcc})
3889 Output representation information for declared types and objects.
3890
3891 @item -gnats
3892 @cindex @option{-gnats} (@code{gcc})
3893 Syntax check only.
3894
3895 @item -gnatS
3896 @cindex @option{-gnatS} (@code{gcc})
3897 Print package Standard.
3898
3899 @item -gnatt
3900 @cindex @option{-gnatt} (@code{gcc})
3901 Generate tree output file.
3902
3903 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3904 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3905 All compiler tables start at @var{nnn} times usual starting size.
3906
3907 @item -gnatu
3908 @cindex @option{-gnatu} (@code{gcc})
3909 List units for this compilation.
3910
3911 @item -gnatU
3912 @cindex @option{-gnatU} (@code{gcc})
3913 Tag all error messages with the unique string ``error:''
3914
3915 @item -gnatv
3916 @cindex @option{-gnatv} (@code{gcc})
3917 Verbose mode. Full error output with source lines to @file{stdout}.
3918
3919 @item -gnatV
3920 @cindex @option{-gnatV} (@code{gcc})
3921 Control level of validity checking. See separate section describing
3922 this feature.
3923
3924 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3925 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3926 Warning mode where
3927 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3928 the exact warnings that
3929 are enabled or disabled. (see @ref{Warning Message Control})
3930
3931 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3932 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3933 Wide character encoding method
3934 @ifclear vms
3935 (@var{e}=n/h/u/s/e/8).
3936 @end ifclear
3937 @ifset vms
3938 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3939 @end ifset
3940
3941 @item -gnatx
3942 @cindex @option{-gnatx} (@code{gcc})
3943 Suppress generation of cross-reference information.
3944
3945 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3946 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3947 Enable built-in style checks. (see @ref{Style Checking})
3948
3949 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3950 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3951 Distribution stub generation and compilation
3952 @ifclear vms
3953 (@var{m}=r/c for receiver/caller stubs).
3954 @end ifclear
3955 @ifset vms
3956 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3957 to be generated and compiled).
3958 @end ifset
3959
3960 @item -gnatZ
3961 Use the zero cost method for exception handling
3962
3963 @item ^-I^/SEARCH=^@var{dir}
3964 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3965 @cindex RTL
3966 Direct GNAT to search the @var{dir} directory for source files needed by
3967 the current compilation
3968 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3969
3970 @item ^-I-^/NOCURRENT_DIRECTORY^
3971 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3972 @cindex RTL
3973 Except for the source file named in the command line, do not look for source
3974 files in the directory containing the source file named in the command line
3975 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3976
3977 @ifclear vms
3978 @item -mbig-switch
3979 @cindex @option{-mbig-switch} (@command{gcc})
3980 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3981 This standard gcc switch causes the compiler to use larger offsets in its
3982 jump table representation for @code{case} statements.
3983 This may result in less efficient code, but is sometimes necessary
3984 (for example on HP-UX targets)
3985 @cindex HP-UX and @option{-mbig-switch} option
3986 in order to compile large and/or nested @code{case} statements.
3987
3988 @item -o @var{file}
3989 @cindex @option{-o} (@code{gcc})
3990 This switch is used in @code{gcc} to redirect the generated object file
3991 and its associated ALI file. Beware of this switch with GNAT, because it may
3992 cause the object file and ALI file to have different names which in turn
3993 may confuse the binder and the linker.
3994 @end ifclear
3995
3996 @item -nostdinc
3997 @cindex @option{-nostdinc} (@command{gcc})
3998 Inhibit the search of the default location for the GNAT Run Time
3999 Library (RTL) source files.
4000
4001 @item -nostdlib
4002 @cindex @option{-nostdlib} (@command{gcc})
4003 Inhibit the search of the default location for the GNAT Run Time
4004 Library (RTL) ALI files.
4005
4006 @ifclear vms
4007 @item -O[@var{n}]
4008 @cindex @option{-O} (@code{gcc})
4009 @var{n} controls the optimization level.
4010
4011 @table @asis
4012 @item n = 0
4013 No optimization, the default setting if no @option{-O} appears
4014
4015 @item n = 1
4016 Normal optimization, the default if you specify @option{-O} without
4017 an operand.
4018
4019 @item n = 2
4020 Extensive optimization
4021
4022 @item n = 3
4023 Extensive optimization with automatic inlining of subprograms not
4024 specified by pragma @code{Inline}. This applies only to
4025 inlining within a unit. For details on control of inlining
4026 see @xref{Subprogram Inlining Control}.
4027 @end table
4028 @end ifclear
4029
4030 @ifset vms
4031 @item  /NOOPTIMIZE
4032 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4033 Equivalent to @option{/OPTIMIZE=NONE}.
4034 This is the default behavior in the absence of an @option{/OPTMIZE}
4035 qualifier.
4036
4037 @item /OPTIMIZE[=(keyword[,...])]
4038 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4039 Selects the level of optimization for your program. The supported
4040 keywords are as follows:
4041 @table @code
4042 @item   ALL
4043 Perform most optimizations, including those that
4044 are expensive.
4045 This is the default if the @option{/OPTMIZE} qualifier is supplied
4046 without keyword options.
4047
4048 @item   NONE
4049 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4050
4051 @item SOME
4052 Perform some optimizations, but omit ones that are costly.
4053
4054 @item   DEVELOPMENT
4055 Same as @code{SOME}.
4056
4057 @item   INLINING
4058 Full optimization, and also attempt automatic inlining of small
4059 subprograms within a unit even when pragma @code{Inline}
4060 is not specified (@pxref{Inlining of Subprograms}).
4061
4062 @item   UNROLL_LOOPS
4063 Try to unroll loops. This keyword may be specified together with
4064 any keyword above other than @code{NONE}. Loop unrolling
4065 usually, but not always, improves the performance of programs.
4066 @end table
4067 @end ifset
4068
4069 @ifclear vms
4070 @item -pass-exit-codes
4071 @cindex @option{-pass-exit-codes} (@code{gcc})
4072 Catch exit codes from the compiler and use the most meaningful as
4073 exit status.
4074 @end ifclear
4075
4076 @item --RTS=@var{rts-path}
4077 @cindex @option{--RTS} (@code{gcc})
4078 Specifies the default location of the runtime library. Same meaning as the
4079 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4080
4081 @item ^-S^/ASM^
4082 @cindex @option{^-S^/ASM^} (@code{gcc})
4083 ^Used in place of @option{-c} to^Used to^
4084 cause the assembler source file to be
4085 generated, using @file{^.s^.S^} as the extension,
4086 instead of the object file.
4087 This may be useful if you need to examine the generated assembly code.
4088
4089 @item ^-v^/VERBOSE^
4090 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4091 Show commands generated by the @code{gcc} driver. Normally used only for
4092 debugging purposes or if you need to be sure what version of the
4093 compiler you are executing.
4094
4095 @ifclear vms
4096 @item -V @var{ver}
4097 @cindex @option{-V} (@code{gcc})
4098 Execute @var{ver} version of the compiler. This is the @code{gcc}
4099 version, not the GNAT version.
4100 @end ifclear
4101
4102 @end table
4103
4104 @ifclear vms
4105 You may combine a sequence of GNAT switches into a single switch. For
4106 example, the combined switch
4107
4108 @cindex Combining GNAT switches
4109 @smallexample
4110 -gnatofi3
4111 @end smallexample
4112
4113 @noindent
4114 is equivalent to specifying the following sequence of switches:
4115
4116 @smallexample
4117 -gnato -gnatf -gnati3
4118 @end smallexample
4119 @end ifclear
4120
4121
4122 @c NEED TO CHECK THIS FOR VMS
4123
4124 @noindent
4125 The following restrictions apply to the combination of switches
4126 in this manner:
4127
4128 @itemize @bullet
4129 @item
4130 The switch @option{-gnatc} if combined with other switches must come
4131 first in the string.
4132
4133 @item
4134 The switch @option{-gnats} if combined with other switches must come
4135 first in the string.
4136
4137 @item
4138 The switches
4139 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4140 may not be combined with any other switches.
4141
4142 @ifclear vms
4143 @item
4144 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4145 switch), then all further characters in the switch are interpreted
4146 as style modifiers (see description of @option{-gnaty}).
4147
4148 @item
4149 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4150 switch), then all further characters in the switch are interpreted
4151 as debug flags (see description of @option{-gnatd}).
4152
4153 @item
4154 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4155 switch), then all further characters in the switch are interpreted
4156 as warning mode modifiers (see description of @option{-gnatw}).
4157
4158 @item
4159 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4160 switch), then all further characters in the switch are interpreted
4161 as validity checking options (see description of @option{-gnatV}).
4162 @end ifclear
4163 @end itemize
4164
4165
4166 @node Output and Error Message Control
4167 @subsection Output and Error Message Control
4168 @findex stderr
4169
4170 @noindent
4171 The standard default format for error messages is called ``brief format''.
4172 Brief format messages are written to @file{stderr} (the standard error
4173 file) and have the following form:
4174
4175 @smallexample
4176 e.adb:3:04: Incorrect spelling of keyword "function"
4177 e.adb:4:20: ";" should be "is"
4178 @end smallexample
4179
4180 @noindent
4181 The first integer after the file name is the line number in the file,
4182 and the second integer is the column number within the line.
4183 @code{glide} can parse the error messages
4184 and point to the referenced character.
4185 The following switches provide control over the error message
4186 format:
4187
4188 @table @option
4189 @c !sort!
4190 @item -gnatv
4191 @cindex @option{-gnatv} (@code{gcc})
4192 @findex stdout
4193 @ifclear vms
4194 The v stands for verbose.
4195 @end ifclear
4196 The effect of this setting is to write long-format error
4197 messages to @file{stdout} (the standard output file.
4198 The same program compiled with the
4199 @option{-gnatv} switch would generate:
4200
4201 @smallexample
4202 @cartouche
4203 3. funcion X (Q : Integer)
4204    |
4205 >>> Incorrect spelling of keyword "function"
4206 4. return Integer;
4207                  |
4208 >>> ";" should be "is"
4209 @end cartouche
4210 @end smallexample
4211
4212 @noindent
4213 The vertical bar indicates the location of the error, and the @samp{>>>}
4214 prefix can be used to search for error messages. When this switch is
4215 used the only source lines output are those with errors.
4216
4217 @item -gnatl
4218 @cindex @option{-gnatl} (@code{gcc})
4219 @ifclear vms
4220 The @code{l} stands for list.
4221 @end ifclear
4222 This switch causes a full listing of
4223 the file to be generated. The output might look as follows:
4224
4225 @smallexample
4226 @cartouche
4227  1. procedure E is
4228  2.    V : Integer;
4229  3.    funcion X (Q : Integer)
4230        |
4231     >>> Incorrect spelling of keyword "function"
4232  4.     return Integer;
4233                       |
4234     >>> ";" should be "is"
4235  5.    begin
4236  6.       return Q + Q;
4237  7.    end;
4238  8. begin
4239  9.    V := X + X;
4240 10.end E;
4241 @end cartouche
4242 @end smallexample
4243
4244 @noindent
4245 @findex stderr
4246 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4247 standard output is redirected, a brief summary is written to
4248 @file{stderr} (standard error) giving the number of error messages and
4249 warning messages generated.
4250
4251 @item -gnatU
4252 @cindex @option{-gnatU} (@code{gcc})
4253 This switch forces all error messages to be preceded by the unique
4254 string ``error:''. This means that error messages take a few more
4255 characters in space, but allows easy searching for and identification
4256 of error messages.
4257
4258 @item -gnatb
4259 @cindex @option{-gnatb} (@code{gcc})
4260 @ifclear vms
4261 The @code{b} stands for brief.
4262 @end ifclear
4263 This switch causes GNAT to generate the
4264 brief format error messages to @file{stderr} (the standard error
4265 file) as well as the verbose
4266 format message or full listing (which as usual is written to
4267 @file{stdout} (the standard output file).
4268
4269 @item -gnatm^^=^@var{n}
4270 @cindex @option{-gnatm} (@code{gcc})
4271 @ifclear vms
4272 The @code{m} stands for maximum.
4273 @end ifclear
4274 @var{n} is a decimal integer in the
4275 range of 1 to 999 and limits the number of error messages to be
4276 generated. For example, using @option{-gnatm2} might yield
4277
4278 @smallexample
4279 e.adb:3:04: Incorrect spelling of keyword "function"
4280 e.adb:5:35: missing ".."
4281 fatal error: maximum errors reached
4282 compilation abandoned
4283 @end smallexample
4284
4285 @item -gnatf
4286 @cindex @option{-gnatf} (@code{gcc})
4287 @cindex Error messages, suppressing
4288 @ifclear vms
4289 The @code{f} stands for full.
4290 @end ifclear
4291 Normally, the compiler suppresses error messages that are likely to be
4292 redundant. This switch causes all error
4293 messages to be generated. In particular, in the case of
4294 references to undefined variables. If a given variable is referenced
4295 several times, the normal format of messages is
4296 @smallexample
4297 e.adb:7:07: "V" is undefined (more references follow)
4298 @end smallexample
4299
4300 @noindent
4301 where the parenthetical comment warns that there are additional
4302 references to the variable @code{V}. Compiling the same program with the
4303 @option{-gnatf} switch yields
4304
4305 @smallexample
4306 e.adb:7:07: "V" is undefined
4307 e.adb:8:07: "V" is undefined
4308 e.adb:8:12: "V" is undefined
4309 e.adb:8:16: "V" is undefined
4310 e.adb:9:07: "V" is undefined
4311 e.adb:9:12: "V" is undefined
4312 @end smallexample
4313
4314 @noindent
4315 The @option{-gnatf} switch also generates additional information for
4316 some error messages.  Some examples are:
4317
4318 @itemize @bullet
4319 @item
4320 Full details on entities not available in high integrity mode
4321 @item
4322 Details on possibly non-portable unchecked conversion
4323 @item
4324 List possible interpretations for ambiguous calls
4325 @item
4326 Additional details on incorrect parameters
4327 @end itemize
4328
4329
4330 @item -gnatq
4331 @cindex @option{-gnatq} (@code{gcc})
4332 @ifclear vms
4333 The @code{q} stands for quit (really ``don't quit'').
4334 @end ifclear
4335 In normal operation mode, the compiler first parses the program and
4336 determines if there are any syntax errors. If there are, appropriate
4337 error messages are generated and compilation is immediately terminated.
4338 This switch tells
4339 GNAT to continue with semantic analysis even if syntax errors have been
4340 found. This may enable the detection of more errors in a single run. On
4341 the other hand, the semantic analyzer is more likely to encounter some
4342 internal fatal error when given a syntactically invalid tree.
4343
4344 @item -gnatQ
4345 @cindex @option{-gnatQ} (@code{gcc})
4346 In normal operation mode, the @file{ALI} file is not generated if any
4347 illegalities are detected in the program. The use of @option{-gnatQ} forces
4348 generation of the @file{ALI} file. This file is marked as being in
4349 error, so it cannot be used for binding purposes, but it does contain
4350 reasonably complete cross-reference information, and thus may be useful
4351 for use by tools (e.g. semantic browsing tools or integrated development
4352 environments) that are driven from the @file{ALI} file. This switch
4353 implies @option{-gnatq}, since the semantic phase must be run to get a
4354 meaningful ALI file.
4355
4356 In addition, if @option{-gnatt} is also specified, then the tree file is
4357 generated even if there are illegalities. It may be useful in this case
4358 to also specify @option{-gnatq} to ensure that full semantic processing
4359 occurs. The resulting tree file can be processed by ASIS, for the purpose
4360 of providing partial information about illegal units, but if the error
4361 causes the tree to be badly malformed, then ASIS may crash during the
4362 analysis.
4363
4364 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4365 being in error, @code{gnatmake} will attempt to recompile the source when it
4366 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4367
4368 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4369 since ALI files are never generated if @option{-gnats} is set.
4370
4371 @end table
4372
4373
4374 @node Warning Message Control
4375 @subsection Warning Message Control
4376 @cindex Warning messages
4377 @noindent
4378 In addition to error messages, which correspond to illegalities as defined
4379 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4380 situations.
4381
4382 First, the compiler considers some constructs suspicious and generates a
4383 warning message to alert you to a possible error. Second, if the
4384 compiler detects a situation that is sure to raise an exception at
4385 run time, it generates a warning message. The following shows an example
4386 of warning messages:
4387 @smallexample
4388 e.adb:4:24: warning: creation of object may raise Storage_Error
4389 e.adb:10:17: warning: static value out of range
4390 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4391 @end smallexample
4392
4393 @noindent
4394 GNAT considers a large number of situations as appropriate
4395 for the generation of warning messages. As always, warnings are not
4396 definite indications of errors. For example, if you do an out-of-range
4397 assignment with the deliberate intention of raising a
4398 @code{Constraint_Error} exception, then the warning that may be
4399 issued does not indicate an error. Some of the situations for which GNAT
4400 issues warnings (at least some of the time) are given in the following
4401 list. This list is not complete, and new warnings are often added to
4402 subsequent versions of GNAT. The list is intended to give a general idea
4403 of the kinds of warnings that are generated.
4404
4405 @itemize @bullet
4406 @item
4407 Possible infinitely recursive calls
4408
4409 @item
4410 Out-of-range values being assigned
4411
4412 @item
4413 Possible order of elaboration problems
4414
4415 @item
4416 Unreachable code
4417
4418 @item
4419 Fixed-point type declarations with a null range
4420
4421 @item
4422 Variables that are never assigned a value
4423
4424 @item
4425 Variables that are referenced before being initialized
4426
4427 @item
4428 Task entries with no corresponding @code{accept} statement
4429
4430 @item
4431 Duplicate accepts for the same task entry in a @code{select}
4432
4433 @item
4434 Objects that take too much storage
4435
4436 @item
4437 Unchecked conversion between types of differing sizes
4438
4439 @item
4440 Missing @code{return} statement along some execution path in a function
4441
4442 @item
4443 Incorrect (unrecognized) pragmas
4444
4445 @item
4446 Incorrect external names
4447
4448 @item
4449 Allocation from empty storage pool
4450
4451 @item
4452 Potentially blocking operation in protected type
4453
4454 @item
4455 Suspicious parenthesization of expressions
4456
4457 @item
4458 Mismatching bounds in an aggregate
4459
4460 @item
4461 Attempt to return local value by reference
4462
4463
4464 @item
4465 Premature instantiation of a generic body
4466
4467 @item
4468 Attempt to pack aliased components
4469
4470 @item
4471 Out of bounds array subscripts
4472
4473 @item
4474 Wrong length on string assignment
4475
4476 @item
4477 Violations of style rules if style checking is enabled
4478
4479 @item
4480 Unused @code{with} clauses
4481
4482 @item
4483 @code{Bit_Order} usage that does not have any effect
4484
4485 @item
4486 @code{Standard.Duration} used to resolve universal fixed expression
4487
4488 @item
4489 Dereference of possibly null value
4490
4491 @item
4492 Declaration that is likely to cause storage error
4493
4494 @item
4495 Internal GNAT unit @code{with}'ed by application unit
4496
4497 @item
4498 Values known to be out of range at compile time
4499
4500 @item
4501 Unreferenced labels and variables
4502
4503 @item
4504 Address overlays that could clobber memory
4505
4506 @item
4507 Unexpected initialization when address clause present
4508
4509 @item
4510 Bad alignment for address clause
4511
4512 @item
4513 Useless type conversions
4514
4515 @item
4516 Redundant assignment statements and other redundant constructs
4517
4518 @item
4519 Useless exception handlers
4520
4521 @item
4522 Accidental hiding of name by child unit
4523
4524
4525 @item
4526 Access before elaboration detected at compile time
4527
4528 @item
4529 A range in a @code{for} loop that is known to be null or might be null
4530
4531 @end itemize
4532
4533 @noindent
4534 The following switches are available to control the handling of
4535 warning messages:
4536
4537 @table @option
4538 @c !sort!
4539 @item -gnatwa
4540 @emph{Activate all optional errors.}
4541 @cindex @option{-gnatwa} (@code{gcc})
4542 This switch activates most optional warning messages, see remaining list
4543 in this section for details on optional warning messages that can be
4544 individually controlled.  The warnings that are not turned on by this
4545 switch are
4546 @option{-gnatwd} (implicit dereferencing),
4547 @option{-gnatwh} (hiding),
4548 and @option{-gnatwl} (elaboration warnings).
4549 All other optional warnings are turned on.
4550
4551 @item -gnatwA
4552 @emph{Suppress all optional errors.}
4553 @cindex @option{-gnatwA} (@code{gcc})
4554 This switch suppresses all optional warning messages, see remaining list
4555 in this section for details on optional warning messages that can be
4556 individually controlled.
4557
4558 @item -gnatwc
4559 @emph{Activate warnings on conditionals.}
4560 @cindex @option{-gnatwc} (@code{gcc})
4561 @cindex Conditionals, constant
4562 This switch activates warnings for conditional expressions used in
4563 tests that are known to be True or False at compile time. The default
4564 is that such warnings are not generated.
4565 Note that this warning does
4566 not get issued for the use of boolean variables or constants whose
4567 values are known at compile time, since this is a standard technique
4568 for conditional compilation in Ada, and this would generate too many
4569 ``false positive'' warnings.
4570 This warning can also be turned on using @option{-gnatwa}.
4571
4572 @item -gnatwC
4573 @emph{Suppress warnings on conditionals.}
4574 @cindex @option{-gnatwC} (@code{gcc})
4575 This switch suppresses warnings for conditional expressions used in
4576 tests that are known to be True or False at compile time.
4577
4578 @item -gnatwd
4579 @emph{Activate warnings on implicit dereferencing.}
4580 @cindex @option{-gnatwd} (@code{gcc})
4581 If this switch is set, then the use of a prefix of an access type
4582 in an indexed component, slice, or selected component without an
4583 explicit @code{.all} will generate a warning. With this warning
4584 enabled, access checks occur only at points where an explicit
4585 @code{.all} appears in the source code (assuming no warnings are
4586 generated as a result of this switch). The default is that such
4587 warnings are not generated.
4588 Note that @option{-gnatwa} does not affect the setting of
4589 this warning option.
4590
4591 @item -gnatwD
4592 @emph{Suppress warnings on implicit dereferencing.}
4593 @cindex @option{-gnatwD} (@code{gcc})
4594 @cindex Implicit dereferencing
4595 @cindex Dereferencing, implicit
4596 This switch suppresses warnings for implicit dereferences in
4597 indexed components, slices, and selected components.
4598
4599 @item -gnatwe
4600 @emph{Treat warnings as errors.}
4601 @cindex @option{-gnatwe} (@code{gcc})
4602 @cindex Warnings, treat as error
4603 This switch causes warning messages to be treated as errors.
4604 The warning string still appears, but the warning messages are counted
4605 as errors, and prevent the generation of an object file.
4606
4607 @item -gnatwf
4608 @emph{Activate warnings on unreferenced formals.}
4609 @cindex @option{-gnatwf} (@code{gcc})
4610 @cindex Formals, unreferenced
4611 This switch causes a warning to be generated if a formal parameter
4612 is not referenced in the body of the subprogram. This warning can
4613 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4614
4615 @item -gnatwF
4616 @emph{Suppress warnings on unreferenced formals.}
4617 @cindex @option{-gnatwF} (@code{gcc})
4618 This switch suppresses warnings for unreferenced formal
4619 parameters. Note that the
4620 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4621 effect of warning on unreferenced entities other than subprogram
4622 formals.
4623
4624 @item -gnatwg
4625 @emph{Activate warnings on unrecognized pragmas.}
4626 @cindex @option{-gnatwg} (@code{gcc})
4627 @cindex Pragmas, unrecognized
4628 This switch causes a warning to be generated if an unrecognized
4629 pragma is encountered. Apart from issuing this warning, the
4630 pragma is ignored and has no effect. This warning can
4631 also be turned on using @option{-gnatwa}. The default
4632 is that such warnings are issued (satisfying the Ada Reference
4633 Manual requirement that such warnings appear).
4634
4635 @item -gnatwG
4636 @emph{Suppress warnings on unrecognized pragmas.}
4637 @cindex @option{-gnatwG} (@code{gcc})
4638 This switch suppresses warnings for unrecognized pragmas.
4639
4640 @item -gnatwh
4641 @emph{Activate warnings on hiding.}
4642 @cindex @option{-gnatwh} (@code{gcc})
4643 @cindex Hiding of Declarations
4644 This switch activates warnings on hiding declarations.
4645 A declaration is considered hiding
4646 if it is for a non-overloadable entity, and it declares an entity with the
4647 same name as some other entity that is directly or use-visible. The default
4648 is that such warnings are not generated.
4649 Note that @option{-gnatwa} does not affect the setting of this warning option.
4650
4651 @item -gnatwH
4652 @emph{Suppress warnings on hiding.}
4653 @cindex @option{-gnatwH} (@code{gcc})
4654 This switch suppresses warnings on hiding declarations.
4655
4656 @item -gnatwi
4657 @emph{Activate warnings on implementation units.}
4658 @cindex @option{-gnatwi} (@code{gcc})
4659 This switch activates warnings for a @code{with} of an internal GNAT
4660 implementation unit, defined as any unit from the @code{Ada},
4661 @code{Interfaces}, @code{GNAT},
4662 ^^@code{DEC},^ or @code{System}
4663 hierarchies that is not
4664 documented in either the Ada Reference Manual or the GNAT
4665 Programmer's Reference Manual. Such units are intended only
4666 for internal implementation purposes and should not be @code{with}'ed
4667 by user programs. The default is that such warnings are generated
4668 This warning can also be turned on using @option{-gnatwa}.
4669
4670 @item -gnatwI
4671 @emph{Disable warnings on implementation units.}
4672 @cindex @option{-gnatwI} (@code{gcc})
4673 This switch disables warnings for a @code{with} of an internal GNAT
4674 implementation unit.
4675
4676 @item -gnatwj
4677 @emph{Activate warnings on obsolescent features (Annex J).}
4678 @cindex @option{-gnatwj} (@code{gcc})
4679 @cindex Features, obsolescent
4680 @cindex Obsolescent features
4681 If this warning option is activated, then warnings are generated for
4682 calls to subprograms marked with @code{pragma Obsolescent} and
4683 for use of features in Annex J of the Ada Reference Manual. In the
4684 case of Annex J, not all features are flagged. In particular use
4685 of the renamed packages (like @code{Text_IO}) and use of package
4686 @code{ASCII} are not flagged, since these are very common and
4687 would generate many annoying positive warnings. The default is that
4688 such warnings are not generated.
4689
4690 @item -gnatwJ
4691 @emph{Suppress warnings on obsolescent features (Annex J).}
4692 @cindex @option{-gnatwJ} (@code{gcc})
4693 This switch disables warnings on use of obsolescent features.
4694
4695 @item -gnatwk
4696 @emph{Activate warnings on variables that could be constants.}
4697 @cindex @option{-gnatwk} (@code{gcc})
4698 This switch activates warnings for variables that are initialized but
4699 never modified, and then could be declared constants.
4700
4701 @item -gnatwK
4702 @emph{Suppress warnings on variables that could be constants.}
4703 @cindex @option{-gnatwK} (@code{gcc})
4704 This switch disables warnings on variables that could be declared constants.
4705
4706 @item -gnatwl
4707 @emph{Activate warnings for missing elaboration pragmas.}
4708 @cindex @option{-gnatwl} (@code{gcc})
4709 @cindex Elaboration, warnings
4710 This switch activates warnings on missing
4711 @code{pragma Elaborate_All} statements.
4712 See the section in this guide on elaboration checking for details on
4713 when such pragma should be used. Warnings are also generated if you
4714 are using the static mode of elaboration, and a @code{pragma Elaborate}
4715 is encountered. The default is that such warnings
4716 are not generated.
4717 This warning is not automatically turned on by the use of @option{-gnatwa}.
4718
4719 @item -gnatwL
4720 @emph{Suppress warnings for missing elaboration pragmas.}
4721 @cindex @option{-gnatwL} (@code{gcc})
4722 This switch suppresses warnings on missing pragma Elaborate_All statements.
4723 See the section in this guide on elaboration checking for details on
4724 when such pragma should be used.
4725
4726 @item -gnatwm
4727 @emph{Activate warnings on modified but unreferenced variables.}
4728 @cindex @option{-gnatwm} (@code{gcc})
4729 This switch activates warnings for variables that are assigned (using
4730 an initialization value or with one or more assignment statements) but
4731 whose value is never read. The warning is suppressed for volatile
4732 variables and also for variables that are renamings of other variables
4733 or for which an address clause is given.
4734 This warning can also be turned on using @option{-gnatwa}.
4735
4736 @item -gnatwM
4737 @emph{Disable warnings on modified but unreferenced variables.}
4738 @cindex @option{-gnatwM} (@code{gcc})
4739 This switch disables warnings for variables that are assigned or
4740 initialized, but never read.
4741
4742 @item -gnatwn
4743 @emph{Set normal warnings mode.}
4744 @cindex @option{-gnatwn} (@code{gcc})
4745 This switch sets normal warning mode, in which enabled warnings are
4746 issued and treated as warnings rather than errors. This is the default
4747 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4748 an explicit @option{-gnatws} or
4749 @option{-gnatwe}. It also cancels the effect of the
4750 implicit @option{-gnatwe} that is activated by the
4751 use of @option{-gnatg}.
4752
4753 @item -gnatwo
4754 @emph{Activate warnings on address clause overlays.}
4755 @cindex @option{-gnatwo} (@code{gcc})
4756 @cindex Address Clauses, warnings
4757 This switch activates warnings for possibly unintended initialization
4758 effects of defining address clauses that cause one variable to overlap
4759 another. The default is that such warnings are generated.
4760 This warning can also be turned on using @option{-gnatwa}.
4761
4762 @item -gnatwO
4763 @emph{Suppress warnings on address clause overlays.}
4764 @cindex @option{-gnatwO} (@code{gcc})
4765 This switch suppresses warnings on possibly unintended initialization
4766 effects of defining address clauses that cause one variable to overlap
4767 another.
4768
4769 @item -gnatwp
4770 @emph{Activate warnings on ineffective pragma Inlines.}
4771 @cindex @option{-gnatwp} (@code{gcc})
4772 @cindex Inlining, warnings
4773 This switch activates warnings for failure of front end inlining
4774 (activated by @option{-gnatN}) to inline a particular call. There are
4775 many reasons for not being able to inline a call, including most
4776 commonly that the call is too complex to inline.
4777 This warning can also be turned on using @option{-gnatwa}.
4778
4779 @item -gnatwP
4780 @emph{Suppress warnings on ineffective pragma Inlines.}
4781 @cindex @option{-gnatwP} (@code{gcc})
4782 This switch suppresses warnings on ineffective pragma Inlines. If the
4783 inlining mechanism cannot inline a call, it will simply ignore the
4784 request silently.
4785
4786 @item -gnatwr
4787 @emph{Activate warnings on redundant constructs.}
4788 @cindex @option{-gnatwr} (@code{gcc})
4789 This switch activates warnings for redundant constructs. The following
4790 is the current list of constructs regarded as redundant:
4791 This warning can also be turned on using @option{-gnatwa}.
4792
4793 @itemize @bullet
4794 @item
4795 Assignment of an item to itself.
4796 @item
4797 Type conversion that converts an expression to its own type.
4798 @item
4799 Use of the attribute @code{Base} where @code{typ'Base} is the same
4800 as @code{typ}.
4801 @item
4802 Use of pragma @code{Pack} when all components are placed by a record
4803 representation clause.
4804 @item
4805 Exception handler containing only a reraise statement (raise with no
4806 operand) which has no effect.
4807 @item
4808 Use of the operator abs on an operand that is known at compile time
4809 to be non-negative
4810 @item
4811 Use of an unnecessary extra level of parentheses (C-style) around conditions
4812 in @code{if} statements, @code{while} statements and @code{exit} statements.
4813 @item
4814 Comparison of boolean expressions to an explicit True value.
4815 @end itemize
4816
4817 @item -gnatwR
4818 @emph{Suppress warnings on redundant constructs.}
4819 @cindex @option{-gnatwR} (@code{gcc})
4820 This switch suppresses warnings for redundant constructs.
4821
4822 @item -gnatws
4823 @emph{Suppress all warnings.}
4824 @cindex @option{-gnatws} (@code{gcc})
4825 This switch completely suppresses the
4826 output of all warning messages from the GNAT front end.
4827 Note that it does not suppress warnings from the @code{gcc} back end.
4828 To suppress these back end warnings as well, use the switch @option{-w}
4829 in addition to @option{-gnatws}.
4830
4831 @item -gnatwu
4832 @emph{Activate warnings on unused entities.}
4833 @cindex @option{-gnatwu} (@code{gcc})
4834 This switch activates warnings to be generated for entities that
4835 are declared but not referenced, and for units that are @code{with}'ed
4836 and not
4837 referenced. In the case of packages, a warning is also generated if
4838 no entities in the package are referenced. This means that if the package
4839 is referenced but the only references are in @code{use}
4840 clauses or @code{renames}
4841 declarations, a warning is still generated. A warning is also generated
4842 for a generic package that is @code{with}'ed but never instantiated.
4843 In the case where a package or subprogram body is compiled, and there
4844 is a @code{with} on the corresponding spec
4845 that is only referenced in the body,
4846 a warning is also generated, noting that the
4847 @code{with} can be moved to the body. The default is that
4848 such warnings are not generated.
4849 This switch also activates warnings on unreferenced formals
4850 (it is includes the effect of @option{-gnatwf}).
4851 This warning can also be turned on using @option{-gnatwa}.
4852
4853 @item -gnatwU
4854 @emph{Suppress warnings on unused entities.}
4855 @cindex @option{-gnatwU} (@code{gcc})
4856 This switch suppresses warnings for unused entities and packages.
4857 It also turns off warnings on unreferenced formals (and thus includes
4858 the effect of @option{-gnatwF}).
4859
4860 @item -gnatwv
4861 @emph{Activate warnings on unassigned variables.}
4862 @cindex @option{-gnatwv} (@code{gcc})
4863 @cindex Unassigned variable warnings
4864 This switch activates warnings for access to variables which
4865 may not be properly initialized. The default is that
4866 such warnings are generated.
4867
4868 @item -gnatwV
4869 @emph{Suppress warnings on unassigned variables.}
4870 @cindex @option{-gnatwV} (@code{gcc})
4871 This switch suppresses warnings for access to variables which
4872 may not be properly initialized.
4873
4874 @item -gnatwx
4875 @emph{Activate warnings on Export/Import pragmas.}
4876 @cindex @option{-gnatwx} (@code{gcc})
4877 @cindex Export/Import pragma warnings
4878 This switch activates warnings on Export/Import pragmas when
4879 the compiler detects a possible conflict between the Ada and
4880 foreign language calling sequences. For example, the use of
4881 default parameters in a convention C procedure is dubious
4882 because the C compiler cannot supply the proper default, so
4883 a warning is issued. The default is that such warnings are
4884 generated.
4885
4886 @item -gnatwX
4887 @emph{Suppress warnings on Export/Import pragmas.}
4888 @cindex @option{-gnatwX} (@code{gcc})
4889 This switch suppresses warnings on Export/Import pragmas.
4890 The sense of this is that you are telling the compiler that
4891 you know what you are doing in writing the pragma, and it
4892 should not complain at you.
4893
4894 @item -gnatwz
4895 @emph{Activate warnings on unchecked conversions.}
4896 @cindex @option{-gnatwz} (@code{gcc})
4897 @cindex Unchecked_Conversion warnings
4898 This switch activates warnings for unchecked conversions
4899 where the types are known at compile time to have different
4900 sizes. The default
4901 is that such warnings are generated.
4902
4903 @item -gnatwZ
4904 @emph{Suppress warnings on unchecked conversions.}
4905 @cindex @option{-gnatwZ} (@code{gcc})
4906 This switch suppresses warnings for unchecked conversions
4907 where the types are known at compile time to have different
4908 sizes.
4909
4910 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4911 @cindex @option{-Wuninitialized}
4912 The warnings controlled by the @option{-gnatw} switch are generated by the
4913 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4914 can provide additional warnings. One such useful warning is provided by
4915 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4916 conjunction with tunrning on optimization mode. This causes the flow
4917 analysis circuits of the back end optimizer to output additional
4918 warnings about uninitialized variables.
4919
4920 @item ^-w^/NO_BACK_END_WARNINGS^
4921 @cindex @option{-w}
4922 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4923 be used in conjunction with @option{-gnatws} to ensure that all warnings
4924 are suppressed during the entire compilation process.
4925
4926 @end table
4927
4928 @noindent
4929 @ifclear vms
4930 A string of warning parameters can be used in the same parameter. For example:
4931
4932 @smallexample
4933 -gnatwaLe
4934 @end smallexample
4935
4936 @noindent
4937 will turn on all optional warnings except for elaboration pragma warnings,
4938 and also specify that warnings should be treated as errors.
4939 @end ifclear
4940 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4941
4942 @table @option
4943 @c !sort!
4944 @item -gnatwC
4945 @item -gnatwD
4946 @item -gnatwF
4947 @item -gnatwg
4948 @item -gnatwH
4949 @item -gnatwi
4950 @item -gnatwJ
4951 @item -gnatwK
4952 @item -gnatwL
4953 @item -gnatwM
4954 @item -gnatwn
4955 @item -gnatwo
4956 @item -gnatwP
4957 @item -gnatwR
4958 @item -gnatwU
4959 @item -gnatwv
4960 @item -gnatwz
4961 @item -gnatwx
4962
4963 @end table
4964
4965
4966 @node Debugging and Assertion Control
4967 @subsection Debugging and Assertion Control
4968
4969 @table @option
4970 @item -gnata
4971 @cindex @option{-gnata} (@code{gcc})
4972 @findex Assert
4973 @findex Debug
4974 @cindex Assertions
4975
4976 @noindent
4977 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4978 are ignored. This switch, where @samp{a} stands for assert, causes
4979 @code{Assert} and @code{Debug} pragmas to be activated.
4980
4981 The pragmas have the form:
4982
4983 @smallexample
4984 @cartouche
4985    @b{pragma} Assert (@var{Boolean-expression} [,
4986                       @var{static-string-expression}])
4987    @b{pragma} Debug (@var{procedure call})
4988 @end cartouche
4989 @end smallexample
4990
4991 @noindent
4992 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4993 If the result is @code{True}, the pragma has no effect (other than
4994 possible side effects from evaluating the expression). If the result is
4995 @code{False}, the exception @code{Assert_Failure} declared in the package
4996 @code{System.Assertions} is
4997 raised (passing @var{static-string-expression}, if present, as the
4998 message associated with the exception). If no string expression is
4999 given the default is a string giving the file name and line number
5000 of the pragma.
5001
5002 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5003 @code{pragma Debug} may appear within a declaration sequence, allowing
5004 debugging procedures to be called between declarations.
5005
5006 @ifset vms
5007 @item /DEBUG[=debug-level]
5008 @itemx  /NODEBUG
5009 Specifies how much debugging information is to be included in
5010 the resulting object file where 'debug-level' is one of the following:
5011 @table @code
5012 @item   TRACEBACK
5013 Include both debugger symbol records and traceback
5014 the object file.
5015 This is the default setting.
5016 @item   ALL
5017 Include both debugger symbol records and traceback in
5018 object file.
5019 @item   NONE
5020 Excludes both debugger symbol records and traceback
5021 the object file. Same as /NODEBUG.
5022 @item   SYMBOLS
5023 Includes only debugger symbol records in the object
5024 file. Note that this doesn't include traceback information.
5025 @end table
5026 @end ifset
5027 @end table
5028
5029 @node Validity Checking
5030 @subsection Validity Checking
5031 @findex Validity Checking
5032
5033 @noindent
5034 The Ada 95 Reference Manual has specific requirements for checking
5035 for invalid values. In particular, RM 13.9.1 requires that the
5036 evaluation of invalid values (for example from unchecked conversions),
5037 not result in erroneous execution. In GNAT, the result of such an
5038 evaluation in normal default mode is to either use the value
5039 unmodified, or to raise Constraint_Error in those cases where use
5040 of the unmodified value would cause erroneous execution. The cases
5041 where unmodified values might lead to erroneous execution are case
5042 statements (where a wild jump might result from an invalid value),
5043 and subscripts on the left hand side (where memory corruption could
5044 occur as a result of an invalid value).
5045
5046 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5047 checking mode.
5048 @ifclear vms
5049 The @code{x} argument is a string of letters that
5050 indicate validity checks that are performed or not performed in addition
5051 to the default checks described above.
5052 @end ifclear
5053 @ifset vms
5054 The options allowed for this qualifier
5055 indicate validity checks that are performed or not performed in addition
5056 to the default checks described above.
5057 @end ifset
5058
5059
5060 @table @option
5061 @c !sort!
5062 @item -gnatVa
5063 @emph{All validity checks.}
5064 @cindex @option{-gnatVa} (@code{gcc})
5065 All validity checks are turned on.
5066 @ifclear vms
5067 That is, @option{-gnatVa} is
5068 equivalent to @option{gnatVcdfimorst}.
5069 @end ifclear
5070
5071 @item -gnatVc
5072 @emph{Validity checks for copies.}
5073 @cindex @option{-gnatVc} (@code{gcc})
5074 The right hand side of assignments, and the initializing values of
5075 object declarations are validity checked.
5076
5077 @item -gnatVd
5078 @emph{Default (RM) validity checks.}
5079 @cindex @option{-gnatVd} (@code{gcc})
5080 Some validity checks are done by default following normal Ada semantics
5081 (RM 13.9.1 (9-11)).
5082 A check is done in case statements that the expression is within the range
5083 of the subtype. If it is not, Constraint_Error is raised.
5084 For assignments to array components, a check is done that the expression used
5085 as index is within the range. If it is not, Constraint_Error is raised.
5086 Both these validity checks may be turned off using switch @option{-gnatVD}.
5087 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5088 switch @option{-gnatVd} will leave the checks turned on.
5089 Switch @option{-gnatVD} should be used only if you are sure that all such
5090 expressions have valid values. If you use this switch and invalid values
5091 are present, then the program is erroneous, and wild jumps or memory
5092 overwriting may occur.
5093
5094 @item -gnatVf
5095 @emph{Validity checks for floating-point values.}
5096 @cindex @option{-gnatVf} (@code{gcc})
5097 In the absence of this switch, validity checking occurs only for discrete
5098 values. If @option{-gnatVf} is specified, then validity checking also applies
5099 for floating-point values, and NaN's and infinities are considered invalid,
5100 as well as out of range values for constrained types. Note that this means
5101 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5102 in which floating-point values are checked depends on the setting of other
5103 options. For example,
5104 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5105 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5106 (the order does not matter) specifies that floating-point parameters of mode
5107 @code{in} should be validity checked.
5108
5109 @item -gnatVi
5110 @emph{Validity checks for @code{in} mode parameters}
5111 @cindex @option{-gnatVi} (@code{gcc})
5112 Arguments for parameters of mode @code{in} are validity checked in function
5113 and procedure calls at the point of call.
5114
5115 @item -gnatVm
5116 @emph{Validity checks for @code{in out} mode parameters.}
5117 @cindex @option{-gnatVm} (@code{gcc})
5118 Arguments for parameters of mode @code{in out} are validity checked in
5119 procedure calls at the point of call. The @code{'m'} here stands for
5120 modify, since this concerns parameters that can be modified by the call.
5121 Note that there is no specific option to test @code{out} parameters,
5122 but any reference within the subprogram will be tested in the usual
5123 manner, and if an invalid value is copied back, any reference to it
5124 will be subject to validity checking.
5125
5126 @item -gnatVn
5127 @emph{No validity checks.}
5128 @cindex @option{-gnatVn} (@code{gcc})
5129 This switch turns off all validity checking, including the default checking
5130 for case statements and left hand side subscripts. Note that the use of
5131 the switch @option{-gnatp} suppresses all run-time checks, including
5132 validity checks, and thus implies @option{-gnatVn}. When this switch
5133 is used, it cancels any other @option{-gnatV} previously issued.
5134
5135 @item -gnatVo
5136 @emph{Validity checks for operator and attribute operands.}
5137 @cindex @option{-gnatVo} (@code{gcc})
5138 Arguments for predefined operators and attributes are validity checked.
5139 This includes all operators in package @code{Standard},
5140 the shift operators defined as intrinsic in package @code{Interfaces}
5141 and operands for attributes such as @code{Pos}. Checks are also made
5142 on individual component values for composite comparisons.
5143
5144 @item -gnatVp
5145 @emph{Validity checks for parameters.}
5146 @cindex @option{-gnatVp} (@code{gcc})
5147 This controls the treatment of parameters within a subprogram (as opposed
5148 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5149 of parameters on a call. If either of these call options is used, then
5150 normally an assumption is made within a subprogram that the input arguments
5151 have been validity checking at the point of call, and do not need checking
5152 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5153 is not made, and parameters are not assumed to be valid, so their validity
5154 will be checked (or rechecked) within the subprogram.
5155
5156 @item -gnatVr
5157 @emph{Validity checks for function returns.}
5158 @cindex @option{-gnatVr} (@code{gcc})
5159 The expression in @code{return} statements in functions is validity
5160 checked.
5161
5162 @item -gnatVs
5163 @emph{Validity checks for subscripts.}
5164 @cindex @option{-gnatVs} (@code{gcc})
5165 All subscripts expressions are checked for validity, whether they appear
5166 on the right side or left side (in default mode only left side subscripts
5167 are validity checked).
5168
5169 @item -gnatVt
5170 @emph{Validity checks for tests.}
5171 @cindex @option{-gnatVt} (@code{gcc})
5172 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5173 statements are checked, as well as guard expressions in entry calls.
5174
5175 @end table
5176
5177 @noindent
5178 The @option{-gnatV} switch may be followed by
5179 ^a string of letters^a list of options^
5180 to turn on a series of validity checking options.
5181 For example,
5182 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5183 specifies that in addition to the default validity checking, copies and
5184 function return expressions are to be validity checked.
5185 In order to make it easier
5186 to specify the desired combination of effects,
5187 @ifclear vms
5188 the upper case letters @code{CDFIMORST} may
5189 be used to turn off the corresponding lower case option.
5190 @end ifclear
5191 @ifset vms
5192 the prefix @code{NO} on an option turns off the corresponding validity
5193 checking:
5194 @itemize @bullet
5195 @item @code{NOCOPIES}
5196 @item @code{NODEFAULT}
5197 @item @code{NOFLOATS}
5198 @item @code{NOIN_PARAMS}
5199 @item @code{NOMOD_PARAMS}
5200 @item @code{NOOPERANDS}
5201 @item @code{NORETURNS}
5202 @item @code{NOSUBSCRIPTS}
5203 @item @code{NOTESTS}
5204 @end itemize
5205 @end ifset
5206 Thus
5207 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5208 turns on all validity checking options except for
5209 checking of @code{@b{in out}} procedure arguments.
5210
5211 The specification of additional validity checking generates extra code (and
5212 in the case of @option{-gnatVa} the code expansion can be substantial.
5213 However, these additional checks can be very useful in detecting
5214 uninitialized variables, incorrect use of unchecked conversion, and other
5215 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5216 is useful in conjunction with the extra validity checking, since this
5217 ensures that wherever possible uninitialized variables have invalid values.
5218
5219 See also the pragma @code{Validity_Checks} which allows modification of
5220 the validity checking mode at the program source level, and also allows for
5221 temporary disabling of validity checks.
5222
5223
5224 @node Style Checking
5225 @subsection Style Checking
5226 @findex Style checking
5227
5228 @noindent
5229 The @option{-gnaty^x^(option,option,...)^} switch
5230 @cindex @option{-gnaty} (@code{gcc})
5231 causes the compiler to
5232 enforce specified style rules. A limited set of style rules has been used
5233 in writing the GNAT sources themselves. This switch allows user programs
5234 to activate all or some of these checks. If the source program fails a
5235 specified style check, an appropriate warning message is given, preceded by
5236 the character sequence ``(style)''.
5237 @ifset vms
5238 @code{(option,option,...)} is a sequence of keywords
5239 @end ifset
5240 @ifclear vms
5241 The string @var{x} is a sequence of letters or digits
5242 @end ifclear
5243 indicating the particular style
5244 checks to be performed. The following checks are defined:
5245
5246 @table @option
5247 @c !sort!
5248 @item 1-9
5249 @emph{Specify indentation level.}
5250 If a digit from 1-9 appears
5251 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5252 then proper indentation is checked, with the digit indicating the
5253 indentation level required.
5254 The general style of required indentation is as specified by
5255 the examples in the Ada Reference Manual. Full line comments must be
5256 aligned with the @code{--} starting on a column that is a multiple of
5257 the alignment level.
5258
5259 @item ^a^ATTRIBUTE^
5260 @emph{Check attribute casing.}
5261 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5262 then attribute names, including the case of keywords such as @code{digits}
5263 used as attributes names, must be written in mixed case, that is, the
5264 initial letter and any letter following an underscore must be uppercase.
5265 All other letters must be lowercase.
5266
5267 @item ^b^BLANKS^
5268 @emph{Blanks not allowed at statement end.}
5269 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5270 trailing blanks are not allowed at the end of statements. The purpose of this
5271 rule, together with h (no horizontal tabs), is to enforce a canonical format
5272 for the use of blanks to separate source tokens.
5273
5274 @item ^c^COMMENTS^
5275 @emph{Check comments.}
5276 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5277 then comments must meet the following set of rules:
5278
5279 @itemize @bullet
5280
5281 @item
5282 The ``@code{--}'' that starts the column must either start in column one,
5283 or else at least one blank must precede this sequence.
5284
5285 @item
5286 Comments that follow other tokens on a line must have at least one blank
5287 following the ``@code{--}'' at the start of the comment.
5288
5289 @item
5290 Full line comments must have two blanks following the ``@code{--}'' that
5291 starts the comment, with the following exceptions.
5292
5293 @item
5294 A line consisting only of the ``@code{--}'' characters, possibly preceded
5295 by blanks is permitted.
5296
5297 @item
5298 A comment starting with ``@code{--x}'' where @code{x} is a special character
5299 is permitted.
5300 This allows proper processing of the output generated by specialized tools
5301 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5302 annotation
5303 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5304 special character is defined as being in one of the ASCII ranges
5305 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5306 Note that this usage is not permitted
5307 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5308
5309 @item
5310 A line consisting entirely of minus signs, possibly preceded by blanks, is
5311 permitted. This allows the construction of box comments where lines of minus
5312 signs are used to form the top and bottom of the box.
5313
5314 @item
5315 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5316 least one blank follows the initial ``@code{--}''. Together with the preceding
5317 rule, this allows the construction of box comments, as shown in the following
5318 example:
5319 @smallexample
5320 ---------------------------
5321 -- This is a box comment --
5322 -- with two text lines.  --
5323 ---------------------------
5324 @end smallexample
5325 @end itemize
5326
5327 @item ^e^END^
5328 @emph{Check end/exit labels.}
5329 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5330 optional labels on @code{end} statements ending subprograms and on
5331 @code{exit} statements exiting named loops, are required to be present.
5332
5333 @item ^f^VTABS^
5334 @emph{No form feeds or vertical tabs.}
5335 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5336 neither form feeds nor vertical tab characters are not permitted
5337 in the source text.
5338
5339 @item ^h^HTABS^
5340 @emph{No horizontal tabs.}
5341 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5342 horizontal tab characters are not permitted in the source text.
5343 Together with the b (no blanks at end of line) check, this
5344 enforces a canonical form for the use of blanks to separate
5345 source tokens.
5346
5347 @item ^i^IF_THEN^
5348 @emph{Check if-then layout.}
5349 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5350 then the keyword @code{then} must appear either on the same
5351 line as corresponding @code{if}, or on a line on its own, lined
5352 up under the @code{if} with at least one non-blank line in between
5353 containing all or part of the condition to be tested.
5354
5355 @item ^k^KEYWORD^
5356 @emph{Check keyword casing.}
5357 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5358 all keywords must be in lower case (with the exception of keywords
5359 such as @code{digits} used as attribute names to which this check
5360 does not apply).
5361
5362 @item ^l^LAYOUT^
5363 @emph{Check layout.}
5364 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5365 layout of statement and declaration constructs must follow the
5366 recommendations in the Ada Reference Manual, as indicated by the
5367 form of the syntax rules. For example an @code{else} keyword must
5368 be lined up with the corresponding @code{if} keyword.
5369
5370 There are two respects in which the style rule enforced by this check
5371 option are more liberal than those in the Ada Reference Manual. First
5372 in the case of record declarations, it is permissible to put the
5373 @code{record} keyword on the same line as the @code{type} keyword, and
5374 then the @code{end} in @code{end record} must line up under @code{type}.
5375 For example, either of the following two layouts is acceptable:
5376
5377 @smallexample @c ada
5378 @cartouche
5379 type q is record
5380    a : integer;
5381    b : integer;
5382 end record;
5383
5384 type q is
5385    record
5386       a : integer;
5387       b : integer;
5388    end record;
5389 @end cartouche
5390 @end smallexample
5391
5392 @noindent
5393 Second, in the case of a block statement, a permitted alternative
5394 is to put the block label on the same line as the @code{declare} or
5395 @code{begin} keyword, and then line the @code{end} keyword up under
5396 the block label. For example both the following are permitted:
5397
5398 @smallexample @c ada
5399 @cartouche
5400 Block : declare
5401    A : Integer := 3;
5402 begin
5403    Proc (A, A);
5404 end Block;
5405
5406 Block :
5407    declare
5408       A : Integer := 3;
5409    begin
5410       Proc (A, A);
5411    end Block;
5412 @end cartouche
5413 @end smallexample
5414
5415 @noindent
5416 The same alternative format is allowed for loops. For example, both of
5417 the following are permitted:
5418
5419 @smallexample @c ada
5420 @cartouche
5421 Clear : while J < 10 loop
5422    A (J) := 0;
5423 end loop Clear;
5424
5425 Clear :
5426    while J < 10 loop
5427       A (J) := 0;
5428    end loop Clear;
5429 @end cartouche
5430 @end smallexample
5431
5432 @item ^Lnnn^MAX_NESTING=nnn^
5433 @emph{Set maximum nesting level}
5434 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5435 the range 0-999, appears in the string after @option{-gnaty} then the
5436 maximum level of nesting of constructs (including subprograms, loops,
5437 blocks, packages, and conditionals) may not exceed the given value. A
5438 value of zero disconnects this style check.
5439
5440 @item ^m^LINE_LENGTH^
5441 @emph{Check maximum line length.}
5442 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5443 then the length of source lines must not exceed 79 characters, including
5444 any trailing blanks. The value of 79 allows convenient display on an
5445 80 character wide device or window, allowing for possible special
5446 treatment of 80 character lines. Note that this count is of raw
5447 characters in the source text. This means that a tab character counts
5448 as one character in this count and a wide character sequence counts as
5449 several characters (however many are needed in the encoding).
5450
5451 @item ^Mnnn^MAX_LENGTH=nnn^
5452 @emph{Set maximum line length.}
5453 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5454 the string after @option{-gnaty} then the length of lines must not exceed the
5455 given value.
5456
5457 @item ^n^STANDARD_CASING^
5458 @emph{Check casing of entities in Standard.}
5459 If the ^letter n^word STANDARD_CASING^ appears in the string
5460 after @option{-gnaty} then any identifier from Standard must be cased
5461 to match the presentation in the Ada Reference Manual (for example,
5462 @code{Integer} and @code{ASCII.NUL}).
5463
5464 @item ^o^ORDERED_SUBPROGRAMS^
5465 @emph{Check order of subprogram bodies.}
5466 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5467 after @option{-gnaty} then all subprogram bodies in a given scope
5468 (e.g. a package body) must be in alphabetical order. The ordering
5469 rule uses normal Ada rules for comparing strings, ignoring casing
5470 of letters, except that if there is a trailing numeric suffix, then
5471 the value of this suffix is used in the ordering (e.g. Junk2 comes
5472 before Junk10).
5473
5474 @item ^p^PRAGMA^
5475 @emph{Check pragma casing.}
5476 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5477 pragma names must be written in mixed case, that is, the
5478 initial letter and any letter following an underscore must be uppercase.
5479 All other letters must be lowercase.
5480
5481 @item ^r^REFERENCES^
5482 @emph{Check references.}
5483 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5484 then all identifier references must be cased in the same way as the
5485 corresponding declaration. No specific casing style is imposed on
5486 identifiers. The only requirement is for consistency of references
5487 with declarations.
5488
5489 @item ^s^SPECS^
5490 @emph{Check separate specs.}
5491 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5492 separate declarations (``specs'') are required for subprograms (a
5493 body is not allowed to serve as its own declaration). The only
5494 exception is that parameterless library level procedures are
5495 not required to have a separate declaration. This exception covers
5496 the most frequent form of main program procedures.
5497
5498 @item ^t^TOKEN^
5499 @emph{Check token spacing.}
5500 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5501 the following token spacing rules are enforced:
5502
5503 @itemize @bullet
5504
5505 @item
5506 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5507
5508 @item
5509 The token @code{=>} must be surrounded by spaces.
5510
5511 @item
5512 The token @code{<>} must be preceded by a space or a left parenthesis.
5513
5514 @item
5515 Binary operators other than @code{**} must be surrounded by spaces.
5516 There is no restriction on the layout of the @code{**} binary operator.
5517
5518 @item
5519 Colon must be surrounded by spaces.
5520
5521 @item
5522 Colon-equal (assignment, initialization) must be surrounded by spaces.
5523
5524 @item
5525 Comma must be the first non-blank character on the line, or be
5526 immediately preceded by a non-blank character, and must be followed
5527 by a space.
5528
5529 @item
5530 If the token preceding a left parenthesis ends with a letter or digit, then
5531 a space must separate the two tokens.
5532
5533 @item
5534 A right parenthesis must either be the first non-blank character on
5535 a line, or it must be preceded by a non-blank character.
5536
5537 @item
5538 A semicolon must not be preceded by a space, and must not be followed by
5539 a non-blank character.
5540
5541 @item
5542 A unary plus or minus may not be followed by a space.
5543
5544 @item
5545 A vertical bar must be surrounded by spaces.
5546 @end itemize
5547
5548 @noindent
5549 In the above rules, appearing in column one is always permitted, that is,
5550 counts as meeting either a requirement for a required preceding space,
5551 or as meeting a requirement for no preceding space.
5552
5553 Appearing at the end of a line is also always permitted, that is, counts
5554 as meeting either a requirement for a following space, or as meeting
5555 a requirement for no following space.
5556
5557 @end table
5558
5559 @noindent
5560 If any of these style rules is violated, a message is generated giving
5561 details on the violation. The initial characters of such messages are
5562 always ``@code{(style)}''. Note that these messages are treated as warning
5563 messages, so they normally do not prevent the generation of an object
5564 file. The @option{-gnatwe} switch can be used to treat warning messages,
5565 including style messages, as fatal errors.
5566
5567 The switch
5568 @ifclear vms
5569 @option{-gnaty} on its own (that is not
5570 followed by any letters or digits),
5571 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5572 options enabled with the exception of -gnatyo,
5573 @end ifclear
5574 @ifset vms
5575 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5576 the exception of ORDERED_SUBPROGRAMS,
5577 @end ifset
5578 with an indentation level of 3. This is the standard
5579 checking option that is used for the GNAT sources.
5580
5581 The switch
5582 @ifclear vms
5583 @option{-gnatyN}
5584 @end ifclear
5585 @ifset vms
5586 /STYLE_CHECKS=NONE
5587 @end ifset
5588 clears any previously set style checks.
5589
5590 @node Run-Time Checks
5591 @subsection Run-Time Checks
5592 @cindex Division by zero
5593 @cindex Access before elaboration
5594 @cindex Checks, division by zero
5595 @cindex Checks, access before elaboration
5596
5597 @noindent
5598 If you compile with the default options, GNAT will insert many run-time
5599 checks into the compiled code, including code that performs range
5600 checking against constraints, but not arithmetic overflow checking for
5601 integer operations (including division by zero) or checks for access
5602 before elaboration on subprogram calls. All other run-time checks, as
5603 required by the Ada 95 Reference Manual, are generated by default.
5604 The following @code{gcc} switches refine this default behavior:
5605
5606 @table @option
5607 @c !sort!
5608 @item -gnatp
5609 @cindex @option{-gnatp} (@code{gcc})
5610 @cindex Suppressing checks
5611 @cindex Checks, suppressing
5612 @findex Suppress
5613 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5614 had been present in the source. Validity checks are also suppressed (in
5615 other words @option{-gnatp} also implies @option{-gnatVn}.
5616 Use this switch to improve the performance
5617 of the code at the expense of safety in the presence of invalid data or
5618 program bugs.
5619
5620 @item -gnato
5621 @cindex @option{-gnato} (@code{gcc})
5622 @cindex Overflow checks
5623 @cindex Check, overflow
5624 Enables overflow checking for integer operations.
5625 This causes GNAT to generate slower and larger executable
5626 programs by adding code to check for overflow (resulting in raising
5627 @code{Constraint_Error} as required by standard Ada
5628 semantics). These overflow checks correspond to situations in which
5629 the true value of the result of an operation may be outside the base
5630 range of the result type. The following example shows the distinction:
5631
5632 @smallexample @c ada
5633 X1 : Integer := Integer'Last;
5634 X2 : Integer range 1 .. 5 := 5;
5635 X3 : Integer := Integer'Last;
5636 X4 : Integer range 1 .. 5 := 5;
5637 F  : Float := 2.0E+20;
5638 ...
5639 X1 := X1 + 1;
5640 X2 := X2 + 1;
5641 X3 := Integer (F);
5642 X4 := Integer (F);
5643 @end smallexample
5644
5645 @noindent
5646 Here the first addition results in a value that is outside the base range
5647 of Integer, and hence requires an overflow check for detection of the
5648 constraint error. Thus the first assignment to @code{X1} raises a
5649 @code{Constraint_Error} exception only if @option{-gnato} is set.
5650
5651 The second increment operation results in a violation
5652 of the explicit range constraint, and such range checks are always
5653 performed (unless specifically suppressed with a pragma @code{suppress}
5654 or the use of @option{-gnatp}).
5655
5656 The two conversions of @code{F} both result in values that are outside
5657 the base range of type @code{Integer} and thus will raise
5658 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5659 The fact that the result of the second conversion is assigned to
5660 variable @code{X4} with a restricted range is irrelevant, since the problem
5661 is in the conversion, not the assignment.
5662
5663 Basically the rule is that in the default mode (@option{-gnato} not
5664 used), the generated code assures that all integer variables stay
5665 within their declared ranges, or within the base range if there is
5666 no declared range. This prevents any serious problems like indexes
5667 out of range for array operations.
5668
5669 What is not checked in default mode is an overflow that results in
5670 an in-range, but incorrect value. In the above example, the assignments
5671 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5672 range of the target variable, but the result is wrong in the sense that
5673 it is too large to be represented correctly. Typically the assignment
5674 to @code{X1} will result in wrap around to the largest negative number.
5675 The conversions of @code{F} will result in some @code{Integer} value
5676 and if that integer value is out of the @code{X4} range then the
5677 subsequent assignment would generate an exception.
5678
5679 @findex Machine_Overflows
5680 Note that the @option{-gnato} switch does not affect the code generated
5681 for any floating-point operations; it applies only to integer
5682 semantics).
5683 For floating-point, GNAT has the @code{Machine_Overflows}
5684 attribute set to @code{False} and the normal mode of operation is to
5685 generate IEEE NaN and infinite values on overflow or invalid operations
5686 (such as dividing 0.0 by 0.0).
5687
5688 The reason that we distinguish overflow checking from other kinds of
5689 range constraint checking is that a failure of an overflow check can
5690 generate an incorrect value, but cannot cause erroneous behavior. This
5691 is unlike the situation with a constraint check on an array subscript,
5692 where failure to perform the check can result in random memory description,
5693 or the range check on a case statement, where failure to perform the check
5694 can cause a wild jump.
5695
5696 Note again that @option{-gnato} is off by default, so overflow checking is
5697 not performed in default mode. This means that out of the box, with the
5698 default settings, GNAT does not do all the checks expected from the
5699 language description in the Ada Reference Manual. If you want all constraint
5700 checks to be performed, as described in this Manual, then you must
5701 explicitly use the -gnato switch either on the @code{gnatmake} or
5702 @code{gcc} command.
5703
5704 @item -gnatE
5705 @cindex @option{-gnatE} (@code{gcc})
5706 @cindex Elaboration checks
5707 @cindex Check, elaboration
5708 Enables dynamic checks for access-before-elaboration
5709 on subprogram calls and generic instantiations.
5710 For full details of the effect and use of this switch,
5711 @xref{Compiling Using gcc}.
5712 @end table
5713
5714 @findex Unsuppress
5715 @noindent
5716 The setting of these switches only controls the default setting of the
5717 checks. You may modify them using either @code{Suppress} (to remove
5718 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5719 the program source.
5720
5721 @node Stack Overflow Checking
5722 @subsection Stack Overflow Checking
5723 @cindex Stack Overflow Checking
5724 @cindex -fstack-check
5725
5726 @noindent
5727 For most operating systems, @code{gcc} does not perform stack overflow
5728 checking by default. This means that if the main environment task or
5729 some other task exceeds the available stack space, then unpredictable
5730 behavior will occur.
5731
5732 To activate stack checking, compile all units with the gcc option
5733 @option{-fstack-check}. For example:
5734
5735 @smallexample
5736 gcc -c -fstack-check package1.adb
5737 @end smallexample
5738
5739 @noindent
5740 Units compiled with this option will generate extra instructions to check
5741 that any use of the stack (for procedure calls or for declaring local
5742 variables in declare blocks) do not exceed the available stack space.
5743 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5744
5745 For declared tasks, the stack size is always controlled by the size
5746 given in an applicable @code{Storage_Size} pragma (or is set to
5747 the default size if no pragma is used.
5748
5749 For the environment task, the stack size depends on
5750 system defaults and is unknown to the compiler. The stack
5751 may even dynamically grow on some systems, precluding the
5752 normal Ada semantics for stack overflow. In the worst case,
5753 unbounded stack usage, causes unbounded stack expansion
5754 resulting in the system running out of virtual memory.
5755
5756 The stack checking may still work correctly if a fixed
5757 size stack is allocated, but this cannot be guaranteed.
5758 To ensure that a clean exception is signalled for stack
5759 overflow, set the environment variable
5760 @code{GNAT_STACK_LIMIT} to indicate the maximum
5761 stack area that can be used, as in:
5762 @cindex GNAT_STACK_LIMIT
5763
5764 @smallexample
5765 SET GNAT_STACK_LIMIT 1600
5766 @end smallexample
5767
5768 @noindent
5769 The limit is given in kilobytes, so the above declaration would
5770 set the stack limit of the environment task to 1.6 megabytes.
5771 Note that the only purpose of this usage is to limit the amount
5772 of stack used by the environment task. If it is necessary to
5773 increase the amount of stack for the environment task, then this
5774 is an operating systems issue, and must be addressed with the
5775 appropriate operating systems commands.
5776
5777
5778 @node Using gcc for Syntax Checking
5779 @subsection Using @code{gcc} for Syntax Checking
5780 @table @option
5781 @item -gnats
5782 @cindex @option{-gnats} (@code{gcc})
5783 @ifclear vms
5784
5785 @noindent
5786 The @code{s} stands for ``syntax''.
5787 @end ifclear
5788
5789 Run GNAT in syntax checking only mode. For
5790 example, the command
5791
5792 @smallexample
5793 $ gcc -c -gnats x.adb
5794 @end smallexample
5795
5796 @noindent
5797 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5798 series of files in a single command
5799 @ifclear vms
5800 , and can use wild cards to specify such a group of files.
5801 Note that you must specify the @option{-c} (compile
5802 only) flag in addition to the @option{-gnats} flag.
5803 @end ifclear
5804 .
5805 You may use other switches in conjunction with @option{-gnats}. In
5806 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5807 format of any generated error messages.
5808
5809 When the source file is empty or contains only empty lines and/or comments,
5810 the output is a warning:
5811
5812 @smallexample
5813 $ gcc -c -gnats -x ada toto.txt
5814 toto.txt:1:01: warning: empty file, contains no compilation units
5815 $
5816 @end smallexample
5817
5818 Otherwise, the output is simply the error messages, if any. No object file or
5819 ALI file is generated by a syntax-only compilation. Also, no units other
5820 than the one specified are accessed. For example, if a unit @code{X}
5821 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5822 check only mode does not access the source file containing unit
5823 @code{Y}.
5824
5825 @cindex Multiple units, syntax checking
5826 Normally, GNAT allows only a single unit in a source file. However, this
5827 restriction does not apply in syntax-check-only mode, and it is possible
5828 to check a file containing multiple compilation units concatenated
5829 together. This is primarily used by the @code{gnatchop} utility
5830 (@pxref{Renaming Files Using gnatchop}).
5831 @end table
5832
5833
5834 @node Using gcc for Semantic Checking
5835 @subsection Using @code{gcc} for Semantic Checking
5836 @table @option
5837 @item -gnatc
5838 @cindex @option{-gnatc} (@code{gcc})
5839
5840 @ifclear vms
5841 @noindent
5842 The @code{c} stands for ``check''.
5843 @end ifclear
5844 Causes the compiler to operate in semantic check mode,
5845 with full checking for all illegalities specified in the
5846 Ada 95 Reference Manual, but without generation of any object code
5847 (no object file is generated).
5848
5849 Because dependent files must be accessed, you must follow the GNAT
5850 semantic restrictions on file structuring to operate in this mode:
5851
5852 @itemize @bullet
5853 @item
5854 The needed source files must be accessible
5855 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5856
5857 @item
5858 Each file must contain only one compilation unit.
5859
5860 @item
5861 The file name and unit name must match (@pxref{File Naming Rules}).
5862 @end itemize
5863
5864 The output consists of error messages as appropriate. No object file is
5865 generated. An @file{ALI} file is generated for use in the context of
5866 cross-reference tools, but this file is marked as not being suitable
5867 for binding (since no object file is generated).
5868 The checking corresponds exactly to the notion of
5869 legality in the Ada 95 Reference Manual.
5870
5871 Any unit can be compiled in semantics-checking-only mode, including
5872 units that would not normally be compiled (subunits,
5873 and specifications where a separate body is present).
5874 @end table
5875
5876 @node Compiling Ada 83 Programs
5877 @subsection Compiling Ada 83 Programs
5878 @table @option
5879 @cindex Ada 83 compatibility
5880 @item -gnat83
5881 @cindex @option{-gnat83} (@code{gcc})
5882 @cindex ACVC, Ada 83 tests
5883
5884 @noindent
5885 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5886 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5887 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5888 where this can be done easily.
5889 It is not possible to guarantee this switch does a perfect
5890 job; for example, some subtle tests, such as are
5891 found in earlier ACVC tests (and that have been removed from the ACATS suite
5892 for Ada 95), might not compile correctly.
5893 Nevertheless, this switch may be useful in some circumstances, for example
5894 where, due to contractual reasons, legacy code needs to be maintained
5895 using only Ada 83 features.
5896
5897 With few exceptions (most notably the need to use @code{<>} on
5898 @cindex Generic formal parameters
5899 unconstrained generic formal parameters, the use of the new Ada 95
5900 reserved words, and the use of packages
5901 with optional bodies), it is not necessary to use the
5902 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5903 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5904 means that a correct Ada 83 program is usually also a correct Ada 95
5905 program.
5906 For further information, please refer to @ref{Compatibility and Porting Guide}.
5907
5908 @end table
5909
5910 @node Character Set Control
5911 @subsection Character Set Control
5912 @table @option
5913 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5914 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5915
5916 @noindent
5917 Normally GNAT recognizes the Latin-1 character set in source program
5918 identifiers, as described in the Ada 95 Reference Manual.
5919 This switch causes
5920 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5921 single character ^^or word^ indicating the character set, as follows:
5922
5923 @table @code
5924 @item 1
5925 ISO 8859-1 (Latin-1) identifiers
5926
5927 @item 2
5928 ISO 8859-2 (Latin-2) letters allowed in identifiers
5929
5930 @item 3
5931 ISO 8859-3 (Latin-3) letters allowed in identifiers
5932
5933 @item 4
5934 ISO 8859-4 (Latin-4) letters allowed in identifiers
5935
5936 @item 5
5937 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5938
5939 @item 9
5940 ISO 8859-15 (Latin-9) letters allowed in identifiers
5941
5942 @item ^p^PC^
5943 IBM PC letters (code page 437) allowed in identifiers
5944
5945 @item ^8^PC850^
5946 IBM PC letters (code page 850) allowed in identifiers
5947
5948 @item ^f^FULL_UPPER^
5949 Full upper-half codes allowed in identifiers
5950
5951 @item ^n^NO_UPPER^
5952 No upper-half codes allowed in identifiers
5953
5954 @item ^w^WIDE^
5955 Wide-character codes (that is, codes greater than 255)
5956 allowed in identifiers
5957 @end table
5958
5959 @xref{Foreign Language Representation}, for full details on the
5960 implementation of these character sets.
5961
5962 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5963 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5964 Specify the method of encoding for wide characters.
5965 @var{e} is one of the following:
5966
5967 @table @code
5968
5969 @item ^h^HEX^
5970 Hex encoding (brackets coding also recognized)
5971
5972 @item ^u^UPPER^
5973 Upper half encoding (brackets encoding also recognized)
5974
5975 @item ^s^SHIFT_JIS^
5976 Shift/JIS encoding (brackets encoding also recognized)
5977
5978 @item ^e^EUC^
5979 EUC encoding (brackets encoding also recognized)
5980
5981 @item ^8^UTF8^
5982 UTF-8 encoding (brackets encoding also recognized)
5983
5984 @item ^b^BRACKETS^
5985 Brackets encoding only (default value)
5986 @end table
5987 For full details on the these encoding
5988 methods see @xref{Wide Character Encodings}.
5989 Note that brackets coding is always accepted, even if one of the other
5990 options is specified, so for example @option{-gnatW8} specifies that both
5991 brackets and @code{UTF-8} encodings will be recognized. The units that are
5992 with'ed directly or indirectly will be scanned using the specified
5993 representation scheme, and so if one of the non-brackets scheme is
5994 used, it must be used consistently throughout the program. However,
5995 since brackets encoding is always recognized, it may be conveniently
5996 used in standard libraries, allowing these libraries to be used with
5997 any of the available coding schemes.
5998 scheme. If no @option{-gnatW?} parameter is present, then the default
5999 representation is Brackets encoding only.
6000
6001 Note that the wide character representation that is specified (explicitly
6002 or by default) for the main program also acts as the default encoding used
6003 for Wide_Text_IO files if not specifically overridden by a WCEM form
6004 parameter.
6005
6006 @end table
6007 @node File Naming Control
6008 @subsection File Naming Control
6009
6010 @table @option
6011 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6012 @cindex @option{-gnatk} (@code{gcc})
6013 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6014 1-999, indicates the maximum allowable length of a file name (not
6015 including the @file{.ads} or @file{.adb} extension). The default is not
6016 to enable file name krunching.
6017
6018 For the source file naming rules, @xref{File Naming Rules}.
6019 @end table
6020
6021
6022 @node Subprogram Inlining Control
6023 @subsection Subprogram Inlining Control
6024
6025 @table @option
6026 @c !sort!
6027 @item -gnatn
6028 @cindex @option{-gnatn} (@code{gcc})
6029 @ifclear vms
6030 The @code{n} here is intended to suggest the first syllable of the
6031 word ``inline''.
6032 @end ifclear
6033 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6034 inlining to actually occur, optimization must be enabled. To enable
6035 inlining of subprograms specified by pragma @code{Inline},
6036 you must also specify this switch.
6037 In the absence of this switch, GNAT does not attempt
6038 inlining and does not need to access the bodies of
6039 subprograms for which @code{pragma Inline} is specified if they are not
6040 in the current unit.
6041
6042 If you specify this switch the compiler will access these bodies,
6043 creating an extra source dependency for the resulting object file, and
6044 where possible, the call will be inlined.
6045 For further details on when inlining is possible
6046 see @xref{Inlining of Subprograms}.
6047
6048 @item -gnatN
6049 @cindex @option{-gnatN} (@code{gcc})
6050 The front end inlining activated by this switch is generally more extensive,
6051 and quite often more effective than the standard @option{-gnatn} inlining mode.
6052 It will also generate additional dependencies.
6053 Note that
6054 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6055 to specify both options.
6056 @end table
6057
6058 @node Auxiliary Output Control
6059 @subsection Auxiliary Output Control
6060
6061 @table @option
6062 @item -gnatt
6063 @cindex @option{-gnatt} (@code{gcc})
6064 @cindex Writing internal trees
6065 @cindex Internal trees, writing to file
6066 Causes GNAT to write the internal tree for a unit to a file (with the
6067 extension @file{.adt}.
6068 This not normally required, but is used by separate analysis tools.
6069 Typically
6070 these tools do the necessary compilations automatically, so you should
6071 not have to specify this switch in normal operation.
6072
6073 @item -gnatu
6074 @cindex @option{-gnatu} (@code{gcc})
6075 Print a list of units required by this compilation on @file{stdout}.
6076 The listing includes all units on which the unit being compiled depends
6077 either directly or indirectly.
6078
6079 @ifclear vms
6080 @item -pass-exit-codes
6081 @cindex @option{-pass-exit-codes} (@code{gcc})
6082 If this switch is not used, the exit code returned by @code{gcc} when
6083 compiling multiple files indicates whether all source files have
6084 been successfully used to generate object files or not.
6085
6086 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6087 exit status and allows an integrated development environment to better
6088 react to a compilation failure. Those exit status are:
6089
6090 @table @asis
6091 @item 5
6092 There was an error in at least one source file.
6093 @item 3
6094 At least one source file did not generate an object file.
6095 @item 2
6096 The compiler died unexpectedly (internal error for example).
6097 @item 0
6098 An object file has been generated for every source file.
6099 @end table
6100 @end ifclear
6101 @end table
6102
6103 @node Debugging Control
6104 @subsection Debugging Control
6105
6106 @table @option
6107 @c !sort!
6108 @cindex Debugging options
6109 @ifclear vms
6110 @item -gnatd@var{x}
6111 @cindex @option{-gnatd} (@code{gcc})
6112 Activate internal debugging switches. @var{x} is a letter or digit, or
6113 string of letters or digits, which specifies the type of debugging
6114 outputs desired. Normally these are used only for internal development
6115 or system debugging purposes. You can find full documentation for these
6116 switches in the body of the @code{Debug} unit in the compiler source
6117 file @file{debug.adb}.
6118 @end ifclear
6119
6120 @item -gnatG
6121 @cindex @option{-gnatG} (@code{gcc})
6122 This switch causes the compiler to generate auxiliary output containing
6123 a pseudo-source listing of the generated expanded code. Like most Ada
6124 compilers, GNAT works by first transforming the high level Ada code into
6125 lower level constructs. For example, tasking operations are transformed
6126 into calls to the tasking run-time routines. A unique capability of GNAT
6127 is to list this expanded code in a form very close to normal Ada source.
6128 This is very useful in understanding the implications of various Ada
6129 usage on the efficiency of the generated code. There are many cases in
6130 Ada (e.g. the use of controlled types), where simple Ada statements can
6131 generate a lot of run-time code. By using @option{-gnatG} you can identify
6132 these cases, and consider whether it may be desirable to modify the coding
6133 approach to improve efficiency.
6134
6135 The format of the output is very similar to standard Ada source, and is
6136 easily understood by an Ada programmer. The following special syntactic
6137 additions correspond to low level features used in the generated code that
6138 do not have any exact analogies in pure Ada source form. The following
6139 is a partial list of these special constructions. See the specification
6140 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6141
6142 @table @code
6143 @item new @var{xxx} [storage_pool = @var{yyy}]
6144 Shows the storage pool being used for an allocator.
6145
6146 @item at end @var{procedure-name};
6147 Shows the finalization (cleanup) procedure for a scope.
6148
6149 @item (if @var{expr} then @var{expr} else @var{expr})
6150 Conditional expression equivalent to the @code{x?y:z} construction in C.
6151
6152 @item @var{target}^^^(@var{source})
6153 A conversion with floating-point truncation instead of rounding.
6154
6155 @item @var{target}?(@var{source})
6156 A conversion that bypasses normal Ada semantic checking. In particular
6157 enumeration types and fixed-point types are treated simply as integers.
6158
6159 @item @var{target}?^^^(@var{source})
6160 Combines the above two cases.
6161
6162 @item @var{x} #/ @var{y}
6163 @itemx @var{x} #mod @var{y}
6164 @itemx @var{x} #* @var{y}
6165 @itemx @var{x} #rem @var{y}
6166 A division or multiplication of fixed-point values which are treated as
6167 integers without any kind of scaling.
6168
6169 @item free @var{expr} [storage_pool = @var{xxx}]
6170 Shows the storage pool associated with a @code{free} statement.
6171
6172 @item freeze @var{typename} [@var{actions}]
6173 Shows the point at which @var{typename} is frozen, with possible
6174 associated actions to be performed at the freeze point.
6175
6176 @item reference @var{itype}
6177 Reference (and hence definition) to internal type @var{itype}.
6178
6179 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6180 Intrinsic function call.
6181
6182 @item @var{labelname} : label
6183 Declaration of label @var{labelname}.
6184
6185 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6186 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6187 @var{expr}, but handled more efficiently).
6188
6189 @item [constraint_error]
6190 Raise the @code{Constraint_Error} exception.
6191
6192 @item @var{expression}'reference
6193 A pointer to the result of evaluating @var{expression}.
6194
6195 @item @var{target-type}!(@var{source-expression})
6196 An unchecked conversion of @var{source-expression} to @var{target-type}.
6197
6198 @item [@var{numerator}/@var{denominator}]
6199 Used to represent internal real literals (that) have no exact
6200 representation in base 2-16 (for example, the result of compile time
6201 evaluation of the expression 1.0/27.0).
6202 @end table
6203
6204 @item -gnatD
6205 @cindex @option{-gnatD} (@code{gcc})
6206 When used in conjunction with @option{-gnatG}, this switch causes
6207 the expanded source, as described above for
6208 @option{-gnatG} to be written to files with names
6209 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6210 instead of to the standard ooutput file. For
6211 example, if the source file name is @file{hello.adb}, then a file
6212 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6213 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6214 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6215 you to do source level debugging using the generated code which is
6216 sometimes useful for complex code, for example to find out exactly
6217 which part of a complex construction raised an exception. This switch
6218 also suppress generation of cross-reference information (see
6219 @option{-gnatx}) since otherwise the cross-reference information
6220 would refer to the @file{^.dg^.DG^} file, which would cause
6221 confusion since this is not the original source file.
6222
6223 Note that @option{-gnatD} actually implies @option{-gnatG}
6224 automatically, so it is not necessary to give both options.
6225 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6226
6227 @ifclear vms
6228 @item -gnatR[0|1|2|3[s]]
6229 @cindex @option{-gnatR} (@code{gcc})
6230 This switch controls output from the compiler of a listing showing
6231 representation information for declared types and objects. For
6232 @option{-gnatR0}, no information is output (equivalent to omitting
6233 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6234 so @option{-gnatR} with no parameter has the same effect), size and alignment
6235 information is listed for declared array and record types. For
6236 @option{-gnatR2}, size and alignment information is listed for all
6237 expression information for values that are computed at run time for
6238 variant records. These symbolic expressions have a mostly obvious
6239 format with #n being used to represent the value of the n'th
6240 discriminant. See source files @file{repinfo.ads/adb} in the
6241 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6242 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6243 the output is to a file with the name @file{^file.rep^file_REP^} where
6244 file is the name of the corresponding source file.
6245 @end ifclear
6246 @ifset vms
6247 @item /REPRESENTATION_INFO
6248 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6249 This qualifier controls output from the compiler of a listing showing
6250 representation information for declared types and objects. For
6251 @option{/REPRESENTATION_INFO=NONE}, no information is output
6252 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6253 @option{/REPRESENTATION_INFO} without option is equivalent to
6254 @option{/REPRESENTATION_INFO=ARRAYS}.
6255 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6256 information is listed for declared array and record types. For
6257 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6258 is listed for all expression information for values that are computed
6259 at run time for variant records. These symbolic expressions have a mostly
6260 obvious format with #n being used to represent the value of the n'th
6261 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6262 @code{GNAT} sources for full details on the format of
6263 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6264 If _FILE is added at the end of an option
6265 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6266 then the output is to a file with the name @file{file_REP} where
6267 file is the name of the corresponding source file.
6268 @end ifset
6269
6270 @item -gnatS
6271 @cindex @option{-gnatS} (@code{gcc})
6272 The use of the switch @option{-gnatS} for an
6273 Ada compilation will cause the compiler to output a
6274 representation of package Standard in a form very
6275 close to standard Ada. It is not quite possible to
6276 do this entirely in standard Ada (since new
6277 numeric base types cannot be created in standard
6278 Ada), but the output is easily
6279 readable to any Ada programmer, and is useful to
6280 determine the characteristics of target dependent
6281 types in package Standard.
6282
6283 @item -gnatx
6284 @cindex @option{-gnatx} (@code{gcc})
6285 Normally the compiler generates full cross-referencing information in
6286 the @file{ALI} file. This information is used by a number of tools,
6287 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6288 suppresses this information. This saves some space and may slightly
6289 speed up compilation, but means that these tools cannot be used.
6290 @end table
6291
6292 @node Exception Handling Control
6293 @subsection Exception Handling Control
6294
6295 @noindent
6296 GNAT uses two methods for handling exceptions at run-time. The
6297 @code{longjmp/setjmp} method saves the context when entering
6298 a frame with an exception handler. Then when an exception is
6299 raised, the context can be restored immediately, without the
6300 need for tracing stack frames. This method provides very fast
6301 exception propagation, but introduces significant overhead for
6302 the use of exception handlers, even if no exception is raised.
6303
6304 The other approach is called ``zero cost'' exception handling.
6305 With this method, the compiler builds static tables to describe
6306 the exception ranges. No dynamic code is required when entering
6307 a frame containing an exception handler. When an exception is
6308 raised, the tables are used to control a back trace of the
6309 subprogram invocation stack to locate the required exception
6310 handler. This method has considerably poorer performance for
6311 the propagation of exceptions, but there is no overhead for
6312 exception handlers if no exception is raised.
6313
6314 The following switches can be used to control which of the
6315 two exception handling methods is used.
6316
6317 @table @option
6318 @c !sort!
6319
6320 @item -gnatL
6321 @cindex @option{-gnatL} (@code{gcc})
6322 This switch causes the longjmp/setjmp approach to be used
6323 for exception handling. If this is the default mechanism for the
6324 target (see below), then this has no effect. If the default
6325 mechanism for the target is zero cost exceptions, then
6326 this switch can be used to modify this default, but it must be
6327 used for all units in the partition, including all run-time
6328 library units. One way to achieve this is to use the
6329 @option{-a} and @option{-f} switches for @code{gnatmake}.
6330 This option is rarely used. One case in which it may be
6331 advantageous is if you have an application where exception
6332 raising is common and the overall performance of the
6333 application is improved by favoring exception propagation.
6334
6335 @item -gnatZ
6336 @cindex @option{-gnatZ} (@code{gcc})
6337 @cindex Zero Cost Exceptions
6338 This switch causes the zero cost approach to be sed
6339 for exception handling. If this is the default mechanism for the
6340 target (see below), then this has no effect. If the default
6341 mechanism for the target is longjmp/setjmp exceptions, then
6342 this switch can be used to modify this default, but it must be
6343 used for all units in the partition, including all run-time
6344 library units. One way to achieve this is to use the
6345 @option{-a} and @option{-f} switches for @code{gnatmake}.
6346 This option can only be used if the zero cost approach
6347 is available for the target in use (see below).
6348 @end table
6349
6350 @noindent
6351 The @code{longjmp/setjmp} approach is available on all targets, but
6352 the @code{zero cost} approach is only available on selected targets.
6353 To determine whether zero cost exceptions can be used for a
6354 particular target, look at the private part of the file system.ads.
6355 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6356 be True to use the zero cost approach. If both of these switches
6357 are set to False, this means that zero cost exception handling
6358 is not yet available for that target. The switch
6359 @code{ZCX_By_Default} indicates the default approach. If this
6360 switch is set to True, then the @code{zero cost} approach is
6361 used by default.
6362
6363 @node Units to Sources Mapping Files
6364 @subsection Units to Sources Mapping Files
6365
6366 @table @option
6367
6368 @item -gnatem^^=^@var{path}
6369 @cindex @option{-gnatem} (@code{gcc})
6370 A mapping file is a way to communicate to the compiler two mappings:
6371 from unit names to file names (without any directory information) and from
6372 file names to path names (with full directory information). These mappings
6373 are used by the compiler to short-circuit the path search.
6374
6375 The use of mapping files is not required for correct operation of the
6376 compiler, but mapping files can improve efficiency, particularly when
6377 sources are read over a slow network connection. In normal operation,
6378 you need not be concerned with the format or use of mapping files,
6379 and the @option{-gnatem} switch is not a switch that you would use
6380 explicitly. it is intended only for use by automatic tools such as
6381 @code{gnatmake} running under the project file facility. The
6382 description here of the format of mapping files is provided
6383 for completeness and for possible use by other tools.
6384
6385 A mapping file is a sequence of sets of three lines. In each set,
6386 the first line is the unit name, in lower case, with ``@code{%s}''
6387 appended for
6388 specifications and ``@code{%b}'' appended for bodies; the second line is the
6389 file name; and the third line is the path name.
6390
6391 Example:
6392 @smallexample
6393    main%b
6394    main.2.ada
6395    /gnat/project1/sources/main.2.ada
6396 @end smallexample
6397
6398 When the switch @option{-gnatem} is specified, the compiler will create
6399 in memory the two mappings from the specified file. If there is any problem
6400 (non existent file, truncated file or duplicate entries), no mapping
6401 will be created.
6402
6403 Several @option{-gnatem} switches may be specified; however, only the last
6404 one on the command line will be taken into account.
6405
6406 When using a project file, @code{gnatmake} create a temporary mapping file
6407 and communicates it to the compiler using this switch.
6408
6409 @end table
6410
6411
6412 @node Integrated Preprocessing
6413 @subsection Integrated Preprocessing
6414
6415 @noindent
6416 GNAT sources may be preprocessed immediately before compilation; the actual
6417 text of the source is not the text of the source file, but is derived from it
6418 through a process called preprocessing. Integrated preprocessing is specified
6419 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6420 indicates, through a text file, the preprocessing data to be used.
6421 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6422
6423 @noindent
6424 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6425 used when Integrated Preprocessing is used. The reason is that preprocessing
6426 with another Preprocessing Data file without changing the sources will
6427 not trigger recompilation without this switch.
6428
6429 @noindent
6430 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6431 always trigger recompilation for sources that are preprocessed,
6432 because @code{gnatmake} cannot compute the checksum of the source after
6433 preprocessing.
6434
6435 @noindent
6436 The actual preprocessing function is described in details in section
6437 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6438 preprocessing is triggered and parameterized.
6439
6440 @table @code
6441
6442 @item -gnatep=@var{file}
6443 @cindex @option{-gnatep} (@code{gcc})
6444 This switch indicates to the compiler the file name (without directory
6445 information) of the preprocessor data file to use. The preprocessor data file
6446 should be found in the source directories.
6447
6448 @noindent
6449 A preprocessing data file is a text file with significant lines indicating
6450 how should be preprocessed either a specific source or all sources not
6451 mentioned in other lines. A significant line is a non empty, non comment line.
6452 Comments are similar to Ada comments.
6453
6454 @noindent
6455 Each significant line starts with either a literal string or the character '*'.
6456 A literal string is the file name (without directory information) of the source
6457 to preprocess. A character '*' indicates the preprocessing for all the sources
6458 that are not specified explicitly on other lines (order of the lines is not
6459 significant). It is an error to have two lines with the same file name or two
6460 lines starting with the character '*'.
6461
6462 @noindent
6463 After the file name or the character '*', another optional literal string
6464 indicating the file name of the definition file to be used for preprocessing.
6465 (see @ref{Form of Definitions File}. The definition files are found by the
6466 compiler in one of the source directories. In some cases, when compiling
6467 a source in a directory other than the current directory, if the definition
6468 file is in the current directory, it may be necessary to add the current
6469 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6470 the compiler would not find the definition file.
6471
6472 @noindent
6473 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6474 be found. Those ^switches^switches^ are:
6475
6476 @table @code
6477
6478 @item -b
6479 Causes both preprocessor lines and the lines deleted by
6480 preprocessing to be replaced by blank lines, preserving the line number.
6481 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6482 it cancels the effect of @option{-c}.
6483
6484 @item -c
6485 Causes both preprocessor lines and the lines deleted
6486 by preprocessing to be retained as comments marked
6487 with the special string ``@code{--! }''.
6488
6489 @item -Dsymbol=value
6490 Define or redefine a symbol, associated with value. A symbol is an Ada
6491 identifier, or an Ada reserved word, with the exception of @code{if},
6492 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6493 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6494 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6495 same name defined in a definition file.
6496
6497 @item -s
6498 Causes a sorted list of symbol names and values to be
6499 listed on the standard output file.
6500
6501 @item -u
6502 Causes undefined symbols to be treated as having the value @code{FALSE}
6503 in the context
6504 of a preprocessor test. In the absence of this option, an undefined symbol in
6505 a @code{#if} or @code{#elsif} test will be treated as an error.
6506
6507 @end table
6508
6509 @noindent
6510 Examples of valid lines in a preprocessor data file:
6511
6512 @smallexample
6513   "toto.adb"  "prep.def" -u
6514   --  preprocess "toto.adb", using definition file "prep.def",
6515   --  undefined symbol are False.
6516
6517   * -c -DVERSION=V101
6518   --  preprocess all other sources without a definition file;
6519   --  suppressed lined are commented; symbol VERSION has the value V101.
6520
6521   "titi.adb" "prep2.def" -s
6522   --  preprocess "titi.adb", using definition file "prep2.def";
6523   --  list all symbols with their values.
6524 @end smallexample
6525
6526 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6527 @cindex @option{-gnateD} (@code{gcc})
6528 Define or redefine a preprocessing symbol, associated with value. If no value
6529 is given on the command line, then the value of the symbol is @code{True}.
6530 A symbol is an identifier, following normal Ada (case-insensitive)
6531 rules for its syntax, and value is any sequence (including an empty sequence)
6532 of characters from the set (letters, digits, period, underline).
6533 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6534 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6535
6536 @noindent
6537 A symbol declared with this ^switch^switch^ on the command line replaces a
6538 symbol with the same name either in a definition file or specified with a
6539 ^switch^switch^ -D in the preprocessor data file.
6540
6541 @noindent
6542 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6543
6544 @end table
6545
6546 @node Code Generation Control
6547 @subsection Code Generation Control
6548
6549 @noindent
6550
6551 The GCC technology provides a wide range of target dependent
6552 @option{-m} switches for controlling
6553 details of code generation with respect to different versions of
6554 architectures. This includes variations in instruction sets (e.g.
6555 different members of the power pc family), and different requirements
6556 for optimal arrangement of instructions (e.g. different members of
6557 the x86 family). The list of available @option{-m} switches may be
6558 found in the GCC documentation.
6559
6560 Use of the these @option{-m} switches may in some cases result in improved
6561 code performance.
6562
6563 The GNAT Pro technology is tested and qualified without any
6564 @option{-m} switches,
6565 so generally the most reliable approach is to avoid the use of these
6566 switches. However, we generally expect most of these switches to work
6567 successfully with GNAT Pro, and many customers have reported successful
6568 use of these options.
6569
6570 Our general advice is to avoid the use of @option{-m} switches unless
6571 special needs lead to requirements in this area. In particular,
6572 there is no point in using @option{-m} switches to improve performance
6573 unless you actually see a performance improvement.
6574
6575 @ifset vms
6576 @node Return Codes
6577 @subsection Return Codes
6578 @cindex Return Codes
6579 @cindex @option{/RETURN_CODES=VMS}
6580
6581 @noindent
6582 On VMS, GNAT compiled programs return POSIX-style codes by default,
6583 e.g. @option{/RETURN_CODES=POSIX}.
6584
6585 To enable VMS style return codes, GNAT LINK with the option
6586 @option{/RETURN_CODES=VMS}. For example:
6587
6588 @smallexample
6589 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6590 @end smallexample
6591
6592 @noindent
6593 Programs built with /RETURN_CODES=VMS are suitable to be called in
6594 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6595 are suitable for spawning with appropriate GNAT RTL routines.
6596
6597 @end ifset
6598
6599
6600 @node Search Paths and the Run-Time Library (RTL)
6601 @section Search Paths and the Run-Time Library (RTL)
6602
6603 @noindent
6604 With the GNAT source-based library system, the compiler must be able to
6605 find source files for units that are needed by the unit being compiled.
6606 Search paths are used to guide this process.
6607
6608 The compiler compiles one source file whose name must be given
6609 explicitly on the command line. In other words, no searching is done
6610 for this file. To find all other source files that are needed (the most
6611 common being the specs of units), the compiler examines the following
6612 directories, in the following order:
6613
6614 @enumerate
6615 @item
6616 The directory containing the source file of the main unit being compiled
6617 (the file name on the command line).
6618
6619 @item
6620 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6621 @code{gcc} command line, in the order given.
6622
6623 @item
6624 @findex ADA_INCLUDE_PATH
6625 Each of the directories listed in the value of the
6626 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6627 @ifclear vms
6628 Construct this value
6629 exactly as the @code{PATH} environment variable: a list of directory
6630 names separated by colons (semicolons when working with the NT version).
6631 @end ifclear
6632 @ifset vms
6633 Normally, define this value as a logical name containing a comma separated
6634 list of directory names.
6635
6636 This variable can also be defined by means of an environment string
6637 (an argument to the DEC C exec* set of functions).
6638
6639 Logical Name:
6640 @smallexample
6641 DEFINE ANOTHER_PATH FOO:[BAG]
6642 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6643 @end smallexample
6644
6645 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6646 first, followed by the standard Ada 95
6647 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6648 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6649 (Text_IO, Sequential_IO, etc)
6650 instead of the Ada95 packages. Thus, in order to get the Ada 95
6651 packages by default, ADA_INCLUDE_PATH must be redefined.
6652 @end ifset
6653
6654 @item
6655 @findex ADA_PRJ_INCLUDE_FILE
6656 Each of the directories listed in the text file whose name is given
6657 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6658
6659 @noindent
6660 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6661 driver when project files are used. It should not normally be set
6662 by other means.
6663
6664 @item
6665 The content of the @file{ada_source_path} file which is part of the GNAT
6666 installation tree and is used to store standard libraries such as the
6667 GNAT Run Time Library (RTL) source files.
6668 @ifclear vms
6669 @ref{Installing the library}
6670 @end ifclear
6671 @end enumerate
6672
6673 @noindent
6674 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6675 inhibits the use of the directory
6676 containing the source file named in the command line. You can still
6677 have this directory on your search path, but in this case it must be
6678 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6679
6680 Specifying the switch @option{-nostdinc}
6681 inhibits the search of the default location for the GNAT Run Time
6682 Library (RTL) source files.
6683
6684 The compiler outputs its object files and ALI files in the current
6685 working directory.
6686 @ifclear vms
6687 Caution: The object file can be redirected with the @option{-o} switch;
6688 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6689 so the @file{ALI} file will not go to the right place. Therefore, you should
6690 avoid using the @option{-o} switch.
6691 @end ifclear
6692
6693 @findex System.IO
6694 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6695 children make up the GNAT RTL, together with the simple @code{System.IO}
6696 package used in the @code{"Hello World"} example. The sources for these units
6697 are needed by the compiler and are kept together in one directory. Not
6698 all of the bodies are needed, but all of the sources are kept together
6699 anyway. In a normal installation, you need not specify these directory
6700 names when compiling or binding. Either the environment variables or
6701 the built-in defaults cause these files to be found.
6702
6703 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6704 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6705 consisting of child units of @code{GNAT}. This is a collection of generally
6706 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6707 further details.
6708
6709 Besides simplifying access to the RTL, a major use of search paths is
6710 in compiling sources from multiple directories. This can make
6711 development environments much more flexible.
6712
6713
6714 @node Order of Compilation Issues
6715 @section Order of Compilation Issues
6716
6717 @noindent
6718 If, in our earlier example, there was a spec for the @code{hello}
6719 procedure, it would be contained in the file @file{hello.ads}; yet this
6720 file would not have to be explicitly compiled. This is the result of the
6721 model we chose to implement library management. Some of the consequences
6722 of this model are as follows:
6723
6724 @itemize @bullet
6725 @item
6726 There is no point in compiling specs (except for package
6727 specs with no bodies) because these are compiled as needed by clients. If
6728 you attempt a useless compilation, you will receive an error message.
6729 It is also useless to compile subunits because they are compiled as needed
6730 by the parent.
6731
6732 @item
6733 There are no order of compilation requirements: performing a
6734 compilation never obsoletes anything. The only way you can obsolete
6735 something and require recompilations is to modify one of the
6736 source files on which it depends.
6737
6738 @item
6739 There is no library as such, apart from the ALI files
6740 (@pxref{The Ada Library Information Files}, for information on the format
6741 of these files). For now we find it convenient to create separate ALI files,
6742 but eventually the information therein may be incorporated into the object
6743 file directly.
6744
6745 @item
6746 When you compile a unit, the source files for the specs of all units
6747 that it @code{with}'s, all its subunits, and the bodies of any generics it
6748 instantiates must be available (reachable by the search-paths mechanism
6749 described above), or you will receive a fatal error message.
6750 @end itemize
6751
6752 @node Examples
6753 @section Examples
6754
6755 @noindent
6756 The following are some typical Ada compilation command line examples:
6757
6758 @table @code
6759 @item $ gcc -c xyz.adb
6760 Compile body in file @file{xyz.adb} with all default options.
6761
6762 @ifclear vms
6763 @item $ gcc -c -O2 -gnata xyz-def.adb
6764 @end ifclear
6765 @ifset vms
6766 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6767 @end ifset
6768
6769 Compile the child unit package in file @file{xyz-def.adb} with extensive
6770 optimizations, and pragma @code{Assert}/@code{Debug} statements
6771 enabled.
6772
6773 @item $ gcc -c -gnatc abc-def.adb
6774 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6775 mode.
6776 @end table
6777
6778 @node Binding Using gnatbind
6779 @chapter Binding Using @code{gnatbind}
6780 @findex gnatbind
6781
6782 @menu
6783 * Running gnatbind::
6784 * Switches for gnatbind::
6785 * Command-Line Access::
6786 * Search Paths for gnatbind::
6787 * Examples of gnatbind Usage::
6788 @end menu
6789
6790 @noindent
6791 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6792 to bind compiled GNAT objects. The @code{gnatbind} program performs
6793 four separate functions:
6794
6795 @enumerate
6796 @item
6797 Checks that a program is consistent, in accordance with the rules in
6798 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6799 messages are generated if a program uses inconsistent versions of a
6800 given unit.
6801
6802 @item
6803 Checks that an acceptable order of elaboration exists for the program
6804 and issues an error message if it cannot find an order of elaboration
6805 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6806
6807 @item
6808 Generates a main program incorporating the given elaboration order.
6809 This program is a small Ada package (body and spec) that
6810 must be subsequently compiled
6811 using the GNAT compiler. The necessary compilation step is usually
6812 performed automatically by @code{gnatlink}. The two most important
6813 functions of this program
6814 are to call the elaboration routines of units in an appropriate order
6815 and to call the main program.
6816
6817 @item
6818 Determines the set of object files required by the given main program.
6819 This information is output in the forms of comments in the generated program,
6820 to be read by the @code{gnatlink} utility used to link the Ada application.
6821 @end enumerate
6822
6823
6824 @node Running gnatbind
6825 @section Running @code{gnatbind}
6826
6827 @noindent
6828 The form of the @code{gnatbind} command is
6829
6830 @smallexample
6831 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6832 @end smallexample
6833
6834 @noindent
6835 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6836 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6837 package in two files whose names are
6838 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6839 For example, if given the
6840 parameter @file{hello.ali}, for a main program contained in file
6841 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6842 and @file{b~hello.adb}.
6843
6844 When doing consistency checking, the binder takes into consideration
6845 any source files it can locate. For example, if the binder determines
6846 that the given main program requires the package @code{Pack}, whose
6847 @file{.ALI}
6848 file is @file{pack.ali} and whose corresponding source spec file is
6849 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6850 (using the same search path conventions as previously described for the
6851 @code{gcc} command). If it can locate this source file, it checks that
6852 the time stamps
6853 or source checksums of the source and its references to in @file{ALI} files
6854 match. In other words, any @file{ALI} files that mentions this spec must have
6855 resulted from compiling this version of the source file (or in the case
6856 where the source checksums match, a version close enough that the
6857 difference does not matter).
6858
6859 @cindex Source files, use by binder
6860 The effect of this consistency checking, which includes source files, is
6861 that the binder ensures that the program is consistent with the latest
6862 version of the source files that can be located at bind time. Editing a
6863 source file without compiling files that depend on the source file cause
6864 error messages to be generated by the binder.
6865
6866 For example, suppose you have a main program @file{hello.adb} and a
6867 package @code{P}, from file @file{p.ads} and you perform the following
6868 steps:
6869
6870 @enumerate
6871 @item
6872 Enter @code{gcc -c hello.adb} to compile the main program.
6873
6874 @item
6875 Enter @code{gcc -c p.ads} to compile package @code{P}.
6876
6877 @item
6878 Edit file @file{p.ads}.
6879
6880 @item
6881 Enter @code{gnatbind hello}.
6882 @end enumerate
6883
6884 @noindent
6885 At this point, the file @file{p.ali} contains an out-of-date time stamp
6886 because the file @file{p.ads} has been edited. The attempt at binding
6887 fails, and the binder generates the following error messages:
6888
6889 @smallexample
6890 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6891 error: "p.ads" has been modified and must be recompiled
6892 @end smallexample
6893
6894 @noindent
6895 Now both files must be recompiled as indicated, and then the bind can
6896 succeed, generating a main program. You need not normally be concerned
6897 with the contents of this file, but for reference purposes a sample
6898 binder output file is given in @ref{Example of Binder Output File}.
6899
6900 In most normal usage, the default mode of @command{gnatbind} which is to
6901 generate the main package in Ada, as described in the previous section.
6902 In particular, this means that any Ada programmer can read and understand
6903 the generated main program. It can also be debugged just like any other
6904 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6905 @command{gnatbind} and @command{gnatlink}.
6906
6907 However for some purposes it may be convenient to generate the main
6908 program in C rather than Ada. This may for example be helpful when you
6909 are generating a mixed language program with the main program in C. The
6910 GNAT compiler itself is an example.
6911 The use of the @option{^-C^/BIND_FILE=C^} switch
6912 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6913 be generated in C (and compiled using the gnu C compiler).
6914
6915
6916 @node Switches for gnatbind
6917 @section Switches for @command{gnatbind}
6918
6919 @noindent
6920 The following switches are available with @code{gnatbind}; details will
6921 be presented in subsequent sections.
6922
6923 @menu
6924 * Consistency-Checking Modes::
6925 * Binder Error Message Control::
6926 * Elaboration Control::
6927 * Output Control::
6928 * Binding with Non-Ada Main Programs::
6929 * Binding Programs with No Main Subprogram::
6930 @end menu
6931
6932 @table @option
6933 @c !sort!
6934 @item ^-aO^/OBJECT_SEARCH^
6935 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6936 Specify directory to be searched for ALI files.
6937
6938 @item ^-aI^/SOURCE_SEARCH^
6939 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6940 Specify directory to be searched for source file.
6941
6942 @item ^-A^/BIND_FILE=ADA^
6943 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6944 Generate binder program in Ada (default)
6945
6946 @item ^-b^/REPORT_ERRORS=BRIEF^
6947 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6948 Generate brief messages to @file{stderr} even if verbose mode set.
6949
6950 @item ^-c^/NOOUTPUT^
6951 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6952 Check only, no generation of binder output file.
6953
6954 @item ^-C^/BIND_FILE=C^
6955 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6956 Generate binder program in C
6957
6958 @item ^-e^/ELABORATION_DEPENDENCIES^
6959 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6960 Output complete list of elaboration-order dependencies.
6961
6962 @item ^-E^/STORE_TRACEBACKS^
6963 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6964 Store tracebacks in exception occurrences when the target supports it.
6965 This is the default with the zero cost exception mechanism.
6966 @ignore
6967 @c The following may get moved to an appendix
6968 This option is currently supported on the following targets:
6969 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6970 @end ignore
6971 See also the packages @code{GNAT.Traceback} and
6972 @code{GNAT.Traceback.Symbolic} for more information.
6973 @ifclear vms
6974 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6975 @code{gcc} option.
6976 @end ifclear
6977
6978 @item ^-F^/FORCE_ELABS_FLAGS^
6979 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6980 Force the checks of elaboration flags. @command{gnatbind} does not normally
6981 generate checks of elaboration flags for the main executable, except when
6982 a Stand-Alone Library is used. However, there are cases when this cannot be
6983 detected by gnatbind. An example is importing an interface of a Stand-Alone
6984 Library through a pragma Import and only specifying through a linker switch
6985 this Stand-Alone Library. This switch is used to guarantee that elaboration
6986 flag checks are generated.
6987
6988 @item ^-h^/HELP^
6989 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6990 Output usage (help) information
6991
6992 @item ^-I^/SEARCH^
6993 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6994 Specify directory to be searched for source and ALI files.
6995
6996 @item ^-I-^/NOCURRENT_DIRECTORY^
6997 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6998 Do not look for sources in the current directory where @code{gnatbind} was
6999 invoked, and do not look for ALI files in the directory containing the
7000 ALI file named in the @code{gnatbind} command line.
7001
7002 @item ^-l^/ORDER_OF_ELABORATION^
7003 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7004 Output chosen elaboration order.
7005
7006 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7007 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7008 Binds the units for library building. In this case the adainit and
7009 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7010 are renamed to ^xxxinit^XXXINIT^ and
7011 ^xxxfinal^XXXFINAL^.
7012 Implies ^-n^/NOCOMPILE^.
7013 @ifclear vms
7014 (@pxref{GNAT and Libraries}, for more details.)
7015 @end ifclear
7016 @ifset vms
7017 On OpenVMS, these init and final procedures are exported in uppercase
7018 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7019 the init procedure will be "TOTOINIT" and the exported name of the final
7020 procedure will be "TOTOFINAL".
7021 @end ifset
7022
7023 @item ^-Mxyz^/RENAME_MAIN=xyz^
7024 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7025 Rename generated main program from main to xyz
7026
7027 @item ^-m^/ERROR_LIMIT=^@var{n}
7028 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7029 Limit number of detected errors to @var{n}, where @var{n} is
7030 in the range 1..999_999. The default value if no switch is
7031 given is 9999. Binding is terminated if the limit is exceeded.
7032 @ifset unw
7033 Furthermore, under Windows, the sources pointed to by the libraries path
7034 set in the registry are not searched for.
7035 @end ifset
7036
7037 @item ^-n^/NOMAIN^
7038 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7039 No main program.
7040
7041 @item -nostdinc
7042 @cindex @option{-nostdinc} (@command{gnatbind})
7043 Do not look for sources in the system default directory.
7044
7045 @item -nostdlib
7046 @cindex @option{-nostdlib} (@command{gnatbind})
7047 Do not look for library files in the system default directory.
7048
7049 @item --RTS=@var{rts-path}
7050 @cindex @option{--RTS} (@code{gnatbind})
7051 Specifies the default location of the runtime library. Same meaning as the
7052 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7053
7054 @item ^-o ^/OUTPUT=^@var{file}
7055 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7056 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7057 Note that if this option is used, then linking must be done manually,
7058 gnatlink cannot be used.
7059
7060 @item ^-O^/OBJECT_LIST^
7061 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7062 Output object list.
7063
7064 @item ^-p^/PESSIMISTIC_ELABORATION^
7065 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7066 Pessimistic (worst-case) elaboration order
7067
7068 @item ^-s^/READ_SOURCES=ALL^
7069 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7070 Require all source files to be present.
7071
7072 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7073 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7074 Specifies the value to be used when detecting uninitialized scalar
7075 objects with pragma Initialize_Scalars.
7076 The @var{xxx} ^string specified with the switch^option^ may be either
7077 @itemize @bullet
7078 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7079 @item ``@option{^lo^LOW^}'' for the lowest possible value
7080 possible, and the low
7081 @item ``@option{^hi^HIGH^}'' for the highest possible value
7082 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7083 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7084 @end itemize
7085
7086 In addition, you can specify @option{-Sev} to indicate that the value is
7087 to be set at run time. In this case, the program will look for an environment
7088 @cindex GNAT_INIT_SCALARS
7089 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7090 of @option{in/lo/hi/xx} with the same meanings as above.
7091 If no environment variable is found, or if it does not have a valid value,
7092 then the default is @option{in} (invalid values).
7093
7094 @ifclear vms
7095 @item -static
7096 @cindex @option{-static} (@code{gnatbind})
7097 Link against a static GNAT run time.
7098
7099 @item -shared
7100 @cindex @option{-shared} (@code{gnatbind})
7101 Link against a shared GNAT run time when available.
7102 @end ifclear
7103
7104 @item ^-t^/NOTIME_STAMP_CHECK^
7105 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7106 Tolerate time stamp and other consistency errors
7107
7108 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7109 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7110 Set the time slice value to @var{n} milliseconds. If the system supports
7111 the specification of a specific time slice value, then the indicated value
7112 is used. If the system does not support specific time slice values, but
7113 does support some general notion of round-robin scheduling, then any
7114 non-zero value will activate round-robin scheduling.
7115
7116 A value of zero is treated specially. It turns off time
7117 slicing, and in addition, indicates to the tasking run time that the
7118 semantics should match as closely as possible the Annex D
7119 requirements of the Ada RM, and in particular sets the default
7120 scheduling policy to @code{FIFO_Within_Priorities}.
7121
7122 @item ^-v^/REPORT_ERRORS=VERBOSE^
7123 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7124 Verbose mode. Write error messages, header, summary output to
7125 @file{stdout}.
7126
7127 @ifclear vms
7128 @item -w@var{x}
7129 @cindex @option{-w} (@code{gnatbind})
7130 Warning mode (@var{x}=s/e for suppress/treat as error)
7131 @end ifclear
7132
7133 @ifset vms
7134 @item /WARNINGS=NORMAL
7135 @cindex @option{/WARNINGS} (@code{gnatbind})
7136 Normal warnings mode. Warnings are issued but ignored
7137
7138 @item /WARNINGS=SUPPRESS
7139 @cindex @option{/WARNINGS} (@code{gnatbind})
7140 All warning messages are suppressed
7141
7142 @item /WARNINGS=ERROR
7143 @cindex @option{/WARNINGS} (@code{gnatbind})
7144 Warning messages are treated as fatal errors
7145 @end ifset
7146
7147 @item ^-x^/READ_SOURCES=NONE^
7148 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7149 Exclude source files (check object consistency only).
7150
7151 @ifset vms
7152 @item /READ_SOURCES=AVAILABLE
7153 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7154 Default mode, in which sources are checked for consistency only if
7155 they are available.
7156 @end ifset
7157
7158 @item ^-z^/ZERO_MAIN^
7159 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7160 No main subprogram.
7161 @end table
7162
7163 @ifclear vms
7164 @noindent
7165 You may obtain this listing of switches by running @code{gnatbind} with
7166 no arguments.
7167 @end ifclear
7168
7169
7170 @node Consistency-Checking Modes
7171 @subsection Consistency-Checking Modes
7172
7173 @noindent
7174 As described earlier, by default @code{gnatbind} checks
7175 that object files are consistent with one another and are consistent
7176 with any source files it can locate. The following switches control binder
7177 access to sources.
7178
7179 @table @option
7180 @c !sort!
7181 @item ^-s^/READ_SOURCES=ALL^
7182 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7183 Require source files to be present. In this mode, the binder must be
7184 able to locate all source files that are referenced, in order to check
7185 their consistency. In normal mode, if a source file cannot be located it
7186 is simply ignored. If you specify this switch, a missing source
7187 file is an error.
7188
7189 @item ^-x^/READ_SOURCES=NONE^
7190 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7191 Exclude source files. In this mode, the binder only checks that ALI
7192 files are consistent with one another. Source files are not accessed.
7193 The binder runs faster in this mode, and there is still a guarantee that
7194 the resulting program is self-consistent.
7195 If a source file has been edited since it was last compiled, and you
7196 specify this switch, the binder will not detect that the object
7197 file is out of date with respect to the source file. Note that this is the
7198 mode that is automatically used by @code{gnatmake} because in this
7199 case the checking against sources has already been performed by
7200 @code{gnatmake} in the course of compilation (i.e. before binding).
7201
7202 @ifset vms
7203 @item /READ_SOURCES=AVAILABLE
7204 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7205 This is the default mode in which source files are checked if they are
7206 available, and ignored if they are not available.
7207 @end ifset
7208 @end table
7209
7210 @node Binder Error Message Control
7211 @subsection Binder Error Message Control
7212
7213 @noindent
7214 The following switches provide control over the generation of error
7215 messages from the binder:
7216
7217 @table @option
7218 @c !sort!
7219 @item ^-v^/REPORT_ERRORS=VERBOSE^
7220 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7221 Verbose mode. In the normal mode, brief error messages are generated to
7222 @file{stderr}. If this switch is present, a header is written
7223 to @file{stdout} and any error messages are directed to @file{stdout}.
7224 All that is written to @file{stderr} is a brief summary message.
7225
7226 @item ^-b^/REPORT_ERRORS=BRIEF^
7227 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7228 Generate brief error messages to @file{stderr} even if verbose mode is
7229 specified. This is relevant only when used with the
7230 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7231
7232 @ifclear vms
7233 @item -m@var{n}
7234 @cindex @option{-m} (@code{gnatbind})
7235 Limits the number of error messages to @var{n}, a decimal integer in the
7236 range 1-999. The binder terminates immediately if this limit is reached.
7237
7238 @item -M@var{xxx}
7239 @cindex @option{-M} (@code{gnatbind})
7240 Renames the generated main program from @code{main} to @code{xxx}.
7241 This is useful in the case of some cross-building environments, where
7242 the actual main program is separate from the one generated
7243 by @code{gnatbind}.
7244 @end ifclear
7245
7246 @item ^-ws^/WARNINGS=SUPPRESS^
7247 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7248 @cindex Warnings
7249 Suppress all warning messages.
7250
7251 @item ^-we^/WARNINGS=ERROR^
7252 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7253 Treat any warning messages as fatal errors.
7254
7255 @ifset vms
7256 @item /WARNINGS=NORMAL
7257 Standard mode with warnings generated, but warnings do not get treated
7258 as errors.
7259 @end ifset
7260
7261 @item ^-t^/NOTIME_STAMP_CHECK^
7262 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7263 @cindex Time stamp checks, in binder
7264 @cindex Binder consistency checks
7265 @cindex Consistency checks, in binder
7266 The binder performs a number of consistency checks including:
7267
7268 @itemize @bullet
7269 @item
7270 Check that time stamps of a given source unit are consistent
7271 @item
7272 Check that checksums of a given source unit are consistent
7273 @item
7274 Check that consistent versions of @code{GNAT} were used for compilation
7275 @item
7276 Check consistency of configuration pragmas as required
7277 @end itemize
7278
7279 @noindent
7280 Normally failure of such checks, in accordance with the consistency
7281 requirements of the Ada Reference Manual, causes error messages to be
7282 generated which abort the binder and prevent the output of a binder
7283 file and subsequent link to obtain an executable.
7284
7285 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7286 into warnings, so that
7287 binding and linking can continue to completion even in the presence of such
7288 errors. The result may be a failed link (due to missing symbols), or a
7289 non-functional executable which has undefined semantics.
7290 @emph{This means that
7291 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7292 with extreme care.}
7293 @end table
7294
7295 @node Elaboration Control
7296 @subsection Elaboration Control
7297
7298 @noindent
7299 The following switches provide additional control over the elaboration
7300 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7301
7302 @table @option
7303 @item ^-p^/PESSIMISTIC_ELABORATION^
7304 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7305 Normally the binder attempts to choose an elaboration order that is
7306 likely to minimize the likelihood of an elaboration order error resulting
7307 in raising a @code{Program_Error} exception. This switch reverses the
7308 action of the binder, and requests that it deliberately choose an order
7309 that is likely to maximize the likelihood of an elaboration error.
7310 This is useful in ensuring portability and avoiding dependence on
7311 accidental fortuitous elaboration ordering.
7312
7313 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7314 switch if dynamic
7315 elaboration checking is used (@option{-gnatE} switch used for compilation).
7316 This is because in the default static elaboration mode, all necessary
7317 @code{Elaborate_All} pragmas are implicitly inserted.
7318 These implicit pragmas are still respected by the binder in
7319 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7320 safe elaboration order is assured.
7321 @end table
7322
7323 @node Output Control
7324 @subsection Output Control
7325
7326 @noindent
7327 The following switches allow additional control over the output
7328 generated by the binder.
7329
7330 @table @option
7331 @c !sort!
7332
7333 @item ^-A^/BIND_FILE=ADA^
7334 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7335 Generate binder program in Ada (default). The binder program is named
7336 @file{b~@var{mainprog}.adb} by default. This can be changed with
7337 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7338
7339 @item ^-c^/NOOUTPUT^
7340 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7341 Check only. Do not generate the binder output file. In this mode the
7342 binder performs all error checks but does not generate an output file.
7343
7344 @item ^-C^/BIND_FILE=C^
7345 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7346 Generate binder program in C. The binder program is named
7347 @file{b_@var{mainprog}.c}.
7348 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7349 option.
7350
7351 @item ^-e^/ELABORATION_DEPENDENCIES^
7352 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7353 Output complete list of elaboration-order dependencies, showing the
7354 reason for each dependency. This output can be rather extensive but may
7355 be useful in diagnosing problems with elaboration order. The output is
7356 written to @file{stdout}.
7357
7358 @item ^-h^/HELP^
7359 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7360 Output usage information. The output is written to @file{stdout}.
7361
7362 @item ^-K^/LINKER_OPTION_LIST^
7363 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7364 Output linker options to @file{stdout}. Includes library search paths,
7365 contents of pragmas Ident and Linker_Options, and libraries added
7366 by @code{gnatbind}.
7367
7368 @item ^-l^/ORDER_OF_ELABORATION^
7369 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7370 Output chosen elaboration order. The output is written to @file{stdout}.
7371
7372 @item ^-O^/OBJECT_LIST^
7373 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7374 Output full names of all the object files that must be linked to provide
7375 the Ada component of the program. The output is written to @file{stdout}.
7376 This list includes the files explicitly supplied and referenced by the user
7377 as well as implicitly referenced run-time unit files. The latter are
7378 omitted if the corresponding units reside in shared libraries. The
7379 directory names for the run-time units depend on the system configuration.
7380
7381 @item ^-o ^/OUTPUT=^@var{file}
7382 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7383 Set name of output file to @var{file} instead of the normal
7384 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7385 binder generated body filename. In C mode you would normally give
7386 @var{file} an extension of @file{.c} because it will be a C source program.
7387 Note that if this option is used, then linking must be done manually.
7388 It is not possible to use gnatlink in this case, since it cannot locate
7389 the binder file.
7390
7391 @item ^-r^/RESTRICTION_LIST^
7392 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7393 Generate list of @code{pragma Restrictions} that could be applied to
7394 the current unit. This is useful for code audit purposes, and also may
7395 be used to improve code generation in some cases.
7396
7397 @end table
7398
7399 @node Binding with Non-Ada Main Programs
7400 @subsection Binding with Non-Ada Main Programs
7401
7402 @noindent
7403 In our description so far we have assumed that the main
7404 program is in Ada, and that the task of the binder is to generate a
7405 corresponding function @code{main} that invokes this Ada main
7406 program. GNAT also supports the building of executable programs where
7407 the main program is not in Ada, but some of the called routines are
7408 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7409 The following switch is used in this situation:
7410
7411 @table @option
7412 @item ^-n^/NOMAIN^
7413 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7414 No main program. The main program is not in Ada.
7415 @end table
7416
7417 @noindent
7418 In this case, most of the functions of the binder are still required,
7419 but instead of generating a main program, the binder generates a file
7420 containing the following callable routines:
7421
7422 @table @code
7423 @item adainit
7424 @findex adainit
7425 You must call this routine to initialize the Ada part of the program by
7426 calling the necessary elaboration routines. A call to @code{adainit} is
7427 required before the first call to an Ada subprogram.
7428
7429 Note that it is assumed that the basic execution environment must be setup
7430 to be appropriate for Ada execution at the point where the first Ada
7431 subprogram is called. In particular, if the Ada code will do any
7432 floating-point operations, then the FPU must be setup in an appropriate
7433 manner. For the case of the x86, for example, full precision mode is
7434 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7435 that the FPU is in the right state.
7436
7437 @item adafinal
7438 @findex adafinal
7439 You must call this routine to perform any library-level finalization
7440 required by the Ada subprograms. A call to @code{adafinal} is required
7441 after the last call to an Ada subprogram, and before the program
7442 terminates.
7443 @end table
7444
7445 @noindent
7446 If the @option{^-n^/NOMAIN^} switch
7447 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7448 @cindex Binder, multiple input files
7449 is given, more than one ALI file may appear on
7450 the command line for @code{gnatbind}. The normal @dfn{closure}
7451 calculation is performed for each of the specified units. Calculating
7452 the closure means finding out the set of units involved by tracing
7453 @code{with} references. The reason it is necessary to be able to
7454 specify more than one ALI file is that a given program may invoke two or
7455 more quite separate groups of Ada units.
7456
7457 The binder takes the name of its output file from the last specified ALI
7458 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7459 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7460 The output is an Ada unit in source form that can
7461 be compiled with GNAT unless the -C switch is used in which case the
7462 output is a C source file, which must be compiled using the C compiler.
7463 This compilation occurs automatically as part of the @code{gnatlink}
7464 processing.
7465
7466 Currently the GNAT run time requires a FPU using 80 bits mode
7467 precision. Under targets where this is not the default it is required to
7468 call GNAT.Float_Control.Reset before using floating point numbers (this
7469 include float computation, float input and output) in the Ada code. A
7470 side effect is that this could be the wrong mode for the foreign code
7471 where floating point computation could be broken after this call.
7472
7473 @node Binding Programs with No Main Subprogram
7474 @subsection Binding Programs with No Main Subprogram
7475
7476 @noindent
7477 It is possible to have an Ada program which does not have a main
7478 subprogram. This program will call the elaboration routines of all the
7479 packages, then the finalization routines.
7480
7481 The following switch is used to bind programs organized in this manner:
7482
7483 @table @option
7484 @item ^-z^/ZERO_MAIN^
7485 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7486 Normally the binder checks that the unit name given on the command line
7487 corresponds to a suitable main subprogram. When this switch is used,
7488 a list of ALI files can be given, and the execution of the program
7489 consists of elaboration of these units in an appropriate order.
7490 @end table
7491
7492
7493 @node Command-Line Access
7494 @section Command-Line Access
7495
7496 @noindent
7497 The package @code{Ada.Command_Line} provides access to the command-line
7498 arguments and program name. In order for this interface to operate
7499 correctly, the two variables
7500
7501 @smallexample
7502 @group
7503 int gnat_argc;
7504 char **gnat_argv;
7505 @end group
7506 @end smallexample
7507
7508 @noindent
7509 @findex gnat_argv
7510 @findex gnat_argc
7511 are declared in one of the GNAT library routines. These variables must
7512 be set from the actual @code{argc} and @code{argv} values passed to the
7513 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7514 generates the C main program to automatically set these variables.
7515 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7516 set these variables. If they are not set, the procedures in
7517 @code{Ada.Command_Line} will not be available, and any attempt to use
7518 them will raise @code{Constraint_Error}. If command line access is
7519 required, your main program must set @code{gnat_argc} and
7520 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7521 it.
7522
7523
7524 @node Search Paths for gnatbind
7525 @section Search Paths for @code{gnatbind}
7526
7527 @noindent
7528 The binder takes the name of an ALI file as its argument and needs to
7529 locate source files as well as other ALI files to verify object consistency.
7530
7531 For source files, it follows exactly the same search rules as @code{gcc}
7532 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7533 directories searched are:
7534
7535 @enumerate
7536 @item
7537 The directory containing the ALI file named in the command line, unless
7538 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7539
7540 @item
7541 All directories specified by @option{^-I^/SEARCH^}
7542 switches on the @code{gnatbind}
7543 command line, in the order given.
7544
7545 @item
7546 @findex ADA_OBJECTS_PATH
7547 Each of the directories listed in the value of the
7548 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7549 @ifset unw
7550 Construct this value
7551 exactly as the @code{PATH} environment variable: a list of directory
7552 names separated by colons (semicolons when working with the NT version
7553 of GNAT).
7554 @end ifset
7555 @ifset vms
7556 Normally, define this value as a logical name containing a comma separated
7557 list of directory names.
7558
7559 This variable can also be defined by means of an environment string
7560 (an argument to the DEC C exec* set of functions).
7561
7562 Logical Name:
7563 @smallexample
7564 DEFINE ANOTHER_PATH FOO:[BAG]
7565 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7566 @end smallexample
7567
7568 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7569 first, followed by the standard Ada 95
7570 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7571 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7572 (Text_IO, Sequential_IO, etc)
7573 instead of the Ada95 packages. Thus, in order to get the Ada 95
7574 packages by default, ADA_OBJECTS_PATH must be redefined.
7575 @end ifset
7576
7577 @item
7578 @findex ADA_PRJ_OBJECTS_FILE
7579 Each of the directories listed in the text file whose name is given
7580 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7581
7582 @noindent
7583 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7584 driver when project files are used. It should not normally be set
7585 by other means.
7586
7587 @item
7588 The content of the @file{ada_object_path} file which is part of the GNAT
7589 installation tree and is used to store standard libraries such as the
7590 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7591 specified.
7592 @ifclear vms
7593 @ref{Installing the library}
7594 @end ifclear
7595 @end enumerate
7596
7597 @noindent
7598 In the binder the switch @option{^-I^/SEARCH^}
7599 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7600 is used to specify both source and
7601 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7602 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7603 instead if you want to specify
7604 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7605 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7606 if you want to specify library paths
7607 only. This means that for the binder
7608 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7609 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7610 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7611 The binder generates the bind file (a C language source file) in the
7612 current working directory.
7613
7614 @findex Ada
7615 @findex System
7616 @findex Interfaces
7617 @findex GNAT
7618 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7619 children make up the GNAT Run-Time Library, together with the package
7620 GNAT and its children, which contain a set of useful additional
7621 library functions provided by GNAT. The sources for these units are
7622 needed by the compiler and are kept together in one directory. The ALI
7623 files and object files generated by compiling the RTL are needed by the
7624 binder and the linker and are kept together in one directory, typically
7625 different from the directory containing the sources. In a normal
7626 installation, you need not specify these directory names when compiling
7627 or binding. Either the environment variables or the built-in defaults
7628 cause these files to be found.
7629
7630 Besides simplifying access to the RTL, a major use of search paths is
7631 in compiling sources from multiple directories. This can make
7632 development environments much more flexible.
7633
7634 @node Examples of gnatbind Usage
7635 @section Examples of @code{gnatbind} Usage
7636
7637 @noindent
7638 This section contains a number of examples of using the GNAT binding
7639 utility @code{gnatbind}.
7640
7641 @table @code
7642 @item gnatbind hello
7643 The main program @code{Hello} (source program in @file{hello.adb}) is
7644 bound using the standard switch settings. The generated main program is
7645 @file{b~hello.adb}. This is the normal, default use of the binder.
7646
7647 @ifclear vms
7648 @item gnatbind hello -o mainprog.adb
7649 @end ifclear
7650 @ifset vms
7651 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7652 @end ifset
7653 The main program @code{Hello} (source program in @file{hello.adb}) is
7654 bound using the standard switch settings. The generated main program is
7655 @file{mainprog.adb} with the associated spec in
7656 @file{mainprog.ads}. Note that you must specify the body here not the
7657 spec, in the case where the output is in Ada. Note that if this option
7658 is used, then linking must be done manually, since gnatlink will not
7659 be able to find the generated file.
7660
7661 @ifclear vms
7662 @item gnatbind main -C -o mainprog.c -x
7663 @end ifclear
7664 @ifset vms
7665 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7666 @end ifset
7667 The main program @code{Main} (source program in
7668 @file{main.adb}) is bound, excluding source files from the
7669 consistency checking, generating
7670 the file @file{mainprog.c}.
7671
7672 @ifclear vms
7673 @item gnatbind -x main_program -C -o mainprog.c
7674 This command is exactly the same as the previous example. Switches may
7675 appear anywhere in the command line, and single letter switches may be
7676 combined into a single switch.
7677 @end ifclear
7678
7679 @ifclear vms
7680 @item gnatbind -n math dbase -C -o ada-control.c
7681 @end ifclear
7682 @ifset vms
7683 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7684 @end ifset
7685 The main program is in a language other than Ada, but calls to
7686 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7687 to @code{gnatbind} generates the file @file{ada-control.c} containing
7688 the @code{adainit} and @code{adafinal} routines to be called before and
7689 after accessing the Ada units.
7690 @end table
7691
7692
7693 @c ------------------------------------
7694 @node Linking Using gnatlink
7695 @chapter Linking Using @code{gnatlink}
7696 @c ------------------------------------
7697 @findex gnatlink
7698
7699 @noindent
7700 This chapter discusses @code{gnatlink}, a tool that links
7701 an Ada program and builds an executable file. This utility
7702 invokes the system linker ^(via the @code{gcc} command)^^
7703 with a correct list of object files and library references.
7704 @code{gnatlink} automatically determines the list of files and
7705 references for the Ada part of a program. It uses the binder file
7706 generated by the @command{gnatbind} to determine this list.
7707
7708 @menu
7709 * Running gnatlink::
7710 * Switches for gnatlink::
7711 * Setting Stack Size from gnatlink::
7712 * Setting Heap Size from gnatlink::
7713 @end menu
7714
7715 @node Running gnatlink
7716 @section Running @code{gnatlink}
7717
7718 @noindent
7719 The form of the @code{gnatlink} command is
7720
7721 @smallexample
7722 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7723            [@var{non-Ada objects}] [@var{linker options}]
7724 @end smallexample
7725
7726 @noindent
7727 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7728 non-Ada objects
7729 or linker options) may be in any order, provided that no non-Ada object may
7730 be mistaken for a main @file{ALI} file.
7731 Any file name @file{F} without the @file{.ali}
7732 extension will be taken as the main @file{ALI} file if a file exists
7733 whose name is the concatenation of @file{F} and @file{.ali}.
7734
7735 @noindent
7736 @file{@var{mainprog}.ali} references the ALI file of the main program.
7737 The @file{.ali} extension of this file can be omitted. From this
7738 reference, @code{gnatlink} locates the corresponding binder file
7739 @file{b~@var{mainprog}.adb} and, using the information in this file along
7740 with the list of non-Ada objects and linker options, constructs a
7741 linker command file to create the executable.
7742
7743 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7744 file are passed to the linker uninterpreted.
7745 They typically include the names of
7746 object files for units written in other languages than Ada and any library
7747 references required to resolve references in any of these foreign language
7748 units, or in @code{Import} pragmas in any Ada units.
7749
7750 @var{linker options} is an optional list of linker specific
7751 switches.
7752 The default linker called by gnatlink is @var{gcc} which in
7753 turn calls the appropriate system linker.
7754 Standard options for the linker such as @option{-lmy_lib} or
7755 @option{-Ldir} can be added as is.
7756 For options that are not recognized by
7757 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7758 @option{-Wl,}.
7759 Refer to the GCC documentation for
7760 details. Here is an example showing how to generate a linker map:
7761
7762 @ifclear vms
7763 @smallexample
7764 $ gnatlink my_prog -Wl,-Map,MAPFILE
7765 @end smallexample
7766 @end ifclear
7767
7768 @ifset vms
7769 <<Need example for VMS>>
7770 @end ifset
7771
7772 Using @var{linker options} it is possible to set the program stack and
7773 heap size. See @ref{Setting Stack Size from gnatlink}, and
7774 @ref{Setting Heap Size from gnatlink}.
7775
7776 @code{gnatlink} determines the list of objects required by the Ada
7777 program and prepends them to the list of objects passed to the linker.
7778 @code{gnatlink} also gathers any arguments set by the use of
7779 @code{pragma Linker_Options} and adds them to the list of arguments
7780 presented to the linker.
7781
7782 @ifset vms
7783 @code{gnatlink} accepts the following types of extra files on the command
7784 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7785 options files (.OPT). These are recognized and handled according to their
7786 extension.
7787 @end ifset
7788
7789 @node Switches for gnatlink
7790 @section Switches for @code{gnatlink}
7791
7792 @noindent
7793 The following switches are available with the @code{gnatlink} utility:
7794
7795 @table @option
7796 @c !sort!
7797
7798 @item ^-A^/BIND_FILE=ADA^
7799 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7800 The binder has generated code in Ada. This is the default.
7801
7802 @item ^-C^/BIND_FILE=C^
7803 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7804 If instead of generating a file in Ada, the binder has generated one in
7805 C, then the linker needs to know about it. Use this switch to signal
7806 to @code{gnatlink} that the binder has generated C code rather than
7807 Ada code.
7808
7809 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7810 @cindex Command line length
7811 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7812 On some targets, the command line length is limited, and @code{gnatlink}
7813 will generate a separate file for the linker if the list of object files
7814 is too long.
7815 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7816 to be generated even if
7817 the limit is not exceeded. This is useful in some cases to deal with
7818 special situations where the command line length is exceeded.
7819
7820 @item ^-g^/DEBUG^
7821 @cindex Debugging information, including
7822 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7823 The option to include debugging information causes the Ada bind file (in
7824 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7825 @option{^-g^/DEBUG^}.
7826 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7827 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7828 Without @option{^-g^/DEBUG^}, the binder removes these files by
7829 default. The same procedure apply if a C bind file was generated using
7830 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7831 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7832
7833 @item ^-n^/NOCOMPILE^
7834 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7835 Do not compile the file generated by the binder. This may be used when
7836 a link is rerun with different options, but there is no need to recompile
7837 the binder file.
7838
7839 @item ^-v^/VERBOSE^
7840 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7841 Causes additional information to be output, including a full list of the
7842 included object files. This switch option is most useful when you want
7843 to see what set of object files are being used in the link step.
7844
7845 @item ^-v -v^/VERBOSE/VERBOSE^
7846 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7847 Very verbose mode. Requests that the compiler operate in verbose mode when
7848 it compiles the binder file, and that the system linker run in verbose mode.
7849
7850 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7851 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7852 @var{exec-name} specifies an alternate name for the generated
7853 executable program. If this switch is omitted, the executable has the same
7854 name as the main unit. For example, @code{gnatlink try.ali} creates
7855 an executable called @file{^try^TRY.EXE^}.
7856
7857 @ifclear vms
7858 @item -b @var{target}
7859 @cindex @option{-b} (@code{gnatlink})
7860 Compile your program to run on @var{target}, which is the name of a
7861 system configuration. You must have a GNAT cross-compiler built if
7862 @var{target} is not the same as your host system.
7863
7864 @item -B@var{dir}
7865 @cindex @option{-B} (@code{gnatlink})
7866 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7867 from @var{dir} instead of the default location. Only use this switch
7868 when multiple versions of the GNAT compiler are available. See the
7869 @code{gcc} manual page for further details. You would normally use the
7870 @option{-b} or @option{-V} switch instead.
7871
7872 @item --GCC=@var{compiler_name}
7873 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7874 Program used for compiling the binder file. The default is
7875 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7876 @code{compiler_name} contains spaces or other separator characters. As
7877 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7878 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7879 inserted after your command name. Thus in the above example the compiler
7880 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7881 If several @option{--GCC=compiler_name} are used, only the last
7882 @var{compiler_name} is taken into account. However, all the additional
7883 switches are also taken into account. Thus,
7884 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7885 @option{--GCC="bar -x -y -z -t"}.
7886
7887 @item --LINK=@var{name}
7888 @cindex @option{--LINK=} (@code{gnatlink})
7889 @var{name} is the name of the linker to be invoked. This is especially
7890 useful in mixed language programs since languages such as C++ require
7891 their own linker to be used. When this switch is omitted, the default
7892 name for the linker is (@file{gcc}). When this switch is used, the
7893 specified linker is called instead of (@file{gcc}) with exactly the same
7894 parameters that would have been passed to (@file{gcc}) so if the desired
7895 linker requires different parameters it is necessary to use a wrapper
7896 script that massages the parameters before invoking the real linker. It
7897 may be useful to control the exact invocation by using the verbose
7898 switch.
7899
7900 @end ifclear
7901
7902 @ifset vms
7903 @item /DEBUG=TRACEBACK
7904 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7905 This qualifier causes sufficient information to be included in the
7906 executable file to allow a traceback, but does not include the full
7907 symbol information needed by the debugger.
7908
7909 @item /IDENTIFICATION="<string>"
7910 @code{"<string>"} specifies the string to be stored in the image file
7911 identification field in the image header.
7912 It overrides any pragma @code{Ident} specified string.
7913
7914 @item /NOINHIBIT-EXEC
7915 Generate the executable file even if there are linker warnings.
7916
7917 @item /NOSTART_FILES
7918 Don't link in the object file containing the ``main'' transfer address.
7919 Used when linking with a foreign language main program compiled with a
7920 Digital compiler.
7921
7922 @item /STATIC
7923 Prefer linking with object libraries over sharable images, even without
7924 /DEBUG.
7925 @end ifset
7926
7927 @end table
7928
7929 @node Setting Stack Size from gnatlink
7930 @section Setting Stack Size from @code{gnatlink}
7931
7932 @noindent
7933 Under Windows systems, it is possible to specify the program stack size from
7934 @code{gnatlink} using either:
7935
7936 @itemize @bullet
7937
7938 @item using @option{-Xlinker} linker option
7939
7940 @smallexample
7941 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7942 @end smallexample
7943
7944 This sets the stack reserve size to 0x10000 bytes and the stack commit
7945 size to 0x1000 bytes.
7946
7947 @item using @option{-Wl} linker option
7948
7949 @smallexample
7950 $ gnatlink hello -Wl,--stack=0x1000000
7951 @end smallexample
7952
7953 This sets the stack reserve size to 0x1000000 bytes. Note that with
7954 @option{-Wl} option it is not possible to set the stack commit size
7955 because the coma is a separator for this option.
7956
7957 @end itemize
7958
7959 @node Setting Heap Size from gnatlink
7960 @section Setting Heap Size from @code{gnatlink}
7961
7962 @noindent
7963 Under Windows systems, it is possible to specify the program heap size from
7964 @code{gnatlink} using either:
7965
7966 @itemize @bullet
7967
7968 @item using @option{-Xlinker} linker option
7969
7970 @smallexample
7971 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7972 @end smallexample
7973
7974 This sets the heap reserve size to 0x10000 bytes and the heap commit
7975 size to 0x1000 bytes.
7976
7977 @item using @option{-Wl} linker option
7978
7979 @smallexample
7980 $ gnatlink hello -Wl,--heap=0x1000000
7981 @end smallexample
7982
7983 This sets the heap reserve size to 0x1000000 bytes. Note that with
7984 @option{-Wl} option it is not possible to set the heap commit size
7985 because the coma is a separator for this option.
7986
7987 @end itemize
7988
7989 @node The GNAT Make Program gnatmake
7990 @chapter The GNAT Make Program @code{gnatmake}
7991 @findex gnatmake
7992
7993 @menu
7994 * Running gnatmake::
7995 * Switches for gnatmake::
7996 * Mode Switches for gnatmake::
7997 * Notes on the Command Line::
7998 * How gnatmake Works::
7999 * Examples of gnatmake Usage::
8000 @end menu
8001 @noindent
8002 A typical development cycle when working on an Ada program consists of
8003 the following steps:
8004
8005 @enumerate
8006 @item
8007 Edit some sources to fix bugs.
8008
8009 @item
8010 Add enhancements.
8011
8012 @item
8013 Compile all sources affected.
8014
8015 @item
8016 Rebind and relink.
8017
8018 @item
8019 Test.
8020 @end enumerate
8021
8022 @noindent
8023 The third step can be tricky, because not only do the modified files
8024 @cindex Dependency rules
8025 have to be compiled, but any files depending on these files must also be
8026 recompiled. The dependency rules in Ada can be quite complex, especially
8027 in the presence of overloading, @code{use} clauses, generics and inlined
8028 subprograms.
8029
8030 @code{gnatmake} automatically takes care of the third and fourth steps
8031 of this process. It determines which sources need to be compiled,
8032 compiles them, and binds and links the resulting object files.
8033
8034 Unlike some other Ada make programs, the dependencies are always
8035 accurately recomputed from the new sources. The source based approach of
8036 the GNAT compilation model makes this possible. This means that if
8037 changes to the source program cause corresponding changes in
8038 dependencies, they will always be tracked exactly correctly by
8039 @code{gnatmake}.
8040
8041 @node Running gnatmake
8042 @section Running @code{gnatmake}
8043
8044 @noindent
8045 The usual form of the @code{gnatmake} command is
8046
8047 @smallexample
8048 $ gnatmake [@var{switches}] @var{file_name}
8049       [@var{file_names}] [@var{mode_switches}]
8050 @end smallexample
8051
8052 @noindent
8053 The only required argument is one @var{file_name}, which specifies
8054 a compilation unit that is a main program. Several @var{file_names} can be
8055 specified: this will result in several executables being built.
8056 If @code{switches} are present, they can be placed before the first
8057 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8058 If @var{mode_switches} are present, they must always be placed after
8059 the last @var{file_name} and all @code{switches}.
8060
8061 If you are using standard file extensions (.adb and .ads), then the
8062 extension may be omitted from the @var{file_name} arguments. However, if
8063 you are using non-standard extensions, then it is required that the
8064 extension be given. A relative or absolute directory path can be
8065 specified in a @var{file_name}, in which case, the input source file will
8066 be searched for in the specified directory only. Otherwise, the input
8067 source file will first be searched in the directory where
8068 @code{gnatmake} was invoked and if it is not found, it will be search on
8069 the source path of the compiler as described in
8070 @ref{Search Paths and the Run-Time Library (RTL)}.
8071
8072 All @code{gnatmake} output (except when you specify
8073 @option{^-M^/DEPENDENCIES_LIST^}) is to
8074 @file{stderr}. The output produced by the
8075 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8076 @file{stdout}.
8077
8078 @node Switches for gnatmake
8079 @section Switches for @code{gnatmake}
8080
8081 @noindent
8082 You may specify any of the following switches to @code{gnatmake}:
8083
8084 @table @option
8085 @c !sort!
8086 @ifclear vms
8087 @item --GCC=@var{compiler_name}
8088 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8089 Program used for compiling. The default is `@code{gcc}'. You need to use
8090 quotes around @var{compiler_name} if @code{compiler_name} contains
8091 spaces or other separator characters. As an example @option{--GCC="foo -x
8092 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8093 compiler. Note that switch @option{-c} is always inserted after your
8094 command name. Thus in the above example the compiler command that will
8095 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8096 If several @option{--GCC=compiler_name} are used, only the last
8097 @var{compiler_name} is taken into account. However, all the additional
8098 switches are also taken into account. Thus,
8099 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8100 @option{--GCC="bar -x -y -z -t"}.
8101
8102 @item --GNATBIND=@var{binder_name}
8103 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8104 Program used for binding. The default is `@code{gnatbind}'. You need to
8105 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8106 or other separator characters. As an example @option{--GNATBIND="bar -x
8107 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8108 binder. Binder switches that are normally appended by @code{gnatmake} to
8109 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8110
8111 @item --GNATLINK=@var{linker_name}
8112 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8113 Program used for linking. The default is `@code{gnatlink}'. You need to
8114 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8115 or other separator characters. As an example @option{--GNATLINK="lan -x
8116 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8117 linker. Linker switches that are normally appended by @code{gnatmake} to
8118 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8119
8120 @end ifclear
8121
8122 @item ^-a^/ALL_FILES^
8123 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8124 Consider all files in the make process, even the GNAT internal system
8125 files (for example, the predefined Ada library files), as well as any
8126 locked files. Locked files are files whose ALI file is write-protected.
8127 By default,
8128 @code{gnatmake} does not check these files,
8129 because the assumption is that the GNAT internal files are properly up
8130 to date, and also that any write protected ALI files have been properly
8131 installed. Note that if there is an installation problem, such that one
8132 of these files is not up to date, it will be properly caught by the
8133 binder.
8134 You may have to specify this switch if you are working on GNAT
8135 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8136 in conjunction with @option{^-f^/FORCE_COMPILE^}
8137 if you need to recompile an entire application,
8138 including run-time files, using special configuration pragmas,
8139 such as a @code{Normalize_Scalars} pragma.
8140
8141 By default
8142 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8143 internal files with
8144 @ifclear vms
8145 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8146 @end ifclear
8147 @ifset vms
8148 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8149 @end ifset
8150
8151 @item ^-b^/ACTIONS=BIND^
8152 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8153 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8154 compilation and binding, but no link.
8155 Can be combined with @option{^-l^/ACTIONS=LINK^}
8156 to do binding and linking. When not combined with
8157 @option{^-c^/ACTIONS=COMPILE^}
8158 all the units in the closure of the main program must have been previously
8159 compiled and must be up to date. The root unit specified by @var{file_name}
8160 may be given without extension, with the source extension or, if no GNAT
8161 Project File is specified, with the ALI file extension.
8162
8163 @item ^-c^/ACTIONS=COMPILE^
8164 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8165 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8166 is also specified. Do not perform linking, except if both
8167 @option{^-b^/ACTIONS=BIND^} and
8168  @option{^-l^/ACTIONS=LINK^} are also specified.
8169 If the root unit specified by @var{file_name} is not a main unit, this is the
8170 default. Otherwise @code{gnatmake} will attempt binding and linking
8171 unless all objects are up to date and the executable is more recent than
8172 the objects.
8173
8174 @item ^-C^/MAPPING^
8175 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8176 Use a temporary mapping file. A mapping file is a way to communicate to the
8177 compiler two mappings: from unit names to file names (without any directory
8178 information) and from file names to path names (with full directory
8179 information). These mappings are used by the compiler to short-circuit the path
8180 search. When @code{gnatmake} is invoked with this switch, it will create
8181 a temporary mapping file, initially populated by the project manager,
8182 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8183 Each invocation of the compiler will add the newly accessed sources to the
8184 mapping file. This will improve the source search during the next invocation
8185 of the compiler.
8186
8187 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8188 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8189 Use a specific mapping file. The file, specified as a path name (absolute or
8190 relative) by this switch, should already exist, otherwise the switch is
8191 ineffective. The specified mapping file will be communicated to the compiler.
8192 This switch is not compatible with a project file
8193 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8194 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8195
8196 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8197 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8198 Put all object files and ALI file in directory @var{dir}.
8199 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8200 and ALI files go in the current working directory.
8201
8202 This switch cannot be used when using a project file.
8203
8204 @ifclear vms
8205 @item -eL
8206 @cindex @option{-eL} (@code{gnatmake})
8207 Follow all symbolic links when processing project files.
8208 @end ifclear
8209
8210 @item ^-f^/FORCE_COMPILE^
8211 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8212 Force recompilations. Recompile all sources, even though some object
8213 files may be up to date, but don't recompile predefined or GNAT internal
8214 files or locked files (files with a write-protected ALI file),
8215 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8216
8217 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8218 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8219 When using project files, if some errors or warnings are detected during
8220 parsing and verbose mode is not in effect (no use of switch
8221 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8222 file, rather than its simple file name.
8223
8224 @item ^-i^/IN_PLACE^
8225 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8226 In normal mode, @code{gnatmake} compiles all object files and ALI files
8227 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8228 then instead object files and ALI files that already exist are overwritten
8229 in place. This means that once a large project is organized into separate
8230 directories in the desired manner, then @code{gnatmake} will automatically
8231 maintain and update this organization. If no ALI files are found on the
8232 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8233 the new object and ALI files are created in the
8234 directory containing the source being compiled. If another organization
8235 is desired, where objects and sources are kept in different directories,
8236 a useful technique is to create dummy ALI files in the desired directories.
8237 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8238 the corresponding source file, and it will be put the resulting object
8239 and ALI files in the directory where it found the dummy file.
8240
8241 @item ^-j^/PROCESSES=^@var{n}
8242 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8243 @cindex Parallel make
8244 Use @var{n} processes to carry out the (re)compilations. On a
8245 multiprocessor machine compilations will occur in parallel. In the
8246 event of compilation errors, messages from various compilations might
8247 get interspersed (but @code{gnatmake} will give you the full ordered
8248 list of failing compiles at the end). If this is problematic, rerun
8249 the make process with n set to 1 to get a clean list of messages.
8250
8251 @item ^-k^/CONTINUE_ON_ERROR^
8252 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8253 Keep going. Continue as much as possible after a compilation error. To
8254 ease the programmer's task in case of compilation errors, the list of
8255 sources for which the compile fails is given when @code{gnatmake}
8256 terminates.
8257
8258 If @code{gnatmake} is invoked with several @file{file_names} and with this
8259 switch, if there are compilation errors when building an executable,
8260 @code{gnatmake} will not attempt to build the following executables.
8261
8262 @item ^-l^/ACTIONS=LINK^
8263 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8264 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8265 and linking. Linking will not be performed if combined with
8266 @option{^-c^/ACTIONS=COMPILE^}
8267 but not with @option{^-b^/ACTIONS=BIND^}.
8268 When not combined with @option{^-b^/ACTIONS=BIND^}
8269 all the units in the closure of the main program must have been previously
8270 compiled and must be up to date, and the main program need to have been bound.
8271 The root unit specified by @var{file_name}
8272 may be given without extension, with the source extension or, if no GNAT
8273 Project File is specified, with the ALI file extension.
8274
8275 @item ^-m^/MINIMAL_RECOMPILATION^
8276 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8277 Specifies that the minimum necessary amount of recompilations
8278 be performed. In this mode @code{gnatmake} ignores time
8279 stamp differences when the only
8280 modifications to a source file consist in adding/removing comments,
8281 empty lines, spaces or tabs. This means that if you have changed the
8282 comments in a source file or have simply reformatted it, using this
8283 switch will tell gnatmake not to recompile files that depend on it
8284 (provided other sources on which these files depend have undergone no
8285 semantic modifications). Note that the debugging information may be
8286 out of date with respect to the sources if the @option{-m} switch causes
8287 a compilation to be switched, so the use of this switch represents a
8288 trade-off between compilation time and accurate debugging information.
8289
8290 @item ^-M^/DEPENDENCIES_LIST^
8291 @cindex Dependencies, producing list
8292 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8293 Check if all objects are up to date. If they are, output the object
8294 dependences to @file{stdout} in a form that can be directly exploited in
8295 a @file{Makefile}. By default, each source file is prefixed with its
8296 (relative or absolute) directory name. This name is whatever you
8297 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8298 and @option{^-I^/SEARCH^} switches. If you use
8299 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8300 @option{^-q^/QUIET^}
8301 (see below), only the source file names,
8302 without relative paths, are output. If you just specify the
8303 @option{^-M^/DEPENDENCIES_LIST^}
8304 switch, dependencies of the GNAT internal system files are omitted. This
8305 is typically what you want. If you also specify
8306 the @option{^-a^/ALL_FILES^} switch,
8307 dependencies of the GNAT internal files are also listed. Note that
8308 dependencies of the objects in external Ada libraries (see switch
8309 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8310 are never reported.
8311
8312 @item ^-n^/DO_OBJECT_CHECK^
8313 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8314 Don't compile, bind, or link. Checks if all objects are up to date.
8315 If they are not, the full name of the first file that needs to be
8316 recompiled is printed.
8317 Repeated use of this option, followed by compiling the indicated source
8318 file, will eventually result in recompiling all required units.
8319
8320 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8321 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8322 Output executable name. The name of the final executable program will be
8323 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8324 name for the executable will be the name of the input file in appropriate form
8325 for an executable file on the host system.
8326
8327 This switch cannot be used when invoking @code{gnatmake} with several
8328 @file{file_names}.
8329
8330 @item ^-P^/PROJECT_FILE=^@var{project}
8331 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8332 Use project file @var{project}. Only one such switch can be used.
8333 See @ref{gnatmake and Project Files}.
8334
8335 @item ^-q^/QUIET^
8336 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8337 Quiet. When this flag is not set, the commands carried out by
8338 @code{gnatmake} are displayed.
8339
8340 @item ^-s^/SWITCH_CHECK/^
8341 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8342 Recompile if compiler switches have changed since last compilation.
8343 All compiler switches but -I and -o are taken into account in the
8344 following way:
8345 orders between different ``first letter'' switches are ignored, but
8346 orders between same switches are taken into account. For example,
8347 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8348 is equivalent to @option{-O -g}.
8349
8350 This switch is recommended when Integrated Preprocessing is used.
8351
8352 @item ^-u^/UNIQUE^
8353 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8354 Unique. Recompile at most the main files. It implies -c. Combined with
8355 -f, it is equivalent to calling the compiler directly. Note that using
8356 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8357 (see @ref{Project Files and Main Subprograms}).
8358
8359 @item ^-U^/ALL_PROJECTS^
8360 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8361 When used without a project file or with one or several mains on the command
8362 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8363 on the command line, all sources of all project files are checked and compiled
8364 if not up to date, and libraries are rebuilt, if necessary.
8365
8366 @item ^-v^/REASONS^
8367 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8368 Verbose. Displays the reason for all recompilations @code{gnatmake}
8369 decides are necessary.
8370
8371 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8372 Indicates the verbosity of the parsing of GNAT project files.
8373 See @ref{Switches Related to Project Files}.
8374
8375 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8376 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8377 Indicates that sources that are not part of any Project File may be compiled.
8378 Normally, when using Project Files, only sources that are part of a Project
8379 File may be compile. When this switch is used, a source outside of all Project
8380 Files may be compiled. The ALI file and the object file will be put in the
8381 object directory of the main Project. The compilation switches used will only
8382 be those specified on the command line.
8383
8384 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8385 Indicates that external variable @var{name} has the value @var{value}.
8386 The Project Manager will use this value for occurrences of
8387 @code{external(name)} when parsing the project file.
8388 See @ref{Switches Related to Project Files}.
8389
8390 @item ^-z^/NOMAIN^
8391 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8392 No main subprogram. Bind and link the program even if the unit name
8393 given on the command line is a package name. The resulting executable
8394 will execute the elaboration routines of the package and its closure,
8395 then the finalization routines.
8396
8397 @item ^-g^/DEBUG^
8398 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8399 Enable debugging. This switch is simply passed to the compiler and to the
8400 linker.
8401
8402 @end table
8403
8404 @table @asis
8405 @item @code{gcc} @asis{switches}
8406 @ifclear vms
8407 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8408 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8409 @end ifclear
8410 @ifset vms
8411 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8412 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8413 automatically treated as a compiler switch, and passed on to all
8414 compilations that are carried out.
8415 @end ifset
8416 @end table
8417
8418 @noindent
8419 Source and library search path switches:
8420
8421 @table @option
8422 @c !sort!
8423 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8424 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8425 When looking for source files also look in directory @var{dir}.
8426 The order in which source files search is undertaken is
8427 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8428
8429 @item ^-aL^/SKIP_MISSING=^@var{dir}
8430 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8431 Consider @var{dir} as being an externally provided Ada library.
8432 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8433 files have been located in directory @var{dir}. This allows you to have
8434 missing bodies for the units in @var{dir} and to ignore out of date bodies
8435 for the same units. You still need to specify
8436 the location of the specs for these units by using the switches
8437 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8438 or @option{^-I^/SEARCH=^@var{dir}}.
8439 Note: this switch is provided for compatibility with previous versions
8440 of @code{gnatmake}. The easier method of causing standard libraries
8441 to be excluded from consideration is to write-protect the corresponding
8442 ALI files.
8443
8444 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8445 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8446 When searching for library and object files, look in directory
8447 @var{dir}. The order in which library files are searched is described in
8448 @ref{Search Paths for gnatbind}.
8449
8450 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8451 @cindex Search paths, for @code{gnatmake}
8452 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8453 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8454 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8455
8456 @item ^-I^/SEARCH=^@var{dir}
8457 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8458 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8459 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8460
8461 @item ^-I-^/NOCURRENT_DIRECTORY^
8462 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8463 @cindex Source files, suppressing search
8464 Do not look for source files in the directory containing the source
8465 file named in the command line.
8466 Do not look for ALI or object files in the directory
8467 where @code{gnatmake} was invoked.
8468
8469 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8470 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8471 @cindex Linker libraries
8472 Add directory @var{dir} to the list of directories in which the linker
8473 will search for libraries. This is equivalent to
8474 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8475 @ifclear vms
8476 Furthermore, under Windows, the sources pointed to by the libraries path
8477 set in the registry are not searched for.
8478 @end ifclear
8479
8480 @item -nostdinc
8481 @cindex @option{-nostdinc} (@code{gnatmake})
8482 Do not look for source files in the system default directory.
8483
8484 @item -nostdlib
8485 @cindex @option{-nostdlib} (@code{gnatmake})
8486 Do not look for library files in the system default directory.
8487
8488 @item --RTS=@var{rts-path}
8489 @cindex @option{--RTS} (@code{gnatmake})
8490 Specifies the default location of the runtime library. GNAT looks for the
8491 runtime
8492 in the following directories, and stops as soon as a valid runtime is found
8493 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8494 @file{ada_object_path} present):
8495
8496 @itemize @bullet
8497 @item <current directory>/$rts_path
8498
8499 @item <default-search-dir>/$rts_path
8500
8501 @item <default-search-dir>/rts-$rts_path
8502 @end itemize
8503
8504 @noindent
8505 The selected path is handled like a normal RTS path.
8506
8507 @end table
8508
8509 @node Mode Switches for gnatmake
8510 @section Mode Switches for @code{gnatmake}
8511
8512 @noindent
8513 The mode switches (referred to as @code{mode_switches}) allow the
8514 inclusion of switches that are to be passed to the compiler itself, the
8515 binder or the linker. The effect of a mode switch is to cause all
8516 subsequent switches up to the end of the switch list, or up to the next
8517 mode switch, to be interpreted as switches to be passed on to the
8518 designated component of GNAT.
8519
8520 @table @option
8521 @c !sort!
8522 @item -cargs @var{switches}
8523 @cindex @option{-cargs} (@code{gnatmake})
8524 Compiler switches. Here @var{switches} is a list of switches
8525 that are valid switches for @code{gcc}. They will be passed on to
8526 all compile steps performed by @code{gnatmake}.
8527
8528 @item -bargs @var{switches}
8529 @cindex @option{-bargs} (@code{gnatmake})
8530 Binder switches. Here @var{switches} is a list of switches
8531 that are valid switches for @code{gnatbind}. They will be passed on to
8532 all bind steps performed by @code{gnatmake}.
8533
8534 @item -largs @var{switches}
8535 @cindex @option{-largs} (@code{gnatmake})
8536 Linker switches. Here @var{switches} is a list of switches
8537 that are valid switches for @code{gnatlink}. They will be passed on to
8538 all link steps performed by @code{gnatmake}.
8539
8540 @item -margs @var{switches}
8541 @cindex @option{-margs} (@code{gnatmake})
8542 Make switches. The switches are directly interpreted by @code{gnatmake},
8543 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8544 or @option{-largs}.
8545 @end table
8546
8547 @node Notes on the Command Line
8548 @section Notes on the Command Line
8549
8550 @noindent
8551 This section contains some additional useful notes on the operation
8552 of the @code{gnatmake} command.
8553
8554 @itemize @bullet
8555 @item
8556 @cindex Recompilation, by @code{gnatmake}
8557 If @code{gnatmake} finds no ALI files, it recompiles the main program
8558 and all other units required by the main program.
8559 This means that @code{gnatmake}
8560 can be used for the initial compile, as well as during subsequent steps of
8561 the development cycle.
8562
8563 @item
8564 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8565 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8566 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8567 warning.
8568
8569 @item
8570 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8571 is used to specify both source and
8572 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8573 instead if you just want to specify
8574 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8575 if you want to specify library paths
8576 only.
8577
8578 @item
8579 @code{gnatmake} examines both an ALI file and its corresponding object file
8580 for consistency. If an ALI is more recent than its corresponding object,
8581 or if the object file is missing, the corresponding source will be recompiled.
8582 Note that @code{gnatmake} expects an ALI and the corresponding object file
8583 to be in the same directory.
8584
8585 @item
8586 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8587 This may conveniently be used to exclude standard libraries from
8588 consideration and in particular it means that the use of the
8589 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8590 unless @option{^-a^/ALL_FILES^} is also specified.
8591
8592 @item
8593 @code{gnatmake} has been designed to make the use of Ada libraries
8594 particularly convenient. Assume you have an Ada library organized
8595 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8596 of your Ada compilation units,
8597 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8598 specs of these units, but no bodies. Then to compile a unit
8599 stored in @code{main.adb}, which uses this Ada library you would just type
8600
8601 @smallexample
8602 @ifclear vms
8603 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8604 @end ifclear
8605 @ifset vms
8606 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8607            /SKIP_MISSING=@i{[OBJ_DIR]} main
8608 @end ifset
8609 @end smallexample
8610
8611 @item
8612 Using @code{gnatmake} along with the
8613 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8614 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8615 this switch,
8616 you can update the comments/format of your
8617 source files without having to recompile everything. Note, however, that
8618 adding or deleting lines in a source files may render its debugging
8619 info obsolete. If the file in question is a spec, the impact is rather
8620 limited, as that debugging info will only be useful during the
8621 elaboration phase of your program. For bodies the impact can be more
8622 significant. In all events, your debugger will warn you if a source file
8623 is more recent than the corresponding object, and alert you to the fact
8624 that the debugging information may be out of date.
8625 @end itemize
8626
8627 @node How gnatmake Works
8628 @section How @code{gnatmake} Works
8629
8630 @noindent
8631 Generally @code{gnatmake} automatically performs all necessary
8632 recompilations and you don't need to worry about how it works. However,
8633 it may be useful to have some basic understanding of the @code{gnatmake}
8634 approach and in particular to understand how it uses the results of
8635 previous compilations without incorrectly depending on them.
8636
8637 First a definition: an object file is considered @dfn{up to date} if the
8638 corresponding ALI file exists and its time stamp predates that of the
8639 object file and if all the source files listed in the
8640 dependency section of this ALI file have time stamps matching those in
8641 the ALI file. This means that neither the source file itself nor any
8642 files that it depends on have been modified, and hence there is no need
8643 to recompile this file.
8644
8645 @code{gnatmake} works by first checking if the specified main unit is up
8646 to date. If so, no compilations are required for the main unit. If not,
8647 @code{gnatmake} compiles the main program to build a new ALI file that
8648 reflects the latest sources. Then the ALI file of the main unit is
8649 examined to find all the source files on which the main program depends,
8650 and @code{gnatmake} recursively applies the above procedure on all these files.
8651
8652 This process ensures that @code{gnatmake} only trusts the dependencies
8653 in an existing ALI file if they are known to be correct. Otherwise it
8654 always recompiles to determine a new, guaranteed accurate set of
8655 dependencies. As a result the program is compiled ``upside down'' from what may
8656 be more familiar as the required order of compilation in some other Ada
8657 systems. In particular, clients are compiled before the units on which
8658 they depend. The ability of GNAT to compile in any order is critical in
8659 allowing an order of compilation to be chosen that guarantees that
8660 @code{gnatmake} will recompute a correct set of new dependencies if
8661 necessary.
8662
8663 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8664 imported by several of the executables, it will be recompiled at most once.
8665
8666 Note: when using non-standard naming conventions
8667 (See @ref{Using Other File Names}), changing through a configuration pragmas
8668 file the version of a source and invoking @code{gnatmake} to recompile may
8669 have no effect, if the previous version of the source is still accessible
8670 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8671
8672 @node Examples of gnatmake Usage
8673 @section Examples of @code{gnatmake} Usage
8674
8675 @table @code
8676 @item gnatmake hello.adb
8677 Compile all files necessary to bind and link the main program
8678 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8679 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8680
8681 @item gnatmake main1 main2 main3
8682 Compile all files necessary to bind and link the main programs
8683 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8684 (containing unit @code{Main2}) and @file{main3.adb}
8685 (containing unit @code{Main3}) and bind and link the resulting object files
8686 to generate three executable files @file{^main1^MAIN1.EXE^},
8687 @file{^main2^MAIN2.EXE^}
8688 and @file{^main3^MAIN3.EXE^}.
8689
8690 @ifclear vms
8691 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8692 @end ifclear
8693
8694 @ifset vms
8695 @item gnatmake Main_Unit /QUIET
8696    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8697    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8698 @end ifset
8699 Compile all files necessary to bind and link the main program unit
8700 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8701 be done with optimization level 2 and the order of elaboration will be
8702 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8703 displaying commands it is executing.
8704 @end table
8705
8706
8707 @c *************************
8708 @node Improving Performance
8709 @chapter Improving Performance
8710 @cindex Improving performance
8711
8712 @noindent
8713 This chapter presents several topics related to program performance.
8714 It first describes some of the tradeoffs that need to be considered
8715 and some of the techniques for making your program run faster.
8716 It then documents the @command{gnatelim} tool, which can reduce
8717 the size of program executables.
8718
8719 @ifnottex
8720 @menu
8721 * Performance Considerations::
8722 * Reducing the Size of Ada Executables with gnatelim::
8723 @end menu
8724 @end ifnottex
8725
8726
8727 @c *****************************
8728 @node Performance Considerations
8729 @section Performance Considerations
8730
8731 @noindent
8732 The GNAT system provides a number of options that allow a trade-off
8733 between
8734
8735 @itemize @bullet
8736 @item
8737 performance of the generated code
8738
8739 @item
8740 speed of compilation
8741
8742 @item
8743 minimization of dependences and recompilation
8744
8745 @item
8746 the degree of run-time checking.
8747 @end itemize
8748
8749 @noindent
8750 The defaults (if no options are selected) aim at improving the speed
8751 of compilation and minimizing dependences, at the expense of performance
8752 of the generated code:
8753
8754 @itemize @bullet
8755 @item
8756 no optimization
8757
8758 @item
8759 no inlining of subprogram calls
8760
8761 @item
8762 all run-time checks enabled except overflow and elaboration checks
8763 @end itemize
8764
8765 @noindent
8766 These options are suitable for most program development purposes. This
8767 chapter describes how you can modify these choices, and also provides
8768 some guidelines on debugging optimized code.
8769
8770 @menu
8771 * Controlling Run-Time Checks::
8772 * Use of Restrictions::
8773 * Optimization Levels::
8774 * Debugging Optimized Code::
8775 * Inlining of Subprograms::
8776 * Optimization and Strict Aliasing::
8777 @ifset vms
8778 * Coverage Analysis::
8779 @end ifset
8780 @end menu
8781
8782 @node Controlling Run-Time Checks
8783 @subsection Controlling Run-Time Checks
8784
8785 @noindent
8786 By default, GNAT generates all run-time checks, except arithmetic overflow
8787 checking for integer operations and checks for access before elaboration on
8788 subprogram calls. The latter are not required in default mode, because all
8789 necessary checking is done at compile time.
8790 @cindex @option{-gnatp} (@code{gcc})
8791 @cindex @option{-gnato} (@code{gcc})
8792 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8793 be modified. @xref{Run-Time Checks}.
8794
8795 Our experience is that the default is suitable for most development
8796 purposes.
8797
8798 We treat integer overflow specially because these
8799 are quite expensive and in our experience are not as important as other
8800 run-time checks in the development process. Note that division by zero
8801 is not considered an overflow check, and divide by zero checks are
8802 generated where required by default.
8803
8804 Elaboration checks are off by default, and also not needed by default, since
8805 GNAT uses a static elaboration analysis approach that avoids the need for
8806 run-time checking. This manual contains a full chapter discussing the issue
8807 of elaboration checks, and if the default is not satisfactory for your use,
8808 you should read this chapter.
8809
8810 For validity checks, the minimal checks required by the Ada Reference
8811 Manual (for case statements and assignments to array elements) are on
8812 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8813 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8814 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8815 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8816 are also suppressed entirely if @option{-gnatp} is used.
8817
8818 @cindex Overflow checks
8819 @cindex Checks, overflow
8820 @findex Suppress
8821 @findex Unsuppress
8822 @cindex pragma Suppress
8823 @cindex pragma Unsuppress
8824 Note that the setting of the switches controls the default setting of
8825 the checks. They may be modified using either @code{pragma Suppress} (to
8826 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8827 checks) in the program source.
8828
8829 @node Use of Restrictions
8830 @subsection Use of Restrictions
8831
8832 @noindent
8833 The use of pragma Restrictions allows you to control which features are
8834 permitted in your program. Apart from the obvious point that if you avoid
8835 relatively expensive features like finalization (enforceable by the use
8836 of pragma Restrictions (No_Finalization), the use of this pragma does not
8837 affect the generated code in most cases.
8838
8839 One notable exception to this rule is that the possibility of task abort
8840 results in some distributed overhead, particularly if finalization or
8841 exception handlers are used. The reason is that certain sections of code
8842 have to be marked as non-abortable.
8843
8844 If you use neither the @code{abort} statement, nor asynchronous transfer
8845 of control (@code{select .. then abort}), then this distributed overhead
8846 is removed, which may have a general positive effect in improving
8847 overall performance.  Especially code involving frequent use of tasking
8848 constructs and controlled types will show much improved performance.
8849 The relevant restrictions pragmas are
8850
8851 @smallexample
8852    pragma Restrictions (No_Abort_Statements);
8853    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8854 @end smallexample
8855
8856 @noindent
8857 It is recommended that these restriction pragmas be used if possible. Note
8858 that this also means that you can write code without worrying about the
8859 possibility of an immediate abort at any point.
8860
8861 @node Optimization Levels
8862 @subsection Optimization Levels
8863 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8864
8865 @noindent
8866 The default is optimization off. This results in the fastest compile
8867 times, but GNAT makes absolutely no attempt to optimize, and the
8868 generated programs are considerably larger and slower than when
8869 optimization is enabled. You can use the
8870 @ifclear vms
8871 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8872 @end ifclear
8873 @ifset vms
8874 @code{OPTIMIZE} qualifier
8875 @end ifset
8876 to @code{gcc} to control the optimization level:
8877
8878 @table @option
8879 @item ^-O0^/OPTIMIZE=NONE^
8880 No optimization (the default);
8881 generates unoptimized code but has
8882 the fastest compilation time.
8883
8884 @item ^-O1^/OPTIMIZE=SOME^
8885 Medium level optimization;
8886 optimizes reasonably well but does not
8887 degrade compilation time significantly.
8888
8889 @item ^-O2^/OPTIMIZE=ALL^
8890 @ifset vms
8891 @itemx /OPTIMIZE=DEVELOPMENT
8892 @end ifset
8893 Full optimization;
8894 generates highly optimized code and has
8895 the slowest compilation time.
8896
8897 @item ^-O3^/OPTIMIZE=INLINING^
8898 Full optimization as in @option{-O2},
8899 and also attempts automatic inlining of small
8900 subprograms within a unit (@pxref{Inlining of Subprograms}).
8901 @end table
8902
8903 @noindent
8904 Higher optimization levels perform more global transformations on the
8905 program and apply more expensive analysis algorithms in order to generate
8906 faster and more compact code. The price in compilation time, and the
8907 resulting improvement in execution time,
8908 both depend on the particular application and the hardware environment.
8909 You should experiment to find the best level for your application.
8910
8911 Since the precise set of optimizations done at each level will vary from
8912 release to release (and sometime from target to target), it is best to think
8913 of the optimization settings in general terms.
8914 The @cite{Using GNU GCC} manual contains details about
8915 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8916 individually enable or disable specific optimizations.
8917
8918 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8919 been tested extensively at all optimization levels. There are some bugs
8920 which appear only with optimization turned on, but there have also been
8921 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8922 level of optimization does not improve the reliability of the code
8923 generator, which in practice is highly reliable at all optimization
8924 levels.
8925
8926 Note regarding the use of @option{-O3}: The use of this optimization level
8927 is generally discouraged with GNAT, since it often results in larger
8928 executables which run more slowly. See further discussion of this point
8929 in @pxref{Inlining of Subprograms}.
8930
8931
8932 @node Debugging Optimized Code
8933 @subsection Debugging Optimized Code
8934 @cindex Debugging optimized code
8935 @cindex Optimization and debugging
8936
8937 @noindent
8938 Although it is possible to do a reasonable amount of debugging at
8939 @ifclear vms
8940 non-zero optimization levels,
8941 the higher the level the more likely that
8942 @end ifclear
8943 @ifset vms
8944 @option{/OPTIMIZE} settings other than @code{NONE},
8945 such settings will make it more likely that
8946 @end ifset
8947 source-level constructs will have been eliminated by optimization.
8948 For example, if a loop is strength-reduced, the loop
8949 control variable may be completely eliminated and thus cannot be
8950 displayed in the debugger.
8951 This can only happen at @option{-O2} or @option{-O3}.
8952 Explicit temporary variables that you code might be eliminated at
8953 ^level^setting^ @option{-O1} or higher.
8954
8955 The use of the @option{^-g^/DEBUG^} switch,
8956 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8957 which is needed for source-level debugging,
8958 affects the size of the program executable on disk,
8959 and indeed the debugging information can be quite large.
8960 However, it has no effect on the generated code (and thus does not
8961 degrade performance)
8962
8963 Since the compiler generates debugging tables for a compilation unit before
8964 it performs optimizations, the optimizing transformations may invalidate some
8965 of the debugging data.  You therefore need to anticipate certain
8966 anomalous situations that may arise while debugging optimized code.
8967 These are the most common cases:
8968
8969 @enumerate
8970 @item
8971 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8972 commands show
8973 the PC bouncing back and forth in the code.  This may result from any of
8974 the following optimizations:
8975
8976 @itemize @bullet
8977 @item
8978 @i{Common subexpression elimination:} using a single instance of code for a
8979 quantity that the source computes several times.  As a result you
8980 may not be able to stop on what looks like a statement.
8981
8982 @item
8983 @i{Invariant code motion:} moving an expression that does not change within a
8984 loop, to the beginning of the loop.
8985
8986 @item
8987 @i{Instruction scheduling:} moving instructions so as to
8988 overlap loads and stores (typically) with other code, or in
8989 general to move computations of values closer to their uses. Often
8990 this causes you to pass an assignment statement without the assignment
8991 happening and then later bounce back to the statement when the
8992 value is actually needed.  Placing a breakpoint on a line of code
8993 and then stepping over it may, therefore, not always cause all the
8994 expected side-effects.
8995 @end itemize
8996
8997 @item
8998 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8999 two identical pieces of code are merged and the program counter suddenly
9000 jumps to a statement that is not supposed to be executed, simply because
9001 it (and the code following) translates to the same thing as the code
9002 that @emph{was} supposed to be executed.  This effect is typically seen in
9003 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9004 a @code{break} in a C @code{^switch^switch^} statement.
9005
9006 @item
9007 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9008 There are various reasons for this effect:
9009
9010 @itemize @bullet
9011 @item
9012 In a subprogram prologue, a parameter may not yet have been moved to its
9013 ``home''.
9014
9015 @item
9016 A variable may be dead, and its register re-used.  This is
9017 probably the most common cause.
9018
9019 @item
9020 As mentioned above, the assignment of a value to a variable may
9021 have been moved.
9022
9023 @item
9024 A variable may be eliminated entirely by value propagation or
9025 other means.  In this case, GCC may incorrectly generate debugging
9026 information for the variable
9027 @end itemize
9028
9029 @noindent
9030 In general, when an unexpected value appears for a local variable or parameter
9031 you should first ascertain if that value was actually computed by
9032 your program, as opposed to being incorrectly reported by the debugger.
9033 Record fields or
9034 array elements in an object designated by an access value
9035 are generally less of a problem, once you have ascertained that the access
9036 value is sensible.
9037 Typically, this means checking variables in the preceding code and in the
9038 calling subprogram to verify that the value observed is explainable from other
9039 values (one must apply the procedure recursively to those
9040 other values); or re-running the code and stopping a little earlier
9041 (perhaps before the call) and stepping to better see how the variable obtained
9042 the value in question; or continuing to step @emph{from} the point of the
9043 strange value to see if code motion had simply moved the variable's
9044 assignments later.
9045 @end enumerate
9046
9047 @noindent
9048 In light of such anomalies, a recommended technique is to use @option{-O0}
9049 early in the software development cycle, when extensive debugging capabilities
9050 are most needed, and then move to @option{-O1} and later @option{-O2} as
9051 the debugger becomes less critical.
9052 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9053 a release management issue.
9054 @ifclear vms
9055 Note that if you use @option{-g} you can then use the @command{strip} program
9056 on the resulting executable,
9057 which removes both debugging information and global symbols.
9058 @end ifclear
9059
9060
9061 @node Inlining of Subprograms
9062 @subsection Inlining of Subprograms
9063
9064 @noindent
9065 A call to a subprogram in the current unit is inlined if all the
9066 following conditions are met:
9067
9068 @itemize @bullet
9069 @item
9070 The optimization level is at least @option{-O1}.
9071
9072 @item
9073 The called subprogram is suitable for inlining: It must be small enough
9074 and not contain nested subprograms or anything else that @code{gcc}
9075 cannot support in inlined subprograms.
9076
9077 @item
9078 The call occurs after the definition of the body of the subprogram.
9079
9080 @item
9081 @cindex pragma Inline
9082 @findex Inline
9083 Either @code{pragma Inline} applies to the subprogram or it is
9084 small and automatic inlining (optimization level @option{-O3}) is
9085 specified.
9086 @end itemize
9087
9088 @noindent
9089 Calls to subprograms in @code{with}'ed units are normally not inlined.
9090 To achieve this level of inlining, the following conditions must all be
9091 true:
9092
9093 @itemize @bullet
9094 @item
9095 The optimization level is at least @option{-O1}.
9096
9097 @item
9098 The called subprogram is suitable for inlining: It must be small enough
9099 and not contain nested subprograms or anything else @code{gcc} cannot
9100 support in inlined subprograms.
9101
9102 @item
9103 The call appears in a body (not in a package spec).
9104
9105 @item
9106 There is a @code{pragma Inline} for the subprogram.
9107
9108 @item
9109 @cindex @option{-gnatn} (@code{gcc})
9110 The @option{^-gnatn^/INLINE^} switch
9111 is used in the @code{gcc} command line
9112 @end itemize
9113
9114 Note that specifying the @option{-gnatn} switch causes additional
9115 compilation dependencies. Consider the following:
9116
9117 @smallexample @c ada
9118 @cartouche
9119 package R is
9120    procedure Q;
9121    pragma Inline (Q);
9122 end R;
9123 package body R is
9124    ...
9125 end R;
9126
9127 with R;
9128 procedure Main is
9129 begin
9130    ...
9131    R.Q;
9132 end Main;
9133 @end cartouche
9134 @end smallexample
9135
9136 @noindent
9137 With the default behavior (no @option{-gnatn} switch specified), the
9138 compilation of the @code{Main} procedure depends only on its own source,
9139 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9140 means that editing the body of @code{R} does not require recompiling
9141 @code{Main}.
9142
9143 On the other hand, the call @code{R.Q} is not inlined under these
9144 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9145 is compiled, the call will be inlined if the body of @code{Q} is small
9146 enough, but now @code{Main} depends on the body of @code{R} in
9147 @file{r.adb} as well as on the spec. This means that if this body is edited,
9148 the main program must be recompiled. Note that this extra dependency
9149 occurs whether or not the call is in fact inlined by @code{gcc}.
9150
9151 The use of front end inlining with @option{-gnatN} generates similar
9152 additional dependencies.
9153
9154 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9155 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9156 can be used to prevent
9157 all inlining. This switch overrides all other conditions and ensures
9158 that no inlining occurs. The extra dependences resulting from
9159 @option{-gnatn} will still be active, even if
9160 this switch is used to suppress the resulting inlining actions.
9161
9162 Note regarding the use of @option{-O3}: There is no difference in inlining
9163 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9164 pragma @code{Inline} assuming the use of @option{-gnatn}
9165 or @option{-gnatN} (the switches that activate inlining). If you have used
9166 pragma @code{Inline} in appropriate cases, then it is usually much better
9167 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9168 in this case only has the effect of inlining subprograms you did not
9169 think should be inlined. We often find that the use of @option{-O3} slows
9170 down code by performing excessive inlining, leading to increased instruction
9171 cache pressure from the increased code size. So the bottom line here is
9172 that you should not automatically assume that @option{-O3} is better than
9173 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9174 it actually improves performance.
9175
9176 @node Optimization and Strict Aliasing
9177 @subsection Optimization and Strict Aliasing
9178 @cindex Aliasing
9179 @cindex Strict Aliasing
9180 @cindex No_Strict_Aliasing
9181
9182 @noindent
9183 The strong typing capabilities of Ada allow an optimizer to generate
9184 efficient code in situations where other languages would be forced to
9185 make worst case assumptions preventing such optimizations. Consider
9186 the following example:
9187
9188 @smallexample @c ada
9189 @cartouche
9190 procedure R is
9191    type Int1 is new Integer;
9192    type Int2 is new Integer;
9193    type Int1A is access Int1;
9194    type Int2A is access Int2;
9195    Int1V : Int1A;
9196    Int2V : Int2A;
9197    ...
9198
9199 begin
9200    ...
9201    for J in Data'Range loop
9202       if Data (J) = Int1V.all then
9203          Int2V.all := Int2V.all + 1;
9204       end if;
9205    end loop;
9206    ...
9207 end R;
9208 @end cartouche
9209 @end smallexample
9210
9211 @noindent
9212 In this example, since the variable @code{Int1V} can only access objects
9213 of type @code{Int1}, and @code{Int2V} can only access objects of type
9214 @code{Int2}, there is no possibility that the assignment to
9215 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9216 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9217 for all iterations of the loop and avoid the extra memory reference
9218 required to dereference it each time through the loop.
9219
9220 This kind of optimziation, called strict aliasing analysis, is
9221 triggered by specifying an optimization level of @option{-O2} or
9222 higher and allows @code{GNAT} to generate more efficient code
9223 when access values are involved.
9224
9225 However, although this optimization is always correct in terms of
9226 the formal semantics of the Ada Reference Manual, difficulties can
9227 arise if features like @code{Unchecked_Conversion} are used to break
9228 the typing system. Consider the following complete program example:
9229
9230 @smallexample @c ada
9231 @cartouche
9232 package p1 is
9233    type int1 is new integer;
9234    type int2 is new integer;
9235    type a1 is access int1;
9236    type a2 is access int2;
9237 end p1;
9238
9239 with p1; use p1;
9240 package p2 is
9241    function to_a2 (Input : a1) return a2;
9242 end p2;
9243
9244 with Unchecked_Conversion;
9245 package body p2 is
9246    function to_a2 (Input : a1) return a2 is
9247       function to_a2u is
9248         new Unchecked_Conversion (a1, a2);
9249    begin
9250       return to_a2u (Input);
9251    end to_a2;
9252 end p2;
9253
9254 with p2; use p2;
9255 with p1; use p1;
9256 with Text_IO; use Text_IO;
9257 procedure m is
9258    v1 : a1 := new int1;
9259    v2 : a2 := to_a2 (v1);
9260 begin
9261    v1.all := 1;
9262    v2.all := 0;
9263    put_line (int1'image (v1.all));
9264 end;
9265 @end cartouche
9266 @end smallexample
9267
9268 @noindent
9269 This program prints out 0 in @code{-O0} or @code{-O1}
9270 mode, but it prints out 1 in @code{-O2} mode. That's
9271 because in strict aliasing mode, the compiler can and
9272 does assume that the assignment to @code{v2.all} could not
9273 affect the value of @code{v1.all}, since different types
9274 are involved.
9275
9276 This behavior is not a case of non-conformance with the standard, since
9277 the Ada RM specifies that an unchecked conversion where the resulting
9278 bit pattern is not a correct value of the target type can result in an
9279 abnormal value and attempting to reference an abnormal value makes the
9280 execution of a program erroneous.  That's the case here since the result
9281 does not point to an object of type @code{int2}.  This means that the
9282 effect is entirely unpredictable.
9283
9284 However, although that explanation may satisfy a language
9285 lawyer, in practice an applications programmer expects an
9286 unchecked conversion involving pointers to create true
9287 aliases and the behavior of printing 1 seems plain wrong.
9288 In this case, the strict aliasing optimization is unwelcome.
9289
9290 Indeed the compiler recognizes this possibility, and the
9291 unchecked conversion generates a warning:
9292
9293 @smallexample
9294 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9295 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9296 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9297 @end smallexample
9298
9299 @noindent
9300 Unfortunately the problem is recognized when compiling the body of
9301 package @code{p2}, but the actual "bad" code is generated while
9302 compiling the body of @code{m} and this latter compilation does not see
9303 the suspicious @code{Unchecked_Conversion}.
9304
9305 As implied by the warning message, there are approaches you can use to
9306 avoid the unwanted strict aliasing optimization in a case like this.
9307
9308 One possibility is to simply avoid the use of @code{-O2}, but
9309 that is a bit drastic, since it throws away a number of useful
9310 optimizations that do not involve strict aliasing assumptions.
9311
9312 A less drastic approach is to compile the program using the
9313 option @code{-fno-strict-aliasing}. Actually it is only the
9314 unit containing the dereferencing of the suspicious pointer
9315 that needs to be compiled. So in this case, if we compile
9316 unit @code{m} with this switch, then we get the expected
9317 value of zero printed. Analyzing which units might need
9318 the switch can be painful, so a more reasonable approach
9319 is to compile the entire program with options @code{-O2}
9320 and @code{-fno-strict-aliasing}. If the performance is
9321 satisfactory with this combination of options, then the
9322 advantage is that the entire issue of possible "wrong"
9323 optimization due to strict aliasing is avoided.
9324
9325 To avoid the use of compiler switches, the configuration
9326 pragma @code{No_Strict_Aliasing} with no parameters may be
9327 used to specify that for all access types, the strict
9328 aliasing optimization should be suppressed.
9329
9330 However, these approaches are still overkill, in that they causes
9331 all manipulations of all access values to be deoptimized. A more
9332 refined approach is to concentrate attention on the specific
9333 access type identified as problematic.
9334
9335 First, if a careful analysis of uses of the pointer shows
9336 that there are no possible problematic references, then
9337 the warning can be suppressed by bracketing the
9338 instantiation of @code{Unchecked_Conversion} to turn
9339 the warning off:
9340
9341 @smallexample @c ada
9342    pragma Warnings (Off);
9343    function to_a2u is
9344      new Unchecked_Conversion (a1, a2);
9345    pragma Warnings (On);
9346 @end smallexample
9347
9348 @noindent
9349 Of course that approach is not appropriate for this particular
9350 example, since indeed there is a problematic reference. In this
9351 case we can take one of two other approaches.
9352
9353 The first possibility is to move the instantiation of unchecked
9354 conversion to the unit in which the type is declared. In
9355 this example, we would move the instantiation of
9356 @code{Unchecked_Conversion} from the body of package
9357 @code{p2} to the spec of package @code{p1}. Now the
9358 warning disappears. That's because any use of the
9359 access type knows there is a suspicious unchecked
9360 conversion, and the strict aliasing optimization
9361 is automatically suppressed for the type.
9362
9363 If it is not practical to move the unchecked conversion to the same unit
9364 in which the destination access type is declared (perhaps because the
9365 source type is not visible in that unit), you may use pragma
9366 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9367 same declarative sequence as the declaration of the access type:
9368
9369 @smallexample @c ada
9370    type a2 is access int2;
9371    pragma No_Strict_Aliasing (a2);
9372 @end smallexample
9373
9374 @noindent
9375 Here again, the compiler now knows that the strict aliasing optimization
9376 should be suppressed for any reference to type @code{a2} and the
9377 expected behavior is obtained.
9378
9379 Finally, note that although the compiler can generate warnings for
9380 simple cases of unchecked conversions, there are tricker and more
9381 indirect ways of creating type incorrect aliases which the compiler
9382 cannot detect. Examples are the use of address overlays and unchecked
9383 conversions involving composite types containing access types as
9384 components. In such cases, no warnings are generated, but there can
9385 still be aliasing problems. One safe coding practice is to forbid the
9386 use of address clauses for type overlaying, and to allow unchecked
9387 conversion only for primitive types. This is not really a significant
9388 restriction since any possible desired effect can be achieved by
9389 unchecked conversion of access values.
9390
9391 @ifset vms
9392 @node Coverage Analysis
9393 @subsection Coverage Analysis
9394
9395 @noindent
9396 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9397 the user to determine the distribution of execution time across a program,
9398 @pxref{Profiling} for details of usage.
9399 @end ifset
9400
9401 @node Reducing the Size of Ada Executables with gnatelim
9402 @section Reducing the Size of Ada Executables with @code{gnatelim}
9403 @findex gnatelim
9404
9405 @noindent
9406 This section describes @command{gnatelim}, a tool which detects unused
9407 subprograms and helps the compiler to create a smaller executable for your
9408 program.
9409
9410 @menu
9411 * About gnatelim::
9412 * Running gnatelim::
9413 * Correcting the List of Eliminate Pragmas::
9414 * Making Your Executables Smaller::
9415 * Summary of the gnatelim Usage Cycle::
9416 @end menu
9417
9418 @node About gnatelim
9419 @subsection About @code{gnatelim}
9420
9421 @noindent
9422 When a program shares a set of Ada
9423 packages with other programs, it may happen that this program uses
9424 only a fraction of the subprograms defined in these packages. The code
9425 created for these unused subprograms increases the size of the executable.
9426
9427 @code{gnatelim} tracks unused subprograms in an Ada program and
9428 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9429 subprograms that are declared but never called. By placing the list of
9430 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9431 recompiling your program, you may decrease the size of its executable,
9432 because the compiler will not generate the code for 'eliminated' subprograms.
9433 See GNAT Reference Manual for more information about this pragma.
9434
9435 @code{gnatelim} needs as its input data the name of the main subprogram
9436 and a bind file for a main subprogram.
9437
9438 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9439 the main subprogram. @code{gnatelim} can work with both Ada and C
9440 bind files; when both are present, it uses the Ada bind file.
9441 The following commands will build the program and create the bind file:
9442
9443 @smallexample
9444 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9445 $ gnatbind main_prog
9446 @end smallexample
9447
9448 Note that @code{gnatelim} needs neither object nor ALI files.
9449
9450 @node Running gnatelim
9451 @subsection Running @code{gnatelim}
9452
9453 @noindent
9454 @code{gnatelim} has the following command-line interface:
9455
9456 @smallexample
9457 $ gnatelim [options] name
9458 @end smallexample
9459
9460 @noindent
9461 @code{name} should be a name of a source file that contains the main subprogram
9462 of a program (partition).
9463
9464 @code{gnatelim} has the following switches:
9465
9466 @table @option
9467 @c !sort!
9468 @item ^-q^/QUIET^
9469 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9470 Quiet mode: by default @code{gnatelim} outputs to the standard error
9471 stream the number of program units left to be processed. This option turns
9472 this trace off.
9473
9474 @item ^-v^/VERBOSE^
9475 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9476 Verbose mode: @code{gnatelim} version information is printed as Ada
9477 comments to the standard output stream. Also, in addition to the number of
9478 program units left @code{gnatelim} will output the name of the current unit
9479 being processed.
9480
9481 @item ^-a^/ALL^
9482 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9483 Also look for subprograms from the GNAT run time that can be eliminated. Note
9484 that when @file{gnat.adc} is produced using this switch, the entire program
9485 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9486
9487 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9488 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9489 When looking for source files also look in directory @var{dir}. Specifying
9490 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9491 sources in the current directory.
9492
9493 @item ^-b^/BIND_FILE=^@var{bind_file}
9494 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9495 Specifies @var{bind_file} as the bind file to process. If not set, the name
9496 of the bind file is computed from the full expanded Ada name
9497 of a main subprogram.
9498
9499 @item ^-C^/CONFIG_FILE=^@var{config_file}
9500 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9501 Specifies a file @var{config_file} that contains configuration pragmas. The
9502 file must be specified with full path.
9503
9504 @item ^--GCC^/COMPILER^=@var{compiler_name}
9505 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9506 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9507 available on the path.
9508
9509 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9510 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9511 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9512 available on the path.
9513
9514 @item -d@var{x}
9515 @cindex @option{-d@var{x}} (@command{gnatelim})
9516 Activate internal debugging switches. @var{x} is a letter or digit, or
9517 string of letters or digits, which specifies the type of debugging
9518 mode desired.  Normally these are used only for internal development
9519 or system debugging purposes. You can find full documentation for these
9520 switches in the spec of the @code{Gnatelim} unit in the compiler
9521 source file @file{gnatelim.ads}.
9522 @end table
9523
9524 @noindent
9525 @code{gnatelim} sends its output to the standard output stream, and all the
9526 tracing and debug information is sent to the standard error stream.
9527 In order to produce a proper GNAT configuration file
9528 @file{gnat.adc}, redirection must be used:
9529
9530 @smallexample
9531 @ifset vms
9532 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9533 @end ifset
9534 @ifclear vms
9535 $ gnatelim main_prog.adb > gnat.adc
9536 @end ifclear
9537 @end smallexample
9538
9539 @ifclear vms
9540 @noindent
9541 or
9542
9543 @smallexample
9544 $ gnatelim main_prog.adb >> gnat.adc
9545 @end smallexample
9546
9547 @noindent
9548 in order to append the @code{gnatelim} output to the existing contents of
9549 @file{gnat.adc}.
9550 @end ifclear
9551
9552 @node Correcting the List of Eliminate Pragmas
9553 @subsection Correcting the List of Eliminate Pragmas
9554
9555 @noindent
9556 In some rare cases @code{gnatelim} may try to eliminate
9557 subprograms that are actually called in the program. In this case, the
9558 compiler will generate an error message of the form:
9559
9560 @smallexample
9561 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9562 @end smallexample
9563
9564 @noindent
9565 You will need to manually remove the wrong @code{Eliminate} pragmas from
9566 the @file{gnat.adc} file. You should recompile your program
9567 from scratch after that, because you need a consistent @file{gnat.adc} file
9568 during the entire compilation.
9569
9570
9571 @node Making Your Executables Smaller
9572 @subsection Making Your Executables Smaller
9573
9574 @noindent
9575 In order to get a smaller executable for your program you now have to
9576 recompile the program completely with the new @file{gnat.adc} file
9577 created by @code{gnatelim} in your current directory:
9578
9579 @smallexample
9580 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9581 @end smallexample
9582
9583 @noindent
9584 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9585 recompile everything
9586 with the set of pragmas @code{Eliminate} that you have obtained with
9587 @command{gnatelim}).
9588
9589 Be aware that the set of @code{Eliminate} pragmas is specific to each
9590 program. It is not recommended to merge sets of @code{Eliminate}
9591 pragmas created for different programs in one @file{gnat.adc} file.
9592
9593 @node Summary of the gnatelim Usage Cycle
9594 @subsection Summary of the gnatelim Usage Cycle
9595
9596 @noindent
9597 Here is a quick summary of the steps to be taken in order to reduce
9598 the size of your executables with @code{gnatelim}. You may use
9599 other GNAT options to control the optimization level,
9600 to produce the debugging information, to set search path, etc.
9601
9602 @enumerate
9603 @item
9604 Produce a bind file
9605
9606 @smallexample
9607 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9608 $ gnatbind main_prog
9609 @end smallexample
9610
9611 @item
9612 Generate a list of @code{Eliminate} pragmas
9613 @smallexample
9614 @ifset vms
9615 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9616 @end ifset
9617 @ifclear vms
9618 $ gnatelim main_prog >[>] gnat.adc
9619 @end ifclear
9620 @end smallexample
9621
9622 @item
9623 Recompile the application
9624
9625 @smallexample
9626 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9627 @end smallexample
9628
9629 @end enumerate
9630
9631
9632
9633
9634 @c ********************************
9635 @node Renaming Files Using gnatchop
9636 @chapter Renaming Files Using @code{gnatchop}
9637 @findex gnatchop
9638
9639 @noindent
9640 This chapter discusses how to handle files with multiple units by using
9641 the @code{gnatchop} utility. This utility is also useful in renaming
9642 files to meet the standard GNAT default file naming conventions.
9643
9644 @menu
9645 * Handling Files with Multiple Units::
9646 * Operating gnatchop in Compilation Mode::
9647 * Command Line for gnatchop::
9648 * Switches for gnatchop::
9649 * Examples of gnatchop Usage::
9650 @end menu
9651
9652 @node Handling Files with Multiple Units
9653 @section Handling Files with Multiple Units
9654
9655 @noindent
9656 The basic compilation model of GNAT requires that a file submitted to the
9657 compiler have only one unit and there be a strict correspondence
9658 between the file name and the unit name.
9659
9660 The @code{gnatchop} utility allows both of these rules to be relaxed,
9661 allowing GNAT to process files which contain multiple compilation units
9662 and files with arbitrary file names. @code{gnatchop}
9663 reads the specified file and generates one or more output files,
9664 containing one unit per file. The unit and the file name correspond,
9665 as required by GNAT.
9666
9667 If you want to permanently restructure a set of ``foreign'' files so that
9668 they match the GNAT rules, and do the remaining development using the
9669 GNAT structure, you can simply use @command{gnatchop} once, generate the
9670 new set of files and work with them from that point on.
9671
9672 Alternatively, if you want to keep your files in the ``foreign'' format,
9673 perhaps to maintain compatibility with some other Ada compilation
9674 system, you can set up a procedure where you use @command{gnatchop} each
9675 time you compile, regarding the source files that it writes as temporary
9676 files that you throw away.
9677
9678
9679 @node Operating gnatchop in Compilation Mode
9680 @section Operating gnatchop in Compilation Mode
9681
9682 @noindent
9683 The basic function of @code{gnatchop} is to take a file with multiple units
9684 and split it into separate files. The boundary between files is reasonably
9685 clear, except for the issue of comments and pragmas. In default mode, the
9686 rule is that any pragmas between units belong to the previous unit, except
9687 that configuration pragmas always belong to the following unit. Any comments
9688 belong to the following unit. These rules
9689 almost always result in the right choice of
9690 the split point without needing to mark it explicitly and most users will
9691 find this default to be what they want. In this default mode it is incorrect to
9692 submit a file containing only configuration pragmas, or one that ends in
9693 configuration pragmas, to @code{gnatchop}.
9694
9695 However, using a special option to activate ``compilation mode'',
9696 @code{gnatchop}
9697 can perform another function, which is to provide exactly the semantics
9698 required by the RM for handling of configuration pragmas in a compilation.
9699 In the absence of configuration pragmas (at the main file level), this
9700 option has no effect, but it causes such configuration pragmas to be handled
9701 in a quite different manner.
9702
9703 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9704 only configuration pragmas, then this file is appended to the
9705 @file{gnat.adc} file in the current directory. This behavior provides
9706 the required behavior described in the RM for the actions to be taken
9707 on submitting such a file to the compiler, namely that these pragmas
9708 should apply to all subsequent compilations in the same compilation
9709 environment. Using GNAT, the current directory, possibly containing a
9710 @file{gnat.adc} file is the representation
9711 of a compilation environment. For more information on the
9712 @file{gnat.adc} file, see the section on handling of configuration
9713 pragmas @pxref{Handling of Configuration Pragmas}.
9714
9715 Second, in compilation mode, if @code{gnatchop}
9716 is given a file that starts with
9717 configuration pragmas, and contains one or more units, then these
9718 configuration pragmas are prepended to each of the chopped files. This
9719 behavior provides the required behavior described in the RM for the
9720 actions to be taken on compiling such a file, namely that the pragmas
9721 apply to all units in the compilation, but not to subsequently compiled
9722 units.
9723
9724 Finally, if configuration pragmas appear between units, they are appended
9725 to the previous unit. This results in the previous unit being illegal,
9726 since the compiler does not accept configuration pragmas that follow
9727 a unit. This provides the required RM behavior that forbids configuration
9728 pragmas other than those preceding the first compilation unit of a
9729 compilation.
9730
9731 For most purposes, @code{gnatchop} will be used in default mode. The
9732 compilation mode described above is used only if you need exactly
9733 accurate behavior with respect to compilations, and you have files
9734 that contain multiple units and configuration pragmas. In this
9735 circumstance the use of @code{gnatchop} with the compilation mode
9736 switch provides the required behavior, and is for example the mode
9737 in which GNAT processes the ACVC tests.
9738
9739 @node Command Line for gnatchop
9740 @section Command Line for @code{gnatchop}
9741
9742 @noindent
9743 The @code{gnatchop} command has the form:
9744
9745 @smallexample
9746 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9747       [@var{directory}]
9748 @end smallexample
9749
9750 @noindent
9751 The only required argument is the file name of the file to be chopped.
9752 There are no restrictions on the form of this file name. The file itself
9753 contains one or more Ada units, in normal GNAT format, concatenated
9754 together. As shown, more than one file may be presented to be chopped.
9755
9756 When run in default mode, @code{gnatchop} generates one output file in
9757 the current directory for each unit in each of the files.
9758
9759 @var{directory}, if specified, gives the name of the directory to which
9760 the output files will be written. If it is not specified, all files are
9761 written to the current directory.
9762
9763 For example, given a
9764 file called @file{hellofiles} containing
9765
9766 @smallexample @c ada
9767 @group
9768 @cartouche
9769 procedure hello;
9770
9771 with Text_IO; use Text_IO;
9772 procedure hello is
9773 begin
9774    Put_Line ("Hello");
9775 end hello;
9776 @end cartouche
9777 @end group
9778 @end smallexample
9779
9780 @noindent
9781 the command
9782
9783 @smallexample
9784 $ gnatchop ^hellofiles^HELLOFILES.^
9785 @end smallexample
9786
9787 @noindent
9788 generates two files in the current directory, one called
9789 @file{hello.ads} containing the single line that is the procedure spec,
9790 and the other called @file{hello.adb} containing the remaining text. The
9791 original file is not affected. The generated files can be compiled in
9792 the normal manner.
9793
9794 @noindent
9795 When gnatchop is invoked on a file that is empty or that contains only empty
9796 lines and/or comments, gnatchop will not fail, but will not produce any
9797 new sources.
9798
9799 For example, given a
9800 file called @file{toto.txt} containing
9801
9802 @smallexample @c ada
9803 @group
9804 @cartouche
9805 --  Just a comment
9806 @end cartouche
9807 @end group
9808 @end smallexample
9809
9810 @noindent
9811 the command
9812
9813 @smallexample
9814 $ gnatchop ^toto.txt^TOT.TXT^
9815 @end smallexample
9816
9817 @noindent
9818 will not produce any new file and will result in the following warnings:
9819
9820 @smallexample
9821 toto.txt:1:01: warning: empty file, contains no compilation units
9822 no compilation units found
9823 no source files written
9824 @end smallexample
9825
9826 @node Switches for gnatchop
9827 @section Switches for @code{gnatchop}
9828
9829 @noindent
9830 @command{gnatchop} recognizes the following switches:
9831
9832 @table @option
9833 @c !sort!
9834
9835 @item ^-c^/COMPILATION^
9836 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9837 Causes @code{gnatchop} to operate in compilation mode, in which
9838 configuration pragmas are handled according to strict RM rules. See
9839 previous section for a full description of this mode.
9840
9841 @ifclear vms
9842 @item -gnatxxx
9843 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9844 used to parse the given file. Not all @code{xxx} options make sense,
9845 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9846 process a source file that uses Latin-2 coding for identifiers.
9847 @end ifclear
9848
9849 @item ^-h^/HELP^
9850 Causes @code{gnatchop} to generate a brief help summary to the standard
9851 output file showing usage information.
9852
9853 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9854 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9855 Limit generated file names to the specified number @code{mm}
9856 of characters.
9857 This is useful if the
9858 resulting set of files is required to be interoperable with systems
9859 which limit the length of file names.
9860 @ifset vms
9861 If no value is given, or
9862 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9863 a default of 39, suitable for OpenVMS Alpha
9864 Systems, is assumed
9865 @end ifset
9866 @ifclear vms
9867 No space is allowed between the @option{-k} and the numeric value. The numeric
9868 value may be omitted in which case a default of @option{-k8},
9869 suitable for use
9870 with DOS-like file systems, is used. If no @option{-k} switch
9871 is present then
9872 there is no limit on the length of file names.
9873 @end ifclear
9874
9875 @item ^-p^/PRESERVE^
9876 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9877 Causes the file ^modification^creation^ time stamp of the input file to be
9878 preserved and used for the time stamp of the output file(s). This may be
9879 useful for preserving coherency of time stamps in an environment where
9880 @code{gnatchop} is used as part of a standard build process.
9881
9882 @item ^-q^/QUIET^
9883 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9884 Causes output of informational messages indicating the set of generated
9885 files to be suppressed. Warnings and error messages are unaffected.
9886
9887 @item ^-r^/REFERENCE^
9888 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9889 @findex Source_Reference
9890 Generate @code{Source_Reference} pragmas. Use this switch if the output
9891 files are regarded as temporary and development is to be done in terms
9892 of the original unchopped file. This switch causes
9893 @code{Source_Reference} pragmas to be inserted into each of the
9894 generated files to refers back to the original file name and line number.
9895 The result is that all error messages refer back to the original
9896 unchopped file.
9897 In addition, the debugging information placed into the object file (when
9898 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9899 also refers back to this original file so that tools like profilers and
9900 debuggers will give information in terms of the original unchopped file.
9901
9902 If the original file to be chopped itself contains
9903 a @code{Source_Reference}
9904 pragma referencing a third file, then gnatchop respects
9905 this pragma, and the generated @code{Source_Reference} pragmas
9906 in the chopped file refer to the original file, with appropriate
9907 line numbers. This is particularly useful when @code{gnatchop}
9908 is used in conjunction with @code{gnatprep} to compile files that
9909 contain preprocessing statements and multiple units.
9910
9911 @item ^-v^/VERBOSE^
9912 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9913 Causes @code{gnatchop} to operate in verbose mode. The version
9914 number and copyright notice are output, as well as exact copies of
9915 the gnat1 commands spawned to obtain the chop control information.
9916
9917 @item ^-w^/OVERWRITE^
9918 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9919 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9920 fatal error if there is already a file with the same name as a
9921 file it would otherwise output, in other words if the files to be
9922 chopped contain duplicated units. This switch bypasses this
9923 check, and causes all but the last instance of such duplicated
9924 units to be skipped.
9925
9926 @ifclear vms
9927 @item --GCC=xxxx
9928 @cindex @option{--GCC=} (@code{gnatchop})
9929 Specify the path of the GNAT parser to be used. When this switch is used,
9930 no attempt is made to add the prefix to the GNAT parser executable.
9931 @end ifclear
9932 @end table
9933
9934 @node Examples of gnatchop Usage
9935 @section Examples of @code{gnatchop} Usage
9936
9937 @table @code
9938 @ifset vms
9939 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9940 @end ifset
9941 @ifclear vms
9942 @item gnatchop -w hello_s.ada prerelease/files
9943 @end ifclear
9944
9945 Chops the source file @file{hello_s.ada}. The output files will be
9946 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9947 overwriting any
9948 files with matching names in that directory (no files in the current
9949 directory are modified).
9950
9951 @item gnatchop ^archive^ARCHIVE.^
9952 Chops the source file @file{^archive^ARCHIVE.^}
9953 into the current directory. One
9954 useful application of @code{gnatchop} is in sending sets of sources
9955 around, for example in email messages. The required sources are simply
9956 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9957 command), and then
9958 @code{gnatchop} is used at the other end to reconstitute the original
9959 file names.
9960
9961 @item gnatchop file1 file2 file3 direc
9962 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9963 the resulting files in the directory @file{direc}. Note that if any units
9964 occur more than once anywhere within this set of files, an error message
9965 is generated, and no files are written. To override this check, use the
9966 @option{^-w^/OVERWRITE^} switch,
9967 in which case the last occurrence in the last file will
9968 be the one that is output, and earlier duplicate occurrences for a given
9969 unit will be skipped.
9970 @end table
9971
9972 @node Configuration Pragmas
9973 @chapter Configuration Pragmas
9974 @cindex Configuration pragmas
9975 @cindex Pragmas, configuration
9976
9977 @noindent
9978 In Ada 95, configuration pragmas include those pragmas described as
9979 such in the Ada 95 Reference Manual, as well as
9980 implementation-dependent pragmas that are configuration pragmas. See the
9981 individual descriptions of pragmas in the GNAT Reference Manual for
9982 details on these additional GNAT-specific configuration pragmas. Most
9983 notably, the pragma @code{Source_File_Name}, which allows
9984 specifying non-default names for source files, is a configuration
9985 pragma. The following is a complete list of configuration pragmas
9986 recognized by @code{GNAT}:
9987
9988 @smallexample
9989    Ada_83
9990    Ada_95
9991    C_Pass_By_Copy
9992    Component_Alignment
9993    Discard_Names
9994    Elaboration_Checks
9995    Eliminate
9996    Extend_System
9997    Extensions_Allowed
9998    External_Name_Casing
9999    Float_Representation
10000    Initialize_Scalars
10001    License
10002    Locking_Policy
10003    Long_Float
10004    Normalize_Scalars
10005    Polling
10006    Profile
10007    Profile_Warnings
10008    Propagate_Exceptions
10009    Queuing_Policy
10010    Ravenscar
10011    Restricted_Run_Time
10012    Restrictions
10013    Restrictions_Warnings
10014    Reviewable
10015    Source_File_Name
10016    Style_Checks
10017    Suppress
10018    Task_Dispatching_Policy
10019    Universal_Data
10020    Unsuppress
10021    Use_VADS_Size
10022    Warnings
10023    Validity_Checks
10024 @end smallexample
10025
10026 @menu
10027 * Handling of Configuration Pragmas::
10028 * The Configuration Pragmas Files::
10029 @end menu
10030
10031 @node Handling of Configuration Pragmas
10032 @section Handling of Configuration Pragmas
10033
10034 Configuration pragmas may either appear at the start of a compilation
10035 unit, in which case they apply only to that unit, or they may apply to
10036 all compilations performed in a given compilation environment.
10037
10038 GNAT also provides the @code{gnatchop} utility to provide an automatic
10039 way to handle configuration pragmas following the semantics for
10040 compilations (that is, files with multiple units), described in the RM.
10041 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10042 However, for most purposes, it will be more convenient to edit the
10043 @file{gnat.adc} file that contains configuration pragmas directly,
10044 as described in the following section.
10045
10046 @node The Configuration Pragmas Files
10047 @section The Configuration Pragmas Files
10048 @cindex @file{gnat.adc}
10049
10050 @noindent
10051 In GNAT a compilation environment is defined by the current
10052 directory at the time that a compile command is given. This current
10053 directory is searched for a file whose name is @file{gnat.adc}. If
10054 this file is present, it is expected to contain one or more
10055 configuration pragmas that will be applied to the current compilation.
10056 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10057 considered.
10058
10059 Configuration pragmas may be entered into the @file{gnat.adc} file
10060 either by running @code{gnatchop} on a source file that consists only of
10061 configuration pragmas, or more conveniently  by
10062 direct editing of the @file{gnat.adc} file, which is a standard format
10063 source file.
10064
10065 In addition to @file{gnat.adc}, one additional file containing configuration
10066 pragmas may be applied to the current compilation using the switch
10067 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10068 contains only configuration pragmas. These configuration pragmas are
10069 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10070 is present and switch @option{-gnatA} is not used).
10071
10072 It is allowed to specify several switches @option{-gnatec}, however only
10073 the last one on the command line will be taken into account.
10074
10075 If you are using project file, a separate mechanism is provided using
10076 project attributes, see @ref{Specifying Configuration Pragmas} for more
10077 details.
10078
10079 @ifset vms
10080 Of special interest to GNAT OpenVMS Alpha is the following
10081 configuration pragma:
10082
10083 @smallexample @c ada
10084 @cartouche
10085 pragma Extend_System (Aux_DEC);
10086 @end cartouche
10087 @end smallexample
10088
10089 @noindent
10090 In the presence of this pragma, GNAT adds to the definition of the
10091 predefined package SYSTEM all the additional types and subprograms that are
10092 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10093 @end ifset
10094
10095 @node Handling Arbitrary File Naming Conventions Using gnatname
10096 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10097 @cindex Arbitrary File Naming Conventions
10098
10099 @menu
10100 * Arbitrary File Naming Conventions::
10101 * Running gnatname::
10102 * Switches for gnatname::
10103 * Examples of gnatname Usage::
10104 @end menu
10105
10106 @node Arbitrary File Naming Conventions
10107 @section Arbitrary File Naming Conventions
10108
10109 @noindent
10110 The GNAT compiler must be able to know the source file name of a compilation
10111 unit.  When using the standard GNAT default file naming conventions
10112 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10113 does not need additional information.
10114
10115 @noindent
10116 When the source file names do not follow the standard GNAT default file naming
10117 conventions, the GNAT compiler must be given additional information through
10118 a configuration pragmas file (see @ref{Configuration Pragmas})
10119 or a project file.
10120 When the non standard file naming conventions are well-defined,
10121 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10122 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10123 if the file naming conventions are irregular or arbitrary, a number
10124 of pragma @code{Source_File_Name} for individual compilation units
10125 must be defined.
10126 To help maintain the correspondence between compilation unit names and
10127 source file names within the compiler,
10128 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10129 set of files.
10130
10131 @node Running gnatname
10132 @section Running @code{gnatname}
10133
10134 @noindent
10135 The usual form of the @code{gnatname} command is
10136
10137 @smallexample
10138 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10139 @end smallexample
10140
10141 @noindent
10142 All of the arguments are optional. If invoked without any argument,
10143 @code{gnatname} will display its usage.
10144
10145 @noindent
10146 When used with at least one naming pattern, @code{gnatname} will attempt to
10147 find all the compilation units in files that follow at least one of the
10148 naming patterns. To find these compilation units,
10149 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10150 regular files.
10151
10152 @noindent
10153 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10154 Each Naming Pattern is enclosed between double quotes.
10155 A Naming Pattern is a regular expression similar to the wildcard patterns
10156 used in file names by the Unix shells or the DOS prompt.
10157
10158 @noindent
10159 Examples of Naming Patterns are
10160
10161 @smallexample
10162    "*.[12].ada"
10163    "*.ad[sb]*"
10164    "body_*"    "spec_*"
10165 @end smallexample
10166
10167 @noindent
10168 For a more complete description of the syntax of Naming Patterns,
10169 see the second kind of regular expressions described in @file{g-regexp.ads}
10170 (the ``Glob'' regular expressions).
10171
10172 @noindent
10173 When invoked with no switches, @code{gnatname} will create a configuration
10174 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10175 @code{Source_File_Name} for each file that contains a valid Ada unit.
10176
10177 @node Switches for gnatname
10178 @section Switches for @code{gnatname}
10179
10180 @noindent
10181 Switches for @code{gnatname} must precede any specified Naming Pattern.
10182
10183 @noindent
10184 You may specify any of the following switches to @code{gnatname}:
10185
10186 @table @option
10187 @c !sort!
10188
10189 @item ^-c^/CONFIG_FILE=^@file{file}
10190 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10191 Create a configuration pragmas file @file{file} (instead of the default
10192 @file{gnat.adc}).
10193 @ifclear vms
10194 There may be zero, one or more space between @option{-c} and
10195 @file{file}.
10196 @end ifclear
10197 @file{file} may include directory information. @file{file} must be
10198 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10199 When a switch @option{^-c^/CONFIG_FILE^} is
10200 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10201
10202 @item ^-d^/SOURCE_DIRS=^@file{dir}
10203 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10204 Look for source files in directory @file{dir}. There may be zero, one or more
10205 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10206 When a switch @option{^-d^/SOURCE_DIRS^}
10207 is specified, the current working directory will not be searched for source
10208 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10209 or @option{^-D^/DIR_FILES^} switch.
10210 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10211 If @file{dir} is a relative path, it is relative to the directory of
10212 the configuration pragmas file specified with switch
10213 @option{^-c^/CONFIG_FILE^},
10214 or to the directory of the project file specified with switch
10215 @option{^-P^/PROJECT_FILE^} or,
10216 if neither switch @option{^-c^/CONFIG_FILE^}
10217 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10218 current working directory. The directory
10219 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10220
10221 @item ^-D^/DIRS_FILE=^@file{file}
10222 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10223 Look for source files in all directories listed in text file @file{file}.
10224 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10225 and @file{file}.
10226 @file{file} must be an existing, readable text file.
10227 Each non empty line in @file{file} must be a directory.
10228 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10229 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10230 @file{file}.
10231
10232 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10233 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10234 Foreign patterns. Using this switch, it is possible to add sources of languages
10235 other than Ada to the list of sources of a project file.
10236 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10237 For example,
10238 @smallexample
10239 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10240 @end smallexample
10241 @noindent
10242 will look for Ada units in all files with the @file{.ada} extension,
10243 and will add to the list of file for project @file{prj.gpr} the C files
10244 with extension ".^c^C^".
10245
10246 @item ^-h^/HELP^
10247 @cindex @option{^-h^/HELP^} (@code{gnatname})
10248 Output usage (help) information. The output is written to @file{stdout}.
10249
10250 @item ^-P^/PROJECT_FILE=^@file{proj}
10251 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10252 Create or update project file @file{proj}. There may be zero, one or more space
10253 between @option{-P} and @file{proj}. @file{proj} may include directory
10254 information. @file{proj} must be writable.
10255 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10256 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10257 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10258
10259 @item ^-v^/VERBOSE^
10260 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10261 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10262 This includes name of the file written, the name of the directories to search
10263 and, for each file in those directories whose name matches at least one of
10264 the Naming Patterns, an indication of whether the file contains a unit,
10265 and if so the name of the unit.
10266
10267 @item ^-v -v^/VERBOSE /VERBOSE^
10268 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10269 Very Verbose mode. In addition to the output produced in verbose mode,
10270 for each file in the searched directories whose name matches none of
10271 the Naming Patterns, an indication is given that there is no match.
10272
10273 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10274 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10275 Excluded patterns. Using this switch, it is possible to exclude some files
10276 that would match the name patterns. For example,
10277 @smallexample
10278 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10279 @end smallexample
10280 @noindent
10281 will look for Ada units in all files with the @file{.ada} extension,
10282 except those whose names end with @file{_nt.ada}.
10283
10284 @end table
10285
10286 @node Examples of gnatname Usage
10287 @section Examples of @code{gnatname} Usage
10288
10289 @ifset vms
10290 @smallexample
10291 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10292 @end smallexample
10293 @end ifset
10294
10295 @ifclear vms
10296 @smallexample
10297 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10298 @end smallexample
10299 @end ifclear
10300
10301 @noindent
10302 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10303 and be writable. In addition, the directory
10304 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10305 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10306
10307 @ifclear vms
10308 Note the optional spaces after @option{-c} and @option{-d}.
10309 @end ifclear
10310
10311 @smallexample
10312 @ifclear vms
10313 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10314   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10315 @end ifclear
10316 @ifset vms
10317 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10318   /EXCLUDED_PATTERN=*_nt_body.ada
10319   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10320   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10321 @end ifset
10322 @end smallexample
10323
10324 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10325 even in conjunction with one or several switches
10326 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10327 are used in this example.
10328
10329
10330 @c *****************************************
10331 @c * G N A T  P r o j e c t  M a n a g e r *
10332 @c *****************************************
10333 @node GNAT Project Manager
10334 @chapter GNAT Project Manager
10335
10336 @menu
10337 * Introduction::
10338 * Examples of Project Files::
10339 * Project File Syntax::
10340 * Objects and Sources in Project Files::
10341 * Importing Projects::
10342 * Project Extension::
10343 * External References in Project Files::
10344 * Packages in Project Files::
10345 * Variables from Imported Projects::
10346 * Naming Schemes::
10347 * Library Projects::
10348 * Using Third-Party Libraries through Projects::
10349 * Stand-alone Library Projects::
10350 * Switches Related to Project Files::
10351 * Tools Supporting Project Files::
10352 * An Extended Example::
10353 * Project File Complete Syntax::
10354 @end menu
10355
10356 @c ****************
10357 @c * Introduction *
10358 @c ****************
10359
10360 @node Introduction
10361 @section Introduction
10362
10363 @noindent
10364 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10365 you to manage complex builds involving a number of source files, directories,
10366 and compilation options for different system configurations. In particular,
10367 project files allow you to specify:
10368 @itemize @bullet
10369 @item
10370 The directory or set of directories containing the source files, and/or the
10371 names of the specific source files themselves
10372 @item
10373 The directory in which the compiler's output
10374 (@file{ALI} files, object files, tree files) is to be placed
10375 @item
10376 The directory in which the executable programs is to be placed
10377 @item
10378 ^Switch^Switch^ settings for any of the project-enabled tools
10379 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10380 @code{gnatfind}); you can apply these settings either globally or to individual
10381 compilation units.
10382 @item
10383 The source files containing the main subprogram(s) to be built
10384 @item
10385 The source programming language(s) (currently Ada and/or C)
10386 @item
10387 Source file naming conventions; you can specify these either globally or for
10388 individual compilation units
10389 @end itemize
10390
10391 @menu
10392 * Project Files::
10393 @end menu
10394
10395 @node Project Files
10396 @subsection Project Files
10397
10398 @noindent
10399 Project files are written in a syntax close to that of Ada, using  familiar
10400 notions such as packages, context clauses, declarations, default values,
10401 assignments, and inheritance. Finally, project files can be built
10402 hierarchically from other project files, simplifying complex system
10403 integration and project reuse.
10404
10405 A @dfn{project} is a specific set of values for various compilation properties.
10406 The settings for a given project are described by means of
10407 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10408 Property values in project files are either strings or lists of strings.
10409 Properties that are not explicitly set receive default values.  A project
10410 file may interrogate the values of @dfn{external variables} (user-defined
10411 command-line switches or environment variables), and it may specify property
10412 settings conditionally, based on the value of such variables.
10413
10414 In simple cases, a project's source files depend only on other source files
10415 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10416 used in
10417 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10418 the Project Manager also allows more sophisticated arrangements,
10419 where the source files in one project depend on source files in other
10420 projects:
10421 @itemize @bullet
10422 @item
10423 One project can @emph{import} other projects containing needed source files.
10424 @item
10425 You can organize GNAT projects in a hierarchy: a @emph{child} project
10426 can extend a @emph{parent} project, inheriting the parent's source files and
10427 optionally overriding any of them with alternative versions
10428 @end itemize
10429
10430 @noindent
10431 More generally, the Project Manager lets you structure large development
10432 efforts into hierarchical subsystems, where build decisions are delegated
10433 to the subsystem level, and thus different compilation environments
10434 (^switch^switch^ settings) used for different subsystems.
10435
10436 The Project Manager is invoked through the
10437 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10438 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10439 @ifclear vms
10440 There may be zero, one or more spaces between @option{-P} and
10441 @option{@emph{projectfile}}.
10442 @end ifclear
10443 If you want to define (on the command line) an external variable that is
10444 queried by the project file, you must use the
10445 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10446 The Project Manager parses and interprets the project file, and drives the
10447 invoked tool based on the project settings.
10448
10449 The Project Manager supports a wide range of development strategies,
10450 for systems of all sizes.  Here are some typical practices that are
10451 easily handled:
10452 @itemize @bullet
10453 @item
10454 Using a common set of source files, but generating object files in different
10455 directories via different ^switch^switch^ settings
10456 @item
10457 Using a mostly-shared set of source files, but with different versions of
10458 some unit or units
10459 @end itemize
10460
10461 @noindent
10462 The destination of an executable can be controlled inside a project file
10463 using the @option{^-o^-o^}
10464 ^switch^switch^.
10465 In the absence of such a ^switch^switch^ either inside
10466 the project file or on the command line, any executable files generated by
10467 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10468 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10469 in the object directory of the project.
10470
10471 You can use project files to achieve some of the effects of a source
10472 versioning system (for example, defining separate projects for
10473 the different sets of sources that comprise different releases) but the
10474 Project Manager is independent of any source configuration management tools
10475 that might be used by the developers.
10476
10477 The next section introduces the main features of GNAT's project facility
10478 through a sequence of examples; subsequent sections will present the syntax
10479 and semantics in more detail. A more formal description of the project
10480 facility appears in the GNAT Reference Manual.
10481
10482 @c *****************************
10483 @c * Examples of Project Files *
10484 @c *****************************
10485
10486 @node Examples of Project Files
10487 @section Examples of Project Files
10488 @noindent
10489 This section illustrates some of the typical uses of project files and
10490 explains their basic structure and behavior.
10491
10492 @menu
10493 * Common Sources with Different ^Switches^Switches^ and Directories::
10494 * Using External Variables::
10495 * Importing Other Projects::
10496 * Extending a Project::
10497 @end menu
10498
10499 @node Common Sources with Different ^Switches^Switches^ and Directories
10500 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10501
10502 @menu
10503 * Source Files::
10504 * Specifying the Object Directory::
10505 * Specifying the Exec Directory::
10506 * Project File Packages::
10507 * Specifying ^Switch^Switch^ Settings::
10508 * Main Subprograms::
10509 * Executable File Names::
10510 * Source File Naming Conventions::
10511 * Source Language(s)::
10512 @end menu
10513
10514 @noindent
10515 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10516 @file{proc.adb} are in the @file{/common} directory.  The file
10517 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10518 package @code{Pack}.  We want to compile these source files under two sets
10519 of ^switches^switches^:
10520 @itemize @bullet
10521 @item
10522 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10523 and the @option{^-gnata^-gnata^},
10524 @option{^-gnato^-gnato^},
10525 and @option{^-gnatE^-gnatE^} switches to the
10526 compiler; the compiler's output is to appear in @file{/common/debug}
10527 @item
10528 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10529 to the compiler; the compiler's output is to appear in @file{/common/release}
10530 @end itemize
10531
10532 @noindent
10533 The GNAT project files shown below, respectively @file{debug.gpr} and
10534 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10535
10536 Schematically:
10537 @smallexample
10538 @group
10539 ^/common^[COMMON]^
10540   debug.gpr
10541   release.gpr
10542   pack.ads
10543   pack.adb
10544   proc.adb
10545 @end group
10546 @group
10547 ^/common/debug^[COMMON.DEBUG]^
10548   proc.ali, proc.o
10549   pack.ali, pack.o
10550 @end group
10551 @group
10552 ^/common/release^[COMMON.RELEASE]^
10553   proc.ali, proc.o
10554   pack.ali, pack.o
10555 @end group
10556 @end smallexample
10557 Here are the corresponding project files:
10558
10559 @smallexample @c projectfile
10560 @group
10561 project Debug is
10562   for Object_Dir use "debug";
10563   for Main use ("proc");
10564
10565   package Builder is
10566     for ^Default_Switches^Default_Switches^ ("Ada")
10567         use ("^-g^-g^");
10568     for Executable ("proc.adb") use "proc1";
10569   end Builder;
10570 @end group
10571
10572 @group
10573   package Compiler is
10574     for ^Default_Switches^Default_Switches^ ("Ada")
10575        use ("-fstack-check",
10576             "^-gnata^-gnata^",
10577             "^-gnato^-gnato^",
10578             "^-gnatE^-gnatE^");
10579   end Compiler;
10580 end Debug;
10581 @end group
10582 @end smallexample
10583
10584 @smallexample @c projectfile
10585 @group
10586 project Release is
10587   for Object_Dir use "release";
10588   for Exec_Dir use ".";
10589   for Main use ("proc");
10590
10591   package Compiler is
10592     for ^Default_Switches^Default_Switches^ ("Ada")
10593         use ("^-O2^-O2^");
10594   end Compiler;
10595 end Release;
10596 @end group
10597 @end smallexample
10598
10599 @noindent
10600 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10601 insensitive), and analogously the project defined by @file{release.gpr} is
10602 @code{"Release"}.  For consistency the file should have the same name as the
10603 project, and the project file's extension should be @code{"gpr"}. These
10604 conventions are not required, but a warning is issued if they are not followed.
10605
10606 If the current directory is @file{^/temp^[TEMP]^}, then the command
10607 @smallexample
10608 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10609 @end smallexample
10610
10611 @noindent
10612 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10613 as well as the @code{^proc1^PROC1.EXE^} executable,
10614 using the ^switch^switch^ settings defined in the project file.
10615
10616 Likewise, the command
10617 @smallexample
10618 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10619 @end smallexample
10620
10621 @noindent
10622 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10623 and the @code{^proc^PROC.EXE^}
10624 executable in @file{^/common^[COMMON]^},
10625 using the ^switch^switch^ settings from the project file.
10626
10627 @node Source Files
10628 @unnumberedsubsubsec Source Files
10629
10630 @noindent
10631 If a project file does not explicitly specify a set of source directories or
10632 a set of source files, then by default the project's source files are the
10633 Ada source files in the project file directory.  Thus @file{pack.ads},
10634 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10635
10636 @node Specifying the Object Directory
10637 @unnumberedsubsubsec Specifying the Object Directory
10638
10639 @noindent
10640 Several project properties are modeled by Ada-style @emph{attributes};
10641 a property is defined by supplying the equivalent of an Ada attribute
10642 definition clause in the project file.
10643 A project's object directory is another such a property; the corresponding
10644 attribute is @code{Object_Dir}, and its value is also a string expression,
10645 specified either as absolute or relative. In the later case,
10646 it is relative to the project file directory. Thus the compiler's
10647 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10648 (for the @code{Debug} project)
10649 and to @file{^/common/release^[COMMON.RELEASE]^}
10650 (for the @code{Release} project).
10651 If @code{Object_Dir} is not specified, then the default is the project file
10652 directory itself.
10653
10654 @node Specifying the Exec Directory
10655 @unnumberedsubsubsec Specifying the Exec Directory
10656
10657 @noindent
10658 A project's exec directory is another property; the corresponding
10659 attribute is @code{Exec_Dir}, and its value is also a string expression,
10660 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10661 then the default is the object directory (which may also be the project file
10662 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10663 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10664 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10665 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10666
10667 @node Project File Packages
10668 @unnumberedsubsubsec Project File Packages
10669
10670 @noindent
10671 A GNAT tool that is integrated with the Project Manager is modeled by a
10672 corresponding package in the project file. In the example above,
10673 The @code{Debug} project defines the packages @code{Builder}
10674 (for @command{gnatmake}) and @code{Compiler};
10675 the @code{Release} project defines only the @code{Compiler} package.
10676
10677 The Ada-like package syntax is not to be taken literally.  Although packages in
10678 project files bear a surface resemblance to packages in Ada source code, the
10679 notation is simply a way to convey a grouping of properties for a named
10680 entity.  Indeed, the package names permitted in project files are restricted
10681 to a predefined set, corresponding to the project-aware tools, and the contents
10682 of packages are limited to a small set of constructs.
10683 The packages in the example above contain attribute definitions.
10684
10685 @node Specifying ^Switch^Switch^ Settings
10686 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10687
10688 @noindent
10689 ^Switch^Switch^ settings for a project-aware tool can be specified through
10690 attributes in the package that corresponds to the tool.
10691 The example above illustrates one of the relevant attributes,
10692 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10693 in both project files.
10694 Unlike simple attributes like @code{Source_Dirs},
10695 @code{^Default_Switches^Default_Switches^} is
10696 known as an @emph{associative array}.  When you define this attribute, you must
10697 supply an ``index'' (a literal string), and the effect of the attribute
10698 definition is to set the value of the array at the specified index.
10699 For the @code{^Default_Switches^Default_Switches^} attribute,
10700 the index is a programming language (in our case, Ada),
10701 and the value specified (after @code{use}) must be a list
10702 of string expressions.
10703
10704 The attributes permitted in project files are restricted to a predefined set.
10705 Some may appear at project level, others in packages.
10706 For any attribute that is an associative array, the index must always be a
10707 literal string, but the restrictions on this string (e.g., a file name or a
10708 language name) depend on the individual attribute.
10709 Also depending on the attribute, its specified value will need to be either a
10710 string or a string list.
10711
10712 In the @code{Debug} project, we set the switches for two tools,
10713 @command{gnatmake} and the compiler, and thus we include the two corresponding
10714 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10715 attribute with index @code{"Ada"}.
10716 Note that the package corresponding to
10717 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10718 similar, but only includes the @code{Compiler} package.
10719
10720 In project @code{Debug} above, the ^switches^switches^ starting with
10721 @option{-gnat} that are specified in package @code{Compiler}
10722 could have been placed in package @code{Builder}, since @command{gnatmake}
10723 transmits all such ^switches^switches^ to the compiler.
10724
10725 @node Main Subprograms
10726 @unnumberedsubsubsec Main Subprograms
10727
10728 @noindent
10729 One of the specifiable properties of a project is a list of files that contain
10730 main subprograms.  This property is captured in the @code{Main} attribute,
10731 whose value is a list of strings.  If a project defines the @code{Main}
10732 attribute, it is not necessary to identify the main subprogram(s) when
10733 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10734
10735 @node Executable File Names
10736 @unnumberedsubsubsec Executable File Names
10737
10738 @noindent
10739 By default, the executable file name corresponding to a main source is
10740 deducted from the main source file name. Through the attributes
10741 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10742 it is possible to change this default.
10743 In project @code{Debug} above, the executable file name
10744 for main source @file{^proc.adb^PROC.ADB^} is
10745 @file{^proc1^PROC1.EXE^}.
10746 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10747 of the the executable files, when no attribute @code{Executable} applies:
10748 its value replace the platform-specific executable suffix.
10749 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10750 specify a non default executable file name when several mains are built at once
10751 in a single @command{gnatmake} command.
10752
10753 @node Source File Naming Conventions
10754 @unnumberedsubsubsec Source File Naming Conventions
10755
10756 @noindent
10757 Since the project files above do not specify any source file naming
10758 conventions, the GNAT defaults are used.  The mechanism for defining source
10759 file naming conventions -- a package named @code{Naming} --
10760 is described below (@pxref{Naming Schemes}).
10761
10762 @node Source Language(s)
10763 @unnumberedsubsubsec Source Language(s)
10764
10765 @noindent
10766 Since the project files do not specify a @code{Languages} attribute, by
10767 default the GNAT tools assume that the language of the project file is Ada.
10768 More generally, a project can comprise source files
10769 in Ada, C, and/or other languages.
10770
10771 @node Using External Variables
10772 @subsection Using External Variables
10773
10774 @noindent
10775 Instead of supplying different project files for debug and release, we can
10776 define a single project file that queries an external variable (set either
10777 on the command line or via an ^environment variable^logical name^) in order to
10778 conditionally define the appropriate settings.  Again, assume that the
10779 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10780 located in directory @file{^/common^[COMMON]^}.  The following project file,
10781 @file{build.gpr}, queries the external variable named @code{STYLE} and
10782 defines an object directory and ^switch^switch^ settings based on whether
10783 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10784 the default is @code{"deb"}.
10785
10786 @smallexample @c projectfile
10787 @group
10788 project Build is
10789   for Main use ("proc");
10790
10791   type Style_Type is ("deb", "rel");
10792   Style : Style_Type := external ("STYLE", "deb");
10793
10794   case Style is
10795     when "deb" =>
10796       for Object_Dir use "debug";
10797
10798     when "rel" =>
10799       for Object_Dir use "release";
10800       for Exec_Dir use ".";
10801   end case;
10802 @end group
10803
10804 @group
10805   package Builder is
10806
10807     case Style is
10808       when "deb" =>
10809         for ^Default_Switches^Default_Switches^ ("Ada")
10810             use ("^-g^-g^");
10811         for Executable ("proc") use "proc1";
10812       when others =>
10813         null;
10814     end case;
10815
10816   end Builder;
10817 @end group
10818
10819 @group
10820   package Compiler is
10821
10822     case Style is
10823       when "deb" =>
10824         for ^Default_Switches^Default_Switches^ ("Ada")
10825             use ("^-gnata^-gnata^",
10826                  "^-gnato^-gnato^",
10827                  "^-gnatE^-gnatE^");
10828
10829       when "rel" =>
10830         for ^Default_Switches^Default_Switches^ ("Ada")
10831             use ("^-O2^-O2^");
10832     end case;
10833
10834   end Compiler;
10835
10836 end Build;
10837 @end group
10838 @end smallexample
10839
10840 @noindent
10841 @code{Style_Type} is an example of a @emph{string type}, which is the project
10842 file analog of an Ada enumeration type but whose components are string literals
10843 rather than identifiers.  @code{Style} is declared as a variable of this type.
10844
10845 The form @code{external("STYLE", "deb")} is known as an
10846 @emph{external reference}; its first argument is the name of an
10847 @emph{external variable}, and the second argument is a default value to be
10848 used if the external variable doesn't exist.  You can define an external
10849 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10850 or you can use ^an environment variable^a logical name^
10851 as an external variable.
10852
10853 Each @code{case} construct is expanded by the Project Manager based on the
10854 value of @code{Style}. Thus the command
10855 @ifclear vms
10856 @smallexample
10857 gnatmake -P/common/build.gpr -XSTYLE=deb
10858 @end smallexample
10859 @end ifclear
10860
10861 @ifset vms
10862 @smallexample
10863 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10864 @end smallexample
10865 @end ifset
10866
10867 @noindent
10868 is equivalent to the @command{gnatmake} invocation using the project file
10869 @file{debug.gpr} in the earlier example.  So is the command
10870 @smallexample
10871 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10872 @end smallexample
10873
10874 @noindent
10875 since @code{"deb"} is the default for @code{STYLE}.
10876
10877 Analogously,
10878
10879 @ifclear vms
10880 @smallexample
10881 gnatmake -P/common/build.gpr -XSTYLE=rel
10882 @end smallexample
10883 @end ifclear
10884
10885 @ifset vms
10886 @smallexample
10887 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10888 @end smallexample
10889 @end ifset
10890
10891 @noindent
10892 is equivalent to the @command{gnatmake} invocation using the project file
10893 @file{release.gpr} in the earlier example.
10894
10895 @node Importing Other Projects
10896 @subsection Importing Other Projects
10897
10898 @noindent
10899 A compilation unit in a source file in one project may depend on compilation
10900 units in source files in other projects.  To compile this unit under
10901 control of a project file, the
10902 dependent project must @emph{import} the projects containing the needed source
10903 files.
10904 This effect is obtained using syntax similar to an Ada @code{with} clause,
10905 but where @code{with}ed entities are strings that denote project files.
10906
10907 As an example, suppose that the two projects @code{GUI_Proj} and
10908 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10909 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10910 and @file{^/comm^[COMM]^}, respectively.
10911 Suppose that the source files for @code{GUI_Proj} are
10912 @file{gui.ads} and @file{gui.adb}, and that the source files for
10913 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10914 files is located in its respective project file directory.  Schematically:
10915
10916 @smallexample
10917 @group
10918 ^/gui^[GUI]^
10919   gui_proj.gpr
10920   gui.ads
10921   gui.adb
10922 @end group
10923
10924 @group
10925 ^/comm^[COMM]^
10926   comm_proj.gpr
10927   comm.ads
10928   comm.adb
10929 @end group
10930 @end smallexample
10931
10932 @noindent
10933 We want to develop an application in directory @file{^/app^[APP]^} that
10934 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10935 the corresponding project files (e.g. the ^switch^switch^ settings
10936 and object directory).
10937 Skeletal code for a main procedure might be something like the following:
10938
10939 @smallexample @c ada
10940 @group
10941 with GUI, Comm;
10942 procedure App_Main is
10943    ...
10944 begin
10945    ...
10946 end App_Main;
10947 @end group
10948 @end smallexample
10949
10950 @noindent
10951 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10952 effect:
10953
10954 @smallexample @c projectfile
10955 @group
10956 with "/gui/gui_proj", "/comm/comm_proj";
10957 project App_Proj is
10958    for Main use ("app_main");
10959 end App_Proj;
10960 @end group
10961 @end smallexample
10962
10963 @noindent
10964 Building an executable is achieved through the command:
10965 @smallexample
10966 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10967 @end smallexample
10968 @noindent
10969 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10970 in the directory where @file{app_proj.gpr} resides.
10971
10972 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10973 (as illustrated above) the @code{with} clause can omit the extension.
10974
10975 Our example specified an absolute path for each imported project file.
10976 Alternatively, the directory name of an imported object can be omitted
10977 if either
10978 @itemize @bullet
10979 @item
10980 The imported project file is in the same directory as the importing project
10981 file, or
10982 @item
10983 You have defined ^an environment variable^a logical name^
10984 that includes the directory containing
10985 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10986 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10987 directory names separated by colons (semicolons on Windows).
10988 @end itemize
10989
10990 @noindent
10991 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10992 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10993 as follows:
10994
10995 @smallexample @c projectfile
10996 @group
10997 with "gui_proj", "comm_proj";
10998 project App_Proj is
10999    for Main use ("app_main");
11000 end App_Proj;
11001 @end group
11002 @end smallexample
11003
11004 @noindent
11005 Importing other projects can create ambiguities.
11006 For example, the same unit might be present in different imported projects, or
11007 it might be present in both the importing project and in an imported project.
11008 Both of these conditions are errors.  Note that in the current version of
11009 the Project Manager, it is illegal to have an ambiguous unit even if the
11010 unit is never referenced by the importing project.  This restriction may be
11011 relaxed in a future release.
11012
11013 @node Extending a Project
11014 @subsection Extending a Project
11015
11016 @noindent
11017 In large software systems it is common to have multiple
11018 implementations of a common interface; in Ada terms, multiple versions of a
11019 package body for the same specification.  For example, one implementation
11020 might be safe for use in tasking programs, while another might only be used
11021 in sequential applications.  This can be modeled in GNAT using the concept
11022 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11023 another project (the ``parent'') then by default all source files of the
11024 parent project are inherited by the child, but the child project can
11025 override any of the parent's source files with new versions, and can also
11026 add new files.  This facility is the project analog of a type extension in
11027 Object-Oriented Programming.  Project hierarchies are permitted (a child
11028 project may be the parent of yet another project), and a project that
11029 inherits one project can also import other projects.
11030
11031 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11032 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11033 @file{pack.adb}, and @file{proc.adb}:
11034
11035 @smallexample
11036 @group
11037 ^/seq^[SEQ]^
11038   pack.ads
11039   pack.adb
11040   proc.adb
11041   seq_proj.gpr
11042 @end group
11043 @end smallexample
11044
11045 @noindent
11046 Note that the project file can simply be empty (that is, no attribute or
11047 package is defined):
11048
11049 @smallexample @c projectfile
11050 @group
11051 project Seq_Proj is
11052 end Seq_Proj;
11053 @end group
11054 @end smallexample
11055
11056 @noindent
11057 implying that its source files are all the Ada source files in the project
11058 directory.
11059
11060 Suppose we want to supply an alternate version of @file{pack.adb}, in
11061 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11062 @file{pack.ads} and @file{proc.adb}.  We can define a project
11063 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11064
11065 @smallexample
11066 @group
11067 ^/tasking^[TASKING]^
11068   pack.adb
11069   tasking_proj.gpr
11070 @end group
11071
11072 @group
11073 project Tasking_Proj extends "/seq/seq_proj" is
11074 end Tasking_Proj;
11075 @end group
11076 @end smallexample
11077
11078 @noindent
11079 The version of @file{pack.adb} used in a build depends on which project file
11080 is specified.
11081
11082 Note that we could have obtained the desired behavior using project import
11083 rather than project inheritance; a @code{base} project would contain the
11084 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11085 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11086 would import @code{base} and add a different version of @file{pack.adb}.  The
11087 choice depends on whether other sources in the original project need to be
11088 overridden.  If they do, then project extension is necessary, otherwise,
11089 importing is sufficient.
11090
11091 @noindent
11092 In a project file that extends another project file, it is possible to
11093 indicate that an inherited source is not part of the sources of the extending
11094 project. This is necessary sometimes when a package spec has been overloaded
11095 and no longer requires a body: in this case, it is necessary to indicate that
11096 the inherited body is not part of the sources of the project, otherwise there
11097 will be a compilation error when compiling the spec.
11098
11099 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11100 Its value is a string list: a list of file names.
11101
11102 @smallexample @c @projectfile
11103 project B extends "a" is
11104    for Source_Files use ("pkg.ads");
11105    --  New spec of Pkg does not need a completion
11106    for Locally_Removed_Files use ("pkg.adb");
11107 end B;
11108 @end smallexample
11109
11110 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11111 is still needed: if it is possible to build using @code{gnatmake} when such
11112 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11113 it is possible to remove the source completely from a system that includes
11114 project P.
11115
11116 @c ***********************
11117 @c * Project File Syntax *
11118 @c ***********************
11119
11120 @node Project File Syntax
11121 @section Project File Syntax
11122
11123 @menu
11124 * Basic Syntax::
11125 * Packages::
11126 * Expressions::
11127 * String Types::
11128 * Variables::
11129 * Attributes::
11130 * Associative Array Attributes::
11131 * case Constructions::
11132 @end menu
11133
11134 @noindent
11135 This section describes the structure of project files.
11136
11137 A project may be an @emph{independent project}, entirely defined by a single
11138 project file. Any Ada source file in an independent project depends only
11139 on the predefined library and other Ada source files in the same project.
11140
11141 @noindent
11142 A project may also @dfn{depend on} other projects, in either or both of
11143 the following ways:
11144 @itemize @bullet
11145 @item It may import any number of projects
11146 @item It may extend at most one other project
11147 @end itemize
11148
11149 @noindent
11150 The dependence relation is a directed acyclic graph (the subgraph reflecting
11151 the ``extends'' relation is a tree).
11152
11153 A project's @dfn{immediate sources} are the source files directly defined by
11154 that project, either implicitly by residing in the project file's directory,
11155 or explicitly through any of the source-related attributes described below.
11156 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11157 of @var{proj} together with the immediate sources (unless overridden) of any
11158 project on which @var{proj} depends (either directly or indirectly).
11159
11160 @node Basic Syntax
11161 @subsection Basic Syntax
11162
11163 @noindent
11164 As seen in the earlier examples, project files have an Ada-like syntax.
11165 The minimal project file is:
11166 @smallexample @c projectfile
11167 @group
11168 project Empty is
11169
11170 end Empty;
11171 @end group
11172 @end smallexample
11173
11174 @noindent
11175 The identifier @code{Empty} is the name of the project.
11176 This project name must be present after the reserved
11177 word @code{end} at the end of the project file, followed by a semi-colon.
11178
11179 Any name in a project file, such as the project name or a variable name,
11180 has the same syntax as an Ada identifier.
11181
11182 The reserved words of project files are the Ada reserved words plus
11183 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11184 reserved words currently used in project file syntax are:
11185
11186 @itemize @bullet
11187 @item
11188 @code{case}
11189 @item
11190 @code{end}
11191 @item
11192 @code{for}
11193 @item
11194 @code{is}
11195 @item
11196 @code{others}
11197 @item
11198 @code{package}
11199 @item
11200 @code{renames}
11201 @item
11202 @code{type}
11203 @item
11204 @code{use}
11205 @item
11206 @code{when}
11207 @item
11208 @code{with}
11209 @end itemize
11210
11211 @noindent
11212 Comments in project files have the same syntax as in Ada, two consecutives
11213 hyphens through the end of the line.
11214
11215 @node Packages
11216 @subsection Packages
11217
11218 @noindent
11219 A project file may contain @emph{packages}. The name of a package must be one
11220 of the identifiers from the following list. A package
11221 with a given name may only appear once in a project file. Package names are
11222 case insensitive. The following package names are legal:
11223
11224 @itemize @bullet
11225 @item
11226 @code{Naming}
11227 @item
11228 @code{Builder}
11229 @item
11230 @code{Compiler}
11231 @item
11232 @code{Binder}
11233 @item
11234 @code{Linker}
11235 @item
11236 @code{Finder}
11237 @item
11238 @code{Cross_Reference}
11239 @item
11240 @code{Eliminate}
11241 @item
11242 @code{gnatls}
11243 @item
11244 @code{gnatstub}
11245 @item
11246 @code{IDE}
11247 @end itemize
11248
11249 @noindent
11250 In its simplest form, a package may be empty:
11251
11252 @smallexample @c projectfile
11253 @group
11254 project Simple is
11255   package Builder is
11256   end Builder;
11257 end Simple;
11258 @end group
11259 @end smallexample
11260
11261 @noindent
11262 A package may contain @emph{attribute declarations},
11263 @emph{variable declarations} and @emph{case constructions}, as will be
11264 described below.
11265
11266 When there is ambiguity between a project name and a package name,
11267 the name always designates the project. To avoid possible confusion, it is
11268 always a good idea to avoid naming a project with one of the
11269 names allowed for packages or any name that starts with @code{gnat}.
11270
11271 @node Expressions
11272 @subsection Expressions
11273
11274 @noindent
11275 An @emph{expression} is either a @emph{string expression} or a
11276 @emph{string list expression}.
11277
11278 A @emph{string expression} is either a @emph{simple string expression} or a
11279 @emph{compound string expression}.
11280
11281 A @emph{simple string expression} is one of the following:
11282 @itemize @bullet
11283 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11284 @item A string-valued variable reference (see @ref{Variables})
11285 @item A string-valued attribute reference (see @ref{Attributes})
11286 @item An external reference (see @ref{External References in Project Files})
11287 @end itemize
11288
11289 @noindent
11290 A @emph{compound string expression} is a concatenation of string expressions,
11291 using the operator @code{"&"}
11292 @smallexample
11293        Path & "/" & File_Name & ".ads"
11294 @end smallexample
11295
11296 @noindent
11297 A @emph{string list expression} is either a
11298 @emph{simple string list expression} or a
11299 @emph{compound string list expression}.
11300
11301 A @emph{simple string list expression} is one of the following:
11302 @itemize @bullet
11303 @item A parenthesized list of zero or more string expressions,
11304 separated by commas
11305 @smallexample
11306    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11307    Empty_List := ();
11308 @end smallexample
11309 @item A string list-valued variable reference
11310 @item A string list-valued attribute reference
11311 @end itemize
11312
11313 @noindent
11314 A @emph{compound string list expression} is the concatenation (using
11315 @code{"&"}) of a simple string list expression and an expression.  Note that
11316 each term in a compound string list expression, except the first, may be
11317 either a string expression or a string list expression.
11318
11319 @smallexample @c projectfile
11320 @group
11321    File_Name_List := () & File_Name; --  One string in this list
11322    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11323    --  Two strings
11324    Big_List := File_Name_List & Extended_File_Name_List;
11325    --  Concatenation of two string lists: three strings
11326    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11327    --  Illegal: must start with a string list
11328 @end group
11329 @end smallexample
11330
11331 @node String Types
11332 @subsection String Types
11333
11334 @noindent
11335 A @emph{string type declaration} introduces a discrete set of string literals.
11336 If a string variable is declared to have this type, its value
11337 is restricted to the given set of literals.
11338
11339 Here is an example of a string type declaration:
11340
11341 @smallexample @c projectfile
11342    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11343 @end smallexample
11344
11345 @noindent
11346 Variables of a string type are called @emph{typed variables}; all other
11347 variables are called @emph{untyped variables}. Typed variables are
11348 particularly useful in @code{case} constructions, to support conditional
11349 attribute declarations.
11350 (see @ref{case Constructions}).
11351
11352 The string literals in the list are case sensitive and must all be different.
11353 They may include any graphic characters allowed in Ada, including spaces.
11354
11355 A string type may only be declared at the project level, not inside a package.
11356
11357 A string type may be referenced by its name if it has been declared in the same
11358 project file, or by an expanded name whose prefix is the name of the project
11359 in which it is declared.
11360
11361 @node Variables
11362 @subsection Variables
11363
11364 @noindent
11365 A variable may be declared at the project file level, or within a package.
11366 Here are some examples of variable declarations:
11367
11368 @smallexample @c projectfile
11369 @group
11370    This_OS : OS := external ("OS"); --  a typed variable declaration
11371    That_OS := "GNU/Linux";          --  an untyped variable declaration
11372 @end group
11373 @end smallexample
11374
11375 @noindent
11376 The syntax of a @emph{typed variable declaration} is identical to the Ada
11377 syntax for an object declaration. By contrast, the syntax of an untyped
11378 variable declaration is identical to an Ada assignment statement. In fact,
11379 variable declarations in project files have some of the characteristics of
11380 an assignment, in that successive declarations for the same variable are
11381 allowed. Untyped variable declarations do establish the expected kind of the
11382 variable (string or string list), and successive declarations for it must
11383 respect the initial kind.
11384
11385 @noindent
11386 A string variable declaration (typed or untyped) declares a variable
11387 whose value is a string. This variable may be used as a string expression.
11388 @smallexample @c projectfile
11389    File_Name       := "readme.txt";
11390    Saved_File_Name := File_Name & ".saved";
11391 @end smallexample
11392
11393 @noindent
11394 A string list variable declaration declares a variable whose value is a list
11395 of strings. The list may contain any number (zero or more) of strings.
11396
11397 @smallexample @c projectfile
11398    Empty_List := ();
11399    List_With_One_Element := ("^-gnaty^-gnaty^");
11400    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11401    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11402                  "pack2.ada", "util_.ada", "util.ada");
11403 @end smallexample
11404
11405 @noindent
11406 The same typed variable may not be declared more than once at project level,
11407 and it may not be declared more than once in any package; it is in effect
11408 a constant.
11409
11410 The same untyped variable may be declared several times. Declarations are
11411 elaborated in the order in which they appear, so  the new value replaces
11412 the old one, and any subsequent reference to the variable uses the new value.
11413 However, as noted above, if a variable has been declared as a string, all
11414 subsequent
11415 declarations must give it a string value. Similarly, if a variable has
11416 been declared as a string list, all subsequent declarations
11417 must give it a string list value.
11418
11419 A @emph{variable reference} may take several forms:
11420
11421 @itemize @bullet
11422 @item The simple variable name, for a variable in the current package (if any)
11423 or in the current project
11424 @item An expanded name, whose prefix is a context name.
11425 @end itemize
11426
11427 @noindent
11428 A @emph{context} may be one of the following:
11429
11430 @itemize @bullet
11431 @item The name of an existing package in the current project
11432 @item The name of an imported project of the current project
11433 @item The name of an ancestor project (i.e., a project extended by the current
11434 project, either directly or indirectly)
11435 @item An expanded name whose prefix is an imported/parent project name, and
11436 whose selector is a package name in that project.
11437 @end itemize
11438
11439 @noindent
11440 A variable reference may be used in an expression.
11441
11442 @node Attributes
11443 @subsection Attributes
11444
11445 @noindent
11446 A project (and its packages) may have @emph{attributes} that define
11447 the project's properties.  Some attributes have values that are strings;
11448 others have values that are string lists.
11449
11450 There are two categories of attributes: @emph{simple attributes}
11451 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11452
11453 Legal project attribute names, and attribute names for each legal package are
11454 listed below. Attributes names are case-insensitive.
11455
11456 The following attributes are defined on projects (all are simple attributes):
11457
11458 @multitable @columnfractions .4 .3
11459 @item @emph{Attribute Name}
11460 @tab @emph{Value}
11461 @item @code{Source_Files}
11462 @tab string list
11463 @item @code{Source_Dirs}
11464 @tab string list
11465 @item @code{Source_List_File}
11466 @tab string
11467 @item @code{Object_Dir}
11468 @tab string
11469 @item @code{Exec_Dir}
11470 @tab string
11471 @item @code{Locally_Removed_Files}
11472 @tab string list
11473 @item @code{Main}
11474 @tab string list
11475 @item @code{Languages}
11476 @tab string list
11477 @item @code{Main_Language}
11478 @tab string
11479 @item @code{Library_Dir}
11480 @tab string
11481 @item @code{Library_Name}
11482 @tab string
11483 @item @code{Library_Kind}
11484 @tab string
11485 @item @code{Library_Version}
11486 @tab string
11487 @item @code{Library_Interface}
11488 @tab string
11489 @item @code{Library_Auto_Init}
11490 @tab string
11491 @item @code{Library_Options}
11492 @tab string list
11493 @item @code{Library_GCC}
11494 @tab string
11495 @end multitable
11496
11497 @noindent
11498 The following attributes are defined for package  @code{Naming}
11499 (see @ref{Naming Schemes}):
11500
11501 @multitable @columnfractions .4 .2 .2 .2
11502 @item Attribute Name @tab Category @tab Index @tab Value
11503 @item @code{Spec_Suffix}
11504 @tab associative array
11505 @tab language name
11506 @tab string
11507 @item @code{Body_Suffix}
11508 @tab associative array
11509 @tab language name
11510 @tab string
11511 @item @code{Separate_Suffix}
11512 @tab simple attribute
11513 @tab n/a
11514 @tab string
11515 @item @code{Casing}
11516 @tab simple attribute
11517 @tab n/a
11518 @tab string
11519 @item @code{Dot_Replacement}
11520 @tab simple attribute
11521 @tab n/a
11522 @tab string
11523 @item @code{Spec}
11524 @tab associative array
11525 @tab Ada unit name
11526 @tab string
11527 @item @code{Body}
11528 @tab associative array
11529 @tab Ada unit name
11530 @tab string
11531 @item @code{Specification_Exceptions}
11532 @tab associative array
11533 @tab language name
11534 @tab string list
11535 @item @code{Implementation_Exceptions}
11536 @tab associative array
11537 @tab language name
11538 @tab string list
11539 @end multitable
11540
11541 @noindent
11542 The following attributes are defined for packages @code{Builder},
11543 @code{Compiler}, @code{Binder},
11544 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11545 (see @ref{^Switches^Switches^ and Project Files}).
11546
11547 @multitable @columnfractions .4 .2 .2 .2
11548 @item Attribute Name @tab Category @tab Index @tab Value
11549 @item @code{^Default_Switches^Default_Switches^}
11550 @tab associative array
11551 @tab language name
11552 @tab string list
11553 @item @code{^Switches^Switches^}
11554 @tab associative array
11555 @tab file name
11556 @tab string list
11557 @end multitable
11558
11559 @noindent
11560 In addition, package @code{Compiler} has a single string attribute
11561 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11562 string attribute @code{Global_Configuration_Pragmas}.
11563
11564 @noindent
11565 Each simple attribute has a default value: the empty string (for string-valued
11566 attributes) and the empty list (for string list-valued attributes).
11567
11568 An attribute declaration defines a new value for an attribute.
11569
11570 Examples of simple attribute declarations:
11571
11572 @smallexample @c projectfile
11573    for Object_Dir use "objects";
11574    for Source_Dirs use ("units", "test/drivers");
11575 @end smallexample
11576
11577 @noindent
11578 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11579 attribute definition clause in Ada.
11580
11581 Attributes references may be appear in expressions.
11582 The general form for such a reference is @code{<entity>'<attribute>}:
11583 Associative array attributes are functions. Associative
11584 array attribute references must have an argument that is a string literal.
11585
11586 Examples are:
11587
11588 @smallexample @c projectfile
11589   project'Object_Dir
11590   Naming'Dot_Replacement
11591   Imported_Project'Source_Dirs
11592   Imported_Project.Naming'Casing
11593   Builder'^Default_Switches^Default_Switches^("Ada")
11594 @end smallexample
11595
11596 @noindent
11597 The prefix of an attribute may be:
11598 @itemize @bullet
11599 @item @code{project} for an attribute of the current project
11600 @item The name of an existing package of the current project
11601 @item The name of an imported project
11602 @item The name of a parent project that is extended by the current project
11603 @item An expanded name whose prefix is imported/parent project name,
11604       and whose selector is a package name
11605 @end itemize
11606
11607 @noindent
11608 Example:
11609 @smallexample @c projectfile
11610 @group
11611    project Prj is
11612      for Source_Dirs use project'Source_Dirs & "units";
11613      for Source_Dirs use project'Source_Dirs & "test/drivers"
11614    end Prj;
11615 @end group
11616 @end smallexample
11617
11618 @noindent
11619 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11620 has the default value: an empty string list. After this declaration,
11621 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11622 After the second attribute declaration @code{Source_Dirs} is a string list of
11623 two elements: @code{"units"} and @code{"test/drivers"}.
11624
11625 Note: this example is for illustration only. In practice,
11626 the project file would contain only one attribute declaration:
11627
11628 @smallexample @c projectfile
11629    for Source_Dirs use ("units", "test/drivers");
11630 @end smallexample
11631
11632 @node Associative Array Attributes
11633 @subsection Associative Array Attributes
11634
11635 @noindent
11636 Some attributes are defined as @emph{associative arrays}. An associative
11637 array may be regarded as a function that takes a string as a parameter
11638 and delivers a string or string list value as its result.
11639
11640 Here are some examples of single associative array attribute associations:
11641
11642 @smallexample @c projectfile
11643    for Body ("main") use "Main.ada";
11644    for ^Switches^Switches^ ("main.ada")
11645        use ("^-v^-v^",
11646             "^-gnatv^-gnatv^");
11647    for ^Switches^Switches^ ("main.ada")
11648             use Builder'^Switches^Switches^ ("main.ada")
11649               & "^-g^-g^";
11650 @end smallexample
11651
11652 @noindent
11653 Like untyped variables and simple attributes, associative array attributes
11654 may be declared several times. Each declaration supplies a new value for the
11655 attribute, and replaces the previous setting.
11656
11657 @noindent
11658 An associative array attribute may be declared as a full associative array
11659 declaration, with the value of the same attribute in an imported or extended
11660 project.
11661
11662 @smallexample @c projectfile
11663    package Builder is
11664       for Default_Switches use Default.Builder'Default_Switches;
11665    end Builder;
11666 @end smallexample
11667
11668 @noindent
11669 In this example, @code{Default} must be either an project imported by the
11670 current project, or the project that the current project extends. If the
11671 attribute is in a package (in this case, in package @code{Builder}), the same
11672 package needs to be specified.
11673
11674 @noindent
11675 A full associative array declaration replaces any other declaration for the
11676 attribute, including other full associative array declaration. Single
11677 associative array associations may be declare after a full associative
11678 declaration, modifying the value for a single association of the attribute.
11679
11680 @node case Constructions
11681 @subsection @code{case} Constructions
11682
11683 @noindent
11684 A @code{case} construction is used in a project file to effect conditional
11685 behavior.
11686 Here is a typical example:
11687
11688 @smallexample @c projectfile
11689 @group
11690 project MyProj is
11691    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11692
11693    OS : OS_Type := external ("OS", "GNU/Linux");
11694 @end group
11695
11696 @group
11697    package Compiler is
11698      case OS is
11699        when "GNU/Linux" | "Unix" =>
11700          for ^Default_Switches^Default_Switches^ ("Ada")
11701              use ("^-gnath^-gnath^");
11702        when "NT" =>
11703          for ^Default_Switches^Default_Switches^ ("Ada")
11704              use ("^-gnatP^-gnatP^");
11705        when others =>
11706      end case;
11707    end Compiler;
11708 end MyProj;
11709 @end group
11710 @end smallexample
11711
11712 @noindent
11713 The syntax of a @code{case} construction is based on the Ada case statement
11714 (although there is no @code{null} construction for empty alternatives).
11715
11716 The case expression must a typed string variable.
11717 Each alternative comprises the reserved word @code{when}, either a list of
11718 literal strings separated by the @code{"|"} character or the reserved word
11719 @code{others},  and the @code{"=>"} token.
11720 Each literal string must belong to the string type that is the type of the
11721 case variable.
11722 An @code{others} alternative, if present, must occur last.
11723
11724 After each @code{=>}, there are zero or more constructions.  The only
11725 constructions allowed in a case construction are other case constructions and
11726 attribute declarations. String type declarations, variable declarations and
11727 package declarations are not allowed.
11728
11729 The value of the case variable is often given by an external reference
11730 (see @ref{External References in Project Files}).
11731
11732 @c ****************************************
11733 @c * Objects and Sources in Project Files *
11734 @c ****************************************
11735
11736 @node Objects and Sources in Project Files
11737 @section Objects and Sources in Project Files
11738
11739 @menu
11740 * Object Directory::
11741 * Exec Directory::
11742 * Source Directories::
11743 * Source File Names::
11744 @end menu
11745
11746 @noindent
11747 Each project has exactly one object directory and one or more source
11748 directories. The source directories must contain at least one source file,
11749 unless  the project file explicitly specifies that no source files are present
11750 (see @ref{Source File Names}).
11751
11752 @node Object Directory
11753 @subsection Object Directory
11754
11755 @noindent
11756 The object directory for a project is the directory containing the compiler's
11757 output (such as @file{ALI} files and object files) for the project's immediate
11758 sources.
11759
11760 The object directory is given by the value of the attribute @code{Object_Dir}
11761 in the project file.
11762
11763 @smallexample @c projectfile
11764    for Object_Dir use "objects";
11765 @end smallexample
11766
11767 @noindent
11768 The attribute @var{Object_Dir} has a string value, the path name of the object
11769 directory. The path name may be absolute or relative to the directory of the
11770 project file. This directory must already exist, and be readable and writable.
11771
11772 By default, when the attribute @code{Object_Dir} is not given an explicit value
11773 or when its value is the empty string, the object directory is the same as the
11774 directory containing the project file.
11775
11776 @node Exec Directory
11777 @subsection Exec Directory
11778
11779 @noindent
11780 The exec directory for a project is the directory containing the executables
11781 for the project's main subprograms.
11782
11783 The exec directory is given by the value of the attribute @code{Exec_Dir}
11784 in the project file.
11785
11786 @smallexample @c projectfile
11787    for Exec_Dir use "executables";
11788 @end smallexample
11789
11790 @noindent
11791 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11792 directory. The path name may be absolute or relative to the directory of the
11793 project file. This directory must already exist, and be writable.
11794
11795 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11796 or when its value is the empty string, the exec directory is the same as the
11797 object directory of the project file.
11798
11799 @node Source Directories
11800 @subsection Source Directories
11801
11802 @noindent
11803 The source directories of a project are specified by the project file
11804 attribute @code{Source_Dirs}.
11805
11806 This attribute's value is a string list. If the attribute is not given an
11807 explicit value, then there is only one source directory, the one where the
11808 project file resides.
11809
11810 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11811 as in
11812
11813 @smallexample @c projectfile
11814     for Source_Dirs use ();
11815 @end smallexample
11816
11817 @noindent
11818 indicates that the project contains no source files.
11819
11820 Otherwise, each string in the string list designates one or more
11821 source directories.
11822
11823 @smallexample @c projectfile
11824    for Source_Dirs use ("sources", "test/drivers");
11825 @end smallexample
11826
11827 @noindent
11828 If a string in the list ends with @code{"/**"},  then the directory whose path
11829 name precedes the two asterisks, as well as all its subdirectories
11830 (recursively), are source directories.
11831
11832 @smallexample @c projectfile
11833    for Source_Dirs use ("/system/sources/**");
11834 @end smallexample
11835
11836 @noindent
11837 Here the directory @code{/system/sources} and all of its subdirectories
11838 (recursively) are source directories.
11839
11840 To specify that the source directories are the directory of the project file
11841 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11842 @smallexample @c projectfile
11843    for Source_Dirs use ("./**");
11844 @end smallexample
11845
11846 @noindent
11847 Each of the source directories must exist and be readable.
11848
11849 @node Source File Names
11850 @subsection Source File Names
11851
11852 @noindent
11853 In a project that contains source files, their names may be specified by the
11854 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11855 (a string). Source file names never include any directory information.
11856
11857 If the attribute @code{Source_Files} is given an explicit value, then each
11858 element of the list is a source file name.
11859
11860 @smallexample @c projectfile
11861    for Source_Files use ("main.adb");
11862    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11863 @end smallexample
11864
11865 @noindent
11866 If the attribute @code{Source_Files} is not given an explicit value,
11867 but the attribute @code{Source_List_File} is given a string value,
11868 then the source file names are contained in the text file whose path name
11869 (absolute or relative to the directory of the project file) is the
11870 value of the attribute @code{Source_List_File}.
11871
11872 Each line in the file that is not empty or is not a comment
11873 contains a source file name.
11874
11875 @smallexample @c projectfile
11876    for Source_List_File use "source_list.txt";
11877 @end smallexample
11878
11879 @noindent
11880 By default, if neither the attribute @code{Source_Files} nor the attribute
11881 @code{Source_List_File} is given an explicit value, then each file in the
11882 source directories that conforms to the project's naming scheme
11883 (see @ref{Naming Schemes}) is an immediate source of the project.
11884
11885 A warning is issued if both attributes @code{Source_Files} and
11886 @code{Source_List_File} are given explicit values. In this case, the attribute
11887 @code{Source_Files} prevails.
11888
11889 Each source file name must be the name of one existing source file
11890 in one of the source directories.
11891
11892 A @code{Source_Files} attribute whose value is an empty list
11893 indicates that there are no source files in the project.
11894
11895 If the order of the source directories is known statically, that is if
11896 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11897 be several files with the same source file name. In this case, only the file
11898 in the first directory is considered as an immediate source of the project
11899 file. If the order of the source directories is not known statically, it is
11900 an error to have several files with the same source file name.
11901
11902 Projects can be specified to have no Ada source
11903 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11904 list, or the @code{"Ada"} may be absent from @code{Languages}:
11905
11906 @smallexample @c projectfile
11907    for Source_Dirs use ();
11908    for Source_Files use ();
11909    for Languages use ("C", "C++");
11910 @end smallexample
11911
11912 @noindent
11913 Otherwise, a project must contain at least one immediate source.
11914
11915 Projects with no source files are useful as template packages
11916 (see @ref{Packages in Project Files}) for other projects; in particular to
11917 define a package @code{Naming} (see @ref{Naming Schemes}).
11918
11919 @c ****************************
11920 @c * Importing Projects *
11921 @c ****************************
11922
11923 @node  Importing Projects
11924 @section Importing Projects
11925
11926 @noindent
11927 An immediate source of a project P may depend on source files that
11928 are neither immediate sources of P nor in the predefined library.
11929 To get this effect, P must @emph{import} the projects that contain the needed
11930 source files.
11931
11932 @smallexample @c projectfile
11933 @group
11934   with "project1", "utilities.gpr";
11935   with "/namings/apex.gpr";
11936   project Main is
11937     ...
11938 @end group
11939 @end smallexample
11940
11941 @noindent
11942 As can be seen in this example, the syntax for importing projects is similar
11943 to the syntax for importing compilation units in Ada. However, project files
11944 use literal strings instead of names, and the @code{with} clause identifies
11945 project files rather than packages.
11946
11947 Each literal string is the file name or path name (absolute or relative) of a
11948 project file. If a string is simply a file name, with no path, then its
11949 location is determined by the @emph{project path}:
11950
11951 @itemize @bullet
11952 @item
11953 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11954 then the project path includes all the directories in this
11955 ^environment variable^logical name^, plus the directory of the project file.
11956
11957 @item
11958 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11959 exist, then the project path contains only one directory, namely the one where
11960 the project file is located.
11961 @end itemize
11962
11963 @noindent
11964 If a relative pathname is used, as in
11965
11966 @smallexample @c projectfile
11967   with "tests/proj";
11968 @end smallexample
11969
11970 @noindent
11971 then the path is relative to the directory where the importing project file is
11972 located. Any symbolic link will be fully resolved in the directory
11973 of the importing project file before the imported project file is examined.
11974
11975 If the @code{with}'ed project file name does not have an extension,
11976 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11977 then the file name as specified in the @code{with} clause (no extension) will
11978 be used. In the above example, if a file @code{project1.gpr} is found, then it
11979 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11980 then it will be used; if neither file exists, this is an error.
11981
11982 A warning is issued if the name of the project file does not match the
11983 name of the project; this check is case insensitive.
11984
11985 Any source file that is an immediate source of the imported project can be
11986 used by the immediate sources of the importing project, transitively. Thus
11987 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11988 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11989 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11990 because if and when @code{B} ceases to import @code{C}, some sources in
11991 @code{A} will no longer compile.
11992
11993 A side effect of this capability is that normally cyclic dependencies are not
11994 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11995 is not allowed to import @code{A}. However, there are cases when cyclic
11996 dependencies would be beneficial. For these cases, another form of import
11997 between projects exists, the @code{limited with}: a project @code{A} that
11998 imports a project @code{B} with a straigh @code{with} may also be imported,
11999 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12000 to @code{A} include at least one @code{limited with}.
12001
12002 @smallexample @c 0projectfile
12003 with "../b/b.gpr";
12004 with "../c/c.gpr";
12005 project A is
12006 end A;
12007
12008 limited with "../a/a.gpr";
12009 project B is
12010 end B;
12011
12012 with "../d/d.gpr";
12013 project C is
12014 end C;
12015
12016 limited with "../a/a.gpr";
12017 project D is
12018 end D;
12019 @end smallexample
12020
12021 @noindent
12022 In the above legal example, there are two project cycles:
12023 @itemize @bullet
12024 @item A-> B-> A
12025 @item A -> C -> D -> A
12026 @end itemize
12027
12028 @noindent
12029 In each of these cycle there is one @code{limited with}: import of @code{A}
12030 from @code{B} and import of @code{A} from @code{D}.
12031
12032 The difference between straight @code{with} and @code{limited with} is that
12033 the name of a project imported with a @code{limited with} cannot be used in the
12034 project that imports it. In particular, its packages cannot be renamed and
12035 its variables cannot be referred to.
12036
12037 An exception to the above rules for @code{limited with} is that for the main
12038 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12039 @code{limited with} is equivalent to a straight @code{with}. For example,
12040 in the example above, projects @code{B} and @code{D} could not be main
12041 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12042 each have a @code{limited with} that is the only one in a cycle of importing
12043 projects.
12044
12045 @c *********************
12046 @c * Project Extension *
12047 @c *********************
12048
12049 @node Project Extension
12050 @section Project Extension
12051
12052 @noindent
12053 During development of a large system, it is sometimes necessary to use
12054 modified versions of some of the source files, without changing the original
12055 sources. This can be achieved through the @emph{project extension} facility.
12056
12057 @smallexample @c projectfile
12058    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12059 @end smallexample
12060
12061 @noindent
12062 A project extension declaration introduces an extending project
12063 (the @emph{child}) and a project being extended (the @emph{parent}).
12064
12065 By default, a child project inherits all the sources of its parent.
12066 However, inherited sources can be overridden: a unit in a parent is hidden
12067 by a unit of the same name in the child.
12068
12069 Inherited sources are considered to be sources (but not immediate sources)
12070 of the child project; see @ref{Project File Syntax}.
12071
12072 An inherited source file retains any switches specified in the parent project.
12073
12074 For example if the project @code{Utilities} contains the specification and the
12075 body of an Ada package @code{Util_IO}, then the project
12076 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12077 The original body of @code{Util_IO} will not be considered in program builds.
12078 However, the package specification will still be found in the project
12079 @code{Utilities}.
12080
12081 A child project can have only one parent but it may import any number of other
12082 projects.
12083
12084 A project is not allowed to import directly or indirectly at the same time a
12085 child project and any of its ancestors.
12086
12087 @c ****************************************
12088 @c * External References in Project Files *
12089 @c ****************************************
12090
12091 @node  External References in Project Files
12092 @section External References in Project Files
12093
12094 @noindent
12095 A project file may contain references to external variables; such references
12096 are called @emph{external references}.
12097
12098 An external variable is either defined as part of the environment (an
12099 environment variable in Unix, for example) or else specified on the command
12100 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12101 If both, then the command line value is used.
12102
12103 The value of an external reference is obtained by means of the built-in
12104 function @code{external}, which returns a string value.
12105 This function has two forms:
12106 @itemize @bullet
12107 @item @code{external (external_variable_name)}
12108 @item @code{external (external_variable_name, default_value)}
12109 @end itemize
12110
12111 @noindent
12112 Each parameter must be a string literal.  For example:
12113
12114 @smallexample @c projectfile
12115    external ("USER")
12116    external ("OS", "GNU/Linux")
12117 @end smallexample
12118
12119 @noindent
12120 In the form with one parameter, the function returns the value of
12121 the external variable given as parameter. If this name is not present in the
12122 environment, the function returns an empty string.
12123
12124 In the form with two string parameters, the second argument is
12125 the value returned when the variable given as the first argument is not
12126 present in the environment. In the example above, if @code{"OS"} is not
12127 the name of ^an environment variable^a logical name^ and is not passed on
12128 the command line, then the returned value is @code{"GNU/Linux"}.
12129
12130 An external reference may be part of a string expression or of a string
12131 list expression, and can therefore appear in a variable declaration or
12132 an attribute declaration.
12133
12134 @smallexample @c projectfile
12135 @group
12136    type Mode_Type is ("Debug", "Release");
12137    Mode : Mode_Type := external ("MODE");
12138    case Mode is
12139      when "Debug" =>
12140         ...
12141 @end group
12142 @end smallexample
12143
12144 @c *****************************
12145 @c * Packages in Project Files *
12146 @c *****************************
12147
12148 @node  Packages in Project Files
12149 @section Packages in Project Files
12150
12151 @noindent
12152 A @emph{package} defines the settings for project-aware tools within a
12153 project.
12154 For each such tool one can declare a package; the names for these
12155 packages are preset (see @ref{Packages}).
12156 A package may contain variable declarations, attribute declarations, and case
12157 constructions.
12158
12159 @smallexample @c projectfile
12160 @group
12161    project Proj is
12162       package Builder is  -- used by gnatmake
12163          for ^Default_Switches^Default_Switches^ ("Ada")
12164              use ("^-v^-v^",
12165                   "^-g^-g^");
12166       end Builder;
12167    end Proj;
12168 @end group
12169 @end smallexample
12170
12171 @noindent
12172 The syntax of package declarations mimics that of package in Ada.
12173
12174 Most of the packages have an attribute
12175 @code{^Default_Switches^Default_Switches^}.
12176 This attribute is an associative array, and its value is a string list.
12177 The index of the associative array is the name of a programming language (case
12178 insensitive). This attribute indicates the ^switch^switch^
12179 or ^switches^switches^ to be used
12180 with the corresponding tool.
12181
12182 Some packages also have another attribute, @code{^Switches^Switches^},
12183 an associative array whose value is a string list.
12184 The index is the name of a source file.
12185 This attribute indicates the ^switch^switch^
12186 or ^switches^switches^ to be used by the corresponding
12187 tool when dealing with this specific file.
12188
12189 Further information on these ^switch^switch^-related attributes is found in
12190 @ref{^Switches^Switches^ and Project Files}.
12191
12192 A package may be declared as a @emph{renaming} of another package; e.g., from
12193 the project file for an imported project.
12194
12195 @smallexample @c projectfile
12196 @group
12197   with "/global/apex.gpr";
12198   project Example is
12199     package Naming renames Apex.Naming;
12200     ...
12201   end Example;
12202 @end group
12203 @end smallexample
12204
12205 @noindent
12206 Packages that are renamed in other project files often come from project files
12207 that have no sources: they are just used as templates. Any modification in the
12208 template will be reflected automatically in all the project files that rename
12209 a package from the template.
12210
12211 In addition to the tool-oriented packages, you can also declare a package
12212 named @code{Naming} to establish specialized source file naming conventions
12213 (see @ref{Naming Schemes}).
12214
12215 @c ************************************
12216 @c * Variables from Imported Projects *
12217 @c ************************************
12218
12219 @node Variables from Imported Projects
12220 @section Variables from Imported Projects
12221
12222 @noindent
12223 An attribute or variable defined in an imported or parent project can
12224 be used in expressions in the importing / extending project.
12225 Such an attribute or variable is denoted by an expanded name whose prefix
12226 is either the name of the project or the expanded name of a package within
12227 a project.
12228
12229 @smallexample @c projectfile
12230 @group
12231   with "imported";
12232   project Main extends "base" is
12233      Var1 := Imported.Var;
12234      Var2 := Base.Var & ".new";
12235 @end group
12236
12237 @group
12238      package Builder is
12239         for ^Default_Switches^Default_Switches^ ("Ada")
12240             use Imported.Builder.Ada_^Switches^Switches^ &
12241                 "^-gnatg^-gnatg^" &
12242                 "^-v^-v^";
12243      end Builder;
12244 @end group
12245
12246 @group
12247      package Compiler is
12248         for ^Default_Switches^Default_Switches^ ("Ada")
12249             use Base.Compiler.Ada_^Switches^Switches^;
12250      end Compiler;
12251   end Main;
12252 @end group
12253 @end smallexample
12254
12255 @noindent
12256 In this example:
12257
12258 @itemize @bullet
12259 @item
12260 The value of @code{Var1} is a copy of the variable @code{Var} defined
12261 in the project file @file{"imported.gpr"}
12262 @item
12263 the value of @code{Var2} is a copy of the value of variable @code{Var}
12264 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12265 @item
12266 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12267 @code{Builder} is a string list that includes in its value a copy of the value
12268 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12269 in project file @file{imported.gpr} plus two new elements:
12270 @option{"^-gnatg^-gnatg^"}
12271 and @option{"^-v^-v^"};
12272 @item
12273 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12274 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12275 defined in the @code{Compiler} package in project file @file{base.gpr},
12276 the project being extended.
12277 @end itemize
12278
12279 @c ******************
12280 @c * Naming Schemes *
12281 @c ******************
12282
12283 @node  Naming Schemes
12284 @section Naming Schemes
12285
12286 @noindent
12287 Sometimes an Ada software system is ported from a foreign compilation
12288 environment to GNAT, and the file names do not use the default GNAT
12289 conventions. Instead of changing all the file names (which for a variety
12290 of reasons might not be possible), you can define the relevant file
12291 naming scheme in the @code{Naming} package in your project file.
12292
12293 @noindent
12294 Note that the use of pragmas described in @ref{Alternative
12295 File Naming Schemes} by mean of a configuration pragmas file is not
12296 supported when using project files. You must use the features described
12297 in this paragraph. You can however use specify other configuration
12298 pragmas (see @ref{Specifying Configuration Pragmas}).
12299
12300 @ifclear vms
12301 For example, the following
12302 package models the Apex file naming rules:
12303
12304 @smallexample @c projectfile
12305 @group
12306   package Naming is
12307     for Casing               use "lowercase";
12308     for Dot_Replacement      use ".";
12309     for Spec_Suffix ("Ada")  use ".1.ada";
12310     for Body_Suffix ("Ada")  use ".2.ada";
12311   end Naming;
12312 @end group
12313 @end smallexample
12314 @end ifclear
12315
12316 @ifset vms
12317 For example, the following package models the DEC Ada file naming rules:
12318
12319 @smallexample @c projectfile
12320 @group
12321   package Naming is
12322     for Casing               use "lowercase";
12323     for Dot_Replacement      use "__";
12324     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12325     for Body_Suffix ("Ada")  use ".^ada^ada^";
12326   end Naming;
12327 @end group
12328 @end smallexample
12329
12330 @noindent
12331 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12332 names in lower case)
12333 @end ifset
12334
12335 @noindent
12336 You can define the following attributes in package @code{Naming}:
12337
12338 @table @code
12339
12340 @item @var{Casing}
12341 This must be a string with one of the three values @code{"lowercase"},
12342 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12343
12344 @noindent
12345 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12346
12347 @item @var{Dot_Replacement}
12348 This must be a string whose value satisfies the following conditions:
12349
12350 @itemize @bullet
12351 @item It must not be empty
12352 @item It cannot start or end with an alphanumeric character
12353 @item It cannot be a single underscore
12354 @item It cannot start with an underscore followed by an alphanumeric
12355 @item It cannot contain a dot @code{'.'} except if the entire string
12356 is @code{"."}
12357 @end itemize
12358
12359 @noindent
12360 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12361
12362 @item @var{Spec_Suffix}
12363 This is an associative array (indexed by the programming language name, case
12364 insensitive) whose value is a string that must satisfy the following
12365 conditions:
12366
12367 @itemize @bullet
12368 @item It must not be empty
12369 @item It must include at least one dot
12370 @end itemize
12371 @noindent
12372 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12373 @code{"^.ads^.ADS^"}.
12374
12375 @item @var{Body_Suffix}
12376 This is an associative array (indexed by the programming language name, case
12377 insensitive) whose value is a string that must satisfy the following
12378 conditions:
12379
12380 @itemize @bullet
12381 @item It must not be empty
12382 @item It must include at least one dot
12383 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12384 @end itemize
12385 @noindent
12386 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12387 @code{"^.adb^.ADB^"}.
12388
12389 @item @var{Separate_Suffix}
12390 This must be a string whose value satisfies the same conditions as
12391 @code{Body_Suffix}.
12392
12393 @noindent
12394 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12395 value as @code{Body_Suffix ("Ada")}.
12396
12397 @item @var{Spec}
12398 @noindent
12399 You can use the associative array attribute @code{Spec}  to define
12400 the source file name for an individual Ada compilation unit's spec. The array
12401 index must be a string literal that identifies the Ada unit (case insensitive).
12402 The value of this attribute must be a string that identifies the file that
12403 contains this unit's spec (case sensitive or insensitive depending on the
12404 operating system).
12405
12406 @smallexample @c projectfile
12407    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12408 @end smallexample
12409
12410 @item @var{Body}
12411
12412 You can use the associative array attribute @code{Body} to
12413 define the source file name for an individual Ada compilation unit's body
12414 (possibly a subunit).  The array index must be a string literal that identifies
12415 the Ada unit (case insensitive).  The value of this attribute must be a string
12416 that identifies the file that contains this unit's body or subunit (case
12417 sensitive or insensitive depending on the operating system).
12418
12419 @smallexample @c projectfile
12420    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12421 @end smallexample
12422 @end table
12423
12424 @c ********************
12425 @c * Library Projects *
12426 @c ********************
12427
12428 @node Library Projects
12429 @section Library Projects
12430
12431 @noindent
12432 @emph{Library projects} are projects whose object code is placed in a library.
12433 (Note that this facility is not yet supported on all platforms)
12434
12435 To create a library project, you need to define in its project file
12436 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12437 Additionally, you may define the library-related attributes
12438 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12439 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12440
12441 The @code{Library_Name} attribute has a string value. There is no restriction
12442 on the name of a library. It is the responsability of the developer to
12443 choose a name that will be accepted by the platform. It is recommanded to
12444 choose names that could be Ada identifiers; such names are almost guaranteed
12445 to be acceptable on all platforms.
12446
12447 The @code{Library_Dir} attribute has a string value that designates the path
12448 (absolute or relative) of the directory where the library will reside.
12449 It must designate an existing directory, and this directory must be
12450 different from the project's object directory. It also needs to be writable.
12451 The directory should only be used for one library; the reason is that all
12452 files contained in this directory may be deleted by the Project Manager.
12453
12454 If both @code{Library_Name} and @code{Library_Dir} are specified and
12455 are legal, then the project file defines a library project.  The optional
12456 library-related attributes are checked only for such project files.
12457
12458 The @code{Library_Kind} attribute has a string value that must be one of the
12459 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12460 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12461 attribute is not specified, the library is a static library, that is
12462 an archive of object files that can be potentially linked into an
12463 static executable. Otherwise, the library may be dynamic or
12464 relocatable, that is a library that is loaded only at the start of execution.
12465
12466 If you need to build both a static and a dynamic library, you should use two
12467 different object directories, since in some cases some extra code needs to
12468 be generated for the latter. For such cases, it is recommended to either use
12469 two different project files, or a single one which uses external variables
12470 to indicate what kind of library should be build.
12471
12472 The @code{Library_Version} attribute has a string value whose interpretation
12473 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12474 used only for dynamic/relocatable libraries as the internal name of the
12475 library (the @code{"soname"}). If the library file name (built from the
12476 @code{Library_Name}) is different from the @code{Library_Version}, then the
12477 library file will be a symbolic link to the actual file whose name will be
12478 @code{Library_Version}.
12479
12480 Example (on Unix):
12481
12482 @smallexample @c projectfile
12483 @group
12484 project Plib is
12485
12486    Version := "1";
12487
12488    for Library_Dir use "lib_dir";
12489    for Library_Name use "dummy";
12490    for Library_Kind use "relocatable";
12491    for Library_Version use "libdummy.so." & Version;
12492
12493 end Plib;
12494 @end group
12495 @end smallexample
12496
12497 @noindent
12498 Directory @file{lib_dir} will contain the internal library file whose name
12499 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12500 @file{libdummy.so.1}.
12501
12502 When @command{gnatmake} detects that a project file
12503 is a library project file, it will check all immediate sources of the project
12504 and rebuild the library if any of the sources have been recompiled.
12505
12506 Standard project files can import library project files. In such cases,
12507 the libraries will only be rebuild if some of its sources are recompiled
12508 because they are in the closure of some other source in an importing project.
12509 Sources of the library project files that are not in such a closure will
12510 not be checked, unless the full library is checked, because one of its sources
12511 needs to be recompiled.
12512
12513 For instance, assume the project file @code{A} imports the library project file
12514 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12515 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12516 @file{l2.ads}, @file{l2.adb}.
12517
12518 If @file{l1.adb} has been modified, then the library associated with @code{L}
12519 will be rebuild when compiling all the immediate sources of @code{A} only
12520 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12521 @code{"with L1;"}.
12522
12523 To be sure that all the sources in the library associated with @code{L} are
12524 up to date, and that all the sources of parject @code{A} are also up to date,
12525 the following two commands needs to be used:
12526
12527 @smallexample
12528 gnatmake -Pl.gpr
12529 gnatmake -Pa.gpr
12530 @end smallexample
12531
12532 When a library is built or rebuilt, an attempt is made first to delete all
12533 files in the library directory.
12534 All @file{ALI} files will also be copied from the object directory to the
12535 library directory. To build executables, @command{gnatmake} will use the
12536 library rather than the individual object files.
12537
12538
12539 @c **********************************************
12540 @c * Using Third-Party Libraries through Projects
12541 @c **********************************************
12542 @node Using Third-Party Libraries through Projects
12543 @section Using Third-Party Libraries through Projects
12544
12545 Whether you are exporting your own library to make it available to
12546 clients, or you are using a library provided by a third party, it is
12547 convenient to have project files that automatically set the correct
12548 command line switches for the compiler and linker.
12549
12550 Such project files are very similar to the library project files;
12551 @xref{Library Projects}. The only difference is that you set the
12552 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12553 directories where, respectively, the sources and the read-only ALI files have
12554 been installed.
12555
12556 If you need to interface with a set of libraries, as opposed to a
12557 single one, you need to create one library project for each of the
12558 libraries. In addition, a top-level project that imports all these
12559 library projects should be provided, so that the user of your library
12560 has a single @code{with} clause to add to his own projects.
12561
12562 For instance, let's assume you are providing two static libraries
12563 @file{liba.a} and @file{libb.a}. The user needs to link with
12564 both of these libraries. Each of these is associated with its
12565 own set of header files. Let's assume furthermore that all the
12566 header files for the two libraries have been installed in the same
12567 directory @file{headers}. The @file{ALI} files are found in the same
12568 @file{headers} directory.
12569
12570 In this case, you should provide the following three projects:
12571
12572 @smallexample @c projectfile
12573 @group
12574 with "liba", "libb";
12575 project My_Library is
12576   for Source_Dirs use ("headers");
12577   for Object_Dir  use "headers";
12578 end My_Library;
12579 @end group
12580
12581 @group
12582 project Liba is
12583    for Source_Dirs use ();
12584    for Library_Dir use "lib";
12585    for Library_Name use "a";
12586    for Library_Kind use "static";
12587 end Liba;
12588 @end group
12589
12590 @group
12591 project Libb is
12592    for Source_Dirs use ();
12593    for Library_Dir use "lib";
12594    for Library_Name use "b";
12595    for Library_Kind use "static";
12596 end Libb;
12597 @end group
12598 @end smallexample
12599
12600 @c *******************************
12601 @c * Stand-alone Library Projects *
12602 @c *******************************
12603
12604 @node Stand-alone Library Projects
12605 @section Stand-alone Library Projects
12606
12607 @noindent
12608 A Stand-alone Library is a library that contains the necessary code to
12609 elaborate the Ada units that are included in the library. A Stand-alone
12610 Library is suitable to be used in an executable when the main is not
12611 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12612 subprogram.
12613
12614 A Stand-alone Library Project is a Library Project where the library is
12615 a Stand-alone Library.
12616
12617 To be a Stand-alone Library Project, in addition to the two attributes
12618 that make a project a Library Project (@code{Library_Name} and
12619 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12620 @code{Library_Interface} must be defined.
12621
12622 @smallexample @c projectfile
12623 @group
12624    for Library_Dir use "lib_dir";
12625    for Library_Name use "dummy";
12626    for Library_Interface use ("int1", "int1.child");
12627 @end group
12628 @end smallexample
12629
12630 Attribute @code{Library_Interface} has a non empty string list value,
12631 each string in the list designating a unit contained in an immediate source
12632 of the project file.
12633
12634 When a Stand-alone Library is built, first the binder is invoked to build
12635 a package whose name depends on the library name
12636 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12637 This binder-generated package includes initialization and
12638 finalization procedures whose
12639 names depend on the library name (dummyinit and dummyfinal in the example
12640 above). The object corresponding to this package is included in the library.
12641
12642 A dynamic or relocatable Stand-alone Library is automatically initialized
12643 if automatic initialization of Stand-alone Libraries is supported on the
12644 platform and if attribute @code{Library_Auto_Init} is not specified or
12645 is specified with the value "true". A static Stand-alone Library is never
12646 automatically initialized.
12647
12648 Single string attribute @code{Library_Auto_Init} may be specified with only
12649 two possible values: "false" or "true" (case-insensitive). Specifying
12650 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12651 initialization of dynamic or relocatable libraries.
12652
12653 When a non automatically initialized Stand-alone Library is used
12654 in an executable, its initialization procedure must be called before
12655 any service of the library is used.
12656 When the main subprogram is in Ada, it may mean that the initialization
12657 procedure has to be called during elaboration of another package.
12658
12659 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12660 (those that are listed in attribute @code{Library_Interface}) are copied to
12661 the Library Directory. As a consequence, only the Interface Units may be
12662 imported from Ada units outside of the library. If other units are imported,
12663 the binding phase will fail.
12664
12665 When a Stand-Alone Library is bound, the switches that are specified in
12666 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12667 used in the call to @command{gnatbind}.
12668
12669 The string list attribute @code{Library_Options} may be used to specified
12670 additional switches to the call to @command{gcc} to link the library.
12671
12672 The attribute @code{Library_Src_Dir}, may be specified for a
12673 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12674 single string value. Its value must be the path (absolute or relative to the
12675 project directory) of an existing directory. This directory cannot be the
12676 object directory or one of the source directories, but it can be the same as
12677 the library directory. The sources of the Interface
12678 Units of the library, necessary to an Ada client of the library, will be
12679 copied to the designated directory, called Interface Copy directory.
12680 These sources includes the specs of the Interface Units, but they may also
12681 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12682 are used, or when there is a generic units in the spec. Before the sources
12683 are copied to the Interface Copy directory, an attempt is made to delete all
12684 files in the Interface Copy directory.
12685
12686 @c *************************************
12687 @c * Switches Related to Project Files *
12688 @c *************************************
12689 @node Switches Related to Project Files
12690 @section Switches Related to Project Files
12691
12692 @noindent
12693 The following switches are used by GNAT tools that support project files:
12694
12695 @table @option
12696
12697 @item ^-P^/PROJECT_FILE=^@var{project}
12698 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12699 Indicates the name of a project file. This project file will be parsed with
12700 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12701 if any, and using the external references indicated
12702 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12703 @ifclear vms
12704 There may zero, one or more spaces between @option{-P} and @var{project}.
12705 @end ifclear
12706
12707 @noindent
12708 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12709
12710 @noindent
12711 Since the Project Manager parses the project file only after all the switches
12712 on the command line are checked, the order of the switches
12713 @option{^-P^/PROJECT_FILE^},
12714 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12715 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12716
12717 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12718 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12719 Indicates that external variable @var{name} has the value @var{value}.
12720 The Project Manager will use this value for occurrences of
12721 @code{external(name)} when parsing the project file.
12722
12723 @ifclear vms
12724 @noindent
12725 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12726 put between quotes.
12727 @smallexample
12728   -XOS=NT
12729   -X"user=John Doe"
12730 @end smallexample
12731 @end ifclear
12732
12733 @noindent
12734 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12735 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12736 @var{name}, only the last one is used.
12737
12738 @noindent
12739 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12740 takes precedence over the value of the same name in the environment.
12741
12742 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12743 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12744 @c Previous line uses code vs option command, to stay less than 80 chars
12745 Indicates the verbosity of the parsing of GNAT project files.
12746
12747 @ifclear vms
12748 @option{-vP0} means Default;
12749 @option{-vP1} means Medium;
12750 @option{-vP2} means High.
12751 @end ifclear
12752
12753 @ifset vms
12754 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12755 HIGH.
12756 @end ifset
12757
12758 @noindent
12759 The default is ^Default^DEFAULT^: no output for syntactically correct
12760 project files.
12761 @noindent
12762 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12763 only the last one is used.
12764
12765 @end table
12766
12767 @c **********************************
12768 @c * Tools Supporting Project Files *
12769 @c **********************************
12770
12771 @node  Tools Supporting Project Files
12772 @section Tools Supporting Project Files
12773
12774 @menu
12775 * gnatmake and Project Files::
12776 * The GNAT Driver and Project Files::
12777 @ifclear vms
12778 * Glide and Project Files::
12779 @end ifclear
12780 @end menu
12781
12782 @node gnatmake and Project Files
12783 @subsection gnatmake and Project Files
12784
12785 @noindent
12786 This section covers several topics related to @command{gnatmake} and
12787 project files: defining ^switches^switches^ for @command{gnatmake}
12788 and for the tools that it invokes; specifying configuration pragmas;
12789 the use of the @code{Main} attribute; building and rebuilding library project
12790 files.
12791
12792 @menu
12793 * ^Switches^Switches^ and Project Files::
12794 * Specifying Configuration Pragmas::
12795 * Project Files and Main Subprograms::
12796 * Library Project Files::
12797 @end menu
12798
12799 @node ^Switches^Switches^ and Project Files
12800 @subsubsection ^Switches^Switches^ and Project Files
12801
12802 @ifset vms
12803 It is not currently possible to specify VMS style qualifiers in the project
12804 files; only Unix style ^switches^switches^ may be specified.
12805 @end ifset
12806
12807 @noindent
12808 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12809 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12810 attribute, a @code{^Switches^Switches^} attribute, or both;
12811 as their names imply, these ^switch^switch^-related
12812 attributes affect the ^switches^switches^ that are used for each of these GNAT
12813 components when
12814 @command{gnatmake} is invoked.  As will be explained below, these
12815 component-specific ^switches^switches^ precede
12816 the ^switches^switches^ provided on the @command{gnatmake} command line.
12817
12818 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12819 array indexed by language name (case insensitive) whose value is a string list.
12820 For example:
12821
12822 @smallexample @c projectfile
12823 @group
12824 package Compiler is
12825   for ^Default_Switches^Default_Switches^ ("Ada")
12826       use ("^-gnaty^-gnaty^",
12827            "^-v^-v^");
12828 end Compiler;
12829 @end group
12830 @end smallexample
12831
12832 @noindent
12833 The @code{^Switches^Switches^} attribute is also an associative array,
12834 indexed by a file name (which may or may not be case sensitive, depending
12835 on the operating system) whose value is a string list.  For example:
12836
12837 @smallexample @c projectfile
12838 @group
12839 package Builder is
12840    for ^Switches^Switches^ ("main1.adb")
12841        use ("^-O2^-O2^");
12842    for ^Switches^Switches^ ("main2.adb")
12843        use ("^-g^-g^");
12844 end Builder;
12845 @end group
12846 @end smallexample
12847
12848 @noindent
12849 For the @code{Builder} package, the file names must designate source files
12850 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12851 file names must designate @file{ALI} or source files for main subprograms.
12852 In each case just the file name without an explicit extension is acceptable.
12853
12854 For each tool used in a program build (@command{gnatmake}, the compiler, the
12855 binder, and the linker), the corresponding package @dfn{contributes} a set of
12856 ^switches^switches^ for each file on which the tool is invoked, based on the
12857 ^switch^switch^-related attributes defined in the package.
12858 In particular, the ^switches^switches^
12859 that each of these packages contributes for a given file @var{f} comprise:
12860
12861 @itemize @bullet
12862 @item
12863 the value of attribute @code{^Switches^Switches^ (@var{f})},
12864 if it is specified in the package for the given file,
12865 @item
12866 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12867 if it is specified in the package.
12868 @end itemize
12869
12870 @noindent
12871 If neither of these attributes is defined in the package, then the package does
12872 not contribute any ^switches^switches^ for the given file.
12873
12874 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12875 two sets, in the following order: those contributed for the file
12876 by the @code{Builder} package;
12877 and the switches passed on the command line.
12878
12879 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12880 the ^switches^switches^ passed to the tool comprise three sets,
12881 in the following order:
12882
12883 @enumerate
12884 @item
12885 the applicable ^switches^switches^ contributed for the file
12886 by the @code{Builder} package in the project file supplied on the command line;
12887
12888 @item
12889 those contributed for the file by the package (in the relevant project file --
12890 see below) corresponding to the tool; and
12891
12892 @item
12893 the applicable switches passed on the command line.
12894 @end enumerate
12895
12896 @noindent
12897 The term @emph{applicable ^switches^switches^} reflects the fact that
12898 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12899 tools, depending on the individual ^switch^switch^.
12900
12901 @command{gnatmake} may invoke the compiler on source files from different
12902 projects. The Project Manager will use the appropriate project file to
12903 determine the @code{Compiler} package for each source file being compiled.
12904 Likewise for the @code{Binder} and @code{Linker} packages.
12905
12906 As an example, consider the following package in a project file:
12907
12908 @smallexample @c projectfile
12909 @group
12910 project Proj1 is
12911    package Compiler is
12912       for ^Default_Switches^Default_Switches^ ("Ada")
12913           use ("^-g^-g^");
12914       for ^Switches^Switches^ ("a.adb")
12915           use ("^-O1^-O1^");
12916       for ^Switches^Switches^ ("b.adb")
12917           use ("^-O2^-O2^",
12918                "^-gnaty^-gnaty^");
12919    end Compiler;
12920 end Proj1;
12921 @end group
12922 @end smallexample
12923
12924 @noindent
12925 If @command{gnatmake} is invoked with this project file, and it needs to
12926 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12927 @file{a.adb} will be compiled with the ^switch^switch^
12928 @option{^-O1^-O1^},
12929 @file{b.adb} with ^switches^switches^
12930 @option{^-O2^-O2^}
12931 and @option{^-gnaty^-gnaty^},
12932 and @file{c.adb} with @option{^-g^-g^}.
12933
12934 The following example illustrates the ordering of the ^switches^switches^
12935 contributed by different packages:
12936
12937 @smallexample @c projectfile
12938 @group
12939 project Proj2 is
12940    package Builder is
12941       for ^Switches^Switches^ ("main.adb")
12942           use ("^-g^-g^",
12943                "^-O1^-)1^",
12944                "^-f^-f^");
12945    end Builder;
12946 @end group
12947
12948 @group
12949    package Compiler is
12950       for ^Switches^Switches^ ("main.adb")
12951           use ("^-O2^-O2^");
12952    end Compiler;
12953 end Proj2;
12954 @end group
12955 @end smallexample
12956
12957 @noindent
12958 If you issue the command:
12959
12960 @smallexample
12961     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12962 @end smallexample
12963
12964 @noindent
12965 then the compiler will be invoked on @file{main.adb} with the following
12966 sequence of ^switches^switches^
12967
12968 @smallexample
12969    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12970 @end smallexample
12971
12972 with the last @option{^-O^-O^}
12973 ^switch^switch^ having precedence over the earlier ones;
12974 several other ^switches^switches^
12975 (such as @option{^-c^-c^}) are added implicitly.
12976
12977 The ^switches^switches^
12978 @option{^-g^-g^}
12979 and @option{^-O1^-O1^} are contributed by package
12980 @code{Builder},  @option{^-O2^-O2^} is contributed
12981 by the package @code{Compiler}
12982 and @option{^-O0^-O0^} comes from the command line.
12983
12984 The @option{^-g^-g^}
12985 ^switch^switch^ will also be passed in the invocation of
12986 @command{Gnatlink.}
12987
12988 A final example illustrates switch contributions from packages in different
12989 project files:
12990
12991 @smallexample @c projectfile
12992 @group
12993 project Proj3 is
12994    for Source_Files use ("pack.ads", "pack.adb");
12995    package Compiler is
12996       for ^Default_Switches^Default_Switches^ ("Ada")
12997           use ("^-gnata^-gnata^");
12998    end Compiler;
12999 end Proj3;
13000 @end group
13001
13002 @group
13003 with "Proj3";
13004 project Proj4 is
13005    for Source_Files use ("foo_main.adb", "bar_main.adb");
13006    package Builder is
13007       for ^Switches^Switches^ ("foo_main.adb")
13008           use ("^-s^-s^",
13009                "^-g^-g^");
13010    end Builder;
13011 end Proj4;
13012 @end group
13013
13014 @group
13015 -- Ada source file:
13016 with Pack;
13017 procedure Foo_Main is
13018    ...
13019 end Foo_Main;
13020 @end group
13021 @end smallexample
13022
13023 If the command is
13024 @smallexample
13025 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13026 @end smallexample
13027
13028 @noindent
13029 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13030 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13031 @option{^-gnato^-gnato^} (passed on the command line).
13032 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13033 are @option{^-g^-g^} from @code{Proj4.Builder},
13034 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13035 and @option{^-gnato^-gnato^} from the command line.
13036
13037 @noindent
13038 When using @command{gnatmake} with project files, some ^switches^switches^ or
13039 arguments may be expressed as relative paths. As the working directory where
13040 compilation occurs may change, these relative paths are converted to absolute
13041 paths. For the ^switches^switches^ found in a project file, the relative paths
13042 are relative to the project file directory, for the switches on the command
13043 line, they are relative to the directory where @command{gnatmake} is invoked.
13044 The ^switches^switches^ for which this occurs are:
13045 ^-I^-I^,
13046 ^-A^-A^,
13047 ^-L^-L^,
13048 ^-aO^-aO^,
13049 ^-aL^-aL^,
13050 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13051 ^switch^switch^
13052 ^-o^-o^, object files specified in package @code{Linker} or after
13053 -largs on the command line). The exception to this rule is the ^switch^switch^
13054 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13055
13056 @node Specifying Configuration Pragmas
13057 @subsubsection Specifying Configuration Pragmas
13058
13059 When using @command{gnatmake} with project files, if there exists a file
13060 @file{gnat.adc} that contains configuration pragmas, this file will be
13061 ignored.
13062
13063 Configuration pragmas can be defined by means of the following attributes in
13064 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13065 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13066
13067 Both these attributes are single string attributes. Their values is the path
13068 name of a file containing configuration pragmas. If a path name is relative,
13069 then it is relative to the project directory of the project file where the
13070 attribute is defined.
13071
13072 When compiling a source, the configuration pragmas used are, in order,
13073 those listed in the file designated by attribute
13074 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13075 project file, if it is specified, and those listed in the file designated by
13076 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13077 the project file of the source, if it exists.
13078
13079 @node Project Files and Main Subprograms
13080 @subsubsection Project Files and Main Subprograms
13081
13082 @noindent
13083 When using a project file, you can invoke @command{gnatmake}
13084 with one or several main subprograms, by specifying their source files on the
13085 command line.
13086
13087 @smallexample
13088     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13089 @end smallexample
13090
13091 @noindent
13092 Each of these needs to be a source file of the same project, except
13093 when the switch ^-u^/UNIQUE^ is used.
13094
13095 @noindent
13096 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13097 same project, one of the project in the tree rooted at the project specified
13098 on the command line. The package @code{Builder} of this common project, the
13099 "main project" is the one that is considered by @command{gnatmake}.
13100
13101 @noindent
13102 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13103 imported directly or indirectly by the project specified on the command line.
13104 Note that if such a source file is not part of the project specified on the
13105 command line, the ^switches^switches^ found in package @code{Builder} of the
13106 project specified on the command line, if any, that are transmitted
13107 to the compiler will still be used, not those found in the project file of
13108 the source file.
13109
13110 @noindent
13111 When using a project file, you can also invoke @command{gnatmake} without
13112 explicitly specifying any main, and the effect depends on whether you have
13113 defined the @code{Main} attribute.  This attribute has a string list value,
13114 where each element in the list is the name of a source file (the file
13115 extension is optional) that contains a unit that can be a main subprogram.
13116
13117 If the @code{Main} attribute is defined in a project file as a non-empty
13118 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13119 line, then invoking @command{gnatmake} with this project file but without any
13120 main on the command line is equivalent to invoking @command{gnatmake} with all
13121 the file names in the @code{Main} attribute on the command line.
13122
13123 Example:
13124 @smallexample @c projectfile
13125 @group
13126    project Prj is
13127       for Main use ("main1", "main2", "main3");
13128    end Prj;
13129 @end group
13130 @end smallexample
13131
13132 @noindent
13133 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13134 is equivalent to
13135 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13136
13137 When the project attribute @code{Main} is not specified, or is specified
13138 as an empty string list, or when the switch @option{-u} is used on the command
13139 line, then invoking @command{gnatmake} with no main on the command line will
13140 result in all immediate sources of the project file being checked, and
13141 potentially recompiled. Depending on the presence of the switch @option{-u},
13142 sources from other project files on which the immediate sources of the main
13143 project file depend are also checked and potentially recompiled. In other
13144 words, the @option{-u} switch is applied to all of the immediate sources of the
13145 main project file.
13146
13147 When no main is specified on the command line and attribute @code{Main} exists
13148 and includes several mains, or when several mains are specified on the
13149 command line, the default ^switches^switches^ in package @code{Builder} will
13150 be used for all mains, even if there are specific ^switches^switches^
13151 specified for one or several mains.
13152
13153 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13154 the specific ^switches^switches^ for each main, if they are specified.
13155
13156 @node Library Project Files
13157 @subsubsection Library Project Files
13158
13159 @noindent
13160 When @command{gnatmake} is invoked with a main project file that is a library
13161 project file, it is not allowed to specify one or more mains on the command
13162 line.
13163
13164 @noindent
13165 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13166 ^-l^/ACTION=LINK^ have special meanings.
13167
13168 @itemize @bullet
13169 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13170 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13171 library.
13172
13173 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13174 to @command{gnatmake} that the binder generated file should be compiled
13175 (in the case of a stand-alone library) and that the library should be built.
13176
13177 @end itemize
13178
13179 @node The GNAT Driver and Project Files
13180 @subsection The GNAT Driver and Project Files
13181
13182 @noindent
13183 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13184 are project-aware:
13185 @command{^gnatbind^gnatbind^},
13186 @command{^gnatfind^gnatfind^},
13187 @command{^gnatlink^gnatlink^},
13188 @command{^gnatls^gnatls^},
13189 @command{^gnatelim^gnatelim^},
13190 @command{^gnatpp^gnatpp^},
13191 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13192 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13193 They must be invoked through the @command{gnat} driver.
13194
13195 The @command{gnat} driver is a front-end that accepts a number of commands and
13196 call the corresponding tool. It has been designed initially for VMS to convert
13197 VMS style qualifiers to Unix style switches, but it is now available to all
13198 the GNAT supported platforms.
13199
13200 On non VMS platforms, the @command{gnat} driver accepts the following commands
13201 (case insensitive):
13202
13203 @itemize @bullet
13204 @item
13205 BIND to invoke @command{^gnatbind^gnatbind^}
13206 @item
13207 CHOP to invoke @command{^gnatchop^gnatchop^}
13208 @item
13209 CLEAN to invoke @command{^gnatclean^gnatclean^}
13210 @item
13211 COMP or COMPILE to invoke the compiler
13212 @item
13213 ELIM to invoke @command{^gnatelim^gnatelim^}
13214 @item
13215 FIND to invoke @command{^gnatfind^gnatfind^}
13216 @item
13217 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13218 @item
13219 LINK to invoke @command{^gnatlink^gnatlink^}
13220 @item
13221 LS or LIST to invoke @command{^gnatls^gnatls^}
13222 @item
13223 MAKE to invoke @command{^gnatmake^gnatmake^}
13224 @item
13225 NAME to invoke @command{^gnatname^gnatname^}
13226 @item
13227 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13228 @item
13229 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13230 @item
13231 STUB to invoke @command{^gnatstub^gnatstub^}
13232 @item
13233 XREF to invoke @command{^gnatxref^gnatxref^}
13234 @end itemize
13235
13236 @noindent
13237 (note that the compiler is invoked using the command
13238 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13239
13240 @noindent
13241 On non VMS platforms, between @command{gnat} and the command, two
13242 special switches may be used:
13243
13244 @itemize @bullet
13245 @item
13246 @command{-v} to display the invocation of the tool.
13247 @item
13248 @command{-dn} to prevent the @command{gnat} driver from removing
13249 the temporary files it has created. These temporary files are
13250 configuration files and temporary file list files.
13251 @end itemize
13252
13253 @noindent
13254 The command may be followed by switches and arguments for the invoked
13255 tool.
13256
13257 @smallexample
13258   gnat bind -C main.ali
13259   gnat ls -a main
13260   gnat chop foo.txt
13261 @end smallexample
13262
13263 @noindent
13264 Switches may also be put in text files, one switch per line, and the text
13265 files may be specified with their path name preceded by '@@'.
13266
13267 @smallexample
13268    gnat bind @@args.txt main.ali
13269 @end smallexample
13270
13271 @noindent
13272 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13273 PP or PRETTY and XREF, the project file related switches
13274 (@option{^-P^/PROJECT_FILE^},
13275 @option{^-X^/EXTERNAL_REFERENCE^} and
13276 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13277 the switches of the invoking tool.
13278
13279 @noindent
13280 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13281 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13282 the immediate sources of the specified project file.
13283
13284 @noindent
13285 For each of these commands, there is optionally a corresponding  package
13286 in the main project.
13287
13288 @itemize @bullet
13289 @item
13290 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13291
13292 @item
13293 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13294
13295 @item
13296 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13297
13298 @item
13299 package @code{Eliminate} for command ELIM (invoking
13300 @code{^gnatelim^gnatelim^})
13301
13302 @item
13303 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13304
13305 @item
13306 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13307
13308 @item
13309 package @code{Pretty_Printer} for command PP or PRETTY
13310 (invoking @code{^gnatpp^gnatpp^})
13311
13312 @item
13313 package @code{Cross_Reference} for command XREF (invoking
13314 @code{^gnatxref^gnatxref^})
13315
13316 @end itemize
13317
13318 @noindent
13319 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13320 a simple variable with a string list value. It contains ^switches^switches^
13321 for the invocation of @code{^gnatls^gnatls^}.
13322
13323 @smallexample @c projectfile
13324 @group
13325 project Proj1 is
13326    package gnatls is
13327       for ^Switches^Switches^
13328           use ("^-a^-a^",
13329                "^-v^-v^");
13330    end gnatls;
13331 end Proj1;
13332 @end group
13333 @end smallexample
13334
13335 @noindent
13336 All other packages have two attribute @code{^Switches^Switches^} and
13337 @code{^Default_Switches^Default_Switches^}.
13338
13339 @noindent
13340 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13341 source file name, that has a string list value: the ^switches^switches^ to be
13342 used when the tool corresponding to the package is invoked for the specific
13343 source file.
13344
13345 @noindent
13346 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13347 indexed by  the programming language that has a string list value.
13348 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13349 ^switches^switches^ for the invocation of the tool corresponding
13350 to the package, except if a specific @code{^Switches^Switches^} attribute
13351 is specified for the source file.
13352
13353 @smallexample @c projectfile
13354 @group
13355 project Proj is
13356
13357    for Source_Dirs use ("./**");
13358
13359    package gnatls is
13360       for ^Switches^Switches^ use
13361           ("^-a^-a^",
13362            "^-v^-v^");
13363    end gnatls;
13364 @end group
13365 @group
13366
13367    package Compiler is
13368       for ^Default_Switches^Default_Switches^ ("Ada")
13369           use ("^-gnatv^-gnatv^",
13370                "^-gnatwa^-gnatwa^");
13371    end Binder;
13372 @end group
13373 @group
13374
13375    package Binder is
13376       for ^Default_Switches^Default_Switches^ ("Ada")
13377           use ("^-C^-C^",
13378                "^-e^-e^");
13379    end Binder;
13380 @end group
13381 @group
13382
13383    package Linker is
13384       for ^Default_Switches^Default_Switches^ ("Ada")
13385           use ("^-C^-C^");
13386       for ^Switches^Switches^ ("main.adb")
13387           use ("^-C^-C^",
13388                "^-v^-v^",
13389                "^-v^-v^");
13390    end Linker;
13391 @end group
13392 @group
13393
13394    package Finder is
13395       for ^Default_Switches^Default_Switches^ ("Ada")
13396            use ("^-a^-a^",
13397                 "^-f^-f^");
13398    end Finder;
13399 @end group
13400 @group
13401
13402    package Cross_Reference is
13403       for ^Default_Switches^Default_Switches^ ("Ada")
13404           use ("^-a^-a^",
13405                "^-f^-f^",
13406                "^-d^-d^",
13407                "^-u^-u^");
13408    end Cross_Reference;
13409 end Proj;
13410 @end group
13411 @end smallexample
13412
13413 @noindent
13414 With the above project file, commands such as
13415
13416 @smallexample
13417    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13418    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13419    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13420    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13421    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13422 @end smallexample
13423
13424 @noindent
13425 will set up the environment properly and invoke the tool with the switches
13426 found in the package corresponding to the tool:
13427 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13428 except @code{^Switches^Switches^ ("main.adb")}
13429 for @code{^gnatlink^gnatlink^}.
13430
13431 @ifclear vms
13432 @node Glide and Project Files
13433 @subsection Glide and Project Files
13434
13435 @noindent
13436 Glide will automatically recognize the @file{.gpr} extension for
13437 project files, and will
13438 convert them to its own internal format automatically. However, it
13439 doesn't provide a syntax-oriented editor for modifying these
13440 files.
13441 The project file will be loaded as text when you select the menu item
13442 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13443 You can edit this text and save the @file{gpr} file;
13444 when you next select this project file in Glide it
13445 will be automatically reloaded.
13446 @end ifclear
13447
13448 @c **********************
13449 @node An Extended Example
13450 @section An Extended Example
13451
13452 @noindent
13453 Suppose that we have two programs, @var{prog1} and @var{prog2},
13454 whose sources are in corresponding directories. We would like
13455 to build them with a single @command{gnatmake} command, and we want to place
13456 their object files into @file{build} subdirectories of the source directories.
13457 Furthermore, we want to have to have two separate subdirectories
13458 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13459 the object files compiled with different set of compilation flags.
13460
13461 In other words, we have the following structure:
13462
13463 @smallexample
13464 @group
13465    main
13466      |- prog1
13467      |    |- build
13468      |         | debug
13469      |         | release
13470      |- prog2
13471           |- build
13472                | debug
13473                | release
13474 @end group
13475 @end smallexample
13476
13477 @noindent
13478 Here are the project files that we must place in a directory @file{main}
13479 to maintain this structure:
13480
13481 @enumerate
13482
13483 @item We create a @code{Common} project with a package @code{Compiler} that
13484 specifies the compilation ^switches^switches^:
13485
13486 @smallexample
13487 File "common.gpr":
13488 @group
13489 @b{project} Common @b{is}
13490
13491    @b{for} Source_Dirs @b{use} (); -- No source files
13492 @end group
13493
13494 @group
13495    @b{type} Build_Type @b{is} ("release", "debug");
13496    Build : Build_Type := External ("BUILD", "debug");
13497 @end group
13498 @group
13499    @b{package} Compiler @b{is}
13500       @b{case} Build @b{is}
13501          @b{when} "release" =>
13502            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13503                    @b{use} ("^-O2^-O2^");
13504          @b{when} "debug"   =>
13505            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13506                    @b{use} ("^-g^-g^");
13507       @b{end case};
13508    @b{end} Compiler;
13509
13510 @b{end} Common;
13511 @end group
13512 @end smallexample
13513
13514 @item We create separate projects for the two programs:
13515
13516 @smallexample
13517 @group
13518 File "prog1.gpr":
13519
13520 @b{with} "common";
13521 @b{project} Prog1 @b{is}
13522
13523     @b{for} Source_Dirs @b{use} ("prog1");
13524     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13525
13526     @b{package} Compiler @b{renames} Common.Compiler;
13527
13528 @b{end} Prog1;
13529 @end group
13530 @end smallexample
13531
13532 @smallexample
13533 @group
13534 File "prog2.gpr":
13535
13536 @b{with} "common";
13537 @b{project} Prog2 @b{is}
13538
13539     @b{for} Source_Dirs @b{use} ("prog2");
13540     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13541
13542     @b{package} Compiler @b{renames} Common.Compiler;
13543
13544 @end group
13545 @b{end} Prog2;
13546 @end smallexample
13547
13548 @item We create a wrapping project @code{Main}:
13549
13550 @smallexample
13551 @group
13552 File "main.gpr":
13553
13554 @b{with} "common";
13555 @b{with} "prog1";
13556 @b{with} "prog2";
13557 @b{project} Main @b{is}
13558
13559    @b{package} Compiler @b{renames} Common.Compiler;
13560
13561 @b{end} Main;
13562 @end group
13563 @end smallexample
13564
13565 @item Finally we need to create a dummy procedure that @code{with}s (either
13566 explicitly or implicitly) all the sources of our two programs.
13567
13568 @end enumerate
13569
13570 @noindent
13571 Now we can build the programs using the command
13572
13573 @smallexample
13574    gnatmake ^-P^/PROJECT_FILE=^main dummy
13575 @end smallexample
13576
13577 @noindent
13578 for the Debug mode, or
13579
13580 @ifclear vms
13581 @smallexample
13582    gnatmake -Pmain -XBUILD=release
13583 @end smallexample
13584 @end ifclear
13585
13586 @ifset vms
13587 @smallexample
13588    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13589 @end smallexample
13590 @end ifset
13591
13592 @noindent
13593 for the Release mode.
13594
13595 @c ********************************
13596 @c * Project File Complete Syntax *
13597 @c ********************************
13598
13599 @node Project File Complete Syntax
13600 @section Project File Complete Syntax
13601
13602 @smallexample
13603 project ::=
13604   context_clause project_declaration
13605
13606 context_clause ::=
13607   @{with_clause@}
13608
13609 with_clause ::=
13610   @b{with} path_name @{ , path_name @} ;
13611
13612 path_name ::=
13613    string_literal
13614
13615 project_declaration ::=
13616   simple_project_declaration | project_extension
13617
13618 simple_project_declaration ::=
13619   @b{project} <project_>simple_name @b{is}
13620     @{declarative_item@}
13621   @b{end} <project_>simple_name;
13622
13623 project_extension ::=
13624   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13625     @{declarative_item@}
13626   @b{end} <project_>simple_name;
13627
13628 declarative_item ::=
13629   package_declaration |
13630   typed_string_declaration |
13631   other_declarative_item
13632
13633 package_declaration ::=
13634   package_specification | package_renaming
13635
13636 package_specification ::=
13637   @b{package} package_identifier @b{is}
13638     @{simple_declarative_item@}
13639   @b{end} package_identifier ;
13640
13641 package_identifier ::=
13642   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13643   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13644   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13645
13646 package_renaming ::==
13647   @b{package} package_identifier @b{renames}
13648        <project_>simple_name.package_identifier ;
13649
13650 typed_string_declaration ::=
13651   @b{type} <typed_string_>_simple_name @b{is}
13652    ( string_literal @{, string_literal@} );
13653
13654 other_declarative_item ::=
13655   attribute_declaration |
13656   typed_variable_declaration |
13657   variable_declaration |
13658   case_construction
13659
13660 attribute_declaration ::=
13661   full_associative_array_declaration |
13662   @b{for} attribute_designator @b{use} expression ;
13663
13664 full_associative_array_declaration ::=
13665   @b{for} <associative_array_attribute_>simple_name @b{use}
13666   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13667
13668 attribute_designator ::=
13669   <simple_attribute_>simple_name |
13670   <associative_array_attribute_>simple_name ( string_literal )
13671
13672 typed_variable_declaration ::=
13673   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13674
13675 variable_declaration ::=
13676   <variable_>simple_name := expression;
13677
13678 expression ::=
13679   term @{& term@}
13680
13681 term ::=
13682   literal_string |
13683   string_list |
13684   <variable_>name |
13685   external_value |
13686   attribute_reference
13687
13688 string_literal ::=
13689   (same as Ada)
13690
13691 string_list ::=
13692   ( <string_>expression @{ , <string_>expression @} )
13693
13694 external_value ::=
13695   @b{external} ( string_literal [, string_literal] )
13696
13697 attribute_reference ::=
13698   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13699
13700 attribute_prefix ::=
13701   @b{project} |
13702   <project_>simple_name | package_identifier |
13703   <project_>simple_name . package_identifier
13704
13705 case_construction ::=
13706   @b{case} <typed_variable_>name @b{is}
13707     @{case_item@}
13708   @b{end case} ;
13709
13710 case_item ::=
13711   @b{when} discrete_choice_list =>
13712       @{case_construction | attribute_declaration@}
13713
13714 discrete_choice_list ::=
13715   string_literal @{| string_literal@} |
13716   @b{others}
13717
13718 name ::=
13719   simple_name @{. simple_name@}
13720
13721 simple_name ::=
13722   identifier (same as Ada)
13723
13724 @end smallexample
13725
13726
13727 @node The Cross-Referencing Tools gnatxref and gnatfind
13728 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13729 @findex gnatxref
13730 @findex gnatfind
13731
13732 @noindent
13733 The compiler generates cross-referencing information (unless
13734 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13735 This information indicates where in the source each entity is declared and
13736 referenced. Note that entities in package Standard are not included, but
13737 entities in all other predefined units are included in the output.
13738
13739 Before using any of these two tools, you need to compile successfully your
13740 application, so that GNAT gets a chance to generate the cross-referencing
13741 information.
13742
13743 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13744 information to provide the user with the capability to easily locate the
13745 declaration and references to an entity. These tools are quite similar,
13746 the difference being that @code{gnatfind} is intended for locating
13747 definitions and/or references to a specified entity or entities, whereas
13748 @code{gnatxref} is oriented to generating a full report of all
13749 cross-references.
13750
13751 To use these tools, you must not compile your application using the
13752 @option{-gnatx} switch on the @file{gnatmake} command line
13753 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13754 information will not be generated.
13755
13756 @menu
13757 * gnatxref Switches::
13758 * gnatfind Switches::
13759 * Project Files for gnatxref and gnatfind::
13760 * Regular Expressions in gnatfind and gnatxref::
13761 * Examples of gnatxref Usage::
13762 * Examples of gnatfind Usage::
13763 @end menu
13764
13765 @node gnatxref Switches
13766 @section @code{gnatxref} Switches
13767
13768 @noindent
13769 The command invocation for @code{gnatxref} is:
13770 @smallexample
13771 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13772 @end smallexample
13773
13774 @noindent
13775 where
13776
13777 @table @code
13778 @item sourcefile1, sourcefile2
13779 identifies the source files for which a report is to be generated. The
13780 ``with''ed units will be processed too. You must provide at least one file.
13781
13782 These file names are considered to be regular expressions, so for instance
13783 specifying @file{source*.adb} is the same as giving every file in the current
13784 directory whose name starts with @file{source} and whose extension is
13785 @file{adb}.
13786
13787 You shouldn't specify any directory name, just base names. @command{gnatxref}
13788 and @command{gnatfind} will be able to locate these files by themselves using
13789 the source path. If you specify directories, no result is produced.
13790
13791 @end table
13792
13793 @noindent
13794 The switches can be :
13795 @table @option
13796 @c !sort!
13797 @item ^-a^/ALL_FILES^
13798 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13799 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13800 the read-only files found in the library search path. Otherwise, these files
13801 will be ignored. This option can be used to protect Gnat sources or your own
13802 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13803 much faster, and their output much smaller. Read-only here refers to access
13804 or permissions status in the file system for the current user.
13805
13806 @item -aIDIR
13807 @cindex @option{-aIDIR} (@command{gnatxref})
13808 When looking for source files also look in directory DIR. The order in which
13809 source file search is undertaken is the same as for @file{gnatmake}.
13810
13811 @item -aODIR
13812 @cindex @option{-aODIR} (@command{gnatxref})
13813 When searching for library and object files, look in directory
13814 DIR. The order in which library files are searched is the same as for
13815 @file{gnatmake}.
13816
13817 @item -nostdinc
13818 @cindex @option{-nostdinc} (@command{gnatxref})
13819 Do not look for sources in the system default directory.
13820
13821 @item -nostdlib
13822 @cindex @option{-nostdlib} (@command{gnatxref})
13823 Do not look for library files in the system default directory.
13824
13825 @item --RTS=@var{rts-path}
13826 @cindex @option{--RTS} (@command{gnatxref})
13827 Specifies the default location of the runtime library. Same meaning as the
13828 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13829
13830 @item ^-d^/DERIVED_TYPES^
13831 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13832 If this switch is set @code{gnatxref} will output the parent type
13833 reference for each matching derived types.
13834
13835 @item ^-f^/FULL_PATHNAME^
13836 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13837 If this switch is set, the output file names will be preceded by their
13838 directory (if the file was found in the search path). If this switch is
13839 not set, the directory will not be printed.
13840
13841 @item ^-g^/IGNORE_LOCALS^
13842 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13843 If this switch is set, information is output only for library-level
13844 entities, ignoring local entities. The use of this switch may accelerate
13845 @code{gnatfind} and @code{gnatxref}.
13846
13847 @item -IDIR
13848 @cindex @option{-IDIR} (@command{gnatxref})
13849 Equivalent to @samp{-aODIR -aIDIR}.
13850
13851 @item -pFILE
13852 @cindex @option{-pFILE} (@command{gnatxref})
13853 Specify a project file to use @xref{Project Files}. These project files are
13854 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13855 project files, you should use gnatxref through the GNAT driver
13856 (@command{gnat xref -Pproject}).
13857
13858 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13859 project file in the current directory.
13860
13861 If a project file is either specified or found by the tools, then the content
13862 of the source directory and object directory lines are added as if they
13863 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13864 and @samp{^-aO^OBJECT_SEARCH^}.
13865 @item ^-u^/UNUSED^
13866 Output only unused symbols. This may be really useful if you give your
13867 main compilation unit on the command line, as @code{gnatxref} will then
13868 display every unused entity and 'with'ed package.
13869
13870 @ifclear vms
13871 @item -v
13872 Instead of producing the default output, @code{gnatxref} will generate a
13873 @file{tags} file that can be used by vi. For examples how to use this
13874 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13875 to the standard output, thus you will have to redirect it to a file.
13876 @end ifclear
13877
13878 @end table
13879
13880 @noindent
13881 All these switches may be in any order on the command line, and may even
13882 appear after the file names. They need not be separated by spaces, thus
13883 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13884 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13885
13886 @node gnatfind Switches
13887 @section @code{gnatfind} Switches
13888
13889 @noindent
13890 The command line for @code{gnatfind} is:
13891
13892 @smallexample
13893 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13894       [file1 file2 ...]
13895 @end smallexample
13896
13897 @noindent
13898 where
13899
13900 @table @code
13901 @item pattern
13902 An entity will be output only if it matches the regular expression found
13903 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13904
13905 Omitting the pattern is equivalent to specifying @samp{*}, which
13906 will match any entity. Note that if you do not provide a pattern, you
13907 have to provide both a sourcefile and a line.
13908
13909 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13910 for matching purposes. At the current time there is no support for
13911 8-bit codes other than Latin-1, or for wide characters in identifiers.
13912
13913 @item sourcefile
13914 @code{gnatfind} will look for references, bodies or declarations
13915 of symbols referenced in @file{sourcefile}, at line @samp{line}
13916 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13917 for syntax examples.
13918
13919 @item line
13920 is a decimal integer identifying the line number containing
13921 the reference to the entity (or entities) to be located.
13922
13923 @item column
13924 is a decimal integer identifying the exact location on the
13925 line of the first character of the identifier for the
13926 entity reference. Columns are numbered from 1.
13927
13928 @item file1 file2 ...
13929 The search will be restricted to these source files. If none are given, then
13930 the search will be done for every library file in the search path.
13931 These file must appear only after the pattern or sourcefile.
13932
13933 These file names are considered to be regular expressions, so for instance
13934 specifying 'source*.adb' is the same as giving every file in the current
13935 directory whose name starts with 'source' and whose extension is 'adb'.
13936
13937 The location of the spec of the entity will always be displayed, even if it
13938 isn't in one of file1, file2,... The occurrences of the entity in the
13939 separate units of the ones given on the command line will also be displayed.
13940
13941 Note that if you specify at least one file in this part, @code{gnatfind} may
13942 sometimes not be able to find the body of the subprograms...
13943
13944 @end table
13945
13946 @noindent
13947 At least one of 'sourcefile' or 'pattern' has to be present on
13948 the command line.
13949
13950 The following switches are available:
13951 @table @option
13952 @c !sort!
13953
13954 @item ^-a^/ALL_FILES^
13955 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13956 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13957 the read-only files found in the library search path. Otherwise, these files
13958 will be ignored. This option can be used to protect Gnat sources or your own
13959 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13960 much faster, and their output much smaller. Read-only here refers to access
13961 or permission status in the file system for the current user.
13962
13963 @item -aIDIR
13964 @cindex @option{-aIDIR} (@command{gnatfind})
13965 When looking for source files also look in directory DIR. The order in which
13966 source file search is undertaken is the same as for @file{gnatmake}.
13967
13968 @item -aODIR
13969 @cindex @option{-aODIR} (@command{gnatfind})
13970 When searching for library and object files, look in directory
13971 DIR. The order in which library files are searched is the same as for
13972 @file{gnatmake}.
13973
13974 @item -nostdinc
13975 @cindex @option{-nostdinc} (@command{gnatfind})
13976 Do not look for sources in the system default directory.
13977
13978 @item -nostdlib
13979 @cindex @option{-nostdlib} (@command{gnatfind})
13980 Do not look for library files in the system default directory.
13981
13982 @item --RTS=@var{rts-path}
13983 @cindex @option{--RTS} (@command{gnatfind})
13984 Specifies the default location of the runtime library. Same meaning as the
13985 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13986
13987 @item ^-d^/DERIVED_TYPE_INFORMATION^
13988 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13989 If this switch is set, then @code{gnatfind} will output the parent type
13990 reference for each matching derived types.
13991
13992 @item ^-e^/EXPRESSIONS^
13993 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13994 By default, @code{gnatfind} accept the simple regular expression set for
13995 @samp{pattern}. If this switch is set, then the pattern will be
13996 considered as full Unix-style regular expression.
13997
13998 @item ^-f^/FULL_PATHNAME^
13999 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14000 If this switch is set, the output file names will be preceded by their
14001 directory (if the file was found in the search path). If this switch is
14002 not set, the directory will not be printed.
14003
14004 @item ^-g^/IGNORE_LOCALS^
14005 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14006 If this switch is set, information is output only for library-level
14007 entities, ignoring local entities. The use of this switch may accelerate
14008 @code{gnatfind} and @code{gnatxref}.
14009
14010 @item -IDIR
14011 @cindex @option{-IDIR} (@command{gnatfind})
14012 Equivalent to @samp{-aODIR -aIDIR}.
14013
14014 @item -pFILE
14015 @cindex @option{-pFILE} (@command{gnatfind})
14016 Specify a project file (@pxref{Project Files}) to use.
14017 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14018 project file in the current directory.
14019
14020 If a project file is either specified or found by the tools, then the content
14021 of the source directory and object directory lines are added as if they
14022 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14023 @samp{^-aO^/OBJECT_SEARCH^}.
14024
14025 @item ^-r^/REFERENCES^
14026 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14027 By default, @code{gnatfind} will output only the information about the
14028 declaration, body or type completion of the entities. If this switch is
14029 set, the @code{gnatfind} will locate every reference to the entities in
14030 the files specified on the command line (or in every file in the search
14031 path if no file is given on the command line).
14032
14033 @item ^-s^/PRINT_LINES^
14034 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14035 If this switch is set, then @code{gnatfind} will output the content
14036 of the Ada source file lines were the entity was found.
14037
14038 @item ^-t^/TYPE_HIERARCHY^
14039 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14040 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14041 the specified type. It act like -d option but recursively from parent
14042 type to parent type. When this switch is set it is not possible to
14043 specify more than one file.
14044
14045 @end table
14046
14047 @noindent
14048 All these switches may be in any order on the command line, and may even
14049 appear after the file names. They need not be separated by spaces, thus
14050 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14051 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14052
14053 As stated previously, gnatfind will search in every directory in the
14054 search path. You can force it to look only in the current directory if
14055 you specify @code{*} at the end of the command line.
14056
14057 @node Project Files for gnatxref and gnatfind
14058 @section Project Files for @command{gnatxref} and @command{gnatfind}
14059
14060 @noindent
14061 Project files allow a programmer to specify how to compile its
14062 application, where to find sources, etc.  These files are used
14063 @ifclear vms
14064 primarily by the Glide Ada mode, but they can also be used
14065 @end ifclear
14066 by the two tools
14067 @code{gnatxref} and @code{gnatfind}.
14068
14069 A project file name must end with @file{.gpr}. If a single one is
14070 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14071 extract the information from it. If multiple project files are found, none of
14072 them is read, and you have to use the @samp{-p} switch to specify the one
14073 you want to use.
14074
14075 The following lines can be included, even though most of them have default
14076 values which can be used in most cases.
14077 The lines can be entered in any order in the file.
14078 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14079 each line. If you have multiple instances, only the last one is taken into
14080 account.
14081
14082 @table @code
14083 @item src_dir=DIR
14084 [default: @code{"^./^[]^"}]
14085 specifies a directory where to look for source files. Multiple @code{src_dir}
14086 lines can be specified and they will be searched in the order they
14087 are specified.
14088
14089 @item obj_dir=DIR
14090 [default: @code{"^./^[]^"}]
14091 specifies a directory where to look for object and library files. Multiple
14092 @code{obj_dir} lines can be specified, and they will be searched in the order
14093 they are specified
14094
14095 @item comp_opt=SWITCHES
14096 [default: @code{""}]
14097 creates a variable which can be referred to subsequently by using
14098 the @code{$@{comp_opt@}} notation. This is intended to store the default
14099 switches given to @command{gnatmake} and @command{gcc}.
14100
14101 @item bind_opt=SWITCHES
14102 [default: @code{""}]
14103 creates a variable which can be referred to subsequently by using
14104 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14105 switches given to @command{gnatbind}.
14106
14107 @item link_opt=SWITCHES
14108 [default: @code{""}]
14109 creates a variable which can be referred to subsequently by using
14110 the @samp{$@{link_opt@}} notation. This is intended to store the default
14111 switches given to @command{gnatlink}.
14112
14113 @item main=EXECUTABLE
14114 [default: @code{""}]
14115 specifies the name of the executable for the application. This variable can
14116 be referred to in the following lines by using the @samp{$@{main@}} notation.
14117
14118 @ifset vms
14119 @item comp_cmd=COMMAND
14120 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14121 @end ifset
14122 @ifclear vms
14123 @item comp_cmd=COMMAND
14124 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14125 @end ifclear
14126 specifies the command used to compile a single file in the application.
14127
14128 @ifset vms
14129 @item make_cmd=COMMAND
14130 [default: @code{"GNAT MAKE $@{main@}
14131 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14132 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14133 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14134 @end ifset
14135 @ifclear vms
14136 @item make_cmd=COMMAND
14137 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14138  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14139  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14140 @end ifclear
14141 specifies the command used to recompile the whole application.
14142
14143 @item run_cmd=COMMAND
14144 [default: @code{"$@{main@}"}]
14145 specifies the command used to run the application.
14146
14147 @item debug_cmd=COMMAND
14148 [default: @code{"gdb $@{main@}"}]
14149 specifies the command used to debug the application
14150
14151 @end table
14152
14153 @noindent
14154 @command{gnatxref} and @command{gnatfind} only take into account the
14155 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14156
14157 @node Regular Expressions in gnatfind and gnatxref
14158 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14159
14160 @noindent
14161 As specified in the section about @command{gnatfind}, the pattern can be a
14162 regular expression. Actually, there are to set of regular expressions
14163 which are recognized by the program :
14164
14165 @table @code
14166 @item globbing patterns
14167 These are the most usual regular expression. They are the same that you
14168 generally used in a Unix shell command line, or in a DOS session.
14169
14170 Here is a more formal grammar :
14171 @smallexample
14172 @group
14173 @iftex
14174 @leftskip=.5cm
14175 @end iftex
14176 regexp ::= term
14177 term   ::= elmt            -- matches elmt
14178 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14179 term   ::= *               -- any string of 0 or more characters
14180 term   ::= ?               -- matches any character
14181 term   ::= [char @{char@}] -- matches any character listed
14182 term   ::= [char - char]   -- matches any character in range
14183 @end group
14184 @end smallexample
14185
14186 @item full regular expression
14187 The second set of regular expressions is much more powerful. This is the
14188 type of regular expressions recognized by utilities such a @file{grep}.
14189
14190 The following is the form of a regular expression, expressed in Ada
14191 reference manual style BNF is as follows
14192
14193 @smallexample
14194 @iftex
14195 @leftskip=.5cm
14196 @end iftex
14197 @group
14198 regexp ::= term @{| term@} -- alternation (term or term ...)
14199
14200 term ::= item @{item@}     -- concatenation (item then item)
14201
14202 item ::= elmt              -- match elmt
14203 item ::= elmt *            -- zero or more elmt's
14204 item ::= elmt +            -- one or more elmt's
14205 item ::= elmt ?            -- matches elmt or nothing
14206 @end group
14207 @group
14208 elmt ::= nschar            -- matches given character
14209 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14210 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14211 elmt ::= [char - char]     -- matches chars in given range
14212 elmt ::= \ char            -- matches given character
14213 elmt ::= .                 -- matches any single character
14214 elmt ::= ( regexp )        -- parens used for grouping
14215
14216 char ::= any character, including special characters
14217 nschar ::= any character except ()[].*+?^^^
14218 @end group
14219 @end smallexample
14220
14221 Following are a few examples :
14222
14223 @table @samp
14224 @item abcde|fghi
14225 will match any of the two strings 'abcde' and 'fghi'.
14226
14227 @item abc*d
14228 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14229
14230 @item [a-z]+
14231 will match any string which has only lowercase characters in it (and at
14232 least one character
14233
14234 @end table
14235 @end table
14236
14237 @node Examples of gnatxref Usage
14238 @section Examples of @code{gnatxref} Usage
14239
14240 @subsection General Usage
14241
14242 @noindent
14243 For the following examples, we will consider the following units :
14244
14245 @smallexample @c ada
14246 @group
14247 @cartouche
14248 main.ads:
14249 1: with Bar;
14250 2: package Main is
14251 3:     procedure Foo (B : in Integer);
14252 4:     C : Integer;
14253 5: private
14254 6:     D : Integer;
14255 7: end Main;
14256
14257 main.adb:
14258 1: package body Main is
14259 2:     procedure Foo (B : in Integer) is
14260 3:     begin
14261 4:        C := B;
14262 5:        D := B;
14263 6:        Bar.Print (B);
14264 7:        Bar.Print (C);
14265 8:     end Foo;
14266 9: end Main;
14267
14268 bar.ads:
14269 1: package Bar is
14270 2:     procedure Print (B : Integer);
14271 3: end bar;
14272 @end cartouche
14273 @end group
14274 @end smallexample
14275
14276 @table @code
14277
14278 @noindent
14279 The first thing to do is to recompile your application (for instance, in
14280 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14281 the cross-referencing information.
14282 You can then issue any of the following commands:
14283
14284 @item gnatxref main.adb
14285 @code{gnatxref} generates cross-reference information for main.adb
14286 and every unit 'with'ed by main.adb.
14287
14288 The output would be:
14289 @smallexample
14290 @iftex
14291 @leftskip=0cm
14292 @end iftex
14293 B                                                      Type: Integer
14294   Decl: bar.ads           2:22
14295 B                                                      Type: Integer
14296   Decl: main.ads          3:20
14297   Body: main.adb          2:20
14298   Ref:  main.adb          4:13     5:13     6:19
14299 Bar                                                    Type: Unit
14300   Decl: bar.ads           1:9
14301   Ref:  main.adb          6:8      7:8
14302        main.ads           1:6
14303 C                                                      Type: Integer
14304   Decl: main.ads          4:5
14305   Modi: main.adb          4:8
14306   Ref:  main.adb          7:19
14307 D                                                      Type: Integer
14308   Decl: main.ads          6:5
14309   Modi: main.adb          5:8
14310 Foo                                                    Type: Unit
14311   Decl: main.ads          3:15
14312   Body: main.adb          2:15
14313 Main                                                    Type: Unit
14314   Decl: main.ads          2:9
14315   Body: main.adb          1:14
14316 Print                                                   Type: Unit
14317   Decl: bar.ads           2:15
14318   Ref:  main.adb          6:12     7:12
14319 @end smallexample
14320
14321 @noindent
14322 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14323 its body is in main.adb, line 1, column 14 and is not referenced any where.
14324
14325 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14326 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14327
14328 @item gnatxref package1.adb package2.ads
14329 @code{gnatxref} will generates cross-reference information for
14330 package1.adb, package2.ads and any other package 'with'ed by any
14331 of these.
14332
14333 @end table
14334
14335 @ifclear vms
14336 @subsection Using gnatxref with vi
14337
14338 @code{gnatxref} can generate a tags file output, which can be used
14339 directly from @file{vi}. Note that the standard version of @file{vi}
14340 will not work properly with overloaded symbols. Consider using another
14341 free implementation of @file{vi}, such as @file{vim}.
14342
14343 @smallexample
14344 $ gnatxref -v gnatfind.adb > tags
14345 @end smallexample
14346
14347 @noindent
14348 will generate the tags file for @code{gnatfind} itself (if the sources
14349 are in the search path!).
14350
14351 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14352 (replacing @i{entity} by whatever you are looking for), and vi will
14353 display a new file with the corresponding declaration of entity.
14354 @end ifclear
14355
14356 @node Examples of gnatfind Usage
14357 @section Examples of @code{gnatfind} Usage
14358
14359 @table @code
14360
14361 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14362 Find declarations for all entities xyz referenced at least once in
14363 main.adb. The references are search in every library file in the search
14364 path.
14365
14366 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14367 switch is set)
14368
14369 The output will look like:
14370 @smallexample
14371 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14372 ^directory/^[directory]^main.adb:24:10: xyz <= body
14373 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14374 @end smallexample
14375
14376 @noindent
14377 that is to say, one of the entities xyz found in main.adb is declared at
14378 line 12 of main.ads (and its body is in main.adb), and another one is
14379 declared at line 45 of foo.ads
14380
14381 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14382 This is the same command as the previous one, instead @code{gnatfind} will
14383 display the content of the Ada source file lines.
14384
14385 The output will look like:
14386
14387 @smallexample
14388 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14389    procedure xyz;
14390 ^directory/^[directory]^main.adb:24:10: xyz <= body
14391    procedure xyz is
14392 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14393    xyz : Integer;
14394 @end smallexample
14395
14396 @noindent
14397 This can make it easier to find exactly the location your are looking
14398 for.
14399
14400 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14401 Find references to all entities containing an x that are
14402 referenced on line 123 of main.ads.
14403 The references will be searched only in main.ads and foo.adb.
14404
14405 @item gnatfind main.ads:123
14406 Find declarations and bodies for all entities that are referenced on
14407 line 123 of main.ads.
14408
14409 This is the same as @code{gnatfind "*":main.adb:123}.
14410
14411 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14412 Find the declaration for the entity referenced at column 45 in
14413 line 123 of file main.adb in directory mydir. Note that it
14414 is usual to omit the identifier name when the column is given,
14415 since the column position identifies a unique reference.
14416
14417 The column has to be the beginning of the identifier, and should not
14418 point to any character in the middle of the identifier.
14419
14420 @end table
14421
14422
14423 @c *********************************
14424 @node The GNAT Pretty-Printer gnatpp
14425 @chapter The GNAT Pretty-Printer @command{gnatpp}
14426 @findex gnatpp
14427 @cindex Pretty-Printer
14428
14429 @noindent
14430 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14431 for source reformatting / pretty-printing.
14432 It takes an Ada source file as input and generates a reformatted
14433 version as output.
14434 You can specify various style directives via switches; e.g.,
14435 identifier case conventions, rules of indentation, and comment layout.
14436
14437 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14438 tree for the input source and thus requires the input to be syntactically and
14439 semantically legal.
14440 If this condition is not met, @command{gnatpp} will terminate with an
14441 error message; no output file will be generated.
14442
14443 If the compilation unit
14444 contained in the input source depends semantically upon units located
14445 outside the current directory, you have to provide the source search path
14446 when invoking @command{gnatpp}, if these units are contained in files with
14447 names that do not follow the GNAT file naming rules, you have to provide
14448 the configuration file describing the corresponding naming scheme;
14449 see the description of the @command{gnatpp}
14450 switches below. Another possibility is to use a project file and to
14451 call @command{gnatpp} through the @command{gnat} driver
14452
14453 The @command{gnatpp} command has the form
14454
14455 @smallexample
14456 $ gnatpp [@var{switches}] @var{filename}
14457 @end smallexample
14458
14459 @noindent
14460 where
14461 @itemize @bullet
14462 @item
14463 @var{switches} is an optional sequence of switches defining such properties as
14464 the formatting rules, the source search path, and the destination for the
14465 output source file
14466
14467 @item
14468 @var{filename} is the name (including the extension) of the source file to
14469 reformat; ``wildcards'' or several file names on the same gnatpp command are
14470 allowed.  The file name may contain path information; it does not have to
14471 follow the GNAT file naming rules
14472 @end itemize
14473
14474
14475 @menu
14476 * Switches for gnatpp::
14477 * Formatting Rules::
14478 @end menu
14479
14480 @node Switches for gnatpp
14481 @section Switches for @command{gnatpp}
14482
14483 @noindent
14484 The following subsections describe the various switches accepted by
14485 @command{gnatpp}, organized by category.
14486
14487 @ifclear vms
14488 You specify a switch by supplying a name and generally also a value.
14489 In many cases the values for a switch with a given name are incompatible with
14490 each other
14491 (for example the switch that controls the casing of a reserved word may have
14492 exactly one value: upper case, lower case, or
14493 mixed case) and thus exactly one such switch can be in effect for an
14494 invocation of @command{gnatpp}.
14495 If more than one is supplied, the last one is used.
14496 However, some values for the same switch are mutually compatible.
14497 You may supply several such switches to @command{gnatpp}, but then
14498 each must be specified in full, with both the name and the value.
14499 Abbreviated forms (the name appearing once, followed by each value) are
14500 not permitted.
14501 For example, to set
14502 the alignment of the assignment delimiter both in declarations and in
14503 assignment statements, you must write @option{-A2A3}
14504 (or @option{-A2 -A3}), but not @option{-A23}.
14505 @end ifclear
14506
14507 @ifset vms
14508 In many cases the set of options for a given qualifier are incompatible with
14509 each other (for example the qualifier that controls the casing of a reserved
14510 word may have exactly one option, which specifies either upper case, lower
14511 case, or mixed case), and thus exactly one such option can be in effect for
14512 an invocation of @command{gnatpp}.
14513 If more than one is supplied, the last one is used.
14514 However, some qualifiers have options that are mutually compatible,
14515 and then you may then supply several such options when invoking
14516 @command{gnatpp}.
14517 @end ifset
14518
14519 In most cases, it is obvious whether or not the
14520 ^values for a switch with a given name^options for a given qualifier^
14521 are compatible with each other.
14522 When the semantics might not be evident, the summaries below explicitly
14523 indicate the effect.
14524
14525 @menu
14526 * Alignment Control::
14527 * Casing Control::
14528 * Construct Layout Control::
14529 * General Text Layout Control::
14530 * Other Formatting Options::
14531 * Setting the Source Search Path::
14532 * Output File Control::
14533 * Other gnatpp Switches::
14534 @end menu
14535
14536
14537 @node Alignment Control
14538 @subsection Alignment Control
14539 @cindex Alignment control in @command{gnatpp}
14540
14541 @noindent
14542 Programs can be easier to read if certain constructs are vertically aligned.
14543 By default all alignments are set ON.
14544 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14545 OFF, and then use one or more of the other
14546 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14547 to activate alignment for specific constructs.
14548
14549 @table @option
14550 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14551
14552 @ifset vms
14553 @item /ALIGN=ON
14554 Set all alignments to ON
14555 @end ifset
14556
14557 @item ^-A0^/ALIGN=OFF^
14558 Set all alignments to OFF
14559
14560 @item ^-A1^/ALIGN=COLONS^
14561 Align @code{:} in declarations
14562
14563 @item ^-A2^/ALIGN=DECLARATIONS^
14564 Align @code{:=} in initializations in declarations
14565
14566 @item ^-A3^/ALIGN=STATEMENTS^
14567 Align @code{:=} in assignment statements
14568
14569 @item ^-A4^/ALIGN=ARROWS^
14570 Align @code{=>} in associations
14571 @end table
14572
14573 @noindent
14574 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14575 is allowed.
14576
14577
14578 @node Casing Control
14579 @subsection Casing Control
14580 @cindex Casing control in @command{gnatpp}
14581
14582 @noindent
14583 @command{gnatpp} allows you to specify the casing for reserved words,
14584 pragma names, attribute designators and identifiers.
14585 For identifiers you may define a
14586 general rule for name casing but also override this rule
14587 via a set of dictionary files.
14588
14589 Three types of casing are supported: lower case, upper case, and mixed case.
14590 Lower and upper case are self-explanatory (but since some letters in
14591 Latin1 and other GNAT-supported character sets
14592 exist only in lower-case form, an upper case conversion will have no
14593 effect on them.)
14594 ``Mixed case'' means that the first letter, and also each letter immediately
14595 following an underscore, are converted to their uppercase forms;
14596 all the other letters are converted to their lowercase forms.
14597
14598 @table @option
14599 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14600 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14601 Attribute designators are lower case
14602
14603 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14604 Attribute designators are upper case
14605
14606 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14607 Attribute designators are mixed case (this is the default)
14608
14609 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14610 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14611 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14612 lower case (this is the default)
14613
14614 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14615 Keywords are upper case
14616
14617 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14618 @item ^-nD^/NAME_CASING=AS_DECLARED^
14619 Name casing for defining occurrences are as they appear in the source file
14620 (this is the default)
14621
14622 @item ^-nU^/NAME_CASING=UPPER_CASE^
14623 Names are in upper case
14624
14625 @item ^-nL^/NAME_CASING=LOWER_CASE^
14626 Names are in lower case
14627
14628 @item ^-nM^/NAME_CASING=MIXED_CASE^
14629 Names are in mixed case
14630
14631 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14632 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14633 Pragma names are lower case
14634
14635 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14636 Pragma names are upper case
14637
14638 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14639 Pragma names are mixed case (this is the default)
14640
14641 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14642 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14643 Use @var{file} as a @emph{dictionary file} that defines
14644 the casing for a set of specified names,
14645 thereby overriding the effect on these names by
14646 any explicit or implicit
14647 ^-n^/NAME_CASING^ switch.
14648 To supply more than one dictionary file,
14649 use ^several @option{-D} switches^a list of files as options^.
14650
14651 @noindent
14652 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14653 to define the casing for the Ada predefined names and
14654 the names declared in the GNAT libraries.
14655
14656 @item ^-D-^/SPECIFIC_CASING^
14657 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14658 Do not use the default dictionary file;
14659 instead, use the casing
14660 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14661 dictionary file(s)
14662 @end table
14663
14664 @noindent
14665 The structure of a dictionary file, and details on the conventions
14666 used in the default dictionary file, are defined in @ref{Name Casing}.
14667
14668 The @option{^-D-^/SPECIFIC_CASING^} and
14669 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14670 compatible.
14671
14672
14673 @node Construct Layout Control
14674 @subsection Construct Layout Control
14675 @cindex Layout control in @command{gnatpp}
14676
14677 @noindent
14678 This group of @command{gnatpp} switches controls the layout of comments and
14679 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14680 on their effect.
14681
14682 @table @option
14683 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14684 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14685 All the comments remain unchanged
14686
14687 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14688 GNAT-style comment line indentation (this is the default).
14689
14690 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14691 Reference-manual comment line indentation.
14692
14693 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14694 GNAT-style comment beginning
14695
14696 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14697 Reformat comment blocks
14698
14699 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14700 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14701 GNAT-style layout (this is the default)
14702
14703 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14704 Compact layout
14705
14706 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14707 Uncompact layout
14708
14709 @item ^-notab^/NOTABS^
14710 All the VT characters are removed from the comment text. All the HT characters
14711 are expanded with the sequences of space characters to get to the next tab
14712 stops.
14713
14714 @end table
14715
14716 @ifclear vms
14717 @noindent
14718 The @option{-c1} and @option{-c2} switches are incompatible.
14719 The @option{-c3} and @option{-c4} switches are compatible with each other and
14720 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14721 the other comment formatting switches.
14722
14723 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14724 @end ifclear
14725
14726 @ifset vms
14727 @noindent
14728 For the @option{/COMMENTS_LAYOUT} qualifier:
14729 @itemize @bullet
14730 @item
14731 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14732 @item
14733 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14734 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14735 @end itemize
14736
14737 @noindent
14738 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14739 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14740 @end ifset
14741
14742 @node General Text Layout Control
14743 @subsection General Text Layout Control
14744
14745 @noindent
14746 These switches allow control over line length and indentation.
14747
14748 @table @option
14749 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14750 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14751 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14752
14753 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14754 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14755 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14756
14757 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14758 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14759 Indentation level for continuation lines (relative to the line being
14760 continued), @i{nnn} from 1 .. 9.
14761 The default
14762 value is one less then the (normal) indentation level, unless the
14763 indentation is set to 1 (in which case the default value for continuation
14764 line indentation is also 1)
14765 @end table
14766
14767
14768 @node Other Formatting Options
14769 @subsection Other Formatting Options
14770
14771 @noindent
14772 These switches control the inclusion of missing end/exit labels, and
14773 the indentation level in @b{case} statements.
14774
14775 @table @option
14776 @item ^-e^/NO_MISSED_LABELS^
14777 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14778 Do not insert missing end/exit labels. An end label is the name of
14779 a construct that may optionally be repeated at the end of the
14780 construct's declaration;
14781 e.g., the names of packages, subprograms, and tasks.
14782 An exit label is the name of a loop that may appear as target
14783 of an exit statement within the loop.
14784 By default, @command{gnatpp} inserts these end/exit labels when
14785 they are absent from the original source. This option suppresses such
14786 insertion, so that the formatted source reflects the original.
14787
14788 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14789 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14790 Insert a Form Feed character after a pragma Page.
14791
14792 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14793 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14794 Do not use an additional indentation level for @b{case} alternatives
14795 and variants if there are @i{nnn} or more (the default
14796 value is 10).
14797 If @i{nnn} is 0, an additional indentation level is
14798 used for @b{case} alternatives and variants regardless of their number.
14799 @end table
14800
14801 @node Setting the Source Search Path
14802 @subsection Setting the Source Search Path
14803
14804 @noindent
14805 To define the search path for the input source file, @command{gnatpp}
14806 uses the same switches as the GNAT compiler, with the same effects.
14807
14808 @table @option
14809 @item ^-I^/SEARCH=^@var{dir}
14810 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14811 The same as the corresponding gcc switch
14812
14813 @item ^-I-^/NOCURRENT_DIRECTORY^
14814 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14815 The same as the corresponding gcc switch
14816
14817 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14818 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14819 The same as the corresponding gcc switch
14820
14821 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14822 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14823 The same as the corresponding gcc switch
14824
14825 @end table
14826
14827
14828 @node Output File Control
14829 @subsection Output File Control
14830
14831 @noindent
14832 By default the output is sent to the file whose name is obtained by appending
14833 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14834 (if the file with this name already exists, it is unconditionally overwritten).
14835 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14836 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14837 as output file.
14838 The output may be redirected by the following switches:
14839
14840 @table @option
14841 @item ^-pipe^/STANDARD_OUTPUT^
14842 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14843 Send the output to @code{Standard_Output}
14844
14845 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14846 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14847 Write the output into @var{output_file}.
14848 If @var{output_file} already exists, @command{gnatpp} terminates without
14849 reading or processing the input file.
14850
14851 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14852 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14853 Write the output into @var{output_file}, overwriting the existing file
14854 (if one is present).
14855
14856 @item ^-r^/REPLACE^
14857 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14858 Replace the input source file with the reformatted output, and copy the
14859 original input source into the file whose name is obtained by appending the
14860 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14861 If a file with this name already exists, @command{gnatpp} terminates without
14862 reading or processing the input file.
14863
14864 @item ^-rf^/OVERRIDING_REPLACE^
14865 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14866 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14867 already exists, it is overwritten.
14868
14869 @item ^-rnb^/NO_BACKUP^
14870 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14871 Replace the input source file with the reformatted output without
14872 creating any backup copy of the input source.
14873 @end table
14874
14875 @noindent
14876 Options @option{^-pipe^/STANDARD_OUTPUT^},
14877 @option{^-o^/OUTPUT^} and
14878 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14879 contains only one file to reformat
14880
14881 @node Other gnatpp Switches
14882 @subsection Other @code{gnatpp} Switches
14883
14884 @noindent
14885 The additional @command{gnatpp} switches are defined in this subsection.
14886
14887 @table @option
14888 @item ^-files @var{filename}^/FILES=@var{output_file}^
14889 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14890 Take the argument source files from the specified file. This file should be an
14891 ordinary textual file containing file names separated by spaces or
14892 line breaks. You can use this switch more then once in the same call to
14893 @command{gnatpp}. You also can combine this switch with explicit list of
14894 files.
14895
14896 @item ^-v^/VERBOSE^
14897 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14898 Verbose mode;
14899 @command{gnatpp} generates version information and then
14900 a trace of the actions it takes to produce or obtain the ASIS tree.
14901
14902 @item ^-w^/WARNINGS^
14903 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14904 Warning mode;
14905 @command{gnatpp} generates a warning whenever it can not provide
14906 a required layout in the result source.
14907 @end table
14908
14909
14910 @node Formatting Rules
14911 @section Formatting Rules
14912
14913 @noindent
14914 The following subsections show how @command{gnatpp} treats ``white space'',
14915 comments, program layout, and name casing.
14916 They provide the detailed descriptions of the switches shown above.
14917
14918 @menu
14919 * White Space and Empty Lines::
14920 * Formatting Comments::
14921 * Construct Layout::
14922 * Name Casing::
14923 @end menu
14924
14925
14926 @node White Space and Empty Lines
14927 @subsection White Space and Empty Lines
14928
14929 @noindent
14930 @command{gnatpp} does not have an option to control space characters.
14931 It will add or remove spaces according to the style illustrated by the
14932 examples in the @cite{Ada Reference Manual}.
14933
14934 The only format effectors
14935 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14936 that will appear in the output file are platform-specific line breaks,
14937 and also format effectors within (but not at the end of) comments.
14938 In particular, each horizontal tab character that is not inside
14939 a comment will be treated as a space and thus will appear in the
14940 output file as zero or more spaces depending on
14941 the reformatting of the line in which it appears.
14942 The only exception is a Form Feed character, which is inserted after a
14943 pragma @code{Page} when @option{-ff} is set.
14944
14945 The output file will contain no lines with trailing ``white space'' (spaces,
14946 format effectors).
14947
14948 Empty lines in the original source are preserved
14949 only if they separate declarations or statements.
14950 In such contexts, a
14951 sequence of two or more empty lines is replaced by exactly one empty line.
14952 Note that a blank line will be removed if it separates two ``comment blocks''
14953 (a comment block is a sequence of whole-line comments).
14954 In order to preserve a visual separation between comment blocks, use an
14955 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14956 Likewise, if for some reason you wish to have a sequence of empty lines,
14957 use a sequence of empty comments instead.
14958
14959
14960 @node Formatting Comments
14961 @subsection Formatting Comments
14962
14963 @noindent
14964 Comments in Ada code are of two kinds:
14965 @itemize @bullet
14966 @item
14967 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14968 ``white space'') on a line
14969
14970 @item
14971 an @emph{end-of-line comment}, which follows some other Ada lexical element
14972 on the same line.
14973 @end itemize
14974
14975 @noindent
14976 The indentation of a whole-line comment is that of either
14977 the preceding or following line in
14978 the formatted source, depending on switch settings as will be described below.
14979
14980 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14981 between the end of the preceding Ada lexical element and the beginning
14982 of the comment as appear in the original source,
14983 unless either the comment has to be split to
14984 satisfy the line length limitation, or else the next line contains a
14985 whole line comment that is considered a continuation of this end-of-line
14986 comment (because it starts at the same position).
14987 In the latter two
14988 cases, the start of the end-of-line comment is moved right to the nearest
14989 multiple of the indentation level.
14990 This may result in a ``line overflow'' (the right-shifted comment extending
14991 beyond the maximum line length), in which case the comment is split as
14992 described below.
14993
14994 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14995 (GNAT-style comment line indentation)
14996 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14997 (reference-manual comment line indentation).
14998 With reference-manual style, a whole-line comment is indented as if it
14999 were a declaration or statement at the same place
15000 (i.e., according to the indentation of the preceding line(s)).
15001 With GNAT style, a whole-line comment that is immediately followed by an
15002 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15003 word @b{begin}, is indented based on the construct that follows it.
15004
15005 For example:
15006 @smallexample @c ada
15007 @cartouche
15008 if A then
15009     null;
15010        -- some comment
15011 else
15012    null;
15013 end if;
15014 @end cartouche
15015 @end smallexample
15016
15017 @noindent
15018 Reference-manual indentation produces:
15019
15020 @smallexample @c ada
15021 @cartouche
15022 if A then
15023    null;
15024    --  some comment
15025 else
15026    null;
15027 end if;
15028 @end cartouche
15029 @end smallexample
15030
15031 @noindent
15032 while GNAT-style indentation produces:
15033
15034 @smallexample @c ada
15035 @cartouche
15036 if A then
15037    null;
15038 --  some comment
15039 else
15040    null;
15041 end if;
15042 @end cartouche
15043 @end smallexample
15044
15045 @noindent
15046 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15047 (GNAT style comment beginning) has the following
15048 effect:
15049
15050 @itemize @bullet
15051 @item
15052 For each whole-line comment that does not end with two hyphens,
15053 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15054 to ensure that there are at least two spaces between these hyphens and the
15055 first non-blank character of the comment.
15056 @end itemize
15057
15058 @noindent
15059 For an end-of-line comment, if in the original source the next line is a
15060 whole-line comment that starts at the same position
15061 as the end-of-line comment,
15062 then the whole-line comment (and all whole-line comments
15063 that follow it and that start at the same position)
15064 will start at this position in the output file.
15065
15066 @noindent
15067 That is, if in the original source we have:
15068
15069 @smallexample @c ada
15070 @cartouche
15071 begin
15072 A := B + C;            --  B must be in the range Low1..High1
15073                        --  C must be in the range Low2..High2
15074              --B+C will be in the range Low1+Low2..High1+High2
15075 X := X + 1;
15076 @end cartouche
15077 @end smallexample
15078
15079 @noindent
15080 Then in the formatted source we get
15081
15082 @smallexample @c ada
15083 @cartouche
15084 begin
15085    A := B + C;            --  B must be in the range Low1..High1
15086                           --  C must be in the range Low2..High2
15087    --  B+C will be in the range Low1+Low2..High1+High2
15088    X := X + 1;
15089 @end cartouche
15090 @end smallexample
15091
15092 @noindent
15093 A comment that exceeds the line length limit will be split.
15094 Unless switch
15095 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15096 the line belongs to a reformattable block, splitting the line generates a
15097 @command{gnatpp} warning.
15098 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15099 comments may be reformatted in typical
15100 word processor style (that is, moving words between lines and putting as
15101 many words in a line as possible).
15102
15103
15104 @node Construct Layout
15105 @subsection Construct Layout
15106
15107 @noindent
15108 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15109 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15110 layout on the one hand, and uncompact layout
15111 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15112 can be illustrated by the following examples:
15113
15114 @iftex
15115 @cartouche
15116 @multitable @columnfractions .5 .5
15117 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15118
15119 @item
15120 @smallexample @c ada
15121 type q is record
15122    a : integer;
15123    b : integer;
15124 end record;
15125 @end smallexample
15126 @tab
15127 @smallexample @c ada
15128 type q is
15129    record
15130       a : integer;
15131       b : integer;
15132    end record;
15133 @end smallexample
15134
15135 @item
15136 @smallexample @c ada
15137 Block : declare
15138    A : Integer := 3;
15139 begin
15140    Proc (A, A);
15141 end Block;
15142 @end smallexample
15143 @tab
15144 @smallexample @c ada
15145 Block :
15146    declare
15147       A : Integer := 3;
15148    begin
15149       Proc (A, A);
15150    end Block;
15151 @end smallexample
15152
15153 @item
15154 @smallexample @c ada
15155 Clear : for J in 1 .. 10 loop
15156    A (J) := 0;
15157 end loop Clear;
15158 @end smallexample
15159 @tab
15160 @smallexample @c ada
15161 Clear :
15162    for J in 1 .. 10 loop
15163       A (J) := 0;
15164    end loop Clear;
15165 @end smallexample
15166 @end multitable
15167 @end cartouche
15168 @end iftex
15169
15170 @ifnottex
15171 @smallexample
15172 @cartouche
15173 GNAT style, compact layout              Uncompact layout
15174
15175 type q is record                        type q is
15176    a : integer;                            record
15177    b : integer;                               a : integer;
15178 end record;                                   b : integer;
15179                                            end record;
15180
15181
15182 Block : declare                         Block :
15183    A : Integer := 3;                       declare
15184 begin                                         A : Integer := 3;
15185    Proc (A, A);                            begin
15186 end Block;                                    Proc (A, A);
15187                                            end Block;
15188
15189 Clear : for J in 1 .. 10 loop           Clear :
15190    A (J) := 0;                             for J in 1 .. 10 loop
15191 end loop Clear;                               A (J) := 0;
15192                                            end loop Clear;
15193 @end cartouche
15194 @end smallexample
15195 @end ifnottex
15196
15197 @noindent
15198 A further difference between GNAT style layout and compact layout is that
15199 GNAT style layout inserts empty lines as separation for
15200 compound statements, return statements and bodies.
15201
15202
15203 @node Name Casing
15204 @subsection Name Casing
15205
15206 @noindent
15207 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15208 the same casing as the corresponding defining identifier.
15209
15210 You control the casing for defining occurrences via the
15211 @option{^-n^/NAME_CASING^} switch.
15212 @ifclear vms
15213 With @option{-nD} (``as declared'', which is the default),
15214 @end ifclear
15215 @ifset vms
15216 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15217 @end ifset
15218 defining occurrences appear exactly as in the source file
15219 where they are declared.
15220 The other ^values for this switch^options for this qualifier^ ---
15221 @option{^-nU^UPPER_CASE^},
15222 @option{^-nL^LOWER_CASE^},
15223 @option{^-nM^MIXED_CASE^} ---
15224 result in
15225 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15226 If @command{gnatpp} changes the casing of a defining
15227 occurrence, it analogously changes the casing of all the
15228 usage occurrences of this name.
15229
15230 If the defining occurrence of a name is not in the source compilation unit
15231 currently being processed by @command{gnatpp}, the casing of each reference to
15232 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15233 switch (subject to the dictionary file mechanism described below).
15234 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15235 had affected the
15236 casing for the defining occurrence of the name.
15237
15238 Some names may need to be spelled with casing conventions that are not
15239 covered by the upper-, lower-, and mixed-case transformations.
15240 You can arrange correct casing by placing such names in a
15241 @emph{dictionary file},
15242 and then supplying a @option{^-D^/DICTIONARY^} switch.
15243 The casing of names from dictionary files overrides
15244 any @option{^-n^/NAME_CASING^} switch.
15245
15246 To handle the casing of Ada predefined names and the names from GNAT libraries,
15247 @command{gnatpp} assumes a default dictionary file.
15248 The name of each predefined entity is spelled with the same casing as is used
15249 for the entity in the @cite{Ada Reference Manual}.
15250 The name of each entity in the GNAT libraries is spelled with the same casing
15251 as is used in the declaration of that entity.
15252
15253 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15254 default dictionary file.
15255 Instead, the casing for predefined and GNAT-defined names will be established
15256 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15257 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15258 will appear as just shown,
15259 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15260 To ensure that even such names are rendered in uppercase,
15261 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15262 (or else, less conveniently, place these names in upper case in a dictionary
15263 file).
15264
15265 A dictionary file is
15266 a plain text file; each line in this file can be either a blank line
15267 (containing only space characters and ASCII.HT characters), an Ada comment
15268 line, or the specification of exactly one @emph{casing schema}.
15269
15270 A casing schema is a string that has the following syntax:
15271
15272 @smallexample
15273 @cartouche
15274   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15275
15276   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15277 @end cartouche
15278 @end smallexample
15279
15280 @noindent
15281 (The @code{[]} metanotation stands for an optional part;
15282 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15283 @var{identifier} lexical element and the @var{letter_or_digit} category).
15284
15285 The casing schema string can be followed by white space and/or an Ada-style
15286 comment; any amount of white space is allowed before the string.
15287
15288 If a dictionary file is passed as
15289 @ifclear vms
15290 the value of a @option{-D@var{file}} switch
15291 @end ifclear
15292 @ifset vms
15293 an option to the @option{/DICTIONARY} qualifier
15294 @end ifset
15295 then for every
15296 simple name and every identifier, @command{gnatpp} checks if the dictionary
15297 defines the casing for the name or for some of its parts (the term ``subword''
15298 is used below to denote the part of a name which is delimited by ``_'' or by
15299 the beginning or end of the word and which does not contain any ``_'' inside):
15300
15301 @itemize @bullet
15302 @item
15303 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15304 the casing defined by the dictionary; no subwords are checked for this word
15305
15306 @item
15307 for the first subword (that is, for the subword preceding the leftmost
15308 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15309 string of the form @code{@var{simple_identifier}*}, and if it does, the
15310 casing of this @var{simple_identifier} is used for this subword
15311
15312 @item
15313 for the last subword (following the rightmost ``_'') @command{gnatpp}
15314 checks if the dictionary contains the corresponding string of the form
15315 @code{*@var{simple_identifier}}, and if it does, the casing of this
15316 @var{simple_identifier} is used for this subword
15317
15318 @item
15319 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15320 if the dictionary contains the corresponding string of the form
15321 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15322 simple_identifier is used for this subword
15323
15324 @item
15325 if more than one dictionary file is passed as @command{gnatpp} switches, each
15326 dictionary adds new casing exceptions and overrides all the existing casing
15327 exceptions set by the previous dictionaries
15328
15329 @item
15330 when @command{gnatpp} checks if the word or subword is in the dictionary,
15331 this check is not case sensitive
15332 @end itemize
15333
15334 @noindent
15335 For example, suppose we have the following source to reformat:
15336
15337 @smallexample @c ada
15338 @cartouche
15339 procedure test is
15340    name1 : integer := 1;
15341    name4_name3_name2 : integer := 2;
15342    name2_name3_name4 : Boolean;
15343    name1_var : Float;
15344 begin
15345    name2_name3_name4 := name4_name3_name2 > name1;
15346 end;
15347 @end cartouche
15348 @end smallexample
15349
15350 @noindent
15351 And suppose we have two dictionaries:
15352
15353 @smallexample
15354 @cartouche
15355 @i{dict1:}
15356    NAME1
15357    *NaMe3*
15358    *NAME2
15359 @end cartouche
15360
15361 @cartouche
15362 @i{dict2:}
15363   *NAME3*
15364 @end cartouche
15365 @end smallexample
15366
15367 @noindent
15368 If @command{gnatpp} is called with the following switches:
15369
15370 @smallexample
15371 @ifclear vms
15372 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15373 @end ifclear
15374 @ifset vms
15375 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15376 @end ifset
15377 @end smallexample
15378
15379 @noindent
15380 then we will get the following name casing in the @command{gnatpp} output:
15381
15382 @smallexample @c ada
15383 @cartouche
15384 procedure Test is
15385    NAME1             : Integer := 1;
15386    Name4_NAME3_NAME2 : integer := 2;
15387    Name2_NAME3_Name4 : Boolean;
15388    Name1_Var         : Float;
15389 begin
15390    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15391 end Test;
15392 @end cartouche
15393 @end smallexample
15394
15395
15396
15397 @c ***********************************
15398 @node File Name Krunching Using gnatkr
15399 @chapter File Name Krunching Using @code{gnatkr}
15400 @findex gnatkr
15401
15402 @noindent
15403 This chapter discusses the method used by the compiler to shorten
15404 the default file names chosen for Ada units so that they do not
15405 exceed the maximum length permitted. It also describes the
15406 @code{gnatkr} utility that can be used to determine the result of
15407 applying this shortening.
15408 @menu
15409 * About gnatkr::
15410 * Using gnatkr::
15411 * Krunching Method::
15412 * Examples of gnatkr Usage::
15413 @end menu
15414
15415 @node About gnatkr
15416 @section About @code{gnatkr}
15417
15418 @noindent
15419 The default file naming rule in GNAT
15420 is that the file name must be derived from
15421 the unit name. The exact default rule is as follows:
15422 @itemize @bullet
15423 @item
15424 Take the unit name and replace all dots by hyphens.
15425 @item
15426 If such a replacement occurs in the
15427 second character position of a name, and the first character is
15428 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15429 ^~ (tilde)^$ (dollar sign)^
15430 instead of a minus.
15431 @end itemize
15432 The reason for this exception is to avoid clashes
15433 with the standard names for children of System, Ada, Interfaces,
15434 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15435 respectively.
15436
15437 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15438 switch of the compiler activates a ``krunching''
15439 circuit that limits file names to nn characters (where nn is a decimal
15440 integer). For example, using OpenVMS,
15441 where the maximum file name length is
15442 39, the value of nn is usually set to 39, but if you want to generate
15443 a set of files that would be usable if ported to a system with some
15444 different maximum file length, then a different value can be specified.
15445 The default value of 39 for OpenVMS need not be specified.
15446
15447 The @code{gnatkr} utility can be used to determine the krunched name for
15448 a given file, when krunched to a specified maximum length.
15449
15450 @node Using gnatkr
15451 @section Using @code{gnatkr}
15452
15453 @noindent
15454 The @code{gnatkr} command has the form
15455
15456 @ifclear vms
15457 @smallexample
15458 $ gnatkr @var{name} [@var{length}]
15459 @end smallexample
15460 @end ifclear
15461
15462 @ifset vms
15463 @smallexample
15464 $ gnatkr @var{name} /COUNT=nn
15465 @end smallexample
15466 @end ifset
15467
15468 @noindent
15469 @var{name} is the uncrunched file name, derived from the name of the unit
15470 in the standard manner described in the previous section (i.e. in particular
15471 all dots are replaced by hyphens). The file name may or may not have an
15472 extension (defined as a suffix of the form period followed by arbitrary
15473 characters other than period). If an extension is present then it will
15474 be preserved in the output. For example, when krunching @file{hellofile.ads}
15475 to eight characters, the result will be hellofil.ads.
15476
15477 Note: for compatibility with previous versions of @code{gnatkr} dots may
15478 appear in the name instead of hyphens, but the last dot will always be
15479 taken as the start of an extension. So if @code{gnatkr} is given an argument
15480 such as @file{Hello.World.adb} it will be treated exactly as if the first
15481 period had been a hyphen, and for example krunching to eight characters
15482 gives the result @file{hellworl.adb}.
15483
15484 Note that the result is always all lower case (except on OpenVMS where it is
15485 all upper case). Characters of the other case are folded as required.
15486
15487 @var{length} represents the length of the krunched name. The default
15488 when no argument is given is ^8^39^ characters. A length of zero stands for
15489 unlimited, in other words do not chop except for system files where the
15490 impled crunching length is always eight characters.
15491
15492 @noindent
15493 The output is the krunched name. The output has an extension only if the
15494 original argument was a file name with an extension.
15495
15496 @node Krunching Method
15497 @section Krunching Method
15498
15499 @noindent
15500 The initial file name is determined by the name of the unit that the file
15501 contains. The name is formed by taking the full expanded name of the
15502 unit and replacing the separating dots with hyphens and
15503 using ^lowercase^uppercase^
15504 for all letters, except that a hyphen in the second character position is
15505 replaced by a ^tilde^dollar sign^ if the first character is
15506 ^a, i, g, or s^A, I, G, or S^.
15507 The extension is @code{.ads} for a
15508 specification and @code{.adb} for a body.
15509 Krunching does not affect the extension, but the file name is shortened to
15510 the specified length by following these rules:
15511
15512 @itemize @bullet
15513 @item
15514 The name is divided into segments separated by hyphens, tildes or
15515 underscores and all hyphens, tildes, and underscores are
15516 eliminated. If this leaves the name short enough, we are done.
15517
15518 @item
15519 If the name is too long, the longest segment is located (left-most
15520 if there are two of equal length), and shortened by dropping
15521 its last character. This is repeated until the name is short enough.
15522
15523 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15524 to fit the name into 8 characters as required by some operating systems.
15525
15526 @smallexample
15527 our-strings-wide_fixed 22
15528 our strings wide fixed 19
15529 our string  wide fixed 18
15530 our strin   wide fixed 17
15531 our stri    wide fixed 16
15532 our stri    wide fixe  15
15533 our str     wide fixe  14
15534 our str     wid  fixe  13
15535 our str     wid  fix   12
15536 ou  str     wid  fix   11
15537 ou  st      wid  fix   10
15538 ou  st      wi   fix   9
15539 ou  st      wi   fi    8
15540 Final file name: oustwifi.adb
15541 @end smallexample
15542
15543 @item
15544 The file names for all predefined units are always krunched to eight
15545 characters. The krunching of these predefined units uses the following
15546 special prefix replacements:
15547
15548 @table @file
15549 @item ada-
15550 replaced by @file{^a^A^-}
15551
15552 @item gnat-
15553 replaced by @file{^g^G^-}
15554
15555 @item interfaces-
15556 replaced by @file{^i^I^-}
15557
15558 @item system-
15559 replaced by @file{^s^S^-}
15560 @end table
15561
15562 These system files have a hyphen in the second character position. That
15563 is why normal user files replace such a character with a
15564 ^tilde^dollar sign^, to
15565 avoid confusion with system file names.
15566
15567 As an example of this special rule, consider
15568 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15569
15570 @smallexample
15571 ada-strings-wide_fixed 22
15572 a-  strings wide fixed 18
15573 a-  string  wide fixed 17
15574 a-  strin   wide fixed 16
15575 a-  stri    wide fixed 15
15576 a-  stri    wide fixe  14
15577 a-  str     wide fixe  13
15578 a-  str     wid  fixe  12
15579 a-  str     wid  fix   11
15580 a-  st      wid  fix   10
15581 a-  st      wi   fix   9
15582 a-  st      wi   fi    8
15583 Final file name: a-stwifi.adb
15584 @end smallexample
15585 @end itemize
15586
15587 Of course no file shortening algorithm can guarantee uniqueness over all
15588 possible unit names, and if file name krunching is used then it is your
15589 responsibility to ensure that no name clashes occur. The utility
15590 program @code{gnatkr} is supplied for conveniently determining the
15591 krunched name of a file.
15592
15593 @node Examples of gnatkr Usage
15594 @section Examples of @code{gnatkr} Usage
15595
15596 @smallexample
15597 @iftex
15598 @leftskip=0cm
15599 @end iftex
15600 @ifclear vms
15601 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15602 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15603 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15604 $ gnatkr grandparent-parent-child     --> grparchi
15605 @end ifclear
15606 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15607 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15608 @end smallexample
15609
15610 @node Preprocessing Using gnatprep
15611 @chapter Preprocessing Using @code{gnatprep}
15612 @findex gnatprep
15613
15614 @noindent
15615 The @code{gnatprep} utility provides
15616 a simple preprocessing capability for Ada programs.
15617 It is designed for use with GNAT, but is not dependent on any special
15618 features of GNAT.
15619
15620 @menu
15621 * Using gnatprep::
15622 * Switches for gnatprep::
15623 * Form of Definitions File::
15624 * Form of Input Text for gnatprep::
15625 @end menu
15626
15627 @node Using gnatprep
15628 @section Using @code{gnatprep}
15629
15630 @noindent
15631 To call @code{gnatprep} use
15632
15633 @smallexample
15634 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15635 @end smallexample
15636
15637 @noindent
15638 where
15639 @table @code
15640 @item infile
15641 is the full name of the input file, which is an Ada source
15642 file containing preprocessor directives.
15643
15644 @item outfile
15645 is the full name of the output file, which is an Ada source
15646 in standard Ada form. When used with GNAT, this file name will
15647 normally have an ads or adb suffix.
15648
15649 @item deffile
15650 is the full name of a text file containing definitions of
15651 symbols to be referenced by the preprocessor. This argument is
15652 optional, and can be replaced by the use of the @option{-D} switch.
15653
15654 @item switches
15655 is an optional sequence of switches as described in the next section.
15656 @end table
15657
15658 @node Switches for gnatprep
15659 @section Switches for @code{gnatprep}
15660
15661 @table @option
15662 @c !sort!
15663
15664 @item ^-b^/BLANK_LINES^
15665 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15666 Causes both preprocessor lines and the lines deleted by
15667 preprocessing to be replaced by blank lines in the output source file,
15668 preserving line numbers in the output file.
15669
15670 @item ^-c^/COMMENTS^
15671 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15672 Causes both preprocessor lines and the lines deleted
15673 by preprocessing to be retained in the output source as comments marked
15674 with the special string @code{"--! "}. This option will result in line numbers
15675 being preserved in the output file.
15676
15677 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15678 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15679 Defines a new symbol, associated with value. If no value is given on the
15680 command line, then symbol is considered to be @code{True}. This switch
15681 can be used in place of a definition file.
15682
15683 @ifset vms
15684 @item /REMOVE
15685 @cindex @option{/REMOVE} (@command{gnatprep})
15686 This is the default setting which causes lines deleted by preprocessing
15687 to be entirely removed from the output file.
15688 @end ifset
15689
15690 @item ^-r^/REFERENCE^
15691 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15692 Causes a @code{Source_Reference} pragma to be generated that
15693 references the original input file, so that error messages will use
15694 the file name of this original file. The use of this switch implies
15695 that preprocessor lines are not to be removed from the file, so its
15696 use will force @option{^-b^/BLANK_LINES^} mode if
15697 @option{^-c^/COMMENTS^}
15698 has not been specified explicitly.
15699
15700 Note that if the file to be preprocessed contains multiple units, then
15701 it will be necessary to @code{gnatchop} the output file from
15702 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15703 in the preprocessed file, it will be respected by
15704 @code{gnatchop ^-r^/REFERENCE^}
15705 so that the final chopped files will correctly refer to the original
15706 input source file for @code{gnatprep}.
15707
15708 @item ^-s^/SYMBOLS^
15709 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15710 Causes a sorted list of symbol names and values to be
15711 listed on the standard output file.
15712
15713 @item ^-u^/UNDEFINED^
15714 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15715 Causes undefined symbols to be treated as having the value FALSE in the context
15716 of a preprocessor test. In the absence of this option, an undefined symbol in
15717 a @code{#if} or @code{#elsif} test will be treated as an error.
15718
15719 @end table
15720
15721 @ifclear vms
15722 @noindent
15723 Note: if neither @option{-b} nor @option{-c} is present,
15724 then preprocessor lines and
15725 deleted lines are completely removed from the output, unless -r is
15726 specified, in which case -b is assumed.
15727 @end ifclear
15728
15729 @node Form of Definitions File
15730 @section Form of Definitions File
15731
15732 @noindent
15733 The definitions file contains lines of the form
15734
15735 @smallexample
15736 symbol := value
15737 @end smallexample
15738
15739 @noindent
15740 where symbol is an identifier, following normal Ada (case-insensitive)
15741 rules for its syntax, and value is one of the following:
15742
15743 @itemize @bullet
15744 @item
15745 Empty, corresponding to a null substitution
15746 @item
15747 A string literal using normal Ada syntax
15748 @item
15749 Any sequence of characters from the set
15750 (letters, digits, period, underline).
15751 @end itemize
15752
15753 @noindent
15754 Comment lines may also appear in the definitions file, starting with
15755 the usual @code{--},
15756 and comments may be added to the definitions lines.
15757
15758 @node Form of Input Text for gnatprep
15759 @section Form of Input Text for @code{gnatprep}
15760
15761 @noindent
15762 The input text may contain preprocessor conditional inclusion lines,
15763 as well as general symbol substitution sequences.
15764
15765 The preprocessor conditional inclusion commands have the form
15766
15767 @smallexample
15768 @group
15769 @cartouche
15770 #if @i{expression} [then]
15771    lines
15772 #elsif @i{expression} [then]
15773    lines
15774 #elsif @i{expression} [then]
15775    lines
15776 ...
15777 #else
15778    lines
15779 #end if;
15780 @end cartouche
15781 @end group
15782 @end smallexample
15783
15784 @noindent
15785 In this example, @i{expression} is defined by the following grammar:
15786 @smallexample
15787 @i{expression} ::=  <symbol>
15788 @i{expression} ::=  <symbol> = "<value>"
15789 @i{expression} ::=  <symbol> = <symbol>
15790 @i{expression} ::=  <symbol> 'Defined
15791 @i{expression} ::=  not @i{expression}
15792 @i{expression} ::=  @i{expression} and @i{expression}
15793 @i{expression} ::=  @i{expression} or @i{expression}
15794 @i{expression} ::=  @i{expression} and then @i{expression}
15795 @i{expression} ::=  @i{expression} or else @i{expression}
15796 @i{expression} ::=  ( @i{expression} )
15797 @end smallexample
15798
15799 @noindent
15800 For the first test (@i{expression} ::= <symbol>) the symbol must have
15801 either the value true or false, that is to say the right-hand of the
15802 symbol definition must be one of the (case-insensitive) literals
15803 @code{True} or @code{False}. If the value is true, then the
15804 corresponding lines are included, and if the value is false, they are
15805 excluded.
15806
15807 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15808 the symbol has been defined in the definition file or by a @option{-D}
15809 switch on the command line. Otherwise, the test is false.
15810
15811 The equality tests are case insensitive, as are all the preprocessor lines.
15812
15813 If the symbol referenced is not defined in the symbol definitions file,
15814 then the effect depends on whether or not switch @option{-u}
15815 is specified. If so, then the symbol is treated as if it had the value
15816 false and the test fails. If this switch is not specified, then
15817 it is an error to reference an undefined symbol. It is also an error to
15818 reference a symbol that is defined with a value other than @code{True}
15819 or @code{False}.
15820
15821 The use of the @code{not} operator inverts the sense of this logical test, so
15822 that the lines are included only if the symbol is not defined.
15823 The @code{then} keyword is optional as shown
15824
15825 The @code{#} must be the first non-blank character on a line, but
15826 otherwise the format is free form. Spaces or tabs may appear between
15827 the @code{#} and the keyword. The keywords and the symbols are case
15828 insensitive as in normal Ada code. Comments may be used on a
15829 preprocessor line, but other than that, no other tokens may appear on a
15830 preprocessor line. Any number of @code{elsif} clauses can be present,
15831 including none at all. The @code{else} is optional, as in Ada.
15832
15833 The @code{#} marking the start of a preprocessor line must be the first
15834 non-blank character on the line, i.e. it must be preceded only by
15835 spaces or horizontal tabs.
15836
15837 Symbol substitution outside of preprocessor lines is obtained by using
15838 the sequence
15839
15840 @smallexample
15841 $symbol
15842 @end smallexample
15843
15844 @noindent
15845 anywhere within a source line, except in a comment or within a
15846 string literal. The identifier
15847 following the @code{$} must match one of the symbols defined in the symbol
15848 definition file, and the result is to substitute the value of the
15849 symbol in place of @code{$symbol} in the output file.
15850
15851 Note that although the substitution of strings within a string literal
15852 is not possible, it is possible to have a symbol whose defined value is
15853 a string literal. So instead of setting XYZ to @code{hello} and writing:
15854
15855 @smallexample
15856 Header : String := "$XYZ";
15857 @end smallexample
15858
15859 @noindent
15860 you should set XYZ to @code{"hello"} and write:
15861
15862 @smallexample
15863 Header : String := $XYZ;
15864 @end smallexample
15865
15866 @noindent
15867 and then the substitution will occur as desired.
15868
15869 @ifset vms
15870 @node The GNAT Run-Time Library Builder gnatlbr
15871 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15872 @findex gnatlbr
15873 @cindex Library builder
15874
15875 @noindent
15876 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15877 supplied configuration pragmas.
15878
15879 @menu
15880 * Running gnatlbr::
15881 * Switches for gnatlbr::
15882 * Examples of gnatlbr Usage::
15883 @end menu
15884
15885 @node Running gnatlbr
15886 @section Running @code{gnatlbr}
15887
15888 @noindent
15889 The @code{gnatlbr} command has the form
15890
15891 @smallexample
15892 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15893 @end smallexample
15894
15895 @node Switches for gnatlbr
15896 @section Switches for @code{gnatlbr}
15897
15898 @noindent
15899 @code{gnatlbr} recognizes the following switches:
15900
15901 @table @option
15902 @c !sort!
15903 @item /CREATE=directory
15904 @cindex @code{/CREATE} (@code{gnatlbr})
15905      Create the new run-time library in the specified directory.
15906
15907 @item /SET=directory
15908 @cindex @code{/SET} (@code{gnatlbr})
15909      Make the library in the specified directory the current run-time
15910      library.
15911
15912 @item /DELETE=directory
15913 @cindex @code{/DELETE} (@code{gnatlbr})
15914      Delete the run-time library in the specified directory.
15915
15916 @item /CONFIG=file
15917 @cindex @code{/CONFIG} (@code{gnatlbr})
15918      With /CREATE:
15919      Use the configuration pragmas in the specified file when building
15920      the library.
15921
15922      With /SET:
15923      Use the configuration pragmas in the specified file when compiling.
15924
15925 @end table
15926
15927 @node Examples of gnatlbr Usage
15928 @section Example of @code{gnatlbr} Usage
15929
15930 @smallexample
15931 Contents of VAXFLOAT.ADC:
15932 pragma Float_Representation (VAX_Float);
15933
15934 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15935
15936 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15937
15938 @end smallexample
15939 @end ifset
15940
15941 @node The GNAT Library Browser gnatls
15942 @chapter The GNAT Library Browser @code{gnatls}
15943 @findex gnatls
15944 @cindex Library browser
15945
15946 @noindent
15947 @code{gnatls} is a tool that outputs information about compiled
15948 units. It gives the relationship between objects, unit names and source
15949 files. It can also be used to check the source dependencies of a unit
15950 as well as various characteristics.
15951
15952 @menu
15953 * Running gnatls::
15954 * Switches for gnatls::
15955 * Examples of gnatls Usage::
15956 @end menu
15957
15958 @node Running gnatls
15959 @section Running @code{gnatls}
15960
15961 @noindent
15962 The @code{gnatls} command has the form
15963
15964 @smallexample
15965 $ gnatls switches @var{object_or_ali_file}
15966 @end smallexample
15967
15968 @noindent
15969 The main argument is the list of object or @file{ali} files
15970 (@pxref{The Ada Library Information Files})
15971 for which information is requested.
15972
15973 In normal mode, without additional option, @code{gnatls} produces a
15974 four-column listing. Each line represents information for a specific
15975 object. The first column gives the full path of the object, the second
15976 column gives the name of the principal unit in this object, the third
15977 column gives the status of the source and the fourth column gives the
15978 full path of the source representing this unit.
15979 Here is a simple example of use:
15980
15981 @smallexample
15982 $ gnatls *.o
15983 ^./^[]^demo1.o            demo1            DIF demo1.adb
15984 ^./^[]^demo2.o            demo2             OK demo2.adb
15985 ^./^[]^hello.o            h1                OK hello.adb
15986 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15987 ^./^[]^instr.o            instr             OK instr.adb
15988 ^./^[]^tef.o              tef              DIF tef.adb
15989 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15990 ^./^[]^tgef.o             tgef             DIF tgef.adb
15991 @end smallexample
15992
15993 @noindent
15994 The first line can be interpreted as follows: the main unit which is
15995 contained in
15996 object file @file{demo1.o} is demo1, whose main source is in
15997 @file{demo1.adb}. Furthermore, the version of the source used for the
15998 compilation of demo1 has been modified (DIF). Each source file has a status
15999 qualifier which can be:
16000
16001 @table @code
16002 @item OK (unchanged)
16003 The version of the source file used for the compilation of the
16004 specified unit corresponds exactly to the actual source file.
16005
16006 @item MOK (slightly modified)
16007 The version of the source file used for the compilation of the
16008 specified unit differs from the actual source file but not enough to
16009 require recompilation. If you use gnatmake with the qualifier
16010 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16011 MOK will not be recompiled.
16012
16013 @item DIF (modified)
16014 No version of the source found on the path corresponds to the source
16015 used to build this object.
16016
16017 @item ??? (file not found)
16018 No source file was found for this unit.
16019
16020 @item HID (hidden,  unchanged version not first on PATH)
16021 The version of the source that corresponds exactly to the source used
16022 for compilation has been found on the path but it is hidden by another
16023 version of the same source that has been modified.
16024
16025 @end table
16026
16027 @node Switches for gnatls
16028 @section Switches for @code{gnatls}
16029
16030 @noindent
16031 @code{gnatls} recognizes the following switches:
16032
16033 @table @option
16034 @c !sort!
16035 @item ^-a^/ALL_UNITS^
16036 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16037 Consider all units, including those of the predefined Ada library.
16038 Especially useful with @option{^-d^/DEPENDENCIES^}.
16039
16040 @item ^-d^/DEPENDENCIES^
16041 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16042 List sources from which specified units depend on.
16043
16044 @item ^-h^/OUTPUT=OPTIONS^
16045 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16046 Output the list of options.
16047
16048 @item ^-o^/OUTPUT=OBJECTS^
16049 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16050 Only output information about object files.
16051
16052 @item ^-s^/OUTPUT=SOURCES^
16053 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16054 Only output information about source files.
16055
16056 @item ^-u^/OUTPUT=UNITS^
16057 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16058 Only output information about compilation units.
16059
16060 @item ^-files^/FILES^=@var{file}
16061 @cindex @option{^-files^/FILES^} (@code{gnatls})
16062 Take as arguments the files listed in text file @var{file}.
16063 Text file @var{file} may contain empty lines that are ignored.
16064 Each non empty line should contain the name of an existing file.
16065 Several such switches may be specified simultaneously.
16066
16067 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16068 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16069 @itemx ^-I^/SEARCH=^@var{dir}
16070 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16071 @itemx -nostdinc
16072 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16073 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16074 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16075 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16076 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16077 (see @ref{Switches for gnatmake}).
16078
16079 @item --RTS=@var{rts-path}
16080 @cindex @option{--RTS} (@code{gnatls})
16081 Specifies the default location of the runtime library. Same meaning as the
16082 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16083
16084 @item ^-v^/OUTPUT=VERBOSE^
16085 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16086 Verbose mode. Output the complete source and object paths. Do not use
16087 the default column layout but instead use long format giving as much as
16088 information possible on each requested units, including special
16089 characteristics such as:
16090
16091 @table @code
16092 @item  Preelaborable
16093 The unit is preelaborable in the Ada 95 sense.
16094
16095 @item No_Elab_Code
16096 No elaboration code has been produced by the compiler for this unit.
16097
16098 @item Pure
16099 The unit is pure in the Ada 95 sense.
16100
16101 @item Elaborate_Body
16102 The unit contains a pragma Elaborate_Body.
16103
16104 @item Remote_Types
16105 The unit contains a pragma Remote_Types.
16106
16107 @item Shared_Passive
16108 The unit contains a pragma Shared_Passive.
16109
16110 @item Predefined
16111 This unit is part of the predefined environment and cannot be modified
16112 by the user.
16113
16114 @item Remote_Call_Interface
16115 The unit contains a pragma Remote_Call_Interface.
16116
16117 @end table
16118
16119 @end table
16120
16121 @node Examples of gnatls Usage
16122 @section Example of @code{gnatls} Usage
16123 @ifclear vms
16124
16125 @noindent
16126 Example of using the verbose switch. Note how the source and
16127 object paths are affected by the -I switch.
16128
16129 @smallexample
16130 $ gnatls -v -I.. demo1.o
16131
16132 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16133
16134 Source Search Path:
16135    <Current_Directory>
16136    ../
16137    /home/comar/local/adainclude/
16138
16139 Object Search Path:
16140    <Current_Directory>
16141    ../
16142    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16143
16144 ./demo1.o
16145    Unit =>
16146      Name   => demo1
16147      Kind   => subprogram body
16148      Flags  => No_Elab_Code
16149      Source => demo1.adb    modified
16150 @end smallexample
16151
16152 @noindent
16153 The following is an example of use of the dependency list.
16154 Note the use of the -s switch
16155 which gives a straight list of source files. This can be useful for
16156 building specialized scripts.
16157
16158 @smallexample
16159 $ gnatls -d demo2.o
16160 ./demo2.o   demo2        OK demo2.adb
16161                          OK gen_list.ads
16162                          OK gen_list.adb
16163                          OK instr.ads
16164                          OK instr-child.ads
16165
16166 $ gnatls -d -s -a demo1.o
16167 demo1.adb
16168 /home/comar/local/adainclude/ada.ads
16169 /home/comar/local/adainclude/a-finali.ads
16170 /home/comar/local/adainclude/a-filico.ads
16171 /home/comar/local/adainclude/a-stream.ads
16172 /home/comar/local/adainclude/a-tags.ads
16173 gen_list.ads
16174 gen_list.adb
16175 /home/comar/local/adainclude/gnat.ads
16176 /home/comar/local/adainclude/g-io.ads
16177 instr.ads
16178 /home/comar/local/adainclude/system.ads
16179 /home/comar/local/adainclude/s-exctab.ads
16180 /home/comar/local/adainclude/s-finimp.ads
16181 /home/comar/local/adainclude/s-finroo.ads
16182 /home/comar/local/adainclude/s-secsta.ads
16183 /home/comar/local/adainclude/s-stalib.ads
16184 /home/comar/local/adainclude/s-stoele.ads
16185 /home/comar/local/adainclude/s-stratt.ads
16186 /home/comar/local/adainclude/s-tasoli.ads
16187 /home/comar/local/adainclude/s-unstyp.ads
16188 /home/comar/local/adainclude/unchconv.ads
16189 @end smallexample
16190 @end ifclear
16191
16192 @ifset vms
16193 @smallexample
16194 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16195
16196 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16197 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16198 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16199 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16200 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16201 demo1.adb
16202 gen_list.ads
16203 gen_list.adb
16204 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16205 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16206 instr.ads
16207 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16208 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16209 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16210 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16211 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16212 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16213 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16214 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16215 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16216 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16217 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16218 @end smallexample
16219 @end ifset
16220
16221 @node Cleaning Up Using gnatclean
16222 @chapter Cleaning Up Using @code{gnatclean}
16223 @findex gnatclean
16224 @cindex Cleaning tool
16225
16226 @noindent
16227 @code{gnatclean} is a tool that allows the deletion of files produced by the
16228 compiler, binder and linker, including ALI files, object files, tree files,
16229 expanded source files, library files, interface copy source files, binder
16230 generated files and executable files.
16231
16232 @menu
16233 * Running gnatclean::
16234 * Switches for gnatclean::
16235 * Examples of gnatclean Usage::
16236 @end menu
16237
16238 @node Running gnatclean
16239 @section Running @code{gnatclean}
16240
16241 @noindent
16242 The @code{gnatclean} command has the form:
16243
16244 @smallexample
16245 $ gnatclean switches @var{names}
16246 @end smallexample
16247
16248 @noindent
16249 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16250 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16251 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16252
16253 @noindent
16254 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16255 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16256 the linker. In informative-only mode, specified by switch
16257 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16258 normal mode is listed, but no file is actually deleted.
16259
16260 @node Switches for gnatclean
16261 @section Switches for @code{gnatclean}
16262
16263 @noindent
16264 @code{gnatclean} recognizes the following switches:
16265
16266 @table @option
16267 @c !sort!
16268 @item ^-c^/COMPILER_FILES_ONLY^
16269 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16270 Only attempt to delete the files produced by the compiler, not those produced
16271 by the binder or the linker. The files that are not to be deleted are library
16272 files, interface copy files, binder generated files and executable files.
16273
16274 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16275 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16276 Indicate that ALI and object files should normally be found in directory
16277 @var{dir}.
16278
16279 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16280 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16281 When using project files, if some errors or warnings are detected during
16282 parsing and verbose mode is not in effect (no use of switch
16283 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16284 file, rather than its simple file name.
16285
16286 @item ^-h^/HELP^
16287 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16288 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16289
16290 @item ^-n^/NODELETE^
16291 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16292 Informative-only mode. Do not delete any files. Output the list of the files
16293 that would have been deleted if this switch was not specified.
16294
16295 @item ^-P^/PROJECT_FILE=^@var{project}
16296 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16297 Use project file @var{project}. Only one such switch can be used.
16298 When cleaning a project file, the files produced by the compilation of the
16299 immediate sources or inherited sources of the project files are to be
16300 deleted. This is not depending on the presence or not of executable names
16301 on the command line.
16302
16303 @item ^-q^/QUIET^
16304 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16305 Quiet output. If there are no error, do not ouuput anything, except in
16306 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16307 (switch ^-n^/NODELETE^).
16308
16309 @item ^-r^/RECURSIVE^
16310 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16311 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16312 clean all imported and extended project files, recursively. If this switch
16313 is not specified, only the files related to the main project file are to be
16314 deleted. This switch has no effect if no project file is specified.
16315
16316 @item ^-v^/VERBOSE^
16317 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16318 Verbose mode.
16319
16320 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16321 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16322 Indicates the verbosity of the parsing of GNAT project files.
16323 See @ref{Switches Related to Project Files}.
16324
16325 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16326 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16327 Indicates that external variable @var{name} has the value @var{value}.
16328 The Project Manager will use this value for occurrences of
16329 @code{external(name)} when parsing the project file.
16330 See @ref{Switches Related to Project Files}.
16331
16332 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16333 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16334 When searching for ALI and object files, look in directory
16335 @var{dir}.
16336
16337 @item ^-I^/SEARCH=^@var{dir}
16338 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16339 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16340
16341 @item ^-I-^/NOCURRENT_DIRECTORY^
16342 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16343 @cindex Source files, suppressing search
16344 Do not look for ALI or object files in the directory
16345 where @code{gnatclean} was invoked.
16346
16347 @end table
16348
16349 @node Examples of gnatclean Usage
16350 @section Examples of @code{gnatclean} Usage
16351
16352 @ifclear vms
16353 @node GNAT and Libraries
16354 @chapter GNAT and Libraries
16355 @cindex Library, building, installing, using
16356
16357 @noindent
16358 This chapter describes how to build and use
16359 libraries with GNAT, and also shows how to recompile the GNAT run-time library.
16360 You should be familiar with the
16361 Project Manager facility (see @ref{GNAT Project Manager}) before reading this
16362 chapter.
16363
16364 @menu
16365 * Introduction to Libraries in GNAT::
16366 * General Ada Libraries::
16367 * Stand-alone Ada Libraries::
16368 * Rebuilding the GNAT Run-Time Library::
16369 @end menu
16370
16371 @node Introduction to Libraries in GNAT
16372 @section Introduction to Libraries in GNAT
16373
16374 @noindent
16375 A library is, conceptually, a collection of objects which does not have its
16376 own main thread of execution, but rather provides certain services to the
16377 applications that use it. A library can be either statically linked with the
16378 application, in which case its code is directly included in the application,
16379 or, on platforms that support it, be dynamically linked, in which case
16380 its code is shared by all applications making use of this library.
16381
16382 GNAT supports both types of libraries.
16383 In the static case, the compiled code can be provided in different ways.
16384 The simplest approach is to provide directly the
16385 set of objects resulting from compilation of the library source files.
16386 Alternatively, you can group the objects into an archive using whatever
16387 commands are provided by the operating system. For the latter case,
16388 the objects are grouped into a shared library.
16389
16390 In the GNAT environment, a library has two types of components:
16391 @itemize @bullet
16392 @item
16393 Source files.
16394 @item
16395 Compiled code and @file{ALI} files.
16396 See @ref{The Ada Library Information Files}.
16397 @end itemize
16398
16399 @noindent
16400 A GNAT library may either completely expose its source files to the
16401 compilation context of the user's application.
16402 Alternatively, it may expose
16403 a limited subset of its source files, called @emph{interface units},
16404 in which case the library is referred to as a @emph{stand-alone library}
16405 (see @ref{Stand-alone Ada Libraries}). In addition, GNAT fully supports
16406 foreign libraries, which are only available in the object format.
16407
16408 All compilation units comprising
16409 an application are elaborated, in an order partially defined by Ada language
16410 semantics.
16411 Where possible, GNAT provides facilities
16412 to ensure that compilation units of a library are automatically elaborated;
16413 however, there are cases where this must be responsibility of a user. This will
16414 be addressed in greater detail below.
16415
16416 @node General Ada Libraries
16417 @section General Ada Libraries
16418
16419 @menu
16420 * Building the library::
16421 * Installing the library::
16422 * Using the library::
16423 @end menu
16424
16425 @node Building the library
16426 @subsection Building the library
16427
16428 @noindent
16429 The easiest way to build a library is to use the Project Manager,
16430 which supports a special type of projects called Library Projects
16431 (see @ref{Library Projects}).
16432
16433 A project is considered a library project, when two project-level attributes
16434 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16435 control different aspects of library configuration, additional optional
16436 project-level attributes can be specified:
16437 @table @code
16438 @item Library_Kind
16439 This attribute controls whether the library is to be static or shared
16440
16441 @item Library_Version
16442 This attribute specifies what is the library version; this value is used
16443 during dynamic linking of shared libraries to determine if the currently
16444 installed versions of the binaries are compatible.
16445
16446 @item Library_Options
16447 @item Library_GCC
16448 These attributes specify additional low-level options to be used during
16449 library generation, and redefine the actual application used to generate
16450 library.
16451 @end table
16452
16453 @noindent
16454 The GNAT Project Manager takes full care of the library maintenance task,
16455 including recompilation of the source files for which objects do not exist
16456 or are not up to date, assembly of the library archive, and installation of
16457 the library, i.e. copying associated source, object and @file{ALI} files
16458 to the specified location.
16459
16460 It is not entirely trivial to correctly perform all the steps required to
16461 produce a library. We recommend that you use the GNAT Project Manager
16462 for this task. In special cases where this is not desired, the necessary
16463 steps are discussed below.
16464
16465 There are various possibilities for compiling the units that make up the
16466 library: for example with a Makefile (see @ref{Using the GNU make Utility})
16467 or with a conventional script.
16468 For simple libraries, it is also possible to create a
16469 dummy main program which depends upon all the packages that comprise the
16470 interface of the library. This dummy main program can then be given to
16471 @command{gnatmake}, which will ensure that all necessary objects are built.
16472
16473 After this task is accomplished, you should follow the standard procedure
16474 of the underlying operating system to produce the static or shared library.
16475
16476 Here is an example of such a dummy program:
16477 @smallexample @c ada
16478 @group
16479 with My_Lib.Service1;
16480 with My_Lib.Service2;
16481 with My_Lib.Service3;
16482 procedure My_Lib_Dummy is
16483 begin
16484    null;
16485 end;
16486 @end group
16487 @end smallexample
16488
16489 @noindent
16490 Here are the generic commands that will build an archive or a shared library.
16491
16492 @smallexample
16493 # compiling the library
16494 $ gnatmake -c my_lib_dummy.adb
16495
16496 # we don't need the dummy object itself
16497 $ rm my_lib_dummy.o my_lib_dummy.ali
16498
16499 # create an archive with the remaining objects
16500 $ ar rc libmy_lib.a *.o
16501 # some systems may require "ranlib" to be run as well
16502
16503 # or create a shared library
16504 $ gcc -shared -o libmy_lib.so *.o
16505 # some systems may require the code to have been compiled with -fPIC
16506
16507 # remove the object files that are now in the library
16508 $ rm *.o
16509
16510 # Make the ALI files read-only so that gnatmake will not try to
16511 # regenerate the objects that are in the library
16512 $ chmod -w *.ali
16513 @end smallexample
16514
16515 @noindent
16516 Please note that the library must have a name of the form @file{libxxx.a} or
16517 @file{libxxx.so} in order to be accessed by the directive @option{-lxxx}
16518 at link time.
16519
16520 @node Installing the library
16521 @subsection Installing the library
16522
16523 @noindent
16524 In the GNAT model, installing a library consists in copying into a specific
16525 location the files that make up this library. When the library is built using
16526 projects, it is automatically installed in the location specified in the
16527 project by means of the attribute @code{Library_Dir},
16528 otherwise the user must specify the destination.
16529 GNAT also supports installing the sources in a
16530 different directory from the other files (@file{ALI}, objects, archives)
16531 since the source path and the object path can be specified separately.
16532
16533 The system administrator can place general purpose libraries in the default
16534 compiler paths, by specifying the libraries' location in the configuration
16535 files @file{ada_source_path} and @file{ada_object_path}.
16536 These configuration files must be located in the GNAT
16537 installation tree at the same place as the gcc spec file. The location of
16538 the gcc spec file can be determined as follows:
16539 @smallexample
16540 $ gcc -v
16541 @end smallexample
16542
16543 @noindent
16544 The configuration files mentioned above have a simple format: each line
16545 must contain one unique directory name.
16546 Those names are added to the corresponding path
16547 in their order of appearance in the file. The names can be either absolute
16548 or relative; in the latter case, they are relative to where theses files
16549 are located.
16550
16551 The files @file{ada_source_path} and @file{ada_object_path} might not be
16552 present in a
16553 GNAT installation, in which case, GNAT will look for its run-time library in
16554 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16555 objects and @file{ALI} files). When the files exist, the compiler does not
16556 look in @file{adainclude} and @file{adalib}, and thus the
16557 @file{ada_source_path} file
16558 must contain the location for the GNAT run-time sources (which can simply
16559 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16560 contain the location for the GNAT run-time objects (which can simply
16561 be @file{adalib}).
16562
16563 You can also specify a new default path to the run-time library at compilation
16564 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16565 the run-time library you want your program to be compiled with. This switch is
16566 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16567 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16568
16569 It is possible to install a library before or after the standard GNAT
16570 library, by reordering the lines in the configuration files. In general, a
16571 library must be installed before the GNAT library if it redefines
16572 any part of it.
16573
16574
16575 @node Using the library
16576 @subsection Using the library
16577
16578 @noindent
16579 Once again, the project facility greatly simplifies the addition of libraries
16580 to the compilation. If the project file for an application lists a library
16581 project in its @code{with} clause, the Project Manager will ensure that the
16582 library files are consistent, and that they are considered during the
16583 compilation and linking of the application.
16584
16585 Even if you have a third-party, non-Ada library, you can still use GNAT's
16586 Project Manager facility to provide a wrapper for it. The following project for
16587 example, when @code{with}ed in your main project, will link with the
16588 third-party library @file{liba.a}:
16589
16590 @smallexample @c projectfile
16591 @group
16592 project Liba is
16593    for Source_Dirs use ();
16594    for Library_Dir use "lib";
16595    for Library_Name use "a";
16596    for Library_Kind use "static";
16597 end Liba;
16598 @end group
16599 @end smallexample
16600
16601 @noindent
16602 In order to use an Ada library manually, you need to make sure that this
16603 library is on both your source and object path
16604 (see @ref{Search Paths and the Run-Time Library (RTL)},
16605 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16606 in an archive or a shared library, you need to specify the desired
16607 library at link time.
16608
16609 For example, you can use the library @file{mylib} installed in
16610 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16611
16612 @smallexample
16613 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16614   -largs -lmy_lib
16615 @end smallexample
16616
16617 @noindent
16618 This can be expressed more simply:
16619 @smallexample
16620 $ gnatmake my_appl
16621 @end smallexample
16622 @noindent
16623 when the following conditions are met:
16624 @itemize @bullet
16625 @item
16626 @file{/dir/my_lib_src} has been added by the user to the environment
16627 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16628 @file{ada_source_path}
16629 @item
16630 @file{/dir/my_lib_obj} has been added by the user to the environment
16631 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16632 @file{ada_object_path}
16633 @item
16634 a pragma @code{Linker_Options} has been added to one of the sources.
16635 For example:
16636
16637 @smallexample @c ada
16638 pragma Linker_Options ("-lmy_lib");
16639 @end smallexample
16640 @end itemize
16641
16642
16643 @node Stand-alone Ada Libraries
16644 @section Stand-alone Ada Libraries
16645 @cindex Stand-alone library, building, using
16646
16647 @menu
16648 * Introduction to Stand-alone Libraries::
16649 * Building a Stand-alone Library::
16650 * Creating a Stand-alone Library to be used in a non-Ada context::
16651 * Restrictions in Stand-alone Libraries::
16652 @end menu
16653
16654 @node Introduction to Stand-alone Libraries
16655 @subsection Introduction to Stand-alone Libraries
16656
16657 @noindent
16658 A Stand-alone Library (SAL) is a library that contains the necessary code to
16659 elaborate the Ada units that are included in the library. In contrast with
16660 an ordinary library, which consists of all sources, objects and @file{ALI}
16661 files of the
16662 library, a SAL may specify a restricted subset of compilation units
16663 to serve as a library interface. In this case, the fully
16664 self-sufficient set of files will normally consist of an objects
16665 archive, the sources of interface units' specs, and the @file{ALI}
16666 files of interface units.
16667 If an interface spec contains a generic unit or an inlined subprogram,
16668 the body's
16669 source must also be provided; if the units that must be provided in the source
16670 form depend on other units, the source and @file{ALI} files of those must
16671 also be provided.
16672
16673 The main purpose of a SAL is to minimize the recompilation overhead of client
16674 applications when a new version of the library is installed. Specifically,
16675 if the interface sources have not changed, client applications do not need to
16676 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16677 version, controlled by @code{Library_Version} attribute, is not changed,
16678 then the clients do not need to be relinked.
16679
16680 SALs also allow the library providers to minimize the amount of library source
16681 text exposed to the clients.  Such ``information hiding'' might be useful or
16682 necessary for various reasons.
16683
16684 Stand-alone libraries are also well suited to be used in an executable whose
16685 main routine is not written in Ada.
16686
16687 @node Building a Stand-alone Library
16688 @subsection Building a Stand-alone Library
16689
16690 @noindent
16691 GNAT's Project facility provides a simple way of building and installing
16692 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16693 To be a Stand-alone Library Project, in addition to the two attributes
16694 that make a project a Library Project (@code{Library_Name} and
16695 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16696 @code{Library_Interface} must be defined.  For example:
16697
16698 @smallexample @c projectfile
16699 @group
16700    for Library_Dir use "lib_dir";
16701    for Library_Name use "dummy";
16702    for Library_Interface use ("int1", "int1.child");
16703 @end group
16704 @end smallexample
16705
16706 @noindent
16707 Attribute @code{Library_Interface} has a non empty string list value,
16708 each string in the list designating a unit contained in an immediate source
16709 of the project file.
16710
16711 When a Stand-alone Library is built, first the binder is invoked to build
16712 a package whose name depends on the library name
16713 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16714 This binder-generated package includes initialization and
16715 finalization procedures whose
16716 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16717 in the example
16718 above). The object corresponding to this package is included in the library.
16719
16720 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16721 calling of these procedures if a static SAL is built, or if a shared SAL
16722 is built
16723 with the project-level attribute @code{Library_Auto_Init} set to
16724 @code{"false"}.
16725
16726 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16727 (those that are listed in attribute @code{Library_Interface}) are copied to
16728 the Library Directory. As a consequence, only the Interface Units may be
16729 imported from Ada units outside of the library. If other units are imported,
16730 the binding phase will fail.
16731
16732 The attribute @code{Library_Src_Dir} may be specified for a
16733 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16734 single string value. Its value must be the path (absolute or relative to the
16735 project directory) of an existing directory. This directory cannot be the
16736 object directory or one of the source directories, but it can be the same as
16737 the library directory. The sources of the Interface
16738 Units of the library that are needed by an Ada client of the library will be
16739 copied to the designated directory, called the Interface Copy directory.
16740 These sources includes the specs of the Interface Units, but they may also
16741 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16742 are used, or when there is a generic unit in the spec. Before the sources
16743 are copied to the Interface Copy directory, an attempt is made to delete all
16744 files in the Interface Copy directory.
16745
16746 Building stand-alone libraries by hand is somewhat tedious, but for those
16747 occasions when it is necessary here are the steps that you need to perform:
16748 @itemize @bullet
16749 @item
16750 Compile all library sources.
16751
16752 @item
16753 Invoke the binder with the switch @option{-n} (No Ada main program),
16754 with all the @file{ALI} files of the interfaces, and
16755 with the switch @option{-L} to give specific names to the @code{init}
16756 and @code{final} procedures.  For example:
16757 @smallexample
16758   gnatbind -n int1.ali int2.ali -Lsal1
16759 @end smallexample
16760
16761 @item
16762 Compile the binder generated file:
16763 @smallexample
16764   gcc -c b~int2.adb
16765 @end smallexample
16766
16767 @item
16768 Link the dynamic library with all the necessary object files,
16769 indicating to the linker the names of the @code{init} (and possibly
16770 @code{final}) procedures for automatic initialization (and finalization).
16771 The built library should be placed in a directory different from
16772 the object directory.
16773
16774 @item
16775 Copy the @code{ALI} files of the interface to the library directory,
16776 add in this copy an indication that it is an interface to a SAL
16777 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
16778 with letter ``P'') and make the modified copy of the @file{ALI} file
16779 read-only.
16780 @end itemize
16781
16782 @noindent
16783 Using SALs is not different from using other libraries
16784 (see @ref{Using the library}).
16785
16786 @node Creating a Stand-alone Library to be used in a non-Ada context
16787 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16788
16789 @noindent
16790 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16791 a non-Ada context.
16792
16793 The only extra step required is to ensure that library interface subprograms
16794 are compatible with the main program, by means of @code{pragma Export}
16795 or @code{pragma Convention}.
16796
16797 Here is an example of simple library interface for use with C main program:
16798
16799 @smallexample @c ada
16800 package Interface is
16801
16802    procedure Do_Something;
16803    pragma Export (C, Do_Something, "do_something");
16804
16805    procedure Do_Something_Else;
16806    pragma Export (C, Do_Something_Else, "do_something_else");
16807
16808 end Interface;
16809 @end smallexample
16810
16811 @noindent
16812 On the foreign language side, you must provide a ``foreign'' view of the
16813 library interface; remember that it should contain elaboration routines in
16814 addition to interface subprograms.
16815
16816 The example below shows the content of @code{mylib_interface.h} (note
16817 that there is no rule for the naming of this file, any name can be used)
16818 @smallexample
16819 /* the library elaboration procedure */
16820 extern void mylibinit (void);
16821
16822 /* the library finalization procedure */
16823 extern void mylibfinal (void);
16824
16825 /* the interface exported by the library */
16826 extern void do_something (void);
16827 extern void do_something_else (void);
16828 @end smallexample
16829
16830 @noindent
16831 Libraries built as explained above can be used from any program, provided
16832 that the elaboration procedures (named @code{mylibinit} in the previous
16833 example) are called before the library services are used. Any number of
16834 libraries can be used simultaneously, as long as the elaboration
16835 procedure of each library is called.
16836
16837 Below is an example of C program that uses the @code{mylib} library.
16838
16839 @smallexample
16840 #include "mylib_interface.h"
16841
16842 int
16843 main (void)
16844 @{
16845    /* First, elaborate the library before using it */
16846    mylibinit ();
16847
16848    /* Main program, using the library exported entities */
16849    do_something ();
16850    do_something_else ();
16851
16852    /* Library finalization at the end of the program */
16853    mylibfinal ();
16854    return 0;
16855 @}
16856 @end smallexample
16857
16858 @noindent
16859 Note that invoking any library finalization procedure generated by
16860 @code{gnatbind} shuts down the Ada run-time environment.
16861 Consequently, the
16862 finalization of all Ada libraries must be performed at the end of the program.
16863 No call to these libraries nor to the Ada run-time library should be made
16864 after the finalization phase.
16865
16866 @node Restrictions in Stand-alone Libraries
16867 @subsection Restrictions in Stand-alone Libraries
16868
16869 @noindent
16870 The pragmas listed below should be used with caution inside libraries,
16871 as they can create incompatibilities with other Ada libraries:
16872 @itemize @bullet
16873 @item pragma @code{Locking_Policy}
16874 @item pragma @code{Queuing_Policy}
16875 @item pragma @code{Task_Dispatching_Policy}
16876 @item pragma @code{Unreserve_All_Interrupts}
16877 @end itemize
16878
16879 @noindent
16880 When using a library that contains such pragmas, the user must make sure
16881 that all libraries use the same pragmas with the same values. Otherwise,
16882 @code{Program_Error} will
16883 be raised during the elaboration of the conflicting
16884 libraries. The usage of these pragmas and its consequences for the user
16885 should therefore be well documented.
16886
16887 Similarly, the traceback in the exception occurrence mechanism should be
16888 enabled or disabled in a consistent manner across all libraries.
16889 Otherwise, Program_Error will be raised during the elaboration of the
16890 conflicting libraries.
16891
16892 If the @code{Version} or @code{Body_Version}
16893 attributes are used inside a library, then you need to
16894 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16895 libraries, so that version identifiers can be properly computed.
16896 In practice these attributes are rarely used, so this is unlikely
16897 to be a consideration.
16898
16899 @node  Rebuilding the GNAT Run-Time Library
16900 @section Rebuilding the GNAT Run-Time Library
16901 @cindex GNAT Run-Time Library, rebuilding
16902
16903 @noindent
16904 It may be useful to recompile the GNAT library in various contexts, the
16905 most important one being the use of partition-wide configuration pragmas
16906 such as @code{Normalize_Scalars}. A special Makefile called
16907 @code{Makefile.adalib} is provided to that effect and can be found in
16908 the directory containing the GNAT library. The location of this
16909 directory depends on the way the GNAT environment has been installed and can
16910 be determined by means of the command:
16911
16912 @smallexample
16913 $ gnatls -v
16914 @end smallexample
16915
16916 @noindent
16917 The last entry in the object search path usually contains the
16918 gnat library. This Makefile contains its own documentation and in
16919 particular the set of instructions needed to rebuild a new library and
16920 to use it.
16921
16922
16923 @node Using the GNU make Utility
16924 @chapter Using the GNU @code{make} Utility
16925 @findex make
16926
16927 @noindent
16928 This chapter offers some examples of makefiles that solve specific
16929 problems. It does not explain how to write a makefile (see the GNU make
16930 documentation), nor does it try to replace the @code{gnatmake} utility
16931 (@pxref{The GNAT Make Program gnatmake}).
16932
16933 All the examples in this section are specific to the GNU version of
16934 make. Although @code{make} is a standard utility, and the basic language
16935 is the same, these examples use some advanced features found only in
16936 @code{GNU make}.
16937
16938 @menu
16939 * Using gnatmake in a Makefile::
16940 * Automatically Creating a List of Directories::
16941 * Generating the Command Line Switches::
16942 * Overcoming Command Line Length Limits::
16943 @end menu
16944
16945 @node Using gnatmake in a Makefile
16946 @section Using gnatmake in a Makefile
16947 @findex makefile
16948 @cindex GNU make
16949
16950 @noindent
16951 Complex project organizations can be handled in a very powerful way by
16952 using GNU make combined with gnatmake. For instance, here is a Makefile
16953 which allows you to build each subsystem of a big project into a separate
16954 shared library. Such a makefile allows you to significantly reduce the link
16955 time of very big applications while maintaining full coherence at
16956 each step of the build process.
16957
16958 The list of dependencies are handled automatically by
16959 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16960 the appropriate directories.
16961
16962 Note that you should also read the example on how to automatically
16963 create the list of directories
16964 (@pxref{Automatically Creating a List of Directories})
16965 which might help you in case your project has a lot of subdirectories.
16966
16967 @smallexample
16968 @iftex
16969 @leftskip=0cm
16970 @font@heightrm=cmr8
16971 @heightrm
16972 @end iftex
16973 ## This Makefile is intended to be used with the following directory
16974 ## configuration:
16975 ##  - The sources are split into a series of csc (computer software components)
16976 ##    Each of these csc is put in its own directory.
16977 ##    Their name are referenced by the directory names.
16978 ##    They will be compiled into shared library (although this would also work
16979 ##    with static libraries
16980 ##  - The main program (and possibly other packages that do not belong to any
16981 ##    csc is put in the top level directory (where the Makefile is).
16982 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16983 ##                    \_ second_csc (sources) __ lib (will contain the library)
16984 ##                    \_ ...
16985 ## Although this Makefile is build for shared library, it is easy to modify
16986 ## to build partial link objects instead (modify the lines with -shared and
16987 ## gnatlink below)
16988 ##
16989 ## With this makefile, you can change any file in the system or add any new
16990 ## file, and everything will be recompiled correctly (only the relevant shared
16991 ## objects will be recompiled, and the main program will be re-linked).
16992
16993 # The list of computer software component for your project. This might be
16994 # generated automatically.
16995 CSC_LIST=aa bb cc
16996
16997 # Name of the main program (no extension)
16998 MAIN=main
16999
17000 # If we need to build objects with -fPIC, uncomment the following line
17001 #NEED_FPIC=-fPIC
17002
17003 # The following variable should give the directory containing libgnat.so
17004 # You can get this directory through 'gnatls -v'. This is usually the last
17005 # directory in the Object_Path.
17006 GLIB=...
17007
17008 # The directories for the libraries
17009 # (This macro expands the list of CSC to the list of shared libraries, you
17010 # could simply use the expanded form :
17011 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17012 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17013
17014 $@{MAIN@}: objects $@{LIB_DIR@}
17015     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17016     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17017
17018 objects::
17019     # recompile the sources
17020     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17021
17022 # Note: In a future version of GNAT, the following commands will be simplified
17023 # by a new tool, gnatmlib
17024 $@{LIB_DIR@}:
17025     mkdir -p $@{dir $@@ @}
17026     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17027     cd $@{dir $@@ @}; cp -f ../*.ali .
17028
17029 # The dependencies for the modules
17030 # Note that we have to force the expansion of *.o, since in some cases
17031 # make won't be able to do it itself.
17032 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17033 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17034 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17035
17036 # Make sure all of the shared libraries are in the path before starting the
17037 # program
17038 run::
17039     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17040
17041 clean::
17042     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17043     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17044     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17045     $@{RM@} *.o *.ali $@{MAIN@}
17046 @end smallexample
17047
17048 @node Automatically Creating a List of Directories
17049 @section Automatically Creating a List of Directories
17050
17051 @noindent
17052 In most makefiles, you will have to specify a list of directories, and
17053 store it in a variable. For small projects, it is often easier to
17054 specify each of them by hand, since you then have full control over what
17055 is the proper order for these directories, which ones should be
17056 included...
17057
17058 However, in larger projects, which might involve hundreds of
17059 subdirectories, it might be more convenient to generate this list
17060 automatically.
17061
17062 The example below presents two methods. The first one, although less
17063 general, gives you more control over the list. It involves wildcard
17064 characters, that are automatically expanded by @code{make}. Its
17065 shortcoming is that you need to explicitly specify some of the
17066 organization of your project, such as for instance the directory tree
17067 depth, whether some directories are found in a separate tree,...
17068
17069 The second method is the most general one. It requires an external
17070 program, called @code{find}, which is standard on all Unix systems. All
17071 the directories found under a given root directory will be added to the
17072 list.
17073
17074 @smallexample
17075 @iftex
17076 @leftskip=0cm
17077 @font@heightrm=cmr8
17078 @heightrm
17079 @end iftex
17080 # The examples below are based on the following directory hierarchy:
17081 # All the directories can contain any number of files
17082 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17083 #                       ->  ab
17084 #                       ->  ac
17085 #                ->  b  ->  ba  ->  baa
17086 #                       ->  bb
17087 #                       ->  bc
17088 # This Makefile creates a variable called DIRS, that can be reused any time
17089 # you need this list (see the other examples in this section)
17090
17091 # The root of your project's directory hierarchy
17092 ROOT_DIRECTORY=.
17093
17094 ####
17095 # First method: specify explicitly the list of directories
17096 # This allows you to specify any subset of all the directories you need.
17097 ####
17098
17099 DIRS := a/aa/ a/ab/ b/ba/
17100
17101 ####
17102 # Second method: use wildcards
17103 # Note that the argument(s) to wildcard below should end with a '/'.
17104 # Since wildcards also return file names, we have to filter them out
17105 # to avoid duplicate directory names.
17106 # We thus use make's @code{dir} and @code{sort} functions.
17107 # It sets DIRs to the following value (note that the directories aaa and baa
17108 # are not given, unless you change the arguments to wildcard).
17109 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17110 ####
17111
17112 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17113                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17114
17115 ####
17116 # Third method: use an external program
17117 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17118 # This is the most complete command: it sets DIRs to the following value:
17119 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17120 ####
17121
17122 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17123
17124 @end smallexample
17125
17126 @node Generating the Command Line Switches
17127 @section Generating the Command Line Switches
17128
17129 @noindent
17130 Once you have created the list of directories as explained in the
17131 previous section (@pxref{Automatically Creating a List of Directories}),
17132 you can easily generate the command line arguments to pass to gnatmake.
17133
17134 For the sake of completeness, this example assumes that the source path
17135 is not the same as the object path, and that you have two separate lists
17136 of directories.
17137
17138 @smallexample
17139 # see "Automatically creating a list of directories" to create
17140 # these variables
17141 SOURCE_DIRS=
17142 OBJECT_DIRS=
17143
17144 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17145 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17146
17147 all:
17148         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17149 @end smallexample
17150
17151 @node Overcoming Command Line Length Limits
17152 @section Overcoming Command Line Length Limits
17153
17154 @noindent
17155 One problem that might be encountered on big projects is that many
17156 operating systems limit the length of the command line. It is thus hard to give
17157 gnatmake the list of source and object directories.
17158
17159 This example shows how you can set up environment variables, which will
17160 make @code{gnatmake} behave exactly as if the directories had been
17161 specified on the command line, but have a much higher length limit (or
17162 even none on most systems).
17163
17164 It assumes that you have created a list of directories in your Makefile,
17165 using one of the methods presented in
17166 @ref{Automatically Creating a List of Directories}.
17167 For the sake of completeness, we assume that the object
17168 path (where the ALI files are found) is different from the sources patch.
17169
17170 Note a small trick in the Makefile below: for efficiency reasons, we
17171 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17172 expanded immediately by @code{make}. This way we overcome the standard
17173 make behavior which is to expand the variables only when they are
17174 actually used.
17175
17176 On Windows, if you are using the standard Windows command shell, you must
17177 replace colons with semicolons in the assignments to these variables.
17178
17179 @smallexample
17180 @iftex
17181 @leftskip=0cm
17182 @font@heightrm=cmr8
17183 @heightrm
17184 @end iftex
17185 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17186 # This is the same thing as putting the -I arguments on the command line.
17187 # (the equivalent of using -aI on the command line would be to define
17188 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17189 # You can of course have different values for these variables.
17190 #
17191 # Note also that we need to keep the previous values of these variables, since
17192 # they might have been set before running 'make' to specify where the GNAT
17193 # library is installed.
17194
17195 # see "Automatically creating a list of directories" to create these
17196 # variables
17197 SOURCE_DIRS=
17198 OBJECT_DIRS=
17199
17200 empty:=
17201 space:=$@{empty@} $@{empty@}
17202 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17203 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17204 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17205 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17206 export ADA_INCLUDE_PATH
17207 export ADA_OBJECT_PATH
17208
17209 all:
17210         gnatmake main_unit
17211 @end smallexample
17212 @end ifclear
17213
17214
17215 @node Finding Memory Problems
17216 @chapter Finding Memory Problems
17217
17218 @noindent
17219 This chapter describes
17220 @ifclear vms
17221 the @command{gnatmem} tool, which can be used to track down
17222 ``memory leaks'', and
17223 @end ifclear
17224 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
17225 access values (including ``dangling references'').
17226
17227 @menu
17228 @ifclear vms
17229 * The gnatmem Tool::
17230 @end ifclear
17231 * The GNAT Debug Pool Facility::
17232 @end menu
17233
17234
17235 @ifclear vms
17236 @node The gnatmem Tool
17237 @section The @command{gnatmem} Tool
17238 @findex gnatmem
17239
17240 @noindent
17241 The @code{gnatmem} utility monitors dynamic allocation and
17242 deallocation activity in a program, and displays information about
17243 incorrect deallocations and possible sources of memory leaks.
17244 It provides three type of information:
17245 @itemize @bullet
17246 @item
17247 General information concerning memory management, such as the total
17248 number of allocations and deallocations, the amount of allocated
17249 memory and the high water mark, i.e. the largest amount of allocated
17250 memory in the course of program execution.
17251
17252 @item
17253 Backtraces for all incorrect deallocations, that is to say deallocations
17254 which do not correspond to a valid allocation.
17255
17256 @item
17257 Information on each allocation that is potentially the origin of a memory
17258 leak.
17259 @end itemize
17260
17261 @menu
17262 * Running gnatmem::
17263 * Switches for gnatmem::
17264 * Example of gnatmem Usage::
17265 @end menu
17266
17267 @node Running gnatmem
17268 @subsection Running @code{gnatmem}
17269
17270 @noindent
17271 @code{gnatmem} makes use of the output created by the special version of
17272 allocation and deallocation routines that record call information. This
17273 allows to obtain accurate dynamic memory usage history at a minimal cost to
17274 the execution speed. Note however, that @code{gnatmem} is not supported on
17275 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
17276 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
17277
17278 @noindent
17279 The @code{gnatmem} command has the form
17280
17281 @smallexample
17282    $ gnatmem [switches] user_program
17283 @end smallexample
17284
17285 @noindent
17286 The program must have been linked with the instrumented version of the
17287 allocation and deallocation routines. This is done by linking with the
17288 @file{libgmem.a} library. For correct symbolic backtrace information,
17289 the user program should be compiled with debugging options
17290 @ref{Switches for gcc}. For example to build @file{my_program}:
17291
17292 @smallexample
17293 $ gnatmake -g my_program -largs -lgmem
17294 @end smallexample
17295
17296 @noindent
17297 When running @file{my_program} the file @file{gmem.out} is produced. This file
17298 contains information about all allocations and deallocations done by the
17299 program. It is produced by the instrumented allocations and
17300 deallocations routines and will be used by @code{gnatmem}.
17301
17302 @noindent
17303 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17304 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17305 @code{-i} switch, gnatmem will assume that this file can be found in the
17306 current directory. For example, after you have executed @file{my_program},
17307 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17308
17309 @smallexample
17310 $ gnatmem my_program
17311 @end smallexample
17312
17313 @noindent
17314 This will produce the output with the following format:
17315
17316 *************** debut cc
17317 @smallexample
17318 $ gnatmem my_program
17319
17320 Global information
17321 ------------------
17322    Total number of allocations        :  45
17323    Total number of deallocations      :   6
17324    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17325    High Water Mark                    :  11.40 Kilobytes
17326
17327 .
17328 .
17329 .
17330 Allocation Root # 2
17331 -------------------
17332  Number of non freed allocations    :  11
17333  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17334  High Water Mark                    :   1.27 Kilobytes
17335  Backtrace                          :
17336    my_program.adb:23 my_program.alloc
17337 .
17338 .
17339 .
17340 @end smallexample
17341
17342 The first block of output gives general information. In this case, the
17343 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17344 Unchecked_Deallocation routine occurred.
17345
17346 @noindent
17347 Subsequent paragraphs display  information on all allocation roots.
17348 An allocation root is a specific point in the execution of the program
17349 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17350 construct. This root is represented by an execution backtrace (or subprogram
17351 call stack). By default the backtrace depth for allocations roots is 1, so
17352 that a root corresponds exactly to a source location. The backtrace can
17353 be made deeper, to make the root more specific.
17354
17355 @node Switches for gnatmem
17356 @subsection Switches for @code{gnatmem}
17357
17358 @noindent
17359 @code{gnatmem} recognizes the following switches:
17360
17361 @table @option
17362
17363 @item -q
17364 @cindex @option{-q} (@code{gnatmem})
17365 Quiet. Gives the minimum output needed to identify the origin of the
17366 memory leaks. Omits statistical information.
17367
17368 @item @var{N}
17369 @cindex @var{N} (@code{gnatmem})
17370 N is an integer literal (usually between 1 and 10) which controls the
17371 depth of the backtraces defining allocation root. The default value for
17372 N is 1. The deeper the backtrace, the more precise the localization of
17373 the root. Note that the total number of roots can depend on this
17374 parameter. This parameter must be specified @emph{before} the name of the
17375 executable to be analyzed, to avoid ambiguity.
17376
17377 @item -b n
17378 @cindex @option{-b} (@code{gnatmem})
17379 This switch has the same effect as just depth parameter.
17380
17381 @item -i @var{file}
17382 @cindex @option{-i} (@code{gnatmem})
17383 Do the @code{gnatmem} processing starting from @file{file}, rather than
17384 @file{gmem.out} in the current directory.
17385
17386 @item -m n
17387 @cindex @option{-m} (@code{gnatmem})
17388 This switch causes @code{gnatmem} to mask the allocation roots that have less
17389 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17390 examine even the roots that didn't result in leaks.
17391
17392 @item -s order
17393 @cindex @option{-s} (@code{gnatmem})
17394 This switch causes @code{gnatmem} to sort the allocation roots according to the
17395 specified order of sort criteria, each identified by a single letter. The
17396 currently supported criteria are @code{n, h, w} standing respectively for
17397 number of unfreed allocations, high watermark, and final watermark
17398 corresponding to a specific root. The default order is @code{nwh}.
17399
17400 @end table
17401
17402 @node Example of gnatmem Usage
17403 @subsection Example of @code{gnatmem} Usage
17404
17405 @noindent
17406 The following example shows the use of @code{gnatmem}
17407 on a simple memory-leaking program.
17408 Suppose that we have the following Ada program:
17409
17410 @smallexample @c ada
17411 @group
17412 @cartouche
17413 with Unchecked_Deallocation;
17414 procedure Test_Gm is
17415
17416    type T is array (1..1000) of Integer;
17417    type Ptr is access T;
17418    procedure Free is new Unchecked_Deallocation (T, Ptr);
17419    A : Ptr;
17420
17421    procedure My_Alloc is
17422    begin
17423       A := new T;
17424    end My_Alloc;
17425
17426    procedure My_DeAlloc is
17427       B : Ptr := A;
17428    begin
17429       Free (B);
17430    end My_DeAlloc;
17431
17432 begin
17433    My_Alloc;
17434    for I in 1 .. 5 loop
17435       for J in I .. 5 loop
17436          My_Alloc;
17437       end loop;
17438       My_Dealloc;
17439    end loop;
17440 end;
17441 @end cartouche
17442 @end group
17443 @end smallexample
17444
17445 @noindent
17446 The program needs to be compiled with debugging option and linked with
17447 @code{gmem} library:
17448
17449 @smallexample
17450 $ gnatmake -g test_gm -largs -lgmem
17451 @end smallexample
17452
17453 @noindent
17454 Then we execute the program as usual:
17455
17456 @smallexample
17457 $ test_gm
17458 @end smallexample
17459
17460 @noindent
17461 Then @code{gnatmem} is invoked simply with
17462 @smallexample
17463 $ gnatmem test_gm
17464 @end smallexample
17465
17466 @noindent
17467 which produces the following output (result may vary on different platforms):
17468
17469 @smallexample
17470 Global information
17471 ------------------
17472    Total number of allocations        :  18
17473    Total number of deallocations      :   5
17474    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17475    High Water Mark                    :  56.90 Kilobytes
17476
17477 Allocation Root # 1
17478 -------------------
17479  Number of non freed allocations    :  11
17480  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17481  High Water Mark                    :  46.88 Kilobytes
17482  Backtrace                          :
17483    test_gm.adb:11 test_gm.my_alloc
17484
17485 Allocation Root # 2
17486 -------------------
17487  Number of non freed allocations    :   1
17488  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17489  High Water Mark                    :  10.02 Kilobytes
17490  Backtrace                          :
17491    s-secsta.adb:81 system.secondary_stack.ss_init
17492
17493 Allocation Root # 3
17494 -------------------
17495  Number of non freed allocations    :   1
17496  Final Water Mark (non freed mem)   :  12 Bytes
17497  High Water Mark                    :  12 Bytes
17498  Backtrace                          :
17499    s-secsta.adb:181 system.secondary_stack.ss_init
17500 @end smallexample
17501
17502 @noindent
17503 Note that the GNAT run time contains itself a certain number of
17504 allocations that have no  corresponding deallocation,
17505 as shown here for root #2 and root
17506 #3. This is a normal behavior when the number of non freed allocations
17507 is one, it allocates dynamic data structures that the run time needs for
17508 the complete lifetime of the program. Note also that there is only one
17509 allocation root in the user program with a single line back trace:
17510 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17511 program shows that 'My_Alloc' is called at 2 different points in the
17512 source (line 21 and line 24). If those two allocation roots need to be
17513 distinguished, the backtrace depth parameter can be used:
17514
17515 @smallexample
17516 $ gnatmem 3 test_gm
17517 @end smallexample
17518
17519 @noindent
17520 which will give the following output:
17521
17522 @smallexample
17523 Global information
17524 ------------------
17525    Total number of allocations        :  18
17526    Total number of deallocations      :   5
17527    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17528    High Water Mark                    :  56.90 Kilobytes
17529
17530 Allocation Root # 1
17531 -------------------
17532  Number of non freed allocations    :  10
17533  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17534  High Water Mark                    :  42.97 Kilobytes
17535  Backtrace                          :
17536    test_gm.adb:11 test_gm.my_alloc
17537    test_gm.adb:24 test_gm
17538    b_test_gm.c:52 main
17539
17540 Allocation Root # 2
17541 -------------------
17542  Number of non freed allocations    :   1
17543  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17544  High Water Mark                    :  10.02 Kilobytes
17545  Backtrace                          :
17546    s-secsta.adb:81  system.secondary_stack.ss_init
17547    s-secsta.adb:283 <system__secondary_stack___elabb>
17548    b_test_gm.c:33   adainit
17549
17550 Allocation Root # 3
17551 -------------------
17552  Number of non freed allocations    :   1
17553  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17554  High Water Mark                    :   3.91 Kilobytes
17555  Backtrace                          :
17556    test_gm.adb:11 test_gm.my_alloc
17557    test_gm.adb:21 test_gm
17558    b_test_gm.c:52 main
17559
17560 Allocation Root # 4
17561 -------------------
17562  Number of non freed allocations    :   1
17563  Final Water Mark (non freed mem)   :  12 Bytes
17564  High Water Mark                    :  12 Bytes
17565  Backtrace                          :
17566    s-secsta.adb:181 system.secondary_stack.ss_init
17567    s-secsta.adb:283 <system__secondary_stack___elabb>
17568    b_test_gm.c:33   adainit
17569 @end smallexample
17570
17571 @noindent
17572 The allocation root #1 of the first example has been split in 2 roots #1
17573 and #3 thanks to the more precise associated backtrace.
17574
17575 @end ifclear
17576
17577
17578 @node The GNAT Debug Pool Facility
17579 @section The GNAT Debug Pool Facility
17580 @findex Debug Pool
17581 @cindex storage, pool, memory corruption
17582
17583 @noindent
17584 The use of unchecked deallocation and unchecked conversion can easily
17585 lead to incorrect memory references. The problems generated by such
17586 references are usually difficult to tackle because the symptoms can be
17587 very remote from the origin of the problem. In such cases, it is
17588 very helpful to detect the problem as early as possible. This is the
17589 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17590
17591 In order to use the GNAT specific debugging pool, the user must
17592 associate a debug pool object with each of the access types that may be
17593 related to suspected memory problems. See Ada Reference Manual 13.11.
17594 @smallexample @c ada
17595 type Ptr is access Some_Type;
17596 Pool : GNAT.Debug_Pools.Debug_Pool;
17597 for Ptr'Storage_Pool use Pool;
17598 @end smallexample
17599
17600 @noindent
17601 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17602 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17603 allow the user to redefine allocation and deallocation strategies. They
17604 also provide a checkpoint for each dereference, through the use of
17605 the primitive operation @code{Dereference} which is implicitly called at
17606 each dereference of an access value.
17607
17608 Once an access type has been associated with a debug pool, operations on
17609 values of the type may raise four distinct exceptions,
17610 which correspond to four potential kinds of memory corruption:
17611 @itemize @bullet
17612 @item
17613 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17614 @item
17615 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17616 @item
17617 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17618 @item
17619 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17620 @end itemize
17621
17622 @noindent
17623 For types associated with a Debug_Pool, dynamic allocation is performed using
17624 the standard
17625 GNAT allocation routine. References to all allocated chunks of memory
17626 are kept in an internal dictionary.
17627 Several deallocation strategies are provided, whereupon the user can choose
17628 to release the memory to the system, keep it allocated for further invalid
17629 access checks, or fill it with an easily recognizable pattern for debug
17630 sessions.
17631 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17632
17633 See the documentation in the file g-debpoo.ads for more information on the
17634 various strategies.
17635
17636 Upon each dereference, a check is made that the access value denotes a
17637 properly allocated memory location. Here is a complete example of use of
17638 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17639 @smallexample @c ada
17640 @iftex
17641 @leftskip=0cm
17642 @end iftex
17643 with Gnat.Io; use Gnat.Io;
17644 with Unchecked_Deallocation;
17645 with Unchecked_Conversion;
17646 with GNAT.Debug_Pools;
17647 with System.Storage_Elements;
17648 with Ada.Exceptions; use Ada.Exceptions;
17649 procedure Debug_Pool_Test is
17650
17651    type T is access Integer;
17652    type U is access all T;
17653
17654    P : GNAT.Debug_Pools.Debug_Pool;
17655    for T'Storage_Pool use P;
17656
17657    procedure Free is new Unchecked_Deallocation (Integer, T);
17658    function UC is new Unchecked_Conversion (U, T);
17659    A, B : aliased T;
17660
17661    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17662
17663 begin
17664    Info (P);
17665    A := new Integer;
17666    B := new Integer;
17667    B := A;
17668    Info (P);
17669    Free (A);
17670    begin
17671       Put_Line (Integer'Image(B.all));
17672    exception
17673       when E : others => Put_Line ("raised: " & Exception_Name (E));
17674    end;
17675    begin
17676       Free (B);
17677    exception
17678       when E : others => Put_Line ("raised: " & Exception_Name (E));
17679    end;
17680    B := UC(A'Access);
17681    begin
17682       Put_Line (Integer'Image(B.all));
17683    exception
17684       when E : others => Put_Line ("raised: " & Exception_Name (E));
17685    end;
17686    begin
17687       Free (B);
17688    exception
17689       when E : others => Put_Line ("raised: " & Exception_Name (E));
17690    end;
17691    Info (P);
17692 end Debug_Pool_Test;
17693 @end smallexample
17694
17695 @noindent
17696 The debug pool mechanism provides the following precise diagnostics on the
17697 execution of this erroneous program:
17698 @smallexample
17699 Debug Pool info:
17700   Total allocated bytes :  0
17701   Total deallocated bytes :  0
17702   Current Water Mark:  0
17703   High Water Mark:  0
17704
17705 Debug Pool info:
17706   Total allocated bytes :  8
17707   Total deallocated bytes :  0
17708   Current Water Mark:  8
17709   High Water Mark:  8
17710
17711 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17712 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17713 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17714 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17715 Debug Pool info:
17716   Total allocated bytes :  8
17717   Total deallocated bytes :  4
17718   Current Water Mark:  4
17719   High Water Mark:  8
17720 @end smallexample
17721
17722
17723 @node Creating Sample Bodies Using gnatstub
17724 @chapter Creating Sample Bodies Using @command{gnatstub}
17725 @findex gnatstub
17726
17727 @noindent
17728 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17729 for library unit declarations.
17730
17731 To create a body stub, @command{gnatstub} has to compile the library
17732 unit declaration. Therefore, bodies can be created only for legal
17733 library units. Moreover, if a library unit depends semantically upon
17734 units located outside the current directory, you have to provide
17735 the source search path when calling @command{gnatstub}, see the description
17736 of @command{gnatstub} switches below.
17737
17738 @menu
17739 * Running gnatstub::
17740 * Switches for gnatstub::
17741 @end menu
17742
17743 @node Running gnatstub
17744 @section Running @command{gnatstub}
17745
17746 @noindent
17747 @command{gnatstub} has the command-line interface of the form
17748
17749 @smallexample
17750 $ gnatstub [switches] filename [directory]
17751 @end smallexample
17752
17753 @noindent
17754 where
17755 @table @emph
17756 @item filename
17757 is the name of the source file that contains a library unit declaration
17758 for which a body must be created. The file name may contain the path
17759 information.
17760 The file name does not have to follow the GNAT file name conventions. If the
17761 name
17762 does not follow GNAT file naming conventions, the name of the body file must
17763 be provided
17764 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17765 If the file name follows the GNAT file naming
17766 conventions and the name of the body file is not provided,
17767 @command{gnatstub}
17768 creates the name
17769 of the body file from the argument file name by replacing the @file{.ads}
17770 suffix
17771 with the @file{.adb} suffix.
17772
17773 @item directory
17774 indicates the directory in which the body stub is to be placed (the default
17775 is the
17776 current directory)
17777
17778 @item switches
17779 is an optional sequence of switches as described in the next section
17780 @end table
17781
17782 @node Switches for gnatstub
17783 @section Switches for @command{gnatstub}
17784
17785 @table @option
17786 @c !sort!
17787
17788 @item ^-f^/FULL^
17789 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17790 If the destination directory already contains a file with the name of the
17791 body file
17792 for the argument spec file, replace it with the generated body stub.
17793
17794 @item ^-hs^/HEADER=SPEC^
17795 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17796 Put the comment header (i.e., all the comments preceding the
17797 compilation unit) from the source of the library unit declaration
17798 into the body stub.
17799
17800 @item ^-hg^/HEADER=GENERAL^
17801 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17802 Put a sample comment header into the body stub.
17803
17804 @ifclear vms
17805 @item -IDIR
17806 @cindex @option{-IDIR} (@command{gnatstub})
17807 @itemx -I-
17808 @cindex @option{-I-} (@command{gnatstub})
17809 @end ifclear
17810 @ifset vms
17811 @item /NOCURRENT_DIRECTORY
17812 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17813 @end ifset
17814 ^These switches have ^This switch has^ the same meaning as in calls to
17815 @command{gcc}.
17816 ^They define ^It defines ^ the source search path in the call to
17817 @command{gcc} issued
17818 by @command{gnatstub} to compile an argument source file.
17819
17820 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17821 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17822 This switch has the same meaning as in calls to @command{gcc}.
17823 It defines the additional configuration file to be passed to the call to
17824 @command{gcc} issued
17825 by @command{gnatstub} to compile an argument source file.
17826
17827 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17828 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17829 (@var{n} is a non-negative integer). Set the maximum line length in the
17830 body stub to @var{n}; the default is 79. The maximum value that can be
17831 specified is 32767. Note that in the special case of configuration
17832 pragma files, the maximum is always 32767 regardless of whether or
17833 not this switch appears.
17834
17835 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17836 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17837 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17838 the generated body sample to @var{n}.
17839 The default indentation is 3.
17840
17841 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17842 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17843 Order local bodies alphabetically. (By default local bodies are ordered
17844 in the same way as the corresponding local specs in the argument spec file.)
17845
17846 @item ^-i^/INDENTATION=^@var{n}
17847 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17848 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17849
17850 @item ^-k^/TREE_FILE=SAVE^
17851 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17852 Do not remove the tree file (i.e., the snapshot of the compiler internal
17853 structures used by @command{gnatstub}) after creating the body stub.
17854
17855 @item ^-l^/LINE_LENGTH=^@var{n}
17856 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17857 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17858
17859 @item ^-o^/BODY=^@var{body-name}
17860 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17861 Body file name.  This should be set if the argument file name does not
17862 follow
17863 the GNAT file naming
17864 conventions. If this switch is omitted the default name for the body will be
17865 obtained
17866 from the argument file name according to the GNAT file naming conventions.
17867
17868 @item ^-q^/QUIET^
17869 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17870 Quiet mode: do not generate a confirmation when a body is
17871 successfully created, and do not generate a message when a body is not
17872 required for an
17873 argument unit.
17874
17875 @item ^-r^/TREE_FILE=REUSE^
17876 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17877 Reuse the tree file (if it exists) instead of creating it.  Instead of
17878 creating the tree file for the library unit declaration, @command{gnatstub}
17879 tries to find it in the current directory and use it for creating
17880 a body. If the tree file is not found, no body is created. This option
17881 also implies @option{^-k^/SAVE^}, whether or not
17882 the latter is set explicitly.
17883
17884 @item ^-t^/TREE_FILE=OVERWRITE^
17885 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17886 Overwrite the existing tree file.  If the current directory already
17887 contains the file which, according to the GNAT file naming rules should
17888 be considered as a tree file for the argument source file,
17889 @command{gnatstub}
17890 will refuse to create the tree file needed to create a sample body
17891 unless this option is set.
17892
17893 @item ^-v^/VERBOSE^
17894 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17895 Verbose mode: generate version information.
17896
17897 @end table
17898
17899
17900 @node Other Utility Programs
17901 @chapter Other Utility Programs
17902
17903 @noindent
17904 This chapter discusses some other utility programs available in the Ada
17905 environment.
17906
17907 @menu
17908 * Using Other Utility Programs with GNAT::
17909 * The External Symbol Naming Scheme of GNAT::
17910 @ifclear vms
17911 * Ada Mode for Glide::
17912 @end ifclear
17913 * Converting Ada Files to html with gnathtml::
17914 * Installing gnathtml::
17915 @ifset vms
17916 * LSE::
17917 * Profiling::
17918 @end ifset
17919 @end menu
17920
17921 @node Using Other Utility Programs with GNAT
17922 @section Using Other Utility Programs with GNAT
17923
17924 @noindent
17925 The object files generated by GNAT are in standard system format and in
17926 particular the debugging information uses this format. This means
17927 programs generated by GNAT can be used with existing utilities that
17928 depend on these formats.
17929
17930 @ifclear vms
17931 In general, any utility program that works with C will also often work with
17932 Ada programs generated by GNAT. This includes software utilities such as
17933 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17934 as Purify.
17935 @end ifclear
17936
17937 @node The External Symbol Naming Scheme of GNAT
17938 @section The External Symbol Naming Scheme of GNAT
17939
17940 @noindent
17941 In order to interpret the output from GNAT, when using tools that are
17942 originally intended for use with other languages, it is useful to
17943 understand the conventions used to generate link names from the Ada
17944 entity names.
17945
17946 All link names are in all lowercase letters. With the exception of library
17947 procedure names, the mechanism used is simply to use the full expanded
17948 Ada name with dots replaced by double underscores. For example, suppose
17949 we have the following package spec:
17950
17951 @smallexample @c ada
17952 @group
17953 @cartouche
17954 package QRS is
17955    MN : Integer;
17956 end QRS;
17957 @end cartouche
17958 @end group
17959 @end smallexample
17960
17961 @noindent
17962 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17963 the corresponding link name is @code{qrs__mn}.
17964 @findex Export
17965 Of course if a @code{pragma Export} is used this may be overridden:
17966
17967 @smallexample @c ada
17968 @group
17969 @cartouche
17970 package Exports is
17971    Var1 : Integer;
17972    pragma Export (Var1, C, External_Name => "var1_name");
17973    Var2 : Integer;
17974    pragma Export (Var2, C, Link_Name => "var2_link_name");
17975 end Exports;
17976 @end cartouche
17977 @end group
17978 @end smallexample
17979
17980 @noindent
17981 In this case, the link name for @var{Var1} is whatever link name the
17982 C compiler would assign for the C function @var{var1_name}. This typically
17983 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17984 system conventions, but other possibilities exist. The link name for
17985 @var{Var2} is @var{var2_link_name}, and this is not operating system
17986 dependent.
17987
17988 @findex _main
17989 One exception occurs for library level procedures. A potential ambiguity
17990 arises between the required name @code{_main} for the C main program,
17991 and the name we would otherwise assign to an Ada library level procedure
17992 called @code{Main} (which might well not be the main program).
17993
17994 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17995 names. So if we have a library level procedure such as
17996
17997 @smallexample @c ada
17998 @group
17999 @cartouche
18000 procedure Hello (S : String);
18001 @end cartouche
18002 @end group
18003 @end smallexample
18004
18005 @noindent
18006 the external name of this procedure will be @var{_ada_hello}.
18007
18008 @ifclear vms
18009 @node Ada Mode for Glide
18010 @section Ada Mode for @code{Glide}
18011 @cindex Ada mode (for Glide)
18012
18013 @noindent
18014 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18015 user to understand and navigate existing code, and facilitates writing
18016 new code. It furthermore provides some utility functions for easier
18017 integration of standard Emacs features when programming in Ada.
18018
18019 Its general features include:
18020
18021 @itemize @bullet
18022 @item
18023 An Integrated Development Environment with functionality such as the
18024 following
18025
18026 @itemize @bullet
18027 @item
18028 ``Project files'' for configuration-specific aspects
18029 (e.g. directories and compilation options)
18030
18031 @item
18032 Compiling and stepping through error messages.
18033
18034 @item
18035 Running and debugging an applications within Glide.
18036 @end itemize
18037
18038 @item
18039 Pull-down menus
18040
18041 @item
18042 User configurability
18043 @end itemize
18044
18045 Some of the specific Ada mode features are:
18046
18047 @itemize @bullet
18048 @item
18049 Functions for easy and quick stepping through Ada code
18050
18051 @item
18052 Getting cross reference information for identifiers (e.g., finding a
18053 defining occurrence)
18054
18055 @item
18056 Displaying an index menu of types and subprograms, allowing
18057 direct selection for browsing
18058
18059 @item
18060 Automatic color highlighting of the various Ada entities
18061 @end itemize
18062
18063 Glide directly supports writing Ada code, via several facilities:
18064
18065 @itemize @bullet
18066 @item
18067 Switching between spec and body files with possible
18068 autogeneration of body files
18069
18070 @item
18071 Automatic formating of subprogram parameter lists
18072
18073 @item
18074 Automatic indentation according to Ada syntax
18075
18076 @item
18077 Automatic completion of identifiers
18078
18079 @item
18080 Automatic (and configurable) casing of identifiers, keywords, and attributes
18081
18082 @item
18083 Insertion of syntactic templates
18084
18085 @item
18086 Block commenting / uncommenting
18087 @end itemize
18088
18089 @noindent
18090 For more information, please refer to the online documentation
18091 available in the @code{Glide} @result{} @code{Help} menu.
18092 @end ifclear
18093
18094
18095 @node Converting Ada Files to html with gnathtml
18096 @section Converting Ada Files to HTML with @code{gnathtml}
18097
18098 @noindent
18099 This @code{Perl} script allows Ada source files to be browsed using
18100 standard Web browsers. For installation procedure, see the section
18101 @xref{Installing gnathtml}.
18102
18103 Ada reserved keywords are highlighted in a bold font and Ada comments in
18104 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18105 switch to suppress the generation of cross-referencing information, user
18106 defined variables and types will appear in a different color; you will
18107 be able to click on any identifier and go to its declaration.
18108
18109 The command line is as follow:
18110 @smallexample
18111 $ perl gnathtml.pl [switches] ada-files
18112 @end smallexample
18113
18114 @noindent
18115 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18116 an html file for every ada file, and a global file called @file{index.htm}.
18117 This file is an index of every identifier defined in the files.
18118
18119 The available switches are the following ones :
18120
18121 @table @option
18122 @item -83
18123 @cindex @option{-83} (@code{gnathtml})
18124 Only the subset on the Ada 83 keywords will be highlighted, not the full
18125 Ada 95 keywords set.
18126
18127 @item -cc @var{color}
18128 @cindex @option{-cc} (@code{gnathtml})
18129 This option allows you to change the color used for comments. The default
18130 value is green. The color argument can be any name accepted by html.
18131
18132 @item -d
18133 @cindex @option{-d} (@code{gnathtml})
18134 If the ada files depend on some other files (using for instance the
18135 @code{with} command, the latter will also be converted to html.
18136 Only the files in the user project will be converted to html, not the files
18137 in the run-time library itself.
18138
18139 @item -D
18140 @cindex @option{-D} (@code{gnathtml})
18141 This command is the same as @option{-d} above, but @command{gnathtml} will
18142 also look for files in the run-time library, and generate html files for them.
18143
18144 @item -ext @var{extension}
18145 @cindex @option{-ext} (@code{gnathtml})
18146 This option allows you to change the extension of the generated HTML files.
18147 If you do not specify an extension, it will default to @file{htm}.
18148
18149 @item -f
18150 @cindex @option{-f} (@code{gnathtml})
18151 By default, gnathtml will generate html links only for global entities
18152 ('with'ed units, global variables and types,...). If you specify the
18153 @option{-f} on the command line, then links will be generated for local
18154 entities too.
18155
18156 @item -l @var{number}
18157 @cindex @option{-l} (@code{gnathtml})
18158 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18159 will number the html files every @var{number} line.
18160
18161 @item -I @var{dir}
18162 @cindex @option{-I} (@code{gnathtml})
18163 Specify a directory to search for library files (@file{.ALI} files) and
18164 source files. You can provide several -I switches on the command line,
18165 and the directories will be parsed in the order of the command line.
18166
18167 @item -o @var{dir}
18168 @cindex @option{-o} (@code{gnathtml})
18169 Specify the output directory for html files. By default, gnathtml will
18170 saved the generated html files in a subdirectory named @file{html/}.
18171
18172 @item -p @var{file}
18173 @cindex @option{-p} (@code{gnathtml})
18174 If you are using Emacs and the most recent Emacs Ada mode, which provides
18175 a full Integrated Development Environment for compiling, checking,
18176 running and debugging applications, you may use @file{.gpr} files
18177 to give the directories where Emacs can find sources and object files.
18178
18179 Using this switch, you can tell gnathtml to use these files. This allows
18180 you to get an html version of your application, even if it is spread
18181 over multiple directories.
18182
18183 @item -sc @var{color}
18184 @cindex @option{-sc} (@code{gnathtml})
18185 This option allows you to change the color used for symbol definitions.
18186 The default value is red. The color argument can be any name accepted by html.
18187
18188 @item -t @var{file}
18189 @cindex @option{-t} (@code{gnathtml})
18190 This switch provides the name of a file. This file contains a list of
18191 file names to be converted, and the effect is exactly as though they had
18192 appeared explicitly on the command line. This
18193 is the recommended way to work around the command line length limit on some
18194 systems.
18195
18196 @end table
18197
18198 @node Installing gnathtml
18199 @section Installing @code{gnathtml}
18200
18201 @noindent
18202 @code{Perl} needs to be installed on your machine to run this script.
18203 @code{Perl} is freely available for almost every architecture and
18204 Operating System via the Internet.
18205
18206 On Unix systems, you  may want to modify  the  first line of  the script
18207 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18208 is. The syntax of this line is :
18209 @smallexample
18210 #!full_path_name_to_perl
18211 @end smallexample
18212
18213 @noindent
18214 Alternatively, you may run the script using the following command line:
18215
18216 @smallexample
18217 $ perl gnathtml.pl [switches] files
18218 @end smallexample
18219
18220 @ifset vms
18221 @node LSE
18222 @section LSE
18223 @findex LSE
18224
18225 @noindent
18226 The GNAT distribution provides an Ada 95 template for the Digital Language
18227 Sensitive Editor (LSE), a component of DECset. In order to
18228 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18229
18230 @node Profiling
18231 @section Profiling
18232 @findex PCA
18233
18234 @noindent
18235 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18236 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18237 the collection phase with the /DEBUG qualifier.
18238
18239 @smallexample
18240 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18241 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18242 $ RUN/DEBUG <PROGRAM_NAME>
18243 @end smallexample
18244 @noindent
18245 @end ifset
18246
18247 @node Running and Debugging Ada Programs
18248 @chapter Running and Debugging Ada Programs
18249 @cindex Debugging
18250
18251 @noindent
18252 This chapter discusses how to debug Ada programs. An incorrect Ada program
18253 may be handled in three ways by the GNAT compiler:
18254
18255 @enumerate
18256 @item
18257 The illegality may be a violation of the static semantics of Ada. In
18258 that case GNAT diagnoses the constructs in the program that are illegal.
18259 It is then a straightforward matter for the user to modify those parts of
18260 the program.
18261
18262 @item
18263 The illegality may be a violation of the dynamic semantics of Ada. In
18264 that case the program compiles and executes, but may generate incorrect
18265 results, or may terminate abnormally with some exception.
18266
18267 @item
18268 When presented with a program that contains convoluted errors, GNAT
18269 itself may terminate abnormally without providing full diagnostics on
18270 the incorrect user program.
18271 @end enumerate
18272
18273 @menu
18274 * The GNAT Debugger GDB::
18275 * Running GDB::
18276 * Introduction to GDB Commands::
18277 * Using Ada Expressions::
18278 * Calling User-Defined Subprograms::
18279 * Using the Next Command in a Function::
18280 * Ada Exceptions::
18281 * Ada Tasks::
18282 * Debugging Generic Units::
18283 * GNAT Abnormal Termination or Failure to Terminate::
18284 * Naming Conventions for GNAT Source Files::
18285 * Getting Internal Debugging Information::
18286 * Stack Traceback::
18287 @end menu
18288
18289 @cindex Debugger
18290 @findex gdb
18291
18292 @node The GNAT Debugger GDB
18293 @section The GNAT Debugger GDB
18294
18295 @noindent
18296 @code{GDB} is a general purpose, platform-independent debugger that
18297 can be used to debug mixed-language programs compiled with @code{GCC},
18298 and in particular is capable of debugging Ada programs compiled with
18299 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18300 complex Ada data structures.
18301
18302 The manual @cite{Debugging with GDB}
18303 @ifset vms
18304 , located in the GNU:[DOCS] directory,
18305 @end ifset
18306 contains full details on the usage of @code{GDB}, including a section on
18307 its usage on programs. This manual should be consulted for full
18308 details. The section that follows is a brief introduction to the
18309 philosophy and use of @code{GDB}.
18310
18311 When GNAT programs are compiled, the compiler optionally writes debugging
18312 information into the generated object file, including information on
18313 line numbers, and on declared types and variables. This information is
18314 separate from the generated code. It makes the object files considerably
18315 larger, but it does not add to the size of the actual executable that
18316 will be loaded into memory, and has no impact on run-time performance. The
18317 generation of debug information is triggered by the use of the
18318 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18319 the compilations. It is important to emphasize that the use of these
18320 options does not change the generated code.
18321
18322 The debugging information is written in standard system formats that
18323 are used by many tools, including debuggers and profilers. The format
18324 of the information is typically designed to describe C types and
18325 semantics, but GNAT implements a translation scheme which allows full
18326 details about Ada types and variables to be encoded into these
18327 standard C formats. Details of this encoding scheme may be found in
18328 the file exp_dbug.ads in the GNAT source distribution. However, the
18329 details of this encoding are, in general, of no interest to a user,
18330 since @code{GDB} automatically performs the necessary decoding.
18331
18332 When a program is bound and linked, the debugging information is
18333 collected from the object files, and stored in the executable image of
18334 the program. Again, this process significantly increases the size of
18335 the generated executable file, but it does not increase the size of
18336 the executable program itself. Furthermore, if this program is run in
18337 the normal manner, it runs exactly as if the debug information were
18338 not present, and takes no more actual memory.
18339
18340 However, if the program is run under control of @code{GDB}, the
18341 debugger is activated.  The image of the program is loaded, at which
18342 point it is ready to run.  If a run command is given, then the program
18343 will run exactly as it would have if @code{GDB} were not present. This
18344 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18345 entirely non-intrusive until a breakpoint is encountered.  If no
18346 breakpoint is ever hit, the program will run exactly as it would if no
18347 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18348 the debugging information and can respond to user commands to inspect
18349 variables, and more generally to report on the state of execution.
18350
18351 @c **************
18352 @node Running GDB
18353 @section Running GDB
18354
18355 @noindent
18356 The debugger can be launched directly and simply from @code{glide} or
18357 through its graphical interface: @code{gvd}. It can also be used
18358 directly in text mode. Here is described the basic use of @code{GDB}
18359 in text mode. All the commands described below can be used in the
18360 @code{gvd} console window even though there is usually other more
18361 graphical ways to achieve the same goals.
18362
18363 @ifclear vms
18364 @noindent
18365 The command to run the graphical interface of the debugger is
18366 @smallexample
18367 $ gvd program
18368 @end smallexample
18369 @end ifclear
18370
18371 @noindent
18372 The command to run @code{GDB} in text mode is
18373
18374 @smallexample
18375 $ ^gdb program^$ GDB PROGRAM^
18376 @end smallexample
18377
18378 @noindent
18379 where @code{^program^PROGRAM^} is the name of the executable file. This
18380 activates the debugger and results in a prompt for debugger commands.
18381 The simplest command is simply @code{run}, which causes the program to run
18382 exactly as if the debugger were not present. The following section
18383 describes some of the additional commands that can be given to @code{GDB}.
18384
18385
18386 @c *******************************
18387 @node Introduction to GDB Commands
18388 @section Introduction to GDB Commands
18389
18390 @noindent
18391 @code{GDB} contains a large repertoire of commands. The manual
18392 @cite{Debugging with GDB}
18393 @ifset vms
18394 , located in the GNU:[DOCS] directory,
18395 @end ifset
18396 includes extensive documentation on the use
18397 of these commands, together with examples of their use. Furthermore,
18398 the command @var{help} invoked from within @code{GDB} activates a simple help
18399 facility which summarizes the available commands and their options.
18400 In this section we summarize a few of the most commonly
18401 used commands to give an idea of what @code{GDB} is about. You should create
18402 a simple program with debugging information and experiment with the use of
18403 these @code{GDB} commands on the program as you read through the
18404 following section.
18405
18406 @table @code
18407 @item set args @var{arguments}
18408 The @var{arguments} list above is a list of arguments to be passed to
18409 the program on a subsequent run command, just as though the arguments
18410 had been entered on a normal invocation of the program. The @code{set args}
18411 command is not needed if the program does not require arguments.
18412
18413 @item run
18414 The @code{run} command causes execution of the program to start from
18415 the beginning. If the program is already running, that is to say if
18416 you are currently positioned at a breakpoint, then a prompt will ask
18417 for confirmation that you want to abandon the current execution and
18418 restart.
18419
18420 @item breakpoint @var{location}
18421 The breakpoint command sets a breakpoint, that is to say a point at which
18422 execution will halt and @code{GDB} will await further
18423 commands. @var{location} is
18424 either a line number within a file, given in the format @code{file:linenumber},
18425 or it is the name of a subprogram. If you request that a breakpoint be set on
18426 a subprogram that is overloaded, a prompt will ask you to specify on which of
18427 those subprograms you want to breakpoint. You can also
18428 specify that all of them should be breakpointed. If the program is run
18429 and execution encounters the breakpoint, then the program
18430 stops and @code{GDB} signals that the breakpoint was encountered by
18431 printing the line of code before which the program is halted.
18432
18433 @item breakpoint exception @var{name}
18434 A special form of the breakpoint command which breakpoints whenever
18435 exception @var{name} is raised.
18436 If @var{name} is omitted,
18437 then a breakpoint will occur when any exception is raised.
18438
18439 @item print @var{expression}
18440 This will print the value of the given expression. Most simple
18441 Ada expression formats are properly handled by @code{GDB}, so the expression
18442 can contain function calls, variables, operators, and attribute references.
18443
18444 @item continue
18445 Continues execution following a breakpoint, until the next breakpoint or the
18446 termination of the program.
18447
18448 @item step
18449 Executes a single line after a breakpoint. If the next statement
18450 is a subprogram call, execution continues into (the first statement of)
18451 the called subprogram.
18452
18453 @item next
18454 Executes a single line. If this line is a subprogram call, executes and
18455 returns from the call.
18456
18457 @item list
18458 Lists a few lines around the current source location. In practice, it
18459 is usually more convenient to have a separate edit window open with the
18460 relevant source file displayed. Successive applications of this command
18461 print subsequent lines. The command can be given an argument which is a
18462 line number, in which case it displays a few lines around the specified one.
18463
18464 @item backtrace
18465 Displays a backtrace of the call chain. This command is typically
18466 used after a breakpoint has occurred, to examine the sequence of calls that
18467 leads to the current breakpoint. The display includes one line for each
18468 activation record (frame) corresponding to an active subprogram.
18469
18470 @item up
18471 At a breakpoint, @code{GDB} can display the values of variables local
18472 to the current frame. The command @code{up} can be used to
18473 examine the contents of other active frames, by moving the focus up
18474 the stack, that is to say from callee to caller, one frame at a time.
18475
18476 @item down
18477 Moves the focus of @code{GDB} down from the frame currently being
18478 examined to the frame of its callee (the reverse of the previous command),
18479
18480 @item frame @var{n}
18481 Inspect the frame with the given number. The value 0 denotes the frame
18482 of the current breakpoint, that is to say the top of the call stack.
18483
18484 @end table
18485
18486 The above list is a very short introduction to the commands that
18487 @code{GDB} provides. Important additional capabilities, including conditional
18488 breakpoints, the ability to execute command sequences on a breakpoint,
18489 the ability to debug at the machine instruction level and many other
18490 features are described in detail in @cite{Debugging with GDB}.
18491 Note that most commands can be abbreviated
18492 (for example, c for continue, bt for backtrace).
18493
18494 @node Using Ada Expressions
18495 @section Using Ada Expressions
18496 @cindex Ada expressions
18497
18498 @noindent
18499 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18500 extensions. The philosophy behind the design of this subset is
18501
18502 @itemize @bullet
18503 @item
18504 That @code{GDB} should provide basic literals and access to operations for
18505 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18506 leaving more sophisticated computations to subprograms written into the
18507 program (which therefore may be called from @code{GDB}).
18508
18509 @item
18510 That type safety and strict adherence to Ada language restrictions
18511 are not particularly important to the @code{GDB} user.
18512
18513 @item
18514 That brevity is important to the @code{GDB} user.
18515 @end itemize
18516
18517 Thus, for brevity, the debugger acts as if there were
18518 implicit @code{with} and @code{use} clauses in effect for all user-written
18519 packages, thus making it unnecessary to fully qualify most names with
18520 their packages, regardless of context. Where this causes ambiguity,
18521 @code{GDB} asks the user's intent.
18522
18523 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18524
18525 @node Calling User-Defined Subprograms
18526 @section Calling User-Defined Subprograms
18527
18528 @noindent
18529 An important capability of @code{GDB} is the ability to call user-defined
18530 subprograms while debugging. This is achieved simply by entering
18531 a subprogram call statement in the form:
18532
18533 @smallexample
18534 call subprogram-name (parameters)
18535 @end smallexample
18536
18537 @noindent
18538 The keyword @code{call} can be omitted in the normal case where the
18539 @code{subprogram-name} does not coincide with any of the predefined
18540 @code{GDB} commands.
18541
18542 The effect is to invoke the given subprogram, passing it the
18543 list of parameters that is supplied. The parameters can be expressions and
18544 can include variables from the program being debugged. The
18545 subprogram must be defined
18546 at the library level within your program, and @code{GDB} will call the
18547 subprogram within the environment of your program execution (which
18548 means that the subprogram is free to access or even modify variables
18549 within your program).
18550
18551 The most important use of this facility is in allowing the inclusion of
18552 debugging routines that are tailored to particular data structures
18553 in your program. Such debugging routines can be written to provide a suitably
18554 high-level description of an abstract type, rather than a low-level dump
18555 of its physical layout. After all, the standard
18556 @code{GDB print} command only knows the physical layout of your
18557 types, not their abstract meaning. Debugging routines can provide information
18558 at the desired semantic level and are thus enormously useful.
18559
18560 For example, when debugging GNAT itself, it is crucial to have access to
18561 the contents of the tree nodes used to represent the program internally.
18562 But tree nodes are represented simply by an integer value (which in turn
18563 is an index into a table of nodes).
18564 Using the @code{print} command on a tree node would simply print this integer
18565 value, which is not very useful. But the PN routine (defined in file
18566 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18567 a useful high level representation of the tree node, which includes the
18568 syntactic category of the node, its position in the source, the integers
18569 that denote descendant nodes and parent node, as well as varied
18570 semantic information. To study this example in more detail, you might want to
18571 look at the body of the PN procedure in the stated file.
18572
18573 @node Using the Next Command in a Function
18574 @section Using the Next Command in a Function
18575
18576 @noindent
18577 When you use the @code{next} command in a function, the current source
18578 location will advance to the next statement as usual. A special case
18579 arises in the case of a @code{return} statement.
18580
18581 Part of the code for a return statement is the ``epilog'' of the function.
18582 This is the code that returns to the caller. There is only one copy of
18583 this epilog code, and it is typically associated with the last return
18584 statement in the function if there is more than one return. In some
18585 implementations, this epilog is associated with the first statement
18586 of the function.
18587
18588 The result is that if you use the @code{next} command from a return
18589 statement that is not the last return statement of the function you
18590 may see a strange apparent jump to the last return statement or to
18591 the start of the function. You should simply ignore this odd jump.
18592 The value returned is always that from the first return statement
18593 that was stepped through.
18594
18595 @node Ada Exceptions
18596 @section Breaking on Ada Exceptions
18597 @cindex Exceptions
18598
18599 @noindent
18600 You can set breakpoints that trip when your program raises
18601 selected exceptions.
18602
18603 @table @code
18604 @item break exception
18605 Set a breakpoint that trips whenever (any task in the) program raises
18606 any exception.
18607
18608 @item break exception @var{name}
18609 Set a breakpoint that trips whenever (any task in the) program raises
18610 the exception @var{name}.
18611
18612 @item break exception unhandled
18613 Set a breakpoint that trips whenever (any task in the) program raises an
18614 exception for which there is no handler.
18615
18616 @item info exceptions
18617 @itemx info exceptions @var{regexp}
18618 The @code{info exceptions} command permits the user to examine all defined
18619 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18620 argument, prints out only those exceptions whose name matches @var{regexp}.
18621 @end table
18622
18623 @node Ada Tasks
18624 @section Ada Tasks
18625 @cindex Tasks
18626
18627 @noindent
18628 @code{GDB} allows the following task-related commands:
18629
18630 @table @code
18631 @item info tasks
18632 This command shows a list of current Ada tasks, as in the following example:
18633
18634 @smallexample
18635 @iftex
18636 @leftskip=0cm
18637 @end iftex
18638 (gdb) info tasks
18639   ID       TID P-ID   Thread Pri State                 Name
18640    1   8088000   0   807e000  15 Child Activation Wait main_task
18641    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18642    3   809a800   1   80a4800  15 Child Activation Wait a
18643 *  4   80ae800   3   80b8000  15 Running               c
18644 @end smallexample
18645
18646 @noindent
18647 In this listing, the asterisk before the first task indicates it to be the
18648 currently running task. The first column lists the task ID that is used
18649 to refer to tasks in the following commands.
18650
18651 @item break @var{linespec} task @var{taskid}
18652 @itemx break @var{linespec} task @var{taskid} if @dots{}
18653 @cindex Breakpoints and tasks
18654 These commands are like the @code{break @dots{} thread @dots{}}.
18655 @var{linespec} specifies source lines.
18656
18657 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18658 to specify that you only want @code{GDB} to stop the program when a
18659 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18660 numeric task identifiers assigned by @code{GDB}, shown in the first
18661 column of the @samp{info tasks} display.
18662
18663 If you do not specify @samp{task @var{taskid}} when you set a
18664 breakpoint, the breakpoint applies to @emph{all} tasks of your
18665 program.
18666
18667 You can use the @code{task} qualifier on conditional breakpoints as
18668 well; in this case, place @samp{task @var{taskid}} before the
18669 breakpoint condition (before the @code{if}).
18670
18671 @item task @var{taskno}
18672 @cindex Task switching
18673
18674 This command allows to switch to the task referred by @var{taskno}. In
18675 particular, This allows to browse the backtrace of the specified
18676 task. It is advised to switch back to the original task before
18677 continuing execution otherwise the scheduling of the program may be
18678 perturbated.
18679 @end table
18680
18681 @noindent
18682 For more detailed information on the tasking support,
18683 see @cite{Debugging with GDB}.
18684
18685 @node Debugging Generic Units
18686 @section Debugging Generic Units
18687 @cindex Debugging Generic Units
18688 @cindex Generics
18689
18690 @noindent
18691 GNAT always uses code expansion for generic instantiation. This means that
18692 each time an instantiation occurs, a complete copy of the original code is
18693 made, with appropriate substitutions of formals by actuals.
18694
18695 It is not possible to refer to the original generic entities in
18696 @code{GDB}, but it is always possible to debug a particular instance of
18697 a generic, by using the appropriate expanded names. For example, if we have
18698
18699 @smallexample @c ada
18700 @group
18701 @cartouche
18702 procedure g is
18703
18704    generic package k is
18705       procedure kp (v1 : in out integer);
18706    end k;
18707
18708    package body k is
18709       procedure kp (v1 : in out integer) is
18710       begin
18711          v1 := v1 + 1;
18712       end kp;
18713    end k;
18714
18715    package k1 is new k;
18716    package k2 is new k;
18717
18718    var : integer := 1;
18719
18720 begin
18721    k1.kp (var);
18722    k2.kp (var);
18723    k1.kp (var);
18724    k2.kp (var);
18725 end;
18726 @end cartouche
18727 @end group
18728 @end smallexample
18729
18730 @noindent
18731 Then to break on a call to procedure kp in the k2 instance, simply
18732 use the command:
18733
18734 @smallexample
18735 (gdb) break g.k2.kp
18736 @end smallexample
18737
18738 @noindent
18739 When the breakpoint occurs, you can step through the code of the
18740 instance in the normal manner and examine the values of local variables, as for
18741 other units.
18742
18743 @node GNAT Abnormal Termination or Failure to Terminate
18744 @section GNAT Abnormal Termination or Failure to Terminate
18745 @cindex GNAT Abnormal Termination or Failure to Terminate
18746
18747 @noindent
18748 When presented with programs that contain serious errors in syntax
18749 or semantics,
18750 GNAT may on rare occasions  experience problems in operation, such
18751 as aborting with a
18752 segmentation fault or illegal memory access, raising an internal
18753 exception, terminating abnormally, or failing to terminate at all.
18754 In such cases, you can activate
18755 various features of GNAT that can help you pinpoint the construct in your
18756 program that is the likely source of the problem.
18757
18758 The following strategies are presented in increasing order of
18759 difficulty, corresponding to your experience in using GNAT and your
18760 familiarity with compiler internals.
18761
18762 @enumerate
18763 @item
18764 Run @code{gcc} with the @option{-gnatf}. This first
18765 switch causes all errors on a given line to be reported. In its absence,
18766 only the first error on a line is displayed.
18767
18768 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18769 are encountered, rather than after compilation is terminated. If GNAT
18770 terminates prematurely or goes into an infinite loop, the last error
18771 message displayed may help to pinpoint the culprit.
18772
18773 @item
18774 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18775 @code{gcc} produces ongoing information about the progress of the
18776 compilation and provides the name of each procedure as code is
18777 generated. This switch allows you to find which Ada procedure was being
18778 compiled when it encountered a code generation problem.
18779
18780 @item
18781 @cindex @option{-gnatdc} switch
18782 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18783 switch that does for the front-end what @option{^-v^VERBOSE^} does
18784 for the back end. The system prints the name of each unit,
18785 either a compilation unit or nested unit, as it is being analyzed.
18786 @item
18787 Finally, you can start
18788 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18789 front-end of GNAT, and can be run independently (normally it is just
18790 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18791 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18792 @code{where} command is the first line of attack; the variable
18793 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18794 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18795 which the execution stopped, and @code{input_file name} indicates the name of
18796 the source file.
18797 @end enumerate
18798
18799 @node Naming Conventions for GNAT Source Files
18800 @section Naming Conventions for GNAT Source Files
18801
18802 @noindent
18803 In order to examine the workings of the GNAT system, the following
18804 brief description of its organization may be helpful:
18805
18806 @itemize @bullet
18807 @item
18808 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18809
18810 @item
18811 All files prefixed with @file{^par^PAR^} are components of the parser. The
18812 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18813 parsing of select statements can be found in @file{par-ch9.adb}.
18814
18815 @item
18816 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18817 numbers correspond to chapters of the Ada standard. For example, all
18818 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18819 addition, some features of the language require sufficient special processing
18820 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18821 dynamic dispatching, etc.
18822
18823 @item
18824 All files prefixed with @file{^exp^EXP^} perform normalization and
18825 expansion of the intermediate representation (abstract syntax tree, or AST).
18826 these files use the same numbering scheme as the parser and semantics files.
18827 For example, the construction of record initialization procedures is done in
18828 @file{exp_ch3.adb}.
18829
18830 @item
18831 The files prefixed with @file{^bind^BIND^} implement the binder, which
18832 verifies the consistency of the compilation, determines an order of
18833 elaboration, and generates the bind file.
18834
18835 @item
18836 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18837 data structures used by the front-end.
18838
18839 @item
18840 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18841 the abstract syntax tree as produced by the parser.
18842
18843 @item
18844 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18845 all entities, computed during semantic analysis.
18846
18847 @item
18848 Library management issues are dealt with in files with prefix
18849 @file{^lib^LIB^}.
18850
18851 @item
18852 @findex Ada
18853 @cindex Annex A
18854 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18855 defined in Annex A.
18856
18857 @item
18858 @findex Interfaces
18859 @cindex Annex B
18860 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18861 defined in Annex B.
18862
18863 @item
18864 @findex System
18865 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18866 both language-defined children and GNAT run-time routines.
18867
18868 @item
18869 @findex GNAT
18870 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18871 general-purpose packages, fully documented in their specifications. All
18872 the other @file{.c} files are modifications of common @code{gcc} files.
18873 @end itemize
18874
18875 @node Getting Internal Debugging Information
18876 @section Getting Internal Debugging Information
18877
18878 @noindent
18879 Most compilers have internal debugging switches and modes. GNAT
18880 does also, except GNAT internal debugging switches and modes are not
18881 secret. A summary and full description of all the compiler and binder
18882 debug flags are in the file @file{debug.adb}. You must obtain the
18883 sources of the compiler to see the full detailed effects of these flags.
18884
18885 The switches that print the source of the program (reconstructed from
18886 the internal tree) are of general interest for user programs, as are the
18887 options to print
18888 the full internal tree, and the entity table (the symbol table
18889 information). The reconstructed source provides a readable version of the
18890 program after the front-end has completed analysis and  expansion,
18891 and is useful when studying the performance of specific constructs.
18892 For example, constraint checks are indicated, complex aggregates
18893 are replaced with loops and assignments, and tasking primitives
18894 are replaced with run-time calls.
18895
18896 @node Stack Traceback
18897 @section Stack Traceback
18898 @cindex traceback
18899 @cindex stack traceback
18900 @cindex stack unwinding
18901
18902 @noindent
18903 Traceback is a mechanism to display the sequence of subprogram calls that
18904 leads to a specified execution point in a program. Often (but not always)
18905 the execution point is an instruction at which an exception has been raised.
18906 This mechanism is also known as @i{stack unwinding} because it obtains
18907 its information by scanning the run-time stack and recovering the activation
18908 records of all active subprograms. Stack unwinding is one of the most
18909 important tools for program debugging.
18910
18911 The first entry stored in traceback corresponds to the deepest calling level,
18912 that is to say the subprogram currently executing the instruction
18913 from which we want to obtain the traceback.
18914
18915 Note that there is no runtime performance penalty when stack traceback
18916 is enabled, and no exception is raised during program execution.
18917
18918 @menu
18919 * Non-Symbolic Traceback::
18920 * Symbolic Traceback::
18921 @end menu
18922
18923 @node Non-Symbolic Traceback
18924 @subsection Non-Symbolic Traceback
18925 @cindex traceback, non-symbolic
18926
18927 @noindent
18928 Note: this feature is not supported on all platforms. See
18929 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18930 platforms.
18931
18932 @menu
18933 * Tracebacks From an Unhandled Exception::
18934 * Tracebacks From Exception Occurrences (non-symbolic)::
18935 * Tracebacks From Anywhere in a Program (non-symbolic)::
18936 @end menu
18937
18938 @node Tracebacks From an Unhandled Exception
18939 @subsubsection Tracebacks From an Unhandled Exception
18940
18941 @noindent
18942 A runtime non-symbolic traceback is a list of addresses of call instructions.
18943 To enable this feature you must use the @option{-E}
18944 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18945 of exception information. You can retrieve this information using the
18946 @code{addr2line} tool.
18947
18948 Here is a simple example:
18949
18950 @smallexample @c ada
18951 @cartouche
18952 procedure STB is
18953
18954    procedure P1 is
18955    begin
18956       raise Constraint_Error;
18957    end P1;
18958
18959    procedure P2 is
18960    begin
18961       P1;
18962    end P2;
18963
18964 begin
18965    P2;
18966 end STB;
18967 @end cartouche
18968 @end smallexample
18969
18970 @smallexample
18971 $ gnatmake stb -bargs -E
18972 $ stb
18973
18974 Execution terminated by unhandled exception
18975 Exception name: CONSTRAINT_ERROR
18976 Message: stb.adb:5
18977 Call stack traceback locations:
18978 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18979 @end smallexample
18980
18981 @noindent
18982 As we see the traceback lists a sequence of addresses for the unhandled
18983 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18984 guess that this exception come from procedure P1. To translate these
18985 addresses into the source lines where the calls appear, the
18986 @code{addr2line} tool, described below, is invaluable. The use of this tool
18987 requires the program to be compiled with debug information.
18988
18989 @smallexample
18990 $ gnatmake -g stb -bargs -E
18991 $ stb
18992
18993 Execution terminated by unhandled exception
18994 Exception name: CONSTRAINT_ERROR
18995 Message: stb.adb:5
18996 Call stack traceback locations:
18997 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18998
18999 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19000    0x4011f1 0x77e892a4
19001
19002 00401373 at d:/stb/stb.adb:5
19003 0040138B at d:/stb/stb.adb:10
19004 0040139C at d:/stb/stb.adb:14
19005 00401335 at d:/stb/b~stb.adb:104
19006 004011C4 at /build/.../crt1.c:200
19007 004011F1 at /build/.../crt1.c:222
19008 77E892A4 in ?? at ??:0
19009 @end smallexample
19010
19011 @noindent
19012 The @code{addr2line} tool has several other useful options:
19013
19014 @table @code
19015 @item --functions
19016 to get the function name corresponding to any location
19017
19018 @item --demangle=gnat
19019 to use the gnat decoding mode for the function names. Note that
19020 for binutils version 2.9.x the option is simply @option{--demangle}.
19021 @end table
19022
19023 @smallexample
19024 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19025    0x40139c 0x401335 0x4011c4 0x4011f1
19026
19027 00401373 in stb.p1 at d:/stb/stb.adb:5
19028 0040138B in stb.p2 at d:/stb/stb.adb:10
19029 0040139C in stb at d:/stb/stb.adb:14
19030 00401335 in main at d:/stb/b~stb.adb:104
19031 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19032 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19033 @end smallexample
19034
19035 @noindent
19036 From this traceback we can see that the exception was raised in
19037 @file{stb.adb} at line 5, which was reached from a procedure call in
19038 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19039 which contains the call to the main program.
19040 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
19041 and the output will vary from platform to platform.
19042
19043 It is also possible to use @code{GDB} with these traceback addresses to debug
19044 the program. For example, we can break at a given code location, as reported
19045 in the stack traceback:
19046
19047 @smallexample
19048 $ gdb -nw stb
19049 @ifclear vms
19050 @noindent
19051 Furthermore, this feature is not implemented inside Windows DLL. Only
19052 the non-symbolic traceback is reported in this case.
19053 @end ifclear
19054
19055 (gdb) break *0x401373
19056 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19057 @end smallexample
19058
19059 @noindent
19060 It is important to note that the stack traceback addresses
19061 do not change when debug information is included. This is particularly useful
19062 because it makes it possible to release software without debug information (to
19063 minimize object size), get a field report that includes a stack traceback
19064 whenever an internal bug occurs, and then be able to retrieve the sequence
19065 of calls with the same program compiled with debug information.
19066
19067 @node Tracebacks From Exception Occurrences (non-symbolic)
19068 @subsubsection Tracebacks From Exception Occurrences
19069
19070 @noindent
19071 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19072 The stack traceback is attached to the exception information string, and can
19073 be retrieved in an exception handler within the Ada program, by means of the
19074 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19075
19076 @smallexample @c ada
19077 with Ada.Text_IO;
19078 with Ada.Exceptions;
19079
19080 procedure STB is
19081
19082    use Ada;
19083    use Ada.Exceptions;
19084
19085    procedure P1 is
19086       K : Positive := 1;
19087    begin
19088       K := K - 1;
19089    exception
19090       when E : others =>
19091          Text_IO.Put_Line (Exception_Information (E));
19092    end P1;
19093
19094    procedure P2 is
19095    begin
19096       P1;
19097    end P2;
19098
19099 begin
19100    P2;
19101 end STB;
19102 @end smallexample
19103
19104 @noindent
19105 This program will output:
19106
19107 @smallexample
19108 $ stb
19109
19110 Exception name: CONSTRAINT_ERROR
19111 Message: stb.adb:12
19112 Call stack traceback locations:
19113 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19114 @end smallexample
19115
19116 @node Tracebacks From Anywhere in a Program (non-symbolic)
19117 @subsubsection Tracebacks From Anywhere in a Program
19118
19119 @noindent
19120 It is also possible to retrieve a stack traceback from anywhere in a
19121 program. For this you need to
19122 use the @code{GNAT.Traceback} API. This package includes a procedure called
19123 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19124 display procedures described below. It is not necessary to use the
19125 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19126 is invoked explicitly.
19127
19128 @noindent
19129 In the following example we compute a traceback at a specific location in
19130 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19131 convert addresses to strings:
19132
19133 @smallexample @c ada
19134 with Ada.Text_IO;
19135 with GNAT.Traceback;
19136 with GNAT.Debug_Utilities;
19137
19138 procedure STB is
19139
19140    use Ada;
19141    use GNAT;
19142    use GNAT.Traceback;
19143
19144    procedure P1 is
19145       TB  : Tracebacks_Array (1 .. 10);
19146       --  We are asking for a maximum of 10 stack frames.
19147       Len : Natural;
19148       --  Len will receive the actual number of stack frames returned.
19149    begin
19150       Call_Chain (TB, Len);
19151
19152       Text_IO.Put ("In STB.P1 : ");
19153
19154       for K in 1 .. Len loop
19155          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19156          Text_IO.Put (' ');
19157       end loop;
19158
19159       Text_IO.New_Line;
19160    end P1;
19161
19162    procedure P2 is
19163    begin
19164       P1;
19165    end P2;
19166
19167 begin
19168    P2;
19169 end STB;
19170 @end smallexample
19171
19172 @smallexample
19173 $ gnatmake -g stb
19174 $ stb
19175
19176 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19177 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19178 @end smallexample
19179
19180 @noindent
19181 You can then get further information by invoking the @code{addr2line}
19182 tool as described earlier (note that the hexadecimal addresses
19183 need to be specified in C format, with a leading ``0x'').
19184
19185
19186 @node Symbolic Traceback
19187 @subsection Symbolic Traceback
19188 @cindex traceback, symbolic
19189
19190 @noindent
19191 A symbolic traceback is a stack traceback in which procedure names are
19192 associated with each code location.
19193
19194 @noindent
19195 Note that this feature is not supported on all platforms. See
19196 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19197 list of currently supported platforms.
19198
19199 @noindent
19200 Note that the symbolic traceback requires that the program be compiled
19201 with debug information. If it is not compiled with debug information
19202 only the non-symbolic information will be valid.
19203
19204 @menu
19205 * Tracebacks From Exception Occurrences (symbolic)::
19206 * Tracebacks From Anywhere in a Program (symbolic)::
19207 @end menu
19208
19209 @node Tracebacks From Exception Occurrences (symbolic)
19210 @subsubsection Tracebacks From Exception Occurrences
19211
19212 @smallexample @c ada
19213 with Ada.Text_IO;
19214 with GNAT.Traceback.Symbolic;
19215
19216 procedure STB is
19217
19218    procedure P1 is
19219    begin
19220       raise Constraint_Error;
19221    end P1;
19222
19223    procedure P2 is
19224    begin
19225       P1;
19226    end P2;
19227
19228    procedure P3 is
19229    begin
19230       P2;
19231    end P3;
19232
19233 begin
19234    P3;
19235 exception
19236    when E : others =>
19237       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19238 end STB;
19239 @end smallexample
19240
19241 @smallexample
19242 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19243 $ stb
19244
19245 0040149F in stb.p1 at stb.adb:8
19246 004014B7 in stb.p2 at stb.adb:13
19247 004014CF in stb.p3 at stb.adb:18
19248 004015DD in ada.stb at stb.adb:22
19249 00401461 in main at b~stb.adb:168
19250 004011C4 in __mingw_CRTStartup at crt1.c:200
19251 004011F1 in mainCRTStartup at crt1.c:222
19252 77E892A4 in ?? at ??:0
19253 @end smallexample
19254
19255 @noindent
19256 In the above example the ``.\'' syntax in the @command{gnatmake} command
19257 is currently required by @command{addr2line} for files that are in
19258 the current working directory.
19259 Moreover, the exact sequence of linker options may vary from platform
19260 to platform.
19261 The above @option{-largs} section is for Windows platforms. By contrast,
19262 under Unix there is no need for the @option{-largs} section.
19263 Differences across platforms are due to details of linker implementation.
19264
19265 @node Tracebacks From Anywhere in a Program (symbolic)
19266 @subsubsection Tracebacks From Anywhere in a Program
19267
19268 @noindent
19269 It is possible to get a symbolic stack traceback
19270 from anywhere in a program, just as for non-symbolic tracebacks.
19271 The first step is to obtain a non-symbolic
19272 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19273 information. Here is an example:
19274
19275 @smallexample @c ada
19276 with Ada.Text_IO;
19277 with GNAT.Traceback;
19278 with GNAT.Traceback.Symbolic;
19279
19280 procedure STB is
19281
19282    use Ada;
19283    use GNAT.Traceback;
19284    use GNAT.Traceback.Symbolic;
19285
19286    procedure P1 is
19287       TB  : Tracebacks_Array (1 .. 10);
19288       --  We are asking for a maximum of 10 stack frames.
19289       Len : Natural;
19290       --  Len will receive the actual number of stack frames returned.
19291    begin
19292       Call_Chain (TB, Len);
19293       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19294    end P1;
19295
19296    procedure P2 is
19297    begin
19298       P1;
19299    end P2;
19300
19301 begin
19302    P2;
19303 end STB;
19304 @end smallexample
19305
19306 @ifset vms
19307 @node Compatibility with DEC Ada
19308 @chapter Compatibility with DEC Ada
19309 @cindex Compatibility
19310
19311 @noindent
19312 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19313 OpenVMS Alpha. GNAT achieves a high level of compatibility
19314 with DEC Ada, and it should generally be straightforward to port code
19315 from the DEC Ada environment to GNAT. However, there are a few language
19316 and implementation differences of which the user must be aware. These
19317 differences are discussed in this section. In
19318 addition, the operating environment and command structure for the
19319 compiler are different, and these differences are also discussed.
19320
19321 Note that this discussion addresses specifically the implementation
19322 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19323 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19324 GNAT always follows the Alpha implementation.
19325
19326 @menu
19327 * Ada 95 Compatibility::
19328 * Differences in the Definition of Package System::
19329 * Language-Related Features::
19330 * The Package STANDARD::
19331 * The Package SYSTEM::
19332 * Tasking and Task-Related Features::
19333 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19334 * Pragmas and Pragma-Related Features::
19335 * Library of Predefined Units::
19336 * Bindings::
19337 * Main Program Definition::
19338 * Implementation-Defined Attributes::
19339 * Compiler and Run-Time Interfacing::
19340 * Program Compilation and Library Management::
19341 * Input-Output::
19342 * Implementation Limits::
19343 * Tools::
19344 @end menu
19345
19346 @node Ada 95 Compatibility
19347 @section Ada 95 Compatibility
19348
19349 @noindent
19350 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19351 compiler. Ada 95 is almost completely upwards compatible
19352 with Ada 83, and therefore Ada 83 programs will compile
19353 and run under GNAT with
19354 no changes or only minor changes. The Ada 95 Reference
19355 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19356 incompatibilities.
19357
19358 GNAT provides the switch /83 on the GNAT COMPILE command,
19359 as well as the pragma ADA_83, to force the compiler to
19360 operate in Ada 83 mode. This mode does not guarantee complete
19361 conformance to Ada 83, but in practice is sufficient to
19362 eliminate most sources of incompatibilities.
19363 In particular, it eliminates the recognition of the
19364 additional Ada 95 keywords, so that their use as identifiers
19365 in Ada83 program is legal, and handles the cases of packages
19366 with optional bodies, and generics that instantiate unconstrained
19367 types without the use of @code{(<>)}.
19368
19369 @node Differences in the Definition of Package System
19370 @section Differences in the Definition of Package System
19371
19372 @noindent
19373 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19374 implementation-dependent declarations to package System. In normal mode,
19375 GNAT does not take advantage of this permission, and the version of System
19376 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19377
19378 However, DEC Ada adds an extensive set of declarations to package System,
19379 as fully documented in the DEC Ada manuals. To minimize changes required
19380 for programs that make use of these extensions, GNAT provides the pragma
19381 Extend_System for extending the definition of package System. By using:
19382
19383 @smallexample @c ada
19384 @group
19385 @cartouche
19386 pragma Extend_System (Aux_DEC);
19387 @end cartouche
19388 @end group
19389 @end smallexample
19390
19391 @noindent
19392 The set of definitions in System is extended to include those in package
19393 @code{System.Aux_DEC}.
19394 These definitions are incorporated directly into package
19395 System, as though they had been declared there in the first place. For a
19396 list of the declarations added, see the specification of this package,
19397 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19398 The pragma Extend_System is a configuration pragma, which means that
19399 it can be placed in the file @file{gnat.adc}, so that it will automatically
19400 apply to all subsequent compilations. See the section on Configuration
19401 Pragmas for further details.
19402
19403 An alternative approach that avoids the use of the non-standard
19404 Extend_System pragma is to add a context clause to the unit that
19405 references these facilities:
19406
19407 @smallexample @c ada
19408 @group
19409 @cartouche
19410 with System.Aux_DEC;
19411 use  System.Aux_DEC;
19412 @end cartouche
19413 @end group
19414 @end smallexample
19415
19416 @noindent
19417 The effect is not quite semantically identical to incorporating
19418 the declarations directly into package @code{System},
19419 but most programs will not notice a difference
19420 unless they use prefix notation (e.g. @code{System.Integer_8})
19421 to reference the
19422 entities directly in package @code{System}.
19423 For units containing such references,
19424 the prefixes must either be removed, or the pragma @code{Extend_System}
19425 must be used.
19426
19427 @node Language-Related Features
19428 @section Language-Related Features
19429
19430 @noindent
19431 The following sections highlight differences in types,
19432 representations of types, operations, alignment, and
19433 related topics.
19434
19435 @menu
19436 * Integer Types and Representations::
19437 * Floating-Point Types and Representations::
19438 * Pragmas Float_Representation and Long_Float::
19439 * Fixed-Point Types and Representations::
19440 * Record and Array Component Alignment::
19441 * Address Clauses::
19442 * Other Representation Clauses::
19443 @end menu
19444
19445 @node Integer Types and Representations
19446 @subsection Integer Types and Representations
19447
19448 @noindent
19449 The set of predefined integer types is identical in DEC Ada and GNAT.
19450 Furthermore the representation of these integer types is also identical,
19451 including the capability of size clauses forcing biased representation.
19452
19453 In addition,
19454 DEC Ada for OpenVMS Alpha systems has defined the
19455 following additional integer types in package System:
19456
19457 @itemize @bullet
19458
19459 @item
19460 INTEGER_8
19461
19462 @item
19463 INTEGER_16
19464
19465 @item
19466 INTEGER_32
19467
19468 @item
19469 INTEGER_64
19470
19471 @item
19472 LARGEST_INTEGER
19473 @end itemize
19474
19475 @noindent
19476 When using GNAT, the first four of these types may be obtained from the
19477 standard Ada 95 package @code{Interfaces}.
19478 Alternatively, by use of the pragma
19479 @code{Extend_System}, identical
19480 declarations can be referenced directly in package @code{System}.
19481 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19482
19483 @node Floating-Point Types and Representations
19484 @subsection Floating-Point Types and Representations
19485 @cindex Floating-Point types
19486
19487 @noindent
19488 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19489 Furthermore the representation of these floating-point
19490 types is also identical. One important difference is that the default
19491 representation for DEC Ada is VAX_Float, but the default representation
19492 for GNAT is IEEE.
19493
19494 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19495 @code{Float_Representation} as described in the DEC Ada documentation.
19496 For example, the declarations:
19497
19498 @smallexample @c ada
19499 @group
19500 @cartouche
19501 type F_Float is digits 6;
19502 pragma Float_Representation (VAX_Float, F_Float);
19503 @end cartouche
19504 @end group
19505 @end smallexample
19506
19507 @noindent
19508 declare a type F_Float that will be represented in VAX_Float format.
19509 This set of declarations actually appears in System.Aux_DEC, which provides
19510 the full set of additional floating-point declarations provided in
19511 the DEC Ada version of package
19512 System. This and similar declarations may be accessed in a user program
19513 by using pragma @code{Extend_System}. The use of this
19514 pragma, and the related pragma @code{Long_Float} is described in further
19515 detail in the following section.
19516
19517 @node Pragmas Float_Representation and Long_Float
19518 @subsection Pragmas Float_Representation and Long_Float
19519
19520 @noindent
19521 DEC Ada provides the pragma @code{Float_Representation}, which
19522 acts as a program library switch to allow control over
19523 the internal representation chosen for the predefined
19524 floating-point types declared in the package @code{Standard}.
19525 The format of this pragma is as follows:
19526
19527 @smallexample
19528 @group
19529 @cartouche
19530 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19531 @end cartouche
19532 @end group
19533 @end smallexample
19534
19535 @noindent
19536 This pragma controls the representation of floating-point
19537 types as follows:
19538
19539 @itemize @bullet
19540 @item
19541 @code{VAX_Float} specifies that floating-point
19542 types are represented by default with the VAX hardware types
19543 F-floating, D-floating, G-floating. Note that the H-floating
19544 type is available only on DIGITAL Vax systems, and is not available
19545 in either DEC Ada or GNAT for Alpha systems.
19546
19547 @item
19548 @code{IEEE_Float} specifies that floating-point
19549 types are represented by default with the IEEE single and
19550 double floating-point types.
19551 @end itemize
19552
19553 @noindent
19554 GNAT provides an identical implementation of the pragma
19555 @code{Float_Representation}, except that it functions as a
19556 configuration pragma, as defined by Ada 95. Note that the
19557 notion of configuration pragma corresponds closely to the
19558 DEC Ada notion of a program library switch.
19559
19560 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19561 from DEC Ada 83, where the default is VAX_Float. In addition, the
19562 predefined libraries in GNAT are built using IEEE_Float, so it is not
19563 advisable to change the format of numbers passed to standard library
19564 routines, and if necessary explicit type conversions may be needed.
19565
19566 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19567 and (given that it conforms to an international standard) potentially more
19568 portable. The situation in which VAX_Float may be useful is in interfacing
19569 to existing code and data that expects the use of VAX_Float. There are
19570 two possibilities here. If the requirement for the use of VAX_Float is
19571 localized, then the best approach is to use the predefined VAX_Float
19572 types in package @code{System}, as extended by
19573 @code{Extend_System}. For example, use @code{System.F_Float}
19574 to specify the 32-bit @code{F-Float} format.
19575
19576 Alternatively, if an entire program depends heavily on the use of
19577 the @code{VAX_Float} and in particular assumes that the types in
19578 package @code{Standard} are in @code{Vax_Float} format, then it
19579 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19580 This is done by using the GNAT LIBRARY command to rebuild the library, and
19581 then using the general form of the @code{Float_Representation}
19582 pragma to ensure that this default format is used throughout.
19583 The form of the GNAT LIBRARY command is:
19584
19585 @smallexample
19586 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19587 @end smallexample
19588
19589 @noindent
19590 where @i{file} contains the new configuration pragmas
19591 and @i{directory} is the directory to be created to contain
19592 the new library.
19593
19594 @noindent
19595 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19596 to allow control over the internal representation chosen
19597 for the predefined type @code{Long_Float} and for floating-point
19598 type declarations with digits specified in the range 7 .. 15.
19599 The format of this pragma is as follows:
19600
19601 @smallexample @c ada
19602 @cartouche
19603 pragma Long_Float (D_FLOAT | G_FLOAT);
19604 @end cartouche
19605 @end smallexample
19606
19607 @node Fixed-Point Types and Representations
19608 @subsection Fixed-Point Types and Representations
19609
19610 @noindent
19611 On DEC Ada for OpenVMS Alpha systems, rounding is
19612 away from zero for both positive and negative numbers.
19613 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19614
19615 On GNAT for OpenVMS Alpha, the results of operations
19616 on fixed-point types are in accordance with the Ada 95
19617 rules. In particular, results of operations on decimal
19618 fixed-point types are truncated.
19619
19620 @node Record and Array Component Alignment
19621 @subsection Record and Array Component Alignment
19622
19623 @noindent
19624 On DEC Ada for OpenVMS Alpha, all non composite components
19625 are aligned on natural boundaries. For example, 1-byte
19626 components are aligned on byte boundaries, 2-byte
19627 components on 2-byte boundaries, 4-byte components on 4-byte
19628 byte boundaries, and so on. The OpenVMS Alpha hardware
19629 runs more efficiently with naturally aligned data.
19630
19631 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19632 with DEC Ada for OpenVMS Alpha.
19633
19634 @node Address Clauses
19635 @subsection Address Clauses
19636
19637 @noindent
19638 In DEC Ada and GNAT, address clauses are supported for
19639 objects and imported subprograms.
19640 The predefined type @code{System.Address} is a private type
19641 in both compilers, with the same representation (it is simply
19642 a machine pointer). Addition, subtraction, and comparison
19643 operations are available in the standard Ada 95 package
19644 @code{System.Storage_Elements}, or in package @code{System}
19645 if it is extended to include @code{System.Aux_DEC} using a
19646 pragma @code{Extend_System} as previously described.
19647
19648 Note that code that with's both this extended package @code{System}
19649 and the package @code{System.Storage_Elements} should not @code{use}
19650 both packages, or ambiguities will result. In general it is better
19651 not to mix these two sets of facilities. The Ada 95 package was
19652 designed specifically to provide the kind of features that DEC Ada
19653 adds directly to package @code{System}.
19654
19655 GNAT is compatible with DEC Ada in its handling of address
19656 clauses, except for some limitations in
19657 the form of address clauses for composite objects with
19658 initialization. Such address clauses are easily replaced
19659 by the use of an explicitly-defined constant as described
19660 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19661 of declarations:
19662
19663 @smallexample @c ada
19664 @cartouche
19665 X, Y : Integer := Init_Func;
19666 Q : String (X .. Y) := "abc";
19667 ...
19668 for Q'Address use Compute_Address;
19669 @end cartouche
19670 @end smallexample
19671
19672 @noindent
19673 will be rejected by GNAT, since the address cannot be computed at the time
19674 that Q is declared. To achieve the intended effect, write instead:
19675
19676 @smallexample @c ada
19677 @group
19678 @cartouche
19679 X, Y : Integer := Init_Func;
19680 Q_Address : constant Address := Compute_Address;
19681 Q : String (X .. Y) := "abc";
19682 ...
19683 for Q'Address use Q_Address;
19684 @end cartouche
19685 @end group
19686 @end smallexample
19687
19688 @noindent
19689 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19690 backwards compatible with Ada 83. A fuller description of the restrictions
19691 on address specifications is found in the GNAT Reference Manual.
19692
19693 @node Other Representation Clauses
19694 @subsection Other Representation Clauses
19695
19696 @noindent
19697 GNAT supports in a compatible manner all the representation
19698 clauses supported by DEC Ada. In addition, it
19699 supports representation clause forms that are new in Ada 95
19700 including COMPONENT_SIZE and SIZE clauses for objects.
19701
19702 @node The Package STANDARD
19703 @section The Package STANDARD
19704
19705 @noindent
19706 The package STANDARD, as implemented by DEC Ada, is fully
19707 described in the Reference Manual for the Ada Programming
19708 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19709 Language Reference Manual. As implemented by GNAT, the
19710 package STANDARD is described in the Ada 95 Reference
19711 Manual.
19712
19713 In addition, DEC Ada supports the Latin-1 character set in
19714 the type CHARACTER. GNAT supports the Latin-1 character set
19715 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19716 the type WIDE_CHARACTER.
19717
19718 The floating-point types supported by GNAT are those
19719 supported by DEC Ada, but defaults are different, and are controlled by
19720 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19721
19722 @node The Package SYSTEM
19723 @section The Package SYSTEM
19724
19725 @noindent
19726 DEC Ada provides a system-specific version of the package
19727 SYSTEM for each platform on which the language ships.
19728 For the complete specification of the package SYSTEM, see
19729 Appendix F of the DEC Ada Language Reference Manual.
19730
19731 On DEC Ada, the package SYSTEM includes the following conversion functions:
19732 @itemize @bullet
19733 @item TO_ADDRESS(INTEGER)
19734
19735 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19736
19737 @item  TO_ADDRESS(universal_integer)
19738
19739 @item  TO_INTEGER(ADDRESS)
19740
19741 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19742
19743 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19744                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19745 @end itemize
19746
19747 @noindent
19748 By default, GNAT supplies a version of SYSTEM that matches
19749 the definition given in the Ada 95 Reference Manual.
19750 This
19751 is a subset of the DIGITAL system definitions, which is as
19752 close as possible to the original definitions. The only difference
19753 is that the definition of SYSTEM_NAME is different:
19754
19755 @smallexample @c ada
19756 @group
19757 @cartouche
19758 type Name is (SYSTEM_NAME_GNAT);
19759 System_Name : constant Name := SYSTEM_NAME_GNAT;
19760 @end cartouche
19761 @end group
19762 @end smallexample
19763
19764 @noindent
19765 Also, GNAT adds the new Ada 95 declarations for
19766 BIT_ORDER and DEFAULT_BIT_ORDER.
19767
19768 However, the use of the following pragma causes GNAT
19769 to extend the definition of package SYSTEM so that it
19770 encompasses the full set of DIGITAL-specific extensions,
19771 including the functions listed above:
19772
19773 @smallexample @c ada
19774 @cartouche
19775 pragma Extend_System (Aux_DEC);
19776 @end cartouche
19777 @end smallexample
19778
19779 @noindent
19780 The pragma Extend_System is a configuration pragma that
19781 is most conveniently placed in the @file{gnat.adc} file. See the
19782 GNAT Reference Manual for further details.
19783
19784 DEC Ada does not allow the recompilation of the package
19785 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19786 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19787 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19788 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19789 its single argument.
19790
19791 GNAT does permit the recompilation of package SYSTEM using
19792 a special switch (@option{-gnatg}) and this switch can be used if
19793 it is necessary to modify the definitions in SYSTEM. GNAT does
19794 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19795 or MEMORY_SIZE by any other means.
19796
19797 On GNAT systems, the pragma SYSTEM_NAME takes the
19798 enumeration literal SYSTEM_NAME_GNAT.
19799
19800 The definitions provided by the use of
19801
19802 @smallexample @c ada
19803 pragma Extend_System (AUX_Dec);
19804 @end smallexample
19805
19806 @noindent
19807 are virtually identical to those provided by the DEC Ada 83 package
19808 System. One important difference is that the name of the TO_ADDRESS
19809 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19810 See the GNAT Reference manual for a discussion of why this change was
19811 necessary.
19812
19813 @noindent
19814 The version of TO_ADDRESS taking a universal integer argument is in fact
19815 an extension to Ada 83 not strictly compatible with the reference manual.
19816 In GNAT, we are constrained to be exactly compatible with the standard,
19817 and this means we cannot provide this capability. In DEC Ada 83, the
19818 point of this definition is to deal with a call like:
19819
19820 @smallexample @c ada
19821 TO_ADDRESS (16#12777#);
19822 @end smallexample
19823
19824 @noindent
19825 Normally, according to the Ada 83 standard, one would expect this to be
19826 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19827 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19828 definition using universal_integer takes precedence.
19829
19830 In GNAT, since the version with universal_integer cannot be supplied, it is
19831 not possible to be 100% compatible. Since there are many programs using
19832 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19833 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19834 declarations provided in the GNAT version of AUX_Dec are:
19835
19836 @smallexample @c ada
19837 function To_Address (X : Integer) return Address;
19838 pragma Pure_Function (To_Address);
19839
19840 function To_Address_Long (X : Unsigned_Longword) return Address;
19841 pragma Pure_Function (To_Address_Long);
19842 @end smallexample
19843
19844 @noindent
19845 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19846 change the name to TO_ADDRESS_LONG.
19847
19848 @node Tasking and Task-Related Features
19849 @section Tasking and Task-Related Features
19850
19851 @noindent
19852 The concepts relevant to a comparison of tasking on GNAT
19853 and on DEC Ada for OpenVMS Alpha systems are discussed in
19854 the following sections.
19855
19856 For detailed information on concepts related to tasking in
19857 DEC Ada, see the DEC Ada Language Reference Manual and the
19858 relevant run-time reference manual.
19859
19860 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19861 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19862
19863 @noindent
19864 On OpenVMS Alpha systems, each Ada task (except a passive
19865 task) is implemented as a single stream of execution
19866 that is created and managed by the kernel. On these
19867 systems, DEC Ada tasking support is based on DECthreads,
19868 an implementation of the POSIX standard for threads.
19869
19870 Although tasks are implemented as threads, all tasks in
19871 an Ada program are part of the same process. As a result,
19872 resources such as open files and virtual memory can be
19873 shared easily among tasks. Having all tasks in one process
19874 allows better integration with the programming environment
19875 (the shell and the debugger, for example).
19876
19877 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19878 code that calls DECthreads routines can be used together.
19879 The interaction between Ada tasks and DECthreads routines
19880 can have some benefits. For example when on OpenVMS Alpha,
19881 DEC Ada can call C code that is already threaded.
19882 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19883 and Ada tasks are mapped to threads.
19884
19885 @menu
19886 * Assigning Task IDs::
19887 * Task IDs and Delays::
19888 * Task-Related Pragmas::
19889 * Scheduling and Task Priority::
19890 * The Task Stack::
19891 * External Interrupts::
19892 @end menu
19893
19894 @node Assigning Task IDs
19895 @subsection Assigning Task IDs
19896
19897 @noindent
19898 The DEC Ada Run-Time Library always assigns %TASK 1 to
19899 the environment task that executes the main program. On
19900 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19901 that have been created but are not yet activated.
19902
19903 On OpenVMS Alpha systems, task IDs are assigned at
19904 activation. On GNAT systems, task IDs are also assigned at
19905 task creation but do not have the same form or values as
19906 task ID values in DEC Ada. There is no null task, and the
19907 environment task does not have a specific task ID value.
19908
19909 @node Task IDs and Delays
19910 @subsection Task IDs and Delays
19911
19912 @noindent
19913 On OpenVMS Alpha systems, tasking delays are implemented
19914 using Timer System Services. The Task ID is used for the
19915 identification of the timer request (the REQIDT parameter).
19916 If Timers are used in the application take care not to use
19917 0 for the identification, because cancelling such a timer
19918 will cancel all timers and may lead to unpredictable results.
19919
19920 @node Task-Related Pragmas
19921 @subsection Task-Related Pragmas
19922
19923 @noindent
19924 Ada supplies the pragma TASK_STORAGE, which allows
19925 specification of the size of the guard area for a task
19926 stack. (The guard area forms an area of memory that has no
19927 read or write access and thus helps in the detection of
19928 stack overflow.) On OpenVMS Alpha systems, if the pragma
19929 TASK_STORAGE specifies a value of zero, a minimal guard
19930 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19931 area is created.
19932
19933 GNAT supplies the following task-related pragmas:
19934
19935 @itemize @bullet
19936 @item  TASK_INFO
19937
19938               This pragma appears within a task definition and
19939               applies to the task in which it appears. The argument
19940               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19941
19942 @item  TASK_STORAGE
19943
19944               GNAT implements pragma TASK_STORAGE in the same way as
19945               DEC Ada.
19946               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19947               SUPPRESS, and VOLATILE.
19948 @end itemize
19949 @node Scheduling and Task Priority
19950 @subsection Scheduling and Task Priority
19951
19952 @noindent
19953 DEC Ada implements the Ada language requirement that
19954 when two tasks are eligible for execution and they have
19955 different priorities, the lower priority task does not
19956 execute while the higher priority task is waiting. The DEC
19957 Ada Run-Time Library keeps a task running until either the
19958 task is suspended or a higher priority task becomes ready.
19959
19960 On OpenVMS Alpha systems, the default strategy is round-
19961 robin with preemption. Tasks of equal priority take turns
19962 at the processor. A task is run for a certain period of
19963 time and then placed at the rear of the ready queue for
19964 its priority level.
19965
19966 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19967 which can be used to enable or disable round-robin
19968 scheduling of tasks with the same priority.
19969 See the relevant DEC Ada run-time reference manual for
19970 information on using the pragmas to control DEC Ada task
19971 scheduling.
19972
19973 GNAT follows the scheduling rules of Annex D (real-time
19974 Annex) of the Ada 95 Reference Manual. In general, this
19975 scheduling strategy is fully compatible with DEC Ada
19976 although it provides some additional constraints (as
19977 fully documented in Annex D).
19978 GNAT implements time slicing control in a manner compatible with
19979 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19980 to the DEC Ada 83 pragma of the same name.
19981 Note that it is not possible to mix GNAT tasking and
19982 DEC Ada 83 tasking in the same program, since the two run times are
19983 not compatible.
19984
19985 @node The Task Stack
19986 @subsection The Task Stack
19987
19988 @noindent
19989 In DEC Ada, a task stack is allocated each time a
19990 non passive task is activated. As soon as the task is
19991 terminated, the storage for the task stack is deallocated.
19992 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19993 a default stack size is used. Also, regardless of the size
19994 specified, some additional space is allocated for task
19995 management purposes. On OpenVMS Alpha systems, at least
19996 one page is allocated.
19997
19998 GNAT handles task stacks in a similar manner. According to
19999 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20000 an alternative method for controlling the task stack size.
20001 The specification of the attribute T'STORAGE_SIZE is also
20002 supported in a manner compatible with DEC Ada.
20003
20004 @node External Interrupts
20005 @subsection External Interrupts
20006
20007 @noindent
20008 On DEC Ada, external interrupts can be associated with task entries.
20009 GNAT is compatible with DEC Ada in its handling of external interrupts.
20010
20011 @node Pragmas and Pragma-Related Features
20012 @section Pragmas and Pragma-Related Features
20013
20014 @noindent
20015 Both DEC Ada and GNAT supply all language-defined pragmas
20016 as specified by the Ada 83 standard. GNAT also supplies all
20017 language-defined pragmas specified in the Ada 95 Reference Manual.
20018 In addition, GNAT implements the implementation-defined pragmas
20019 from DEC Ada 83.
20020
20021 @itemize @bullet
20022 @item  AST_ENTRY
20023
20024 @item  COMMON_OBJECT
20025
20026 @item  COMPONENT_ALIGNMENT
20027
20028 @item  EXPORT_EXCEPTION
20029
20030 @item  EXPORT_FUNCTION
20031
20032 @item  EXPORT_OBJECT
20033
20034 @item  EXPORT_PROCEDURE
20035
20036 @item  EXPORT_VALUED_PROCEDURE
20037
20038 @item  FLOAT_REPRESENTATION
20039
20040 @item  IDENT
20041
20042 @item  IMPORT_EXCEPTION
20043
20044 @item  IMPORT_FUNCTION
20045
20046 @item  IMPORT_OBJECT
20047
20048 @item  IMPORT_PROCEDURE
20049
20050 @item  IMPORT_VALUED_PROCEDURE
20051
20052 @item  INLINE_GENERIC
20053
20054 @item  INTERFACE_NAME
20055
20056 @item  LONG_FLOAT
20057
20058 @item  MAIN_STORAGE
20059
20060 @item  PASSIVE
20061
20062 @item  PSET_OBJECT
20063
20064 @item  SHARE_GENERIC
20065
20066 @item  SUPPRESS_ALL
20067
20068 @item  TASK_STORAGE
20069
20070 @item  TIME_SLICE
20071
20072 @item  TITLE
20073 @end itemize
20074
20075 @noindent
20076 These pragmas are all fully implemented, with the exception of @code{Title},
20077 @code{Passive}, and @code{Share_Generic}, which are
20078 recognized, but which have no
20079 effect in GNAT. The effect of @code{Passive} may be obtained by the
20080 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20081
20082 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20083 a separate subprogram specification which must appear before the
20084 subprogram body.
20085
20086 GNAT also supplies a number of implementation-defined pragmas as follows:
20087 @itemize @bullet
20088 @item  C_PASS_BY_COPY
20089
20090 @item  EXTEND_SYSTEM
20091
20092 @item  SOURCE_FILE_NAME
20093
20094 @item  UNSUPPRESS
20095
20096 @item  WARNINGS
20097
20098 @item  ABORT_DEFER
20099
20100 @item  ADA_83
20101
20102 @item  ADA_95
20103
20104 @item  ANNOTATE
20105
20106 @item  ASSERT
20107
20108 @item  CPP_CLASS
20109
20110 @item  CPP_CONSTRUCTOR
20111
20112 @item  CPP_DESTRUCTOR
20113
20114 @item  CPP_VIRTUAL
20115
20116 @item  CP_VTABLE
20117
20118 @item  DEBUG
20119
20120 @item  LINKER_ALIAS
20121
20122 @item  LINKER_SECTION
20123
20124 @item  MACHINE_ATTRIBUTE
20125
20126 @item  NO_RETURN
20127
20128 @item  PURE_FUNCTION
20129
20130 @item  SOURCE_REFERENCE
20131
20132 @item  TASK_INFO
20133
20134 @item  UNCHECKED_UNION
20135
20136 @item  UNIMPLEMENTED_UNIT
20137
20138 @item  UNIVERSAL_DATA
20139
20140 @item  WEAK_EXTERNAL
20141 @end itemize
20142
20143 @noindent
20144 For full details on these GNAT implementation-defined pragmas, see
20145 the GNAT Reference Manual.
20146
20147 @menu
20148 * Restrictions on the Pragma INLINE::
20149 * Restrictions on the Pragma INTERFACE::
20150 * Restrictions on the Pragma SYSTEM_NAME::
20151 @end menu
20152
20153 @node Restrictions on the Pragma INLINE
20154 @subsection Restrictions on the Pragma INLINE
20155
20156 @noindent
20157 DEC Ada applies the following restrictions to the pragma INLINE:
20158 @itemize @bullet
20159 @item  Parameters cannot be a task type.
20160
20161 @item  Function results cannot be task types, unconstrained
20162 array types, or unconstrained types with discriminants.
20163
20164 @item  Bodies cannot declare the following:
20165 @itemize @bullet
20166 @item  Subprogram body or stub (imported subprogram is allowed)
20167
20168 @item  Tasks
20169
20170 @item  Generic declarations
20171
20172 @item  Instantiations
20173
20174 @item  Exceptions
20175
20176 @item  Access types (types derived from access types allowed)
20177
20178 @item  Array or record types
20179
20180 @item  Dependent tasks
20181
20182 @item  Direct recursive calls of subprogram or containing
20183 subprogram, directly or via a renaming
20184
20185 @end itemize
20186 @end itemize
20187
20188 @noindent
20189 In GNAT, the only restriction on pragma INLINE is that the
20190 body must occur before the call if both are in the same
20191 unit, and the size must be appropriately small. There are
20192 no other specific restrictions which cause subprograms to
20193 be incapable of being inlined.
20194
20195 @node  Restrictions on the Pragma INTERFACE
20196 @subsection  Restrictions on the Pragma INTERFACE
20197
20198 @noindent
20199 The following lists and describes the restrictions on the
20200 pragma INTERFACE on DEC Ada and GNAT:
20201 @itemize @bullet
20202 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20203 Default is the default on OpenVMS Alpha systems.
20204
20205 @item  Parameter passing: Language specifies default
20206 mechanisms but can be overridden with an EXPORT pragma.
20207
20208 @itemize @bullet
20209 @item  Ada: Use internal Ada rules.
20210
20211 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20212 record or task type. Result cannot be a string, an
20213 array, or a record.
20214
20215 @item  Fortran: Parameters cannot be a task. Result cannot
20216 be a string, an array, or a record.
20217 @end itemize
20218 @end itemize
20219
20220 @noindent
20221 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20222 record parameters for all languages.
20223
20224 @node  Restrictions on the Pragma SYSTEM_NAME
20225 @subsection  Restrictions on the Pragma SYSTEM_NAME
20226
20227 @noindent
20228 For DEC Ada for OpenVMS Alpha, the enumeration literal
20229 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20230 literal for the type NAME is SYSTEM_NAME_GNAT.
20231
20232 @node  Library of Predefined Units
20233 @section  Library of Predefined Units
20234
20235 @noindent
20236 A library of predefined units is provided as part of the
20237 DEC Ada and GNAT implementations. DEC Ada does not provide
20238 the package MACHINE_CODE but instead recommends importing
20239 assembler code.
20240
20241 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20242 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20243 version. During GNAT installation, the DEC Ada Predefined
20244 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20245 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20246 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20247 for details.
20248
20249 The GNAT RTL is contained in
20250 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20251 the default search path is set up to find DECLIB units in preference
20252 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20253 for example).
20254
20255 However, it is possible to change the default so that the
20256 reverse is true, or even to mix them using child package
20257 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20258 is the package name, and the Ada units are available in the
20259 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20260 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20261 appropriately. For example, to change the default to use the Ada95
20262 versions do:
20263
20264 @smallexample
20265 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20266                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20267 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20268                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20269 @end smallexample
20270
20271 @menu
20272 * Changes to DECLIB::
20273 @end menu
20274
20275 @node Changes to DECLIB
20276 @subsection Changes to DECLIB
20277
20278 @noindent
20279 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20280 compatibility are minor and include the following:
20281
20282 @itemize @bullet
20283 @item  Adjusting the location of pragmas and record representation
20284 clauses to obey Ada 95 rules
20285
20286 @item  Adding the proper notation to generic formal parameters
20287 that take unconstrained types in instantiation
20288
20289 @item  Adding pragma ELABORATE_BODY to package specifications
20290 that have package bodies not otherwise allowed
20291
20292 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20293 @code{"PROTECTD"}.
20294 Currently these are found only in the STARLET package spec.
20295 @end itemize
20296
20297 @noindent
20298 None of the above changes is visible to users.
20299
20300 @node Bindings
20301 @section Bindings
20302
20303 @noindent
20304 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20305 @itemize @bullet
20306
20307 @item  Command Language Interpreter (CLI interface)
20308
20309 @item  DECtalk Run-Time Library (DTK interface)
20310
20311 @item  Librarian utility routines (LBR interface)
20312
20313 @item  General Purpose Run-Time Library (LIB interface)
20314
20315 @item  Math Run-Time Library (MTH interface)
20316
20317 @item  National Character Set Run-Time Library (NCS interface)
20318
20319 @item  Compiled Code Support Run-Time Library (OTS interface)
20320
20321 @item  Parallel Processing Run-Time Library (PPL interface)
20322
20323 @item  Screen Management Run-Time Library (SMG interface)
20324
20325 @item  Sort Run-Time Library (SOR interface)
20326
20327 @item  String Run-Time Library (STR interface)
20328
20329 @item STARLET System Library
20330 @findex Starlet
20331
20332 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20333
20334 @item  X Windows Toolkit (XT interface)
20335
20336 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20337 @end itemize
20338
20339 @noindent
20340 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20341
20342 The X/Motif bindings used to build DECLIB are whatever versions are in the
20343 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20344 The build script will
20345 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20346 and @code{X_Lib}
20347 causing the default X/Motif sharable image libraries to be linked in. This
20348 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20349 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20350
20351 It may be necessary to edit these options files to update or correct the
20352 library names if, for example, the newer X/Motif bindings from
20353 @file{ADA$EXAMPLES}
20354 had been (previous to installing GNAT) copied and renamed to supersede the
20355 default @file{ADA$PREDEFINED} versions.
20356
20357 @menu
20358 * Shared Libraries and Options Files::
20359 * Interfaces to C::
20360 @end menu
20361
20362 @node Shared Libraries and Options Files
20363 @subsection Shared Libraries and Options Files
20364
20365 @noindent
20366 When using the DEC Ada
20367 predefined X and Motif bindings, the linking with their sharable images is
20368 done automatically by @command{GNAT LINK}.
20369 When using other X and Motif bindings, you need
20370 to add the corresponding sharable images to the command line for
20371 @code{GNAT LINK}. When linking with shared libraries, or with
20372 @file{.OPT} files, you must
20373 also add them to the command line for @command{GNAT LINK}.
20374
20375 A shared library to be used with GNAT is built in the same way as other
20376 libraries under VMS. The VMS Link command can be used in standard fashion.
20377
20378 @node Interfaces to C
20379 @subsection Interfaces to C
20380
20381 @noindent
20382 DEC Ada
20383 provides the following Ada types and operations:
20384
20385 @itemize @bullet
20386 @item C types package (C_TYPES)
20387
20388 @item C strings (C_TYPES.NULL_TERMINATED)
20389
20390 @item Other_types (SHORT_INT)
20391 @end itemize
20392
20393 @noindent
20394 Interfacing to C with GNAT, one can use the above approach
20395 described for DEC Ada or the facilities of Annex B of
20396 the Ada 95 Reference Manual (packages INTERFACES.C,
20397 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20398 information, see the section ``Interfacing to C'' in the
20399 @cite{GNAT Reference Manual}.
20400
20401 The @option{-gnatF} qualifier forces default and explicit
20402 @code{External_Name} parameters in pragmas Import and Export
20403 to be uppercased for compatibility with the default behavior
20404 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20405
20406 @node Main Program Definition
20407 @section Main Program Definition
20408
20409 @noindent
20410 The following section discusses differences in the
20411 definition of main programs on DEC Ada and GNAT.
20412 On DEC Ada, main programs are defined to meet the
20413 following conditions:
20414 @itemize @bullet
20415 @item  Procedure with no formal parameters (returns 0 upon
20416        normal completion)
20417
20418 @item  Procedure with no formal parameters (returns 42 when
20419        unhandled exceptions are raised)
20420
20421 @item  Function with no formal parameters whose returned value
20422        is of a discrete type
20423
20424 @item  Procedure with one OUT formal of a discrete type for
20425        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20426
20427 @end itemize
20428
20429 @noindent
20430 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20431 a main function or main procedure returns a discrete
20432 value whose size is less than 64 bits (32 on VAX systems),
20433 the value is zero- or sign-extended as appropriate.
20434 On GNAT, main programs are defined as follows:
20435 @itemize @bullet
20436 @item  Must be a non-generic, parameter-less subprogram that
20437 is either a procedure or function returning an Ada
20438 STANDARD.INTEGER (the predefined type)
20439
20440 @item  Cannot be a generic subprogram or an instantiation of a
20441 generic subprogram
20442 @end itemize
20443
20444 @node Implementation-Defined Attributes
20445 @section Implementation-Defined Attributes
20446
20447 @noindent
20448 GNAT provides all DEC Ada implementation-defined
20449 attributes.
20450
20451 @node Compiler and Run-Time Interfacing
20452 @section Compiler and Run-Time Interfacing
20453
20454 @noindent
20455 DEC Ada provides the following ways to pass options to the linker
20456 (ACS LINK):
20457 @itemize @bullet
20458 @item  /WAIT and /SUBMIT qualifiers
20459
20460 @item  /COMMAND qualifier
20461
20462 @item  /[NO]MAP qualifier
20463
20464 @item  /OUTPUT=file-spec
20465
20466 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20467 @end itemize
20468
20469 @noindent
20470 To pass options to the linker, GNAT provides the following
20471 switches:
20472
20473 @itemize @bullet
20474 @item   @option{/EXECUTABLE=exec-name}
20475
20476 @item   @option{/VERBOSE qualifier}
20477
20478 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20479 @end itemize
20480
20481 @noindent
20482 For more information on these switches, see
20483 @ref{Switches for gnatlink}.
20484 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20485 to control optimization. DEC Ada also supplies the
20486 following pragmas:
20487 @itemize @bullet
20488 @item  @code{OPTIMIZE}
20489
20490 @item  @code{INLINE}
20491
20492 @item  @code{INLINE_GENERIC}
20493
20494 @item  @code{SUPPRESS_ALL}
20495
20496 @item  @code{PASSIVE}
20497 @end itemize
20498
20499 @noindent
20500 In GNAT, optimization is controlled strictly by command
20501 line parameters, as described in the corresponding section of this guide.
20502 The DIGITAL pragmas for control of optimization are
20503 recognized but ignored.
20504
20505 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20506 the default is that optimization is turned on.
20507
20508 @node Program Compilation and Library Management
20509 @section Program Compilation and Library Management
20510
20511 @noindent
20512 DEC Ada and GNAT provide a comparable set of commands to
20513 build programs. DEC Ada also provides a program library,
20514 which is a concept that does not exist on GNAT. Instead,
20515 GNAT provides directories of sources that are compiled as
20516 needed.
20517
20518 The following table summarizes
20519 the DEC Ada commands and provides
20520 equivalent GNAT commands. In this table, some GNAT
20521 equivalents reflect the fact that GNAT does not use the
20522 concept of a program library. Instead, it uses a model
20523 in which collections of source and object files are used
20524 in a manner consistent with other languages like C and
20525 Fortran. Therefore, standard system file commands are used
20526 to manipulate these elements. Those GNAT commands are marked with
20527 an asterisk.
20528 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20529
20530 @need 1500
20531 @multitable @columnfractions .35 .65
20532
20533 @item @emph{DEC Ada Command}
20534 @tab @emph{GNAT Equivalent / Description}
20535
20536 @item @command{ADA}
20537 @tab @command{GNAT COMPILE}@*
20538 Invokes the compiler to compile one or more Ada source files.
20539
20540 @item @command{ACS ATTACH}@*
20541 @tab [No equivalent]@*
20542 Switches control of terminal from current process running the program
20543 library manager.
20544
20545 @item @command{ACS CHECK}
20546 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20547 Forms the execution closure of one
20548 or more compiled units and checks completeness and currency.
20549
20550 @item @command{ACS COMPILE}
20551 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20552 Forms the execution closure of one or
20553 more specified units, checks completeness and currency,
20554 identifies units that have revised source files, compiles same,
20555 and recompiles units that are or will become obsolete.
20556 Also completes incomplete generic instantiations.
20557
20558 @item @command{ACS COPY FOREIGN}
20559 @tab Copy (*)@*
20560 Copies a foreign object file into the program library as a
20561 library unit body.
20562
20563 @item @command{ACS COPY UNIT}
20564 @tab Copy (*)@*
20565 Copies a compiled unit from one program library to another.
20566
20567 @item @command{ACS CREATE LIBRARY}
20568 @tab Create /directory (*)@*
20569 Creates a program library.
20570
20571 @item @command{ACS CREATE SUBLIBRARY}
20572 @tab Create /directory (*)@*
20573 Creates a program sublibrary.
20574
20575 @item @command{ACS DELETE LIBRARY}
20576 @tab @*
20577 Deletes a program library and its contents.
20578
20579 @item @command{ACS DELETE SUBLIBRARY}
20580 @tab @*
20581 Deletes a program sublibrary and its contents.
20582
20583 @item @command{ACS DELETE UNIT}
20584 @tab Delete file (*)@*
20585 On OpenVMS systems, deletes one or more compiled units from
20586 the current program library.
20587
20588 @item @command{ACS DIRECTORY}
20589 @tab Directory (*)@*
20590 On OpenVMS systems, lists units contained in the current
20591 program library.
20592
20593 @item @command{ACS ENTER FOREIGN}
20594 @tab Copy (*)@*
20595 Allows the import of a foreign body as an Ada library
20596 specification and enters a reference to a pointer.
20597
20598 @item @command{ACS ENTER UNIT}
20599 @tab Copy (*)@*
20600 Enters a reference (pointer) from the current program library to
20601 a unit compiled into another program library.
20602
20603 @item @command{ACS EXIT}
20604 @tab [No equivalent]@*
20605 Exits from the program library manager.
20606
20607 @item @command{ACS EXPORT}
20608 @tab Copy (*)@*
20609 Creates an object file that contains system-specific object code
20610 for one or more units. With GNAT, object files can simply be copied
20611 into the desired directory.
20612
20613 @item @command{ACS EXTRACT SOURCE}
20614 @tab Copy (*)@*
20615 Allows access to the copied source file for each Ada compilation unit
20616
20617 @item @command{ACS HELP}
20618 @tab @command{HELP GNAT}@*
20619 Provides online help.
20620
20621 @item @command{ACS LINK}
20622 @tab @command{GNAT LINK}@*
20623 Links an object file containing Ada units into an executable file.
20624
20625 @item @command{ACS LOAD}
20626 @tab Copy (*)@*
20627 Loads (partially compiles) Ada units into the program library.
20628 Allows loading a program from a collection of files into a library
20629 without knowing the relationship among units.
20630
20631 @item @command{ACS MERGE}
20632 @tab Copy (*)@*
20633 Merges into the current program library, one or more units from
20634 another library where they were modified.
20635
20636 @item @command{ACS RECOMPILE}
20637 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20638 Recompiles from   external or copied source files any obsolete
20639 unit in the closure. Also, completes any incomplete generic
20640 instantiations.
20641
20642 @item @command{ACS REENTER}
20643 @tab @command{GNAT MAKE}@*
20644 Reenters current references to units compiled after last entered
20645 with the @command{ACS ENTER UNIT} command.
20646
20647 @item @command{ACS SET LIBRARY}
20648 @tab Set default (*)@*
20649 Defines a program library to be the compilation context as well
20650 as the target library for compiler output and commands in general.
20651
20652 @item @command{ACS SET PRAGMA}
20653 @tab Edit @file{gnat.adc} (*)@*
20654 Redefines specified  values of the library characteristics
20655 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20656 and @code{Float_Representation}.
20657
20658 @item @command{ACS SET SOURCE}
20659 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20660 Defines the source file search list for the @command{ACS COMPILE} command.
20661
20662 @item @command{ACS SHOW LIBRARY}
20663 @tab Directory (*)@*
20664 Lists information about one or more program libraries.
20665
20666 @item @command{ACS SHOW PROGRAM}
20667 @tab [No equivalent]@*
20668 Lists information about the execution closure of one or
20669 more units in the program library.
20670
20671 @item @command{ACS SHOW SOURCE}
20672 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20673 Shows the source file search used when compiling units.
20674
20675 @item @command{ACS SHOW VERSION}
20676 @tab Compile with @option{VERBOSE} option
20677 Displays the version number of the compiler and program library
20678 manager used.
20679
20680 @item @command{ACS SPAWN}
20681 @tab [No equivalent]@*
20682 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20683 command).
20684
20685 @item @command{ACS VERIFY}
20686 @tab [No equivalent]@*
20687 Performs a series of consistency checks on a program library to
20688 determine whether the library structure and library files are in
20689 valid form.
20690 @end multitable
20691
20692 @noindent
20693
20694 @node Input-Output
20695 @section Input-Output
20696
20697 @noindent
20698 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20699 Management Services (RMS) to perform operations on
20700 external files.
20701
20702 @noindent
20703 DEC Ada and GNAT predefine an identical set of input-
20704 output packages. To make the use of the
20705 generic TEXT_IO operations more convenient, DEC Ada
20706 provides predefined library packages that instantiate the
20707 integer and floating-point operations for the predefined
20708 integer and floating-point types as shown in the following table.
20709
20710 @multitable @columnfractions .45 .55
20711 @item @emph{Package Name} @tab Instantiation
20712
20713 @item @code{INTEGER_TEXT_IO}
20714 @tab @code{INTEGER_IO(INTEGER)}
20715
20716 @item @code{SHORT_INTEGER_TEXT_IO}
20717 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20718
20719 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20720 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20721
20722 @item @code{FLOAT_TEXT_IO}
20723 @tab @code{FLOAT_IO(FLOAT)}
20724
20725 @item @code{LONG_FLOAT_TEXT_IO}
20726 @tab @code{FLOAT_IO(LONG_FLOAT)}
20727 @end multitable
20728
20729 @noindent
20730 The DEC Ada predefined packages and their operations
20731 are implemented using OpenVMS Alpha files and input-
20732 output facilities. DEC Ada supports asynchronous input-
20733 output on OpenVMS Alpha. Familiarity with the following is
20734 recommended:
20735 @itemize @bullet
20736 @item  RMS file organizations and access methods
20737
20738 @item  OpenVMS file specifications and directories
20739
20740 @item  OpenVMS File Definition Language (FDL)
20741 @end itemize
20742
20743 @noindent
20744 GNAT provides I/O facilities that are completely
20745 compatible with DEC Ada. The distribution includes the
20746 standard DEC Ada versions of all I/O packages, operating
20747 in a manner compatible with DEC Ada. In particular, the
20748 following packages are by default the DEC Ada (Ada 83)
20749 versions of these packages rather than the renamings
20750 suggested in annex J of the Ada 95 Reference Manual:
20751 @itemize @bullet
20752 @item  @code{TEXT_IO}
20753
20754 @item  @code{SEQUENTIAL_IO}
20755
20756 @item  @code{DIRECT_IO}
20757 @end itemize
20758
20759 @noindent
20760 The use of the standard Ada 95 syntax for child packages (for
20761 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20762 packages, as defined in the Ada 95 Reference Manual.
20763 GNAT provides DIGITAL-compatible predefined instantiations
20764 of the @code{TEXT_IO} packages, and also
20765 provides the standard predefined instantiations required
20766 by the Ada 95 Reference Manual.
20767
20768 For further information on how GNAT interfaces to the file
20769 system or how I/O is implemented in programs written in
20770 mixed languages, see the chapter ``Implementation of the
20771 Standard I/O'' in the @cite{GNAT Reference Manual}.
20772 This chapter covers the following:
20773 @itemize @bullet
20774 @item  Standard I/O packages
20775
20776 @item  @code{FORM} strings
20777
20778 @item  @code{ADA.DIRECT_IO}
20779
20780 @item  @code{ADA.SEQUENTIAL_IO}
20781
20782 @item  @code{ADA.TEXT_IO}
20783
20784 @item  Stream pointer positioning
20785
20786 @item  Reading and writing non-regular files
20787
20788 @item  @code{GET_IMMEDIATE}
20789
20790 @item  Treating @code{TEXT_IO} files as streams
20791
20792 @item  Shared files
20793
20794 @item  Open modes
20795 @end itemize
20796
20797 @node Implementation Limits
20798 @section Implementation Limits
20799
20800 @noindent
20801 The following table lists implementation limits for DEC Ada
20802 and GNAT systems.
20803 @multitable @columnfractions .60 .20 .20
20804 @sp 1
20805 @item  @emph{Compilation Parameter}
20806 @tab   @emph{DEC Ada}
20807 @tab   @emph{GNAT}
20808 @sp 1
20809
20810 @item  In a subprogram or entry  declaration, maximum number of
20811        formal parameters that are of an unconstrained record type
20812 @tab   32
20813 @tab   No set limit
20814 @sp 1
20815
20816 @item  Maximum identifier length (number of characters)
20817 @tab   255
20818 @tab   255
20819 @sp 1
20820
20821 @item  Maximum number of characters in a source line
20822 @tab   255
20823 @tab   255
20824 @sp 1
20825
20826 @item  Maximum collection size   (number of bytes)
20827 @tab   2**31-1
20828 @tab   2**31-1
20829 @sp 1
20830
20831 @item  Maximum number of discriminants for a record type
20832 @tab   245
20833 @tab   No set limit
20834 @sp 1
20835
20836 @item  Maximum number of formal parameters in an entry or
20837        subprogram declaration
20838 @tab   246
20839 @tab    No set limit
20840 @sp 1
20841
20842 @item  Maximum number of dimensions in an array type
20843 @tab   255
20844 @tab   No set limit
20845 @sp 1
20846
20847 @item  Maximum number of library  units and subunits in a compilation.
20848 @tab   4095
20849 @tab   No set limit
20850 @sp 1
20851
20852 @item  Maximum number of library units and subunits in an execution.
20853 @tab   16383
20854 @tab   No set limit
20855 @sp 1
20856
20857 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20858        or @code{PSECT_OBJECT}
20859 @tab   32757
20860 @tab   No set limit
20861 @sp 1
20862
20863 @item  Maximum number of enumeration literals in an enumeration type
20864        definition
20865 @tab   65535
20866 @tab   No set limit
20867 @sp 1
20868
20869 @item  Maximum number of lines in a source file
20870 @tab   65534
20871 @tab   No set limit
20872 @sp 1
20873
20874 @item  Maximum number of bits in any object
20875 @tab   2**31-1
20876 @tab   2**31-1
20877 @sp 1
20878
20879 @item  Maximum size of the static portion of a stack frame (approximate)
20880 @tab   2**31-1
20881 @tab   2**31-1
20882 @end multitable
20883
20884 @node  Tools
20885 @section Tools
20886
20887 @end ifset
20888
20889
20890 @c **************************************
20891 @node Platform-Specific Information for the Run-Time Libraries
20892 @appendix Platform-Specific Information for the Run-Time Libraries
20893 @cindex Tasking and threads libraries
20894 @cindex Threads libraries and tasking
20895 @cindex Run-time libraries (platform-specific information)
20896
20897 @noindent
20898 The GNAT run-time implementation
20899 may vary with respect to both the underlying threads library and
20900 the exception handling scheme.
20901 For threads support, one or more of the following are supplied:
20902 @itemize @bullet
20903 @item @b{native threads library}, a binding to the thread package from
20904 the underlying operating system
20905
20906 @item @b{FSU threads library}, a binding to the Florida State University
20907 threads implementation, which complies fully with the requirements of Annex D
20908
20909 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20910 POSIX thread package
20911 @end itemize
20912
20913 @noindent
20914 For exception handling, either or both of two models are supplied:
20915 @itemize @bullet
20916 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20917 Most programs should experience a substantial speed improvement by
20918 being compiled with a ZCX run-time.
20919 This is especially true for
20920 tasking applications or applications with many exception handlers.}
20921 @cindex Zero-Cost Exceptions
20922 @cindex ZCX (Zero-Cost Exceptions)
20923 which uses binder-generated tables that
20924 are interrogated at run time to locate a handler
20925
20926 @item @b{setjmp / longjmp} (``SJLJ''),
20927 @cindex setjmp/longjmp Exception Model
20928 @cindex SJLJ (setjmp/longjmp Exception Model)
20929 which uses dynamically-set data to establish
20930 the set of handlers
20931 @end itemize
20932
20933 @noindent
20934 This appendix summarizes which combinations of threads and exception support
20935 are supplied on various GNAT platforms.
20936 It then shows how to select a particular library either
20937 permanently or temporarily,
20938 explains the properties of (and tradeoffs among) the various threads
20939 libraries, and provides some additional
20940 information about several specific platforms.
20941
20942 @menu
20943 * Summary of Run-Time Configurations::
20944 * Specifying a Run-Time Library::
20945 * Choosing between Native and FSU Threads Libraries::
20946 * Choosing the Scheduling Policy::
20947 * Solaris-Specific Considerations::
20948 * IRIX-Specific Considerations::
20949 * Linux-Specific Considerations::
20950 * AIX-Specific Considerations::
20951 @end menu
20952
20953
20954 @node Summary of Run-Time Configurations
20955 @section Summary of Run-Time Configurations
20956
20957
20958 @multitable @columnfractions .30 .70
20959 @item @b{alpha-openvms}
20960 @item @code{@ @ }@i{rts-native (default)}
20961 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20962 @item @code{@ @ @ @ }Exceptions @tab ZCX
20963 @*
20964 @item @b{pa-hpux}
20965 @item @code{@ @ }@i{rts-native (default)}
20966 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20967 @item @code{@ @ @ @ }Exceptions @tab ZCX
20968 @*
20969 @item @code{@ @ }@i{rts-sjlj}
20970 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20971 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20972 @*
20973 @item @b{sparc-solaris}  @tab
20974 @item @code{@ @ }@i{rts-native (default)}
20975 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20976 @item @code{@ @ @ @ }Exceptions @tab ZCX
20977 @*
20978 @item @code{@ @ }@i{rts-fsu}    @tab
20979 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20980 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20981 @*
20982 @item @code{@ @ }@i{rts-m64}
20983 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20984 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20985 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20986 @item    @tab Use only on Solaris 8 or later.
20987 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20988 @*
20989 @item @code{@ @ }@i{rts-pthread}
20990 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20991 @item @code{@ @ @ @ }Exceptions @tab ZCX
20992 @*
20993 @item @code{@ @ }@i{rts-sjlj}
20994 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20995 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20996 @*
20997 @item @b{x86-linux}
20998 @item @code{@ @ }@i{rts-native (default)}
20999 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21000 @item @code{@ @ @ @ }Exceptions @tab ZCX
21001 @*
21002 @item @code{@ @ }@i{rts-fsu}
21003 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
21004 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21005 @*
21006 @item @code{@ @ }@i{rts-sjlj}
21007 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21008 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21009 @*
21010 @item @b{x86-windows}
21011 @item @code{@ @ }@i{rts-native (default)}
21012 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21013 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21014 @*
21015 @end multitable
21016
21017
21018
21019 @node Specifying a Run-Time Library
21020 @section Specifying a Run-Time Library
21021
21022 @noindent
21023 The @file{adainclude} subdirectory containing the sources of the GNAT
21024 run-time library, and the @file{adalib} subdirectory containing the
21025 @file{ALI} files and the static and/or shared GNAT library, are located
21026 in the gcc target-dependent area:
21027
21028 @smallexample
21029 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21030 @end smallexample
21031
21032 @noindent
21033 As indicated above, on some platforms several run-time libraries are supplied.
21034 These libraries are installed in the target dependent area and
21035 contain a complete source and binary subdirectory. The detailed description
21036 below explains the differences between the different libraries in terms of
21037 their thread support.
21038
21039 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21040 This default run time is selected by the means of soft links.
21041 For example on x86-linux:
21042
21043 @smallexample
21044 @group
21045  $(target-dir)
21046      |
21047      +--- adainclude----------+
21048      |                        |
21049      +--- adalib-----------+  |
21050      |                     |  |
21051      +--- rts-native       |  |
21052      |    |                |  |
21053      |    +--- adainclude <---+
21054      |    |                |
21055      |    +--- adalib <----+
21056      |
21057      +--- rts-fsu
21058      |    |
21059      |    +--- adainclude
21060      |    |
21061      |    +--- adalib
21062      |
21063      +--- rts-sjlj
21064           |
21065           +--- adainclude
21066           |
21067           +--- adalib
21068 @end group
21069 @end smallexample
21070
21071 @noindent
21072 If the @i{rts-fsu} library is to be selected on a permanent basis,
21073 these soft links can be modified with the following commands:
21074
21075 @smallexample
21076 $ cd $target
21077 $ rm -f adainclude adalib
21078 $ ln -s rts-fsu/adainclude adainclude
21079 $ ln -s rts-fsu/adalib adalib
21080 @end smallexample
21081
21082 @noindent
21083 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21084 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21085 @file{$target/ada_object_path}.
21086
21087 Selecting another run-time library temporarily can be
21088 achieved by the regular mechanism for GNAT object or source path selection:
21089
21090 @itemize @bullet
21091 @item
21092 Set the environment variables:
21093
21094 @smallexample
21095 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21096 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21097 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21098 @end smallexample
21099
21100 @item
21101 Use @option{-aI$target/rts-fsu/adainclude}
21102 and @option{-aO$target/rts-fsu/adalib}
21103 on the @command{gnatmake} command line
21104
21105 @item
21106 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21107 @cindex @option{--RTS} option
21108 @end itemize
21109
21110 @noindent
21111 You can similarly switch to @emph{rts-sjlj}.
21112
21113 @node Choosing between Native and FSU Threads Libraries
21114 @section Choosing between Native and FSU Threads Libraries
21115 @cindex Native threads library
21116 @cindex FSU threads library
21117
21118 @noindent
21119 Some GNAT implementations offer a choice between
21120 native threads and FSU threads.
21121
21122 @itemize @bullet
21123 @item
21124 The @emph{native threads} library correspond to the standard system threads
21125 implementation (e.g. LinuxThreads on GNU/Linux,
21126 @cindex LinuxThreads library
21127 POSIX threads on AIX, or
21128 Solaris threads on Solaris). When this option is chosen, GNAT provides
21129 a full and accurate implementation of the core language tasking model
21130 as described in Chapter 9 of the Ada Reference Manual,
21131 but might not (and probably does not) implement
21132 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21133 @cindex Annex D (Real-Time Systems Annex) compliance
21134 @cindex Real-Time Systems Annex compliance
21135 Indeed, the reason that a choice of libraries is offered
21136 on a given target is because some of the
21137 ACATS tests for @w{Annex D} fail using the native threads library.
21138 As far as possible, this library is implemented
21139 in accordance with Ada semantics (e.g., modifying priorities as required
21140 to simulate ceiling locking),
21141 but there are often slight inaccuracies, most often in the area of
21142 absolutely respecting the priority rules on a single
21143 processor.
21144 Moreover, it is not possible in general to define the exact behavior,
21145 because the native threads implementations
21146 are not well enough documented.
21147
21148 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21149 @cindex POSIX scheduling policies
21150 @cindex @code{SCHED_FIFO} scheduling policy
21151 native threads will provide a behavior very close to the @w{Annex D}
21152 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21153 on some systems (in particular GNU/Linux and Solaris), you need to have root
21154 privileges to use the @code{SCHED_FIFO} policy.
21155
21156 @item
21157 The @emph{FSU threads} library provides a completely accurate implementation
21158 of @w{Annex D}.
21159 Thus, operating with this library, GNAT is 100% compliant with both the core
21160 and all @w{Annex D}
21161 requirements.
21162 The formal validations for implementations offering
21163 a choice of threads packages are always carried out using the FSU
21164 threads option.
21165 @end itemize
21166
21167 @noindent
21168 From these considerations, it might seem that FSU threads are the
21169 better choice,
21170 but that is by no means always the case. The FSU threads package
21171 operates with all Ada tasks appearing to the system to be a single
21172 thread. This is often considerably more efficient than operating
21173 with separate threads, since for example, switching between tasks
21174 can be accomplished without the (in some cases considerable)
21175 overhead of a context switch between two system threads. However,
21176 it means that you may well lose concurrency at the system
21177 level. Notably, some system operations (such as I/O) may block all
21178 tasks in a program and not just the calling task. More
21179 significantly, the FSU threads approach likely means you cannot
21180 take advantage of multiple processors, since for this you need
21181 separate threads (or even separate processes) to operate on
21182 different processors.
21183
21184 For most programs, the native threads library is
21185 usually the better choice. Use the FSU threads if absolute
21186 conformance to @w{Annex D} is important for your application, or if
21187 you find that the improved efficiency of FSU threads is significant to you.
21188
21189 Note also that to take full advantage of Florist and Glade, it is highly
21190 recommended that you use native threads.
21191
21192
21193 @node Choosing the Scheduling Policy
21194 @section Choosing the Scheduling Policy
21195
21196 @noindent
21197 When using a POSIX threads implementation, you have a choice of several
21198 scheduling policies: @code{SCHED_FIFO},
21199 @cindex @code{SCHED_FIFO} scheduling policy
21200 @code{SCHED_RR}
21201 @cindex @code{SCHED_RR} scheduling policy
21202 and @code{SCHED_OTHER}.
21203 @cindex @code{SCHED_OTHER} scheduling policy
21204 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21205 or @code{SCHED_RR} requires special (e.g., root) privileges.
21206
21207 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21208 @code{SCHED_FIFO},
21209 @cindex @code{SCHED_FIFO} scheduling policy
21210 you can use one of the following:
21211
21212 @itemize @bullet
21213 @item
21214 @code{pragma Time_Slice (0.0)}
21215 @cindex pragma Time_Slice
21216 @item
21217 the corresponding binder option @option{-T0}
21218 @cindex @option{-T0} option
21219 @item
21220 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21221 @cindex pragma Task_Dispatching_Policy
21222 @end itemize
21223
21224 @noindent
21225 To specify @code{SCHED_RR},
21226 @cindex @code{SCHED_RR} scheduling policy
21227 you should use @code{pragma Time_Slice} with a
21228 value greater than @code{0.0}, or else use the corresponding @option{-T}
21229 binder option.
21230
21231
21232
21233 @node Solaris-Specific Considerations
21234 @section Solaris-Specific Considerations
21235 @cindex Solaris Sparc threads libraries
21236
21237 @noindent
21238 This section addresses some topics related to the various threads libraries
21239 on Sparc Solaris and then provides some information on building and
21240 debugging 64-bit applications.
21241
21242 @menu
21243 * Solaris Threads Issues::
21244 * Building and Debugging 64-bit Applications::
21245 @end menu
21246
21247
21248 @node Solaris Threads Issues
21249 @subsection Solaris Threads Issues
21250
21251 @noindent
21252 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21253 run-time library based on POSIX threads --- @emph{rts-pthread}.
21254 @cindex rts-pthread threads library
21255 This run-time library has the advantage of being mostly shared across all
21256 POSIX-compliant thread implementations, and it also provides under
21257 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21258 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21259 and @code{PTHREAD_PRIO_PROTECT}
21260 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21261 semantics that can be selected using the predefined pragma
21262 @code{Locking_Policy}
21263 @cindex pragma Locking_Policy (under rts-pthread)
21264 with respectively
21265 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21266 @cindex @code{Inheritance_Locking} (under rts-pthread)
21267 @cindex @code{Ceiling_Locking} (under rts-pthread)
21268
21269 As explained above, the native run-time library is based on the Solaris thread
21270 library (@code{libthread}) and is the default library.
21271 The FSU run-time library is based on the FSU threads.
21272 @cindex FSU threads library
21273
21274 Starting with Solaris 2.5.1, when the Solaris threads library is used
21275 (this is the default), programs
21276 compiled with GNAT can automatically take advantage of
21277 and can thus execute on multiple processors.
21278 The user can alternatively specify a processor on which the program should run
21279 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21280 is made by
21281 setting the environment variable @code{GNAT_PROCESSOR}
21282 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21283 to one of the following:
21284
21285 @table @code
21286 @item -2
21287 Use the default configuration (run the program on all
21288          available processors) - this is the same as having
21289          @code{GNAT_PROCESSOR} unset
21290
21291 @item -1
21292 Let the run-time implementation choose one processor and run the program on
21293          that processor
21294
21295 @item 0 .. Last_Proc
21296 Run the program on the specified processor.
21297   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21298 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21299 @end table
21300
21301
21302 @node Building and Debugging 64-bit Applications
21303 @subsection Building and Debugging 64-bit Applications
21304
21305 @noindent
21306 In a 64-bit application, all the sources involved must be compiled with the
21307 @option{-m64} command-line option, and a specific GNAT library (compiled with
21308 this option) is required.
21309 The easiest way to build a 64bit application is to add
21310 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21311
21312 To debug these applications, dwarf-2 debug information is required, so you
21313 have to add @option{-gdwarf-2} to your gnatmake arguments.
21314 In addition, a special
21315 version of gdb, called @command{gdb64}, needs to be used.
21316
21317 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21318 amounts to:
21319
21320 @smallexample
21321      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21322      $ gdb64 hello
21323 @end smallexample
21324
21325
21326
21327 @node IRIX-Specific Considerations
21328 @section IRIX-Specific Considerations
21329 @cindex IRIX thread library
21330
21331 @noindent
21332 On SGI IRIX, the thread library depends on which compiler is used.
21333 The @emph{o32 ABI} compiler comes with a run-time library based on the
21334 user-level @code{athread}
21335 library. Thus kernel-level capabilities such as nonblocking system
21336 calls or time slicing can only be achieved reliably by specifying different
21337 @code{sprocs} via the pragma @code{Task_Info}
21338 @cindex pragma Task_Info (and IRIX threads)
21339 and the
21340 @code{System.Task_Info} package.
21341 @cindex @code{System.Task_Info} package (and IRIX threads)
21342 See the @cite{GNAT Reference Manual} for further information.
21343
21344 The @emph{n32 ABI} compiler comes with a run-time library based on the
21345 kernel POSIX threads and thus does not have the limitations mentioned above.
21346
21347
21348 @node Linux-Specific Considerations
21349 @section Linux-Specific Considerations
21350 @cindex Linux threads libraries
21351
21352 @noindent
21353 The default thread library under GNU/Linux has the following disadvantages
21354 compared to other native thread libraries:
21355
21356 @itemize @bullet
21357 @item The size of the task's stack is limited to 2 megabytes.
21358 @item  The signal model is not POSIX compliant, which means that to send a
21359   signal to the process, you need to send the signal to all threads,
21360   e.g. by using @code{killpg()}.
21361 @end itemize
21362
21363 @node AIX-Specific Considerations
21364 @section AIX-Specific Considerations
21365 @cindex AIX resolver library
21366
21367 @noindent
21368 On AIX, the resolver library initializes some internal structure on
21369 the first call to @code{get*by*} functions, which are used to implement
21370 @code{GNAT.Sockets.Get_Host_By_Name} and
21371 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21372 If such initialization occurs within an Ada task, and the stack size for
21373 the task is the default size, a stack overflow may occur.
21374
21375 To avoid this overflow, the user should either ensure that the first call
21376 to @code{GNAT.Sockets.Get_Host_By_Name} or
21377 @code{GNAT.Sockets.Get_Host_By_Addrss}
21378 occurs in the environment task, or use @code{pragma Storage_Size} to
21379 specify a sufficiently large size for the stack of the task that contains
21380 this call.
21381
21382 @c *******************************
21383 @node Example of Binder Output File
21384 @appendix Example of Binder Output File
21385
21386 @noindent
21387 This Appendix displays the source code for @command{gnatbind}'s output
21388 file generated for a simple ``Hello World'' program.
21389 Comments have been added for clarification purposes.
21390
21391
21392 @smallexample @c adanocomment
21393 @iftex
21394 @leftskip=0cm
21395 @end iftex
21396 --  The package is called Ada_Main unless this name is actually used
21397 --  as a unit name in the partition, in which case some other unique
21398 --  name is used.
21399
21400 with System;
21401 package ada_main is
21402
21403    Elab_Final_Code : Integer;
21404    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21405
21406    --  The main program saves the parameters (argument count,
21407    --  argument values, environment pointer) in global variables
21408    --  for later access by other units including
21409    --  Ada.Command_Line.
21410
21411    gnat_argc : Integer;
21412    gnat_argv : System.Address;
21413    gnat_envp : System.Address;
21414
21415    --  The actual variables are stored in a library routine. This
21416    --  is useful for some shared library situations, where there
21417    --  are problems if variables are not in the library.
21418
21419    pragma Import (C, gnat_argc);
21420    pragma Import (C, gnat_argv);
21421    pragma Import (C, gnat_envp);
21422
21423    --  The exit status is similarly an external location
21424
21425    gnat_exit_status : Integer;
21426    pragma Import (C, gnat_exit_status);
21427
21428    GNAT_Version : constant String :=
21429                     "GNAT Version: 3.15w (20010315)";
21430    pragma Export (C, GNAT_Version, "__gnat_version");
21431
21432    --  This is the generated adafinal routine that performs
21433    --  finalization at the end of execution. In the case where
21434    --  Ada is the main program, this main program makes a call
21435    --  to adafinal at program termination.
21436
21437    procedure adafinal;
21438    pragma Export (C, adafinal, "adafinal");
21439
21440    --  This is the generated adainit routine that performs
21441    --  initialization at the start of execution. In the case
21442    --  where Ada is the main program, this main program makes
21443    --  a call to adainit at program startup.
21444
21445    procedure adainit;
21446    pragma Export (C, adainit, "adainit");
21447
21448    --  This routine is called at the start of execution. It is
21449    --  a dummy routine that is used by the debugger to breakpoint
21450    --  at the start of execution.
21451
21452    procedure Break_Start;
21453    pragma Import (C, Break_Start, "__gnat_break_start");
21454
21455    --  This is the actual generated main program (it would be
21456    --  suppressed if the no main program switch were used). As
21457    --  required by standard system conventions, this program has
21458    --  the external name main.
21459
21460    function main
21461      (argc : Integer;
21462       argv : System.Address;
21463       envp : System.Address)
21464       return Integer;
21465    pragma Export (C, main, "main");
21466
21467    --  The following set of constants give the version
21468    --  identification values for every unit in the bound
21469    --  partition. This identification is computed from all
21470    --  dependent semantic units, and corresponds to the
21471    --  string that would be returned by use of the
21472    --  Body_Version or Version attributes.
21473
21474    type Version_32 is mod 2 ** 32;
21475    u00001 : constant Version_32 := 16#7880BEB3#;
21476    u00002 : constant Version_32 := 16#0D24CBD0#;
21477    u00003 : constant Version_32 := 16#3283DBEB#;
21478    u00004 : constant Version_32 := 16#2359F9ED#;
21479    u00005 : constant Version_32 := 16#664FB847#;
21480    u00006 : constant Version_32 := 16#68E803DF#;
21481    u00007 : constant Version_32 := 16#5572E604#;
21482    u00008 : constant Version_32 := 16#46B173D8#;
21483    u00009 : constant Version_32 := 16#156A40CF#;
21484    u00010 : constant Version_32 := 16#033DABE0#;
21485    u00011 : constant Version_32 := 16#6AB38FEA#;
21486    u00012 : constant Version_32 := 16#22B6217D#;
21487    u00013 : constant Version_32 := 16#68A22947#;
21488    u00014 : constant Version_32 := 16#18CC4A56#;
21489    u00015 : constant Version_32 := 16#08258E1B#;
21490    u00016 : constant Version_32 := 16#367D5222#;
21491    u00017 : constant Version_32 := 16#20C9ECA4#;
21492    u00018 : constant Version_32 := 16#50D32CB6#;
21493    u00019 : constant Version_32 := 16#39A8BB77#;
21494    u00020 : constant Version_32 := 16#5CF8FA2B#;
21495    u00021 : constant Version_32 := 16#2F1EB794#;
21496    u00022 : constant Version_32 := 16#31AB6444#;
21497    u00023 : constant Version_32 := 16#1574B6E9#;
21498    u00024 : constant Version_32 := 16#5109C189#;
21499    u00025 : constant Version_32 := 16#56D770CD#;
21500    u00026 : constant Version_32 := 16#02F9DE3D#;
21501    u00027 : constant Version_32 := 16#08AB6B2C#;
21502    u00028 : constant Version_32 := 16#3FA37670#;
21503    u00029 : constant Version_32 := 16#476457A0#;
21504    u00030 : constant Version_32 := 16#731E1B6E#;
21505    u00031 : constant Version_32 := 16#23C2E789#;
21506    u00032 : constant Version_32 := 16#0F1BD6A1#;
21507    u00033 : constant Version_32 := 16#7C25DE96#;
21508    u00034 : constant Version_32 := 16#39ADFFA2#;
21509    u00035 : constant Version_32 := 16#571DE3E7#;
21510    u00036 : constant Version_32 := 16#5EB646AB#;
21511    u00037 : constant Version_32 := 16#4249379B#;
21512    u00038 : constant Version_32 := 16#0357E00A#;
21513    u00039 : constant Version_32 := 16#3784FB72#;
21514    u00040 : constant Version_32 := 16#2E723019#;
21515    u00041 : constant Version_32 := 16#623358EA#;
21516    u00042 : constant Version_32 := 16#107F9465#;
21517    u00043 : constant Version_32 := 16#6843F68A#;
21518    u00044 : constant Version_32 := 16#63305874#;
21519    u00045 : constant Version_32 := 16#31E56CE1#;
21520    u00046 : constant Version_32 := 16#02917970#;
21521    u00047 : constant Version_32 := 16#6CCBA70E#;
21522    u00048 : constant Version_32 := 16#41CD4204#;
21523    u00049 : constant Version_32 := 16#572E3F58#;
21524    u00050 : constant Version_32 := 16#20729FF5#;
21525    u00051 : constant Version_32 := 16#1D4F93E8#;
21526    u00052 : constant Version_32 := 16#30B2EC3D#;
21527    u00053 : constant Version_32 := 16#34054F96#;
21528    u00054 : constant Version_32 := 16#5A199860#;
21529    u00055 : constant Version_32 := 16#0E7F912B#;
21530    u00056 : constant Version_32 := 16#5760634A#;
21531    u00057 : constant Version_32 := 16#5D851835#;
21532
21533    --  The following Export pragmas export the version numbers
21534    --  with symbolic names ending in B (for body) or S
21535    --  (for spec) so that they can be located in a link. The
21536    --  information provided here is sufficient to track down
21537    --  the exact versions of units used in a given build.
21538
21539    pragma Export (C, u00001, "helloB");
21540    pragma Export (C, u00002, "system__standard_libraryB");
21541    pragma Export (C, u00003, "system__standard_libraryS");
21542    pragma Export (C, u00004, "adaS");
21543    pragma Export (C, u00005, "ada__text_ioB");
21544    pragma Export (C, u00006, "ada__text_ioS");
21545    pragma Export (C, u00007, "ada__exceptionsB");
21546    pragma Export (C, u00008, "ada__exceptionsS");
21547    pragma Export (C, u00009, "gnatS");
21548    pragma Export (C, u00010, "gnat__heap_sort_aB");
21549    pragma Export (C, u00011, "gnat__heap_sort_aS");
21550    pragma Export (C, u00012, "systemS");
21551    pragma Export (C, u00013, "system__exception_tableB");
21552    pragma Export (C, u00014, "system__exception_tableS");
21553    pragma Export (C, u00015, "gnat__htableB");
21554    pragma Export (C, u00016, "gnat__htableS");
21555    pragma Export (C, u00017, "system__exceptionsS");
21556    pragma Export (C, u00018, "system__machine_state_operationsB");
21557    pragma Export (C, u00019, "system__machine_state_operationsS");
21558    pragma Export (C, u00020, "system__machine_codeS");
21559    pragma Export (C, u00021, "system__storage_elementsB");
21560    pragma Export (C, u00022, "system__storage_elementsS");
21561    pragma Export (C, u00023, "system__secondary_stackB");
21562    pragma Export (C, u00024, "system__secondary_stackS");
21563    pragma Export (C, u00025, "system__parametersB");
21564    pragma Export (C, u00026, "system__parametersS");
21565    pragma Export (C, u00027, "system__soft_linksB");
21566    pragma Export (C, u00028, "system__soft_linksS");
21567    pragma Export (C, u00029, "system__stack_checkingB");
21568    pragma Export (C, u00030, "system__stack_checkingS");
21569    pragma Export (C, u00031, "system__tracebackB");
21570    pragma Export (C, u00032, "system__tracebackS");
21571    pragma Export (C, u00033, "ada__streamsS");
21572    pragma Export (C, u00034, "ada__tagsB");
21573    pragma Export (C, u00035, "ada__tagsS");
21574    pragma Export (C, u00036, "system__string_opsB");
21575    pragma Export (C, u00037, "system__string_opsS");
21576    pragma Export (C, u00038, "interfacesS");
21577    pragma Export (C, u00039, "interfaces__c_streamsB");
21578    pragma Export (C, u00040, "interfaces__c_streamsS");
21579    pragma Export (C, u00041, "system__file_ioB");
21580    pragma Export (C, u00042, "system__file_ioS");
21581    pragma Export (C, u00043, "ada__finalizationB");
21582    pragma Export (C, u00044, "ada__finalizationS");
21583    pragma Export (C, u00045, "system__finalization_rootB");
21584    pragma Export (C, u00046, "system__finalization_rootS");
21585    pragma Export (C, u00047, "system__finalization_implementationB");
21586    pragma Export (C, u00048, "system__finalization_implementationS");
21587    pragma Export (C, u00049, "system__string_ops_concat_3B");
21588    pragma Export (C, u00050, "system__string_ops_concat_3S");
21589    pragma Export (C, u00051, "system__stream_attributesB");
21590    pragma Export (C, u00052, "system__stream_attributesS");
21591    pragma Export (C, u00053, "ada__io_exceptionsS");
21592    pragma Export (C, u00054, "system__unsigned_typesS");
21593    pragma Export (C, u00055, "system__file_control_blockS");
21594    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21595    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21596
21597    -- BEGIN ELABORATION ORDER
21598    -- ada (spec)
21599    -- gnat (spec)
21600    -- gnat.heap_sort_a (spec)
21601    -- gnat.heap_sort_a (body)
21602    -- gnat.htable (spec)
21603    -- gnat.htable (body)
21604    -- interfaces (spec)
21605    -- system (spec)
21606    -- system.machine_code (spec)
21607    -- system.parameters (spec)
21608    -- system.parameters (body)
21609    -- interfaces.c_streams (spec)
21610    -- interfaces.c_streams (body)
21611    -- system.standard_library (spec)
21612    -- ada.exceptions (spec)
21613    -- system.exception_table (spec)
21614    -- system.exception_table (body)
21615    -- ada.io_exceptions (spec)
21616    -- system.exceptions (spec)
21617    -- system.storage_elements (spec)
21618    -- system.storage_elements (body)
21619    -- system.machine_state_operations (spec)
21620    -- system.machine_state_operations (body)
21621    -- system.secondary_stack (spec)
21622    -- system.stack_checking (spec)
21623    -- system.soft_links (spec)
21624    -- system.soft_links (body)
21625    -- system.stack_checking (body)
21626    -- system.secondary_stack (body)
21627    -- system.standard_library (body)
21628    -- system.string_ops (spec)
21629    -- system.string_ops (body)
21630    -- ada.tags (spec)
21631    -- ada.tags (body)
21632    -- ada.streams (spec)
21633    -- system.finalization_root (spec)
21634    -- system.finalization_root (body)
21635    -- system.string_ops_concat_3 (spec)
21636    -- system.string_ops_concat_3 (body)
21637    -- system.traceback (spec)
21638    -- system.traceback (body)
21639    -- ada.exceptions (body)
21640    -- system.unsigned_types (spec)
21641    -- system.stream_attributes (spec)
21642    -- system.stream_attributes (body)
21643    -- system.finalization_implementation (spec)
21644    -- system.finalization_implementation (body)
21645    -- ada.finalization (spec)
21646    -- ada.finalization (body)
21647    -- ada.finalization.list_controller (spec)
21648    -- ada.finalization.list_controller (body)
21649    -- system.file_control_block (spec)
21650    -- system.file_io (spec)
21651    -- system.file_io (body)
21652    -- ada.text_io (spec)
21653    -- ada.text_io (body)
21654    -- hello (body)
21655    -- END ELABORATION ORDER
21656
21657 end ada_main;
21658
21659 --  The following source file name pragmas allow the generated file
21660 --  names to be unique for different main programs. They are needed
21661 --  since the package name will always be Ada_Main.
21662
21663 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21664 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21665
21666 --  Generated package body for Ada_Main starts here
21667
21668 package body ada_main is
21669
21670    --  The actual finalization is performed by calling the
21671    --  library routine in System.Standard_Library.Adafinal
21672
21673    procedure Do_Finalize;
21674    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21675
21676    -------------
21677    -- adainit --
21678    -------------
21679
21680 @findex adainit
21681    procedure adainit is
21682
21683       --  These booleans are set to True once the associated unit has
21684       --  been elaborated. It is also used to avoid elaborating the
21685       --  same unit twice.
21686
21687       E040 : Boolean;
21688       pragma Import (Ada, E040, "interfaces__c_streams_E");
21689
21690       E008 : Boolean;
21691       pragma Import (Ada, E008, "ada__exceptions_E");
21692
21693       E014 : Boolean;
21694       pragma Import (Ada, E014, "system__exception_table_E");
21695
21696       E053 : Boolean;
21697       pragma Import (Ada, E053, "ada__io_exceptions_E");
21698
21699       E017 : Boolean;
21700       pragma Import (Ada, E017, "system__exceptions_E");
21701
21702       E024 : Boolean;
21703       pragma Import (Ada, E024, "system__secondary_stack_E");
21704
21705       E030 : Boolean;
21706       pragma Import (Ada, E030, "system__stack_checking_E");
21707
21708       E028 : Boolean;
21709       pragma Import (Ada, E028, "system__soft_links_E");
21710
21711       E035 : Boolean;
21712       pragma Import (Ada, E035, "ada__tags_E");
21713
21714       E033 : Boolean;
21715       pragma Import (Ada, E033, "ada__streams_E");
21716
21717       E046 : Boolean;
21718       pragma Import (Ada, E046, "system__finalization_root_E");
21719
21720       E048 : Boolean;
21721       pragma Import (Ada, E048, "system__finalization_implementation_E");
21722
21723       E044 : Boolean;
21724       pragma Import (Ada, E044, "ada__finalization_E");
21725
21726       E057 : Boolean;
21727       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21728
21729       E055 : Boolean;
21730       pragma Import (Ada, E055, "system__file_control_block_E");
21731
21732       E042 : Boolean;
21733       pragma Import (Ada, E042, "system__file_io_E");
21734
21735       E006 : Boolean;
21736       pragma Import (Ada, E006, "ada__text_io_E");
21737
21738       --  Set_Globals is a library routine that stores away the
21739       --  value of the indicated set of global values in global
21740       --  variables within the library.
21741
21742       procedure Set_Globals
21743         (Main_Priority            : Integer;
21744          Time_Slice_Value         : Integer;
21745          WC_Encoding              : Character;
21746          Locking_Policy           : Character;
21747          Queuing_Policy           : Character;
21748          Task_Dispatching_Policy  : Character;
21749          Adafinal                 : System.Address;
21750          Unreserve_All_Interrupts : Integer;
21751          Exception_Tracebacks     : Integer);
21752 @findex __gnat_set_globals
21753       pragma Import (C, Set_Globals, "__gnat_set_globals");
21754
21755       --  SDP_Table_Build is a library routine used to build the
21756       --  exception tables. See unit Ada.Exceptions in files
21757       --  a-except.ads/adb for full details of how zero cost
21758       --  exception handling works. This procedure, the call to
21759       --  it, and the two following tables are all omitted if the
21760       --  build is in longjmp/setjump exception mode.
21761
21762 @findex SDP_Table_Build
21763 @findex Zero Cost Exceptions
21764       procedure SDP_Table_Build
21765         (SDP_Addresses   : System.Address;
21766          SDP_Count       : Natural;
21767          Elab_Addresses  : System.Address;
21768          Elab_Addr_Count : Natural);
21769       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21770
21771       --  Table of Unit_Exception_Table addresses. Used for zero
21772       --  cost exception handling to build the top level table.
21773
21774       ST : aliased constant array (1 .. 23) of System.Address := (
21775         Hello'UET_Address,
21776         Ada.Text_Io'UET_Address,
21777         Ada.Exceptions'UET_Address,
21778         Gnat.Heap_Sort_A'UET_Address,
21779         System.Exception_Table'UET_Address,
21780         System.Machine_State_Operations'UET_Address,
21781         System.Secondary_Stack'UET_Address,
21782         System.Parameters'UET_Address,
21783         System.Soft_Links'UET_Address,
21784         System.Stack_Checking'UET_Address,
21785         System.Traceback'UET_Address,
21786         Ada.Streams'UET_Address,
21787         Ada.Tags'UET_Address,
21788         System.String_Ops'UET_Address,
21789         Interfaces.C_Streams'UET_Address,
21790         System.File_Io'UET_Address,
21791         Ada.Finalization'UET_Address,
21792         System.Finalization_Root'UET_Address,
21793         System.Finalization_Implementation'UET_Address,
21794         System.String_Ops_Concat_3'UET_Address,
21795         System.Stream_Attributes'UET_Address,
21796         System.File_Control_Block'UET_Address,
21797         Ada.Finalization.List_Controller'UET_Address);
21798
21799       --  Table of addresses of elaboration routines. Used for
21800       --  zero cost exception handling to make sure these
21801       --  addresses are included in the top level procedure
21802       --  address table.
21803
21804       EA : aliased constant array (1 .. 23) of System.Address := (
21805         adainit'Code_Address,
21806         Do_Finalize'Code_Address,
21807         Ada.Exceptions'Elab_Spec'Address,
21808         System.Exceptions'Elab_Spec'Address,
21809         Interfaces.C_Streams'Elab_Spec'Address,
21810         System.Exception_Table'Elab_Body'Address,
21811         Ada.Io_Exceptions'Elab_Spec'Address,
21812         System.Stack_Checking'Elab_Spec'Address,
21813         System.Soft_Links'Elab_Body'Address,
21814         System.Secondary_Stack'Elab_Body'Address,
21815         Ada.Tags'Elab_Spec'Address,
21816         Ada.Tags'Elab_Body'Address,
21817         Ada.Streams'Elab_Spec'Address,
21818         System.Finalization_Root'Elab_Spec'Address,
21819         Ada.Exceptions'Elab_Body'Address,
21820         System.Finalization_Implementation'Elab_Spec'Address,
21821         System.Finalization_Implementation'Elab_Body'Address,
21822         Ada.Finalization'Elab_Spec'Address,
21823         Ada.Finalization.List_Controller'Elab_Spec'Address,
21824         System.File_Control_Block'Elab_Spec'Address,
21825         System.File_Io'Elab_Body'Address,
21826         Ada.Text_Io'Elab_Spec'Address,
21827         Ada.Text_Io'Elab_Body'Address);
21828
21829    --  Start of processing for adainit
21830
21831    begin
21832
21833       --  Call SDP_Table_Build to build the top level procedure
21834       --  table for zero cost exception handling (omitted in
21835       --  longjmp/setjump mode).
21836
21837       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21838
21839       --  Call Set_Globals to record various information for
21840       --  this partition.  The values are derived by the binder
21841       --  from information stored in the ali files by the compiler.
21842
21843 @findex __gnat_set_globals
21844       Set_Globals
21845         (Main_Priority            => -1,
21846          --  Priority of main program, -1 if no pragma Priority used
21847
21848          Time_Slice_Value         => -1,
21849          --  Time slice from Time_Slice pragma, -1 if none used
21850
21851          WC_Encoding              => 'b',
21852          --  Wide_Character encoding used, default is brackets
21853
21854          Locking_Policy           => ' ',
21855          --  Locking_Policy used, default of space means not
21856          --  specified, otherwise it is the first character of
21857          --  the policy name.
21858
21859          Queuing_Policy           => ' ',
21860          --  Queuing_Policy used, default of space means not
21861          --  specified, otherwise it is the first character of
21862          --  the policy name.
21863
21864          Task_Dispatching_Policy  => ' ',
21865          --  Task_Dispatching_Policy used, default of space means
21866          --  not specified, otherwise first character of the
21867          --  policy name.
21868
21869          Adafinal                 => System.Null_Address,
21870          --  Address of Adafinal routine, not used anymore
21871
21872          Unreserve_All_Interrupts => 0,
21873          --  Set true if pragma Unreserve_All_Interrupts was used
21874
21875          Exception_Tracebacks     => 0);
21876          --  Indicates if exception tracebacks are enabled
21877
21878       Elab_Final_Code := 1;
21879
21880       --  Now we have the elaboration calls for all units in the partition.
21881       --  The Elab_Spec and Elab_Body attributes generate references to the
21882       --  implicit elaboration procedures generated by the compiler for
21883       --  each unit that requires elaboration.
21884
21885       if not E040 then
21886          Interfaces.C_Streams'Elab_Spec;
21887       end if;
21888       E040 := True;
21889       if not E008 then
21890          Ada.Exceptions'Elab_Spec;
21891       end if;
21892       if not E014 then
21893          System.Exception_Table'Elab_Body;
21894          E014 := True;
21895       end if;
21896       if not E053 then
21897          Ada.Io_Exceptions'Elab_Spec;
21898          E053 := True;
21899       end if;
21900       if not E017 then
21901          System.Exceptions'Elab_Spec;
21902          E017 := True;
21903       end if;
21904       if not E030 then
21905          System.Stack_Checking'Elab_Spec;
21906       end if;
21907       if not E028 then
21908          System.Soft_Links'Elab_Body;
21909          E028 := True;
21910       end if;
21911       E030 := True;
21912       if not E024 then
21913          System.Secondary_Stack'Elab_Body;
21914          E024 := True;
21915       end if;
21916       if not E035 then
21917          Ada.Tags'Elab_Spec;
21918       end if;
21919       if not E035 then
21920          Ada.Tags'Elab_Body;
21921          E035 := True;
21922       end if;
21923       if not E033 then
21924          Ada.Streams'Elab_Spec;
21925          E033 := True;
21926       end if;
21927       if not E046 then
21928          System.Finalization_Root'Elab_Spec;
21929       end if;
21930       E046 := True;
21931       if not E008 then
21932          Ada.Exceptions'Elab_Body;
21933          E008 := True;
21934       end if;
21935       if not E048 then
21936          System.Finalization_Implementation'Elab_Spec;
21937       end if;
21938       if not E048 then
21939          System.Finalization_Implementation'Elab_Body;
21940          E048 := True;
21941       end if;
21942       if not E044 then
21943          Ada.Finalization'Elab_Spec;
21944       end if;
21945       E044 := True;
21946       if not E057 then
21947          Ada.Finalization.List_Controller'Elab_Spec;
21948       end if;
21949       E057 := True;
21950       if not E055 then
21951          System.File_Control_Block'Elab_Spec;
21952          E055 := True;
21953       end if;
21954       if not E042 then
21955          System.File_Io'Elab_Body;
21956          E042 := True;
21957       end if;
21958       if not E006 then
21959          Ada.Text_Io'Elab_Spec;
21960       end if;
21961       if not E006 then
21962          Ada.Text_Io'Elab_Body;
21963          E006 := True;
21964       end if;
21965
21966       Elab_Final_Code := 0;
21967    end adainit;
21968
21969    --------------
21970    -- adafinal --
21971    --------------
21972
21973 @findex adafinal
21974    procedure adafinal is
21975    begin
21976       Do_Finalize;
21977    end adafinal;
21978
21979    ----------
21980    -- main --
21981    ----------
21982
21983    --  main is actually a function, as in the ANSI C standard,
21984    --  defined to return the exit status. The three parameters
21985    --  are the argument count, argument values and environment
21986    --  pointer.
21987
21988 @findex Main Program
21989    function main
21990      (argc : Integer;
21991       argv : System.Address;
21992       envp : System.Address)
21993       return Integer
21994    is
21995       --  The initialize routine performs low level system
21996       --  initialization using a standard library routine which
21997       --  sets up signal handling and performs any other
21998       --  required setup. The routine can be found in file
21999       --  a-init.c.
22000
22001 @findex __gnat_initialize
22002       procedure initialize;
22003       pragma Import (C, initialize, "__gnat_initialize");
22004
22005       --  The finalize routine performs low level system
22006       --  finalization using a standard library routine. The
22007       --  routine is found in file a-final.c and in the standard
22008       --  distribution is a dummy routine that does nothing, so
22009       --  really this is a hook for special user finalization.
22010
22011 @findex __gnat_finalize
22012       procedure finalize;
22013       pragma Import (C, finalize, "__gnat_finalize");
22014
22015       --  We get to the main program of the partition by using
22016       --  pragma Import because if we try to with the unit and
22017       --  call it Ada style, then not only do we waste time
22018       --  recompiling it, but also, we don't really know the right
22019       --  switches (e.g. identifier character set) to be used
22020       --  to compile it.
22021
22022       procedure Ada_Main_Program;
22023       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22024
22025    --  Start of processing for main
22026
22027    begin
22028       --  Save global variables
22029
22030       gnat_argc := argc;
22031       gnat_argv := argv;
22032       gnat_envp := envp;
22033
22034       --  Call low level system initialization
22035
22036       Initialize;
22037
22038       --  Call our generated Ada initialization routine
22039
22040       adainit;
22041
22042       --  This is the point at which we want the debugger to get
22043       --  control
22044
22045       Break_Start;
22046
22047       --  Now we call the main program of the partition
22048
22049       Ada_Main_Program;
22050
22051       --  Perform Ada finalization
22052
22053       adafinal;
22054
22055       --  Perform low level system finalization
22056
22057       Finalize;
22058
22059       --  Return the proper exit status
22060       return (gnat_exit_status);
22061    end;
22062
22063 --  This section is entirely comments, so it has no effect on the
22064 --  compilation of the Ada_Main package. It provides the list of
22065 --  object files and linker options, as well as some standard
22066 --  libraries needed for the link. The gnatlink utility parses
22067 --  this b~hello.adb file to read these comment lines to generate
22068 --  the appropriate command line arguments for the call to the
22069 --  system linker. The BEGIN/END lines are used for sentinels for
22070 --  this parsing operation.
22071
22072 --  The exact file names will of course depend on the environment,
22073 --  host/target and location of files on the host system.
22074
22075 @findex Object file list
22076 -- BEGIN Object file/option list
22077    --   ./hello.o
22078    --   -L./
22079    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22080    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22081 -- END Object file/option list
22082
22083 end ada_main;
22084 @end smallexample
22085
22086 @noindent
22087 The Ada code in the above example is exactly what is generated by the
22088 binder. We have added comments to more clearly indicate the function
22089 of each part of the generated @code{Ada_Main} package.
22090
22091 The code is standard Ada in all respects, and can be processed by any
22092 tools that handle Ada. In particular, it is possible to use the debugger
22093 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22094 suppose that for reasons that you do not understand, your program is crashing
22095 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22096 you can place a breakpoint on the call:
22097
22098 @smallexample @c ada
22099 Ada.Text_Io'Elab_Body;
22100 @end smallexample
22101
22102 @noindent
22103 and trace the elaboration routine for this package to find out where
22104 the problem might be (more usually of course you would be debugging
22105 elaboration code in your own application).
22106
22107
22108 @node Elaboration Order Handling in GNAT
22109 @appendix Elaboration Order Handling in GNAT
22110 @cindex Order of elaboration
22111 @cindex Elaboration control
22112
22113 @menu
22114 * Elaboration Code in Ada 95::
22115 * Checking the Elaboration Order in Ada 95::
22116 * Controlling the Elaboration Order in Ada 95::
22117 * Controlling Elaboration in GNAT - Internal Calls::
22118 * Controlling Elaboration in GNAT - External Calls::
22119 * Default Behavior in GNAT - Ensuring Safety::
22120 * Treatment of Pragma Elaborate::
22121 * Elaboration Issues for Library Tasks::
22122 * Mixing Elaboration Models::
22123 * What to Do If the Default Elaboration Behavior Fails::
22124 * Elaboration for Access-to-Subprogram Values::
22125 * Summary of Procedures for Elaboration Control::
22126 * Other Elaboration Order Considerations::
22127 @end menu
22128
22129 @noindent
22130 This chapter describes the handling of elaboration code in Ada 95 and
22131 in GNAT, and discusses how the order of elaboration of program units can
22132 be controlled in GNAT, either automatically or with explicit programming
22133 features.
22134
22135 @node Elaboration Code in Ada 95
22136 @section Elaboration Code in Ada 95
22137
22138 @noindent
22139 Ada 95 provides rather general mechanisms for executing code at elaboration
22140 time, that is to say before the main program starts executing. Such code arises
22141 in three contexts:
22142
22143 @table @asis
22144 @item Initializers for variables.
22145 Variables declared at the library level, in package specs or bodies, can
22146 require initialization that is performed at elaboration time, as in:
22147 @smallexample @c ada
22148 @cartouche
22149 Sqrt_Half : Float := Sqrt (0.5);
22150 @end cartouche
22151 @end smallexample
22152
22153 @item Package initialization code
22154 Code in a @code{BEGIN-END} section at the outer level of a package body is
22155 executed as part of the package body elaboration code.
22156
22157 @item Library level task allocators
22158 Tasks that are declared using task allocators at the library level
22159 start executing immediately and hence can execute at elaboration time.
22160 @end table
22161
22162 @noindent
22163 Subprogram calls are possible in any of these contexts, which means that
22164 any arbitrary part of the program may be executed as part of the elaboration
22165 code. It is even possible to write a program which does all its work at
22166 elaboration time, with a null main program, although stylistically this
22167 would usually be considered an inappropriate way to structure
22168 a program.
22169
22170 An important concern arises in the context of elaboration code:
22171 we have to be sure that it is executed in an appropriate order. What we
22172 have is a series of elaboration code sections, potentially one section
22173 for each unit in the program. It is important that these execute
22174 in the correct order. Correctness here means that, taking the above
22175 example of the declaration of @code{Sqrt_Half},
22176 if some other piece of
22177 elaboration code references @code{Sqrt_Half},
22178 then it must run after the
22179 section of elaboration code that contains the declaration of
22180 @code{Sqrt_Half}.
22181
22182 There would never be any order of elaboration problem if we made a rule
22183 that whenever you @code{with} a unit, you must elaborate both the spec and body
22184 of that unit before elaborating the unit doing the @code{with}'ing:
22185
22186 @smallexample @c ada
22187 @group
22188 @cartouche
22189 with Unit_1;
22190 package Unit_2 is ...
22191 @end cartouche
22192 @end group
22193 @end smallexample
22194
22195 @noindent
22196 would require that both the body and spec of @code{Unit_1} be elaborated
22197 before the spec of @code{Unit_2}. However, a rule like that would be far too
22198 restrictive. In particular, it would make it impossible to have routines
22199 in separate packages that were mutually recursive.
22200
22201 You might think that a clever enough compiler could look at the actual
22202 elaboration code and determine an appropriate correct order of elaboration,
22203 but in the general case, this is not possible. Consider the following
22204 example.
22205
22206 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22207 that references
22208 the variable @code{Sqrt_1}, which is declared in the elaboration code
22209 of the body of @code{Unit_1}:
22210
22211 @smallexample @c ada
22212 @cartouche
22213 Sqrt_1 : Float := Sqrt (0.1);
22214 @end cartouche
22215 @end smallexample
22216
22217 @noindent
22218 The elaboration code of the body of @code{Unit_1} also contains:
22219
22220 @smallexample @c ada
22221 @group
22222 @cartouche
22223 if expression_1 = 1 then
22224    Q := Unit_2.Func_2;
22225 end if;
22226 @end cartouche
22227 @end group
22228 @end smallexample
22229
22230 @noindent
22231 @code{Unit_2} is exactly parallel,
22232 it has a procedure @code{Func_2} that references
22233 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22234 the body @code{Unit_2}:
22235
22236 @smallexample @c ada
22237 @cartouche
22238 Sqrt_2 : Float := Sqrt (0.1);
22239 @end cartouche
22240 @end smallexample
22241
22242 @noindent
22243 The elaboration code of the body of @code{Unit_2} also contains:
22244
22245 @smallexample @c ada
22246 @group
22247 @cartouche
22248 if expression_2 = 2 then
22249    Q := Unit_1.Func_1;
22250 end if;
22251 @end cartouche
22252 @end group
22253 @end smallexample
22254
22255 @noindent
22256 Now the question is, which of the following orders of elaboration is
22257 acceptable:
22258
22259 @smallexample
22260 @group
22261 Spec of Unit_1
22262 Spec of Unit_2
22263 Body of Unit_1
22264 Body of Unit_2
22265 @end group
22266 @end smallexample
22267
22268 @noindent
22269 or
22270
22271 @smallexample
22272 @group
22273 Spec of Unit_2
22274 Spec of Unit_1
22275 Body of Unit_2
22276 Body of Unit_1
22277 @end group
22278 @end smallexample
22279
22280 @noindent
22281 If you carefully analyze the flow here, you will see that you cannot tell
22282 at compile time the answer to this question.
22283 If @code{expression_1} is not equal to 1,
22284 and @code{expression_2} is not equal to 2,
22285 then either order is acceptable, because neither of the function calls is
22286 executed. If both tests evaluate to true, then neither order is acceptable
22287 and in fact there is no correct order.
22288
22289 If one of the two expressions is true, and the other is false, then one
22290 of the above orders is correct, and the other is incorrect. For example,
22291 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22292 then the call to @code{Func_2}
22293 will occur, but not the call to @code{Func_1.}
22294 This means that it is essential
22295 to elaborate the body of @code{Unit_1} before
22296 the body of @code{Unit_2}, so the first
22297 order of elaboration is correct and the second is wrong.
22298
22299 By making @code{expression_1} and @code{expression_2}
22300 depend on input data, or perhaps
22301 the time of day, we can make it impossible for the compiler or binder
22302 to figure out which of these expressions will be true, and hence it
22303 is impossible to guarantee a safe order of elaboration at run time.
22304
22305 @node Checking the Elaboration Order in Ada 95
22306 @section Checking the Elaboration Order in Ada 95
22307
22308 @noindent
22309 In some languages that involve the same kind of elaboration problems,
22310 e.g. Java and C++, the programmer is expected to worry about these
22311 ordering problems himself, and it is common to
22312 write a program in which an incorrect elaboration order  gives
22313 surprising results, because it references variables before they
22314 are initialized.
22315 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22316 clearly not sufficient. Consequently, the language provides three lines
22317 of defense:
22318
22319 @table @asis
22320 @item Standard rules
22321 Some standard rules restrict the possible choice of elaboration
22322 order. In particular, if you @code{with} a unit, then its spec is always
22323 elaborated before the unit doing the @code{with}. Similarly, a parent
22324 spec is always elaborated before the child spec, and finally
22325 a spec is always elaborated before its corresponding body.
22326
22327 @item Dynamic elaboration checks
22328 @cindex Elaboration checks
22329 @cindex Checks, elaboration
22330 Dynamic checks are made at run time, so that if some entity is accessed
22331 before it is elaborated (typically  by means of a subprogram call)
22332 then the exception (@code{Program_Error}) is raised.
22333
22334 @item Elaboration control
22335 Facilities are provided for the programmer to specify the desired order
22336 of elaboration.
22337 @end table
22338
22339 Let's look at these facilities in more detail. First, the rules for
22340 dynamic checking. One possible rule would be simply to say that the
22341 exception is raised if you access a variable which has not yet been
22342 elaborated. The trouble with this approach is that it could require
22343 expensive checks on every variable reference. Instead Ada 95 has two
22344 rules which are a little more restrictive, but easier to check, and
22345 easier to state:
22346
22347 @table @asis
22348 @item Restrictions on calls
22349 A subprogram can only be called at elaboration time if its body
22350 has been elaborated. The rules for elaboration given above guarantee
22351 that the spec of the subprogram has been elaborated before the
22352 call, but not the body. If this rule is violated, then the
22353 exception @code{Program_Error} is raised.
22354
22355 @item Restrictions on instantiations
22356 A generic unit can only be instantiated if the body of the generic
22357 unit has been elaborated. Again, the rules for elaboration given above
22358 guarantee that the spec of the generic unit has been elaborated
22359 before the instantiation, but not the body. If this rule is
22360 violated, then the exception @code{Program_Error} is raised.
22361 @end table
22362
22363 @noindent
22364 The idea is that if the body has been elaborated, then any variables
22365 it references must have been elaborated; by checking for the body being
22366 elaborated we guarantee that none of its references causes any
22367 trouble. As we noted above, this is a little too restrictive, because a
22368 subprogram that has no non-local references in its body may in fact be safe
22369 to call. However, it really would be unsafe to rely on this, because
22370 it would mean that the caller was aware of details of the implementation
22371 in the body. This goes against the basic tenets of Ada.
22372
22373 A plausible implementation can be described as follows.
22374 A Boolean variable is associated with each subprogram
22375 and each generic unit. This variable is initialized to False, and is set to
22376 True at the point body is elaborated. Every call or instantiation checks the
22377 variable, and raises @code{Program_Error} if the variable is False.
22378
22379 Note that one might think that it would be good enough to have one Boolean
22380 variable for each package, but that would not deal with cases of trying
22381 to call a body in the same package as the call
22382 that has not been elaborated yet.
22383 Of course a compiler may be able to do enough analysis to optimize away
22384 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22385 does such optimizations, but still the easiest conceptual model is to
22386 think of there being one variable per subprogram.
22387
22388 @node Controlling the Elaboration Order in Ada 95
22389 @section Controlling the Elaboration Order in Ada 95
22390
22391 @noindent
22392 In the previous section we discussed the rules in Ada 95 which ensure
22393 that @code{Program_Error} is raised if an incorrect elaboration order is
22394 chosen. This prevents erroneous executions, but we need mechanisms to
22395 specify a correct execution and avoid the exception altogether.
22396 To achieve this, Ada 95 provides a number of features for controlling
22397 the order of elaboration. We discuss these features in this section.
22398
22399 First, there are several ways of indicating to the compiler that a given
22400 unit has no elaboration problems:
22401
22402 @table @asis
22403 @item packages that do not require a body
22404 In Ada 95, a library package that does not require a body does not permit
22405 a body. This means that if we have a such a package, as in:
22406
22407 @smallexample @c ada
22408 @group
22409 @cartouche
22410 package Definitions is
22411    generic
22412       type m is new integer;
22413    package Subp is
22414       type a is array (1 .. 10) of m;
22415       type b is array (1 .. 20) of m;
22416    end Subp;
22417 end Definitions;
22418 @end cartouche
22419 @end group
22420 @end smallexample
22421
22422 @noindent
22423 A package that @code{with}'s @code{Definitions} may safely instantiate
22424 @code{Definitions.Subp} because the compiler can determine that there
22425 definitely is no package body to worry about in this case
22426
22427 @item pragma Pure
22428 @cindex pragma Pure
22429 @findex Pure
22430 Places sufficient restrictions on a unit to guarantee that
22431 no call to any subprogram in the unit can result in an
22432 elaboration problem. This means that the compiler does not need
22433 to worry about the point of elaboration of such units, and in
22434 particular, does not need to check any calls to any subprograms
22435 in this unit.
22436
22437 @item pragma Preelaborate
22438 @findex Preelaborate
22439 @cindex pragma Preelaborate
22440 This pragma places slightly less stringent restrictions on a unit than
22441 does pragma Pure,
22442 but these restrictions are still sufficient to ensure that there
22443 are no elaboration problems with any calls to the unit.
22444
22445 @item pragma Elaborate_Body
22446 @findex Elaborate_Body
22447 @cindex pragma Elaborate_Body
22448 This pragma requires that the body of a unit be elaborated immediately
22449 after its spec. Suppose a unit @code{A} has such a pragma,
22450 and unit @code{B} does
22451 a @code{with} of unit @code{A}. Recall that the standard rules require
22452 the spec of unit @code{A}
22453 to be elaborated before the @code{with}'ing unit; given the pragma in
22454 @code{A}, we also know that the body of @code{A}
22455 will be elaborated before @code{B}, so
22456 that calls to @code{A} are safe and do not need a check.
22457 @end table
22458
22459 @noindent
22460 Note that,
22461 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22462 the use of
22463 @code{Elaborate_Body} does not guarantee that the program is
22464 free of elaboration problems, because it may not be possible
22465 to satisfy the requested elaboration order.
22466 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22467 If a programmer
22468 marks @code{Unit_1} as @code{Elaborate_Body},
22469 and not @code{Unit_2,} then the order of
22470 elaboration will be:
22471
22472 @smallexample
22473 @group
22474 Spec of Unit_2
22475 Spec of Unit_1
22476 Body of Unit_1
22477 Body of Unit_2
22478 @end group
22479 @end smallexample
22480
22481 @noindent
22482 Now that means that the call to @code{Func_1} in @code{Unit_2}
22483 need not be checked,
22484 it must be safe. But the call to @code{Func_2} in
22485 @code{Unit_1} may still fail if
22486 @code{Expression_1} is equal to 1,
22487 and the programmer must still take
22488 responsibility for this not being the case.
22489
22490 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22491 eliminated, except for calls entirely within a body, which are
22492 in any case fully under programmer control. However, using the pragma
22493 everywhere is not always possible.
22494 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22495 we marked both of them as having pragma @code{Elaborate_Body}, then
22496 clearly there would be no possible elaboration order.
22497
22498 The above pragmas allow a server to guarantee safe use by clients, and
22499 clearly this is the preferable approach. Consequently a good rule in
22500 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22501 and if this is not possible,
22502 mark them as @code{Elaborate_Body} if possible.
22503 As we have seen, there are situations where neither of these
22504 three pragmas can be used.
22505 So we also provide methods for clients to control the
22506 order of elaboration of the servers on which they depend:
22507
22508 @table @asis
22509 @item pragma Elaborate (unit)
22510 @findex Elaborate
22511 @cindex pragma Elaborate
22512 This pragma is placed in the context clause, after a @code{with} clause,
22513 and it requires that the body of the named unit be elaborated before
22514 the unit in which the pragma occurs. The idea is to use this pragma
22515 if the current unit calls at elaboration time, directly or indirectly,
22516 some subprogram in the named unit.
22517
22518 @item pragma Elaborate_All (unit)
22519 @findex Elaborate_All
22520 @cindex pragma Elaborate_All
22521 This is a stronger version of the Elaborate pragma. Consider the
22522 following example:
22523
22524 @smallexample
22525 Unit A @code{with}'s unit B and calls B.Func in elab code
22526 Unit B @code{with}'s unit C, and B.Func calls C.Func
22527 @end smallexample
22528
22529 @noindent
22530 Now if we put a pragma @code{Elaborate (B)}
22531 in unit @code{A}, this ensures that the
22532 body of @code{B} is elaborated before the call, but not the
22533 body of @code{C}, so
22534 the call to @code{C.Func} could still cause @code{Program_Error} to
22535 be raised.
22536
22537 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22538 not only that the body of the named unit be elaborated before the
22539 unit doing the @code{with}, but also the bodies of all units that the
22540 named unit uses, following @code{with} links transitively. For example,
22541 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22542 then it requires
22543 not only that the body of @code{B} be elaborated before @code{A},
22544 but also the
22545 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22546 @end table
22547
22548 @noindent
22549 We are now in a position to give a usage rule in Ada 95 for avoiding
22550 elaboration problems, at least if dynamic dispatching and access to
22551 subprogram values are not used. We will handle these cases separately
22552 later.
22553
22554 The rule is simple. If a unit has elaboration code that can directly or
22555 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22556 a generic unit in a @code{with}'ed unit,
22557 then if the @code{with}'ed unit does not have
22558 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22559 a pragma @code{Elaborate_All}
22560 for the @code{with}'ed unit. By following this rule a client is
22561 assured that calls can be made without risk of an exception.
22562 If this rule is not followed, then a program may be in one of four
22563 states:
22564
22565 @table @asis
22566 @item No order exists
22567 No order of elaboration exists which follows the rules, taking into
22568 account any @code{Elaborate}, @code{Elaborate_All},
22569 or @code{Elaborate_Body} pragmas. In
22570 this case, an Ada 95 compiler must diagnose the situation at bind
22571 time, and refuse to build an executable program.
22572
22573 @item One or more orders exist, all incorrect
22574 One or more acceptable elaboration orders exists, and all of them
22575 generate an elaboration order problem. In this case, the binder
22576 can build an executable program, but @code{Program_Error} will be raised
22577 when the program is run.
22578
22579 @item Several orders exist, some right, some incorrect
22580 One or more acceptable elaboration orders exists, and some of them
22581 work, and some do not. The programmer has not controlled
22582 the order of elaboration, so the binder may or may not pick one of
22583 the correct orders, and the program may or may not raise an
22584 exception when it is run. This is the worst case, because it means
22585 that the program may fail when moved to another compiler, or even
22586 another version of the same compiler.
22587
22588 @item One or more orders exists, all correct
22589 One ore more acceptable elaboration orders exist, and all of them
22590 work. In this case the program runs successfully. This state of
22591 affairs can be guaranteed by following the rule we gave above, but
22592 may be true even if the rule is not followed.
22593 @end table
22594
22595 @noindent
22596 Note that one additional advantage of following our Elaborate_All rule
22597 is that the program continues to stay in the ideal (all orders OK) state
22598 even if maintenance
22599 changes some bodies of some subprograms. Conversely, if a program that does
22600 not follow this rule happens to be safe at some point, this state of affairs
22601 may deteriorate silently as a result of maintenance changes.
22602
22603 You may have noticed that the above discussion did not mention
22604 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22605 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22606 code in the body makes calls to some other unit, so it is still necessary
22607 to use @code{Elaborate_All} on such units.
22608
22609 @node Controlling Elaboration in GNAT - Internal Calls
22610 @section Controlling Elaboration in GNAT - Internal Calls
22611
22612 @noindent
22613 In the case of internal calls, i.e. calls within a single package, the
22614 programmer has full control over the order of elaboration, and it is up
22615 to the programmer to elaborate declarations in an appropriate order. For
22616 example writing:
22617
22618 @smallexample @c ada
22619 @group
22620 @cartouche
22621 function One return Float;
22622
22623 Q : Float := One;
22624
22625 function One return Float is
22626 begin
22627      return 1.0;
22628 end One;
22629 @end cartouche
22630 @end group
22631 @end smallexample
22632
22633 @noindent
22634 will obviously raise @code{Program_Error} at run time, because function
22635 One will be called before its body is elaborated. In this case GNAT will
22636 generate a warning that the call will raise @code{Program_Error}:
22637
22638 @smallexample
22639 @group
22640 @cartouche
22641  1. procedure y is
22642  2.    function One return Float;
22643  3.
22644  4.    Q : Float := One;
22645                     |
22646     >>> warning: cannot call "One" before body is elaborated
22647     >>> warning: Program_Error will be raised at run time
22648
22649  5.
22650  6.    function One return Float is
22651  7.    begin
22652  8.         return 1.0;
22653  9.    end One;
22654 10.
22655 11. begin
22656 12.    null;
22657 13. end;
22658 @end cartouche
22659 @end group
22660 @end smallexample
22661
22662 @noindent
22663 Note that in this particular case, it is likely that the call is safe, because
22664 the function @code{One} does not access any global variables.
22665 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22666 the contents of the body (think about the separate compilation case), so this
22667 is still wrong, as we discussed in the previous sections.
22668
22669 The error is easily corrected by rearranging the declarations so that the
22670 body of One appears before the declaration containing the call
22671 (note that in Ada 95,
22672 declarations can appear in any order, so there is no restriction that
22673 would prevent this reordering, and if we write:
22674
22675 @smallexample @c ada
22676 @group
22677 @cartouche
22678 function One return Float;
22679
22680 function One return Float is
22681 begin
22682      return 1.0;
22683 end One;
22684
22685 Q : Float := One;
22686 @end cartouche
22687 @end group
22688 @end smallexample
22689
22690 @noindent
22691 then all is well, no warning is generated, and no
22692 @code{Program_Error} exception
22693 will be raised.
22694 Things are more complicated when a chain of subprograms is executed:
22695
22696 @smallexample @c ada
22697 @group
22698 @cartouche
22699 function A return Integer;
22700 function B return Integer;
22701 function C return Integer;
22702
22703 function B return Integer is begin return A; end;
22704 function C return Integer is begin return B; end;
22705
22706 X : Integer := C;
22707
22708 function A return Integer is begin return 1; end;
22709 @end cartouche
22710 @end group
22711 @end smallexample
22712
22713 @noindent
22714 Now the call to @code{C}
22715 at elaboration time in the declaration of @code{X} is correct, because
22716 the body of @code{C} is already elaborated,
22717 and the call to @code{B} within the body of
22718 @code{C} is correct, but the call
22719 to @code{A} within the body of @code{B} is incorrect, because the body
22720 of @code{A} has not been elaborated, so @code{Program_Error}
22721 will be raised on the call to @code{A}.
22722 In this case GNAT will generate a
22723 warning that @code{Program_Error} may be
22724 raised at the point of the call. Let's look at the warning:
22725
22726 @smallexample
22727 @group
22728 @cartouche
22729  1. procedure x is
22730  2.    function A return Integer;
22731  3.    function B return Integer;
22732  4.    function C return Integer;
22733  5.
22734  6.    function B return Integer is begin return A; end;
22735                                                     |
22736     >>> warning: call to "A" before body is elaborated may
22737                  raise Program_Error
22738     >>> warning: "B" called at line 7
22739     >>> warning: "C" called at line 9
22740
22741  7.    function C return Integer is begin return B; end;
22742  8.
22743  9.    X : Integer := C;
22744 10.
22745 11.    function A return Integer is begin return 1; end;
22746 12.
22747 13. begin
22748 14.    null;
22749 15. end;
22750 @end cartouche
22751 @end group
22752 @end smallexample
22753
22754 @noindent
22755 Note that the message here says ``may raise'', instead of the direct case,
22756 where the message says ``will be raised''. That's because whether
22757 @code{A} is
22758 actually called depends in general on run-time flow of control.
22759 For example, if the body of @code{B} said
22760
22761 @smallexample @c ada
22762 @group
22763 @cartouche
22764 function B return Integer is
22765 begin
22766    if some-condition-depending-on-input-data then
22767       return A;
22768    else
22769       return 1;
22770    end if;
22771 end B;
22772 @end cartouche
22773 @end group
22774 @end smallexample
22775
22776 @noindent
22777 then we could not know until run time whether the incorrect call to A would
22778 actually occur, so @code{Program_Error} might
22779 or might not be raised. It is possible for a compiler to
22780 do a better job of analyzing bodies, to
22781 determine whether or not @code{Program_Error}
22782 might be raised, but it certainly
22783 couldn't do a perfect job (that would require solving the halting problem
22784 and is provably impossible), and because this is a warning anyway, it does
22785 not seem worth the effort to do the analysis. Cases in which it
22786 would be relevant are rare.
22787
22788 In practice, warnings of either of the forms given
22789 above will usually correspond to
22790 real errors, and should be examined carefully and eliminated.
22791 In the rare case where a warning is bogus, it can be suppressed by any of
22792 the following methods:
22793
22794 @itemize @bullet
22795 @item
22796 Compile with the @option{-gnatws} switch set
22797
22798 @item
22799 Suppress @code{Elaboration_Check} for the called subprogram
22800
22801 @item
22802 Use pragma @code{Warnings_Off} to turn warnings off for the call
22803 @end itemize
22804
22805 @noindent
22806 For the internal elaboration check case,
22807 GNAT by default generates the
22808 necessary run-time checks to ensure
22809 that @code{Program_Error} is raised if any
22810 call fails an elaboration check. Of course this can only happen if a
22811 warning has been issued as described above. The use of pragma
22812 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22813 some of these checks, meaning that it may be possible (but is not
22814 guaranteed) for a program to be able to call a subprogram whose body
22815 is not yet elaborated, without raising a @code{Program_Error} exception.
22816
22817 @node Controlling Elaboration in GNAT - External Calls
22818 @section Controlling Elaboration in GNAT - External Calls
22819
22820 @noindent
22821 The previous section discussed the case in which the execution of a
22822 particular thread of elaboration code occurred entirely within a
22823 single unit. This is the easy case to handle, because a programmer
22824 has direct and total control over the order of elaboration, and
22825 furthermore, checks need only be generated in cases which are rare
22826 and which the compiler can easily detect.
22827 The situation is more complex when separate compilation is taken into account.
22828 Consider the following:
22829
22830 @smallexample @c ada
22831 @cartouche
22832 @group
22833 package Math is
22834    function Sqrt (Arg : Float) return Float;
22835 end Math;
22836
22837 package body Math is
22838    function Sqrt (Arg : Float) return Float is
22839    begin
22840          ...
22841    end Sqrt;
22842 end Math;
22843 @end group
22844 @group
22845 with Math;
22846 package Stuff is
22847    X : Float := Math.Sqrt (0.5);
22848 end Stuff;
22849
22850 with Stuff;
22851 procedure Main is
22852 begin
22853    ...
22854 end Main;
22855 @end group
22856 @end cartouche
22857 @end smallexample
22858
22859 @noindent
22860 where @code{Main} is the main program. When this program is executed, the
22861 elaboration code must first be executed, and one of the jobs of the
22862 binder is to determine the order in which the units of a program are
22863 to be elaborated. In this case we have four units: the spec and body
22864 of @code{Math},
22865 the spec of @code{Stuff} and the body of @code{Main}).
22866 In what order should the four separate sections of elaboration code
22867 be executed?
22868
22869 There are some restrictions in the order of elaboration that the binder
22870 can choose. In particular, if unit U has a @code{with}
22871 for a package @code{X}, then you
22872 are assured that the spec of @code{X}
22873 is elaborated before U , but you are
22874 not assured that the body of @code{X}
22875 is elaborated before U.
22876 This means that in the above case, the binder is allowed to choose the
22877 order:
22878
22879 @smallexample
22880 spec of Math
22881 spec of Stuff
22882 body of Math
22883 body of Main
22884 @end smallexample
22885
22886 @noindent
22887 but that's not good, because now the call to @code{Math.Sqrt}
22888 that happens during
22889 the elaboration of the @code{Stuff}
22890 spec happens before the body of @code{Math.Sqrt} is
22891 elaborated, and hence causes @code{Program_Error} exception to be raised.
22892 At first glance, one might say that the binder is misbehaving, because
22893 obviously you want to elaborate the body of something you @code{with}
22894 first, but
22895 that is not a general rule that can be followed in all cases. Consider
22896
22897 @smallexample @c ada
22898 @group
22899 @cartouche
22900 package X is ...
22901
22902 package Y is ...
22903
22904 with X;
22905 package body Y is ...
22906
22907 with Y;
22908 package body X is ...
22909 @end cartouche
22910 @end group
22911 @end smallexample
22912
22913 @noindent
22914 This is a common arrangement, and, apart from the order of elaboration
22915 problems that might arise in connection with elaboration code, this works fine.
22916 A rule that says that you must first elaborate the body of anything you
22917 @code{with} cannot work in this case:
22918 the body of @code{X} @code{with}'s @code{Y},
22919 which means you would have to
22920 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22921 which means
22922 you have to elaborate the body of @code{X} first, but ... and we have a
22923 loop that cannot be broken.
22924
22925 It is true that the binder can in many cases guess an order of elaboration
22926 that is unlikely to cause a @code{Program_Error}
22927 exception to be raised, and it tries to do so (in the
22928 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22929 by default
22930 elaborate the body of @code{Math} right after its spec, so all will be well).
22931
22932 However, a program that blindly relies on the binder to be helpful can
22933 get into trouble, as we discussed in the previous sections, so
22934 GNAT
22935 provides a number of facilities for assisting the programmer in
22936 developing programs that are robust with respect to elaboration order.
22937
22938 @node Default Behavior in GNAT - Ensuring Safety
22939 @section Default Behavior in GNAT - Ensuring Safety
22940
22941 @noindent
22942 The default behavior in GNAT ensures elaboration safety. In its
22943 default mode GNAT implements the
22944 rule we previously described as the right approach. Let's restate it:
22945
22946 @itemize
22947 @item
22948 @emph{If a unit has elaboration code that can directly or indirectly make a
22949 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22950 in a @code{with}'ed unit, then if the @code{with}'ed unit
22951 does not have pragma @code{Pure} or
22952 @code{Preelaborate}, then the client should have an
22953 @code{Elaborate_All} for the @code{with}'ed unit.}
22954 @end itemize
22955
22956 @noindent
22957 By following this rule a client is assured that calls and instantiations
22958 can be made without risk of an exception.
22959
22960 In this mode GNAT traces all calls that are potentially made from
22961 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22962 pragmas.
22963 The advantage of this approach is that no elaboration problems
22964 are possible if the binder can find an elaboration order that is
22965 consistent with these implicit @code{Elaborate_All} pragmas. The
22966 disadvantage of this approach is that no such order may exist.
22967
22968 If the binder does not generate any diagnostics, then it means that it
22969 has found an elaboration order that is guaranteed to be safe. However,
22970 the binder may still be relying on implicitly generated
22971 @code{Elaborate_All} pragmas so portability to other compilers than
22972 GNAT is not guaranteed.
22973
22974 If it is important to guarantee portability, then the compilations should
22975 use the
22976 @option{-gnatwl}
22977 (warn on elaboration problems) switch. This will cause warning messages
22978 to be generated indicating the missing @code{Elaborate_All} pragmas.
22979 Consider the following source program:
22980
22981 @smallexample @c ada
22982 @group
22983 @cartouche
22984 with k;
22985 package j is
22986   m : integer := k.r;
22987 end;
22988 @end cartouche
22989 @end group
22990 @end smallexample
22991
22992 @noindent
22993 where it is clear that there
22994 should be a pragma @code{Elaborate_All}
22995 for unit @code{k}. An implicit pragma will be generated, and it is
22996 likely that the binder will be able to honor it. However, if you want
22997 to port this program to some other Ada compiler than GNAT.
22998 it is safer to include the pragma explicitly in the source. If this
22999 unit is compiled with the
23000 @option{-gnatwl}
23001 switch, then the compiler outputs a warning:
23002
23003 @smallexample
23004 @group
23005 @cartouche
23006 1. with k;
23007 2. package j is
23008 3.   m : integer := k.r;
23009                      |
23010    >>> warning: call to "r" may raise Program_Error
23011    >>> warning: missing pragma Elaborate_All for "k"
23012
23013 4. end;
23014 @end cartouche
23015 @end group
23016 @end smallexample
23017
23018 @noindent
23019 and these warnings can be used as a guide for supplying manually
23020 the missing pragmas. It is usually a bad idea to use this warning
23021 option during development. That's because it will warn you when
23022 you need to put in a pragma, but cannot warn you when it is time
23023 to take it out. So the use of pragma Elaborate_All may lead to
23024 unnecessary dependencies and even false circularities.
23025
23026 This default mode is more restrictive than the Ada Reference
23027 Manual, and it is possible to construct programs which will compile
23028 using the dynamic model described there, but will run into a
23029 circularity using the safer static model we have described.
23030
23031 Of course any Ada compiler must be able to operate in a mode
23032 consistent with the requirements of the Ada Reference Manual,
23033 and in particular must have the capability of implementing the
23034 standard dynamic model of elaboration with run-time checks.
23035
23036 In GNAT, this standard mode can be achieved either by the use of
23037 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
23038 command, or by the use of the configuration pragma:
23039
23040 @smallexample @c ada
23041 pragma Elaboration_Checks (RM);
23042 @end smallexample
23043
23044 @noindent
23045 Either approach will cause the unit affected to be compiled using the
23046 standard dynamic run-time elaboration checks described in the Ada
23047 Reference Manual. The static model is generally preferable, since it
23048 is clearly safer to rely on compile and link time checks rather than
23049 run-time checks. However, in the case of legacy code, it may be
23050 difficult to meet the requirements of the static model. This
23051 issue is further discussed in
23052 @ref{What to Do If the Default Elaboration Behavior Fails}.
23053
23054 Note that the static model provides a strict subset of the allowed
23055 behavior and programs of the Ada Reference Manual, so if you do
23056 adhere to the static model and no circularities exist,
23057 then you are assured that your program will
23058 work using the dynamic model, providing that you remove any
23059 pragma Elaborate statements from the source.
23060
23061 @node Treatment of Pragma Elaborate
23062 @section Treatment of Pragma Elaborate
23063 @cindex Pragma Elaborate
23064
23065 @noindent
23066 The use of @code{pragma Elaborate}
23067 should generally be avoided in Ada 95 programs.
23068 The reason for this is that there is no guarantee that transitive calls
23069 will be properly handled. Indeed at one point, this pragma was placed
23070 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23071
23072 Now that's a bit restrictive. In practice, the case in which
23073 @code{pragma Elaborate} is useful is when the caller knows that there
23074 are no transitive calls, or that the called unit contains all necessary
23075 transitive @code{pragma Elaborate} statements, and legacy code often
23076 contains such uses.
23077
23078 Strictly speaking the static mode in GNAT should ignore such pragmas,
23079 since there is no assurance at compile time that the necessary safety
23080 conditions are met. In practice, this would cause GNAT to be incompatible
23081 with correctly written Ada 83 code that had all necessary
23082 @code{pragma Elaborate} statements in place. Consequently, we made the
23083 decision that GNAT in its default mode will believe that if it encounters
23084 a @code{pragma Elaborate} then the programmer knows what they are doing,
23085 and it will trust that no elaboration errors can occur.
23086
23087 The result of this decision is two-fold. First to be safe using the
23088 static mode, you should remove all @code{pragma Elaborate} statements.
23089 Second, when fixing circularities in existing code, you can selectively
23090 use @code{pragma Elaborate} statements to convince the static mode of
23091 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23092 statement.
23093
23094 When using the static mode with @option{-gnatwl}, any use of
23095 @code{pragma Elaborate} will generate a warning about possible
23096 problems.
23097
23098 @node Elaboration Issues for Library Tasks
23099 @section Elaboration Issues for Library Tasks
23100 @cindex Library tasks, elaboration issues
23101 @cindex Elaboration of library tasks
23102
23103 @noindent
23104 In this section we examine special elaboration issues that arise for
23105 programs that declare library level tasks.
23106
23107 Generally the model of execution of an Ada program is that all units are
23108 elaborated, and then execution of the program starts. However, the
23109 declaration of library tasks definitely does not fit this model. The
23110 reason for this is that library tasks start as soon as they are declared
23111 (more precisely, as soon as the statement part of the enclosing package
23112 body is reached), that is to say before elaboration
23113 of the program is complete. This means that if such a task calls a
23114 subprogram, or an entry in another task, the callee may or may not be
23115 elaborated yet, and in the standard
23116 Reference Manual model of dynamic elaboration checks, you can even
23117 get timing dependent Program_Error exceptions, since there can be
23118 a race between the elaboration code and the task code.
23119
23120 The static model of elaboration in GNAT seeks to avoid all such
23121 dynamic behavior, by being conservative, and the conservative
23122 approach in this particular case is to assume that all the code
23123 in a task body is potentially executed at elaboration time if
23124 a task is declared at the library level.
23125
23126 This can definitely result in unexpected circularities. Consider
23127 the following example
23128
23129 @smallexample @c ada
23130 package Decls is
23131   task Lib_Task is
23132      entry Start;
23133   end Lib_Task;
23134
23135   type My_Int is new Integer;
23136
23137   function Ident (M : My_Int) return My_Int;
23138 end Decls;
23139
23140 with Utils;
23141 package body Decls is
23142   task body Lib_Task is
23143   begin
23144      accept Start;
23145      Utils.Put_Val (2);
23146   end Lib_Task;
23147
23148   function Ident (M : My_Int) return My_Int is
23149   begin
23150      return M;
23151   end Ident;
23152 end Decls;
23153
23154 with Decls;
23155 package Utils is
23156   procedure Put_Val (Arg : Decls.My_Int);
23157 end Utils;
23158
23159 with Text_IO;
23160 package body Utils is
23161   procedure Put_Val (Arg : Decls.My_Int) is
23162   begin
23163      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23164   end Put_Val;
23165 end Utils;
23166
23167 with Decls;
23168 procedure Main is
23169 begin
23170    Decls.Lib_Task.Start;
23171 end;
23172 @end smallexample
23173
23174 @noindent
23175 If the above example is compiled in the default static elaboration
23176 mode, then a circularity occurs. The circularity comes from the call
23177 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23178 this call occurs in elaboration code, we need an implicit pragma
23179 @code{Elaborate_All} for @code{Utils}. This means that not only must
23180 the spec and body of @code{Utils} be elaborated before the body
23181 of @code{Decls}, but also the spec and body of any unit that is
23182 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23183 the body of @code{Decls}. This is the transitive implication of
23184 pragma @code{Elaborate_All} and it makes sense, because in general
23185 the body of @code{Put_Val} might have a call to something in a
23186 @code{with'ed} unit.
23187
23188 In this case, the body of Utils (actually its spec) @code{with's}
23189 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23190 must be elaborated before itself, in case there is a call from the
23191 body of @code{Utils}.
23192
23193 Here is the exact chain of events we are worrying about:
23194
23195 @enumerate
23196 @item
23197 In the body of @code{Decls} a call is made from within the body of a library
23198 task to a subprogram in the package @code{Utils}. Since this call may
23199 occur at elaboration time (given that the task is activated at elaboration
23200 time), we have to assume the worst, i.e. that the
23201 call does happen at elaboration time.
23202
23203 @item
23204 This means that the body and spec of @code{Util} must be elaborated before
23205 the body of @code{Decls} so that this call does not cause an access before
23206 elaboration.
23207
23208 @item
23209 Within the body of @code{Util}, specifically within the body of
23210 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23211 by this package.
23212
23213 @item
23214 One such @code{with}'ed package is package @code{Decls}, so there
23215 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23216 In fact there is such a call in this example, but we would have to
23217 assume that there was such a call even if it were not there, since
23218 we are not supposed to write the body of @code{Decls} knowing what
23219 is in the body of @code{Utils}; certainly in the case of the
23220 static elaboration model, the compiler does not know what is in
23221 other bodies and must assume the worst.
23222
23223 @item
23224 This means that the spec and body of @code{Decls} must also be
23225 elaborated before we elaborate the unit containing the call, but
23226 that unit is @code{Decls}! This means that the body of @code{Decls}
23227 must be elaborated before itself, and that's a circularity.
23228 @end enumerate
23229
23230 @noindent
23231 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23232 the body of @code{Decls} you will get a true Ada Reference Manual
23233 circularity that makes the program illegal.
23234
23235 In practice, we have found that problems with the static model of
23236 elaboration in existing code often arise from library tasks, so
23237 we must address this particular situation.
23238
23239 Note that if we compile and run the program above, using the dynamic model of
23240 elaboration (that is to say use the @option{-gnatE} switch),
23241 then it compiles, binds,
23242 links, and runs, printing the expected result of 2. Therefore in some sense
23243 the circularity here is only apparent, and we need to capture
23244 the properties of this program that  distinguish it from other library-level
23245 tasks that have real elaboration problems.
23246
23247 We have four possible answers to this question:
23248
23249 @itemize @bullet
23250
23251 @item
23252 Use the dynamic model of elaboration.
23253
23254 If we use the @option{-gnatE} switch, then as noted above, the program works.
23255 Why is this? If we examine the task body, it is apparent that the task cannot
23256 proceed past the
23257 @code{accept} statement until after elaboration has been completed, because
23258 the corresponding entry call comes from the main program, not earlier.
23259 This is why the dynamic model works here. But that's really giving
23260 up on a precise analysis, and we prefer to take this approach only if we cannot
23261 solve the
23262 problem in any other manner. So let us examine two ways to reorganize
23263 the program to avoid the potential elaboration problem.
23264
23265 @item
23266 Split library tasks into separate packages.
23267
23268 Write separate packages, so that library tasks are isolated from
23269 other declarations as much as possible. Let us look at a variation on
23270 the above program.
23271
23272 @smallexample @c ada
23273 package Decls1 is
23274   task Lib_Task is
23275      entry Start;
23276   end Lib_Task;
23277 end Decls1;
23278
23279 with Utils;
23280 package body Decls1 is
23281   task body Lib_Task is
23282   begin
23283      accept Start;
23284      Utils.Put_Val (2);
23285   end Lib_Task;
23286 end Decls1;
23287
23288 package Decls2 is
23289   type My_Int is new Integer;
23290   function Ident (M : My_Int) return My_Int;
23291 end Decls2;
23292
23293 with Utils;
23294 package body Decls2 is
23295   function Ident (M : My_Int) return My_Int is
23296   begin
23297      return M;
23298   end Ident;
23299 end Decls2;
23300
23301 with Decls2;
23302 package Utils is
23303   procedure Put_Val (Arg : Decls2.My_Int);
23304 end Utils;
23305
23306 with Text_IO;
23307 package body Utils is
23308   procedure Put_Val (Arg : Decls2.My_Int) is
23309   begin
23310      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23311   end Put_Val;
23312 end Utils;
23313
23314 with Decls1;
23315 procedure Main is
23316 begin
23317    Decls1.Lib_Task.Start;
23318 end;
23319 @end smallexample
23320
23321 @noindent
23322 All we have done is to split @code{Decls} into two packages, one
23323 containing the library task, and one containing everything else. Now
23324 there is no cycle, and the program compiles, binds, links and executes
23325 using the default static model of elaboration.
23326
23327 @item
23328 Declare separate task types.
23329
23330 A significant part of the problem arises because of the use of the
23331 single task declaration form. This means that the elaboration of
23332 the task type, and the elaboration of the task itself (i.e. the
23333 creation of the task) happen at the same time. A good rule
23334 of style in Ada 95 is to always create explicit task types. By
23335 following the additional step of placing task objects in separate
23336 packages from the task type declaration, many elaboration problems
23337 are avoided. Here is another modified example of the example program:
23338
23339 @smallexample @c ada
23340 package Decls is
23341   task type Lib_Task_Type is
23342      entry Start;
23343   end Lib_Task_Type;
23344
23345   type My_Int is new Integer;
23346
23347   function Ident (M : My_Int) return My_Int;
23348 end Decls;
23349
23350 with Utils;
23351 package body Decls is
23352   task body Lib_Task_Type is
23353   begin
23354      accept Start;
23355      Utils.Put_Val (2);
23356   end Lib_Task_Type;
23357
23358   function Ident (M : My_Int) return My_Int is
23359   begin
23360      return M;
23361   end Ident;
23362 end Decls;
23363
23364 with Decls;
23365 package Utils is
23366   procedure Put_Val (Arg : Decls.My_Int);
23367 end Utils;
23368
23369 with Text_IO;
23370 package body Utils is
23371   procedure Put_Val (Arg : Decls.My_Int) is
23372   begin
23373      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23374   end Put_Val;
23375 end Utils;
23376
23377 with Decls;
23378 package Declst is
23379    Lib_Task : Decls.Lib_Task_Type;
23380 end Declst;
23381
23382 with Declst;
23383 procedure Main is
23384 begin
23385    Declst.Lib_Task.Start;
23386 end;
23387 @end smallexample
23388
23389 @noindent
23390 What we have done here is to replace the @code{task} declaration in
23391 package @code{Decls} with a @code{task type} declaration. Then we
23392 introduce a separate package @code{Declst} to contain the actual
23393 task object. This separates the elaboration issues for
23394 the @code{task type}
23395 declaration, which causes no trouble, from the elaboration issues
23396 of the task object, which is also unproblematic, since it is now independent
23397 of the elaboration of  @code{Utils}.
23398 This separation of concerns also corresponds to
23399 a generally sound engineering principle of separating declarations
23400 from instances. This version of the program also compiles, binds, links,
23401 and executes, generating the expected output.
23402
23403 @item
23404 Use No_Entry_Calls_In_Elaboration_Code restriction.
23405 @cindex No_Entry_Calls_In_Elaboration_Code
23406
23407 The previous two approaches described how a program can be restructured
23408 to avoid the special problems caused by library task bodies. in practice,
23409 however, such restructuring may be difficult to apply to existing legacy code,
23410 so we must consider solutions that do not require massive rewriting.
23411
23412 Let us consider more carefully why our original sample program works
23413 under the dynamic model of elaboration. The reason is that the code
23414 in the task body blocks immediately on the @code{accept}
23415 statement. Now of course there is nothing to prohibit elaboration
23416 code from making entry calls (for example from another library level task),
23417 so we cannot tell in isolation that
23418 the task will not execute the accept statement  during elaboration.
23419
23420 However, in practice it is very unusual to see elaboration code
23421 make any entry calls, and the pattern of tasks starting
23422 at elaboration time and then immediately blocking on @code{accept} or
23423 @code{select} statements is very common. What this means is that
23424 the compiler is being too pessimistic when it analyzes the
23425 whole package body as though it might be executed at elaboration
23426 time.
23427
23428 If we know that the elaboration code contains no entry calls, (a very safe
23429 assumption most of the time, that could almost be made the default
23430 behavior), then we can compile all units of the program under control
23431 of the following configuration pragma:
23432
23433 @smallexample
23434 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23435 @end smallexample
23436
23437 @noindent
23438 This pragma can be placed in the @file{gnat.adc} file in the usual
23439 manner. If we take our original unmodified program and compile it
23440 in the presence of a @file{gnat.adc} containing the above pragma,
23441 then once again, we can compile, bind, link, and execute, obtaining
23442 the expected result. In the presence of this pragma, the compiler does
23443 not trace calls in a task body, that appear after the first @code{accept}
23444 or @code{select} statement, and therefore does not report a potential
23445 circularity in the original program.
23446
23447 The compiler will check to the extent it can that the above
23448 restriction is not violated, but it is not always possible to do a
23449 complete check at compile time, so it is important to use this
23450 pragma only if the stated restriction is in fact met, that is to say
23451 no task receives an entry call before elaboration of all units is completed.
23452
23453 @end itemize
23454
23455 @node Mixing Elaboration Models
23456 @section Mixing Elaboration Models
23457 @noindent
23458 So far, we have assumed that the entire program is either compiled
23459 using the dynamic model or static model, ensuring consistency. It
23460 is possible to mix the two models, but rules have to be followed
23461 if this mixing is done to ensure that elaboration checks are not
23462 omitted.
23463
23464 The basic rule is that @emph{a unit compiled with the static model cannot
23465 be @code{with'ed} by a unit compiled with the dynamic model}. The
23466 reason for this is that in the static model, a unit assumes that
23467 its clients guarantee to use (the equivalent of) pragma
23468 @code{Elaborate_All} so that no elaboration checks are required
23469 in inner subprograms, and this assumption is violated if the
23470 client is compiled with dynamic checks.
23471
23472 The precise rule is as follows. A unit that is compiled with dynamic
23473 checks can only @code{with} a unit that meets at least one of the
23474 following criteria:
23475
23476 @itemize @bullet
23477
23478 @item
23479 The @code{with'ed} unit is itself compiled with dynamic elaboration
23480 checks (that is with the @option{-gnatE} switch.
23481
23482 @item
23483 The @code{with'ed} unit is an internal GNAT implementation unit from
23484 the System, Interfaces, Ada, or GNAT hierarchies.
23485
23486 @item
23487 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23488
23489 @item
23490 The @code{with'ing} unit (that is the client) has an explicit pragma
23491 @code{Elaborate_All} for the @code{with'ed} unit.
23492
23493 @end itemize
23494
23495 @noindent
23496 If this rule is violated, that is if a unit with dynamic elaboration
23497 checks @code{with's} a unit that does not meet one of the above four
23498 criteria, then the binder (@code{gnatbind}) will issue a warning
23499 similar to that in the following example:
23500
23501 @smallexample
23502 warning: "x.ads" has dynamic elaboration checks and with's
23503 warning:   "y.ads" which has static elaboration checks
23504 @end smallexample
23505
23506 @noindent
23507 These warnings indicate that the rule has been violated, and that as a result
23508 elaboration checks may be missed in the resulting executable file.
23509 This warning may be suppressed using the @option{-ws} binder switch
23510 in the usual manner.
23511
23512 One useful application of this mixing rule is in the case of a subsystem
23513 which does not itself @code{with} units from the remainder of the
23514 application. In this case, the entire subsystem can be compiled with
23515 dynamic checks to resolve a circularity in the subsystem, while
23516 allowing the main application that uses this subsystem to be compiled
23517 using the more reliable default static model.
23518
23519 @node What to Do If the Default Elaboration Behavior Fails
23520 @section What to Do If the Default Elaboration Behavior Fails
23521
23522 @noindent
23523 If the binder cannot find an acceptable order, it outputs detailed
23524 diagnostics. For example:
23525 @smallexample
23526 @group
23527 @iftex
23528 @leftskip=0cm
23529 @end iftex
23530 error: elaboration circularity detected
23531 info:   "proc (body)" must be elaborated before "pack (body)"
23532 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23533 info:     recompile "pack (body)" with -gnatwl
23534 info:                             for full details
23535 info:       "proc (body)"
23536 info:         is needed by its spec:
23537 info:       "proc (spec)"
23538 info:         which is withed by:
23539 info:       "pack (body)"
23540 info:  "pack (body)" must be elaborated before "proc (body)"
23541 info:     reason: pragma Elaborate in unit "proc (body)"
23542 @end group
23543
23544 @end smallexample
23545
23546 @noindent
23547 In this case we have a cycle that the binder cannot break. On the one
23548 hand, there is an explicit pragma Elaborate in @code{proc} for
23549 @code{pack}. This means that the body of @code{pack} must be elaborated
23550 before the body of @code{proc}. On the other hand, there is elaboration
23551 code in @code{pack} that calls a subprogram in @code{proc}. This means
23552 that for maximum safety, there should really be a pragma
23553 Elaborate_All in @code{pack} for @code{proc} which would require that
23554 the body of @code{proc} be elaborated before the body of
23555 @code{pack}. Clearly both requirements cannot be satisfied.
23556 Faced with a circularity of this kind, you have three different options.
23557
23558 @table @asis
23559 @item Fix the program
23560 The most desirable option from the point of view of long-term maintenance
23561 is to rearrange the program so that the elaboration problems are avoided.
23562 One useful technique is to place the elaboration code into separate
23563 child packages. Another is to move some of the initialization code to
23564 explicitly called subprograms, where the program controls the order
23565 of initialization explicitly. Although this is the most desirable option,
23566 it may be impractical and involve too much modification, especially in
23567 the case of complex legacy code.
23568
23569 @item Perform dynamic checks
23570 If the compilations are done using the
23571 @option{-gnatE}
23572 (dynamic elaboration check) switch, then GNAT behaves in
23573 a quite different manner. Dynamic checks are generated for all calls
23574 that could possibly result in raising an exception. With this switch,
23575 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23576 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23577 The binder will generate an executable program that may or may not
23578 raise @code{Program_Error}, and then it is the programmer's job to ensure
23579 that it does not raise an exception. Note that it is important to
23580 compile all units with the switch, it cannot be used selectively.
23581
23582 @item Suppress checks
23583 The drawback of dynamic checks is that they generate a
23584 significant overhead at run time, both in space and time. If you
23585 are absolutely sure that your program cannot raise any elaboration
23586 exceptions, and you still want to use the dynamic elaboration model,
23587 then you can use the configuration pragma
23588 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23589 example this pragma could be placed in the @file{gnat.adc} file.
23590
23591 @item Suppress checks selectively
23592 When you know that certain calls in elaboration code cannot possibly
23593 lead to an elaboration error, and the binder nevertheless generates warnings
23594 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23595 circularities, it is possible to remove those warnings locally and obtain
23596 a program that will bind. Clearly this can be unsafe, and it is the
23597 responsibility of the programmer to make sure that the resulting program has
23598 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23599 be used with different granularity to suppress warnings and break
23600 elaboration circularities:
23601
23602 @itemize @bullet
23603 @item
23604 Place the pragma that names the called subprogram in the declarative part
23605 that contains the call.
23606
23607 @item
23608 Place the pragma in the declarative part, without naming an entity. This
23609 disables warnings on all calls in the corresponding  declarative region.
23610
23611 @item
23612 Place the pragma in the package spec that declares the called subprogram,
23613 and name the subprogram. This disables warnings on all elaboration calls to
23614 that subprogram.
23615
23616 @item
23617 Place the pragma in the package spec that declares the called subprogram,
23618 without naming any entity. This disables warnings on all elaboration calls to
23619 all subprograms declared in this spec.
23620
23621 @item Use Pragma Elaborate
23622 As previously described in section @xref{Treatment of Pragma Elaborate},
23623 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23624 that no elaboration checks are required on calls to the designated unit.
23625 There may be cases in which the caller knows that no transitive calls
23626 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23627 case where @code{pragma Elaborate_All} would cause a circularity.
23628 @end itemize
23629
23630 @noindent
23631 These five cases are listed in order of decreasing safety, and therefore
23632 require increasing programmer care in their application. Consider the
23633 following program:
23634
23635 @smallexample @c adanocomment
23636 package Pack1 is
23637   function F1 return Integer;
23638   X1 : Integer;
23639 end Pack1;
23640
23641 package Pack2 is
23642   function F2 return Integer;
23643   function Pure (x : integer) return integer;
23644   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23645   --  pragma Suppress (Elaboration_Check);              -- (4)
23646 end Pack2;
23647
23648 with Pack2;
23649 package body Pack1 is
23650   function F1 return Integer is
23651   begin
23652     return 100;
23653   end F1;
23654   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23655 begin
23656   declare
23657     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23658     --  pragma Suppress(Elaboration_Check);             -- (2)
23659   begin
23660     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23661   end;
23662 end Pack1;
23663
23664 with Pack1;
23665 package body Pack2 is
23666   function F2 return Integer is
23667   begin
23668      return Pack1.F1;
23669   end F2;
23670   function Pure (x : integer) return integer is
23671   begin
23672      return x ** 3 - 3 * x;
23673   end;
23674 end Pack2;
23675
23676 with Pack1, Ada.Text_IO;
23677 procedure Proc3 is
23678 begin
23679   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23680 end Proc3;
23681 @end smallexample
23682 In the absence of any pragmas, an attempt to bind this program produces
23683 the following diagnostics:
23684 @smallexample
23685 @group
23686 @iftex
23687 @leftskip=.5cm
23688 @end iftex
23689 error: elaboration circularity detected
23690 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23691 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23692 info:       recompile "pack1 (body)" with -gnatwl for full details
23693 info:          "pack1 (body)"
23694 info:             must be elaborated along with its spec:
23695 info:          "pack1 (spec)"
23696 info:             which is withed by:
23697 info:          "pack2 (body)"
23698 info:             which must be elaborated along with its spec:
23699 info:          "pack2 (spec)"
23700 info:             which is withed by:
23701 info:          "pack1 (body)"
23702 @end group
23703 @end smallexample
23704 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23705 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23706 F2 is safe, even though F2 calls F1, because the call appears after the
23707 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23708 remove the warning on the call. It is also possible to use pragma (2)
23709 because there are no other potentially unsafe calls in the block.
23710
23711 @noindent
23712 The call to @code{Pure} is safe because this function does not depend on the
23713 state of @code{Pack2}. Therefore any call to this function is safe, and it
23714 is correct to place pragma (3) in the corresponding package spec.
23715
23716 @noindent
23717 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23718 warnings on all calls to functions declared therein. Note that this is not
23719 necessarily safe, and requires more detailed examination of the subprogram
23720 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23721 be already elaborated.
23722 @end table
23723
23724 @noindent
23725 It is hard to generalize on which of these four approaches should be
23726 taken. Obviously if it is possible to fix the program so that the default
23727 treatment works, this is preferable, but this may not always be practical.
23728 It is certainly simple enough to use
23729 @option{-gnatE}
23730 but the danger in this case is that, even if the GNAT binder
23731 finds a correct elaboration order, it may not always do so,
23732 and certainly a binder from another Ada compiler might not. A
23733 combination of testing and analysis (for which the warnings generated
23734 with the
23735 @option{-gnatwl}
23736 switch can be useful) must be used to ensure that the program is free
23737 of errors. One switch that is useful in this testing is the
23738 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23739 switch for
23740 @code{gnatbind}.
23741 Normally the binder tries to find an order that has the best chance of
23742 of avoiding elaboration problems. With this switch, the binder
23743 plays a devil's advocate role, and tries to choose the order that
23744 has the best chance of failing. If your program works even with this
23745 switch, then it has a better chance of being error free, but this is still
23746 not a guarantee.
23747
23748 For an example of this approach in action, consider the C-tests (executable
23749 tests) from the ACVC suite. If these are compiled and run with the default
23750 treatment, then all but one of them succeed without generating any error
23751 diagnostics from the binder. However, there is one test that fails, and
23752 this is not surprising, because the whole point of this test is to ensure
23753 that the compiler can handle cases where it is impossible to determine
23754 a correct order statically, and it checks that an exception is indeed
23755 raised at run time.
23756
23757 This one test must be compiled and run using the
23758 @option{-gnatE}
23759 switch, and then it passes. Alternatively, the entire suite can
23760 be run using this switch. It is never wrong to run with the dynamic
23761 elaboration switch if your code is correct, and we assume that the
23762 C-tests are indeed correct (it is less efficient, but efficiency is
23763 not a factor in running the ACVC tests.)
23764
23765 @node Elaboration for Access-to-Subprogram Values
23766 @section Elaboration for Access-to-Subprogram Values
23767 @cindex Access-to-subprogram
23768
23769 @noindent
23770 The introduction of access-to-subprogram types in Ada 95 complicates
23771 the handling of elaboration. The trouble is that it becomes
23772 impossible to tell at compile time which procedure
23773 is being called. This means that it is not possible for the binder
23774 to analyze the elaboration requirements in this case.
23775
23776 If at the point at which the access value is created
23777 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23778 the body of the subprogram is
23779 known to have been elaborated, then the access value is safe, and its use
23780 does not require a check. This may be achieved by appropriate arrangement
23781 of the order of declarations if the subprogram is in the current unit,
23782 or, if the subprogram is in another unit, by using pragma
23783 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23784 on the referenced unit.
23785
23786 If the referenced body is not known to have been elaborated at the point
23787 the access value is created, then any use of the access value must do a
23788 dynamic check, and this dynamic check will fail and raise a
23789 @code{Program_Error} exception if the body has not been elaborated yet.
23790 GNAT will generate the necessary checks, and in addition, if the
23791 @option{-gnatwl}
23792 switch is set, will generate warnings that such checks are required.
23793
23794 The use of dynamic dispatching for tagged types similarly generates
23795 a requirement for dynamic checks, and premature calls to any primitive
23796 operation of a tagged type before the body of the operation has been
23797 elaborated, will result in the raising of @code{Program_Error}.
23798
23799 @node Summary of Procedures for Elaboration Control
23800 @section Summary of Procedures for Elaboration Control
23801 @cindex Elaboration control
23802
23803 @noindent
23804 First, compile your program with the default options, using none of
23805 the special elaboration control switches. If the binder successfully
23806 binds your program, then you can be confident that, apart from issues
23807 raised by the use of access-to-subprogram types and dynamic dispatching,
23808 the program is free of elaboration errors. If it is important that the
23809 program be portable, then use the
23810 @option{-gnatwl}
23811 switch to generate warnings about missing @code{Elaborate_All}
23812 pragmas, and supply the missing pragmas.
23813
23814 If the program fails to bind using the default static elaboration
23815 handling, then you can fix the program to eliminate the binder
23816 message, or recompile the entire program with the
23817 @option{-gnatE} switch to generate dynamic elaboration checks,
23818 and, if you are sure there really are no elaboration problems,
23819 use a global pragma @code{Suppress (Elaboration_Check)}.
23820
23821 @node Other Elaboration Order Considerations
23822 @section Other Elaboration Order Considerations
23823 @noindent
23824 This section has been entirely concerned with the issue of finding a valid
23825 elaboration order, as defined by the Ada Reference Manual. In a case
23826 where several elaboration orders are valid, the task is to find one
23827 of the possible valid elaboration orders (and the static model in GNAT
23828 will ensure that this is achieved).
23829
23830 The purpose of the elaboration rules in the Ada Reference Manual is to
23831 make sure that no entity is accessed before it has been elaborated. For
23832 a subprogram, this means that the spec and body must have been elaborated
23833 before the subprogram is called. For an object, this means that the object
23834 must have been elaborated before its value is read or written. A violation
23835 of either of these two requirements is an access before elaboration order,
23836 and this section has been all about avoiding such errors.
23837
23838 In the case where more than one order of elaboration is possible, in the
23839 sense that access before elaboration errors are avoided, then any one of
23840 the orders is ``correct'' in the sense that it meets the requirements of
23841 the Ada Reference Manual, and no such error occurs.
23842
23843 However, it may be the case for a given program, that there are
23844 constraints on the order of elaboration that come not from consideration
23845 of avoiding elaboration errors, but rather from extra-lingual logic
23846 requirements. Consider this example:
23847
23848 @smallexample @c ada
23849 with Init_Constants;
23850 package Constants is
23851    X : Integer := 0;
23852    Y : Integer := 0;
23853 end Constants;
23854
23855 package Init_Constants is
23856    procedure P; -- require a body
23857 end Init_Constants;
23858
23859 with Constants;
23860 package body Init_Constants is
23861    procedure P is begin null; end;
23862 begin
23863    Constants.X := 3;
23864    Constants.Y := 4;
23865 end Init_Constants;
23866
23867 with Constants;
23868 package Calc is
23869    Z : Integer := Constants.X + Constants.Y;
23870 end Calc;
23871
23872 with Calc;
23873 with Text_IO; use Text_IO;
23874 procedure Main is
23875 begin
23876    Put_Line (Calc.Z'Img);
23877 end Main;
23878 @end smallexample
23879
23880 @noindent
23881 In this example, there is more than one valid order of elaboration. For
23882 example both the following are correct orders:
23883
23884 @smallexample
23885 Init_Constants spec
23886 Constants spec
23887 Calc spec
23888 Init_Constants body
23889 Main body
23890
23891   and
23892
23893 Init_Constants spec
23894 Init_Constants body
23895 Constants spec
23896 Calc spec
23897 Main body
23898 @end smallexample
23899
23900 @noindent
23901 There is no language rule to prefer one or the other, both are correct
23902 from an order of elaboration point of view. But the programmatic effects
23903 of the two orders are very different. In the first, the elaboration routine
23904 of @code{Calc} initializes @code{Z} to zero, and then the main program
23905 runs with this value of zero. But in the second order, the elaboration
23906 routine of @code{Calc} runs after the body of Init_Constants has set
23907 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23908 runs.
23909
23910 One could perhaps by applying pretty clever non-artificial intelligence
23911 to the situation guess that it is more likely that the second order of
23912 elaboration is the one desired, but there is no formal linguistic reason
23913 to prefer one over the other. In fact in this particular case, GNAT will
23914 prefer the second order, because of the rule that bodies are elaborated
23915 as soon as possible, but it's just luck that this is what was wanted
23916 (if indeed the second order was preferred).
23917
23918 If the program cares about the order of elaboration routines in a case like
23919 this, it is important to specify the order required. In this particular
23920 case, that could have been achieved by adding to the spec of Calc:
23921
23922 @smallexample @c ada
23923 pragma Elaborate_All (Constants);
23924 @end smallexample
23925
23926 @noindent
23927 which requires that the body (if any) and spec of @code{Constants},
23928 as well as the body and spec of any unit @code{with}'ed by
23929 @code{Constants} be elaborated before @code{Calc} is elaborated.
23930
23931 Clearly no automatic method can always guess which alternative you require,
23932 and if you are working with legacy code that had constraints of this kind
23933 which were not properly specified by adding @code{Elaborate} or
23934 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23935 compilers can choose different orders.
23936
23937 The @code{gnatbind}
23938 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23939 out problems. This switch causes bodies to be elaborated as late as possible
23940 instead of as early as possible. In the example above, it would have forced
23941 the choice of the first elaboration order. If you get different results
23942 when using this switch, and particularly if one set of results is right,
23943 and one is wrong as far as you are concerned, it shows that you have some
23944 missing @code{Elaborate} pragmas. For the example above, we have the
23945 following output:
23946
23947 @smallexample
23948 gnatmake -f -q main
23949 main
23950  7
23951 gnatmake -f -q main -bargs -p
23952 main
23953  0
23954 @end smallexample
23955
23956 @noindent
23957 It is of course quite unlikely that both these results are correct, so
23958 it is up to you in a case like this to investigate the source of the
23959 difference, by looking at the two elaboration orders that are chosen,
23960 and figuring out which is correct, and then adding the necessary
23961 @code{Elaborate_All} pragmas to ensure the desired order.
23962
23963
23964 @node Inline Assembler
23965 @appendix Inline Assembler
23966
23967 @noindent
23968 If you need to write low-level software that interacts directly
23969 with the hardware, Ada provides two ways to incorporate assembly
23970 language code into your program.  First, you can import and invoke
23971 external routines written in assembly language, an Ada feature fully
23972 supported by GNAT.  However, for small sections of code it may be simpler
23973 or more efficient to include assembly language statements directly
23974 in your Ada source program, using the facilities of the implementation-defined
23975 package @code{System.Machine_Code}, which incorporates the gcc
23976 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23977 including the following:
23978
23979 @itemize @bullet
23980 @item No need to use non-Ada tools
23981 @item Consistent interface over different targets
23982 @item Automatic usage of the proper calling conventions
23983 @item Access to Ada constants and variables
23984 @item Definition of intrinsic routines
23985 @item Possibility of inlining a subprogram comprising assembler code
23986 @item Code optimizer can take Inline Assembler code into account
23987 @end itemize
23988
23989 This chapter presents a series of examples to show you how to use
23990 the Inline Assembler.  Although it focuses on the Intel x86,
23991 the general approach applies also to other processors.
23992 It is assumed that you are familiar with Ada
23993 and with assembly language programming.
23994
23995 @menu
23996 * Basic Assembler Syntax::
23997 * A Simple Example of Inline Assembler::
23998 * Output Variables in Inline Assembler::
23999 * Input Variables in Inline Assembler::
24000 * Inlining Inline Assembler Code::
24001 * Other Asm Functionality::
24002 * A Complete Example::
24003 @end menu
24004
24005 @c ---------------------------------------------------------------------------
24006 @node Basic Assembler Syntax
24007 @section Basic Assembler Syntax
24008
24009 @noindent
24010 The assembler used by GNAT and gcc is based not on the Intel assembly
24011 language, but rather on a language that descends from the AT&T Unix
24012 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24013 The following table summarizes the main features of @emph{as} syntax
24014 and points out the differences from the Intel conventions.
24015 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24016 pre-processor) documentation for further information.
24017
24018 @table @asis
24019 @item Register names
24020 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24021 @*
24022 Intel: No extra punctuation; for example @code{eax}
24023
24024 @item Immediate operand
24025 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24026 @*
24027 Intel: No extra punctuation; for example @code{4}
24028
24029 @item Address
24030 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24031 @*
24032 Intel: No extra punctuation; for example @code{loc}
24033
24034 @item Memory contents
24035 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24036 @*
24037 Intel: Square brackets; for example @code{[loc]}
24038
24039 @item Register contents
24040 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24041 @*
24042 Intel: Square brackets; for example @code{[eax]}
24043
24044 @item Hexadecimal numbers
24045 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24046 @*
24047 Intel: Trailing ``h''; for example @code{A0h}
24048
24049 @item Operand size
24050 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24051 a 16-bit word
24052 @*
24053 Intel: Implicit, deduced by assembler; for example @code{mov}
24054
24055 @item Instruction repetition
24056 gcc / @emph{as}: Split into two lines; for example
24057 @*
24058 @code{rep}
24059 @*
24060 @code{stosl}
24061 @*
24062 Intel: Keep on one line; for example @code{rep stosl}
24063
24064 @item Order of operands
24065 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24066 @*
24067 Intel: Destination first; for example @code{mov eax, 4}
24068 @end table
24069
24070 @c ---------------------------------------------------------------------------
24071 @node A Simple Example of Inline Assembler
24072 @section A Simple Example of Inline Assembler
24073
24074 @noindent
24075 The following example will generate a single assembly language statement,
24076 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24077 the example will be useful in illustrating the basics of
24078 the Inline Assembler facility.
24079
24080 @smallexample @c ada
24081 @group
24082 with System.Machine_Code; use System.Machine_Code;
24083 procedure Nothing is
24084 begin
24085    Asm ("nop");
24086 end Nothing;
24087 @end group
24088 @end smallexample
24089
24090 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24091 here it takes one parameter, a @emph{template string} that must be a static
24092 expression and that will form the generated instruction.
24093 @code{Asm} may be regarded as a compile-time procedure that parses
24094 the template string and additional parameters (none here),
24095 from which it generates a sequence of assembly language instructions.
24096
24097 The examples in this chapter will illustrate several of the forms
24098 for invoking @code{Asm}; a complete specification of the syntax
24099 is found in the @cite{GNAT Reference Manual}.
24100
24101 Under the standard GNAT conventions, the @code{Nothing} procedure
24102 should be in a file named @file{nothing.adb}.
24103 You can build the executable in the usual way:
24104 @smallexample
24105 gnatmake nothing
24106 @end smallexample
24107 However, the interesting aspect of this example is not its run-time behavior
24108 but rather the generated assembly code.
24109 To see this output, invoke the compiler as follows:
24110 @smallexample
24111    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24112 @end smallexample
24113 where the options are:
24114
24115 @table @code
24116 @item -c
24117 compile only (no bind or link)
24118 @item -S
24119 generate assembler listing
24120 @item -fomit-frame-pointer
24121 do not set up separate stack frames
24122 @item -gnatp
24123 do not add runtime checks
24124 @end table
24125
24126 This gives a human-readable assembler version of the code. The resulting
24127 file will have the same name as the Ada source file, but with a @code{.s}
24128 extension. In our example, the file @file{nothing.s} has the following
24129 contents:
24130
24131 @smallexample
24132 @group
24133 .file "nothing.adb"
24134 gcc2_compiled.:
24135 ___gnu_compiled_ada:
24136 .text
24137    .align 4
24138 .globl __ada_nothing
24139 __ada_nothing:
24140 #APP
24141    nop
24142 #NO_APP
24143    jmp L1
24144    .align 2,0x90
24145 L1:
24146    ret
24147 @end group
24148 @end smallexample
24149
24150 The assembly code you included is clearly indicated by
24151 the compiler, between the @code{#APP} and @code{#NO_APP}
24152 delimiters. The character before the 'APP' and 'NOAPP'
24153 can differ on different targets. For example, GNU/Linux uses '#APP' while
24154 on NT you will see '/APP'.
24155
24156 If you make a mistake in your assembler code (such as using the
24157 wrong size modifier, or using a wrong operand for the instruction) GNAT
24158 will report this error in a temporary file, which will be deleted when
24159 the compilation is finished.  Generating an assembler file will help
24160 in such cases, since you can assemble this file separately using the
24161 @emph{as} assembler that comes with gcc.
24162
24163 Assembling the file using the command
24164
24165 @smallexample
24166 as @file{nothing.s}
24167 @end smallexample
24168 @noindent
24169 will give you error messages whose lines correspond to the assembler
24170 input file, so you can easily find and correct any mistakes you made.
24171 If there are no errors, @emph{as} will generate an object file
24172 @file{nothing.out}.
24173
24174 @c ---------------------------------------------------------------------------
24175 @node Output Variables in Inline Assembler
24176 @section Output Variables in Inline Assembler
24177
24178 @noindent
24179 The examples in this section, showing how to access the processor flags,
24180 illustrate how to specify the destination operands for assembly language
24181 statements.
24182
24183 @smallexample @c ada
24184 @group
24185 with Interfaces; use Interfaces;
24186 with Ada.Text_IO; use Ada.Text_IO;
24187 with System.Machine_Code; use System.Machine_Code;
24188 procedure Get_Flags is
24189    Flags : Unsigned_32;
24190    use ASCII;
24191 begin
24192    Asm ("pushfl"          & LF & HT & -- push flags on stack
24193         "popl %%eax"      & LF & HT & -- load eax with flags
24194         "movl %%eax, %0",             -- store flags in variable
24195         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24196    Put_Line ("Flags register:" & Flags'Img);
24197 end Get_Flags;
24198 @end group
24199 @end smallexample
24200
24201 In order to have a nicely aligned assembly listing, we have separated
24202 multiple assembler statements in the Asm template string with linefeed
24203 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24204 The resulting section of the assembly output file is:
24205
24206 @smallexample
24207 @group
24208 #APP
24209    pushfl
24210    popl %eax
24211    movl %eax, -40(%ebp)
24212 #NO_APP
24213 @end group
24214 @end smallexample
24215
24216 It would have been legal to write the Asm invocation as:
24217
24218 @smallexample
24219 Asm ("pushfl popl %%eax movl %%eax, %0")
24220 @end smallexample
24221
24222 but in the generated assembler file, this would come out as:
24223
24224 @smallexample
24225 #APP
24226    pushfl popl %eax movl %eax, -40(%ebp)
24227 #NO_APP
24228 @end smallexample
24229
24230 which is not so convenient for the human reader.
24231
24232 We use Ada comments
24233 at the end of each line to explain what the assembler instructions
24234 actually do.  This is a useful convention.
24235
24236 When writing Inline Assembler instructions, you need to precede each register
24237 and variable name with a percent sign.  Since the assembler already requires
24238 a percent sign at the beginning of a register name, you need two consecutive
24239 percent signs for such names in the Asm template string, thus @code{%%eax}.
24240 In the generated assembly code, one of the percent signs will be stripped off.
24241
24242 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24243 variables: operands you later define using @code{Input} or @code{Output}
24244 parameters to @code{Asm}.
24245 An output variable is illustrated in
24246 the third statement in the Asm template string:
24247 @smallexample
24248 movl %%eax, %0
24249 @end smallexample
24250 The intent is to store the contents of the eax register in a variable that can
24251 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24252 necessarily work, since the compiler might optimize by using a register
24253 to hold Flags, and the expansion of the @code{movl} instruction would not be
24254 aware of this optimization.  The solution is not to store the result directly
24255 but rather to advise the compiler to choose the correct operand form;
24256 that is the purpose of the @code{%0} output variable.
24257
24258 Information about the output variable is supplied in the @code{Outputs}
24259 parameter to @code{Asm}:
24260 @smallexample
24261 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24262 @end smallexample
24263
24264 The output is defined by the @code{Asm_Output} attribute of the target type;
24265 the general format is
24266 @smallexample
24267 Type'Asm_Output (constraint_string, variable_name)
24268 @end smallexample
24269
24270 The constraint string directs the compiler how
24271 to store/access the associated variable.  In the example
24272 @smallexample
24273 Unsigned_32'Asm_Output ("=m", Flags);
24274 @end smallexample
24275 the @code{"m"} (memory) constraint tells the compiler that the variable
24276 @code{Flags} should be stored in a memory variable, thus preventing
24277 the optimizer from keeping it in a register.  In contrast,
24278 @smallexample
24279 Unsigned_32'Asm_Output ("=r", Flags);
24280 @end smallexample
24281 uses the @code{"r"} (register) constraint, telling the compiler to
24282 store the variable in a register.
24283
24284 If the constraint is preceded by the equal character (@strong{=}), it tells
24285 the compiler that the variable will be used to store data into it.
24286
24287 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24288 allowing the optimizer to choose whatever it deems best.
24289
24290 There are a fairly large number of constraints, but the ones that are
24291 most useful (for the Intel x86 processor) are the following:
24292
24293 @table @code
24294 @item =
24295 output constraint
24296 @item g
24297 global (i.e. can be stored anywhere)
24298 @item m
24299 in memory
24300 @item I
24301 a constant
24302 @item a
24303 use eax
24304 @item b
24305 use ebx
24306 @item c
24307 use ecx
24308 @item d
24309 use edx
24310 @item S
24311 use esi
24312 @item D
24313 use edi
24314 @item r
24315 use one of eax, ebx, ecx or edx
24316 @item q
24317 use one of eax, ebx, ecx, edx, esi or edi
24318 @end table
24319
24320 The full set of constraints is described in the gcc and @emph{as}
24321 documentation; note that it is possible to combine certain constraints
24322 in one constraint string.
24323
24324 You specify the association of an output variable with an assembler operand
24325 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24326 integer.  Thus in
24327 @smallexample @c ada
24328 @group
24329 Asm ("pushfl"          & LF & HT & -- push flags on stack
24330      "popl %%eax"      & LF & HT & -- load eax with flags
24331      "movl %%eax, %0",             -- store flags in variable
24332      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24333 @end group
24334 @end smallexample
24335 @noindent
24336 @code{%0} will be replaced in the expanded code by the appropriate operand,
24337 whatever
24338 the compiler decided for the @code{Flags} variable.
24339
24340 In general, you may have any number of output variables:
24341 @itemize @bullet
24342 @item
24343 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24344 @item
24345 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24346 of @code{Asm_Output} attributes
24347 @end itemize
24348
24349 For example:
24350 @smallexample @c ada
24351 @group
24352 Asm ("movl %%eax, %0" & LF & HT &
24353      "movl %%ebx, %1" & LF & HT &
24354      "movl %%ecx, %2",
24355      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24356                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24357                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24358 @end group
24359 @end smallexample
24360 @noindent
24361 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24362 in the Ada program.
24363
24364 As a variation on the @code{Get_Flags} example, we can use the constraints
24365 string to direct the compiler to store the eax register into the @code{Flags}
24366 variable, instead of including the store instruction explicitly in the
24367 @code{Asm} template string:
24368
24369 @smallexample @c ada
24370 @group
24371 with Interfaces; use Interfaces;
24372 with Ada.Text_IO; use Ada.Text_IO;
24373 with System.Machine_Code; use System.Machine_Code;
24374 procedure Get_Flags_2 is
24375    Flags : Unsigned_32;
24376    use ASCII;
24377 begin
24378    Asm ("pushfl"      & LF & HT & -- push flags on stack
24379         "popl %%eax",             -- save flags in eax
24380         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24381    Put_Line ("Flags register:" & Flags'Img);
24382 end Get_Flags_2;
24383 @end group
24384 @end smallexample
24385
24386 @noindent
24387 The @code{"a"} constraint tells the compiler that the @code{Flags}
24388 variable will come from the eax register. Here is the resulting code:
24389
24390 @smallexample
24391 @group
24392 #APP
24393    pushfl
24394    popl %eax
24395 #NO_APP
24396    movl %eax,-40(%ebp)
24397 @end group
24398 @end smallexample
24399
24400 @noindent
24401 The compiler generated the store of eax into Flags after
24402 expanding the assembler code.
24403
24404 Actually, there was no need to pop the flags into the eax register;
24405 more simply, we could just pop the flags directly into the program variable:
24406
24407 @smallexample @c ada
24408 @group
24409 with Interfaces; use Interfaces;
24410 with Ada.Text_IO; use Ada.Text_IO;
24411 with System.Machine_Code; use System.Machine_Code;
24412 procedure Get_Flags_3 is
24413    Flags : Unsigned_32;
24414    use ASCII;
24415 begin
24416    Asm ("pushfl"  & LF & HT & -- push flags on stack
24417         "pop %0",             -- save flags in Flags
24418         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24419    Put_Line ("Flags register:" & Flags'Img);
24420 end Get_Flags_3;
24421 @end group
24422 @end smallexample
24423
24424 @c ---------------------------------------------------------------------------
24425 @node Input Variables in Inline Assembler
24426 @section Input Variables in Inline Assembler
24427
24428 @noindent
24429 The example in this section illustrates how to specify the source operands
24430 for assembly language statements.
24431 The program simply increments its input value by 1:
24432
24433 @smallexample @c ada
24434 @group
24435 with Interfaces; use Interfaces;
24436 with Ada.Text_IO; use Ada.Text_IO;
24437 with System.Machine_Code; use System.Machine_Code;
24438 procedure Increment is
24439
24440    function Incr (Value : Unsigned_32) return Unsigned_32 is
24441       Result : Unsigned_32;
24442    begin
24443       Asm ("incl %0",
24444            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24445            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24446       return Result;
24447    end Incr;
24448
24449    Value : Unsigned_32;
24450
24451 begin
24452    Value := 5;
24453    Put_Line ("Value before is" & Value'Img);
24454    Value := Incr (Value);
24455    Put_Line ("Value after is" & Value'Img);
24456 end Increment;
24457 @end group
24458 @end smallexample
24459
24460 The @code{Outputs} parameter to @code{Asm} specifies
24461 that the result will be in the eax register and that it is to be stored
24462 in the @code{Result} variable.
24463
24464 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24465 but with an @code{Asm_Input} attribute.
24466 The @code{"="} constraint, indicating an output value, is not present.
24467
24468 You can have multiple input variables, in the same way that you can have more
24469 than one output variable.
24470
24471 The parameter count (%0, %1) etc, now starts at the first input
24472 statement, and continues with the output statements.
24473 When both parameters use the same variable, the
24474 compiler will treat them as the same %n operand, which is the case here.
24475
24476 Just as the @code{Outputs} parameter causes the register to be stored into the
24477 target variable after execution of the assembler statements, so does the
24478 @code{Inputs} parameter cause its variable to be loaded into the register
24479 before execution of the assembler statements.
24480
24481 Thus the effect of the @code{Asm} invocation is:
24482 @enumerate
24483 @item load the 32-bit value of @code{Value} into eax
24484 @item execute the @code{incl %eax} instruction
24485 @item store the contents of eax into the @code{Result} variable
24486 @end enumerate
24487
24488 The resulting assembler file (with @option{-O2} optimization) contains:
24489 @smallexample
24490 @group
24491 _increment__incr.1:
24492    subl $4,%esp
24493    movl 8(%esp),%eax
24494 #APP
24495    incl %eax
24496 #NO_APP
24497    movl %eax,%edx
24498    movl %ecx,(%esp)
24499    addl $4,%esp
24500    ret
24501 @end group
24502 @end smallexample
24503
24504 @c ---------------------------------------------------------------------------
24505 @node Inlining Inline Assembler Code
24506 @section Inlining Inline Assembler Code
24507
24508 @noindent
24509 For a short subprogram such as the @code{Incr} function in the previous
24510 section, the overhead of the call and return (creating / deleting the stack
24511 frame) can be significant, compared to the amount of code in the subprogram
24512 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24513 which directs the compiler to expand invocations of the subprogram at the
24514 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24515 Here is the resulting program:
24516
24517 @smallexample @c ada
24518 @group
24519 with Interfaces; use Interfaces;
24520 with Ada.Text_IO; use Ada.Text_IO;
24521 with System.Machine_Code; use System.Machine_Code;
24522 procedure Increment_2 is
24523
24524    function Incr (Value : Unsigned_32) return Unsigned_32 is
24525       Result : Unsigned_32;
24526    begin
24527       Asm ("incl %0",
24528            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24529            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24530       return Result;
24531    end Incr;
24532    pragma Inline (Increment);
24533
24534    Value : Unsigned_32;
24535
24536 begin
24537    Value := 5;
24538    Put_Line ("Value before is" & Value'Img);
24539    Value := Increment (Value);
24540    Put_Line ("Value after is" & Value'Img);
24541 end Increment_2;
24542 @end group
24543 @end smallexample
24544
24545 Compile the program with both optimization (@option{-O2}) and inlining
24546 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24547
24548 The @code{Incr} function is still compiled as usual, but at the
24549 point in @code{Increment} where our function used to be called:
24550
24551 @smallexample
24552 @group
24553 pushl %edi
24554 call _increment__incr.1
24555 @end group
24556 @end smallexample
24557
24558 @noindent
24559 the code for the function body directly appears:
24560
24561 @smallexample
24562 @group
24563 movl %esi,%eax
24564 #APP
24565    incl %eax
24566 #NO_APP
24567    movl %eax,%edx
24568 @end group
24569 @end smallexample
24570
24571 @noindent
24572 thus saving the overhead of stack frame setup and an out-of-line call.
24573
24574 @c ---------------------------------------------------------------------------
24575 @node Other Asm Functionality
24576 @section Other @code{Asm} Functionality
24577
24578 @noindent
24579 This section describes two important parameters to the @code{Asm}
24580 procedure: @code{Clobber}, which identifies register usage;
24581 and @code{Volatile}, which inhibits unwanted optimizations.
24582
24583 @menu
24584 * The Clobber Parameter::
24585 * The Volatile Parameter::
24586 @end menu
24587
24588 @c ---------------------------------------------------------------------------
24589 @node The Clobber Parameter
24590 @subsection The @code{Clobber} Parameter
24591
24592 @noindent
24593 One of the dangers of intermixing assembly language and a compiled language
24594 such as Ada is that the compiler needs to be aware of which registers are
24595 being used by the assembly code.  In some cases, such as the earlier examples,
24596 the constraint string is sufficient to indicate register usage (e.g.,
24597 @code{"a"} for
24598 the eax register).  But more generally, the compiler needs an explicit
24599 identification of the registers that are used by the Inline Assembly
24600 statements.
24601
24602 Using a register that the compiler doesn't know about
24603 could be a side effect of an instruction (like @code{mull}
24604 storing its result in both eax and edx).
24605 It can also arise from explicit register usage in your
24606 assembly code; for example:
24607 @smallexample
24608 @group
24609 Asm ("movl %0, %%ebx" & LF & HT &
24610      "movl %%ebx, %1",
24611      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24612      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24613 @end group
24614 @end smallexample
24615 @noindent
24616 where the compiler (since it does not analyze the @code{Asm} template string)
24617 does not know you are using the ebx register.
24618
24619 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24620 to identify the registers that will be used by your assembly code:
24621
24622 @smallexample
24623 @group
24624 Asm ("movl %0, %%ebx" & LF & HT &
24625      "movl %%ebx, %1",
24626      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24627      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24628      Clobber => "ebx");
24629 @end group
24630 @end smallexample
24631
24632 The Clobber parameter is a static string expression specifying the
24633 register(s) you are using.  Note that register names are @emph{not} prefixed
24634 by a percent sign. Also, if more than one register is used then their names
24635 are separated by commas; e.g., @code{"eax, ebx"}
24636
24637 The @code{Clobber} parameter has several additional uses:
24638 @enumerate
24639 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24640 @item Use ``register'' name @code{memory} if you changed a memory location
24641 @end enumerate
24642
24643 @c ---------------------------------------------------------------------------
24644 @node The Volatile Parameter
24645 @subsection The @code{Volatile} Parameter
24646 @cindex Volatile parameter
24647
24648 @noindent
24649 Compiler optimizations in the presence of Inline Assembler may sometimes have
24650 unwanted effects.  For example, when an @code{Asm} invocation with an input
24651 variable is inside a loop, the compiler might move the loading of the input
24652 variable outside the loop, regarding it as a one-time initialization.
24653
24654 If this effect is not desired, you can disable such optimizations by setting
24655 the @code{Volatile} parameter to @code{True}; for example:
24656
24657 @smallexample @c ada
24658 @group
24659 Asm ("movl %0, %%ebx" & LF & HT &
24660      "movl %%ebx, %1",
24661      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24662      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24663      Clobber  => "ebx",
24664      Volatile => True);
24665 @end group
24666 @end smallexample
24667
24668 By default, @code{Volatile} is set to @code{False} unless there is no
24669 @code{Outputs} parameter.
24670
24671 Although setting @code{Volatile} to @code{True} prevents unwanted
24672 optimizations, it will also disable other optimizations that might be
24673 important for efficiency. In general, you should set @code{Volatile}
24674 to @code{True} only if the compiler's optimizations have created
24675 problems.
24676
24677 @c ---------------------------------------------------------------------------
24678 @node A Complete Example
24679 @section A Complete Example
24680
24681 @noindent
24682 This section contains a complete program illustrating a realistic usage
24683 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24684 @code{Check_CPU} and a package @code{Intel_CPU}.
24685 The package declares a collection of functions that detect the properties
24686 of the 32-bit x86 processor that is running the program.
24687 The main procedure invokes these functions and displays the information.
24688
24689 The Intel_CPU package could be enhanced by adding functions to
24690 detect the type of x386 co-processor, the processor caching options and
24691 special operations such as the SIMD extensions.
24692
24693 Although the Intel_CPU package has been written for 32-bit Intel
24694 compatible CPUs, it is OS neutral. It has been tested on DOS,
24695 Windows/NT and GNU/Linux.
24696
24697 @menu
24698 * Check_CPU Procedure::
24699 * Intel_CPU Package Specification::
24700 * Intel_CPU Package Body::
24701 @end menu
24702
24703 @c ---------------------------------------------------------------------------
24704 @node Check_CPU Procedure
24705 @subsection @code{Check_CPU} Procedure
24706 @cindex Check_CPU procedure
24707
24708 @smallexample @c adanocomment
24709 ---------------------------------------------------------------------
24710 --                                                                 --
24711 --  Uses the Intel_CPU package to identify the CPU the program is  --
24712 --  running on, and some of the features it supports.              --
24713 --                                                                 --
24714 ---------------------------------------------------------------------
24715
24716 with Intel_CPU;                     --  Intel CPU detection functions
24717 with Ada.Text_IO;                   --  Standard text I/O
24718 with Ada.Command_Line;              --  To set the exit status
24719
24720 procedure Check_CPU is
24721
24722    Type_Found : Boolean := False;
24723    --  Flag to indicate that processor was identified
24724
24725    Features   : Intel_CPU.Processor_Features;
24726    --  The processor features
24727
24728    Signature  : Intel_CPU.Processor_Signature;
24729    --  The processor type signature
24730
24731 begin
24732
24733    -----------------------------------
24734    --  Display the program banner.  --
24735    -----------------------------------
24736
24737    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24738                          ": check Intel CPU version and features, v1.0");
24739    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24740    Ada.Text_IO.New_Line;
24741
24742    -----------------------------------------------------------------------
24743    --  We can safely start with the assumption that we are on at least  --
24744    --  a x386 processor. If the CPUID instruction is present, then we   --
24745    --  have a later processor type.                                     --
24746    -----------------------------------------------------------------------
24747
24748    if Intel_CPU.Has_CPUID = False then
24749
24750       --  No CPUID instruction, so we assume this is indeed a x386
24751       --  processor. We can still check if it has a FP co-processor.
24752       if Intel_CPU.Has_FPU then
24753          Ada.Text_IO.Put_Line
24754            ("x386-type processor with a FP co-processor");
24755       else
24756          Ada.Text_IO.Put_Line
24757            ("x386-type processor without a FP co-processor");
24758       end if;  --  check for FPU
24759
24760       --  Program done
24761       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24762       return;
24763
24764    end if;  --  check for CPUID
24765
24766    -----------------------------------------------------------------------
24767    --  If CPUID is supported, check if this is a true Intel processor,  --
24768    --  if it is not, display a warning.                                 --
24769    -----------------------------------------------------------------------
24770
24771    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24772       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24773       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24774    end if;  --  check if Intel
24775
24776    ----------------------------------------------------------------------
24777    --  With the CPUID instruction present, we can assume at least a    --
24778    --  x486 processor. If the CPUID support level is < 1 then we have  --
24779    --  to leave it at that.                                            --
24780    ----------------------------------------------------------------------
24781
24782    if Intel_CPU.CPUID_Level < 1 then
24783
24784       --  Ok, this is a x486 processor. we still can get the Vendor ID
24785       Ada.Text_IO.Put_Line ("x486-type processor");
24786       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24787
24788       --  We can also check if there is a FPU present
24789       if Intel_CPU.Has_FPU then
24790          Ada.Text_IO.Put_Line ("Floating-Point support");
24791       else
24792          Ada.Text_IO.Put_Line ("No Floating-Point support");
24793       end if;  --  check for FPU
24794
24795       --  Program done
24796       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24797       return;
24798
24799    end if;  --  check CPUID level
24800
24801    ---------------------------------------------------------------------
24802    --  With a CPUID level of 1 we can use the processor signature to  --
24803    --  determine it's exact type.                                     --
24804    ---------------------------------------------------------------------
24805
24806    Signature := Intel_CPU.Signature;
24807
24808    ----------------------------------------------------------------------
24809    --  Ok, now we go into a lot of messy comparisons to get the        --
24810    --  processor type. For clarity, no attememt to try to optimize the --
24811    --  comparisons has been made. Note that since Intel_CPU does not   --
24812    --  support getting cache info, we cannot distinguish between P5    --
24813    --  and Celeron types yet.                                          --
24814    ----------------------------------------------------------------------
24815
24816    --  x486SL
24817    if Signature.Processor_Type = 2#00#   and
24818      Signature.Family          = 2#0100# and
24819      Signature.Model           = 2#0100# then
24820       Type_Found := True;
24821       Ada.Text_IO.Put_Line ("x486SL processor");
24822    end if;
24823
24824    --  x486DX2 Write-Back
24825    if Signature.Processor_Type = 2#00#   and
24826      Signature.Family          = 2#0100# and
24827      Signature.Model           = 2#0111# then
24828       Type_Found := True;
24829       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24830    end if;
24831
24832    --  x486DX4
24833    if Signature.Processor_Type = 2#00#   and
24834      Signature.Family          = 2#0100# and
24835      Signature.Model           = 2#1000# then
24836       Type_Found := True;
24837       Ada.Text_IO.Put_Line ("x486DX4 processor");
24838    end if;
24839
24840    --  x486DX4 Overdrive
24841    if Signature.Processor_Type = 2#01#   and
24842      Signature.Family          = 2#0100# and
24843      Signature.Model           = 2#1000# then
24844       Type_Found := True;
24845       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24846    end if;
24847
24848    --  Pentium (60, 66)
24849    if Signature.Processor_Type = 2#00#   and
24850      Signature.Family          = 2#0101# and
24851      Signature.Model           = 2#0001# then
24852       Type_Found := True;
24853       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24854    end if;
24855
24856    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24857    if Signature.Processor_Type = 2#00#   and
24858      Signature.Family          = 2#0101# and
24859      Signature.Model           = 2#0010# then
24860       Type_Found := True;
24861       Ada.Text_IO.Put_Line
24862         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24863    end if;
24864
24865    --  Pentium OverDrive (60, 66)
24866    if Signature.Processor_Type = 2#01#   and
24867      Signature.Family          = 2#0101# and
24868      Signature.Model           = 2#0001# then
24869       Type_Found := True;
24870       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24871    end if;
24872
24873    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24874    if Signature.Processor_Type = 2#01#   and
24875      Signature.Family          = 2#0101# and
24876      Signature.Model           = 2#0010# then
24877       Type_Found := True;
24878       Ada.Text_IO.Put_Line
24879         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24880    end if;
24881
24882    --  Pentium OverDrive processor for x486 processor-based systems
24883    if Signature.Processor_Type = 2#01#   and
24884      Signature.Family          = 2#0101# and
24885      Signature.Model           = 2#0011# then
24886       Type_Found := True;
24887       Ada.Text_IO.Put_Line
24888         ("Pentium OverDrive processor for x486 processor-based systems");
24889    end if;
24890
24891    --  Pentium processor with MMX technology (166, 200)
24892    if Signature.Processor_Type = 2#00#   and
24893      Signature.Family          = 2#0101# and
24894      Signature.Model           = 2#0100# then
24895       Type_Found := True;
24896       Ada.Text_IO.Put_Line
24897         ("Pentium processor with MMX technology (166, 200)");
24898    end if;
24899
24900    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24901    if Signature.Processor_Type = 2#01#   and
24902      Signature.Family          = 2#0101# and
24903      Signature.Model           = 2#0100# then
24904       Type_Found := True;
24905       Ada.Text_IO.Put_Line
24906         ("Pentium OverDrive processor with MMX " &
24907          "technology for Pentium processor (75, 90, 100, 120, 133)");
24908    end if;
24909
24910    --  Pentium Pro processor
24911    if Signature.Processor_Type = 2#00#   and
24912      Signature.Family          = 2#0110# and
24913      Signature.Model           = 2#0001# then
24914       Type_Found := True;
24915       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24916    end if;
24917
24918    --  Pentium II processor, model 3
24919    if Signature.Processor_Type = 2#00#   and
24920      Signature.Family          = 2#0110# and
24921      Signature.Model           = 2#0011# then
24922       Type_Found := True;
24923       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24924    end if;
24925
24926    --  Pentium II processor, model 5 or Celeron processor
24927    if Signature.Processor_Type = 2#00#   and
24928      Signature.Family          = 2#0110# and
24929      Signature.Model           = 2#0101# then
24930       Type_Found := True;
24931       Ada.Text_IO.Put_Line
24932         ("Pentium II processor, model 5 or Celeron processor");
24933    end if;
24934
24935    --  Pentium Pro OverDrive processor
24936    if Signature.Processor_Type = 2#01#   and
24937      Signature.Family          = 2#0110# and
24938      Signature.Model           = 2#0011# then
24939       Type_Found := True;
24940       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24941    end if;
24942
24943    --  If no type recognized, we have an unknown. Display what
24944    --  we _do_ know
24945    if Type_Found = False then
24946       Ada.Text_IO.Put_Line ("Unknown processor");
24947    end if;
24948
24949    -----------------------------------------
24950    --  Display processor stepping level.  --
24951    -----------------------------------------
24952
24953    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24954
24955    ---------------------------------
24956    --  Display vendor ID string.  --
24957    ---------------------------------
24958
24959    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24960
24961    ------------------------------------
24962    --  Get the processors features.  --
24963    ------------------------------------
24964
24965    Features := Intel_CPU.Features;
24966
24967    -----------------------------
24968    --  Check for a FPU unit.  --
24969    -----------------------------
24970
24971    if Features.FPU = True then
24972       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24973    else
24974       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24975    end if;  --  check for FPU
24976
24977    --------------------------------
24978    --  List processor features.  --
24979    --------------------------------
24980
24981    Ada.Text_IO.Put_Line ("Supported features: ");
24982
24983    --  Virtual Mode Extension
24984    if Features.VME = True then
24985       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24986    end if;
24987
24988    --  Debugging Extension
24989    if Features.DE = True then
24990       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24991    end if;
24992
24993    --  Page Size Extension
24994    if Features.PSE = True then
24995       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24996    end if;
24997
24998    --  Time Stamp Counter
24999    if Features.TSC = True then
25000       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
25001    end if;
25002
25003    --  Model Specific Registers
25004    if Features.MSR = True then
25005       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
25006    end if;
25007
25008    --  Physical Address Extension
25009    if Features.PAE = True then
25010       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
25011    end if;
25012
25013    --  Machine Check Extension
25014    if Features.MCE = True then
25015       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
25016    end if;
25017
25018    --  CMPXCHG8 instruction supported
25019    if Features.CX8 = True then
25020       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
25021    end if;
25022
25023    --  on-chip APIC hardware support
25024    if Features.APIC = True then
25025       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
25026    end if;
25027
25028    --  Fast System Call
25029    if Features.SEP = True then
25030       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
25031    end if;
25032
25033    --  Memory Type Range Registers
25034    if Features.MTRR = True then
25035       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
25036    end if;
25037
25038    --  Page Global Enable
25039    if Features.PGE = True then
25040       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
25041    end if;
25042
25043    --  Machine Check Architecture
25044    if Features.MCA = True then
25045       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
25046    end if;
25047
25048    --  Conditional Move Instruction Supported
25049    if Features.CMOV = True then
25050       Ada.Text_IO.Put_Line
25051         ("    CMOV   - Conditional Move Instruction Supported");
25052    end if;
25053
25054    --  Page Attribute Table
25055    if Features.PAT = True then
25056       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
25057    end if;
25058
25059    --  36-bit Page Size Extension
25060    if Features.PSE_36 = True then
25061       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
25062    end if;
25063
25064    --  MMX technology supported
25065    if Features.MMX = True then
25066       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
25067    end if;
25068
25069    --  Fast FP Save and Restore
25070    if Features.FXSR = True then
25071       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
25072    end if;
25073
25074    ---------------------
25075    --  Program done.  --
25076    ---------------------
25077
25078    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25079
25080 exception
25081
25082    when others =>
25083       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25084       raise;
25085
25086 end Check_CPU;
25087 @end smallexample
25088
25089 @c ---------------------------------------------------------------------------
25090 @node Intel_CPU Package Specification
25091 @subsection @code{Intel_CPU} Package Specification
25092 @cindex Intel_CPU package specification
25093
25094 @smallexample @c adanocomment
25095 -------------------------------------------------------------------------
25096 --                                                                     --
25097 --  file: intel_cpu.ads                                                --
25098 --                                                                     --
25099 --           *********************************************             --
25100 --           * WARNING: for 32-bit Intel processors only *             --
25101 --           *********************************************             --
25102 --                                                                     --
25103 --  This package contains a number of subprograms that are useful in   --
25104 --  determining the Intel x86 CPU (and the features it supports) on    --
25105 --  which the program is running.                                      --
25106 --                                                                     --
25107 --  The package is based upon the information given in the Intel       --
25108 --  Application Note AP-485: "Intel Processor Identification and the   --
25109 --  CPUID Instruction" as of April 1998. This application note can be  --
25110 --  found on www.intel.com.                                            --
25111 --                                                                     --
25112 --  It currently deals with 32-bit processors only, will not detect    --
25113 --  features added after april 1998, and does not guarantee proper     --
25114 --  results on Intel-compatible processors.                            --
25115 --                                                                     --
25116 --  Cache info and x386 fpu type detection are not supported.          --
25117 --                                                                     --
25118 --  This package does not use any privileged instructions, so should   --
25119 --  work on any OS running on a 32-bit Intel processor.                --
25120 --                                                                     --
25121 -------------------------------------------------------------------------
25122
25123 with Interfaces;             use Interfaces;
25124 --  for using unsigned types
25125
25126 with System.Machine_Code;    use System.Machine_Code;
25127 --  for using inline assembler code
25128
25129 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25130 --  for inserting control characters
25131
25132 package Intel_CPU is
25133
25134    ----------------------
25135    --  Processor bits  --
25136    ----------------------
25137
25138    subtype Num_Bits is Natural range 0 .. 31;
25139    --  the number of processor bits (32)
25140
25141    --------------------------
25142    --  Processor register  --
25143    --------------------------
25144
25145    --  define a processor register type for easy access to
25146    --  the individual bits
25147
25148    type Processor_Register is array (Num_Bits) of Boolean;
25149    pragma Pack (Processor_Register);
25150    for Processor_Register'Size use 32;
25151
25152    -------------------------
25153    --  Unsigned register  --
25154    -------------------------
25155
25156    --  define a processor register type for easy access to
25157    --  the individual bytes
25158
25159    type Unsigned_Register is
25160       record
25161          L1 : Unsigned_8;
25162          H1 : Unsigned_8;
25163          L2 : Unsigned_8;
25164          H2 : Unsigned_8;
25165       end record;
25166
25167    for Unsigned_Register use
25168       record
25169          L1 at 0 range  0 ..  7;
25170          H1 at 0 range  8 .. 15;
25171          L2 at 0 range 16 .. 23;
25172          H2 at 0 range 24 .. 31;
25173       end record;
25174
25175    for Unsigned_Register'Size use 32;
25176
25177    ---------------------------------
25178    --  Intel processor vendor ID  --
25179    ---------------------------------
25180
25181    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25182    --  indicates an Intel manufactured processor
25183
25184    ------------------------------------
25185    --  Processor signature register  --
25186    ------------------------------------
25187
25188    --  a register type to hold the processor signature
25189
25190    type Processor_Signature is
25191       record
25192          Stepping       : Natural range 0 .. 15;
25193          Model          : Natural range 0 .. 15;
25194          Family         : Natural range 0 .. 15;
25195          Processor_Type : Natural range 0 .. 3;
25196          Reserved       : Natural range 0 .. 262143;
25197       end record;
25198
25199    for Processor_Signature use
25200       record
25201          Stepping       at 0 range  0 ..  3;
25202          Model          at 0 range  4 ..  7;
25203          Family         at 0 range  8 .. 11;
25204          Processor_Type at 0 range 12 .. 13;
25205          Reserved       at 0 range 14 .. 31;
25206       end record;
25207
25208    for Processor_Signature'Size use 32;
25209
25210    -----------------------------------
25211    --  Processor features register  --
25212    -----------------------------------
25213
25214    --  a processor register to hold the processor feature flags
25215
25216    type Processor_Features is
25217       record
25218          FPU    : Boolean;                --  floating point unit on chip
25219          VME    : Boolean;                --  virtual mode extension
25220          DE     : Boolean;                --  debugging extension
25221          PSE    : Boolean;                --  page size extension
25222          TSC    : Boolean;                --  time stamp counter
25223          MSR    : Boolean;                --  model specific registers
25224          PAE    : Boolean;                --  physical address extension
25225          MCE    : Boolean;                --  machine check extension
25226          CX8    : Boolean;                --  cmpxchg8 instruction
25227          APIC   : Boolean;                --  on-chip apic hardware
25228          Res_1  : Boolean;                --  reserved for extensions
25229          SEP    : Boolean;                --  fast system call
25230          MTRR   : Boolean;                --  memory type range registers
25231          PGE    : Boolean;                --  page global enable
25232          MCA    : Boolean;                --  machine check architecture
25233          CMOV   : Boolean;                --  conditional move supported
25234          PAT    : Boolean;                --  page attribute table
25235          PSE_36 : Boolean;                --  36-bit page size extension
25236          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25237          MMX    : Boolean;                --  MMX technology supported
25238          FXSR   : Boolean;                --  fast FP save and restore
25239          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25240       end record;
25241
25242    for Processor_Features use
25243       record
25244          FPU    at 0 range  0 ..  0;
25245          VME    at 0 range  1 ..  1;
25246          DE     at 0 range  2 ..  2;
25247          PSE    at 0 range  3 ..  3;
25248          TSC    at 0 range  4 ..  4;
25249          MSR    at 0 range  5 ..  5;
25250          PAE    at 0 range  6 ..  6;
25251          MCE    at 0 range  7 ..  7;
25252          CX8    at 0 range  8 ..  8;
25253          APIC   at 0 range  9 ..  9;
25254          Res_1  at 0 range 10 .. 10;
25255          SEP    at 0 range 11 .. 11;
25256          MTRR   at 0 range 12 .. 12;
25257          PGE    at 0 range 13 .. 13;
25258          MCA    at 0 range 14 .. 14;
25259          CMOV   at 0 range 15 .. 15;
25260          PAT    at 0 range 16 .. 16;
25261          PSE_36 at 0 range 17 .. 17;
25262          Res_2  at 0 range 18 .. 22;
25263          MMX    at 0 range 23 .. 23;
25264          FXSR   at 0 range 24 .. 24;
25265          Res_3  at 0 range 25 .. 31;
25266       end record;
25267
25268    for Processor_Features'Size use 32;
25269
25270    -------------------
25271    --  Subprograms  --
25272    -------------------
25273
25274    function Has_FPU return Boolean;
25275    --  return True if a FPU is found
25276    --  use only if CPUID is not supported
25277
25278    function Has_CPUID return Boolean;
25279    --  return True if the processor supports the CPUID instruction
25280
25281    function CPUID_Level return Natural;
25282    --  return the CPUID support level (0, 1 or 2)
25283    --  can only be called if the CPUID instruction is supported
25284
25285    function Vendor_ID return String;
25286    --  return the processor vendor identification string
25287    --  can only be called if the CPUID instruction is supported
25288
25289    function Signature return Processor_Signature;
25290    --  return the processor signature
25291    --  can only be called if the CPUID instruction is supported
25292
25293    function Features return Processor_Features;
25294    --  return the processors features
25295    --  can only be called if the CPUID instruction is supported
25296
25297 private
25298
25299    ------------------------
25300    --  EFLAGS bit names  --
25301    ------------------------
25302
25303    ID_Flag : constant Num_Bits := 21;
25304    --  ID flag bit
25305
25306 end Intel_CPU;
25307 @end smallexample
25308
25309 @c ---------------------------------------------------------------------------
25310 @node Intel_CPU Package Body
25311 @subsection @code{Intel_CPU} Package Body
25312 @cindex Intel_CPU package body
25313
25314 @smallexample @c adanocomment
25315 package body Intel_CPU is
25316
25317    ---------------------------
25318    --  Detect FPU presence  --
25319    ---------------------------
25320
25321    --  There is a FPU present if we can set values to the FPU Status
25322    --  and Control Words.
25323
25324    function Has_FPU return Boolean is
25325
25326       Register : Unsigned_16;
25327       --  processor register to store a word
25328
25329    begin
25330
25331       --  check if we can change the status word
25332       Asm (
25333
25334            --  the assembler code
25335            "finit"              & LF & HT &    --  reset status word
25336            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25337            "fnstsw %0"          & LF & HT &    --  save status word
25338            "movw %%ax, %0",                    --  store status word
25339
25340            --  output stored in Register
25341            --  register must be a memory location
25342            Outputs => Unsigned_16'Asm_output ("=m", Register),
25343
25344            --  tell compiler that we used eax
25345            Clobber => "eax");
25346
25347       --  if the status word is zero, there is no FPU
25348       if Register = 0 then
25349          return False;   --  no status word
25350       end if;  --  check status word value
25351
25352       --  check if we can get the control word
25353       Asm (
25354
25355            --  the assembler code
25356            "fnstcw %0",   --  save the control word
25357
25358            --  output into Register
25359            --  register must be a memory location
25360            Outputs => Unsigned_16'Asm_output ("=m", Register));
25361
25362       --  check the relevant bits
25363       if (Register and 16#103F#) /= 16#003F# then
25364          return False;   --  no control word
25365       end if;  --  check control word value
25366
25367       --  FPU found
25368       return True;
25369
25370    end Has_FPU;
25371
25372    --------------------------------
25373    --  Detect CPUID instruction  --
25374    --------------------------------
25375
25376    --  The processor supports the CPUID instruction if it is possible
25377    --  to change the value of ID flag bit in the EFLAGS register.
25378
25379    function Has_CPUID return Boolean is
25380
25381       Original_Flags, Modified_Flags : Processor_Register;
25382       --  EFLAG contents before and after changing the ID flag
25383
25384    begin
25385
25386       --  try flipping the ID flag in the EFLAGS register
25387       Asm (
25388
25389            --  the assembler code
25390            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25391            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25392            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25393            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25394            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25395            "popfl"                & LF & HT &     --  load EFLAGS register
25396            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25397            "pop %1",                              --  save EFLAGS content
25398
25399            --  output values, may be anything
25400            --  Original_Flags is %0
25401            --  Modified_Flags is %1
25402            Outputs =>
25403               (Processor_Register'Asm_output ("=g", Original_Flags),
25404                Processor_Register'Asm_output ("=g", Modified_Flags)),
25405
25406            --  tell compiler eax is destroyed
25407            Clobber => "eax");
25408
25409       --  check if CPUID is supported
25410       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25411          return True;   --  ID flag was modified
25412       else
25413          return False;  --  ID flag unchanged
25414       end if;  --  check for CPUID
25415
25416    end Has_CPUID;
25417
25418    -------------------------------
25419    --  Get CPUID support level  --
25420    -------------------------------
25421
25422    function CPUID_Level return Natural is
25423
25424       Level : Unsigned_32;
25425       --  returned support level
25426
25427    begin
25428
25429       --  execute CPUID, storing the results in the Level register
25430       Asm (
25431
25432            --  the assembler code
25433            "cpuid",    --  execute CPUID
25434
25435            --  zero is stored in eax
25436            --  returning the support level in eax
25437            Inputs => Unsigned_32'Asm_input ("a", 0),
25438
25439            --  eax is stored in Level
25440            Outputs => Unsigned_32'Asm_output ("=a", Level),
25441
25442            --  tell compiler ebx, ecx and edx registers are destroyed
25443            Clobber => "ebx, ecx, edx");
25444
25445       --  return the support level
25446       return Natural (Level);
25447
25448    end CPUID_Level;
25449
25450    --------------------------------
25451    --  Get CPU Vendor ID String  --
25452    --------------------------------
25453
25454    --  The vendor ID string is returned in the ebx, ecx and edx register
25455    --  after executing the CPUID instruction with eax set to zero.
25456    --  In case of a true Intel processor the string returned is
25457    --  "GenuineIntel"
25458
25459    function Vendor_ID return String is
25460
25461       Ebx, Ecx, Edx : Unsigned_Register;
25462       --  registers containing the vendor ID string
25463
25464       Vendor_ID : String (1 .. 12);
25465       -- the vendor ID string
25466
25467    begin
25468
25469       --  execute CPUID, storing the results in the processor registers
25470       Asm (
25471
25472            --  the assembler code
25473            "cpuid",    --  execute CPUID
25474
25475            --  zero stored in eax
25476            --  vendor ID string returned in ebx, ecx and edx
25477            Inputs => Unsigned_32'Asm_input ("a", 0),
25478
25479            --  ebx is stored in Ebx
25480            --  ecx is stored in Ecx
25481            --  edx is stored in Edx
25482            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25483                        Unsigned_Register'Asm_output ("=c", Ecx),
25484                        Unsigned_Register'Asm_output ("=d", Edx)));
25485
25486       --  now build the vendor ID string
25487       Vendor_ID( 1) := Character'Val (Ebx.L1);
25488       Vendor_ID( 2) := Character'Val (Ebx.H1);
25489       Vendor_ID( 3) := Character'Val (Ebx.L2);
25490       Vendor_ID( 4) := Character'Val (Ebx.H2);
25491       Vendor_ID( 5) := Character'Val (Edx.L1);
25492       Vendor_ID( 6) := Character'Val (Edx.H1);
25493       Vendor_ID( 7) := Character'Val (Edx.L2);
25494       Vendor_ID( 8) := Character'Val (Edx.H2);
25495       Vendor_ID( 9) := Character'Val (Ecx.L1);
25496       Vendor_ID(10) := Character'Val (Ecx.H1);
25497       Vendor_ID(11) := Character'Val (Ecx.L2);
25498       Vendor_ID(12) := Character'Val (Ecx.H2);
25499
25500       --  return string
25501       return Vendor_ID;
25502
25503    end Vendor_ID;
25504
25505    -------------------------------
25506    --  Get processor signature  --
25507    -------------------------------
25508
25509    function Signature return Processor_Signature is
25510
25511       Result : Processor_Signature;
25512       --  processor signature returned
25513
25514    begin
25515
25516       --  execute CPUID, storing the results in the Result variable
25517       Asm (
25518
25519            --  the assembler code
25520            "cpuid",    --  execute CPUID
25521
25522            --  one is stored in eax
25523            --  processor signature returned in eax
25524            Inputs => Unsigned_32'Asm_input ("a", 1),
25525
25526            --  eax is stored in Result
25527            Outputs => Processor_Signature'Asm_output ("=a", Result),
25528
25529            --  tell compiler that ebx, ecx and edx are also destroyed
25530            Clobber => "ebx, ecx, edx");
25531
25532       --  return processor signature
25533       return Result;
25534
25535    end Signature;
25536
25537    ------------------------------
25538    --  Get processor features  --
25539    ------------------------------
25540
25541    function Features return Processor_Features is
25542
25543       Result : Processor_Features;
25544       --  processor features returned
25545
25546    begin
25547
25548       --  execute CPUID, storing the results in the Result variable
25549       Asm (
25550
25551            --  the assembler code
25552            "cpuid",    --  execute CPUID
25553
25554            --  one stored in eax
25555            --  processor features returned in edx
25556            Inputs => Unsigned_32'Asm_input ("a", 1),
25557
25558            --  edx is stored in Result
25559            Outputs => Processor_Features'Asm_output ("=d", Result),
25560
25561            --  tell compiler that ebx and ecx are also destroyed
25562            Clobber => "ebx, ecx");
25563
25564       --  return processor signature
25565       return Result;
25566
25567    end Features;
25568
25569 end Intel_CPU;
25570 @end smallexample
25571 @c END OF INLINE ASSEMBLER CHAPTER
25572 @c ===============================
25573
25574
25575
25576 @c ***********************************
25577 @c * Compatibility and Porting Guide *
25578 @c ***********************************
25579 @node Compatibility and Porting Guide
25580 @appendix Compatibility and Porting Guide
25581
25582 @noindent
25583 This chapter describes the compatibility issues that may arise between
25584 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25585 can expedite porting
25586 applications developed in other Ada environments.
25587
25588 @menu
25589 * Compatibility with Ada 83::
25590 * Implementation-dependent characteristics::
25591 * Compatibility with DEC Ada 83::
25592 * Compatibility with Other Ada 95 Systems::
25593 * Representation Clauses::
25594 @end menu
25595
25596 @node Compatibility with Ada 83
25597 @section Compatibility with Ada 83
25598 @cindex Compatibility (between Ada 83 and Ada 95)
25599
25600 @noindent
25601 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25602 particular, the design intention is that the difficulties associated
25603 with moving from Ada 83 to Ada 95 should be no greater than those
25604 that occur when moving from one Ada 83 system to another.
25605
25606 However, there are a number of points at which there are minor
25607 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25608 full details of these issues,
25609 and should be consulted for a complete treatment.
25610 In practice the
25611 following subsections treat the most likely issues to be encountered.
25612
25613 @menu
25614 * Legal Ada 83 programs that are illegal in Ada 95::
25615 * More deterministic semantics::
25616 * Changed semantics::
25617 * Other language compatibility issues::
25618 @end menu
25619
25620 @node Legal Ada 83 programs that are illegal in Ada 95
25621 @subsection Legal Ada 83 programs that are illegal in Ada 95
25622
25623 @table @asis
25624 @item Character literals
25625 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25626 @code{Wide_Character} as a new predefined character type, some uses of
25627 character literals that were legal in Ada 83 are illegal in Ada 95.
25628 For example:
25629 @smallexample @c ada
25630    for Char in 'A' .. 'Z' loop ... end loop;
25631 @end smallexample
25632 @noindent
25633 The problem is that @code{'A'} and @code{'Z'} could be from either
25634 @code{Character} or @code{Wide_Character}.  The simplest correction
25635 is to make the type explicit; e.g.:
25636 @smallexample @c ada
25637    for Char in Character range 'A' .. 'Z' loop ... end loop;
25638 @end smallexample
25639
25640 @item New reserved words
25641 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25642 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25643 Existing Ada 83 code using any of these identifiers must be edited to
25644 use some alternative name.
25645
25646 @item Freezing rules
25647 The rules in Ada 95 are slightly different with regard to the point at
25648 which entities are frozen, and representation pragmas and clauses are
25649 not permitted past the freeze point.  This shows up most typically in
25650 the form of an error message complaining that a representation item
25651 appears too late, and the appropriate corrective action is to move
25652 the item nearer to the declaration of the entity to which it refers.
25653
25654 A particular case is that representation pragmas
25655 @ifset vms
25656 (including the
25657 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25658 @end ifset
25659 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25660 declaration must be introduced to which the pragma can be applied.
25661
25662 @item Optional bodies for library packages
25663 In Ada 83, a package that did not require a package body was nevertheless
25664 allowed to have one.  This lead to certain surprises in compiling large
25665 systems (situations in which the body could be unexpectedly ignored by the
25666 binder).  In Ada 95, if a package does not require a body then it is not
25667 permitted to have a body.  To fix this problem, simply remove a redundant
25668 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25669 into the spec that makes the body required.  One approach is to add a private
25670 part to the package declaration (if necessary), and define a parameterless
25671 procedure called @code{Requires_Body}, which must then be given a dummy
25672 procedure body in the package body, which then becomes required.
25673 Another approach (assuming that this does not introduce elaboration
25674 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25675 since one effect of this pragma is to require the presence of a package body.
25676
25677 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25678 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25679 @code{Constraint_Error}.
25680 This means that it is illegal to have separate exception handlers for
25681 the two exceptions.  The fix is simply to remove the handler for the
25682 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25683 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25684
25685 @item Indefinite subtypes in generics
25686 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25687 as the actual for a generic formal private type, but then the instantiation
25688 would be illegal if there were any instances of declarations of variables
25689 of this type in the generic body.  In Ada 95, to avoid this clear violation
25690 of the methodological principle known as the ``contract model'',
25691 the generic declaration explicitly indicates whether
25692 or not such instantiations are permitted.  If a generic formal parameter
25693 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25694 type name, then it can be instantiated with indefinite types, but no
25695 stand-alone variables can be declared of this type.  Any attempt to declare
25696 such a variable will result in an illegality at the time the generic is
25697 declared.  If the @code{(<>)} notation is not used, then it is illegal
25698 to instantiate the generic with an indefinite type.
25699 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25700 It will show up as a compile time error, and
25701 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25702 @end table
25703
25704 @node More deterministic semantics
25705 @subsection More deterministic semantics
25706
25707 @table @asis
25708 @item Conversions
25709 Conversions from real types to integer types round away from 0.  In Ada 83
25710 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25711 implementation freedom was intended to support unbiased rounding in
25712 statistical applications, but in practice it interfered with portability.
25713 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25714 is required.  Numeric code may be affected by this change in semantics.
25715 Note, though, that this issue is no worse than already existed in Ada 83
25716 when porting code from one vendor to another.
25717
25718 @item Tasking
25719 The Real-Time Annex introduces a set of policies that define the behavior of
25720 features that were implementation dependent in Ada 83, such as the order in
25721 which open select branches are executed.
25722 @end table
25723
25724 @node Changed semantics
25725 @subsection Changed semantics
25726
25727 @noindent
25728 The worst kind of incompatibility is one where a program that is legal in
25729 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25730 possible in Ada 83.  Fortunately this is extremely rare, but the one
25731 situation that you should be alert to is the change in the predefined type
25732 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25733
25734 @table @asis
25735 @item range of @code{Character}
25736 The range of @code{Standard.Character} is now the full 256 characters
25737 of Latin-1, whereas in most Ada 83 implementations it was restricted
25738 to 128 characters. Although some of the effects of
25739 this change will be manifest in compile-time rejection of legal
25740 Ada 83 programs it is possible for a working Ada 83 program to have
25741 a different effect in Ada 95, one that was not permitted in Ada 83.
25742 As an example, the expression
25743 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25744 delivers @code{255} as its value.
25745 In general, you should look at the logic of any
25746 character-processing Ada 83 program and see whether it needs to be adapted
25747 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25748 character handling package that may be relevant if code needs to be adapted
25749 to account for the additional Latin-1 elements.
25750 The desirable fix is to
25751 modify the program to accommodate the full character set, but in some cases
25752 it may be convenient to define a subtype or derived type of Character that
25753 covers only the restricted range.
25754 @cindex Latin-1
25755 @end table
25756
25757 @node Other language compatibility issues
25758 @subsection Other language compatibility issues
25759 @table @asis
25760 @item @option{-gnat83 switch}
25761 All implementations of GNAT provide a switch that causes GNAT to operate
25762 in Ada 83 mode.  In this mode, some but not all compatibility problems
25763 of the type described above are handled automatically.  For example, the
25764 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25765 However,
25766 in practice, it is usually advisable to make the necessary modifications
25767 to the program to remove the need for using this switch.
25768 See @ref{Compiling Ada 83 Programs}.
25769
25770 @item Support for removed Ada 83 pragmas and attributes
25771 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25772 generally because they have been replaced by other mechanisms.  Ada 95
25773 compilers are allowed, but not required, to implement these missing
25774 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25775 such pragmas and attributes, eliminating this compatibility concern.  These
25776 include @code{pragma Interface} and the floating point type attributes
25777 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25778 @end table
25779
25780
25781 @node Implementation-dependent characteristics
25782 @section Implementation-dependent characteristics
25783 @noindent
25784 Although the Ada language defines the semantics of each construct as
25785 precisely as practical, in some situations (for example for reasons of
25786 efficiency, or where the effect is heavily dependent on the host or target
25787 platform) the implementation is allowed some freedom.  In porting Ada 83
25788 code to GNAT, you need to be aware of whether / how the existing code
25789 exercised such implementation dependencies.  Such characteristics fall into
25790 several categories, and GNAT offers specific support in assisting the
25791 transition from certain Ada 83 compilers.
25792
25793 @menu
25794 * Implementation-defined pragmas::
25795 * Implementation-defined attributes::
25796 * Libraries::
25797 * Elaboration order::
25798 * Target-specific aspects::
25799 @end menu
25800
25801
25802 @node Implementation-defined pragmas
25803 @subsection Implementation-defined pragmas
25804
25805 @noindent
25806 Ada compilers are allowed to supplement the language-defined pragmas, and
25807 these are a potential source of non-portability.  All GNAT-defined pragmas
25808 are described in the GNAT Reference Manual, and these include several that
25809 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25810 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25811 For
25812 compatibility with DEC Ada 83, GNAT supplies the pragmas
25813 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25814 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25815 and @code{Volatile}.
25816 Other relevant pragmas include @code{External} and @code{Link_With}.
25817 Some vendor-specific
25818 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25819 recognized, thus
25820 avoiding compiler rejection of units that contain such pragmas; they are not
25821 relevant in a GNAT context and hence are not otherwise implemented.
25822
25823 @node Implementation-defined attributes
25824 @subsection Implementation-defined attributes
25825
25826 Analogous to pragmas, the set of attributes may be extended by an
25827 implementation.  All GNAT-defined attributes are described in the
25828 @cite{GNAT Reference Manual}, and these include several that are specifically
25829 intended
25830 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25831 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25832 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25833 @code{Type_Class}.
25834
25835 @node Libraries
25836 @subsection Libraries
25837 @noindent
25838 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25839 code uses vendor-specific libraries then there are several ways to manage
25840 this in Ada 95:
25841 @enumerate
25842 @item
25843 If the source code for the libraries (specifications and bodies) are
25844 available, then the libraries can be migrated in the same way as the
25845 application.
25846 @item
25847 If the source code for the specifications but not the bodies are
25848 available, then you can reimplement the bodies.
25849 @item
25850 Some new Ada 95 features obviate the need for library support.  For
25851 example most Ada 83 vendors supplied a package for unsigned integers.  The
25852 Ada 95 modular type feature is the preferred way to handle this need, so
25853 instead of migrating or reimplementing the unsigned integer package it may
25854 be preferable to retrofit the application using modular types.
25855 @end enumerate
25856
25857 @node Elaboration order
25858 @subsection Elaboration order
25859 @noindent
25860 The implementation can choose any elaboration order consistent with the unit
25861 dependency relationship.  This freedom means that some orders can result in
25862 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25863 to invoke a subprogram its body has been elaborated, or to instantiate a
25864 generic before the generic body has been elaborated.  By default GNAT
25865 attempts to choose a safe order (one that will not encounter access before
25866 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25867 needed.  However, this can lead to the creation of elaboration circularities
25868 and a resulting rejection of the program by gnatbind.  This issue is
25869 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25870 In brief, there are several
25871 ways to deal with this situation:
25872
25873 @itemize @bullet
25874 @item
25875 Modify the program to eliminate the circularities, e.g. by moving
25876 elaboration-time code into explicitly-invoked procedures
25877 @item
25878 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25879 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25880 @code{Elaborate_All}
25881 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25882 (by selectively suppressing elaboration checks via pragma
25883 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25884 @end itemize
25885
25886 @node Target-specific aspects
25887 @subsection Target-specific aspects
25888 @noindent
25889 Low-level applications need to deal with machine addresses, data
25890 representations, interfacing with assembler code, and similar issues.  If
25891 such an Ada 83 application is being ported to different target hardware (for
25892 example where the byte endianness has changed) then you will need to
25893 carefully examine the program logic; the porting effort will heavily depend
25894 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25895 incompatible with typical Ada 83 compiler practices regarding implicit
25896 packing, the meaning of the Size attribute, and the size of access values.
25897 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25898
25899
25900 @node Compatibility with Other Ada 95 Systems
25901 @section Compatibility with Other Ada 95 Systems
25902
25903 @noindent
25904 Providing that programs avoid the use of implementation dependent and
25905 implementation defined features of Ada 95, as documented in the Ada 95
25906 reference manual, there should be a high degree of portability between
25907 GNAT and other Ada 95 systems.  The following are specific items which
25908 have proved troublesome in moving GNAT programs to other Ada 95
25909 compilers, but do not affect porting code to GNAT@.
25910
25911 @table @asis
25912 @item Ada 83 Pragmas and Attributes
25913 Ada 95 compilers are allowed, but not required, to implement the missing
25914 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25915 GNAT implements all such pragmas and attributes, eliminating this as
25916 a compatibility concern, but some other Ada 95 compilers reject these
25917 pragmas and attributes.
25918
25919 @item Special-needs Annexes
25920 GNAT implements the full set of special needs annexes.  At the
25921 current time, it is the only Ada 95 compiler to do so.  This means that
25922 programs making use of these features may not be portable to other Ada
25923 95 compilation systems.
25924
25925 @item Representation Clauses
25926 Some other Ada 95 compilers implement only the minimal set of
25927 representation clauses required by the Ada 95 reference manual.  GNAT goes
25928 far beyond this minimal set, as described in the next section.
25929 @end table
25930
25931 @node Representation Clauses
25932 @section Representation Clauses
25933
25934 @noindent
25935 The Ada 83 reference manual was quite vague in describing both the minimal
25936 required implementation of representation clauses, and also their precise
25937 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25938 set of capabilities required in Ada 95 is quite limited.
25939
25940 GNAT implements the full required set of capabilities described in the
25941 Ada 95 reference manual, but also goes much beyond this, and in particular
25942 an effort has been made to be compatible with existing Ada 83 usage to the
25943 greatest extent possible.
25944
25945 A few cases exist in which Ada 83 compiler behavior is incompatible with
25946 requirements in the Ada 95 reference manual.  These are instances of
25947 intentional or accidental dependence on specific implementation dependent
25948 characteristics of these Ada 83 compilers.  The following is a list of
25949 the cases most likely to arise in existing legacy Ada 83 code.
25950
25951 @table @asis
25952 @item Implicit Packing
25953 Some Ada 83 compilers allowed a Size specification to cause implicit
25954 packing of an array or record.  This could cause expensive implicit
25955 conversions for change of representation in the presence of derived
25956 types, and the Ada design intends to avoid this possibility.
25957 Subsequent AI's were issued to make it clear that such implicit
25958 change of representation in response to a Size clause is inadvisable,
25959 and this recommendation is represented explicitly in the Ada 95 RM
25960 as implementation advice that is followed by GNAT@.
25961 The problem will show up as an error
25962 message rejecting the size clause.  The fix is simply to provide
25963 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25964 a Component_Size clause.
25965
25966 @item Meaning of Size Attribute
25967 The Size attribute in Ada 95 for discrete types is defined as being the
25968 minimal number of bits required to hold values of the type.  For example,
25969 on a 32-bit machine, the size of Natural will typically be 31 and not
25970 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25971 some 32 in this situation.  This problem will usually show up as a compile
25972 time error, but not always.  It is a good idea to check all uses of the
25973 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25974 Object_Size can provide a useful way of duplicating the behavior of
25975 some Ada 83 compiler systems.
25976
25977 @item Size of Access Types
25978 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25979 and that therefore it will be the same size as a System.Address value.  This
25980 assumption is true for GNAT in most cases with one exception.  For the case of
25981 a pointer to an unconstrained array type (where the bounds may vary from one
25982 value of the access type to another), the default is to use a ``fat pointer'',
25983 which is represented as two separate pointers, one to the bounds, and one to
25984 the array.  This representation has a number of advantages, including improved
25985 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25986 code which makes the assumption that, for example, pointers fit in 32 bits on
25987 a machine with 32-bit addressing.
25988
25989 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25990 access types in this case (where the designated type is an unconstrained array
25991 type).  These thin pointers are indeed the same size as a System.Address value.
25992 To specify a thin pointer, use a size clause for the type, for example:
25993
25994 @smallexample @c ada
25995 type X is access all String;
25996 for X'Size use Standard'Address_Size;
25997 @end smallexample
25998
25999 @noindent
26000 which will cause the type X to be represented using a single pointer.
26001 When using this representation, the bounds are right behind the array.
26002 This representation is slightly less efficient, and does not allow quite
26003 such flexibility in the use of foreign pointers or in using the
26004 Unrestricted_Access attribute to create pointers to non-aliased objects.
26005 But for any standard portable use of the access type it will work in
26006 a functionally correct manner and allow porting of existing code.
26007 Note that another way of forcing a thin pointer representation
26008 is to use a component size clause for the element size in an array,
26009 or a record representation clause for an access field in a record.
26010 @end table
26011
26012 @node Compatibility with DEC Ada 83
26013 @section Compatibility with DEC Ada 83
26014
26015 @noindent
26016 The VMS version of GNAT fully implements all the pragmas and attributes
26017 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26018 libraries, including Starlet.  In addition, data layouts and parameter
26019 passing conventions are highly compatible.  This means that porting
26020 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26021 most other porting efforts.  The following are some of the most
26022 significant differences between GNAT and DEC Ada 83.
26023
26024 @table @asis
26025 @item Default floating-point representation
26026 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26027 it is VMS format.  GNAT does implement the necessary pragmas
26028 (Long_Float, Float_Representation) for changing this default.
26029
26030 @item System
26031 The package System in GNAT exactly corresponds to the definition in the
26032 Ada 95 reference manual, which means that it excludes many of the
26033 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
26034 that contains the additional definitions, and a special pragma,
26035 Extend_System allows this package to be treated transparently as an
26036 extension of package System.
26037
26038 @item To_Address
26039 The definitions provided by Aux_DEC are exactly compatible with those
26040 in the DEC Ada 83 version of System, with one exception.
26041 DEC Ada provides the following declarations:
26042
26043 @smallexample @c ada
26044 TO_ADDRESS (INTEGER)
26045 TO_ADDRESS (UNSIGNED_LONGWORD)
26046 TO_ADDRESS (universal_integer)
26047 @end smallexample
26048
26049 @noindent
26050 The version of TO_ADDRESS taking a universal integer argument is in fact
26051 an extension to Ada 83 not strictly compatible with the reference manual.
26052 In GNAT, we are constrained to be exactly compatible with the standard,
26053 and this means we cannot provide this capability.  In DEC Ada 83, the
26054 point of this definition is to deal with a call like:
26055
26056 @smallexample @c ada
26057 TO_ADDRESS (16#12777#);
26058 @end smallexample
26059
26060 @noindent
26061 Normally, according to the Ada 83 standard, one would expect this to be
26062 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26063 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
26064 definition using universal_integer takes precedence.
26065
26066 In GNAT, since the version with universal_integer cannot be supplied, it is
26067 not possible to be 100% compatible.  Since there are many programs using
26068 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26069 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26070 declarations provided in the GNAT version of AUX_Dec are:
26071
26072 @smallexample @c ada
26073 function To_Address (X : Integer) return Address;
26074 pragma Pure_Function (To_Address);
26075
26076 function To_Address_Long (X : Unsigned_Longword)
26077  return Address;
26078 pragma Pure_Function (To_Address_Long);
26079 @end smallexample
26080
26081 @noindent
26082 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26083 change the name to TO_ADDRESS_LONG@.
26084
26085 @item Task_Id values
26086 The Task_Id values assigned will be different in the two systems, and GNAT
26087 does not provide a specified value for the Task_Id of the environment task,
26088 which in GNAT is treated like any other declared task.
26089 @end table
26090
26091 For full details on these and other less significant compatibility issues,
26092 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26093 Overview and Comparison on DIGITAL Platforms}.
26094
26095 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26096 attributes are recognized, although only a subset of them can sensibly
26097 be implemented.  The description of pragmas in this reference manual
26098 indicates whether or not they are applicable to non-VMS systems.
26099
26100
26101
26102 @ifset unw
26103 @node Microsoft Windows Topics
26104 @appendix Microsoft Windows Topics
26105 @cindex Windows NT
26106 @cindex Windows 95
26107 @cindex Windows 98
26108
26109 @noindent
26110 This chapter describes topics that are specific to the Microsoft Windows
26111 platforms (NT, 2000, and XP Professional).
26112
26113 @menu
26114 * Using GNAT on Windows::
26115 * Using a network installation of GNAT::
26116 * CONSOLE and WINDOWS subsystems::
26117 * Temporary Files::
26118 * Mixed-Language Programming on Windows::
26119 * Windows Calling Conventions::
26120 * Introduction to Dynamic Link Libraries (DLLs)::
26121 * Using DLLs with GNAT::
26122 * Building DLLs with GNAT::
26123 * GNAT and Windows Resources::
26124 * Debugging a DLL::
26125 * GNAT and COM/DCOM Objects::
26126 @end menu
26127
26128 @node Using GNAT on Windows
26129 @section Using GNAT on Windows
26130
26131 @noindent
26132 One of the strengths of the GNAT technology is that its tool set
26133 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
26134 @code{gdb} debugger, etc.) is used in the same way regardless of the
26135 platform.
26136
26137 On Windows this tool set is complemented by a number of Microsoft-specific
26138 tools that have been provided to facilitate interoperability with Windows
26139 when this is required. With these tools:
26140
26141 @itemize @bullet
26142
26143 @item
26144 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26145 subsystems.
26146
26147 @item
26148 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26149 relocatable and non-relocatable DLLs are supported).
26150
26151 @item
26152 You can build Ada DLLs for use in other applications. These applications
26153 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26154 relocatable and non-relocatable Ada DLLs are supported.
26155
26156 @item
26157 You can include Windows resources in your Ada application.
26158
26159 @item
26160 You can use or create COM/DCOM objects.
26161 @end itemize
26162
26163 @noindent
26164 Immediately below are listed all known general GNAT-for-Windows restrictions.
26165 Other restrictions about specific features like Windows Resources and DLLs
26166 are listed in separate sections below.
26167
26168 @itemize @bullet
26169
26170 @item
26171 It is not possible to use @code{GetLastError} and @code{SetLastError}
26172 when tasking, protected records, or exceptions are used. In these
26173 cases, in order to implement Ada semantics, the GNAT run-time system
26174 calls certain Win32 routines that set the last error variable to 0 upon
26175 success. It should be possible to use @code{GetLastError} and
26176 @code{SetLastError} when tasking, protected record, and exception
26177 features are not used, but it is not guaranteed to work.
26178
26179 @item
26180 It is not possible to link against Microsoft libraries except for
26181 import libraries. The library must be built to be compatible with
26182 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26183 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26184 not be compatible with the GNAT runtime. Even if the library is
26185 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26186
26187 @item
26188 When the compilation environment is located on FAT32 drives, users may
26189 experience recompilations of the source files that have not changed if
26190 Daylight Saving Time (DST) state has changed since the last time files
26191 were compiled. NTFS drives do not have this problem.
26192
26193 @item
26194 No components of the GNAT toolset use any entries in the Windows
26195 registry. The only entries that can be created are file associations and
26196 PATH settings, provided the user has chosen to create them at installation
26197 time, as well as some minimal book-keeping information needed to correctly
26198 uninstall or integrate different GNAT products.
26199 @end itemize
26200
26201 @node Using a network installation of GNAT
26202 @section Using a network installation of GNAT
26203
26204 @noindent
26205 Make sure the system on which GNAT is installed is accessible from the
26206 current machine, i.e. the install location is shared over the network.
26207 Shared resources are accessed on Windows by means of UNC paths, which
26208 have the format @code{\\server\sharename\path}
26209
26210 In order to use such a network installation, simply add the UNC path of the
26211 @file{bin} directory of your GNAT installation in front of your PATH. For
26212 example, if GNAT is installed in @file{\GNAT} directory of a share location
26213 called @file{c-drive} on a machine @file{LOKI}, the following command will
26214 make it available:
26215
26216 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26217
26218 Be aware that every compilation using the network installation results in the
26219 transfer of large amounts of data across the network and will likely cause
26220 serious performance penalty.
26221
26222 @node CONSOLE and WINDOWS subsystems
26223 @section CONSOLE and WINDOWS subsystems
26224 @cindex CONSOLE Subsystem
26225 @cindex WINDOWS Subsystem
26226 @cindex -mwindows
26227
26228 @noindent
26229 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26230 (which is the default subsystem) will always create a console when
26231 launching the application. This is not something desirable when the
26232 application has a Windows GUI. To get rid of this console the
26233 application must be using the @code{WINDOWS} subsystem. To do so
26234 the @option{-mwindows} linker option must be specified.
26235
26236 @smallexample
26237 $ gnatmake winprog -largs -mwindows
26238 @end smallexample
26239
26240 @node Temporary Files
26241 @section Temporary Files
26242 @cindex Temporary files
26243
26244 @noindent
26245 It is possible to control where temporary files gets created by setting
26246 the TMP environment variable. The file will be created:
26247
26248 @itemize
26249 @item Under the directory pointed to by the TMP environment variable if
26250 this directory exists.
26251
26252 @item Under c:\temp, if the TMP environment variable is not set (or not
26253 pointing to a directory) and if this directory exists.
26254
26255 @item Under the current working directory otherwise.
26256 @end itemize
26257
26258 @noindent
26259 This allows you to determine exactly where the temporary
26260 file will be created. This is particularly useful in networked
26261 environments where you may not have write access to some
26262 directories.
26263
26264 @node Mixed-Language Programming on Windows
26265 @section Mixed-Language Programming on Windows
26266
26267 @noindent
26268 Developing pure Ada applications on Windows is no different than on
26269 other GNAT-supported platforms. However, when developing or porting an
26270 application that contains a mix of Ada and C/C++, the choice of your
26271 Windows C/C++ development environment conditions your overall
26272 interoperability strategy.
26273
26274 If you use @code{gcc} to compile the non-Ada part of your application,
26275 there are no Windows-specific restrictions that affect the overall
26276 interoperability with your Ada code. If you plan to use
26277 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26278 the following limitations:
26279
26280 @itemize @bullet
26281 @item
26282 You cannot link your Ada code with an object or library generated with
26283 Microsoft tools if these use the @code{.tls} section (Thread Local
26284 Storage section) since the GNAT linker does not yet support this section.
26285
26286 @item
26287 You cannot link your Ada code with an object or library generated with
26288 Microsoft tools if these use I/O routines other than those provided in
26289 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26290 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26291 libraries can cause a conflict with @code{msvcrt.dll} services. For
26292 instance Visual C++ I/O stream routines conflict with those in
26293 @code{msvcrt.dll}.
26294 @end itemize
26295
26296 @noindent
26297 If you do want to use the Microsoft tools for your non-Ada code and hit one
26298 of the above limitations, you have two choices:
26299
26300 @enumerate
26301 @item
26302 Encapsulate your non Ada code in a DLL to be linked with your Ada
26303 application. In this case, use the Microsoft or whatever environment to
26304 build the DLL and use GNAT to build your executable
26305 (@pxref{Using DLLs with GNAT}).
26306
26307 @item
26308 Or you can encapsulate your Ada code in a DLL to be linked with the
26309 other part of your application. In this case, use GNAT to build the DLL
26310 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26311 environment to build your executable.
26312 @end enumerate
26313
26314 @node Windows Calling Conventions
26315 @section Windows Calling Conventions
26316 @findex Stdcall
26317 @findex APIENTRY
26318
26319 @menu
26320 * C Calling Convention::
26321 * Stdcall Calling Convention::
26322 * DLL Calling Convention::
26323 @end menu
26324
26325 @noindent
26326 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26327 (callee), there are several ways to push @code{G}'s parameters on the
26328 stack and there are several possible scenarios to clean up the stack
26329 upon @code{G}'s return. A calling convention is an agreed upon software
26330 protocol whereby the responsibilities between the caller (@code{F}) and
26331 the callee (@code{G}) are clearly defined. Several calling conventions
26332 are available for Windows:
26333
26334 @itemize @bullet
26335 @item
26336 @code{C} (Microsoft defined)
26337
26338 @item
26339 @code{Stdcall} (Microsoft defined)
26340
26341 @item
26342 @code{DLL} (GNAT specific)
26343 @end itemize
26344
26345 @node C Calling Convention
26346 @subsection @code{C} Calling Convention
26347
26348 @noindent
26349 This is the default calling convention used when interfacing to C/C++
26350 routines compiled with either @code{gcc} or Microsoft Visual C++.
26351
26352 In the @code{C} calling convention subprogram parameters are pushed on the
26353 stack by the caller from right to left. The caller itself is in charge of
26354 cleaning up the stack after the call. In addition, the name of a routine
26355 with @code{C} calling convention is mangled by adding a leading underscore.
26356
26357 The name to use on the Ada side when importing (or exporting) a routine
26358 with @code{C} calling convention is the name of the routine. For
26359 instance the C function:
26360
26361 @smallexample
26362 int get_val (long);
26363 @end smallexample
26364
26365 @noindent
26366 should be imported from Ada as follows:
26367
26368 @smallexample @c ada
26369 @group
26370 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26371 pragma Import (C, Get_Val, External_Name => "get_val");
26372 @end group
26373 @end smallexample
26374
26375 @noindent
26376 Note that in this particular case the @code{External_Name} parameter could
26377 have been omitted since, when missing, this parameter is taken to be the
26378 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26379 is missing, as in the above example, this parameter is set to be the
26380 @code{External_Name} with a leading underscore.
26381
26382 When importing a variable defined in C, you should always use the @code{C}
26383 calling convention unless the object containing the variable is part of a
26384 DLL (in which case you should use the @code{DLL} calling convention,
26385 @pxref{DLL Calling Convention}).
26386
26387 @node Stdcall Calling Convention
26388 @subsection @code{Stdcall} Calling Convention
26389
26390 @noindent
26391 This convention, which was the calling convention used for Pascal
26392 programs, is used by Microsoft for all the routines in the Win32 API for
26393 efficiency reasons. It must be used to import any routine for which this
26394 convention was specified.
26395
26396 In the @code{Stdcall} calling convention subprogram parameters are pushed
26397 on the stack by the caller from right to left. The callee (and not the
26398 caller) is in charge of cleaning the stack on routine exit. In addition,
26399 the name of a routine with @code{Stdcall} calling convention is mangled by
26400 adding a leading underscore (as for the @code{C} calling convention) and a
26401 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26402 bytes) of the parameters passed to the routine.
26403
26404 The name to use on the Ada side when importing a C routine with a
26405 @code{Stdcall} calling convention is the name of the C routine. The leading
26406 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26407 the compiler. For instance the Win32 function:
26408
26409 @smallexample
26410 @b{APIENTRY} int get_val (long);
26411 @end smallexample
26412
26413 @noindent
26414 should be imported from Ada as follows:
26415
26416 @smallexample @c ada
26417 @group
26418 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26419 pragma Import (Stdcall, Get_Val);
26420 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26421 @end group
26422 @end smallexample
26423
26424 @noindent
26425 As for the @code{C} calling convention, when the @code{External_Name}
26426 parameter is missing, it is taken to be the name of the Ada entity in lower
26427 case. If instead of writing the above import pragma you write:
26428
26429 @smallexample @c ada
26430 @group
26431 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26432 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26433 @end group
26434 @end smallexample
26435
26436 @noindent
26437 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26438 of specifying the @code{External_Name} parameter you specify the
26439 @code{Link_Name} as in the following example:
26440
26441 @smallexample @c ada
26442 @group
26443 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26444 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26445 @end group
26446 @end smallexample
26447
26448 @noindent
26449 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26450 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26451 added at the end of the @code{Link_Name} by the compiler.
26452
26453 @noindent
26454 Note, that in some special cases a DLL's entry point name lacks a trailing
26455 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26456 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26457 to handle those cases (see the description of the switches in
26458 @pxref{Using gnatdll} section).
26459
26460 @node DLL Calling Convention
26461 @subsection @code{DLL} Calling Convention
26462
26463 @noindent
26464 This convention, which is GNAT-specific, must be used when you want to
26465 import in Ada a variables defined in a DLL. For functions and procedures
26466 this convention is equivalent to the @code{Stdcall} convention. As an
26467 example, if a DLL contains a variable defined as:
26468
26469 @smallexample
26470 int my_var;
26471 @end smallexample
26472
26473 @noindent
26474 then, to access this variable from Ada you should write:
26475
26476 @smallexample @c ada
26477 @group
26478 My_Var : Interfaces.C.int;
26479 pragma Import (DLL, My_Var);
26480 @end group
26481 @end smallexample
26482
26483 The remarks concerning the @code{External_Name} and @code{Link_Name}
26484 parameters given in the previous sections equally apply to the @code{DLL}
26485 calling convention.
26486
26487 @node Introduction to Dynamic Link Libraries (DLLs)
26488 @section Introduction to Dynamic Link Libraries (DLLs)
26489 @findex DLL
26490
26491 @noindent
26492 A Dynamically Linked Library (DLL) is a library that can be shared by
26493 several applications running under Windows. A DLL can contain any number of
26494 routines and variables.
26495
26496 One advantage of DLLs is that you can change and enhance them without
26497 forcing all the applications that depend on them to be relinked or
26498 recompiled. However, you should be aware than all calls to DLL routines are
26499 slower since, as you will understand below, such calls are indirect.
26500
26501 To illustrate the remainder of this section, suppose that an application
26502 wants to use the services of a DLL @file{API.dll}. To use the services
26503 provided by @file{API.dll} you must statically link against an import
26504 library which contains a jump table with an entry for each routine and
26505 variable exported by the DLL. In the Microsoft world this import library is
26506 called @file{API.lib}. When using GNAT this import library is called either
26507 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26508
26509 After you have statically linked your application with the import library
26510 and you run your application, here is what happens:
26511
26512 @enumerate
26513 @item
26514 Your application is loaded into memory.
26515
26516 @item
26517 The DLL @file{API.dll} is mapped into the address space of your
26518 application. This means that:
26519
26520 @itemize @bullet
26521 @item
26522 The DLL will use the stack of the calling thread.
26523
26524 @item
26525 The DLL will use the virtual address space of the calling process.
26526
26527 @item
26528 The DLL will allocate memory from the virtual address space of the calling
26529 process.
26530
26531 @item
26532 Handles (pointers) can be safely exchanged between routines in the DLL
26533 routines and routines in the application using the DLL.
26534 @end itemize
26535
26536 @item
26537 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
26538 part of your application are initialized with the addresses of the routines
26539 and variables in @file{API.dll}.
26540
26541 @item
26542 If present in @file{API.dll}, routines @code{DllMain} or
26543 @code{DllMainCRTStartup} are invoked. These routines typically contain
26544 the initialization code needed for the well-being of the routines and
26545 variables exported by the DLL.
26546 @end enumerate
26547
26548 @noindent
26549 There is an additional point which is worth mentioning. In the Windows
26550 world there are two kind of DLLs: relocatable and non-relocatable
26551 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26552 in the target application address space. If the addresses of two
26553 non-relocatable DLLs overlap and these happen to be used by the same
26554 application, a conflict will occur and the application will run
26555 incorrectly. Hence, when possible, it is always preferable to use and
26556 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26557 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26558 User's Guide) removes the debugging symbols from the DLL but the DLL can
26559 still be relocated.
26560
26561 As a side note, an interesting difference between Microsoft DLLs and
26562 Unix shared libraries, is the fact that on most Unix systems all public
26563 routines are exported by default in a Unix shared library, while under
26564 Windows the exported routines must be listed explicitly in a definition
26565 file (@pxref{The Definition File}).
26566
26567 @node Using DLLs with GNAT
26568 @section Using DLLs with GNAT
26569
26570 @menu
26571 * Creating an Ada Spec for the DLL Services::
26572 * Creating an Import Library::
26573 @end menu
26574
26575 @noindent
26576 To use the services of a DLL, say @file{API.dll}, in your Ada application
26577 you must have:
26578
26579 @enumerate
26580 @item
26581 The Ada spec for the routines and/or variables you want to access in
26582 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26583 header files provided with the DLL.
26584
26585 @item
26586 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26587 mentioned an import library is a statically linked library containing the
26588 import table which will be filled at load time to point to the actual
26589 @file{API.dll} routines. Sometimes you don't have an import library for the
26590 DLL you want to use. The following sections will explain how to build one.
26591
26592 @item
26593 The actual DLL, @file{API.dll}.
26594 @end enumerate
26595
26596 @noindent
26597 Once you have all the above, to compile an Ada application that uses the
26598 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26599 you simply issue the command
26600
26601 @smallexample
26602 $ gnatmake my_ada_app -largs -lAPI
26603 @end smallexample
26604
26605 @noindent
26606 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26607 tells the GNAT linker to look first for a library named @file{API.lib}
26608 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26609 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26610 contains the following pragma
26611
26612 @smallexample @c ada
26613 pragma Linker_Options ("-lAPI");
26614 @end smallexample
26615
26616 @noindent
26617 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26618 command.
26619
26620 If any one of the items above is missing you will have to create it
26621 yourself. The following sections explain how to do so using as an
26622 example a fictitious DLL called @file{API.dll}.
26623
26624 @node Creating an Ada Spec for the DLL Services
26625 @subsection Creating an Ada Spec for the DLL Services
26626
26627 @noindent
26628 A DLL typically comes with a C/C++ header file which provides the
26629 definitions of the routines and variables exported by the DLL. The Ada
26630 equivalent of this header file is a package spec that contains definitions
26631 for the imported entities. If the DLL you intend to use does not come with
26632 an Ada spec you have to generate one such spec yourself. For example if
26633 the header file of @file{API.dll} is a file @file{api.h} containing the
26634 following two definitions:
26635
26636 @smallexample
26637 @group
26638 @cartouche
26639 int some_var;
26640 int get (char *);
26641 @end cartouche
26642 @end group
26643 @end smallexample
26644
26645 @noindent
26646 then the equivalent Ada spec could be:
26647
26648 @smallexample @c ada
26649 @group
26650 @cartouche
26651 with Interfaces.C.Strings;
26652 package API is
26653    use Interfaces;
26654
26655    Some_Var : C.int;
26656    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26657
26658 private
26659    pragma Import (C, Get);
26660    pragma Import (DLL, Some_Var);
26661 end API;
26662 @end cartouche
26663 @end group
26664 @end smallexample
26665
26666 @noindent
26667 Note that a variable is @strong{always imported with a DLL convention}. A
26668 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26669 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26670 (@pxref{Windows Calling Conventions}).
26671
26672 @node Creating an Import Library
26673 @subsection Creating an Import Library
26674 @cindex Import library
26675
26676 @menu
26677 * The Definition File::
26678 * GNAT-Style Import Library::
26679 * Microsoft-Style Import Library::
26680 @end menu
26681
26682 @noindent
26683 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26684 import library @file{libAPI.a} is available with @file{API.dll} you
26685 can skip this section. Otherwise read on.
26686
26687 @node The Definition File
26688 @subsubsection The Definition File
26689 @cindex Definition file
26690 @findex .def
26691
26692 @noindent
26693 As previously mentioned, and unlike Unix systems, the list of symbols
26694 that are exported from a DLL must be provided explicitly in Windows.
26695 The main goal of a definition file is precisely that: list the symbols
26696 exported by a DLL. A definition file (usually a file with a @code{.def}
26697 suffix) has the following structure:
26698
26699 @smallexample
26700 @group
26701 @cartouche
26702 [LIBRARY @i{name}]
26703 [DESCRIPTION @i{string}]
26704 EXPORTS
26705    @i{symbol1}
26706    @i{symbol2}
26707    ...
26708 @end cartouche
26709 @end group
26710 @end smallexample
26711
26712 @table @code
26713 @item LIBRARY @i{name}
26714 This section, which is optional, gives the name of the DLL.
26715
26716 @item DESCRIPTION @i{string}
26717 This section, which is optional, gives a description string that will be
26718 embedded in the import library.
26719
26720 @item EXPORTS
26721 This section gives the list of exported symbols (procedures, functions or
26722 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26723 section of @file{API.def} looks like:
26724
26725 @smallexample
26726 @group
26727 @cartouche
26728 EXPORTS
26729    some_var
26730    get
26731 @end cartouche
26732 @end group
26733 @end smallexample
26734 @end table
26735
26736 @noindent
26737 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26738 (@pxref{Windows Calling Conventions}) for a Stdcall
26739 calling convention function in the exported symbols list.
26740
26741 @noindent
26742 There can actually be other sections in a definition file, but these
26743 sections are not relevant to the discussion at hand.
26744
26745 @node GNAT-Style Import Library
26746 @subsubsection GNAT-Style Import Library
26747
26748 @noindent
26749 To create a static import library from @file{API.dll} with the GNAT tools
26750 you should proceed as follows:
26751
26752 @enumerate
26753 @item
26754 Create the definition file @file{API.def} (@pxref{The Definition File}).
26755 For that use the @code{dll2def} tool as follows:
26756
26757 @smallexample
26758 $ dll2def API.dll > API.def
26759 @end smallexample
26760
26761 @noindent
26762 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26763 to standard output the list of entry points in the DLL. Note that if
26764 some routines in the DLL have the @code{Stdcall} convention
26765 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26766 suffix then you'll have to edit @file{api.def} to add it, and specify
26767 @code{-k} to @code{gnatdll} when creating the import library.
26768
26769 @noindent
26770 Here are some hints to find the right @code{@@}@i{nn} suffix.
26771
26772 @enumerate
26773 @item
26774 If you have the Microsoft import library (.lib), it is possible to get
26775 the right symbols by using Microsoft @code{dumpbin} tool (see the
26776 corresponding Microsoft documentation for further details).
26777
26778 @smallexample
26779 $ dumpbin /exports api.lib
26780 @end smallexample
26781
26782 @item
26783 If you have a message about a missing symbol at link time the compiler
26784 tells you what symbol is expected. You just have to go back to the
26785 definition file and add the right suffix.
26786 @end enumerate
26787
26788 @item
26789 Build the import library @code{libAPI.a}, using @code{gnatdll}
26790 (@pxref{Using gnatdll}) as follows:
26791
26792 @smallexample
26793 $ gnatdll -e API.def -d API.dll
26794 @end smallexample
26795
26796 @noindent
26797 @code{gnatdll} takes as input a definition file @file{API.def} and the
26798 name of the DLL containing the services listed in the definition file
26799 @file{API.dll}. The name of the static import library generated is
26800 computed from the name of the definition file as follows: if the
26801 definition file name is @i{xyz}@code{.def}, the import library name will
26802 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26803 @option{-e} could have been removed because the name of the definition
26804 file (before the ``@code{.def}'' suffix) is the same as the name of the
26805 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26806 @end enumerate
26807
26808 @node Microsoft-Style Import Library
26809 @subsubsection Microsoft-Style Import Library
26810
26811 @noindent
26812 With GNAT you can either use a GNAT-style or Microsoft-style import
26813 library. A Microsoft import library is needed only if you plan to make an
26814 Ada DLL available to applications developed with Microsoft
26815 tools (@pxref{Mixed-Language Programming on Windows}).
26816
26817 To create a Microsoft-style import library for @file{API.dll} you
26818 should proceed as follows:
26819
26820 @enumerate
26821 @item
26822 Create the definition file @file{API.def} from the DLL. For this use either
26823 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26824 tool (see the corresponding Microsoft documentation for further details).
26825
26826 @item
26827 Build the actual import library using Microsoft's @code{lib} utility:
26828
26829 @smallexample
26830 $ lib -machine:IX86 -def:API.def -out:API.lib
26831 @end smallexample
26832
26833 @noindent
26834 If you use the above command the definition file @file{API.def} must
26835 contain a line giving the name of the DLL:
26836
26837 @smallexample
26838 LIBRARY      "API"
26839 @end smallexample
26840
26841 @noindent
26842 See the Microsoft documentation for further details about the usage of
26843 @code{lib}.
26844 @end enumerate
26845
26846 @node Building DLLs with GNAT
26847 @section Building DLLs with GNAT
26848 @cindex DLLs, building
26849
26850 @menu
26851 * Limitations When Using Ada DLLs from Ada::
26852 * Exporting Ada Entities::
26853 * Ada DLLs and Elaboration::
26854 * Ada DLLs and Finalization::
26855 * Creating a Spec for Ada DLLs::
26856 * Creating the Definition File::
26857 * Using gnatdll::
26858 @end menu
26859
26860 @noindent
26861 This section explains how to build DLLs containing Ada code. These DLLs
26862 will be referred to as Ada DLLs in the remainder of this section.
26863
26864 The steps required to build an Ada DLL that is to be used by Ada as well as
26865 non-Ada applications are as follows:
26866
26867 @enumerate
26868 @item
26869 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26870 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26871 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26872 skip this step if you plan to use the Ada DLL only from Ada applications.
26873
26874 @item
26875 Your Ada code must export an initialization routine which calls the routine
26876 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26877 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26878 routine exported by the Ada DLL must be invoked by the clients of the DLL
26879 to initialize the DLL.
26880
26881 @item
26882 When useful, the DLL should also export a finalization routine which calls
26883 routine @code{adafinal} generated by @code{gnatbind} to perform the
26884 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26885 The finalization routine exported by the Ada DLL must be invoked by the
26886 clients of the DLL when the DLL services are no further needed.
26887
26888 @item
26889 You must provide a spec for the services exported by the Ada DLL in each
26890 of the programming languages to which you plan to make the DLL available.
26891
26892 @item
26893 You must provide a definition file listing the exported entities
26894 (@pxref{The Definition File}).
26895
26896 @item
26897 Finally you must use @code{gnatdll} to produce the DLL and the import
26898 library (@pxref{Using gnatdll}).
26899 @end enumerate
26900
26901 @noindent
26902 Note that a relocatable DLL stripped using the @code{strip} binutils
26903 tool will not be relocatable anymore. To build a DLL without debug
26904 information pass @code{-largs -s} to @code{gnatdll}.
26905
26906 @node Limitations When Using Ada DLLs from Ada
26907 @subsection Limitations When Using Ada DLLs from Ada
26908
26909 @noindent
26910 When using Ada DLLs from Ada applications there is a limitation users
26911 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26912 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26913 each Ada DLL includes the services of the GNAT run time that are necessary
26914 to the Ada code inside the DLL. As a result, when an Ada program uses an
26915 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26916 one in the main program.
26917
26918 It is therefore not possible to exchange GNAT run-time objects between the
26919 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26920 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26921 types, etc.
26922
26923 It is completely safe to exchange plain elementary, array or record types,
26924 Windows object handles, etc.
26925
26926 @node Exporting Ada Entities
26927 @subsection Exporting Ada Entities
26928 @cindex Export table
26929
26930 @noindent
26931 Building a DLL is a way to encapsulate a set of services usable from any
26932 application. As a result, the Ada entities exported by a DLL should be
26933 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26934 any Ada name mangling. Please note that the @code{Stdcall} convention
26935 should only be used for subprograms, not for variables. As an example here
26936 is an Ada package @code{API}, spec and body, exporting two procedures, a
26937 function, and a variable:
26938
26939 @smallexample @c ada
26940 @group
26941 @cartouche
26942 with Interfaces.C; use Interfaces;
26943 package API is
26944    Count : C.int := 0;
26945    function Factorial (Val : C.int) return C.int;
26946
26947    procedure Initialize_API;
26948    procedure Finalize_API;
26949    --  Initialization & Finalization routines. More in the next section.
26950 private
26951    pragma Export (C, Initialize_API);
26952    pragma Export (C, Finalize_API);
26953    pragma Export (C, Count);
26954    pragma Export (C, Factorial);
26955 end API;
26956 @end cartouche
26957 @end group
26958 @end smallexample
26959
26960 @smallexample @c ada
26961 @group
26962 @cartouche
26963 package body API is
26964    function Factorial (Val : C.int) return C.int is
26965       Fact : C.int := 1;
26966    begin
26967       Count := Count + 1;
26968       for K in 1 .. Val loop
26969          Fact := Fact * K;
26970       end loop;
26971       return Fact;
26972    end Factorial;
26973
26974    procedure Initialize_API is
26975       procedure Adainit;
26976       pragma Import (C, Adainit);
26977    begin
26978       Adainit;
26979    end Initialize_API;
26980
26981    procedure Finalize_API is
26982       procedure Adafinal;
26983       pragma Import (C, Adafinal);
26984    begin
26985       Adafinal;
26986    end Finalize_API;
26987 end API;
26988 @end cartouche
26989 @end group
26990 @end smallexample
26991
26992 @noindent
26993 If the Ada DLL you are building will only be used by Ada applications
26994 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26995 convention. As an example, the previous package could be written as
26996 follows:
26997
26998 @smallexample @c ada
26999 @group
27000 @cartouche
27001 package API is
27002    Count : Integer := 0;
27003    function Factorial (Val : Integer) return Integer;
27004
27005    procedure Initialize_API;
27006    procedure Finalize_API;
27007    --  Initialization and Finalization routines.
27008 end API;
27009 @end cartouche
27010 @end group
27011 @end smallexample
27012
27013 @smallexample @c ada
27014 @group
27015 @cartouche
27016 package body API is
27017    function Factorial (Val : Integer) return Integer is
27018       Fact : Integer := 1;
27019    begin
27020       Count := Count + 1;
27021       for K in 1 .. Val loop
27022          Fact := Fact * K;
27023       end loop;
27024       return Fact;
27025    end Factorial;
27026
27027    ...
27028    --  The remainder of this package body is unchanged.
27029 end API;
27030 @end cartouche
27031 @end group
27032 @end smallexample
27033
27034 @noindent
27035 Note that if you do not export the Ada entities with a @code{C} or
27036 @code{Stdcall} convention you will have to provide the mangled Ada names
27037 in the definition file of the Ada DLL
27038 (@pxref{Creating the Definition File}).
27039
27040 @node Ada DLLs and Elaboration
27041 @subsection Ada DLLs and Elaboration
27042 @cindex DLLs and elaboration
27043
27044 @noindent
27045 The DLL that you are building contains your Ada code as well as all the
27046 routines in the Ada library that are needed by it. The first thing a
27047 user of your DLL must do is elaborate the Ada code
27048 (@pxref{Elaboration Order Handling in GNAT}).
27049
27050 To achieve this you must export an initialization routine
27051 (@code{Initialize_API} in the previous example), which must be invoked
27052 before using any of the DLL services. This elaboration routine must call
27053 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27054 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27055 @code{Initialize_Api} for an example. Note that the GNAT binder is
27056 automatically invoked during the DLL build process by the @code{gnatdll}
27057 tool (@pxref{Using gnatdll}).
27058
27059 When a DLL is loaded, Windows systematically invokes a routine called
27060 @code{DllMain}. It would therefore be possible to call @code{adainit}
27061 directly from @code{DllMain} without having to provide an explicit
27062 initialization routine. Unfortunately, it is not possible to call
27063 @code{adainit} from the @code{DllMain} if your program has library level
27064 tasks because access to the @code{DllMain} entry point is serialized by
27065 the system (that is, only a single thread can execute ``through'' it at a
27066 time), which means that the GNAT run time will deadlock waiting for the
27067 newly created task to complete its initialization.
27068
27069 @node Ada DLLs and Finalization
27070 @subsection Ada DLLs and Finalization
27071 @cindex DLLs and finalization
27072
27073 @noindent
27074 When the services of an Ada DLL are no longer needed, the client code should
27075 invoke the DLL finalization routine, if available. The DLL finalization
27076 routine is in charge of releasing all resources acquired by the DLL. In the
27077 case of the Ada code contained in the DLL, this is achieved by calling
27078 routine @code{adafinal} generated by the GNAT binder
27079 (@pxref{Binding with Non-Ada Main Programs}).
27080 See the body of @code{Finalize_Api} for an
27081 example. As already pointed out the GNAT binder is automatically invoked
27082 during the DLL build process by the @code{gnatdll} tool
27083 (@pxref{Using gnatdll}).
27084
27085 @node Creating a Spec for Ada DLLs
27086 @subsection Creating a Spec for Ada DLLs
27087
27088 @noindent
27089 To use the services exported by the Ada DLL from another programming
27090 language (e.g. C), you have to translate the specs of the exported Ada
27091 entities in that language. For instance in the case of @code{API.dll},
27092 the corresponding C header file could look like:
27093
27094 @smallexample
27095 @group
27096 @cartouche
27097 extern int *_imp__count;
27098 #define count (*_imp__count)
27099 int factorial (int);
27100 @end cartouche
27101 @end group
27102 @end smallexample
27103
27104 @noindent
27105 It is important to understand that when building an Ada DLL to be used by
27106 other Ada applications, you need two different specs for the packages
27107 contained in the DLL: one for building the DLL and the other for using
27108 the DLL. This is because the @code{DLL} calling convention is needed to
27109 use a variable defined in a DLL, but when building the DLL, the variable
27110 must have either the @code{Ada} or @code{C} calling convention. As an
27111 example consider a DLL comprising the following package @code{API}:
27112
27113 @smallexample @c ada
27114 @group
27115 @cartouche
27116 package API is
27117    Count : Integer := 0;
27118    ...
27119    --  Remainder of the package omitted.
27120 end API;
27121 @end cartouche
27122 @end group
27123 @end smallexample
27124
27125 @noindent
27126 After producing a DLL containing package @code{API}, the spec that
27127 must be used to import @code{API.Count} from Ada code outside of the
27128 DLL is:
27129
27130 @smallexample @c ada
27131 @group
27132 @cartouche
27133 package API is
27134    Count : Integer;
27135    pragma Import (DLL, Count);
27136 end API;
27137 @end cartouche
27138 @end group
27139 @end smallexample
27140
27141 @node Creating the Definition File
27142 @subsection Creating the Definition File
27143
27144 @noindent
27145 The definition file is the last file needed to build the DLL. It lists
27146 the exported symbols. As an example, the definition file for a DLL
27147 containing only package @code{API} (where all the entities are exported
27148 with a @code{C} calling convention) is:
27149
27150 @smallexample
27151 @group
27152 @cartouche
27153 EXPORTS
27154     count
27155     factorial
27156     finalize_api
27157     initialize_api
27158 @end cartouche
27159 @end group
27160 @end smallexample
27161
27162 @noindent
27163 If the @code{C} calling convention is missing from package @code{API},
27164 then the definition file contains the mangled Ada names of the above
27165 entities, which in this case are:
27166
27167 @smallexample
27168 @group
27169 @cartouche
27170 EXPORTS
27171     api__count
27172     api__factorial
27173     api__finalize_api
27174     api__initialize_api
27175 @end cartouche
27176 @end group
27177 @end smallexample
27178
27179 @node Using gnatdll
27180 @subsection Using @code{gnatdll}
27181 @findex gnatdll
27182
27183 @menu
27184 * gnatdll Example::
27185 * gnatdll behind the Scenes::
27186 * Using dlltool::
27187 @end menu
27188
27189 @noindent
27190 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27191 and non-Ada sources that make up your DLL have been compiled.
27192 @code{gnatdll} is actually in charge of two distinct tasks: build the
27193 static import library for the DLL and the actual DLL. The form of the
27194 @code{gnatdll} command is
27195
27196 @smallexample
27197 @cartouche
27198 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27199 @end cartouche
27200 @end smallexample
27201
27202 @noindent
27203 where @i{list-of-files} is a list of ALI and object files. The object
27204 file list must be the exact list of objects corresponding to the non-Ada
27205 sources whose services are to be included in the DLL. The ALI file list
27206 must be the exact list of ALI files for the corresponding Ada sources
27207 whose services are to be included in the DLL. If @i{list-of-files} is
27208 missing, only the static import library is generated.
27209
27210 @noindent
27211 You may specify any of the following switches to @code{gnatdll}:
27212
27213 @table @code
27214 @item -a[@var{address}]
27215 @cindex @option{-a} (@code{gnatdll})
27216 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27217 specified the default address @var{0x11000000} will be used. By default,
27218 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27219 advise the reader to build relocatable DLL.
27220
27221 @item -b @var{address}
27222 @cindex @option{-b} (@code{gnatdll})
27223 Set the relocatable DLL base address. By default the address is
27224 @var{0x11000000}.
27225
27226 @item -bargs @var{opts}
27227 @cindex @option{-bargs} (@code{gnatdll})
27228 Binder options. Pass @var{opts} to the binder.
27229
27230 @item -d @var{dllfile}
27231 @cindex @option{-d} (@code{gnatdll})
27232 @var{dllfile} is the name of the DLL. This switch must be present for
27233 @code{gnatdll} to do anything. The name of the generated import library is
27234 obtained algorithmically from @var{dllfile} as shown in the following
27235 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27236 @code{libxyz.a}. The name of the definition file to use (if not specified
27237 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27238 as shown in the following example:
27239 if @var{dllfile} is @code{xyz.dll}, the definition
27240 file used is @code{xyz.def}.
27241
27242 @item -e @var{deffile}
27243 @cindex @option{-e} (@code{gnatdll})
27244 @var{deffile} is the name of the definition file.
27245
27246 @item -g
27247 @cindex @option{-g} (@code{gnatdll})
27248 Generate debugging information. This information is stored in the object
27249 file and copied from there to the final DLL file by the linker,
27250 where it can be read by the debugger. You must use the
27251 @option{-g} switch if you plan on using the debugger or the symbolic
27252 stack traceback.
27253
27254 @item -h
27255 @cindex @option{-h} (@code{gnatdll})
27256 Help mode. Displays @code{gnatdll} switch usage information.
27257
27258 @item -Idir
27259 @cindex @option{-I} (@code{gnatdll})
27260 Direct @code{gnatdll} to search the @var{dir} directory for source and
27261 object files needed to build the DLL.
27262 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27263
27264 @item -k
27265 @cindex @option{-k} (@code{gnatdll})
27266 Removes the @code{@@}@i{nn} suffix from the import library's exported
27267 names, but keeps them for the link names. You must specify this
27268 option if you want to use a @code{Stdcall} function in a DLL for which
27269 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27270 of the Windows NT DLL for example. This option has no effect when
27271 @option{-n} option is specified.
27272
27273 @item -l @var{file}
27274 @cindex @option{-l} (@code{gnatdll})
27275 The list of ALI and object files used to build the DLL are listed in
27276 @var{file}, instead of being given in the command line. Each line in
27277 @var{file} contains the name of an ALI or object file.
27278
27279 @item -n
27280 @cindex @option{-n} (@code{gnatdll})
27281 No Import. Do not create the import library.
27282
27283 @item -q
27284 @cindex @option{-q} (@code{gnatdll})
27285 Quiet mode. Do not display unnecessary messages.
27286
27287 @item -v
27288 @cindex @option{-v} (@code{gnatdll})
27289 Verbose mode. Display extra information.
27290
27291 @item -largs @var{opts}
27292 @cindex @option{-largs} (@code{gnatdll})
27293 Linker options. Pass @var{opts} to the linker.
27294 @end table
27295
27296 @node gnatdll Example
27297 @subsubsection @code{gnatdll} Example
27298
27299 @noindent
27300 As an example the command to build a relocatable DLL from @file{api.adb}
27301 once @file{api.adb} has been compiled and @file{api.def} created is
27302
27303 @smallexample
27304 $ gnatdll -d api.dll api.ali
27305 @end smallexample
27306
27307 @noindent
27308 The above command creates two files: @file{libapi.a} (the import
27309 library) and @file{api.dll} (the actual DLL). If you want to create
27310 only the DLL, just type:
27311
27312 @smallexample
27313 $ gnatdll -d api.dll -n api.ali
27314 @end smallexample
27315
27316 @noindent
27317 Alternatively if you want to create just the import library, type:
27318
27319 @smallexample
27320 $ gnatdll -d api.dll
27321 @end smallexample
27322
27323 @node gnatdll behind the Scenes
27324 @subsubsection @code{gnatdll} behind the Scenes
27325
27326 @noindent
27327 This section details the steps involved in creating a DLL. @code{gnatdll}
27328 does these steps for you. Unless you are interested in understanding what
27329 goes on behind the scenes, you should skip this section.
27330
27331 We use the previous example of a DLL containing the Ada package @code{API},
27332 to illustrate the steps necessary to build a DLL. The starting point is a
27333 set of objects that will make up the DLL and the corresponding ALI
27334 files. In the case of this example this means that @file{api.o} and
27335 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27336 the following:
27337
27338 @enumerate
27339 @item
27340 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27341 the information necessary to generate relocation information for the
27342 DLL.
27343
27344 @smallexample
27345 @group
27346 $ gnatbind -n api
27347 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27348 @end group
27349 @end smallexample
27350
27351 @noindent
27352 In addition to the base file, the @code{gnatlink} command generates an
27353 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27354 asks @code{gnatlink} to generate the routines @code{DllMain} and
27355 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27356 is loaded into memory.
27357
27358 @item
27359 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27360 export table (@file{api.exp}). The export table contains the relocation
27361 information in a form which can be used during the final link to ensure
27362 that the Windows loader is able to place the DLL anywhere in memory.
27363
27364 @smallexample
27365 @group
27366 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27367           --output-exp api.exp
27368 @end group
27369 @end smallexample
27370
27371 @item
27372 @code{gnatdll} builds the base file using the new export table. Note that
27373 @code{gnatbind} must be called once again since the binder generated file
27374 has been deleted during the previous call to @code{gnatlink}.
27375
27376 @smallexample
27377 @group
27378 $ gnatbind -n api
27379 $ gnatlink api -o api.jnk api.exp -mdll
27380       -Wl,--base-file,api.base
27381 @end group
27382 @end smallexample
27383
27384 @item
27385 @code{gnatdll} builds the new export table using the new base file and
27386 generates the DLL import library @file{libAPI.a}.
27387
27388 @smallexample
27389 @group
27390 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27391           --output-exp api.exp --output-lib libAPI.a
27392 @end group
27393 @end smallexample
27394
27395 @item
27396 Finally @code{gnatdll} builds the relocatable DLL using the final export
27397 table.
27398
27399 @smallexample
27400 @group
27401 $ gnatbind -n api
27402 $ gnatlink api api.exp -o api.dll -mdll
27403 @end group
27404 @end smallexample
27405 @end enumerate
27406
27407 @node Using dlltool
27408 @subsubsection Using @code{dlltool}
27409
27410 @noindent
27411 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27412 DLLs and static import libraries. This section summarizes the most
27413 common @code{dlltool} switches. The form of the @code{dlltool} command
27414 is
27415
27416 @smallexample
27417 $ dlltool [@var{switches}]
27418 @end smallexample
27419
27420 @noindent
27421 @code{dlltool} switches include:
27422
27423 @table @option
27424 @item --base-file @var{basefile}
27425 @cindex @option{--base-file} (@command{dlltool})
27426 Read the base file @var{basefile} generated by the linker. This switch
27427 is used to create a relocatable DLL.
27428
27429 @item --def @var{deffile}
27430 @cindex @option{--def} (@command{dlltool})
27431 Read the definition file.
27432
27433 @item --dllname @var{name}
27434 @cindex @option{--dllname} (@command{dlltool})
27435 Gives the name of the DLL. This switch is used to embed the name of the
27436 DLL in the static import library generated by @code{dlltool} with switch
27437 @option{--output-lib}.
27438
27439 @item -k
27440 @cindex @option{-k} (@command{dlltool})
27441 Kill @code{@@}@i{nn} from exported names
27442 (@pxref{Windows Calling Conventions}
27443 for a discussion about @code{Stdcall}-style symbols.
27444
27445 @item --help
27446 @cindex @option{--help} (@command{dlltool})
27447 Prints the @code{dlltool} switches with a concise description.
27448
27449 @item --output-exp @var{exportfile}
27450 @cindex @option{--output-exp} (@command{dlltool})
27451 Generate an export file @var{exportfile}. The export file contains the
27452 export table (list of symbols in the DLL) and is used to create the DLL.
27453
27454 @item --output-lib @i{libfile}
27455 @cindex @option{--output-lib} (@command{dlltool})
27456 Generate a static import library @var{libfile}.
27457
27458 @item -v
27459 @cindex @option{-v} (@command{dlltool})
27460 Verbose mode.
27461
27462 @item --as @i{assembler-name}
27463 @cindex @option{--as} (@command{dlltool})
27464 Use @i{assembler-name} as the assembler. The default is @code{as}.
27465 @end table
27466
27467 @node GNAT and Windows Resources
27468 @section GNAT and Windows Resources
27469 @cindex Resources, windows
27470
27471 @menu
27472 * Building Resources::
27473 * Compiling Resources::
27474 * Using Resources::
27475 @end menu
27476
27477 @noindent
27478 Resources are an easy way to add Windows specific objects to your
27479 application. The objects that can be added as resources include:
27480
27481 @itemize @bullet
27482 @item
27483 menus
27484
27485 @item
27486 accelerators
27487
27488 @item
27489 dialog boxes
27490
27491 @item
27492 string tables
27493
27494 @item
27495 bitmaps
27496
27497 @item
27498 cursors
27499
27500 @item
27501 icons
27502
27503 @item
27504 fonts
27505 @end itemize
27506
27507 @noindent
27508 This section explains how to build, compile and use resources.
27509
27510 @node Building Resources
27511 @subsection Building Resources
27512 @cindex Resources, building
27513
27514 @noindent
27515 A resource file is an ASCII file. By convention resource files have an
27516 @file{.rc} extension.
27517 The easiest way to build a resource file is to use Microsoft tools
27518 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27519 @code{dlgedit.exe} to build dialogs.
27520 It is always possible to build an @file{.rc} file yourself by writing a
27521 resource script.
27522
27523 It is not our objective to explain how to write a resource file. A
27524 complete description of the resource script language can be found in the
27525 Microsoft documentation.
27526
27527 @node Compiling Resources
27528 @subsection Compiling Resources
27529 @findex rc
27530 @findex windres
27531 @cindex Resources, compiling
27532
27533 @noindent
27534 This section describes how to build a GNAT-compatible (COFF) object file
27535 containing the resources. This is done using the Resource Compiler
27536 @code{windres} as follows:
27537
27538 @smallexample
27539 $ windres -i myres.rc -o myres.o
27540 @end smallexample
27541
27542 @noindent
27543 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27544 file. You can specify an alternate preprocessor (usually named
27545 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27546 parameter. A list of all possible options may be obtained by entering
27547 the command @code{windres} @option{--help}.
27548
27549 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27550 to produce a @file{.res} file (binary resource file). See the
27551 corresponding Microsoft documentation for further details. In this case
27552 you need to use @code{windres} to translate the @file{.res} file to a
27553 GNAT-compatible object file as follows:
27554
27555 @smallexample
27556 $ windres -i myres.res -o myres.o
27557 @end smallexample
27558
27559 @node Using Resources
27560 @subsection Using Resources
27561 @cindex Resources, using
27562
27563 @noindent
27564 To include the resource file in your program just add the
27565 GNAT-compatible object file for the resource(s) to the linker
27566 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27567 option:
27568
27569 @smallexample
27570 $ gnatmake myprog -largs myres.o
27571 @end smallexample
27572
27573 @node Debugging a DLL
27574 @section Debugging a DLL
27575 @cindex DLL debugging
27576
27577 @menu
27578 * Program and DLL Both Built with GCC/GNAT::
27579 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27580 @end menu
27581
27582 @noindent
27583 Debugging a DLL is similar to debugging a standard program. But
27584 we have to deal with two different executable parts: the DLL and the
27585 program that uses it. We have the following four possibilities:
27586
27587 @enumerate 1
27588 @item
27589 The program and the DLL are built with @code{GCC/GNAT}.
27590 @item
27591 The program is built with foreign tools and the DLL is built with
27592 @code{GCC/GNAT}.
27593 @item
27594 The program is built with @code{GCC/GNAT} and the DLL is built with
27595 foreign tools.
27596 @item
27597 @end enumerate
27598
27599 @noindent
27600 In this section we address only cases one and two above.
27601 There is no point in trying to debug
27602 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27603 information in it. To do so you must use a debugger compatible with the
27604 tools suite used to build the DLL.
27605
27606 @node Program and DLL Both Built with GCC/GNAT
27607 @subsection Program and DLL Both Built with GCC/GNAT
27608
27609 @noindent
27610 This is the simplest case. Both the DLL and the program have @code{GDB}
27611 compatible debugging information. It is then possible to break anywhere in
27612 the process. Let's suppose here that the main procedure is named
27613 @code{ada_main} and that in the DLL there is an entry point named
27614 @code{ada_dll}.
27615
27616 @noindent
27617 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27618 program must have been built with the debugging information (see GNAT -g
27619 switch). Here are the step-by-step instructions for debugging it:
27620
27621 @enumerate 1
27622 @item Launch @code{GDB} on the main program.
27623
27624 @smallexample
27625 $ gdb -nw ada_main
27626 @end smallexample
27627
27628 @item Break on the main procedure and run the program.
27629
27630 @smallexample
27631 (gdb) break ada_main
27632 (gdb) run
27633 @end smallexample
27634
27635 @noindent
27636 This step is required to be able to set a breakpoint inside the DLL. As long
27637 as the program is not run, the DLL is not loaded. This has the
27638 consequence that the DLL debugging information is also not loaded, so it is not
27639 possible to set a breakpoint in the DLL.
27640
27641 @item Set a breakpoint inside the DLL
27642
27643 @smallexample
27644 (gdb) break ada_dll
27645 (gdb) run
27646 @end smallexample
27647
27648 @end enumerate
27649
27650 @noindent
27651 At this stage a breakpoint is set inside the DLL. From there on
27652 you can use the standard approach to debug the whole program
27653 (@pxref{Running and Debugging Ada Programs}).
27654
27655 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27656 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27657
27658 @menu
27659 * Debugging the DLL Directly::
27660 * Attaching to a Running Process::
27661 @end menu
27662
27663 @noindent
27664 In this case things are slightly more complex because it is not possible to
27665 start the main program and then break at the beginning to load the DLL and the
27666 associated DLL debugging information. It is not possible to break at the
27667 beginning of the program because there is no @code{GDB} debugging information,
27668 and therefore there is no direct way of getting initial control. This
27669 section addresses this issue by describing some methods that can be used
27670 to break somewhere in the DLL to debug it.
27671
27672 @noindent
27673 First suppose that the main procedure is named @code{main} (this is for
27674 example some C code built with Microsoft Visual C) and that there is a
27675 DLL named @code{test.dll} containing an Ada entry point named
27676 @code{ada_dll}.
27677
27678 @noindent
27679 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27680 been built with debugging information (see GNAT -g option).
27681
27682 @node Debugging the DLL Directly
27683 @subsubsection Debugging the DLL Directly
27684
27685 @enumerate 1
27686 @item
27687 Launch the debugger on the DLL.
27688
27689 @smallexample
27690 $ gdb -nw test.dll
27691 @end smallexample
27692
27693 @item Set a breakpoint on a DLL subroutine.
27694
27695 @smallexample
27696 (gdb) break ada_dll
27697 @end smallexample
27698
27699 @item
27700 Specify the executable file to @code{GDB}.
27701
27702 @smallexample
27703 (gdb) exec-file main.exe
27704 @end smallexample
27705
27706 @item
27707 Run the program.
27708
27709 @smallexample
27710 (gdb) run
27711 @end smallexample
27712
27713 @noindent
27714 This will run the program until it reaches the breakpoint that has been
27715 set. From that point you can use the standard way to debug a program
27716 as described in (@pxref{Running and Debugging Ada Programs}).
27717
27718 @end enumerate
27719
27720 @noindent
27721 It is also possible to debug the DLL by attaching to a running process.
27722
27723 @node Attaching to a Running Process
27724 @subsubsection Attaching to a Running Process
27725 @cindex DLL debugging, attach to process
27726
27727 @noindent
27728 With @code{GDB} it is always possible to debug a running process by
27729 attaching to it. It is possible to debug a DLL this way. The limitation
27730 of this approach is that the DLL must run long enough to perform the
27731 attach operation. It may be useful for instance to insert a time wasting
27732 loop in the code of the DLL to meet this criterion.
27733
27734 @enumerate 1
27735
27736 @item Launch the main program @file{main.exe}.
27737
27738 @smallexample
27739 $ main
27740 @end smallexample
27741
27742 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27743 that the process PID for @file{main.exe} is 208.
27744
27745 @item Launch gdb.
27746
27747 @smallexample
27748 $ gdb -nw
27749 @end smallexample
27750
27751 @item Attach to the running process to be debugged.
27752
27753 @smallexample
27754 (gdb) attach 208
27755 @end smallexample
27756
27757 @item Load the process debugging information.
27758
27759 @smallexample
27760 (gdb) symbol-file main.exe
27761 @end smallexample
27762
27763 @item Break somewhere in the DLL.
27764
27765 @smallexample
27766 (gdb) break ada_dll
27767 @end smallexample
27768
27769 @item Continue process execution.
27770
27771 @smallexample
27772 (gdb) continue
27773 @end smallexample
27774
27775 @end enumerate
27776
27777 @noindent
27778 This last step will resume the process execution, and stop at
27779 the breakpoint we have set. From there you can use the standard
27780 approach to debug a program as described in
27781 (@pxref{Running and Debugging Ada Programs}).
27782
27783 @node GNAT and COM/DCOM Objects
27784 @section GNAT and COM/DCOM Objects
27785 @findex COM
27786 @findex DCOM
27787
27788 @noindent
27789 This section is temporarily left blank.
27790
27791 @end ifset
27792
27793
27794 @c **********************************
27795 @c * GNU Free Documentation License *
27796 @c **********************************
27797 @include fdl.texi
27798 @c GNU Free Documentation License
27799
27800 @node Index,,GNU Free Documentation License, Top
27801 @unnumbered Index
27802
27803 @printindex cp
27804
27805 @contents
27806 @c Put table of contents at end, otherwise it precedes the "title page" in
27807 @c the .txt version
27808 @c Edit the pdf file to move the contents to the beginning, after the title
27809 @c page
27810
27811 @bye