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
110Copyright @copyright{} 1995-2004, Free Software Foundation
111
112Permission is granted to copy, distribute and/or modify this document
113under the terms of the GNU Free Documentation License, Version 1.2
114or any later version published by the Free Software Foundation;
115with the Invariant Sections being ``GNU Free Documentation License'', with the
116Front-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
123and with no Back-Cover Texts.
124A 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
163GNAT User's Guide for Native Platforms / OpenVMS Alpha
164@end ifset
165
166@ifset unw
167@noindent
168GNAT User's Guide for Native Platforms / Unix and Windows
169@end ifset
170
171@noindent
172GNAT, The GNU Ada 95 Compiler@*
173GCC version @value{version-GCC}@*
174
175@noindent
176Ada 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
224About This Guide
225
226* What This Guide Contains::
227* What You Should Know before Reading This Guide::
228* Related Information::
229* Conventions::
230
231Getting 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
245The 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
264Foreign Language Representation
265
266* Latin-1::
267* Other 8-Bit Codes::
268* Wide Character Encodings::
269
270Compiling 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
278Switches for gcc
279
280* Output and Error Message Control::
281* Warning Message Control::
282* Debugging and Assertion Control::
283* Run-Time Checks::
284* Stack Overflow Checking::
285* Validity Checking::
286* Style 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
302Binding 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
310Switches 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
319Linking Using gnatlink
320
321* Running gnatlink::
322* Switches for gnatlink::
323* Setting Stack Size from gnatlink::
324* Setting Heap Size from gnatlink::
325
326The 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
336Improving Performance
337* Performance Considerations::
338* Reducing the Size of Ada Executables with gnatelim::
339
340Performance Considerations
341* Controlling Run-Time Checks::
342* Use of Restrictions::
343* Optimization Levels::
344* Debugging Optimized Code::
345* Inlining of Subprograms::
346@ifset vms
347* Coverage Analysis::
348@end ifset
349
350Reducing the Size of Ada Executables with gnatelim
351* About gnatelim::
352* Running gnatelim::
353* Correcting the List of Eliminate Pragmas::
354* Making Your Executables Smaller::
355* Summary of the gnatelim Usage Cycle::
356
357Renaming Files Using gnatchop
358
359* Handling Files with Multiple Units::
360* Operating gnatchop in Compilation Mode::
361* Command Line for gnatchop::
362* Switches for gnatchop::
363* Examples of gnatchop Usage::
364
365Configuration Pragmas
366
367* Handling of Configuration Pragmas::
368* The Configuration Pragmas Files::
369
370Handling Arbitrary File Naming Conventions Using gnatname
371
372* Arbitrary File Naming Conventions::
373* Running gnatname::
374* Switches for gnatname::
375* Examples of gnatname Usage::
376
377GNAT Project Manager
378
379* Introduction::
380* Examples of Project Files::
381* Project File Syntax::
382* Objects and Sources in Project Files::
383* Importing Projects::
384* Project Extension::
385* External References in Project Files::
386* Packages in Project Files::
387* Variables from Imported Projects::
388* Naming Schemes::
389* Library Projects::
390* Using Third-Party Libraries through Projects::
391* Stand-alone Library Projects::
392* Switches Related to Project Files::
393* Tools Supporting Project Files::
394* An Extended Example::
395* Project File Complete Syntax::
396
397
398The Cross-Referencing Tools gnatxref and gnatfind
399
400* gnatxref Switches::
401* gnatfind Switches::
402* Project Files for gnatxref and gnatfind::
403* Regular Expressions in gnatfind and gnatxref::
404* Examples of gnatxref Usage::
405* Examples of gnatfind Usage::
406
407
408The GNAT Pretty-Printer gnatpp
409
410* Switches for gnatpp::
411* Formatting Rules::
412
413
414File Name Krunching Using gnatkr
415
416* About gnatkr::
417* Using gnatkr::
418* Krunching Method::
419* Examples of gnatkr Usage::
420
421Preprocessing Using gnatprep
422
423* Using gnatprep::
424* Switches for gnatprep::
425* Form of Definitions File::
426* Form of Input Text for gnatprep::
427
428@ifset vms
429The GNAT Run-Time Library Builder gnatlbr
430
431* Running gnatlbr::
432* Switches for gnatlbr::
433* Examples of gnatlbr Usage::
434@end ifset
435
436The GNAT Library Browser gnatls
437
438* Running gnatls::
439* Switches for gnatls::
440* Examples of gnatls Usage::
441
442Cleaning Up Using gnatclean
443
444* Running gnatclean::
445* Switches for gnatclean::
446* Examples of gnatclean Usage::
447
448@ifclear vms
449
450GNAT and Libraries
451
452* Creating an Ada Library::
453* Installing an Ada Library::
454* Using an Ada Library::
455* Creating an Ada Library to be Used in a Non-Ada Context::
456* Rebuilding the GNAT Run-Time Library::
457
458Using 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
466Finding Memory Problems
467
468@ifclear vms
469* The gnatmem Tool::
470@end ifclear
471* The GNAT Debug Pool Facility::
472
473@ifclear vms
474The gnatmem Tool
475
476* Running gnatmem::
477* Switches for gnatmem::
478* Example of gnatmem Usage::
479@end ifclear
480
481The GNAT Debug Pool Facility
482
483Creating Sample Bodies Using gnatstub
484
485* Running gnatstub::
486* Switches for gnatstub::
487
488Other 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
497Running 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
518Compatibility 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
538Language-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
548Implementation 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
557Pragmas 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
563Library of Predefined Units
564
565* Changes to DECLIB::
566
567Bindings
568
569* Shared Libraries and Options Files::
570* Interfaces to C::
571@end ifset
572
573Platform-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
583Example of Binder Output File
584
585Elaboration Order Handling in GNAT
586
587* Elaboration Code in Ada 95::
588* Checking the Elaboration Order in Ada 95::
589* Controlling the Elaboration Order in Ada 95::
590* Controlling Elaboration in GNAT - Internal Calls::
591* Controlling Elaboration in GNAT - External Calls::
592* Default Behavior in GNAT - Ensuring Safety::
593* Treatment of Pragma Elaborate::
594* Elaboration Issues for Library Tasks::
595* Mixing Elaboration Models::
596* What to Do If the Default Elaboration Behavior Fails::
597* Elaboration for Access-to-Subprogram Values::
598* Summary of Procedures for Elaboration Control::
599* Other Elaboration Order Considerations::
600
601Inline Assembler
602
603* Basic Assembler Syntax::
604* A Simple Example of Inline Assembler::
605* Output Variables in Inline Assembler::
606* Input Variables in Inline Assembler::
607* Inlining Inline Assembler Code::
608* Other Asm Functionality::
609* A Complete Example::
610
611Compatibility and Porting Guide
612
613* Compatibility with Ada 83::
614* Implementation-dependent characteristics::
615* Compatibility with DEC Ada 83::
616* Compatibility with Other Ada 95 Systems::
617* Representation Clauses::
618
619@ifset unw
620Microsoft Windows Topics
621
622* Using GNAT on Windows::
623* CONSOLE and WINDOWS subsystems::
624* Temporary Files::
625* Mixed-Language Programming on Windows::
626* Windows Calling Conventions::
627* Introduction to Dynamic Link Libraries (DLLs)::
628* Using DLLs with GNAT::
629* Building DLLs with GNAT::
630* GNAT and Windows Resources::
631* Debugging a DLL::
632* GNAT and COM/DCOM Objects::
633@end ifset
634
635
636* Index::
637@end menu
638@end ifnottex
639
640@node About This Guide
641@unnumbered About This Guide
642
643@noindent
644@ifset vms
645This guide describes the use of of GNAT, a full language compiler for the Ada
64695 programming language, implemented on HP OpenVMS Alpha platforms.
647@end ifset
648@ifclear vms
649This guide describes the use of GNAT, a compiler and software development
650toolset for the full Ada 95 programming language.
651@end ifclear
652It describes the features of the compiler and tools, and details
653how to use them to build Ada 95 applications.
654
655@menu
656* What This Guide Contains::
657* What You Should Know before Reading This Guide::
658* Related Information::
659* Conventions::
660@end menu
661
662@node What This Guide Contains
663@unnumberedsec What This Guide Contains
664
665@noindent
666This guide contains the following chapters:
667@itemize @bullet
668
669@item
670@ref{Getting Started with GNAT}, describes how to get started compiling
671and running Ada programs with the GNAT Ada programming environment.
672@item
673@ref{The GNAT Compilation Model}, describes the compilation model used
674by GNAT.
675
676@item
677@ref{Compiling Using gcc}, describes how to compile
678Ada programs with @code{gcc}, the Ada compiler.
679
680@item
681@ref{Binding Using gnatbind}, describes how to
682perform binding of Ada programs with @code{gnatbind}, the GNAT binding
683utility.
684
685@item
686@ref{Linking Using gnatlink},
687describes @code{gnatlink}, a
688program that provides for linking using the GNAT run-time library to
689construct a program. @code{gnatlink} can also incorporate foreign language
690object units into the executable.
691
692@item
693@ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
694utility that automatically determines the set of sources
695needed by an Ada compilation unit, and executes the necessary compilations
696binding and link.
697
698@item
699@ref{Improving Performance}, shows various techniques for making your
700Ada program run faster or take less space.
701It discusses the effect of the compiler's optimization switch and
702also describes the @command{gnatelim} tool.
703
704@item
705@ref{Renaming Files Using gnatchop}, describes
706@code{gnatchop}, a utility that allows you to preprocess a file that
707contains Ada source code, and split it into one or more new files, one
708for each compilation unit.
709
710@item
711@ref{Configuration Pragmas}, describes the configuration pragmas
712handled by GNAT.
713
714@item
715@ref{Handling Arbitrary File Naming Conventions Using gnatname},
716shows how to override the default GNAT file naming conventions,
717either for an individual unit or globally.
718
719@item
720@ref{GNAT Project Manager}, describes how to use project files
721to organize large projects.
722
723@item
724@ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
725@code{gnatxref} and @code{gnatfind}, two tools that provide an easy
726way to navigate through sources.
727
728@item
729@ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
730version of an Ada source file with control over casing, indentation,
731comment placement, and other elements of program presentation style.
732
733
734@item
735@ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
736file name krunching utility, used to handle shortened
737file names on operating systems with a limit on the length of names.
738
739@item
740@ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
741preprocessor utility that allows a single source file to be used to
742generate multiple or parameterized source files, by means of macro
743substitution.
744
745@ifset vms
746@item
747@ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
748a tool for rebuilding the GNAT run time with user-supplied
749configuration pragmas.
750@end ifset
751
752@item
753@ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
754utility that displays information about compiled units, including dependences
755on the corresponding sources files, and consistency of compilations.
756
757@item
758@ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
759to delete files that are produced by the compiler, binder and linker.
760
761@ifclear vms
762@item
763@ref{GNAT and Libraries}, describes the process of creating and using
764Libraries with GNAT. It also describes how to recompile the GNAT run-time
765library.
766
767@item
768@ref{Using the GNU make Utility}, describes some techniques for using
769the GNAT toolset in Makefiles.
770@end ifclear
771
772@item
773@ref{Finding Memory Problems}, describes
774@ifclear vms
775@command{gnatmem}, a utility that monitors dynamic allocation and deallocation
776and helps detect ``memory leaks'', and
777@end ifclear
778the GNAT Debug Pool facility, which helps detect incorrect memory references.
779
780@item
781@ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
782a utility that generates empty but compilable bodies for library units.
783
784@item
785@ref{Other Utility Programs}, discusses several other GNAT utilities,
786including @code{gnathtml}.
787
788@item
789@ref{Running and Debugging Ada Programs}, describes how to run and debug
790Ada programs.
791
792@ifset vms
793@item
794@ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
795DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
796developed by Digital Equipment Corporation and currently supported by HP.}
797for OpenVMS Alpha.
798@end ifset
799
800@item
801@ref{Platform-Specific Information for the Run-Time Libraries},
802describes the various run-time
803libraries supported by GNAT on various platforms and explains how to
804choose a particular library.
805
806@item
807@ref{Example of Binder Output File}, shows the source code for the binder
808output file for a sample program.
809
810@item
811@ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
812you deal with elaboration order issues.
813
814@item
815@ref{Inline Assembler}, shows how to use the inline assembly facility
816in an Ada program.
817
818@item
819@ref{Compatibility and Porting Guide}, includes sections on compatibility
820of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
821in porting code from other environments.
822
823@ifset unw
824@item
825@ref{Microsoft Windows Topics}, presents information relevant to the
826Microsoft Windows platform.
827@end ifset
828@end itemize
829
830
831@c *************************************************
832@node What You Should Know before Reading This Guide
833@c *************************************************
834@unnumberedsec What You Should Know before Reading This Guide
835
836@cindex Ada 95 Language Reference Manual
837@noindent
838This user's guide assumes that you are familiar with Ada 95 language, as
839described in the International Standard ANSI/ISO/IEC-8652:1995, January
8401995.
841
842@node Related Information
843@unnumberedsec Related Information
844
845@noindent
846For further information about related tools, refer to the following
847documents:
848
849@itemize @bullet
850@item
851@cite{GNAT Reference Manual}, which contains all reference
852material for the GNAT implementation of Ada 95.
853
854@ifset unw
855@item
856@cite{Using the GNAT Programming System}, which describes the GPS
857integrated development environment.
858
859@item
860@cite{GNAT Programming System Tutorial}, which introduces the
861main GPS features through examples.
862@end ifset
863
864@item
865@cite{Ada 95 Language Reference Manual}, which contains all reference
866material for the Ada 95 programming language.
867
868@item
869@cite{Debugging with GDB}
870@ifset vms
871, located in the GNU:[DOCS] directory,
872@end ifset
873contains all details on the use of the GNU source-level debugger.
874
875@item
876@cite{GNU Emacs Manual}
877@ifset vms
878, located in the GNU:[DOCS] directory if the EMACS kit is installed,
879@end ifset
880contains full information on the extensible editor and programming
881environment Emacs.
882
883@end itemize
884
885@c **************
886@node Conventions
887@unnumberedsec Conventions
888@cindex Conventions
889@cindex Typographical conventions
890
891@noindent
892Following are examples of the typographical and graphic conventions used
893in this guide:
894
895@itemize @bullet
896@item
897@code{Functions}, @code{utility program names}, @code{standard names},
898and @code{classes}.
899
900@item
901@samp{Option flags}
902
903@item
904@file{File Names}, @file{button names}, and @file{field names}.
905
906@item
907@var{Variables}.
908
909@item
910@emph{Emphasis}.
911
912@item
913[optional information or parameters]
914
915@item
916Examples are described by text
917@smallexample
918and then shown this way.
919@end smallexample
920@end itemize
921
922@noindent
923Commands that are entered by the user are preceded in this manual by the
924characters @w{``@code{$ }''} (dollar sign followed by space). If your system
925uses this sequence as a prompt, then the commands will appear exactly as
926you see them in the manual. If your system uses some other prompt, then
927the command will appear with the @code{$} replaced by whatever prompt
928character you are using.
929
930@ifset unw
931Full file names are shown with the ``@code{/}'' character
932as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
933If you are using GNAT on a Windows platform, please note that
934the ``@code{\}'' character should be used instead.
935@end ifset
936
937
938
939@c ****************************
940@node Getting Started with GNAT
941@chapter Getting Started with GNAT
942
943@noindent
944This chapter describes some simple ways of using GNAT to build
945executable Ada programs.
946@ifset unw
947@ref{Running GNAT}, through @ref{Using the gnatmake Utility},
948show how to use the command line environment.
949@ref{Introduction to Glide and GVD}, provides a brief
950introduction to the visually-oriented IDE for GNAT.
951Supplementing Glide on some platforms is GPS, the
952GNAT Programming System, which offers a richer graphical
953``look and feel'', enhanced configurability, support for
954development in other programming language, comprehensive
955browsing features, and many other capabilities.
956For information on GPS please refer to
957@cite{Using the GNAT Programming System}.
958@end ifset
959
960@menu
961* Running GNAT::
962* Running a Simple Ada Program::
963* Running a Program with Multiple Units::
964* Using the gnatmake Utility::
965@ifset vms
966* Editing with Emacs::
967@end ifset
968@ifclear vms
969* Introduction to GPS::
970* Introduction to Glide and GVD::
971@end ifclear
972@end menu
973
974@node Running GNAT
975@section Running GNAT
976
977@noindent
978Three steps are needed to create an executable file from an Ada source
979file:
980
981@enumerate
982@item
983The source file(s) must be compiled.
984@item
985The file(s) must be bound using the GNAT binder.
986@item
987All appropriate object files must be linked to produce an executable.
988@end enumerate
989
990@noindent
991All three steps are most commonly handled by using the @code{gnatmake}
992utility program that, given the name of the main program, automatically
993performs the necessary compilation, binding and linking steps.
994
995
996@node Running a Simple Ada Program
997@section Running a Simple Ada Program
998
999@noindent
1000Any text editor may be used to prepare an Ada program.
1001@ifclear vms
1002If @code{Glide} is
1003used, the optional Ada mode may be helpful in laying out the program.
1004@end ifclear
1005The
1006program text is a normal text file. We will suppose in our initial
1007example that you have used your editor to prepare the following
1008standard format text file:
1009
1010@smallexample @c ada
1011@cartouche
1012with Ada.Text_IO; use Ada.Text_IO;
1013procedure Hello is
1014begin
1015   Put_Line ("Hello WORLD!");
1016end Hello;
1017@end cartouche
1018@end smallexample
1019
1020@noindent
1021This file should be named @file{hello.adb}.
1022With the normal default file naming conventions, GNAT requires
1023that each file
1024contain a single compilation unit whose file name is the
1025unit name,
1026with periods replaced by hyphens; the
1027extension is @file{ads} for a
1028spec and @file{adb} for a body.
1029You can override this default file naming convention by use of the
1030special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1031Alternatively, if you want to rename your files according to this default
1032convention, which is probably more convenient if you will be using GNAT
1033for all your compilations, then the @code{gnatchop} utility
1034can be used to generate correctly-named source files
1035(@pxref{Renaming Files Using gnatchop}).
1036
1037You can compile the program using the following command (@code{$} is used
1038as the command prompt in the examples in this document):
1039
1040@smallexample
1041$ gcc -c hello.adb
1042@end smallexample
1043
1044@noindent
1045@code{gcc} is the command used to run the compiler. This compiler is
1046capable of compiling programs in several languages, including Ada 95 and
1047C. It assumes that you have given it an Ada program if the file extension is
1048either @file{.ads} or @file{.adb}, and it will then call
1049the GNAT compiler to compile the specified file.
1050
1051@ifclear vms
1052The @option{-c} switch is required. It tells @command{gcc} to only do a
1053compilation. (For C programs, @command{gcc} can also do linking, but this
1054capability is not used directly for Ada programs, so the @option{-c}
1055switch must always be present.)
1056@end ifclear
1057
1058This compile command generates a file
1059@file{hello.o}, which is the object
1060file corresponding to your Ada program. It also generates
1061an ``Ada Library Information'' file @file{hello.ali},
1062which contains additional information used to check
1063that an Ada program is consistent.
1064To build an executable file,
1065use @code{gnatbind} to bind the program
1066and @code{gnatlink} to link it. The
1067argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1068@file{ALI} file, but the default extension of @file{.ali} can
1069be omitted. This means that in the most common case, the argument
1070is simply the name of the main program:
1071
1072@smallexample
1073$ gnatbind hello
1074$ gnatlink hello
1075@end smallexample
1076
1077@noindent
1078A simpler method of carrying out these steps is to use
1079@command{gnatmake},
1080a master program that invokes all the required
1081compilation, binding and linking tools in the correct order. In particular,
1082@command{gnatmake} automatically recompiles any sources that have been
1083modified since they were last compiled, or sources that depend
1084on such modified sources, so that ``version skew'' is avoided.
1085@cindex Version skew (avoided by @command{gnatmake})
1086
1087@smallexample
1088$ gnatmake hello.adb
1089@end smallexample
1090
1091@noindent
1092The result is an executable program called @file{hello}, which can be
1093run by entering:
1094
1095@c The following should be removed (BMB 2001-01-23)
1096@c @smallexample
1097@c $ ^./hello^$ RUN HELLO^
1098@c @end smallexample
1099
1100@smallexample
1101$ hello
1102@end smallexample
1103
1104@noindent
1105assuming that the current directory is on the search path
1106for executable programs.
1107
1108@noindent
1109and, if all has gone well, you will see
1110
1111@smallexample
1112Hello WORLD!
1113@end smallexample
1114
1115@noindent
1116appear in response to this command.
1117
1118
1119@c ****************************************
1120@node Running a Program with Multiple Units
1121@section Running a Program with Multiple Units
1122
1123@noindent
1124Consider a slightly more complicated example that has three files: a
1125main program, and the spec and body of a package:
1126
1127@smallexample @c ada
1128@cartouche
1129@group
1130package Greetings is
1131   procedure Hello;
1132   procedure Goodbye;
1133end Greetings;
1134
1135with Ada.Text_IO; use Ada.Text_IO;
1136package body Greetings is
1137   procedure Hello is
1138   begin
1139      Put_Line ("Hello WORLD!");
1140   end Hello;
1141
1142   procedure Goodbye is
1143   begin
1144      Put_Line ("Goodbye WORLD!");
1145   end Goodbye;
1146end Greetings;
1147@end group
1148
1149@group
1150with Greetings;
1151procedure Gmain is
1152begin
1153   Greetings.Hello;
1154   Greetings.Goodbye;
1155end Gmain;
1156@end group
1157@end cartouche
1158@end smallexample
1159
1160@noindent
1161Following the one-unit-per-file rule, place this program in the
1162following three separate files:
1163
1164@table @file
1165@item greetings.ads
1166spec of package @code{Greetings}
1167
1168@item greetings.adb
1169body of package @code{Greetings}
1170
1171@item gmain.adb
1172body of main program
1173@end table
1174
1175@noindent
1176To build an executable version of
1177this program, we could use four separate steps to compile, bind, and link
1178the program, as follows:
1179
1180@smallexample
1181$ gcc -c gmain.adb
1182$ gcc -c greetings.adb
1183$ gnatbind gmain
1184$ gnatlink gmain
1185@end smallexample
1186
1187@noindent
1188Note that there is no required order of compilation when using GNAT.
1189In particular it is perfectly fine to compile the main program first.
1190Also, it is not necessary to compile package specs in the case where
1191there is an accompanying body; you only need to compile the body. If you want
1192to submit these files to the compiler for semantic checking and not code
1193generation, then use the
1194@option{-gnatc} switch:
1195
1196@smallexample
1197$ gcc -c greetings.ads -gnatc
1198@end smallexample
1199
1200@noindent
1201Although the compilation can be done in separate steps as in the
1202above example, in practice it is almost always more convenient
1203to use the @code{gnatmake} tool. All you need to know in this case
1204is the name of the main program's source file. The effect of the above four
1205commands can be achieved with a single one:
1206
1207@smallexample
1208$ gnatmake gmain.adb
1209@end smallexample
1210
1211@noindent
1212In the next section we discuss the advantages of using @code{gnatmake} in
1213more detail.
1214
1215@c *****************************
1216@node Using the gnatmake Utility
1217@section Using the @command{gnatmake} Utility
1218
1219@noindent
1220If you work on a program by compiling single components at a time using
1221@code{gcc}, you typically keep track of the units you modify. In order to
1222build a consistent system, you compile not only these units, but also any
1223units that depend on the units you have modified.
1224For example, in the preceding case,
1225if you edit @file{gmain.adb}, you only need to recompile that file. But if
1226you edit @file{greetings.ads}, you must recompile both
1227@file{greetings.adb} and @file{gmain.adb}, because both files contain
1228units that depend on @file{greetings.ads}.
1229
1230@code{gnatbind} will warn you if you forget one of these compilation
1231steps, so that it is impossible to generate an inconsistent program as a
1232result of forgetting to do a compilation. Nevertheless it is tedious and
1233error-prone to keep track of dependencies among units.
1234One approach to handle the dependency-bookkeeping is to use a
1235makefile. However, makefiles present maintenance problems of their own:
1236if the dependencies change as you change the program, you must make
1237sure that the makefile is kept up-to-date manually, which is also an
1238error-prone process.
1239
1240The @code{gnatmake} utility takes care of these details automatically.
1241Invoke it using either one of the following forms:
1242
1243@smallexample
1244$ gnatmake gmain.adb
1245$ gnatmake ^gmain^GMAIN^
1246@end smallexample
1247
1248@noindent
1249The argument is the name of the file containing the main program;
1250you may omit the extension. @code{gnatmake}
1251examines the environment, automatically recompiles any files that need
1252recompiling, and binds and links the resulting set of object files,
1253generating the executable file, @file{^gmain^GMAIN.EXE^}.
1254In a large program, it
1255can be extremely helpful to use @code{gnatmake}, because working out by hand
1256what needs to be recompiled can be difficult.
1257
1258Note that @code{gnatmake}
1259takes into account all the Ada 95 rules that
1260establish dependencies among units. These include dependencies that result
1261from inlining subprogram bodies, and from
1262generic instantiation. Unlike some other
1263Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1264found by the compiler on a previous compilation, which may possibly
1265be wrong when sources change. @code{gnatmake} determines the exact set of
1266dependencies from scratch each time it is run.
1267
1268@ifset vms
1269@node Editing with Emacs
1270@section Editing with Emacs
1271@cindex Emacs
1272
1273@noindent
1274Emacs is an extensible self-documenting text editor that is available in a
1275separate VMSINSTAL kit.
1276
1277Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1278click on the Emacs Help menu and run the Emacs Tutorial.
1279In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1280written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1281
1282Documentation on Emacs and other tools is available in Emacs under the
1283pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1284use the middle mouse button to select a topic (e.g. Emacs).
1285
1286In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1287(stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1288get to the Emacs manual.
1289Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1290prompt.
1291
1292The tutorial is highly recommended in order to learn the intricacies of Emacs,
1293which is sufficiently extensible to provide for a complete programming
1294environment and shell for the sophisticated user.
1295@end ifset
1296
1297@ifclear vms
1298@node Introduction to GPS
1299@section Introduction to GPS
1300@cindex GPS (GNAT Programming System)
1301@cindex GNAT Programming System (GPS)
1302@noindent
1303Although the command line interface (@command{gnatmake}, etc.) alone
1304is sufficient, a graphical Interactive Development
1305Environment can make it easier for you to compose, navigate, and debug
1306programs.  This section describes the main features of GPS
1307(``GNAT Programming System''), the GNAT graphical IDE.
1308You will see how to use GPS to build and debug an executable, and
1309you will also learn some of the basics of the GNAT ``project'' facility.
1310
1311GPS enables you to do much more than is presented here;
1312e.g., you can produce a call graph, interface to a third-party
1313Version Control System, and inspect the generated assembly language
1314for a program.
1315Indeed, GPS also supports languages other than Ada.
1316Such additional information, and an explanation of all of the GPS menu
1317items. may be found in the on-line help, which includes
1318a user's guide and a tutorial (these are also accessible from the GNAT
1319startup menu).
1320
1321@menu
1322* Building a New Program with GPS::
1323* Simple Debugging with GPS::
1324@end menu
1325
1326
1327@node Building a New Program with GPS
1328@subsection Building a New Program with GPS
1329@noindent
1330GPS invokes the GNAT compilation tools using information
1331contained in a @emph{project} (also known as a @emph{project file}):
1332a collection of properties such
1333as source directories, identities of main subprograms, tool switches, etc.,
1334and their associated values.
1335(See @ref{GNAT Project Manager}, for details.)
1336In order to run GPS, you will need to either create a new project
1337or else open an existing one.
1338
1339This section will explain how you can use GPS to create a project,
1340to associate Ada source files with a project, and to build and run
1341programs.
1342
1343@enumerate
1344@item @emph{Creating a project}
1345
1346Invoke GPS, either from the command line or the platform's IDE.
1347After it starts, GPS will display a ``Welcome'' screen with three
1348radio buttons:
1349
1350@itemize @bullet
1351@item
1352@code{Start with default project in directory}
1353
1354@item
1355@code{Create new project with wizard}
1356
1357@item
1358@code{Open existing project}
1359@end itemize
1360
1361@noindent
1362Select @code{Create new project with wizard} and press @code{OK}.
1363A new window will appear.  In the text box labeled with
1364@code{Enter the name of the project to create}, type @file{sample}
1365as the project name.
1366In the next box, browse to choose the directory in which you
1367would like to create the project file.
1368After selecting an appropriate directory, press @code{Forward}.
1369
1370A window will appear with the title
1371@code{Version Control System Configuration}.
1372Simply press @code{Forward}.
1373
1374A window will appear with the title
1375@code{Please select the source directories for this project}.
1376The directory that you specified for the project file will be selected
1377by default as the one to use for sources; simply press @code{Forward}.
1378
1379A window will appear with the title
1380@code{Please select the build directory for this project}.
1381The directory that you specified for the project file will be selected
1382by default for object files and executables;
1383simply press @code{Forward}.
1384
1385A window will appear with the title
1386@code{Please select the main units for this project}.
1387You will supply this information later, after creating the source file.
1388Simply press @code{Forward} for now.
1389
1390A window will appear with the title
1391@code{Please select the switches to build the project}.
1392Press @code{Apply}.  This will create a project file named
1393@file{sample.prj} in the directory that you had specified.
1394
1395@item @emph{Creating and saving the source file}
1396
1397After you create the new project, a GPS window will appear, which is
1398partitioned into two main sections:
1399
1400@itemize @bullet
1401@item
1402A @emph{Workspace area}, initially greyed out, which you will use for
1403creating and editing source files
1404
1405@item
1406Directly below, a @emph{Messages area}, which initially displays a
1407``Welcome'' message.
1408(If the Messages area is not visible, drag its border upward to expand it.)
1409@end itemize
1410
1411@noindent
1412Select @code{File} on the menu bar, and then the @code{New} command.
1413The Workspace area will become white, and you can now
1414enter the source program explicitly.
1415Type the following text
1416
1417@smallexample @c ada
1418@group
1419with Ada.Text_IO; use Ada.Text_IO;
1420procedure Hello is
1421begin
1422  Put_Line("Hello from GPS!");
1423end Hello;
1424@end group
1425@end smallexample
1426
1427@noindent
1428Select @code{File}, then @code{Save As}, and enter the source file name
1429@file{hello.adb}.
1430The file will be saved in the same directory you specified as the
1431location of the default project file.
1432
1433
1434@item @emph{Updating the project file}
1435
1436You need to add the new source file to the project.
1437To do this, select
1438the @code{Project} menu and then @code{Edit project properties}.
1439Click the @code{Main files} tab on the left, and then the
1440@code{Add} button.
1441Choose @file{hello.adb} from the list, and press @code{Open}.
1442The project settings window will reflect this action.
1443Click @code{OK}.
1444
1445@item @emph{Building and running the program}
1446
1447In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1448and select @file{hello.adb}.
1449The Messages window will display the resulting invocations of @command{gcc},
1450@command{gnatbind}, and @command{gnatlink}
1451(reflecting the default switch settings from the
1452project file that you created) and then a ``successful compilation/build''
1453message.
1454
1455To run the program, choose the @code{Build} menu, then @code{Run}, and
1456select @command{hello}.
1457An @emph{Arguments Selection} window will appear.
1458There are no command line arguments, so just click @code{OK}.
1459
1460The Messages window will now display the program's output (the string
1461@code{Hello from GPS}), and at the bottom of the GPS window a status
1462update is displayed (@code{Run: hello}).
1463Close the GPS window (or select @code{File}, then @code{Exit}) to
1464terminate this GPS session.
1465@end enumerate
1466
1467
1468
1469@node Simple Debugging with GPS
1470@subsection Simple Debugging with GPS
1471@noindent
1472This section illustrates basic debugging techniques (setting breakpoints,
1473examining/modifying variables, single stepping).
1474
1475@enumerate
1476@item @emph{Opening a project}
1477
1478Start GPS and select @code{Open existing project}; browse to
1479specify the project file @file{sample.prj} that you had created in the
1480earlier example.
1481
1482@item @emph{Creating a source file}
1483
1484Select @code{File}, then @code{New}, and type in the following program:
1485
1486@smallexample @c ada
1487@group
1488with Ada.Text_IO; use Ada.Text_IO;
1489procedure Example is
1490   Line : String (1..80);
1491   N    : Natural;
1492begin
1493   Put_Line("Type a line of text at each prompt; an empty line to exit");
1494   loop
1495      Put(": ");
1496      Get_Line (Line, N);
1497      Put_Line (Line (1..N) );
1498      exit when N=0;
1499   end loop;
1500end Example;
1501@end group
1502@end smallexample
1503
1504@noindent
1505Select @code{File}, then @code{Save as}, and enter the file name
1506@file{example.adb}.
1507
1508@item @emph{Updating the project file}
1509
1510Add @code{Example} as a new main unit for the project:
1511@enumerate a
1512@item
1513Select @code{Project}, then @code{Edit Project Properties}.
1514
1515@item
1516Select the @code{Main files} tab, click @code{Add}, then
1517select the file @file{example.adb} from the list, and
1518click @code{Open}.
1519You will see the file name appear in the list of main units
1520
1521@item
1522Click @code{OK}
1523@end enumerate
1524
1525@item @emph{Building/running the executable}
1526
1527To build the executable
1528select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1529
1530Run the program to see its effect (in the Messages area).
1531Each line that you enter is displayed; an empty line will
1532cause the loop to exit and the program to terminate.
1533
1534@item @emph{Debugging the program}
1535
1536Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1537which are required for debugging, are on by default when you create
1538a new project.
1539Thus unless you intentionally remove these settings, you will be able
1540to debug any program that you develop using GPS.
1541
1542@enumerate a
1543@item @emph{Initializing}
1544
1545Select @code{Debug}, then @code{Initialize}, then @file{example}
1546
1547@item @emph{Setting a breakpoint}
1548
1549After performing the initialization step, you will observe a small
1550icon to the right of each line number.
1551This serves as a toggle for breakpoints; clicking the icon will
1552set a breakpoint at the corresponding line (the icon will change to
1553a red circle with an ``x''), and clicking it again
1554will remove the breakpoint / reset the icon.
1555
1556For purposes of this example, set a breakpoint at line 10 (the
1557statement @code{Put_Line@ (Line@ (1..N));}
1558
1559@item @emph{Starting program execution}
1560
1561Select @code{Debug}, then @code{Run}.  When the
1562@code{Program Arguments} window appears, click @code{OK}.
1563A console window will appear; enter some line of text,
1564e.g. @code{abcde}, at the prompt.
1565The program will pause execution when it gets to the
1566breakpoint, and the corresponding line is highlighted.
1567
1568@item @emph{Examining a variable}
1569
1570Move the mouse over one of the occurrences of the variable @code{N}.
1571You will see the value (5) displayed, in ``tool tip'' fashion.
1572Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1573You will see information about @code{N} appear in the @code{Debugger Data}
1574pane, showing the value as 5.
1575
1576
1577@item @emph{Assigning a new value to a variable}
1578
1579Right click on the @code{N} in the @code{Debugger Data} pane, and
1580select @code{Set value of N}.
1581When the input window appears, enter the value @code{4} and click
1582@code{OK}.
1583This value does not automatically appear in the @code{Debugger Data}
1584pane; to see it, right click again on the @code{N} in the
1585@code{Debugger Data} pane and select @code{Update value}.
1586The new value, 4, will appear in red.
1587
1588@item @emph{Single stepping}
1589
1590Select @code{Debug}, then @code{Next}.
1591This will cause the next statement to be executed, in this case the
1592call of @code{Put_Line} with the string slice.
1593Notice in the console window that the displayed string is simply
1594@code{abcd} and not @code{abcde} which you had entered.
1595This is because the upper bound of the slice is now 4 rather than 5.
1596
1597@item @emph{Removing a breakpoint}
1598
1599Toggle the breakpoint icon at line 10.
1600
1601@item @emph{Resuming execution from a breakpoint}
1602
1603Select @code{Debug}, then @code{Continue}.
1604The program will reach the next iteration of the loop, and
1605wait for input after displaying the prompt.
1606This time, just hit the @kbd{Enter} key.
1607The value of @code{N} will be 0, and the program will terminate.
1608The console window will disappear.
1609@end enumerate
1610@end enumerate
1611
1612
1613@node Introduction to Glide and GVD
1614@section Introduction to Glide and GVD
1615@cindex Glide
1616@cindex GVD
1617@noindent
1618This section describes the main features of Glide,
1619a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1620the GNU Visual Debugger.
1621These tools may be present in addition to, or in place of, GPS on some
1622platforms.
1623Additional information on Glide and GVD may be found
1624in the on-line help for these tools.
1625
1626@menu
1627* Building a New Program with Glide::
1628* Simple Debugging with GVD::
1629* Other Glide Features::
1630@end menu
1631
1632@node Building a New Program with Glide
1633@subsection Building a New Program with Glide
1634@noindent
1635The simplest way to invoke Glide is to enter @command{glide}
1636at the command prompt.  It will generally be useful to issue this
1637as a background command, thus allowing you to continue using
1638your command window for other purposes while Glide is running:
1639
1640@smallexample
1641$ glide&
1642@end smallexample
1643
1644@noindent
1645Glide will start up with an initial screen displaying the top-level menu items
1646as well as some other information.  The menu selections are as follows
1647@itemize @bullet
1648@item @code{Buffers}
1649@item @code{Files}
1650@item @code{Tools}
1651@item @code{Edit}
1652@item @code{Search}
1653@item @code{Mule}
1654@item @code{Glide}
1655@item @code{Help}
1656@end itemize
1657
1658@noindent
1659For this introductory example, you will need to create a new Ada source file.
1660First, select the @code{Files} menu.  This will pop open a menu with around
1661a dozen or so items.  To create a file, select the @code{Open file...} choice.
1662Depending on the platform, you may see a pop-up window where you can browse
1663to an appropriate directory and then enter the file name, or else simply
1664see a line at the bottom of the Glide window where you can likewise enter
1665the file name.  Note that in Glide, when you attempt to open a non-existent
1666file, the effect is to create a file with that name.  For this example enter
1667@file{hello.adb} as the name of the file.
1668
1669A new buffer will now appear, occupying the entire Glide window,
1670with the file name at the top.  The menu selections are slightly different
1671from the ones you saw on the opening screen; there is an @code{Entities} item,
1672and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1673the file extension to identify the source language, so @file{adb} indicates
1674an Ada source file.
1675
1676You will enter some of the source program lines explicitly,
1677and use the syntax-oriented template mechanism to enter other lines.
1678First, type the following text:
1679@smallexample
1680with Ada.Text_IO; use Ada.Text_IO;
1681procedure Hello is
1682begin
1683@end smallexample
1684
1685@noindent
1686Observe that Glide uses different colors to distinguish reserved words from
1687identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1688automatically indented in anticipation of declarations.  When you enter
1689@code{begin}, Glide recognizes that there are no declarations and thus places
1690@code{begin} flush left.  But after the @code{begin} line the cursor is again
1691indented, where the statement(s) will be placed.
1692
1693The main part of the program will be a @code{for} loop.  Instead of entering
1694the text explicitly, however, use a statement template.  Select the @code{Ada}
1695item on the top menu bar, move the mouse to the @code{Statements} item,
1696and you will see a large selection of alternatives.  Choose @code{for loop}.
1697You will be prompted (at the bottom of the buffer) for a loop name;
1698simply press the @key{Enter} key since a loop name is not needed.
1699You should see the beginning of a @code{for} loop appear in the source
1700program window.  You will now be prompted for the name of the loop variable;
1701enter a line with the identifier @code{ind} (lower case).  Note that,
1702by default, Glide capitalizes the name (you can override such behavior
1703if you wish, although this is outside the scope of this introduction).
1704Next, Glide prompts you for the loop range; enter a line containing
1705@code{1..5} and you will see this also appear in the source program,
1706together with the remaining elements of the @code{for} loop syntax.
1707
1708Next enter the statement (with an intentional error, a missing semicolon)
1709that will form the body of the loop:
1710@smallexample
1711Put_Line("Hello, World" & Integer'Image(I))
1712@end smallexample
1713
1714@noindent
1715Finally, type @code{end Hello;} as the last line in the program.
1716Now save the file: choose the @code{File} menu item, and then the
1717@code{Save buffer} selection.  You will see a message at the bottom
1718of the buffer confirming that the file has been saved.
1719
1720You are now ready to attempt to build the program.  Select the @code{Ada}
1721item from the top menu bar.  Although we could choose simply to compile
1722the file, we will instead attempt to do a build (which invokes
1723@command{gnatmake}) since, if the compile is successful, we want to build
1724an executable.  Thus select @code{Ada build}.  This will fail because of the
1725compilation error, and you will notice that the Glide window has been split:
1726the top window contains the source file, and the bottom window contains the
1727output from the GNAT tools. Glide allows you to navigate from a compilation
1728error to the source file position corresponding to the error: click the
1729middle mouse button (or simultaneously press the left and right buttons,
1730on a two-button mouse) on the diagnostic line in the tool window.  The
1731focus will shift to the source window, and the cursor will be positioned
1732on the character at which the error was detected.
1733
1734Correct the error: type in a semicolon to terminate the statement.
1735Although you can again save the file explicitly, you can also simply invoke
1736@code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1737This time the build will succeed; the tool output window shows you the
1738options that are supplied by default.  The GNAT tools' output (e.g.
1739object and ALI files, executable) will go in the directory from which
1740Glide was launched.
1741
1742To execute the program, choose @code{Ada} and then @code{Run}.
1743You should see the program's output displayed in the bottom window:
1744
1745@smallexample
1746Hello, world 1
1747Hello, world 2
1748Hello, world 3
1749Hello, world 4
1750Hello, world 5
1751@end smallexample
1752
1753@node Simple Debugging with GVD
1754@subsection Simple Debugging with GVD
1755
1756@noindent
1757This section describes how to set breakpoints, examine/modify variables,
1758and step through execution.
1759
1760In order to enable debugging, you need to pass the @option{-g} switch
1761to both the compiler and to @command{gnatlink}.  If you are using
1762the command line, passing @option{-g} to @command{gnatmake} will have
1763this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1764by issuing the command:
1765
1766@smallexample
1767$ gvd hello
1768@end smallexample
1769
1770@noindent
1771If you are using Glide, then @option{-g} is passed to the relevant tools
1772by default when you do a build.  Start the debugger by selecting the
1773@code{Ada} menu item, and then @code{Debug}.
1774
1775GVD comes up in a multi-part window.  One pane shows the names of files
1776comprising your executable; another pane shows the source code of the current
1777unit (initially your main subprogram), another pane shows the debugger output
1778and user interactions, and the fourth pane (the data canvas at the top
1779of the window) displays data objects that you have selected.
1780
1781To the left of the source file pane, you will notice green dots adjacent
1782to some lines.  These are lines for which object code exists and where
1783breakpoints can thus be set.  You set/reset a breakpoint by clicking
1784the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1785in a red circle.  Clicking the circle toggles the breakpoint off,
1786and the red circle is replaced by the green dot.
1787
1788For this example, set a breakpoint at the statement where @code{Put_Line}
1789is invoked.
1790
1791Start program execution by selecting the @code{Run} button on the top menu bar.
1792(The @code{Start} button will also start your program, but it will
1793cause program execution to break at the entry to your main subprogram.)
1794Evidence of reaching the breakpoint will appear: the source file line will be
1795highlighted, and the debugger interactions pane will display
1796a relevant message.
1797
1798You can examine the values of variables in several ways.  Move the mouse
1799over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1800the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1801and select @code{Display Ind}; a box showing the variable's name and value
1802will appear in the data canvas.
1803
1804Although a loop index is a constant with respect to Ada semantics,
1805you can change its value in the debugger.  Right-click in the box
1806for @code{Ind}, and select the @code{Set Value of Ind} item.
1807Enter @code{2} as the new value, and press @command{OK}.
1808The box for @code{Ind} shows the update.
1809
1810Press the @code{Step} button on the top menu bar; this will step through
1811one line of program text (the invocation of @code{Put_Line}), and you can
1812observe the effect of having modified @code{Ind} since the value displayed
1813is @code{2}.
1814
1815Remove the breakpoint, and resume execution by selecting the @code{Cont}
1816button.  You will see the remaining output lines displayed in the debugger
1817interaction window, along with a message confirming normal program
1818termination.
1819
1820@node Other Glide Features
1821@subsection Other Glide Features
1822
1823@noindent
1824You may have observed that some of the menu selections contain abbreviations;
1825e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1826These are @emph{shortcut keys} that you can use instead of selecting
1827menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1828@key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1829of selecting @code{Files} and then @code{Open file...}.
1830
1831To abort a Glide command, type @key{Ctrl-g}.
1832
1833If you want Glide to start with an existing source file, you can either
1834launch Glide as above and then open the file via @code{Files} @result{}
1835@code{Open file...}, or else simply pass the name of the source file
1836on the command line:
1837
1838@smallexample
1839$ glide hello.adb&
1840@end smallexample
1841
1842@noindent
1843While you are using Glide, a number of @emph{buffers} exist.
1844You create some explicitly; e.g., when you open/create a file.
1845Others arise as an effect of the commands that you issue; e.g., the buffer
1846containing the output of the tools invoked during a build.  If a buffer
1847is hidden, you can bring it into a visible window by first opening
1848the @code{Buffers} menu and then selecting the desired entry.
1849
1850If a buffer occupies only part of the Glide screen and you want to expand it
1851to fill the entire screen, then click in the buffer and then select
1852@code{Files} @result{} @code{One Window}.
1853
1854If a window is occupied by one buffer and you want to split the window
1855to bring up a second buffer, perform the following steps:
1856@itemize @bullet
1857@item Select @code{Files} @result{} @code{Split Window};
1858this will produce two windows each of which holds the original buffer
1859(these are not copies, but rather different views of the same buffer contents)
1860
1861@item With the focus in one of the windows,
1862select the desired buffer from the @code{Buffers} menu
1863@end itemize
1864
1865@noindent
1866To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1867@end ifclear
1868
1869@node The GNAT Compilation Model
1870@chapter The GNAT Compilation Model
1871@cindex GNAT compilation model
1872@cindex Compilation model
1873
1874@menu
1875* Source Representation::
1876* Foreign Language Representation::
1877* File Naming Rules::
1878* Using Other File Names::
1879* Alternative File Naming Schemes::
1880* Generating Object Files::
1881* Source Dependencies::
1882* The Ada Library Information Files::
1883* Binding an Ada Program::
1884* Mixed Language Programming::
1885* Building Mixed Ada & C++ Programs::
1886* Comparison between GNAT and C/C++ Compilation Models::
1887* Comparison between GNAT and Conventional Ada Library Models::
1888@ifset vms
1889* Placement of temporary files::
1890@end ifset
1891@end menu
1892
1893@noindent
1894This chapter describes the compilation model used by GNAT. Although
1895similar to that used by other languages, such as C and C++, this model
1896is substantially different from the traditional Ada compilation models,
1897which are based on a library. The model is initially described without
1898reference to the library-based model. If you have not previously used an
1899Ada compiler, you need only read the first part of this chapter. The
1900last section describes and discusses the differences between the GNAT
1901model and the traditional Ada compiler models. If you have used other
1902Ada compilers, this section will help you to understand those
1903differences, and the advantages of the GNAT model.
1904
1905@node Source Representation
1906@section Source Representation
1907@cindex Latin-1
1908
1909@noindent
1910Ada source programs are represented in standard text files, using
1911Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
19127-bit ASCII set, plus additional characters used for
1913representing foreign languages (@pxref{Foreign Language Representation}
1914for support of non-USA character sets). The format effector characters
1915are represented using their standard ASCII encodings, as follows:
1916
1917@table @code
1918@item VT
1919@findex VT
1920Vertical tab, @code{16#0B#}
1921
1922@item HT
1923@findex HT
1924Horizontal tab, @code{16#09#}
1925
1926@item CR
1927@findex CR
1928Carriage return, @code{16#0D#}
1929
1930@item LF
1931@findex LF
1932Line feed, @code{16#0A#}
1933
1934@item FF
1935@findex FF
1936Form feed, @code{16#0C#}
1937@end table
1938
1939@noindent
1940Source files are in standard text file format. In addition, GNAT will
1941recognize a wide variety of stream formats, in which the end of physical
1942physical lines is marked by any of the following sequences:
1943@code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1944in accommodating files that are imported from other operating systems.
1945
1946@cindex End of source file
1947@cindex Source file, end
1948@findex SUB
1949The end of a source file is normally represented by the physical end of
1950file. However, the control character @code{16#1A#} (@code{SUB}) is also
1951recognized as signalling the end of the source file. Again, this is
1952provided for compatibility with other operating systems where this
1953code is used to represent the end of file.
1954
1955Each file contains a single Ada compilation unit, including any pragmas
1956associated with the unit. For example, this means you must place a
1957package declaration (a package @dfn{spec}) and the corresponding body in
1958separate files. An Ada @dfn{compilation} (which is a sequence of
1959compilation units) is represented using a sequence of files. Similarly,
1960you will place each subunit or child unit in a separate file.
1961
1962@node Foreign Language Representation
1963@section Foreign Language Representation
1964
1965@noindent
1966GNAT supports the standard character sets defined in Ada 95 as well as
1967several other non-standard character sets for use in localized versions
1968of the compiler (@pxref{Character Set Control}).
1969@menu
1970* Latin-1::
1971* Other 8-Bit Codes::
1972* Wide Character Encodings::
1973@end menu
1974
1975@node Latin-1
1976@subsection Latin-1
1977@cindex Latin-1
1978
1979@noindent
1980The basic character set is Latin-1. This character set is defined by ISO
1981standard 8859, part 1. The lower half (character codes @code{16#00#}
1982... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1983is used to represent additional characters. These include extended letters
1984used by European languages, such as French accents, the vowels with umlauts
1985used in German, and the extra letter A-ring used in Swedish.
1986
1987@findex Ada.Characters.Latin_1
1988For a complete list of Latin-1 codes and their encodings, see the source
1989file of library unit @code{Ada.Characters.Latin_1} in file
1990@file{a-chlat1.ads}.
1991You may use any of these extended characters freely in character or
1992string literals. In addition, the extended characters that represent
1993letters can be used in identifiers.
1994
1995@node Other 8-Bit Codes
1996@subsection Other 8-Bit Codes
1997
1998@noindent
1999GNAT also supports several other 8-bit coding schemes:
2000
2001@table @asis
2002@item ISO 8859-2 (Latin-2)
2003@cindex Latin-2
2004@cindex ISO 8859-2
2005Latin-2 letters allowed in identifiers, with uppercase and lowercase
2006equivalence.
2007
2008@item ISO 8859-3 (Latin-3)
2009@cindex Latin-3
2010@cindex ISO 8859-3
2011Latin-3 letters allowed in identifiers, with uppercase and lowercase
2012equivalence.
2013
2014@item ISO 8859-4 (Latin-4)
2015@cindex Latin-4
2016@cindex ISO 8859-4
2017Latin-4 letters allowed in identifiers, with uppercase and lowercase
2018equivalence.
2019
2020@item ISO 8859-5 (Cyrillic)
2021@cindex ISO 8859-5
2022@cindex Cyrillic
2023ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2024lowercase equivalence.
2025
2026@item ISO 8859-15 (Latin-9)
2027@cindex ISO 8859-15
2028@cindex Latin-9
2029ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2030lowercase equivalence
2031
2032@item IBM PC (code page 437)
2033@cindex code page 437
2034This code page is the normal default for PCs in the U.S. It corresponds
2035to the original IBM PC character set. This set has some, but not all, of
2036the extended Latin-1 letters, but these letters do not have the same
2037encoding as Latin-1. In this mode, these letters are allowed in
2038identifiers with uppercase and lowercase equivalence.
2039
2040@item IBM PC (code page 850)
2041@cindex code page 850
2042This code page is a modification of 437 extended to include all the
2043Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2044mode, all these letters are allowed in identifiers with uppercase and
2045lowercase equivalence.
2046
2047@item Full Upper 8-bit
2048Any character in the range 80-FF allowed in identifiers, and all are
2049considered distinct. In other words, there are no uppercase and lowercase
2050equivalences in this range. This is useful in conjunction with
2051certain encoding schemes used for some foreign character sets (e.g.
2052the typical method of representing Chinese characters on the PC).
2053
2054@item No Upper-Half
2055No upper-half characters in the range 80-FF are allowed in identifiers.
2056This gives Ada 83 compatibility for identifier names.
2057@end table
2058
2059@noindent
2060For precise data on the encodings permitted, and the uppercase and lowercase
2061equivalences that are recognized, see the file @file{csets.adb} in
2062the GNAT compiler sources. You will need to obtain a full source release
2063of GNAT to obtain this file.
2064
2065@node Wide Character Encodings
2066@subsection Wide Character Encodings
2067
2068@noindent
2069GNAT allows wide character codes to appear in character and string
2070literals, and also optionally in identifiers, by means of the following
2071possible encoding schemes:
2072
2073@table @asis
2074
2075@item Hex Coding
2076In this encoding, a wide character is represented by the following five
2077character sequence:
2078
2079@smallexample
2080ESC a b c d
2081@end smallexample
2082
2083@noindent
2084Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2085characters (using uppercase letters) of the wide character code. For
2086example, ESC A345 is used to represent the wide character with code
2087@code{16#A345#}.
2088This scheme is compatible with use of the full Wide_Character set.
2089
2090@item Upper-Half Coding
2091@cindex Upper-Half Coding
2092The wide character with encoding @code{16#abcd#} where the upper bit is on
2093(in other words, ``a'' is in the range 8-F) is represented as two bytes,
2094@code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2095character, but is not required to be in the upper half. This method can
2096be also used for shift-JIS or EUC, where the internal coding matches the
2097external coding.
2098
2099@item Shift JIS Coding
2100@cindex Shift JIS Coding
2101A wide character is represented by a two-character sequence,
2102@code{16#ab#} and
2103@code{16#cd#}, with the restrictions described for upper-half encoding as
2104described above. The internal character code is the corresponding JIS
2105character according to the standard algorithm for Shift-JIS
2106conversion. Only characters defined in the JIS code set table can be
2107used with this encoding method.
2108
2109@item EUC Coding
2110@cindex EUC Coding
2111A wide character is represented by a two-character sequence
2112@code{16#ab#} and
2113@code{16#cd#}, with both characters being in the upper half. The internal
2114character code is the corresponding JIS character according to the EUC
2115encoding algorithm. Only characters defined in the JIS code set table
2116can be used with this encoding method.
2117
2118@item UTF-8 Coding
2119A wide character is represented using
2120UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
212110646-1/Am.2. Depending on the character value, the representation
2122is a one, two, or three byte sequence:
2123@smallexample
2124@iftex
2125@leftskip=.7cm
2126@end iftex
212716#0000#-16#007f#: 2#0xxxxxxx#
212816#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
212916#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2130
2131@end smallexample
2132
2133@noindent
2134where the xxx bits correspond to the left-padded bits of the
213516-bit character value. Note that all lower half ASCII characters
2136are represented as ASCII bytes and all upper half characters and
2137other wide characters are represented as sequences of upper-half
2138(The full UTF-8 scheme allows for encoding 31-bit characters as
21396-byte sequences, but in this implementation, all UTF-8 sequences
2140of four or more bytes length will be treated as illegal).
2141@item Brackets Coding
2142In this encoding, a wide character is represented by the following eight
2143character sequence:
2144
2145@smallexample
2146[ " a b c d " ]
2147@end smallexample
2148
2149@noindent
2150Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2151characters (using uppercase letters) of the wide character code. For
2152example, [``A345''] is used to represent the wide character with code
2153@code{16#A345#}. It is also possible (though not required) to use the
2154Brackets coding for upper half characters. For example, the code
2155@code{16#A3#} can be represented as @code{[``A3'']}.
2156
2157This scheme is compatible with use of the full Wide_Character set,
2158and is also the method used for wide character encoding in the standard
2159ACVC (Ada Compiler Validation Capability) test suite distributions.
2160
2161@end table
2162
2163@noindent
2164Note: Some of these coding schemes do not permit the full use of the
2165Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2166use of the upper half of the Latin-1 set.
2167
2168@node File Naming Rules
2169@section File Naming Rules
2170
2171@noindent
2172The default file name is determined by the name of the unit that the
2173file contains. The name is formed by taking the full expanded name of
2174the unit and replacing the separating dots with hyphens and using
2175^lowercase^uppercase^ for all letters.
2176
2177An exception arises if the file name generated by the above rules starts
2178with one of the characters
2179@ifset vms
2180A,G,I, or S,
2181@end ifset
2182@ifclear vms
2183a,g,i, or s,
2184@end ifclear
2185and the second character is a
2186minus. In this case, the character ^tilde^dollar sign^ is used in place
2187of the minus. The reason for this special rule is to avoid clashes with
2188the standard names for child units of the packages System, Ada,
2189Interfaces, and GNAT, which use the prefixes
2190@ifset vms
2191S- A- I- and G-
2192@end ifset
2193@ifclear vms
2194s- a- i- and g-
2195@end ifclear
2196respectively.
2197
2198The file extension is @file{.ads} for a spec and
2199@file{.adb} for a body. The following list shows some
2200examples of these rules.
2201
2202@table @file
2203@item main.ads
2204Main (spec)
2205@item main.adb
2206Main (body)
2207@item arith_functions.ads
2208Arith_Functions (package spec)
2209@item arith_functions.adb
2210Arith_Functions (package body)
2211@item func-spec.ads
2212Func.Spec (child package spec)
2213@item func-spec.adb
2214Func.Spec (child package body)
2215@item main-sub.adb
2216Sub (subunit of Main)
2217@item ^a~bad.adb^A$BAD.ADB^
2218A.Bad (child package body)
2219@end table
2220
2221@noindent
2222Following these rules can result in excessively long
2223file names if corresponding
2224unit names are long (for example, if child units or subunits are
2225heavily nested). An option is available to shorten such long file names
2226(called file name ``krunching''). This may be particularly useful when
2227programs being developed with GNAT are to be used on operating systems
2228with limited file name lengths. @xref{Using gnatkr}.
2229
2230Of course, no file shortening algorithm can guarantee uniqueness over
2231all possible unit names; if file name krunching is used, it is your
2232responsibility to ensure no name clashes occur. Alternatively you
2233can specify the exact file names that you want used, as described
2234in the next section. Finally, if your Ada programs are migrating from a
2235compiler with a different naming convention, you can use the gnatchop
2236utility to produce source files that follow the GNAT naming conventions.
2237(For details @pxref{Renaming Files Using gnatchop}.)
2238
2239Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2240systems, case is not significant. So for example on @code{Windows XP}
2241if the canonical name is @code{main-sub.adb}, you can use the file name
2242@code{Main-Sub.adb} instead. However, case is significant for other
2243operating systems, so for example, if you want to use other than
2244canonically cased file names on a Unix system, you need to follow
2245the procedures described in the next section.
2246
2247@node Using Other File Names
2248@section Using Other File Names
2249@cindex File names
2250
2251@noindent
2252In the previous section, we have described the default rules used by
2253GNAT to determine the file name in which a given unit resides. It is
2254often convenient to follow these default rules, and if you follow them,
2255the compiler knows without being explicitly told where to find all
2256the files it needs.
2257
2258However, in some cases, particularly when a program is imported from
2259another Ada compiler environment, it may be more convenient for the
2260programmer to specify which file names contain which units. GNAT allows
2261arbitrary file names to be used by means of the Source_File_Name pragma.
2262The form of this pragma is as shown in the following examples:
2263@cindex Source_File_Name pragma
2264
2265@smallexample @c ada
2266@cartouche
2267pragma Source_File_Name (My_Utilities.Stacks,
2268  Spec_File_Name => "myutilst_a.ada");
2269pragma Source_File_name (My_Utilities.Stacks,
2270  Body_File_Name => "myutilst.ada");
2271@end cartouche
2272@end smallexample
2273
2274@noindent
2275As shown in this example, the first argument for the pragma is the unit
2276name (in this example a child unit). The second argument has the form
2277of a named association. The identifier
2278indicates whether the file name is for a spec or a body;
2279the file name itself is given by a string literal.
2280
2281The source file name pragma is a configuration pragma, which means that
2282normally it will be placed in the @file{gnat.adc}
2283file used to hold configuration
2284pragmas that apply to a complete compilation environment.
2285For more details on how the @file{gnat.adc} file is created and used
2286@pxref{Handling of Configuration Pragmas}
2287@cindex @file{gnat.adc}
2288
2289@ifclear vms
2290GNAT allows completely arbitrary file names to be specified using the
2291source file name pragma. However, if the file name specified has an
2292extension other than @file{.ads} or @file{.adb} it is necessary to use
2293a special syntax when compiling the file. The name in this case must be
2294preceded by the special sequence @code{-x} followed by a space and the name
2295of the language, here @code{ada}, as in:
2296
2297@smallexample
2298$ gcc -c -x ada peculiar_file_name.sim
2299@end smallexample
2300@end ifclear
2301
2302@noindent
2303@code{gnatmake} handles non-standard file names in the usual manner (the
2304non-standard file name for the main program is simply used as the
2305argument to gnatmake). Note that if the extension is also non-standard,
2306then it must be included in the gnatmake command, it may not be omitted.
2307
2308@node Alternative File Naming Schemes
2309@section Alternative File Naming Schemes
2310@cindex File naming schemes, alternative
2311@cindex File names
2312
2313In the previous section, we described the use of the @code{Source_File_Name}
2314pragma to allow arbitrary names to be assigned to individual source files.
2315However, this approach requires one pragma for each file, and especially in
2316large systems can result in very long @file{gnat.adc} files, and also create
2317a maintenance problem.
2318
2319GNAT also provides a facility for specifying systematic file naming schemes
2320other than the standard default naming scheme previously described. An
2321alternative scheme for naming is specified by the use of
2322@code{Source_File_Name} pragmas having the following format:
2323@cindex Source_File_Name pragma
2324
2325@smallexample @c ada
2326pragma Source_File_Name (
2327   Spec_File_Name  => FILE_NAME_PATTERN
2328 [,Casing          => CASING_SPEC]
2329 [,Dot_Replacement => STRING_LITERAL]);
2330
2331pragma Source_File_Name (
2332   Body_File_Name  => FILE_NAME_PATTERN
2333 [,Casing          => CASING_SPEC]
2334 [,Dot_Replacement => STRING_LITERAL]);
2335
2336pragma Source_File_Name (
2337   Subunit_File_Name  => FILE_NAME_PATTERN
2338 [,Casing             => CASING_SPEC]
2339 [,Dot_Replacement    => STRING_LITERAL]);
2340
2341FILE_NAME_PATTERN ::= STRING_LITERAL
2342CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2343@end smallexample
2344
2345@noindent
2346The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2347It contains a single asterisk character, and the unit name is substituted
2348systematically for this asterisk. The optional parameter
2349@code{Casing} indicates
2350whether the unit name is to be all upper-case letters, all lower-case letters,
2351or mixed-case. If no
2352@code{Casing} parameter is used, then the default is all
2353^lower-case^upper-case^.
2354
2355The optional @code{Dot_Replacement} string is used to replace any periods
2356that occur in subunit or child unit names. If no @code{Dot_Replacement}
2357argument is used then separating dots appear unchanged in the resulting
2358file name.
2359Although the above syntax indicates that the
2360@code{Casing} argument must appear
2361before the @code{Dot_Replacement} argument, but it
2362is also permissible to write these arguments in the opposite order.
2363
2364As indicated, it is possible to specify different naming schemes for
2365bodies, specs, and subunits. Quite often the rule for subunits is the
2366same as the rule for bodies, in which case, there is no need to give
2367a separate @code{Subunit_File_Name} rule, and in this case the
2368@code{Body_File_name} rule is used for subunits as well.
2369
2370The separate rule for subunits can also be used to implement the rather
2371unusual case of a compilation environment (e.g. a single directory) which
2372contains a subunit and a child unit with the same unit name. Although
2373both units cannot appear in the same partition, the Ada Reference Manual
2374allows (but does not require) the possibility of the two units coexisting
2375in the same environment.
2376
2377The file name translation works in the following steps:
2378
2379@itemize @bullet
2380
2381@item
2382If there is a specific @code{Source_File_Name} pragma for the given unit,
2383then this is always used, and any general pattern rules are ignored.
2384
2385@item
2386If there is a pattern type @code{Source_File_Name} pragma that applies to
2387the unit, then the resulting file name will be used if the file exists. If
2388more than one pattern matches, the latest one will be tried first, and the
2389first attempt resulting in a reference to a file that exists will be used.
2390
2391@item
2392If no pattern type @code{Source_File_Name} pragma that applies to the unit
2393for which the corresponding file exists, then the standard GNAT default
2394naming rules are used.
2395
2396@end itemize
2397
2398@noindent
2399As an example of the use of this mechanism, consider a commonly used scheme
2400in which file names are all lower case, with separating periods copied
2401unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2402bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2403two pragmas appear:
2404
2405@smallexample @c ada
2406pragma Source_File_Name
2407  (Spec_File_Name => "*.1.ada");
2408pragma Source_File_Name
2409  (Body_File_Name => "*.2.ada");
2410@end smallexample
2411
2412@noindent
2413The default GNAT scheme is actually implemented by providing the following
2414default pragmas internally:
2415
2416@smallexample @c ada
2417pragma Source_File_Name
2418  (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2419pragma Source_File_Name
2420  (Body_File_Name => "*.adb", Dot_Replacement => "-");
2421@end smallexample
2422
2423@noindent
2424Our final example implements a scheme typically used with one of the
2425Ada 83 compilers, where the separator character for subunits was ``__''
2426(two underscores), specs were identified by adding @file{_.ADA}, bodies
2427by adding @file{.ADA}, and subunits by
2428adding @file{.SEP}. All file names were
2429upper case. Child units were not present of course since this was an
2430Ada 83 compiler, but it seems reasonable to extend this scheme to use
2431the same double underscore separator for child units.
2432
2433@smallexample @c ada
2434pragma Source_File_Name
2435  (Spec_File_Name => "*_.ADA",
2436   Dot_Replacement => "__",
2437   Casing = Uppercase);
2438pragma Source_File_Name
2439  (Body_File_Name => "*.ADA",
2440   Dot_Replacement => "__",
2441   Casing = Uppercase);
2442pragma Source_File_Name
2443  (Subunit_File_Name => "*.SEP",
2444   Dot_Replacement => "__",
2445   Casing = Uppercase);
2446@end smallexample
2447
2448@node Generating Object Files
2449@section Generating Object Files
2450
2451@noindent
2452An Ada program consists of a set of source files, and the first step in
2453compiling the program is to generate the corresponding object files.
2454These are generated by compiling a subset of these source files.
2455The files you need to compile are the following:
2456
2457@itemize @bullet
2458@item
2459If a package spec has no body, compile the package spec to produce the
2460object file for the package.
2461
2462@item
2463If a package has both a spec and a body, compile the body to produce the
2464object file for the package. The source file for the package spec need
2465not be compiled in this case because there is only one object file, which
2466contains the code for both the spec and body of the package.
2467
2468@item
2469For a subprogram, compile the subprogram body to produce the object file
2470for the subprogram. The spec, if one is present, is as usual in a
2471separate file, and need not be compiled.
2472
2473@item
2474@cindex Subunits
2475In the case of subunits, only compile the parent unit. A single object
2476file is generated for the entire subunit tree, which includes all the
2477subunits.
2478
2479@item
2480Compile child units independently of their parent units
2481(though, of course, the spec of all the ancestor unit must be present in order
2482to compile a child unit).
2483
2484@item
2485@cindex Generics
2486Compile generic units in the same manner as any other units. The object
2487files in this case are small dummy files that contain at most the
2488flag used for elaboration checking. This is because GNAT always handles generic
2489instantiation by means of macro expansion. However, it is still necessary to
2490compile generic units, for dependency checking and elaboration purposes.
2491@end itemize
2492
2493@noindent
2494The preceding rules describe the set of files that must be compiled to
2495generate the object files for a program. Each object file has the same
2496name as the corresponding source file, except that the extension is
2497@file{.o} as usual.
2498
2499You may wish to compile other files for the purpose of checking their
2500syntactic and semantic correctness. For example, in the case where a
2501package has a separate spec and body, you would not normally compile the
2502spec. However, it is convenient in practice to compile the spec to make
2503sure it is error-free before compiling clients of this spec, because such
2504compilations will fail if there is an error in the spec.
2505
2506GNAT provides an option for compiling such files purely for the
2507purposes of checking correctness; such compilations are not required as
2508part of the process of building a program. To compile a file in this
2509checking mode, use the @option{-gnatc} switch.
2510
2511@node Source Dependencies
2512@section Source Dependencies
2513
2514@noindent
2515A given object file clearly depends on the source file which is compiled
2516to produce it. Here we are using @dfn{depends} in the sense of a typical
2517@code{make} utility; in other words, an object file depends on a source
2518file if changes to the source file require the object file to be
2519recompiled.
2520In addition to this basic dependency, a given object may depend on
2521additional source files as follows:
2522
2523@itemize @bullet
2524@item
2525If a file being compiled @code{with}'s a unit @var{X}, the object file
2526depends on the file containing the spec of unit @var{X}. This includes
2527files that are @code{with}'ed implicitly either because they are parents
2528of @code{with}'ed child units or they are run-time units required by the
2529language constructs used in a particular unit.
2530
2531@item
2532If a file being compiled instantiates a library level generic unit, the
2533object file depends on both the spec and body files for this generic
2534unit.
2535
2536@item
2537If a file being compiled instantiates a generic unit defined within a
2538package, the object file depends on the body file for the package as
2539well as the spec file.
2540
2541@item
2542@findex Inline
2543@cindex @option{-gnatn} switch
2544If a file being compiled contains a call to a subprogram for which
2545pragma @code{Inline} applies and inlining is activated with the
2546@option{-gnatn} switch, the object file depends on the file containing the
2547body of this subprogram as well as on the file containing the spec. Note
2548that for inlining to actually occur as a result of the use of this switch,
2549it is necessary to compile in optimizing mode.
2550
2551@cindex @option{-gnatN} switch
2552The use of @option{-gnatN} activates a more extensive inlining optimization
2553that is performed by the front end of the compiler. This inlining does
2554not require that the code generation be optimized. Like @option{-gnatn},
2555the use of this switch generates additional dependencies.
2556Note that
2557@option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2558to specify both options.
2559
2560@item
2561If an object file O  depends on the proper body of a subunit through inlining
2562or instantiation, it depends on the parent unit of the subunit. This means that
2563any modification of the parent unit or one of its subunits affects the
2564compilation of O.
2565
2566@item
2567The object file for a parent unit depends on all its subunit body files.
2568
2569@item
2570The previous two rules meant that for purposes of computing dependencies and
2571recompilation, a body and all its subunits are treated as an indivisible whole.
2572
2573@noindent
2574These rules are applied transitively: if unit @code{A} @code{with}'s
2575unit @code{B}, whose elaboration calls an inlined procedure in package
2576@code{C}, the object file for unit @code{A} will depend on the body of
2577@code{C}, in file @file{c.adb}.
2578
2579The set of dependent files described by these rules includes all the
2580files on which the unit is semantically dependent, as described in the
2581Ada 95 Language Reference Manual. However, it is a superset of what the
2582ARM describes, because it includes generic, inline, and subunit dependencies.
2583
2584An object file must be recreated by recompiling the corresponding source
2585file if any of the source files on which it depends are modified. For
2586example, if the @code{make} utility is used to control compilation,
2587the rule for an Ada object file must mention all the source files on
2588which the object file depends, according to the above definition.
2589The determination of the necessary
2590recompilations is done automatically when one uses @code{gnatmake}.
2591@end itemize
2592
2593@node The Ada Library Information Files
2594@section The Ada Library Information Files
2595@cindex Ada Library Information files
2596@cindex @file{ALI} files
2597
2598@noindent
2599Each compilation actually generates two output files. The first of these
2600is the normal object file that has a @file{.o} extension. The second is a
2601text file containing full dependency information. It has the same
2602name as the source file, but an @file{.ali} extension.
2603This file is known as the Ada Library Information (@file{ALI}) file.
2604The following information is contained in the @file{ALI} file.
2605
2606@itemize @bullet
2607@item
2608Version information (indicates which version of GNAT was used to compile
2609the unit(s) in question)
2610
2611@item
2612Main program information (including priority and time slice settings,
2613as well as the wide character encoding used during compilation).
2614
2615@item
2616List of arguments used in the @code{gcc} command for the compilation
2617
2618@item
2619Attributes of the unit, including configuration pragmas used, an indication
2620of whether the compilation was successful, exception model used etc.
2621
2622@item
2623A list of relevant restrictions applying to the unit (used for consistency)
2624checking.
2625
2626@item
2627Categorization information (e.g. use of pragma @code{Pure}).
2628
2629@item
2630Information on all @code{with}'ed units, including presence of
2631@code{Elaborate} or @code{Elaborate_All} pragmas.
2632
2633@item
2634Information from any @code{Linker_Options} pragmas used in the unit
2635
2636@item
2637Information on the use of @code{Body_Version} or @code{Version}
2638attributes in the unit.
2639
2640@item
2641Dependency information. This is a list of files, together with
2642time stamp and checksum information. These are files on which
2643the unit depends in the sense that recompilation is required
2644if any of these units are modified.
2645
2646@item
2647Cross-reference data. Contains information on all entities referenced
2648in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2649provide cross-reference information.
2650
2651@end itemize
2652
2653@noindent
2654For a full detailed description of the format of the @file{ALI} file,
2655see the source of the body of unit @code{Lib.Writ}, contained in file
2656@file{lib-writ.adb} in the GNAT compiler sources.
2657
2658@node Binding an Ada Program
2659@section Binding an Ada Program
2660
2661@noindent
2662When using languages such as C and C++, once the source files have been
2663compiled the only remaining step in building an executable program
2664is linking the object modules together. This means that it is possible to
2665link an inconsistent version of a program, in which two units have
2666included different versions of the same header.
2667
2668The rules of Ada do not permit such an inconsistent program to be built.
2669For example, if two clients have different versions of the same package,
2670it is illegal to build a program containing these two clients.
2671These rules are enforced by the GNAT binder, which also determines an
2672elaboration order consistent with the Ada rules.
2673
2674The GNAT binder is run after all the object files for a program have
2675been created. It is given the name of the main program unit, and from
2676this it determines the set of units required by the program, by reading the
2677corresponding ALI files. It generates error messages if the program is
2678inconsistent or if no valid order of elaboration exists.
2679
2680If no errors are detected, the binder produces a main program, in Ada by
2681default, that contains calls to the elaboration procedures of those
2682compilation unit that require them, followed by
2683a call to the main program. This Ada program is compiled to generate the
2684object file for the main program. The name of
2685the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2686@file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2687main program unit.
2688
2689Finally, the linker is used to build the resulting executable program,
2690using the object from the main program from the bind step as well as the
2691object files for the Ada units of the program.
2692
2693@node Mixed Language Programming
2694@section Mixed Language Programming
2695@cindex Mixed Language Programming
2696
2697@noindent
2698This section describes how to develop a mixed-language program,
2699specifically one that comprises units in both Ada and C.
2700
2701@menu
2702* Interfacing to C::
2703* Calling Conventions::
2704@end menu
2705
2706@node Interfacing to C
2707@subsection Interfacing to C
2708@noindent
2709Interfacing Ada with a foreign language such as C involves using
2710compiler directives to import and/or export entity definitions in each
2711language---using @code{extern} statements in C, for instance, and the
2712@code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2713a full treatment of these topics, read Appendix B, section 1 of the Ada
271495 Language Reference Manual.
2715
2716There are two ways to build a program using GNAT that contains some Ada
2717sources and some foreign language sources, depending on whether or not
2718the main subprogram is written in Ada.  Here is a source example with
2719the main subprogram in Ada:
2720
2721@smallexample
2722/* file1.c */
2723#include <stdio.h>
2724
2725void print_num (int num)
2726@{
2727  printf ("num is %d.\n", num);
2728  return;
2729@}
2730
2731/* file2.c */
2732
2733/* num_from_Ada is declared in my_main.adb */
2734extern int num_from_Ada;
2735
2736int get_num (void)
2737@{
2738  return num_from_Ada;
2739@}
2740@end smallexample
2741
2742@smallexample @c ada
2743--  my_main.adb
2744procedure My_Main is
2745
2746   --  Declare then export an Integer entity called num_from_Ada
2747   My_Num : Integer := 10;
2748   pragma Export (C, My_Num, "num_from_Ada");
2749
2750   --  Declare an Ada function spec for Get_Num, then use
2751   --  C function get_num for the implementation.
2752   function Get_Num return Integer;
2753   pragma Import (C, Get_Num, "get_num");
2754
2755   --  Declare an Ada procedure spec for Print_Num, then use
2756   --  C function print_num for the implementation.
2757   procedure Print_Num (Num : Integer);
2758   pragma Import (C, Print_Num, "print_num");
2759
2760begin
2761   Print_Num (Get_Num);
2762end My_Main;
2763@end smallexample
2764
2765@enumerate
2766@item
2767To build this example, first compile the foreign language files to
2768generate object files:
2769@smallexample
2770gcc -c file1.c
2771gcc -c file2.c
2772@end smallexample
2773
2774@item
2775Then, compile the Ada units to produce a set of object files and ALI
2776files:
2777@smallexample
2778gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2779@end smallexample
2780
2781@item
2782Run the Ada binder on the Ada main program:
2783@smallexample
2784gnatbind my_main.ali
2785@end smallexample
2786
2787@item
2788Link the Ada main program, the Ada objects and the other language
2789objects:
2790@smallexample
2791gnatlink my_main.ali file1.o file2.o
2792@end smallexample
2793@end enumerate
2794
2795The last three steps can be grouped in a single command:
2796@smallexample
2797gnatmake my_main.adb -largs file1.o file2.o
2798@end smallexample
2799
2800@cindex Binder output file
2801@noindent
2802If the main program is in a language other than Ada, then you may have
2803more than one entry point into the Ada subsystem. You must use a special
2804binder option to generate callable routines that initialize and
2805finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2806Calls to the initialization and finalization routines must be inserted
2807in the main program, or some other appropriate point in the code. The
2808call to initialize the Ada units must occur before the first Ada
2809subprogram is called, and the call to finalize the Ada units must occur
2810after the last Ada subprogram returns. The binder will place the
2811initialization and finalization subprograms into the
2812@file{b~@var{xxx}.adb} file where they can be accessed by your C
2813sources.  To illustrate, we have the following example:
2814
2815@smallexample
2816/* main.c */
2817extern void adainit (void);
2818extern void adafinal (void);
2819extern int add (int, int);
2820extern int sub (int, int);
2821
2822int main (int argc, char *argv[])
2823@{
2824  int a = 21, b = 7;
2825
2826  adainit();
2827
2828  /* Should print "21 + 7 = 28" */
2829  printf ("%d + %d = %d\n", a, b, add (a, b));
2830  /* Should print "21 - 7 = 14" */
2831  printf ("%d - %d = %d\n", a, b, sub (a, b));
2832
2833  adafinal();
2834@}
2835@end smallexample
2836
2837@smallexample @c ada
2838--  unit1.ads
2839package Unit1 is
2840   function Add (A, B : Integer) return Integer;
2841   pragma Export (C, Add, "add");
2842end Unit1;
2843
2844--  unit1.adb
2845package body Unit1 is
2846   function Add (A, B : Integer) return Integer is
2847   begin
2848      return A + B;
2849   end Add;
2850end Unit1;
2851
2852--  unit2.ads
2853package Unit2 is
2854   function Sub (A, B : Integer) return Integer;
2855   pragma Export (C, Sub, "sub");
2856end Unit2;
2857
2858--  unit2.adb
2859package body Unit2 is
2860   function Sub (A, B : Integer) return Integer is
2861   begin
2862      return A - B;
2863   end Sub;
2864end Unit2;
2865@end smallexample
2866
2867@enumerate
2868@item
2869The build procedure for this application is similar to the last
2870example's.  First, compile the foreign language files to generate object
2871files:
2872@smallexample
2873gcc -c main.c
2874@end smallexample
2875
2876@item
2877Next, compile the Ada units to produce a set of object files and ALI
2878files:
2879@smallexample
2880gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2881gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2882@end smallexample
2883
2884@item
2885Run the Ada binder on every generated ALI file.  Make sure to use the
2886@option{-n} option to specify a foreign main program:
2887@smallexample
2888gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2889@end smallexample
2890
2891@item
2892Link the Ada main program, the Ada objects and the foreign language
2893objects. You need only list the last ALI file here:
2894@smallexample
2895gnatlink unit2.ali main.o -o exec_file
2896@end smallexample
2897
2898This procedure yields a binary executable called @file{exec_file}.
2899@end enumerate
2900
2901@node Calling Conventions
2902@subsection Calling Conventions
2903@cindex Foreign Languages
2904@cindex Calling Conventions
2905GNAT follows standard calling sequence conventions and will thus interface
2906to any other language that also follows these conventions. The following
2907Convention identifiers are recognized by GNAT:
2908
2909@table @code
2910@cindex Interfacing to Ada
2911@cindex Other Ada compilers
2912@cindex Convention Ada
2913@item Ada
2914This indicates that the standard Ada calling sequence will be
2915used and all Ada data items may be passed without any limitations in the
2916case where GNAT is used to generate both the caller and callee. It is also
2917possible to mix GNAT generated code and code generated by another Ada
2918compiler. In this case, the data types should be restricted to simple
2919cases, including primitive types. Whether complex data types can be passed
2920depends on the situation. Probably it is safe to pass simple arrays, such
2921as arrays of integers or floats. Records may or may not work, depending
2922on whether both compilers lay them out identically. Complex structures
2923involving variant records, access parameters, tasks, or protected types,
2924are unlikely to be able to be passed.
2925
2926Note that in the case of GNAT running
2927on a platform that supports DEC Ada 83, a higher degree of compatibility
2928can be guaranteed, and in particular records are layed out in an identical
2929manner in the two compilers. Note also that if output from two different
2930compilers is mixed, the program is responsible for dealing with elaboration
2931issues. Probably the safest approach is to write the main program in the
2932version of Ada other than GNAT, so that it takes care of its own elaboration
2933requirements, and then call the GNAT-generated adainit procedure to ensure
2934elaboration of the GNAT components. Consult the documentation of the other
2935Ada compiler for further details on elaboration.
2936
2937However, it is not possible to mix the tasking run time of GNAT and
2938DEC Ada 83, All the tasking operations must either be entirely within
2939GNAT compiled sections of the program, or entirely within DEC Ada 83
2940compiled sections of the program.
2941
2942@cindex Interfacing to Assembly
2943@cindex Convention Assembler
2944@item Assembler
2945Specifies assembler as the convention. In practice this has the
2946same effect as convention Ada (but is not equivalent in the sense of being
2947considered the same convention).
2948
2949@cindex Convention Asm
2950@findex Asm
2951@item Asm
2952Equivalent to Assembler.
2953
2954@cindex Interfacing to COBOL
2955@cindex Convention COBOL
2956@findex COBOL
2957@item COBOL
2958Data will be passed according to the conventions described
2959in section B.4 of the Ada 95 Reference Manual.
2960
2961@findex C
2962@cindex Interfacing to C
2963@cindex Convention C
2964@item C
2965Data will be passed according to the conventions described
2966in section B.3 of the Ada 95 Reference Manual.
2967
2968@cindex Convention Default
2969@findex Default
2970@item Default
2971Equivalent to C.
2972
2973@cindex Convention External
2974@findex External
2975@item External
2976Equivalent to C.
2977
2978@findex C++
2979@cindex Interfacing to C++
2980@cindex Convention C++
2981@item CPP
2982This stands for C++. For most purposes this is identical to C.
2983See the separate description of the specialized GNAT pragmas relating to
2984C++ interfacing for further details.
2985
2986@findex Fortran
2987@cindex Interfacing to Fortran
2988@cindex Convention Fortran
2989@item Fortran
2990Data will be passed according to the conventions described
2991in section B.5 of the Ada 95 Reference Manual.
2992
2993@item Intrinsic
2994This applies to an intrinsic operation, as defined in the Ada 95
2995Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2996this means that the body of the subprogram is provided by the compiler itself,
2997usually by means of an efficient code sequence, and that the user does not
2998supply an explicit body for it. In an application program, the pragma can
2999only be applied to the following two sets of names, which the GNAT compiler
3000recognizes.
3001
3002@itemize @bullet
3003@item
3004Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3005Arithmetic.  The corresponding subprogram declaration must have
3006two formal parameters. The
3007first one must be a signed integer type or a modular type with a binary
3008modulus, and the second parameter must be of type Natural.
3009The return type must be the same as the type of the first argument. The size
3010of this type can only be 8, 16, 32, or 64.
3011@item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3012The corresponding operator declaration must have parameters and result type
3013that have the same root numeric type (for example, all three are long_float
3014types). This simplifies the definition of operations that use type checking
3015to perform dimensional checks:
3016
3017@smallexample @c ada
3018type Distance is new Long_Float;
3019type Time     is new Long_Float;
3020type Velocity is new Long_Float;
3021function "/" (D : Distance; T : Time)
3022  return Velocity;
3023pragma Import (Intrinsic, "/");
3024@end smallexample
3025
3026@noindent
3027This common idiom is often programmed with a generic definition and an
3028explicit body. The pragma makes it simpler to introduce such declarations.
3029It incurs no overhead in compilation time or code size, because it is
3030implemented as a single machine instruction.
3031@end itemize
3032@noindent
3033
3034@ifset unw
3035@findex Stdcall
3036@cindex Convention Stdcall
3037@item Stdcall
3038This is relevant only to NT/Win95 implementations of GNAT,
3039and specifies that the Stdcall calling sequence will be used, as defined
3040by the NT API.
3041
3042@findex DLL
3043@cindex Convention DLL
3044@item DLL
3045This is equivalent to Stdcall.
3046
3047@findex Win32
3048@cindex Convention Win32
3049@item Win32
3050This is equivalent to Stdcall.
3051@end ifset
3052
3053@findex Stubbed
3054@cindex Convention Stubbed
3055@item Stubbed
3056This is a special convention that indicates that the compiler
3057should provide a stub body that raises @code{Program_Error}.
3058@end table
3059
3060@noindent
3061GNAT additionally provides a useful pragma @code{Convention_Identifier}
3062that can be used to parametrize conventions and allow additional synonyms
3063to be specified. For example if you have legacy code in which the convention
3064identifier Fortran77 was used for Fortran, you can use the configuration
3065pragma:
3066
3067@smallexample @c ada
3068pragma Convention_Identifier (Fortran77, Fortran);
3069@end smallexample
3070
3071@noindent
3072And from now on the identifier Fortran77 may be used as a convention
3073identifier (for example in an @code{Import} pragma) with the same
3074meaning as Fortran.
3075
3076@node Building Mixed Ada & C++ Programs
3077@section Building Mixed Ada & C++ Programs
3078
3079@noindent
3080A programmer inexperienced with mixed-language development may find that
3081building an application containing both Ada and C++ code can be a
3082challenge. As a matter of fact, interfacing with C++ has not been
3083standardized in the Ada 95 Reference Manual due to the immaturity of --
3084and lack of standards for -- C++ at the time. This section gives a few
3085hints that should make this task easier. The first section addresses
3086the differences regarding interfacing with C. The second section
3087looks into the delicate problem of linking the complete application from
3088its Ada and C++ parts. The last section gives some hints on how the GNAT
3089run time can be adapted in order to allow inter-language dispatching
3090with a new C++ compiler.
3091
3092@menu
3093* Interfacing to C++::
3094* Linking a Mixed C++ & Ada Program::
3095* A Simple Example::
3096* Adapting the Run Time to a New C++ Compiler::
3097@end menu
3098
3099@node Interfacing to C++
3100@subsection Interfacing to C++
3101
3102@noindent
3103GNAT supports interfacing with C++ compilers generating code that is
3104compatible with the standard Application Binary Interface of the given
3105platform.
3106
3107@noindent
3108Interfacing can be done at 3 levels: simple data, subprograms, and
3109classes. In the first two cases, GNAT offers a specific @var{Convention
3110CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3111the names of subprograms, and currently, GNAT does not provide any help
3112to solve the demangling problem. This problem can be addressed in two
3113ways:
3114@itemize @bullet
3115@item
3116by modifying the C++ code in order to force a C convention using
3117the @code{extern "C"} syntax.
3118
3119@item
3120by figuring out the mangled name and use it as the Link_Name argument of
3121the pragma import.
3122@end itemize
3123
3124@noindent
3125Interfacing at the class level can be achieved by using the GNAT specific
3126pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3127Reference Manual for additional information.
3128
3129@node Linking a Mixed C++ & Ada Program
3130@subsection Linking a Mixed C++ & Ada Program
3131
3132@noindent
3133Usually the linker of the C++ development system must be used to link
3134mixed applications because most C++ systems will resolve elaboration
3135issues (such as calling constructors on global class instances)
3136transparently during the link phase. GNAT has been adapted to ease the
3137use of a foreign linker for the last phase. Three cases can be
3138considered:
3139@enumerate
3140
3141@item
3142Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3143The C++ linker can simply be called by using the C++ specific driver
3144called @code{c++}. Note that this setup is not very common because it
3145may involve recompiling the whole GCC tree from sources, which makes it
3146harder to upgrade the compilation system for one language without
3147destabilizing the other.
3148
3149@smallexample
3150$ c++ -c file1.C
3151$ c++ -c file2.C
3152$ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3153@end smallexample
3154
3155@item
3156Using GNAT and G++ from two different GCC installations: If both
3157compilers are on the PATH, the previous method may be used. It is
3158important to note that environment variables such as C_INCLUDE_PATH,
3159GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3160at the same time and may make one of the two compilers operate
3161improperly if set during invocation of the wrong compiler.  It is also
3162very important that the linker uses the proper @file{libgcc.a} GCC
3163library -- that is, the one from the C++ compiler installation. The
3164implicit link command as suggested in the gnatmake command from the
3165former example can be replaced by an explicit link command with the
3166full-verbosity option in order to verify which library is used:
3167@smallexample
3168$ gnatbind ada_unit
3169$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3170@end smallexample
3171If there is a problem due to interfering environment variables, it can
3172be worked around by using an intermediate script. The following example
3173shows the proper script to use when GNAT has not been installed at its
3174default location and g++ has been installed at its default location:
3175
3176@smallexample
3177$ cat ./my_script
3178#!/bin/sh
3179unset BINUTILS_ROOT
3180unset GCC_ROOT
3181c++ $*
3182$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3183@end smallexample
3184
3185@item
3186Using a non-GNU C++ compiler: The commands previously described can be
3187used to insure that the C++ linker is used. Nonetheless, you need to add
3188the path to libgcc explicitly, since some libraries needed by GNAT are
3189located in this directory:
3190
3191@smallexample
3192$ cat ./my_script
3193#!/bin/sh
3194CC $* `gcc -print-libgcc-file-name`
3195$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3196@end smallexample
3197
3198Where CC is the name of the non-GNU C++ compiler.
3199
3200@end enumerate
3201
3202@node A Simple Example
3203@subsection  A Simple Example
3204@noindent
3205The following example, provided as part of the GNAT examples, shows how
3206to achieve procedural interfacing between Ada and C++ in both
3207directions. The C++ class A has two methods. The first method is exported
3208to Ada by the means of an extern C wrapper function. The second method
3209calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3210a limited record with a layout comparable to the C++ class. The Ada
3211subprogram, in turn, calls the C++ method. So, starting from the C++
3212main program, the process passes back and forth between the two
3213languages.
3214
3215@noindent
3216Here are the compilation commands:
3217@smallexample
3218$ gnatmake -c simple_cpp_interface
3219$ c++ -c cpp_main.C
3220$ c++ -c ex7.C
3221$ gnatbind -n simple_cpp_interface
3222$ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3223      -lstdc++ ex7.o cpp_main.o
3224@end smallexample
3225
3226@noindent
3227Here are the corresponding sources:
3228@smallexample
3229
3230//cpp_main.C
3231
3232#include "ex7.h"
3233
3234extern "C" @{
3235  void adainit (void);
3236  void adafinal (void);
3237  void method1 (A *t);
3238@}
3239
3240void method1 (A *t)
3241@{
3242  t->method1 ();
3243@}
3244
3245int main ()
3246@{
3247  A obj;
3248  adainit ();
3249  obj.method2 (3030);
3250  adafinal ();
3251@}
3252
3253//ex7.h
3254
3255class Origin @{
3256 public:
3257  int o_value;
3258@};
3259class A : public Origin @{
3260 public:
3261  void method1 (void);
3262  virtual void method2 (int v);
3263  A();
3264  int   a_value;
3265@};
3266
3267//ex7.C
3268
3269#include "ex7.h"
3270#include <stdio.h>
3271
3272extern "C" @{ void ada_method2 (A *t, int v);@}
3273
3274void A::method1 (void)
3275@{
3276  a_value = 2020;
3277  printf ("in A::method1, a_value = %d \n",a_value);
3278
3279@}
3280
3281void A::method2 (int v)
3282@{
3283   ada_method2 (this, v);
3284   printf ("in A::method2, a_value = %d \n",a_value);
3285
3286@}
3287
3288A::A(void)
3289@{
3290   a_value = 1010;
3291  printf ("in A::A, a_value = %d \n",a_value);
3292@}
3293
3294-- Ada sources
3295@b{package} @b{body} Simple_Cpp_Interface @b{is}
3296
3297   @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3298   @b{begin}
3299      Method1 (This);
3300      This.A_Value := V;
3301   @b{end} Ada_Method2;
3302
3303@b{end} Simple_Cpp_Interface;
3304
3305@b{package} Simple_Cpp_Interface @b{is}
3306   @b{type} A @b{is} @b{limited}
3307      @b{record}
3308         O_Value : Integer;
3309         A_Value : Integer;
3310      @b{end} @b{record};
3311   @b{pragma} Convention (C, A);
3312
3313   @b{procedure} Method1 (This : @b{in} @b{out} A);
3314   @b{pragma} Import (C, Method1);
3315
3316   @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3317   @b{pragma} Export (C, Ada_Method2);
3318
3319@b{end} Simple_Cpp_Interface;
3320@end smallexample
3321
3322@node Adapting the Run Time to a New C++ Compiler
3323@subsection Adapting the Run Time to a New C++ Compiler
3324@noindent
3325GNAT offers the capability to derive Ada 95 tagged types directly from
3326preexisting C++ classes and . See ``Interfacing with C++'' in the
3327@cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3328such a goal
3329has been made user configurable through a GNAT library unit
3330@code{Interfaces.CPP}. The default version of this file is adapted to
3331the GNU C++ compiler. Internal knowledge of the virtual
3332table layout used by the new C++ compiler is needed to configure
3333properly this unit. The Interface of this unit is known by the compiler
3334and cannot be changed except for the value of the constants defining the
3335characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3336CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3337of this unit for more details.
3338
3339@node Comparison between GNAT and C/C++ Compilation Models
3340@section Comparison between GNAT and C/C++ Compilation Models
3341
3342@noindent
3343The GNAT model of compilation is close to the C and C++ models. You can
3344think of Ada specs as corresponding to header files in C. As in C, you
3345don't need to compile specs; they are compiled when they are used. The
3346Ada @code{with} is similar in effect to the @code{#include} of a C
3347header.
3348
3349One notable difference is that, in Ada, you may compile specs separately
3350to check them for semantic and syntactic accuracy. This is not always
3351possible with C headers because they are fragments of programs that have
3352less specific syntactic or semantic rules.
3353
3354The other major difference is the requirement for running the binder,
3355which performs two important functions. First, it checks for
3356consistency. In C or C++, the only defense against assembling
3357inconsistent programs lies outside the compiler, in a makefile, for
3358example. The binder satisfies the Ada requirement that it be impossible
3359to construct an inconsistent program when the compiler is used in normal
3360mode.
3361
3362@cindex Elaboration order control
3363The other important function of the binder is to deal with elaboration
3364issues. There are also elaboration issues in C++ that are handled
3365automatically. This automatic handling has the advantage of being
3366simpler to use, but the C++ programmer has no control over elaboration.
3367Where @code{gnatbind} might complain there was no valid order of
3368elaboration, a C++ compiler would simply construct a program that
3369malfunctioned at run time.
3370
3371@node Comparison between GNAT and Conventional Ada Library Models
3372@section Comparison between GNAT and Conventional Ada Library Models
3373
3374@noindent
3375This section is intended to be useful to Ada programmers who have
3376previously used an Ada compiler implementing the traditional Ada library
3377model, as described in the Ada 95 Language Reference Manual. If you
3378have not used such a system, please go on to the next section.
3379
3380@cindex GNAT library
3381In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3382source files themselves acts as the library. Compiling Ada programs does
3383not generate any centralized information, but rather an object file and
3384a ALI file, which are of interest only to the binder and linker.
3385In a traditional system, the compiler reads information not only from
3386the source file being compiled, but also from the centralized library.
3387This means that the effect of a compilation depends on what has been
3388previously compiled. In particular:
3389
3390@itemize @bullet
3391@item
3392When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3393to the version of the unit most recently compiled into the library.
3394
3395@item
3396Inlining is effective only if the necessary body has already been
3397compiled into the library.
3398
3399@item
3400Compiling a unit may obsolete other units in the library.
3401@end itemize
3402
3403@noindent
3404In GNAT, compiling one unit never affects the compilation of any other
3405units because the compiler reads only source files. Only changes to source
3406files can affect the results of a compilation. In particular:
3407
3408@itemize @bullet
3409@item
3410When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3411to the source version of the unit that is currently accessible to the
3412compiler.
3413
3414@item
3415@cindex Inlining
3416Inlining requires the appropriate source files for the package or
3417subprogram bodies to be available to the compiler. Inlining is always
3418effective, independent of the order in which units are complied.
3419
3420@item
3421Compiling a unit never affects any other compilations. The editing of
3422sources may cause previous compilations to be out of date if they
3423depended on the source file being modified.
3424@end itemize
3425
3426@noindent
3427The most important result of these differences is that order of compilation
3428is never significant in GNAT. There is no situation in which one is
3429required to do one compilation before another. What shows up as order of
3430compilation requirements in the traditional Ada library becomes, in
3431GNAT, simple source dependencies; in other words, there is only a set
3432of rules saying what source files must be present when a file is
3433compiled.
3434
3435@ifset vms
3436@node Placement of temporary files
3437@section Placement of temporary files
3438@cindex Temporary files (user control over placement)
3439
3440@noindent
3441GNAT creates temporary files in the directory designated by the environment
3442variable @env{TMPDIR}.
3443(See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3444for detailed information on how environment variables are resolved.
3445For most users the easiest way to make use of this feature is to simply
3446define @env{TMPDIR} as a job level logical name).
3447For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3448for compiler temporary files, then you can include something like the
3449following command in your @file{LOGIN.COM} file:
3450
3451@smallexample
3452$ define/job TMPDIR "/disk$scratchram/000000/temp/"
3453@end smallexample
3454
3455@noindent
3456If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3457@env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3458designated by @env{TEMP}.
3459If none of these environment variables are defined then GNAT uses the
3460directory designated by the logical name @code{SYS$SCRATCH:}
3461(by default the user's home directory). If all else fails
3462GNAT uses the current directory for temporary files.
3463@end ifset
3464
3465
3466@c *************************
3467@node Compiling Using gcc
3468@chapter Compiling Using @code{gcc}
3469
3470@noindent
3471This chapter discusses how to compile Ada programs using the @code{gcc}
3472command. It also describes the set of switches
3473that can be used to control the behavior of the compiler.
3474@menu
3475* Compiling Programs::
3476* Switches for gcc::
3477* Search Paths and the Run-Time Library (RTL)::
3478* Order of Compilation Issues::
3479* Examples::
3480@end menu
3481
3482@node Compiling Programs
3483@section Compiling Programs
3484
3485@noindent
3486The first step in creating an executable program is to compile the units
3487of the program using the @code{gcc} command. You must compile the
3488following files:
3489
3490@itemize @bullet
3491@item
3492the body file (@file{.adb}) for a library level subprogram or generic
3493subprogram
3494
3495@item
3496the spec file (@file{.ads}) for a library level package or generic
3497package that has no body
3498
3499@item
3500the body file (@file{.adb}) for a library level package
3501or generic package that has a body
3502
3503@end itemize
3504
3505@noindent
3506You need @emph{not} compile the following files
3507
3508@itemize @bullet
3509
3510@item
3511the spec of a library unit which has a body
3512
3513@item
3514subunits
3515@end itemize
3516
3517@noindent
3518because they are compiled as part of compiling related units. GNAT
3519package specs
3520when the corresponding body is compiled, and subunits when the parent is
3521compiled.
3522
3523@cindex cannot generate code
3524If you attempt to compile any of these files, you will get one of the
3525following error messages (where fff is the name of the file you compiled):
3526
3527@smallexample
3528cannot generate code for file @var{fff} (package spec)
3529to check package spec, use -gnatc
3530
3531cannot generate code for file @var{fff} (missing subunits)
3532to check parent unit, use -gnatc
3533
3534cannot generate code for file @var{fff} (subprogram spec)
3535to check subprogram spec, use -gnatc
3536
3537cannot generate code for file @var{fff} (subunit)
3538to check subunit, use -gnatc
3539@end smallexample
3540
3541@noindent
3542As indicated by the above error messages, if you want to submit
3543one of these files to the compiler to check for correct semantics
3544without generating code, then use the @option{-gnatc} switch.
3545
3546The basic command for compiling a file containing an Ada unit is
3547
3548@smallexample
3549$ gcc -c [@var{switches}] @file{file name}
3550@end smallexample
3551
3552@noindent
3553where @var{file name} is the name of the Ada file (usually
3554having an extension
3555@file{.ads} for a spec or @file{.adb} for a body).
3556@ifclear vms
3557You specify the
3558@option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3559@end ifclear
3560The result of a successful compilation is an object file, which has the
3561same name as the source file but an extension of @file{.o} and an Ada
3562Library Information (ALI) file, which also has the same name as the
3563source file, but with @file{.ali} as the extension. GNAT creates these
3564two output files in the current directory, but you may specify a source
3565file in any directory using an absolute or relative path specification
3566containing the directory information.
3567
3568@findex gnat1
3569@code{gcc} is actually a driver program that looks at the extensions of
3570the file arguments and loads the appropriate compiler. For example, the
3571GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3572These programs are in directories known to the driver program (in some
3573configurations via environment variables you set), but need not be in
3574your path. The @code{gcc} driver also calls the assembler and any other
3575utilities needed to complete the generation of the required object
3576files.
3577
3578It is possible to supply several file names on the same @code{gcc}
3579command. This causes @code{gcc} to call the appropriate compiler for
3580each file. For example, the following command lists three separate
3581files to be compiled:
3582
3583@smallexample
3584$ gcc -c x.adb y.adb z.c
3585@end smallexample
3586
3587@noindent
3588calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3589@file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3590The compiler generates three object files @file{x.o}, @file{y.o} and
3591@file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3592Ada compilations. Any switches apply to all the files ^listed,^listed.^
3593@ifclear vms
3594except for
3595@option{-gnat@var{x}} switches, which apply only to Ada compilations.
3596@end ifclear
3597
3598@node Switches for gcc
3599@section Switches for @code{gcc}
3600
3601@noindent
3602The @code{gcc} command accepts switches that control the
3603compilation process. These switches are fully described in this section.
3604First we briefly list all the switches, in alphabetical order, then we
3605describe the switches in more detail in functionally grouped sections.
3606
3607@menu
3608* Output and Error Message Control::
3609* Warning Message Control::
3610* Debugging and Assertion Control::
3611* Run-Time Checks::
3612* Stack Overflow Checking::
3613* Validity Checking::
3614* Style Checking::
3615* Using gcc for Syntax Checking::
3616* Using gcc for Semantic Checking::
3617* Compiling Ada 83 Programs::
3618* Character Set Control::
3619* File Naming Control::
3620* Subprogram Inlining Control::
3621* Auxiliary Output Control::
3622* Debugging Control::
3623* Exception Handling Control::
3624* Units to Sources Mapping Files::
3625* Integrated Preprocessing::
3626@ifset vms
3627* Return Codes::
3628@end ifset
3629@end menu
3630
3631@table @option
3632@c !sort!
3633@ifclear vms
3634@cindex @option{-b} (@code{gcc})
3635@item -b @var{target}
3636Compile your program to run on @var{target}, which is the name of a
3637system configuration. You must have a GNAT cross-compiler built if
3638@var{target} is not the same as your host system.
3639
3640@item -B@var{dir}
3641@cindex @option{-B} (@code{gcc})
3642Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3643from @var{dir} instead of the default location. Only use this switch
3644when multiple versions of the GNAT compiler are available. See the
3645@code{gcc} manual page for further details. You would normally use the
3646@option{-b} or @option{-V} switch instead.
3647
3648@item -c
3649@cindex @option{-c} (@code{gcc})
3650Compile. Always use this switch when compiling Ada programs.
3651
3652Note: for some other languages when using @code{gcc}, notably in
3653the case of C and C++, it is possible to use
3654use @code{gcc} without a @option{-c} switch to
3655compile and link in one step. In the case of GNAT, you
3656cannot use this approach, because the binder must be run
3657and @code{gcc} cannot be used to run the GNAT binder.
3658@end ifclear
3659
3660@item -fno-inline
3661@cindex @option{-fno-inline} (@code{gcc})
3662Suppresses all back-end inlining, even if other optimization or inlining
3663switches are set.
3664This includes suppression of inlining that results
3665from the use of the pragma @code{Inline_Always}.
3666See also @option{-gnatn} and @option{-gnatN}.
3667
3668@item -fstack-check
3669@cindex @option{-fstack-check} (@code{gcc})
3670Activates stack checking.
3671See @ref{Stack Overflow Checking}, for details of the use of this option.
3672
3673@item ^-g^/DEBUG^
3674@cindex @option{^-g^/DEBUG^} (@code{gcc})
3675Generate debugging information. This information is stored in the object
3676file and copied from there to the final executable file by the linker,
3677where it can be read by the debugger. You must use the
3678@option{^-g^/DEBUG^} switch if you plan on using the debugger.
3679
3680@item -gnat83
3681@cindex @option{-gnat83} (@code{gcc})
3682Enforce Ada 83 restrictions.
3683
3684@item -gnata
3685@cindex @option{-gnata} (@code{gcc})
3686Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3687activated.
3688
3689@item -gnatA
3690@cindex @option{-gnatA} (@code{gcc})
3691Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3692it will be ignored.
3693
3694@item -gnatb
3695@cindex @option{-gnatb} (@code{gcc})
3696Generate brief messages to @file{stderr} even if verbose mode set.
3697
3698@item -gnatc
3699@cindex @option{-gnatc} (@code{gcc})
3700Check syntax and semantics only (no code generation attempted).
3701
3702@item -gnatd
3703@cindex @option{-gnatd} (@code{gcc})
3704Specify debug options for the compiler. The string of characters after
3705the @option{-gnatd} specify the specific debug options. The possible
3706characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3707compiler source file @file{debug.adb} for details of the implemented
3708debug options. Certain debug options are relevant to applications
3709programmers, and these are documented at appropriate points in this
3710users guide.
3711
3712@item -gnatD
3713@cindex @option{-gnatD} (@code{gcc})
3714Output expanded source files for source level debugging. This switch
3715also suppress generation of cross-reference information
3716(see @option{-gnatx}).
3717
3718@item -gnatec=@var{path}
3719@cindex @option{-gnatec} (@code{gcc})
3720Specify a configuration pragma file
3721@ifclear vms
3722(the equal sign is optional)
3723@end ifclear
3724(see @ref{The Configuration Pragmas Files}).
3725
3726@item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3727@cindex @option{-gnateD} (@code{gcc})
3728Defines a symbol, associated with value, for preprocessing.
3729(see @ref{Integrated Preprocessing})
3730
3731@item -gnatef
3732@cindex @option{-gnatef} (@code{gcc})
3733Display full source path name in brief error messages.
3734
3735@item -gnatem=@var{path}
3736@cindex @option{-gnatem} (@code{gcc})
3737Specify a mapping file
3738@ifclear vms
3739(the equal sign is optional)
3740@end ifclear
3741(see @ref{Units to Sources Mapping Files}).
3742
3743@item -gnatep=@var{file}
3744@cindex @option{-gnatep} (@code{gcc})
3745Specify a preprocessing data file
3746@ifclear vms
3747(the equal sign is optional)
3748@end ifclear
3749(see @ref{Integrated Preprocessing}).
3750
3751@item -gnatE
3752@cindex @option{-gnatE} (@code{gcc})
3753Full dynamic elaboration checks.
3754
3755@item -gnatf
3756@cindex @option{-gnatf} (@code{gcc})
3757Full errors. Multiple errors per line, all undefined references, do not
3758attempt to suppress cascaded errors.
3759
3760@item -gnatF
3761@cindex @option{-gnatF} (@code{gcc})
3762Externals names are folded to all uppercase.
3763
3764@item -gnatg
3765@cindex @option{-gnatg} (@code{gcc})
3766Internal GNAT implementation mode. This should not be used for
3767applications programs, it is intended only for use by the compiler
3768and its run-time library. For documentation, see the GNAT sources.
3769Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3770are generated on unreferenced entities, and all warnings are treated
3771as errors.
3772
3773@item -gnatG
3774@cindex @option{-gnatG} (@code{gcc})
3775List generated expanded code in source form.
3776
3777@item ^-gnath^/HELP^
3778@cindex @option{^-gnath^/HELP^} (@code{gcc})
3779Output usage information. The output is written to @file{stdout}.
3780
3781@item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3782@cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3783Identifier character set
3784@ifclear vms
3785(@var{c}=1/2/3/4/8/9/p/f/n/w).
3786@end ifclear
3787@ifset vms
3788For details of the possible selections for @var{c},
3789see @xref{Character Set Control}.
3790@end ifset
3791
3792@item -gnatk=@var{n}
3793@cindex @option{-gnatk} (@code{gcc})
3794Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3795
3796@item -gnatl
3797@cindex @option{-gnatl} (@code{gcc})
3798Output full source listing with embedded error messages.
3799
3800@item -gnatL
3801@cindex @option{-gnatL} (@code{gcc})
3802Use the longjmp/setjmp method for exception handling
3803
3804@item -gnatm=@var{n}
3805@cindex @option{-gnatm} (@code{gcc})
3806Limit number of detected error or warning messages to @var{n}
3807where @var{n} is in the range 1..999_999. The default setting if
3808no switch is given is 9999. Compilation is terminated if this
3809limit is exceeded.
3810
3811@item -gnatn
3812@cindex @option{-gnatn} (@code{gcc})
3813Activate inlining for subprograms for which
3814pragma @code{inline} is specified. This inlining is performed
3815by the GCC back-end.
3816
3817@item -gnatN
3818@cindex @option{-gnatN} (@code{gcc})
3819Activate front end inlining for subprograms for which
3820pragma @code{Inline} is specified. This inlining is performed
3821by the front end and will be visible in the
3822@option{-gnatG} output.
3823In some cases, this has proved more effective than the back end
3824inlining resulting from the use of
3825@option{-gnatn}.
3826Note that
3827@option{-gnatN} automatically implies
3828@option{-gnatn} so it is not necessary
3829to specify both options. There are a few cases that the back-end inlining
3830catches that cannot be dealt with in the front-end.
3831
3832@item -gnato
3833@cindex @option{-gnato} (@code{gcc})
3834Enable numeric overflow checking (which is not normally enabled by
3835default). Not that division by zero is a separate check that is not
3836controlled by this switch (division by zero checking is on by default).
3837
3838@item -gnatp
3839@cindex @option{-gnatp} (@code{gcc})
3840Suppress all checks.
3841
3842@item -gnatP
3843@cindex @option{-gnatP} (@code{gcc})
3844Enable polling. This is required on some systems (notably Windows NT) to
3845obtain asynchronous abort and asynchronous transfer of control capability.
3846See the description of pragma Polling in the GNAT Reference Manual for
3847full details.
3848
3849@item -gnatq
3850@cindex @option{-gnatq} (@code{gcc})
3851Don't quit; try semantics, even if parse errors.
3852
3853@item -gnatQ
3854@cindex @option{-gnatQ} (@code{gcc})
3855Don't quit; generate @file{ALI} and tree files even if illegalities.
3856
3857@item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3858@cindex @option{-gnatR} (@code{gcc})
3859Output representation information for declared types and objects.
3860
3861@item -gnats
3862@cindex @option{-gnats} (@code{gcc})
3863Syntax check only.
3864
3865@item -gnatS
3866@cindex @option{-gnatS} (@code{gcc})
3867Print package Standard.
3868
3869@item -gnatt
3870@cindex @option{-gnatt} (@code{gcc})
3871Generate tree output file.
3872
3873@item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3874@cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3875All compiler tables start at @var{nnn} times usual starting size.
3876
3877@item -gnatu
3878@cindex @option{-gnatu} (@code{gcc})
3879List units for this compilation.
3880
3881@item -gnatU
3882@cindex @option{-gnatU} (@code{gcc})
3883Tag all error messages with the unique string ``error:''
3884
3885@item -gnatv
3886@cindex @option{-gnatv} (@code{gcc})
3887Verbose mode. Full error output with source lines to @file{stdout}.
3888
3889@item -gnatV
3890@cindex @option{-gnatV} (@code{gcc})
3891Control level of validity checking. See separate section describing
3892this feature.
3893
3894@item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3895@cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3896Warning mode where
3897^@var{xxx} is a string of option letters that^the list of options^ denotes
3898the exact warnings that
3899are enabled or disabled. (see @ref{Warning Message Control})
3900
3901@item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3902@cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3903Wide character encoding method
3904@ifclear vms
3905(@var{e}=n/h/u/s/e/8).
3906@end ifclear
3907@ifset vms
3908(@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3909@end ifset
3910
3911@item -gnatx
3912@cindex @option{-gnatx} (@code{gcc})
3913Suppress generation of cross-reference information.
3914
3915@item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3916@cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3917Enable built-in style checks. (see @ref{Style Checking})
3918
3919@item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3920@cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3921Distribution stub generation and compilation
3922@ifclear vms
3923(@var{m}=r/c for receiver/caller stubs).
3924@end ifclear
3925@ifset vms
3926(@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3927to be generated and compiled).
3928@end ifset
3929
3930@item -gnatZ
3931Use the zero cost method for exception handling
3932
3933@item ^-I^/SEARCH=^@var{dir}
3934@cindex @option{^-I^/SEARCH^} (@code{gcc})
3935@cindex RTL
3936Direct GNAT to search the @var{dir} directory for source files needed by
3937the current compilation
3938(@pxref{Search Paths and the Run-Time Library (RTL)}).
3939
3940@item ^-I-^/NOCURRENT_DIRECTORY^
3941@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3942@cindex RTL
3943Except for the source file named in the command line, do not look for source
3944files in the directory containing the source file named in the command line
3945(@pxref{Search Paths and the Run-Time Library (RTL)}).
3946
3947@ifclear vms
3948@item -mbig-switch
3949@cindex @option{-mbig-switch} (@command{gcc})
3950@cindex @code{case} statement (effect of @option{-mbig-switch} option)
3951This standard gcc switch causes the compiler to use larger offsets in its
3952jump table representation for @code{case} statements.
3953This may result in less efficient code, but is sometimes necessary
3954(for example on HP-UX targets)
3955@cindex HP-UX and @option{-mbig-switch} option
3956in order to compile large and/or nested @code{case} statements.
3957
3958@item -o @var{file}
3959@cindex @option{-o} (@code{gcc})
3960This switch is used in @code{gcc} to redirect the generated object file
3961and its associated ALI file. Beware of this switch with GNAT, because it may
3962cause the object file and ALI file to have different names which in turn
3963may confuse the binder and the linker.
3964@end ifclear
3965
3966@item -nostdinc
3967@cindex @option{-nostdinc} (@command{gcc})
3968Inhibit the search of the default location for the GNAT Run Time
3969Library (RTL) source files.
3970
3971@item -nostdlib
3972@cindex @option{-nostdlib} (@command{gcc})
3973Inhibit the search of the default location for the GNAT Run Time
3974Library (RTL) ALI files.
3975
3976@ifclear vms
3977@item -O[@var{n}]
3978@cindex @option{-O} (@code{gcc})
3979@var{n} controls the optimization level.
3980
3981@table @asis
3982@item n = 0
3983No optimization, the default setting if no @option{-O} appears
3984
3985@item n = 1
3986Normal optimization, the default if you specify @option{-O} without
3987an operand.
3988
3989@item n = 2
3990Extensive optimization
3991
3992@item n = 3
3993Extensive optimization with automatic inlining of subprograms not
3994specified by pragma @code{Inline}. This applies only to
3995inlining within a unit. For details on control of inlining
3996see @xref{Subprogram Inlining Control}.
3997@end table
3998@end ifclear
3999
4000@ifset vms
4001@item  /NOOPTIMIZE
4002@cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4003Equivalent to @option{/OPTIMIZE=NONE}.
4004This is the default behavior in the absence of an @option{/OPTMIZE}
4005qualifier.
4006
4007@item /OPTIMIZE[=(keyword[,...])]
4008@cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4009Selects the level of optimization for your program. The supported
4010keywords are as follows:
4011@table @code
4012@item   ALL
4013Perform most optimizations, including those that
4014are expensive.
4015This is the default if the @option{/OPTMIZE} qualifier is supplied
4016without keyword options.
4017
4018@item   NONE
4019Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4020
4021@item SOME
4022Perform some optimizations, but omit ones that are costly.
4023
4024@item   DEVELOPMENT
4025Same as @code{SOME}.
4026
4027@item   INLINING
4028Full optimization, and also attempt automatic inlining of small
4029subprograms within a unit even when pragma @code{Inline}
4030is not specified (@pxref{Inlining of Subprograms}).
4031
4032@item   UNROLL_LOOPS
4033Try to unroll loops. This keyword may be specified together with
4034any keyword above other than @code{NONE}. Loop unrolling
4035usually, but not always, improves the performance of programs.
4036@end table
4037@end ifset
4038
4039@ifclear vms
4040@item -pass-exit-codes
4041@cindex @option{-pass-exit-codes} (@code{gcc})
4042Catch exit codes from the compiler and use the most meaningful as
4043exit status.
4044@end ifclear
4045
4046@item --RTS=@var{rts-path}
4047@cindex @option{--RTS} (@code{gcc})
4048Specifies the default location of the runtime library. Same meaning as the
4049equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4050
4051@item ^-S^/ASM^
4052@cindex @option{^-S^/ASM^} (@code{gcc})
4053^Used in place of @option{-c} to^Used to^
4054cause the assembler source file to be
4055generated, using @file{^.s^.S^} as the extension,
4056instead of the object file.
4057This may be useful if you need to examine the generated assembly code.
4058
4059@item ^-v^/VERBOSE^
4060@cindex @option{^-v^/VERBOSE^} (@code{gcc})
4061Show commands generated by the @code{gcc} driver. Normally used only for
4062debugging purposes or if you need to be sure what version of the
4063compiler you are executing.
4064
4065@ifclear vms
4066@item -V @var{ver}
4067@cindex @option{-V} (@code{gcc})
4068Execute @var{ver} version of the compiler. This is the @code{gcc}
4069version, not the GNAT version.
4070@end ifclear
4071
4072@end table
4073
4074@ifclear vms
4075You may combine a sequence of GNAT switches into a single switch. For
4076example, the combined switch
4077
4078@cindex Combining GNAT switches
4079@smallexample
4080-gnatofi3
4081@end smallexample
4082
4083@noindent
4084is equivalent to specifying the following sequence of switches:
4085
4086@smallexample
4087-gnato -gnatf -gnati3
4088@end smallexample
4089@end ifclear
4090
4091
4092@c NEED TO CHECK THIS FOR VMS
4093
4094@noindent
4095The following restrictions apply to the combination of switches
4096in this manner:
4097
4098@itemize @bullet
4099@item
4100The switch @option{-gnatc} if combined with other switches must come
4101first in the string.
4102
4103@item
4104The switch @option{-gnats} if combined with other switches must come
4105first in the string.
4106
4107@item
4108The switches
4109@option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4110may not be combined with any other switches.
4111
4112@ifclear vms
4113@item
4114Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4115switch), then all further characters in the switch are interpreted
4116as style modifiers (see description of @option{-gnaty}).
4117
4118@item
4119Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4120switch), then all further characters in the switch are interpreted
4121as debug flags (see description of @option{-gnatd}).
4122
4123@item
4124Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4125switch), then all further characters in the switch are interpreted
4126as warning mode modifiers (see description of @option{-gnatw}).
4127
4128@item
4129Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4130switch), then all further characters in the switch are interpreted
4131as validity checking options (see description of @option{-gnatV}).
4132@end ifclear
4133@end itemize
4134
4135
4136@node Output and Error Message Control
4137@subsection Output and Error Message Control
4138@findex stderr
4139
4140@noindent
4141The standard default format for error messages is called ``brief format''.
4142Brief format messages are written to @file{stderr} (the standard error
4143file) and have the following form:
4144
4145@smallexample
4146e.adb:3:04: Incorrect spelling of keyword "function"
4147e.adb:4:20: ";" should be "is"
4148@end smallexample
4149
4150@noindent
4151The first integer after the file name is the line number in the file,
4152and the second integer is the column number within the line.
4153@code{glide} can parse the error messages
4154and point to the referenced character.
4155The following switches provide control over the error message
4156format:
4157
4158@table @option
4159@c !sort!
4160@item -gnatv
4161@cindex @option{-gnatv} (@code{gcc})
4162@findex stdout
4163@ifclear vms
4164The v stands for verbose.
4165@end ifclear
4166The effect of this setting is to write long-format error
4167messages to @file{stdout} (the standard output file.
4168The same program compiled with the
4169@option{-gnatv} switch would generate:
4170
4171@smallexample
4172@cartouche
41733. funcion X (Q : Integer)
4174   |
4175>>> Incorrect spelling of keyword "function"
41764. return Integer;
4177                 |
4178>>> ";" should be "is"
4179@end cartouche
4180@end smallexample
4181
4182@noindent
4183The vertical bar indicates the location of the error, and the @samp{>>>}
4184prefix can be used to search for error messages. When this switch is
4185used the only source lines output are those with errors.
4186
4187@item -gnatl
4188@cindex @option{-gnatl} (@code{gcc})
4189@ifclear vms
4190The @code{l} stands for list.
4191@end ifclear
4192This switch causes a full listing of
4193the file to be generated. The output might look as follows:
4194
4195@smallexample
4196@cartouche
4197 1. procedure E is
4198 2.    V : Integer;
4199 3.    funcion X (Q : Integer)
4200       |
4201    >>> Incorrect spelling of keyword "function"
4202 4.     return Integer;
4203                      |
4204    >>> ";" should be "is"
4205 5.    begin
4206 6.       return Q + Q;
4207 7.    end;
4208 8. begin
4209 9.    V := X + X;
421010.end E;
4211@end cartouche
4212@end smallexample
4213
4214@noindent
4215@findex stderr
4216When you specify the @option{-gnatv} or @option{-gnatl} switches and
4217standard output is redirected, a brief summary is written to
4218@file{stderr} (standard error) giving the number of error messages and
4219warning messages generated.
4220
4221@item -gnatU
4222@cindex @option{-gnatU} (@code{gcc})
4223This switch forces all error messages to be preceded by the unique
4224string ``error:''. This means that error messages take a few more
4225characters in space, but allows easy searching for and identification
4226of error messages.
4227
4228@item -gnatb
4229@cindex @option{-gnatb} (@code{gcc})
4230@ifclear vms
4231The @code{b} stands for brief.
4232@end ifclear
4233This switch causes GNAT to generate the
4234brief format error messages to @file{stderr} (the standard error
4235file) as well as the verbose
4236format message or full listing (which as usual is written to
4237@file{stdout} (the standard output file).
4238
4239@item -gnatm^^=^@var{n}
4240@cindex @option{-gnatm} (@code{gcc})
4241@ifclear vms
4242The @code{m} stands for maximum.
4243@end ifclear
4244@var{n} is a decimal integer in the
4245range of 1 to 999 and limits the number of error messages to be
4246generated. For example, using @option{-gnatm2} might yield
4247
4248@smallexample
4249e.adb:3:04: Incorrect spelling of keyword "function"
4250e.adb:5:35: missing ".."
4251fatal error: maximum errors reached
4252compilation abandoned
4253@end smallexample
4254
4255@item -gnatf
4256@cindex @option{-gnatf} (@code{gcc})
4257@cindex Error messages, suppressing
4258@ifclear vms
4259The @code{f} stands for full.
4260@end ifclear
4261Normally, the compiler suppresses error messages that are likely to be
4262redundant. This switch causes all error
4263messages to be generated. In particular, in the case of
4264references to undefined variables. If a given variable is referenced
4265several times, the normal format of messages is
4266@smallexample
4267e.adb:7:07: "V" is undefined (more references follow)
4268@end smallexample
4269
4270@noindent
4271where the parenthetical comment warns that there are additional
4272references to the variable @code{V}. Compiling the same program with the
4273@option{-gnatf} switch yields
4274
4275@smallexample
4276e.adb:7:07: "V" is undefined
4277e.adb:8:07: "V" is undefined
4278e.adb:8:12: "V" is undefined
4279e.adb:8:16: "V" is undefined
4280e.adb:9:07: "V" is undefined
4281e.adb:9:12: "V" is undefined
4282@end smallexample
4283
4284@noindent
4285The @option{-gnatf} switch also generates additional information for
4286some error messages.  Some examples are:
4287
4288@itemize @bullet
4289@item
4290Full details on entities not available in high integrity mode
4291@item
4292Details on possibly non-portable unchecked conversion
4293@item
4294List possible interpretations for ambiguous calls
4295@item
4296Additional details on incorrect parameters
4297@end itemize
4298
4299
4300@item -gnatq
4301@cindex @option{-gnatq} (@code{gcc})
4302@ifclear vms
4303The @code{q} stands for quit (really ``don't quit'').
4304@end ifclear
4305In normal operation mode, the compiler first parses the program and
4306determines if there are any syntax errors. If there are, appropriate
4307error messages are generated and compilation is immediately terminated.
4308This switch tells
4309GNAT to continue with semantic analysis even if syntax errors have been
4310found. This may enable the detection of more errors in a single run. On
4311the other hand, the semantic analyzer is more likely to encounter some
4312internal fatal error when given a syntactically invalid tree.
4313
4314@item -gnatQ
4315@cindex @option{-gnatQ} (@code{gcc})
4316In normal operation mode, the @file{ALI} file is not generated if any
4317illegalities are detected in the program. The use of @option{-gnatQ} forces
4318generation of the @file{ALI} file. This file is marked as being in
4319error, so it cannot be used for binding purposes, but it does contain
4320reasonably complete cross-reference information, and thus may be useful
4321for use by tools (e.g. semantic browsing tools or integrated development
4322environments) that are driven from the @file{ALI} file. This switch
4323implies @option{-gnatq}, since the semantic phase must be run to get a
4324meaningful ALI file.
4325
4326In addition, if @option{-gnatt} is also specified, then the tree file is
4327generated even if there are illegalities. It may be useful in this case
4328to also specify @option{-gnatq} to ensure that full semantic processing
4329occurs. The resulting tree file can be processed by ASIS, for the purpose
4330of providing partial information about illegal units, but if the error
4331causes the tree to be badly malformed, then ASIS may crash during the
4332analysis.
4333
4334When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4335being in error, @code{gnatmake} will attempt to recompile the source when it
4336finds such an @file{ALI} file, including with switch @option{-gnatc}.
4337
4338Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4339since ALI files are never generated if @option{-gnats} is set.
4340
4341@end table
4342
4343
4344@node Warning Message Control
4345@subsection Warning Message Control
4346@cindex Warning messages
4347@noindent
4348In addition to error messages, which correspond to illegalities as defined
4349in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4350situations.
4351
4352First, the compiler considers some constructs suspicious and generates a
4353warning message to alert you to a possible error. Second, if the
4354compiler detects a situation that is sure to raise an exception at
4355run time, it generates a warning message. The following shows an example
4356of warning messages:
4357@smallexample
4358e.adb:4:24: warning: creation of object may raise Storage_Error
4359e.adb:10:17: warning: static value out of range
4360e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4361@end smallexample
4362
4363@noindent
4364GNAT considers a large number of situations as appropriate
4365for the generation of warning messages. As always, warnings are not
4366definite indications of errors. For example, if you do an out-of-range
4367assignment with the deliberate intention of raising a
4368@code{Constraint_Error} exception, then the warning that may be
4369issued does not indicate an error. Some of the situations for which GNAT
4370issues warnings (at least some of the time) are given in the following
4371list. This list is not complete, and new warnings are often added to
4372subsequent versions of GNAT. The list is intended to give a general idea
4373of the kinds of warnings that are generated.
4374
4375@itemize @bullet
4376@item
4377Possible infinitely recursive calls
4378
4379@item
4380Out-of-range values being assigned
4381
4382@item
4383Possible order of elaboration problems
4384
4385@item
4386Unreachable code
4387
4388@item
4389Fixed-point type declarations with a null range
4390
4391@item
4392Variables that are never assigned a value
4393
4394@item
4395Variables that are referenced before being initialized
4396
4397@item
4398Task entries with no corresponding @code{accept} statement
4399
4400@item
4401Duplicate accepts for the same task entry in a @code{select}
4402
4403@item
4404Objects that take too much storage
4405
4406@item
4407Unchecked conversion between types of differing sizes
4408
4409@item
4410Missing @code{return} statement along some execution path in a function
4411
4412@item
4413Incorrect (unrecognized) pragmas
4414
4415@item
4416Incorrect external names
4417
4418@item
4419Allocation from empty storage pool
4420
4421@item
4422Potentially blocking operation in protected type
4423
4424@item
4425Suspicious parenthesization of expressions
4426
4427@item
4428Mismatching bounds in an aggregate
4429
4430@item
4431Attempt to return local value by reference
4432
4433
4434@item
4435Premature instantiation of a generic body
4436
4437@item
4438Attempt to pack aliased components
4439
4440@item
4441Out of bounds array subscripts
4442
4443@item
4444Wrong length on string assignment
4445
4446@item
4447Violations of style rules if style checking is enabled
4448
4449@item
4450Unused @code{with} clauses
4451
4452@item
4453@code{Bit_Order} usage that does not have any effect
4454
4455@item
4456@code{Standard.Duration} used to resolve universal fixed expression
4457
4458@item
4459Dereference of possibly null value
4460
4461@item
4462Declaration that is likely to cause storage error
4463
4464@item
4465Internal GNAT unit @code{with}'ed by application unit
4466
4467@item
4468Values known to be out of range at compile time
4469
4470@item
4471Unreferenced labels and variables
4472
4473@item
4474Address overlays that could clobber memory
4475
4476@item
4477Unexpected initialization when address clause present
4478
4479@item
4480Bad alignment for address clause
4481
4482@item
4483Useless type conversions
4484
4485@item
4486Redundant assignment statements and other redundant constructs
4487
4488@item
4489Useless exception handlers
4490
4491@item
4492Accidental hiding of name by child unit
4493
4494
4495@item
4496Access before elaboration detected at compile time
4497
4498@item
4499A range in a @code{for} loop that is known to be null or might be null
4500
4501@end itemize
4502
4503@noindent
4504The following switches are available to control the handling of
4505warning messages:
4506
4507@table @option
4508@c !sort!
4509@item -gnatwa
4510@emph{Activate all optional errors.}
4511@cindex @option{-gnatwa} (@code{gcc})
4512This switch activates most optional warning messages, see remaining list
4513in this section for details on optional warning messages that can be
4514individually controlled.  The warnings that are not turned on by this
4515switch are
4516@option{-gnatwd} (implicit dereferencing),
4517@option{-gnatwh} (hiding),
4518and @option{-gnatwl} (elaboration warnings).
4519All other optional warnings are turned on.
4520
4521@item -gnatwA
4522@emph{Suppress all optional errors.}
4523@cindex @option{-gnatwA} (@code{gcc})
4524This switch suppresses all optional warning messages, see remaining list
4525in this section for details on optional warning messages that can be
4526individually controlled.
4527
4528@item -gnatwc
4529@emph{Activate warnings on conditionals.}
4530@cindex @option{-gnatwc} (@code{gcc})
4531@cindex Conditionals, constant
4532This switch activates warnings for conditional expressions used in
4533tests that are known to be True or False at compile time. The default
4534is that such warnings are not generated.
4535Note that this warning does
4536not get issued for the use of boolean variables or constants whose
4537values are known at compile time, since this is a standard technique
4538for conditional compilation in Ada, and this would generate too many
4539``false positive'' warnings.
4540This warning can also be turned on using @option{-gnatwa}.
4541
4542@item -gnatwC
4543@emph{Suppress warnings on conditionals.}
4544@cindex @option{-gnatwC} (@code{gcc})
4545This switch suppresses warnings for conditional expressions used in
4546tests that are known to be True or False at compile time.
4547
4548@item -gnatwd
4549@emph{Activate warnings on implicit dereferencing.}
4550@cindex @option{-gnatwd} (@code{gcc})
4551If this switch is set, then the use of a prefix of an access type
4552in an indexed component, slice, or selected component without an
4553explicit @code{.all} will generate a warning. With this warning
4554enabled, access checks occur only at points where an explicit
4555@code{.all} appears in the source code (assuming no warnings are
4556generated as a result of this switch). The default is that such
4557warnings are not generated.
4558Note that @option{-gnatwa} does not affect the setting of
4559this warning option.
4560
4561@item -gnatwD
4562@emph{Suppress warnings on implicit dereferencing.}
4563@cindex @option{-gnatwD} (@code{gcc})
4564@cindex Implicit dereferencing
4565@cindex Dereferencing, implicit
4566This switch suppresses warnings for implicit dereferences in
4567indexed components, slices, and selected components.
4568
4569@item -gnatwe
4570@emph{Treat warnings as errors.}
4571@cindex @option{-gnatwe} (@code{gcc})
4572@cindex Warnings, treat as error
4573This switch causes warning messages to be treated as errors.
4574The warning string still appears, but the warning messages are counted
4575as errors, and prevent the generation of an object file.
4576
4577@item -gnatwf
4578@emph{Activate warnings on unreferenced formals.}
4579@cindex @option{-gnatwf} (@code{gcc})
4580@cindex Formals, unreferenced
4581This switch causes a warning to be generated if a formal parameter
4582is not referenced in the body of the subprogram. This warning can
4583also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4584
4585@item -gnatwF
4586@emph{Suppress warnings on unreferenced formals.}
4587@cindex @option{-gnatwF} (@code{gcc})
4588This switch suppresses warnings for unreferenced formal
4589parameters. Note that the
4590combination @option{-gnatwu} followed by @option{-gnatwF} has the
4591effect of warning on unreferenced entities other than subprogram
4592formals.
4593
4594@item -gnatwg
4595@emph{Activate warnings on unrecognized pragmas.}
4596@cindex @option{-gnatwg} (@code{gcc})
4597@cindex Pragmas, unrecognized
4598This switch causes a warning to be generated if an unrecognized
4599pragma is encountered. Apart from issuing this warning, the
4600pragma is ignored and has no effect. This warning can
4601also be turned on using @option{-gnatwa}. The default
4602is that such warnings are issued (satisfying the Ada Reference
4603Manual requirement that such warnings appear).
4604
4605@item -gnatwG
4606@emph{Suppress warnings on unrecognized pragmas.}
4607@cindex @option{-gnatwG} (@code{gcc})
4608This switch suppresses warnings for unrecognized pragmas.
4609
4610@item -gnatwh
4611@emph{Activate warnings on hiding.}
4612@cindex @option{-gnatwh} (@code{gcc})
4613@cindex Hiding of Declarations
4614This switch activates warnings on hiding declarations.
4615A declaration is considered hiding
4616if it is for a non-overloadable entity, and it declares an entity with the
4617same name as some other entity that is directly or use-visible. The default
4618is that such warnings are not generated.
4619Note that @option{-gnatwa} does not affect the setting of this warning option.
4620
4621@item -gnatwH
4622@emph{Suppress warnings on hiding.}
4623@cindex @option{-gnatwH} (@code{gcc})
4624This switch suppresses warnings on hiding declarations.
4625
4626@item -gnatwi
4627@emph{Activate warnings on implementation units.}
4628@cindex @option{-gnatwi} (@code{gcc})
4629This switch activates warnings for a @code{with} of an internal GNAT
4630implementation unit, defined as any unit from the @code{Ada},
4631@code{Interfaces}, @code{GNAT},
4632^^@code{DEC},^ or @code{System}
4633hierarchies that is not
4634documented in either the Ada Reference Manual or the GNAT
4635Programmer's Reference Manual. Such units are intended only
4636for internal implementation purposes and should not be @code{with}'ed
4637by user programs. The default is that such warnings are generated
4638This warning can also be turned on using @option{-gnatwa}.
4639
4640@item -gnatwI
4641@emph{Disable warnings on implementation units.}
4642@cindex @option{-gnatwI} (@code{gcc})
4643This switch disables warnings for a @code{with} of an internal GNAT
4644implementation unit.
4645
4646@item -gnatwj
4647@emph{Activate warnings on obsolescent features (Annex J).}
4648@cindex @option{-gnatwj} (@code{gcc})
4649@cindex Features, obsolescent
4650@cindex Obsolescent features
4651If this warning option is activated, then warnings are generated for
4652calls to subprograms marked with @code{pragma Obsolescent} and
4653for use of features in Annex J of the Ada Reference Manual. In the
4654case of Annex J, not all features are flagged. In particular use
4655of the renamed packages (like @code{Text_IO}) and use of package
4656@code{ASCII} are not flagged, since these are very common and
4657would generate many annoying positive warnings. The default is that
4658such warnings are not generated.
4659
4660@item -gnatwJ
4661@emph{Suppress warnings on obsolescent features (Annex J).}
4662@cindex @option{-gnatwJ} (@code{gcc})
4663This switch disables warnings on use of obsolescent features.
4664
4665@item -gnatwk
4666@emph{Activate warnings on variables that could be constants.}
4667@cindex @option{-gnatwk} (@code{gcc})
4668This switch activates warnings for variables that are initialized but
4669never modified, and then could be declared constants.
4670
4671@item -gnatwK
4672@emph{Suppress warnings on variables that could be constants.}
4673@cindex @option{-gnatwK} (@code{gcc})
4674This switch disables warnings on variables that could be declared constants.
4675
4676@item -gnatwl
4677@emph{Activate warnings for missing elaboration pragmas.}
4678@cindex @option{-gnatwl} (@code{gcc})
4679@cindex Elaboration, warnings
4680This switch activates warnings on missing
4681@code{pragma Elaborate_All} statements.
4682See the section in this guide on elaboration checking for details on
4683when such pragma should be used. Warnings are also generated if you
4684are using the static mode of elaboration, and a @code{pragma Elaborate}
4685is encountered. The default is that such warnings
4686are not generated.
4687This warning is not automatically turned on by the use of @option{-gnatwa}.
4688
4689@item -gnatwL
4690@emph{Suppress warnings for missing elaboration pragmas.}
4691@cindex @option{-gnatwL} (@code{gcc})
4692This switch suppresses warnings on missing pragma Elaborate_All statements.
4693See the section in this guide on elaboration checking for details on
4694when such pragma should be used.
4695
4696@item -gnatwm
4697@emph{Activate warnings on modified but unreferenced variables.}
4698@cindex @option{-gnatwm} (@code{gcc})
4699This switch activates warnings for variables that are assigned (using
4700an initialization value or with one or more assignment statements) but
4701whose value is never read. The warning is suppressed for volatile
4702variables and also for variables that are renamings of other variables
4703or for which an address clause is given.
4704This warning can also be turned on using @option{-gnatwa}.
4705
4706@item -gnatwM
4707@emph{Disable warnings on modified but unreferenced variables.}
4708@cindex @option{-gnatwM} (@code{gcc})
4709This switch disables warnings for variables that are assigned or
4710initialized, but never read.
4711
4712@item -gnatwn
4713@emph{Set normal warnings mode.}
4714@cindex @option{-gnatwn} (@code{gcc})
4715This switch sets normal warning mode, in which enabled warnings are
4716issued and treated as warnings rather than errors. This is the default
4717mode. the switch @option{-gnatwn} can be used to cancel the effect of
4718an explicit @option{-gnatws} or
4719@option{-gnatwe}. It also cancels the effect of the
4720implicit @option{-gnatwe} that is activated by the
4721use of @option{-gnatg}.
4722
4723@item -gnatwo
4724@emph{Activate warnings on address clause overlays.}
4725@cindex @option{-gnatwo} (@code{gcc})
4726@cindex Address Clauses, warnings
4727This switch activates warnings for possibly unintended initialization
4728effects of defining address clauses that cause one variable to overlap
4729another. The default is that such warnings are generated.
4730This warning can also be turned on using @option{-gnatwa}.
4731
4732@item -gnatwO
4733@emph{Suppress warnings on address clause overlays.}
4734@cindex @option{-gnatwO} (@code{gcc})
4735This switch suppresses warnings on possibly unintended initialization
4736effects of defining address clauses that cause one variable to overlap
4737another.
4738
4739@item -gnatwp
4740@emph{Activate warnings on ineffective pragma Inlines.}
4741@cindex @option{-gnatwp} (@code{gcc})
4742@cindex Inlining, warnings
4743This switch activates warnings for failure of front end inlining
4744(activated by @option{-gnatN}) to inline a particular call. There are
4745many reasons for not being able to inline a call, including most
4746commonly that the call is too complex to inline.
4747This warning can also be turned on using @option{-gnatwa}.
4748
4749@item -gnatwP
4750@emph{Suppress warnings on ineffective pragma Inlines.}
4751@cindex @option{-gnatwP} (@code{gcc})
4752This switch suppresses warnings on ineffective pragma Inlines. If the
4753inlining mechanism cannot inline a call, it will simply ignore the
4754request silently.
4755
4756@item -gnatwr
4757@emph{Activate warnings on redundant constructs.}
4758@cindex @option{-gnatwr} (@code{gcc})
4759This switch activates warnings for redundant constructs. The following
4760is the current list of constructs regarded as redundant:
4761This warning can also be turned on using @option{-gnatwa}.
4762
4763@itemize @bullet
4764@item
4765Assignment of an item to itself.
4766@item
4767Type conversion that converts an expression to its own type.
4768@item
4769Use of the attribute @code{Base} where @code{typ'Base} is the same
4770as @code{typ}.
4771@item
4772Use of pragma @code{Pack} when all components are placed by a record
4773representation clause.
4774@item
4775Exception handler containing only a reraise statement (raise with no
4776operand) which has no effect.
4777@item
4778Use of the operator abs on an operand that is known at compile time
4779to be non-negative
4780@item
4781Use of an unnecessary extra level of parentheses (C-style) around conditions
4782in @code{if} statements, @code{while} statements and @code{exit} statements.
4783@item
4784Comparison of boolean expressions to an explicit True value.
4785@end itemize
4786
4787@item -gnatwR
4788@emph{Suppress warnings on redundant constructs.}
4789@cindex @option{-gnatwR} (@code{gcc})
4790This switch suppresses warnings for redundant constructs.
4791
4792@item -gnatws
4793@emph{Suppress all warnings.}
4794@cindex @option{-gnatws} (@code{gcc})
4795This switch completely suppresses the
4796output of all warning messages from the GNAT front end.
4797Note that it does not suppress warnings from the @code{gcc} back end.
4798To suppress these back end warnings as well, use the switch @option{-w}
4799in addition to @option{-gnatws}.
4800
4801@item -gnatwu
4802@emph{Activate warnings on unused entities.}
4803@cindex @option{-gnatwu} (@code{gcc})
4804This switch activates warnings to be generated for entities that
4805are declared but not referenced, and for units that are @code{with}'ed
4806and not
4807referenced. In the case of packages, a warning is also generated if
4808no entities in the package are referenced. This means that if the package
4809is referenced but the only references are in @code{use}
4810clauses or @code{renames}
4811declarations, a warning is still generated. A warning is also generated
4812for a generic package that is @code{with}'ed but never instantiated.
4813In the case where a package or subprogram body is compiled, and there
4814is a @code{with} on the corresponding spec
4815that is only referenced in the body,
4816a warning is also generated, noting that the
4817@code{with} can be moved to the body. The default is that
4818such warnings are not generated.
4819This switch also activates warnings on unreferenced formals
4820(it is includes the effect of @option{-gnatwf}).
4821This warning can also be turned on using @option{-gnatwa}.
4822
4823@item -gnatwU
4824@emph{Suppress warnings on unused entities.}
4825@cindex @option{-gnatwU} (@code{gcc})
4826This switch suppresses warnings for unused entities and packages.
4827It also turns off warnings on unreferenced formals (and thus includes
4828the effect of @option{-gnatwF}).
4829
4830@item -gnatwv
4831@emph{Activate warnings on unassigned variables.}
4832@cindex @option{-gnatwv} (@code{gcc})
4833@cindex Unassigned variable warnings
4834This switch activates warnings for access to variables which
4835may not be properly initialized. The default is that
4836such warnings are generated.
4837
4838@item -gnatwV
4839@emph{Suppress warnings on unassigned variables.}
4840@cindex @option{-gnatwV} (@code{gcc})
4841This switch suppresses warnings for access to variables which
4842may not be properly initialized.
4843
4844@item -gnatwx
4845@emph{Activate warnings on Export/Import pragmas.}
4846@cindex @option{-gnatwx} (@code{gcc})
4847@cindex Export/Import pragma warnings
4848This switch activates warnings on Export/Import pragmas when
4849the compiler detects a possible conflict between the Ada and
4850foreign language calling sequences. For example, the use of
4851default parameters in a convention C procedure is dubious
4852because the C compiler cannot supply the proper default, so
4853a warning is issued. The default is that such warnings are
4854generated.
4855
4856@item -gnatwX
4857@emph{Suppress warnings on Export/Import pragmas.}
4858@cindex @option{-gnatwX} (@code{gcc})
4859This switch suppresses warnings on Export/Import pragmas.
4860The sense of this is that you are telling the compiler that
4861you know what you are doing in writing the pragma, and it
4862should not complain at you.
4863
4864@item -gnatwz
4865@emph{Activate warnings on unchecked conversions.}
4866@cindex @option{-gnatwz} (@code{gcc})
4867@cindex Unchecked_Conversion warnings
4868This switch activates warnings for unchecked conversions
4869where the types are known at compile time to have different
4870sizes. The default
4871is that such warnings are generated.
4872
4873@item -gnatwZ
4874@emph{Suppress warnings on unchecked conversions.}
4875@cindex @option{-gnatwZ} (@code{gcc})
4876This switch suppresses warnings for unchecked conversions
4877where the types are known at compile time to have different
4878sizes.
4879
4880@item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4881@cindex @option{-Wuninitialized}
4882The warnings controlled by the @option{-gnatw} switch are generated by the
4883front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4884can provide additional warnings. One such useful warning is provided by
4885@option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4886conjunction with tunrning on optimization mode. This causes the flow
4887analysis circuits of the back end optimizer to output additional
4888warnings about uninitialized variables.
4889
4890@item ^-w^/NO_BACK_END_WARNINGS^
4891@cindex @option{-w}
4892This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4893be used in conjunction with @option{-gnatws} to ensure that all warnings
4894are suppressed during the entire compilation process.
4895
4896@end table
4897
4898@noindent
4899@ifclear vms
4900A string of warning parameters can be used in the same parameter. For example:
4901
4902@smallexample
4903-gnatwaLe
4904@end smallexample
4905
4906@noindent
4907will turn on all optional warnings except for elaboration pragma warnings,
4908and also specify that warnings should be treated as errors.
4909@end ifclear
4910When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4911
4912@table @option
4913@c !sort!
4914@item -gnatwB
4915@item -gnatwC
4916@item -gnatwK
4917@item -gnatwD
4918@item -gnatwL
4919@item -gnatwH
4920@item -gnatwi
4921@item -gnatwP
4922@item -gnatwn
4923@item -gnatwo
4924@item -gnatwz
4925@item -gnatwx
4926
4927@end table
4928
4929
4930@node Debugging and Assertion Control
4931@subsection Debugging and Assertion Control
4932
4933@table @option
4934@item -gnata
4935@cindex @option{-gnata} (@code{gcc})
4936@findex Assert
4937@findex Debug
4938@cindex Assertions
4939
4940@noindent
4941The pragmas @code{Assert} and @code{Debug} normally have no effect and
4942are ignored. This switch, where @samp{a} stands for assert, causes
4943@code{Assert} and @code{Debug} pragmas to be activated.
4944
4945The pragmas have the form:
4946
4947@smallexample
4948@cartouche
4949   @b{pragma} Assert (@var{Boolean-expression} [,
4950                      @var{static-string-expression}])
4951   @b{pragma} Debug (@var{procedure call})
4952@end cartouche
4953@end smallexample
4954
4955@noindent
4956The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4957If the result is @code{True}, the pragma has no effect (other than
4958possible side effects from evaluating the expression). If the result is
4959@code{False}, the exception @code{Assert_Failure} declared in the package
4960@code{System.Assertions} is
4961raised (passing @var{static-string-expression}, if present, as the
4962message associated with the exception). If no string expression is
4963given the default is a string giving the file name and line number
4964of the pragma.
4965
4966The @code{Debug} pragma causes @var{procedure} to be called. Note that
4967@code{pragma Debug} may appear within a declaration sequence, allowing
4968debugging procedures to be called between declarations.
4969
4970@ifset vms
4971@item /DEBUG[=debug-level]
4972@itemx  /NODEBUG
4973Specifies how much debugging information is to be included in
4974the resulting object file where 'debug-level' is one of the following:
4975@table @code
4976@item   TRACEBACK
4977Include both debugger symbol records and traceback
4978the object file.
4979This is the default setting.
4980@item   ALL
4981Include both debugger symbol records and traceback in
4982object file.
4983@item   NONE
4984Excludes both debugger symbol records and traceback
4985the object file. Same as /NODEBUG.
4986@item   SYMBOLS
4987Includes only debugger symbol records in the object
4988file. Note that this doesn't include traceback information.
4989@end table
4990@end ifset
4991@end table
4992
4993@node Validity Checking
4994@subsection Validity Checking
4995@findex Validity Checking
4996
4997@noindent
4998The Ada 95 Reference Manual has specific requirements for checking
4999for invalid values. In particular, RM 13.9.1 requires that the
5000evaluation of invalid values (for example from unchecked conversions),
5001not result in erroneous execution. In GNAT, the result of such an
5002evaluation in normal default mode is to either use the value
5003unmodified, or to raise Constraint_Error in those cases where use
5004of the unmodified value would cause erroneous execution. The cases
5005where unmodified values might lead to erroneous execution are case
5006statements (where a wild jump might result from an invalid value),
5007and subscripts on the left hand side (where memory corruption could
5008occur as a result of an invalid value).
5009
5010The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5011checking mode.
5012@ifclear vms
5013The @code{x} argument is a string of letters that
5014indicate validity checks that are performed or not performed in addition
5015to the default checks described above.
5016@end ifclear
5017@ifset vms
5018The options allowed for this qualifier
5019indicate validity checks that are performed or not performed in addition
5020to the default checks described above.
5021@end ifset
5022
5023
5024@table @option
5025@c !sort!
5026@item -gnatVa
5027@emph{All validity checks.}
5028@cindex @option{-gnatVa} (@code{gcc})
5029All validity checks are turned on.
5030@ifclear vms
5031That is, @option{-gnatVa} is
5032equivalent to @option{gnatVcdfimorst}.
5033@end ifclear
5034
5035@item -gnatVc
5036@emph{Validity checks for copies.}
5037@cindex @option{-gnatVc} (@code{gcc})
5038The right hand side of assignments, and the initializing values of
5039object declarations are validity checked.
5040
5041@item -gnatVd
5042@emph{Default (RM) validity checks.}
5043@cindex @option{-gnatVd} (@code{gcc})
5044Some validity checks are done by default following normal Ada semantics
5045(RM 13.9.1 (9-11)).
5046A check is done in case statements that the expression is within the range
5047of the subtype. If it is not, Constraint_Error is raised.
5048For assignments to array components, a check is done that the expression used
5049as index is within the range. If it is not, Constraint_Error is raised.
5050Both these validity checks may be turned off using switch @option{-gnatVD}.
5051They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5052switch @option{-gnatVd} will leave the checks turned on.
5053Switch @option{-gnatVD} should be used only if you are sure that all such
5054expressions have valid values. If you use this switch and invalid values
5055are present, then the program is erroneous, and wild jumps or memory
5056overwriting may occur.
5057
5058@item -gnatVf
5059@emph{Validity checks for floating-point values.}
5060@cindex @option{-gnatVf} (@code{gcc})
5061In the absence of this switch, validity checking occurs only for discrete
5062values. If @option{-gnatVf} is specified, then validity checking also applies
5063for floating-point values, and NaN's and infinities are considered invalid,
5064as well as out of range values for constrained types. Note that this means
5065that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5066in which floating-point values are checked depends on the setting of other
5067options. For example,
5068@option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5069@option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5070(the order does not matter) specifies that floating-point parameters of mode
5071@code{in} should be validity checked.
5072
5073@item -gnatVi
5074@emph{Validity checks for @code{in} mode parameters}
5075@cindex @option{-gnatVi} (@code{gcc})
5076Arguments for parameters of mode @code{in} are validity checked in function
5077and procedure calls at the point of call.
5078
5079@item -gnatVm
5080@emph{Validity checks for @code{in out} mode parameters.}
5081@cindex @option{-gnatVm} (@code{gcc})
5082Arguments for parameters of mode @code{in out} are validity checked in
5083procedure calls at the point of call. The @code{'m'} here stands for
5084modify, since this concerns parameters that can be modified by the call.
5085Note that there is no specific option to test @code{out} parameters,
5086but any reference within the subprogram will be tested in the usual
5087manner, and if an invalid value is copied back, any reference to it
5088will be subject to validity checking.
5089
5090@item -gnatVn
5091@emph{No validity checks.}
5092@cindex @option{-gnatVn} (@code{gcc})
5093This switch turns off all validity checking, including the default checking
5094for case statements and left hand side subscripts. Note that the use of
5095the switch @option{-gnatp} suppresses all run-time checks, including
5096validity checks, and thus implies @option{-gnatVn}. When this switch
5097is used, it cancels any other @option{-gnatV} previously issued.
5098
5099@item -gnatVo
5100@emph{Validity checks for operator and attribute operands.}
5101@cindex @option{-gnatVo} (@code{gcc})
5102Arguments for predefined operators and attributes are validity checked.
5103This includes all operators in package @code{Standard},
5104the shift operators defined as intrinsic in package @code{Interfaces}
5105and operands for attributes such as @code{Pos}. Checks are also made
5106on individual component values for composite comparisons.
5107
5108@item -gnatVp
5109@emph{Validity checks for parameters.}
5110@cindex @option{-gnatVp} (@code{gcc})
5111This controls the treatment of parameters within a subprogram (as opposed
5112to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5113of parameters on a call. If either of these call options is used, then
5114normally an assumption is made within a subprogram that the input arguments
5115have been validity checking at the point of call, and do not need checking
5116again within a subprogram). If @option{-gnatVp} is set, then this assumption
5117is not made, and parameters are not assumed to be valid, so their validity
5118will be checked (or rechecked) within the subprogram.
5119
5120@item -gnatVr
5121@emph{Validity checks for function returns.}
5122@cindex @option{-gnatVr} (@code{gcc})
5123The expression in @code{return} statements in functions is validity
5124checked.
5125
5126@item -gnatVs
5127@emph{Validity checks for subscripts.}
5128@cindex @option{-gnatVs} (@code{gcc})
5129All subscripts expressions are checked for validity, whether they appear
5130on the right side or left side (in default mode only left side subscripts
5131are validity checked).
5132
5133@item -gnatVt
5134@emph{Validity checks for tests.}
5135@cindex @option{-gnatVt} (@code{gcc})
5136Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5137statements are checked, as well as guard expressions in entry calls.
5138
5139@end table
5140
5141@noindent
5142The @option{-gnatV} switch may be followed by
5143^a string of letters^a list of options^
5144to turn on a series of validity checking options.
5145For example,
5146@option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5147specifies that in addition to the default validity checking, copies and
5148function return expressions are to be validity checked.
5149In order to make it easier
5150to specify the desired combination of effects,
5151@ifclear vms
5152the upper case letters @code{CDFIMORST} may
5153be used to turn off the corresponding lower case option.
5154@end ifclear
5155@ifset vms
5156the prefix @code{NO} on an option turns off the corresponding validity
5157checking:
5158@itemize @bullet
5159@item @code{NOCOPIES}
5160@item @code{NODEFAULT}
5161@item @code{NOFLOATS}
5162@item @code{NOIN_PARAMS}
5163@item @code{NOMOD_PARAMS}
5164@item @code{NOOPERANDS}
5165@item @code{NORETURNS}
5166@item @code{NOSUBSCRIPTS}
5167@item @code{NOTESTS}
5168@end itemize
5169@end ifset
5170Thus
5171@option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5172turns on all validity checking options except for
5173checking of @code{@b{in out}} procedure arguments.
5174
5175The specification of additional validity checking generates extra code (and
5176in the case of @option{-gnatVa} the code expansion can be substantial.
5177However, these additional checks can be very useful in detecting
5178uninitialized variables, incorrect use of unchecked conversion, and other
5179errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5180is useful in conjunction with the extra validity checking, since this
5181ensures that wherever possible uninitialized variables have invalid values.
5182
5183See also the pragma @code{Validity_Checks} which allows modification of
5184the validity checking mode at the program source level, and also allows for
5185temporary disabling of validity checks.
5186
5187
5188@node Style Checking
5189@subsection Style Checking
5190@findex Style checking
5191
5192@noindent
5193The @option{-gnaty^x^(option,option,...)^} switch
5194@cindex @option{-gnaty} (@code{gcc})
5195causes the compiler to
5196enforce specified style rules. A limited set of style rules has been used
5197in writing the GNAT sources themselves. This switch allows user programs
5198to activate all or some of these checks. If the source program fails a
5199specified style check, an appropriate warning message is given, preceded by
5200the character sequence ``(style)''.
5201@ifset vms
5202@code{(option,option,...)} is a sequence of keywords
5203@end ifset
5204@ifclear vms
5205The string @var{x} is a sequence of letters or digits
5206@end ifclear
5207indicating the particular style
5208checks to be performed. The following checks are defined:
5209
5210@table @option
5211@c !sort!
5212@item 1-9
5213@emph{Specify indentation level.}
5214If a digit from 1-9 appears
5215^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5216then proper indentation is checked, with the digit indicating the
5217indentation level required.
5218The general style of required indentation is as specified by
5219the examples in the Ada Reference Manual. Full line comments must be
5220aligned with the @code{--} starting on a column that is a multiple of
5221the alignment level.
5222
5223@item ^a^ATTRIBUTE^
5224@emph{Check attribute casing.}
5225If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5226then attribute names, including the case of keywords such as @code{digits}
5227used as attributes names, must be written in mixed case, that is, the
5228initial letter and any letter following an underscore must be uppercase.
5229All other letters must be lowercase.
5230
5231@item ^b^BLANKS^
5232@emph{Blanks not allowed at statement end.}
5233If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5234trailing blanks are not allowed at the end of statements. The purpose of this
5235rule, together with h (no horizontal tabs), is to enforce a canonical format
5236for the use of blanks to separate source tokens.
5237
5238@item ^c^COMMENTS^
5239@emph{Check comments.}
5240If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5241then comments must meet the following set of rules:
5242
5243@itemize @bullet
5244
5245@item
5246The ``@code{--}'' that starts the column must either start in column one,
5247or else at least one blank must precede this sequence.
5248
5249@item
5250Comments that follow other tokens on a line must have at least one blank
5251following the ``@code{--}'' at the start of the comment.
5252
5253@item
5254Full line comments must have two blanks following the ``@code{--}'' that
5255starts the comment, with the following exceptions.
5256
5257@item
5258A line consisting only of the ``@code{--}'' characters, possibly preceded
5259by blanks is permitted.
5260
5261@item
5262A comment starting with ``@code{--x}'' where @code{x} is a special character
5263is permitted.
5264This allows proper processing of the output generated by specialized tools
5265including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5266annotation
5267language (where ``@code{--#}'' is used). For the purposes of this rule, a
5268special character is defined as being in one of the ASCII ranges
5269@code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5270Note that this usage is not permitted
5271in GNAT implementation units (i.e. when @option{-gnatg} is used).
5272
5273@item
5274A line consisting entirely of minus signs, possibly preceded by blanks, is
5275permitted. This allows the construction of box comments where lines of minus
5276signs are used to form the top and bottom of the box.
5277
5278@item
5279If a comment starts and ends with ``@code{--}'' is permitted as long as at
5280least one blank follows the initial ``@code{--}''. Together with the preceding
5281rule, this allows the construction of box comments, as shown in the following
5282example:
5283@smallexample
5284---------------------------
5285-- This is a box comment --
5286-- with two text lines.  --
5287---------------------------
5288@end smallexample
5289@end itemize
5290
5291@item ^e^END^
5292@emph{Check end/exit labels.}
5293If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5294optional labels on @code{end} statements ending subprograms and on
5295@code{exit} statements exiting named loops, are required to be present.
5296
5297@item ^f^VTABS^
5298@emph{No form feeds or vertical tabs.}
5299If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5300neither form feeds nor vertical tab characters are not permitted
5301in the source text.
5302
5303@item ^h^HTABS^
5304@emph{No horizontal tabs.}
5305If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5306horizontal tab characters are not permitted in the source text.
5307Together with the b (no blanks at end of line) check, this
5308enforces a canonical form for the use of blanks to separate
5309source tokens.
5310
5311@item ^i^IF_THEN^
5312@emph{Check if-then layout.}
5313If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5314then the keyword @code{then} must appear either on the same
5315line as corresponding @code{if}, or on a line on its own, lined
5316up under the @code{if} with at least one non-blank line in between
5317containing all or part of the condition to be tested.
5318
5319@item ^k^KEYWORD^
5320@emph{Check keyword casing.}
5321If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5322all keywords must be in lower case (with the exception of keywords
5323such as @code{digits} used as attribute names to which this check
5324does not apply).
5325
5326@item ^l^LAYOUT^
5327@emph{Check layout.}
5328If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5329layout of statement and declaration constructs must follow the
5330recommendations in the Ada Reference Manual, as indicated by the
5331form of the syntax rules. For example an @code{else} keyword must
5332be lined up with the corresponding @code{if} keyword.
5333
5334There are two respects in which the style rule enforced by this check
5335option are more liberal than those in the Ada Reference Manual. First
5336in the case of record declarations, it is permissible to put the
5337@code{record} keyword on the same line as the @code{type} keyword, and
5338then the @code{end} in @code{end record} must line up under @code{type}.
5339For example, either of the following two layouts is acceptable:
5340
5341@smallexample @c ada
5342@cartouche
5343type q is record
5344   a : integer;
5345   b : integer;
5346end record;
5347
5348type q is
5349   record
5350      a : integer;
5351      b : integer;
5352   end record;
5353@end cartouche
5354@end smallexample
5355
5356@noindent
5357Second, in the case of a block statement, a permitted alternative
5358is to put the block label on the same line as the @code{declare} or
5359@code{begin} keyword, and then line the @code{end} keyword up under
5360the block label. For example both the following are permitted:
5361
5362@smallexample @c ada
5363@cartouche
5364Block : declare
5365   A : Integer := 3;
5366begin
5367   Proc (A, A);
5368end Block;
5369
5370Block :
5371   declare
5372      A : Integer := 3;
5373   begin
5374      Proc (A, A);
5375   end Block;
5376@end cartouche
5377@end smallexample
5378
5379@noindent
5380The same alternative format is allowed for loops. For example, both of
5381the following are permitted:
5382
5383@smallexample @c ada
5384@cartouche
5385Clear : while J < 10 loop
5386   A (J) := 0;
5387end loop Clear;
5388
5389Clear :
5390   while J < 10 loop
5391      A (J) := 0;
5392   end loop Clear;
5393@end cartouche
5394@end smallexample
5395
5396@item ^m^LINE_LENGTH^
5397@emph{Check maximum line length.}
5398If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5399then the length of source lines must not exceed 79 characters, including
5400any trailing blanks. The value of 79 allows convenient display on an
540180 character wide device or window, allowing for possible special
5402treatment of 80 character lines. Note that this count is of raw
5403characters in the source text. This means that a tab character counts
5404as one character in this count and a wide character sequence counts as
5405several characters (however many are needed in the encoding).
5406
5407@item ^Mnnn^MAX_LENGTH=nnn^
5408@emph{Set maximum line length.}
5409If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5410the string after @option{-gnaty} then the length of lines must not exceed the
5411given value.
5412
5413@item ^n^STANDARD_CASING^
5414@emph{Check casing of entities in Standard.}
5415If the ^letter n^word STANDARD_CASING^ appears in the string
5416after @option{-gnaty} then any identifier from Standard must be cased
5417to match the presentation in the Ada Reference Manual (for example,
5418@code{Integer} and @code{ASCII.NUL}).
5419
5420@item ^o^ORDERED_SUBPROGRAMS^
5421@emph{Check order of subprogram bodies.}
5422If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5423after @option{-gnaty} then all subprogram bodies in a given scope
5424(e.g. a package body) must be in alphabetical order. The ordering
5425rule uses normal Ada rules for comparing strings, ignoring casing
5426of letters, except that if there is a trailing numeric suffix, then
5427the value of this suffix is used in the ordering (e.g. Junk2 comes
5428before Junk10).
5429
5430@item ^p^PRAGMA^
5431@emph{Check pragma casing.}
5432If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5433pragma names must be written in mixed case, that is, the
5434initial letter and any letter following an underscore must be uppercase.
5435All other letters must be lowercase.
5436
5437@item ^r^REFERENCES^
5438@emph{Check references.}
5439If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5440then all identifier references must be cased in the same way as the
5441corresponding declaration. No specific casing style is imposed on
5442identifiers. The only requirement is for consistency of references
5443with declarations.
5444
5445@item ^s^SPECS^
5446@emph{Check separate specs.}
5447If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5448separate declarations (``specs'') are required for subprograms (a
5449body is not allowed to serve as its own declaration). The only
5450exception is that parameterless library level procedures are
5451not required to have a separate declaration. This exception covers
5452the most frequent form of main program procedures.
5453
5454@item ^t^TOKEN^
5455@emph{Check token spacing.}
5456If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5457the following token spacing rules are enforced:
5458
5459@itemize @bullet
5460
5461@item
5462The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5463
5464@item
5465The token @code{=>} must be surrounded by spaces.
5466
5467@item
5468The token @code{<>} must be preceded by a space or a left parenthesis.
5469
5470@item
5471Binary operators other than @code{**} must be surrounded by spaces.
5472There is no restriction on the layout of the @code{**} binary operator.
5473
5474@item
5475Colon must be surrounded by spaces.
5476
5477@item
5478Colon-equal (assignment, initialization) must be surrounded by spaces.
5479
5480@item
5481Comma must be the first non-blank character on the line, or be
5482immediately preceded by a non-blank character, and must be followed
5483by a space.
5484
5485@item
5486If the token preceding a left parenthesis ends with a letter or digit, then
5487a space must separate the two tokens.
5488
5489@item
5490A right parenthesis must either be the first non-blank character on
5491a line, or it must be preceded by a non-blank character.
5492
5493@item
5494A semicolon must not be preceded by a space, and must not be followed by
5495a non-blank character.
5496
5497@item
5498A unary plus or minus may not be followed by a space.
5499
5500@item
5501A vertical bar must be surrounded by spaces.
5502@end itemize
5503
5504@noindent
5505In the above rules, appearing in column one is always permitted, that is,
5506counts as meeting either a requirement for a required preceding space,
5507or as meeting a requirement for no preceding space.
5508
5509Appearing at the end of a line is also always permitted, that is, counts
5510as meeting either a requirement for a following space, or as meeting
5511a requirement for no following space.
5512
5513@end table
5514
5515@noindent
5516If any of these style rules is violated, a message is generated giving
5517details on the violation. The initial characters of such messages are
5518always ``@code{(style)}''. Note that these messages are treated as warning
5519messages, so they normally do not prevent the generation of an object
5520file. The @option{-gnatwe} switch can be used to treat warning messages,
5521including style messages, as fatal errors.
5522
5523@noindent
5524The switch
5525@ifclear vms
5526@option{-gnaty} on its own (that is not
5527followed by any letters or digits),
5528is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5529options enabled with the exception of -gnatyo,
5530@end ifclear
5531@ifset vms
5532/STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5533the exception of ORDERED_SUBPROGRAMS,
5534@end ifset
5535with an indentation level of 3. This is the standard
5536checking option that is used for the GNAT sources.
5537
5538
5539@node Run-Time Checks
5540@subsection Run-Time Checks
5541@cindex Division by zero
5542@cindex Access before elaboration
5543@cindex Checks, division by zero
5544@cindex Checks, access before elaboration
5545
5546@noindent
5547If you compile with the default options, GNAT will insert many run-time
5548checks into the compiled code, including code that performs range
5549checking against constraints, but not arithmetic overflow checking for
5550integer operations (including division by zero) or checks for access
5551before elaboration on subprogram calls. All other run-time checks, as
5552required by the Ada 95 Reference Manual, are generated by default.
5553The following @code{gcc} switches refine this default behavior:
5554
5555@table @option
5556@c !sort!
5557@item -gnatp
5558@cindex @option{-gnatp} (@code{gcc})
5559@cindex Suppressing checks
5560@cindex Checks, suppressing
5561@findex Suppress
5562Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5563had been present in the source. Validity checks are also suppressed (in
5564other words @option{-gnatp} also implies @option{-gnatVn}.
5565Use this switch to improve the performance
5566of the code at the expense of safety in the presence of invalid data or
5567program bugs.
5568
5569@item -gnato
5570@cindex @option{-gnato} (@code{gcc})
5571@cindex Overflow checks
5572@cindex Check, overflow
5573Enables overflow checking for integer operations.
5574This causes GNAT to generate slower and larger executable
5575programs by adding code to check for overflow (resulting in raising
5576@code{Constraint_Error} as required by standard Ada
5577semantics). These overflow checks correspond to situations in which
5578the true value of the result of an operation may be outside the base
5579range of the result type. The following example shows the distinction:
5580
5581@smallexample @c ada
5582X1 : Integer := Integer'Last;
5583X2 : Integer range 1 .. 5 := 5;
5584X3 : Integer := Integer'Last;
5585X4 : Integer range 1 .. 5 := 5;
5586F  : Float := 2.0E+20;
5587...
5588X1 := X1 + 1;
5589X2 := X2 + 1;
5590X3 := Integer (F);
5591X4 := Integer (F);
5592@end smallexample
5593
5594@noindent
5595Here the first addition results in a value that is outside the base range
5596of Integer, and hence requires an overflow check for detection of the
5597constraint error. Thus the first assignment to @code{X1} raises a
5598@code{Constraint_Error} exception only if @option{-gnato} is set.
5599
5600The second increment operation results in a violation
5601of the explicit range constraint, and such range checks are always
5602performed (unless specifically suppressed with a pragma @code{suppress}
5603or the use of @option{-gnatp}).
5604
5605The two conversions of @code{F} both result in values that are outside
5606the base range of type @code{Integer} and thus will raise
5607@code{Constraint_Error} exceptions only if @option{-gnato} is used.
5608The fact that the result of the second conversion is assigned to
5609variable @code{X4} with a restricted range is irrelevant, since the problem
5610is in the conversion, not the assignment.
5611
5612Basically the rule is that in the default mode (@option{-gnato} not
5613used), the generated code assures that all integer variables stay
5614within their declared ranges, or within the base range if there is
5615no declared range. This prevents any serious problems like indexes
5616out of range for array operations.
5617
5618What is not checked in default mode is an overflow that results in
5619an in-range, but incorrect value. In the above example, the assignments
5620to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5621range of the target variable, but the result is wrong in the sense that
5622it is too large to be represented correctly. Typically the assignment
5623to @code{X1} will result in wrap around to the largest negative number.
5624The conversions of @code{F} will result in some @code{Integer} value
5625and if that integer value is out of the @code{X4} range then the
5626subsequent assignment would generate an exception.
5627
5628@findex Machine_Overflows
5629Note that the @option{-gnato} switch does not affect the code generated
5630for any floating-point operations; it applies only to integer
5631semantics).
5632For floating-point, GNAT has the @code{Machine_Overflows}
5633attribute set to @code{False} and the normal mode of operation is to
5634generate IEEE NaN and infinite values on overflow or invalid operations
5635(such as dividing 0.0 by 0.0).
5636
5637The reason that we distinguish overflow checking from other kinds of
5638range constraint checking is that a failure of an overflow check can
5639generate an incorrect value, but cannot cause erroneous behavior. This
5640is unlike the situation with a constraint check on an array subscript,
5641where failure to perform the check can result in random memory description,
5642or the range check on a case statement, where failure to perform the check
5643can cause a wild jump.
5644
5645Note again that @option{-gnato} is off by default, so overflow checking is
5646not performed in default mode. This means that out of the box, with the
5647default settings, GNAT does not do all the checks expected from the
5648language description in the Ada Reference Manual. If you want all constraint
5649checks to be performed, as described in this Manual, then you must
5650explicitly use the -gnato switch either on the @code{gnatmake} or
5651@code{gcc} command.
5652
5653@item -gnatE
5654@cindex @option{-gnatE} (@code{gcc})
5655@cindex Elaboration checks
5656@cindex Check, elaboration
5657Enables dynamic checks for access-before-elaboration
5658on subprogram calls and generic instantiations.
5659For full details of the effect and use of this switch,
5660@xref{Compiling Using gcc}.
5661@end table
5662
5663@findex Unsuppress
5664@noindent
5665The setting of these switches only controls the default setting of the
5666checks. You may modify them using either @code{Suppress} (to remove
5667checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5668the program source.
5669
5670@node Stack Overflow Checking
5671@subsection Stack Overflow Checking
5672@cindex Stack Overflow Checking
5673@cindex -fstack-check
5674
5675@noindent
5676For most operating systems, @code{gcc} does not perform stack overflow
5677checking by default. This means that if the main environment task or
5678some other task exceeds the available stack space, then unpredictable
5679behavior will occur.
5680
5681To activate stack checking, compile all units with the gcc option
5682@option{-fstack-check}. For example:
5683
5684@smallexample
5685gcc -c -fstack-check package1.adb
5686@end smallexample
5687
5688@noindent
5689Units compiled with this option will generate extra instructions to check
5690that any use of the stack (for procedure calls or for declaring local
5691variables in declare blocks) do not exceed the available stack space.
5692If the space is exceeded, then a @code{Storage_Error} exception is raised.
5693
5694For declared tasks, the stack size is always controlled by the size
5695given in an applicable @code{Storage_Size} pragma (or is set to
5696the default size if no pragma is used.
5697
5698For the environment task, the stack size depends on
5699system defaults and is unknown to the compiler. The stack
5700may even dynamically grow on some systems, precluding the
5701normal Ada semantics for stack overflow. In the worst case,
5702unbounded stack usage, causes unbounded stack expansion
5703resulting in the system running out of virtual memory.
5704
5705The stack checking may still work correctly if a fixed
5706size stack is allocated, but this cannot be guaranteed.
5707To ensure that a clean exception is signalled for stack
5708overflow, set the environment variable
5709@code{GNAT_STACK_LIMIT} to indicate the maximum
5710stack area that can be used, as in:
5711@cindex GNAT_STACK_LIMIT
5712
5713@smallexample
5714SET GNAT_STACK_LIMIT 1600
5715@end smallexample
5716
5717@noindent
5718The limit is given in kilobytes, so the above declaration would
5719set the stack limit of the environment task to 1.6 megabytes.
5720Note that the only purpose of this usage is to limit the amount
5721of stack used by the environment task. If it is necessary to
5722increase the amount of stack for the environment task, then this
5723is an operating systems issue, and must be addressed with the
5724appropriate operating systems commands.
5725
5726
5727@node Using gcc for Syntax Checking
5728@subsection Using @code{gcc} for Syntax Checking
5729@table @option
5730@item -gnats
5731@cindex @option{-gnats} (@code{gcc})
5732@ifclear vms
5733
5734@noindent
5735The @code{s} stands for ``syntax''.
5736@end ifclear
5737
5738Run GNAT in syntax checking only mode. For
5739example, the command
5740
5741@smallexample
5742$ gcc -c -gnats x.adb
5743@end smallexample
5744
5745@noindent
5746compiles file @file{x.adb} in syntax-check-only mode. You can check a
5747series of files in a single command
5748@ifclear vms
5749, and can use wild cards to specify such a group of files.
5750Note that you must specify the @option{-c} (compile
5751only) flag in addition to the @option{-gnats} flag.
5752@end ifclear
5753.
5754You may use other switches in conjunction with @option{-gnats}. In
5755particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5756format of any generated error messages.
5757
5758When the source file is empty or contains only empty lines and/or comments,
5759the output is a warning:
5760
5761@smallexample
5762$ gcc -c -gnats -x ada toto.txt
5763toto.txt:1:01: warning: empty file, contains no compilation units
5764$
5765@end smallexample
5766
5767Otherwise, the output is simply the error messages, if any. No object file or
5768ALI file is generated by a syntax-only compilation. Also, no units other
5769than the one specified are accessed. For example, if a unit @code{X}
5770@code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5771check only mode does not access the source file containing unit
5772@code{Y}.
5773
5774@cindex Multiple units, syntax checking
5775Normally, GNAT allows only a single unit in a source file. However, this
5776restriction does not apply in syntax-check-only mode, and it is possible
5777to check a file containing multiple compilation units concatenated
5778together. This is primarily used by the @code{gnatchop} utility
5779(@pxref{Renaming Files Using gnatchop}).
5780@end table
5781
5782
5783@node Using gcc for Semantic Checking
5784@subsection Using @code{gcc} for Semantic Checking
5785@table @option
5786@item -gnatc
5787@cindex @option{-gnatc} (@code{gcc})
5788
5789@ifclear vms
5790@noindent
5791The @code{c} stands for ``check''.
5792@end ifclear
5793Causes the compiler to operate in semantic check mode,
5794with full checking for all illegalities specified in the
5795Ada 95 Reference Manual, but without generation of any object code
5796(no object file is generated).
5797
5798Because dependent files must be accessed, you must follow the GNAT
5799semantic restrictions on file structuring to operate in this mode:
5800
5801@itemize @bullet
5802@item
5803The needed source files must be accessible
5804(@pxref{Search Paths and the Run-Time Library (RTL)}).
5805
5806@item
5807Each file must contain only one compilation unit.
5808
5809@item
5810The file name and unit name must match (@pxref{File Naming Rules}).
5811@end itemize
5812
5813The output consists of error messages as appropriate. No object file is
5814generated. An @file{ALI} file is generated for use in the context of
5815cross-reference tools, but this file is marked as not being suitable
5816for binding (since no object file is generated).
5817The checking corresponds exactly to the notion of
5818legality in the Ada 95 Reference Manual.
5819
5820Any unit can be compiled in semantics-checking-only mode, including
5821units that would not normally be compiled (subunits,
5822and specifications where a separate body is present).
5823@end table
5824
5825@node Compiling Ada 83 Programs
5826@subsection Compiling Ada 83 Programs
5827@table @option
5828@cindex Ada 83 compatibility
5829@item -gnat83
5830@cindex @option{-gnat83} (@code{gcc})
5831@cindex ACVC, Ada 83 tests
5832
5833@noindent
5834Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5835specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5836this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5837where this can be done easily.
5838It is not possible to guarantee this switch does a perfect
5839job; for example, some subtle tests, such as are
5840found in earlier ACVC tests (and that have been removed from the ACATS suite
5841for Ada 95), might not compile correctly.
5842Nevertheless, this switch may be useful in some circumstances, for example
5843where, due to contractual reasons, legacy code needs to be maintained
5844using only Ada 83 features.
5845
5846With few exceptions (most notably the need to use @code{<>} on
5847@cindex Generic formal parameters
5848unconstrained generic formal parameters, the use of the new Ada 95
5849reserved words, and the use of packages
5850with optional bodies), it is not necessary to use the
5851@option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5852exceptions, Ada 95 is upwardly compatible with Ada 83. This
5853means that a correct Ada 83 program is usually also a correct Ada 95
5854program.
5855For further information, please refer to @ref{Compatibility and Porting Guide}.
5856
5857@end table
5858
5859@node Character Set Control
5860@subsection Character Set Control
5861@table @option
5862@item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5863@cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5864
5865@noindent
5866Normally GNAT recognizes the Latin-1 character set in source program
5867identifiers, as described in the Ada 95 Reference Manual.
5868This switch causes
5869GNAT to recognize alternate character sets in identifiers. @var{c} is a
5870single character ^^or word^ indicating the character set, as follows:
5871
5872@table @code
5873@item 1
5874ISO 8859-1 (Latin-1) identifiers
5875
5876@item 2
5877ISO 8859-2 (Latin-2) letters allowed in identifiers
5878
5879@item 3
5880ISO 8859-3 (Latin-3) letters allowed in identifiers
5881
5882@item 4
5883ISO 8859-4 (Latin-4) letters allowed in identifiers
5884
5885@item 5
5886ISO 8859-5 (Cyrillic) letters allowed in identifiers
5887
5888@item 9
5889ISO 8859-15 (Latin-9) letters allowed in identifiers
5890
5891@item ^p^PC^
5892IBM PC letters (code page 437) allowed in identifiers
5893
5894@item ^8^PC850^
5895IBM PC letters (code page 850) allowed in identifiers
5896
5897@item ^f^FULL_UPPER^
5898Full upper-half codes allowed in identifiers
5899
5900@item ^n^NO_UPPER^
5901No upper-half codes allowed in identifiers
5902
5903@item ^w^WIDE^
5904Wide-character codes (that is, codes greater than 255)
5905allowed in identifiers
5906@end table
5907
5908@xref{Foreign Language Representation}, for full details on the
5909implementation of these character sets.
5910
5911@item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5912@cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5913Specify the method of encoding for wide characters.
5914@var{e} is one of the following:
5915
5916@table @code
5917
5918@item ^h^HEX^
5919Hex encoding (brackets coding also recognized)
5920
5921@item ^u^UPPER^
5922Upper half encoding (brackets encoding also recognized)
5923
5924@item ^s^SHIFT_JIS^
5925Shift/JIS encoding (brackets encoding also recognized)
5926
5927@item ^e^EUC^
5928EUC encoding (brackets encoding also recognized)
5929
5930@item ^8^UTF8^
5931UTF-8 encoding (brackets encoding also recognized)
5932
5933@item ^b^BRACKETS^
5934Brackets encoding only (default value)
5935@end table
5936For full details on the these encoding
5937methods see @xref{Wide Character Encodings}.
5938Note that brackets coding is always accepted, even if one of the other
5939options is specified, so for example @option{-gnatW8} specifies that both
5940brackets and @code{UTF-8} encodings will be recognized. The units that are
5941with'ed directly or indirectly will be scanned using the specified
5942representation scheme, and so if one of the non-brackets scheme is
5943used, it must be used consistently throughout the program. However,
5944since brackets encoding is always recognized, it may be conveniently
5945used in standard libraries, allowing these libraries to be used with
5946any of the available coding schemes.
5947scheme. If no @option{-gnatW?} parameter is present, then the default
5948representation is Brackets encoding only.
5949
5950Note that the wide character representation that is specified (explicitly
5951or by default) for the main program also acts as the default encoding used
5952for Wide_Text_IO files if not specifically overridden by a WCEM form
5953parameter.
5954
5955@end table
5956@node File Naming Control
5957@subsection File Naming Control
5958
5959@table @option
5960@item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5961@cindex @option{-gnatk} (@code{gcc})
5962Activates file name ``krunching''. @var{n}, a decimal integer in the range
59631-999, indicates the maximum allowable length of a file name (not
5964including the @file{.ads} or @file{.adb} extension). The default is not
5965to enable file name krunching.
5966
5967For the source file naming rules, @xref{File Naming Rules}.
5968@end table
5969
5970
5971@node Subprogram Inlining Control
5972@subsection Subprogram Inlining Control
5973
5974@table @option
5975@c !sort!
5976@item -gnatn
5977@cindex @option{-gnatn} (@code{gcc})
5978@ifclear vms
5979The @code{n} here is intended to suggest the first syllable of the
5980word ``inline''.
5981@end ifclear
5982GNAT recognizes and processes @code{Inline} pragmas. However, for the
5983inlining to actually occur, optimization must be enabled. To enable
5984inlining of subprograms specified by pragma @code{Inline},
5985you must also specify this switch.
5986In the absence of this switch, GNAT does not attempt
5987inlining and does not need to access the bodies of
5988subprograms for which @code{pragma Inline} is specified if they are not
5989in the current unit.
5990
5991If you specify this switch the compiler will access these bodies,
5992creating an extra source dependency for the resulting object file, and
5993where possible, the call will be inlined.
5994For further details on when inlining is possible
5995see @xref{Inlining of Subprograms}.
5996
5997@item -gnatN
5998@cindex @option{-gnatN} (@code{gcc})
5999The front end inlining activated by this switch is generally more extensive,
6000and quite often more effective than the standard @option{-gnatn} inlining mode.
6001It will also generate additional dependencies.
6002Note that
6003@option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6004to specify both options.
6005@end table
6006
6007@node Auxiliary Output Control
6008@subsection Auxiliary Output Control
6009
6010@table @option
6011@item -gnatt
6012@cindex @option{-gnatt} (@code{gcc})
6013@cindex Writing internal trees
6014@cindex Internal trees, writing to file
6015Causes GNAT to write the internal tree for a unit to a file (with the
6016extension @file{.adt}.
6017This not normally required, but is used by separate analysis tools.
6018Typically
6019these tools do the necessary compilations automatically, so you should
6020not have to specify this switch in normal operation.
6021
6022@item -gnatu
6023@cindex @option{-gnatu} (@code{gcc})
6024Print a list of units required by this compilation on @file{stdout}.
6025The listing includes all units on which the unit being compiled depends
6026either directly or indirectly.
6027
6028@ifclear vms
6029@item -pass-exit-codes
6030@cindex @option{-pass-exit-codes} (@code{gcc})
6031If this switch is not used, the exit code returned by @code{gcc} when
6032compiling multiple files indicates whether all source files have
6033been successfully used to generate object files or not.
6034
6035When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6036exit status and allows an integrated development environment to better
6037react to a compilation failure. Those exit status are:
6038
6039@table @asis
6040@item 5
6041There was an error in at least one source file.
6042@item 3
6043At least one source file did not generate an object file.
6044@item 2
6045The compiler died unexpectedly (internal error for example).
6046@item 0
6047An object file has been generated for every source file.
6048@end table
6049@end ifclear
6050@end table
6051
6052@node Debugging Control
6053@subsection Debugging Control
6054
6055@table @option
6056@c !sort!
6057@cindex Debugging options
6058@ifclear vms
6059@item -gnatd@var{x}
6060@cindex @option{-gnatd} (@code{gcc})
6061Activate internal debugging switches. @var{x} is a letter or digit, or
6062string of letters or digits, which specifies the type of debugging
6063outputs desired. Normally these are used only for internal development
6064or system debugging purposes. You can find full documentation for these
6065switches in the body of the @code{Debug} unit in the compiler source
6066file @file{debug.adb}.
6067@end ifclear
6068
6069@item -gnatG
6070@cindex @option{-gnatG} (@code{gcc})
6071This switch causes the compiler to generate auxiliary output containing
6072a pseudo-source listing of the generated expanded code. Like most Ada
6073compilers, GNAT works by first transforming the high level Ada code into
6074lower level constructs. For example, tasking operations are transformed
6075into calls to the tasking run-time routines. A unique capability of GNAT
6076is to list this expanded code in a form very close to normal Ada source.
6077This is very useful in understanding the implications of various Ada
6078usage on the efficiency of the generated code. There are many cases in
6079Ada (e.g. the use of controlled types), where simple Ada statements can
6080generate a lot of run-time code. By using @option{-gnatG} you can identify
6081these cases, and consider whether it may be desirable to modify the coding
6082approach to improve efficiency.
6083
6084The format of the output is very similar to standard Ada source, and is
6085easily understood by an Ada programmer. The following special syntactic
6086additions correspond to low level features used in the generated code that
6087do not have any exact analogies in pure Ada source form. The following
6088is a partial list of these special constructions. See the specification
6089of package @code{Sprint} in file @file{sprint.ads} for a full list.
6090
6091@table @code
6092@item new @var{xxx} [storage_pool = @var{yyy}]
6093Shows the storage pool being used for an allocator.
6094
6095@item at end @var{procedure-name};
6096Shows the finalization (cleanup) procedure for a scope.
6097
6098@item (if @var{expr} then @var{expr} else @var{expr})
6099Conditional expression equivalent to the @code{x?y:z} construction in C.
6100
6101@item @var{target}^^^(@var{source})
6102A conversion with floating-point truncation instead of rounding.
6103
6104@item @var{target}?(@var{source})
6105A conversion that bypasses normal Ada semantic checking. In particular
6106enumeration types and fixed-point types are treated simply as integers.
6107
6108@item @var{target}?^^^(@var{source})
6109Combines the above two cases.
6110
6111@item @var{x} #/ @var{y}
6112@itemx @var{x} #mod @var{y}
6113@itemx @var{x} #* @var{y}
6114@itemx @var{x} #rem @var{y}
6115A division or multiplication of fixed-point values which are treated as
6116integers without any kind of scaling.
6117
6118@item free @var{expr} [storage_pool = @var{xxx}]
6119Shows the storage pool associated with a @code{free} statement.
6120
6121@item freeze @var{typename} [@var{actions}]
6122Shows the point at which @var{typename} is frozen, with possible
6123associated actions to be performed at the freeze point.
6124
6125@item reference @var{itype}
6126Reference (and hence definition) to internal type @var{itype}.
6127
6128@item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6129Intrinsic function call.
6130
6131@item @var{labelname} : label
6132Declaration of label @var{labelname}.
6133
6134@item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6135A multiple concatenation (same effect as @var{expr} & @var{expr} &
6136@var{expr}, but handled more efficiently).
6137
6138@item [constraint_error]
6139Raise the @code{Constraint_Error} exception.
6140
6141@item @var{expression}'reference
6142A pointer to the result of evaluating @var{expression}.
6143
6144@item @var{target-type}!(@var{source-expression})
6145An unchecked conversion of @var{source-expression} to @var{target-type}.
6146
6147@item [@var{numerator}/@var{denominator}]
6148Used to represent internal real literals (that) have no exact
6149representation in base 2-16 (for example, the result of compile time
6150evaluation of the expression 1.0/27.0).
6151@end table
6152
6153@item -gnatD
6154@cindex @option{-gnatD} (@code{gcc})
6155This switch is used in conjunction with @option{-gnatG} to cause the expanded
6156source, as described above to be written to files with names
6157@file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6158for example, if the source file name is @file{hello.adb},
6159then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.
6160The debugging information generated
6161by the @code{gcc} @option{^-g^/DEBUG^} switch will refer to the generated
6162@file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using
6163the generated code which is sometimes useful for complex code, for example
6164to find out exactly which part of a complex construction raised an
6165exception. This switch also suppress generation of cross-reference
6166information (see -gnatx).
6167
6168@ifclear vms
6169@item -gnatR[0|1|2|3[s]]
6170@cindex @option{-gnatR} (@code{gcc})
6171This switch controls output from the compiler of a listing showing
6172representation information for declared types and objects. For
6173@option{-gnatR0}, no information is output (equivalent to omitting
6174the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6175so @option{-gnatR} with no parameter has the same effect), size and alignment
6176information is listed for declared array and record types. For
6177@option{-gnatR2}, size and alignment information is listed for all
6178expression information for values that are computed at run time for
6179variant records. These symbolic expressions have a mostly obvious
6180format with #n being used to represent the value of the n'th
6181discriminant. See source files @file{repinfo.ads/adb} in the
6182@code{GNAT} sources for full details on the format of @option{-gnatR3}
6183output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6184the output is to a file with the name @file{^file.rep^file_REP^} where
6185file is the name of the corresponding source file.
6186@end ifclear
6187@ifset vms
6188@item /REPRESENTATION_INFO
6189@cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6190This qualifier controls output from the compiler of a listing showing
6191representation information for declared types and objects. For
6192@option{/REPRESENTATION_INFO=NONE}, no information is output
6193(equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6194@option{/REPRESENTATION_INFO} without option is equivalent to
6195@option{/REPRESENTATION_INFO=ARRAYS}.
6196For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6197information is listed for declared array and record types. For
6198@option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6199is listed for all expression information for values that are computed
6200at run time for variant records. These symbolic expressions have a mostly
6201obvious format with #n being used to represent the value of the n'th
6202discriminant. See source files @file{REPINFO.ADS/ADB} in the
6203@code{GNAT} sources for full details on the format of
6204@option{/REPRESENTATION_INFO=SYMBOLIC} output.
6205If _FILE is added at the end of an option
6206(e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6207then the output is to a file with the name @file{file_REP} where
6208file is the name of the corresponding source file.
6209@end ifset
6210
6211@item -gnatS
6212@cindex @option{-gnatS} (@code{gcc})
6213The use of the switch @option{-gnatS} for an
6214Ada compilation will cause the compiler to output a
6215representation of package Standard in a form very
6216close to standard Ada. It is not quite possible to
6217do this and remain entirely Standard (since new
6218numeric base types cannot be created in standard
6219Ada), but the output is easily
6220readable to any Ada programmer, and is useful to
6221determine the characteristics of target dependent
6222types in package Standard.
6223
6224@item -gnatx
6225@cindex @option{-gnatx} (@code{gcc})
6226Normally the compiler generates full cross-referencing information in
6227the @file{ALI} file. This information is used by a number of tools,
6228including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6229suppresses this information. This saves some space and may slightly
6230speed up compilation, but means that these tools cannot be used.
6231@end table
6232
6233@node Exception Handling Control
6234@subsection Exception Handling Control
6235
6236@noindent
6237GNAT uses two methods for handling exceptions at run-time. The
6238@code{longjmp/setjmp} method saves the context when entering
6239a frame with an exception handler. Then when an exception is
6240raised, the context can be restored immediately, without the
6241need for tracing stack frames. This method provides very fast
6242exception propagation, but introduces significant overhead for
6243the use of exception handlers, even if no exception is raised.
6244
6245The other approach is called ``zero cost'' exception handling.
6246With this method, the compiler builds static tables to describe
6247the exception ranges. No dynamic code is required when entering
6248a frame containing an exception handler. When an exception is
6249raised, the tables are used to control a back trace of the
6250subprogram invocation stack to locate the required exception
6251handler. This method has considerably poorer performance for
6252the propagation of exceptions, but there is no overhead for
6253exception handlers if no exception is raised.
6254
6255The following switches can be used to control which of the
6256two exception handling methods is used.
6257
6258@table @option
6259@c !sort!
6260
6261@item -gnatL
6262@cindex @option{-gnatL} (@code{gcc})
6263This switch causes the longjmp/setjmp approach to be used
6264for exception handling. If this is the default mechanism for the
6265target (see below), then this has no effect. If the default
6266mechanism for the target is zero cost exceptions, then
6267this switch can be used to modify this default, but it must be
6268used for all units in the partition, including all run-time
6269library units. One way to achieve this is to use the
6270@option{-a} and @option{-f} switches for @code{gnatmake}.
6271This option is rarely used. One case in which it may be
6272advantageous is if you have an application where exception
6273raising is common and the overall performance of the
6274application is improved by favoring exception propagation.
6275
6276@item -gnatZ
6277@cindex @option{-gnatZ} (@code{gcc})
6278@cindex Zero Cost Exceptions
6279This switch causes the zero cost approach to be sed
6280for exception handling. If this is the default mechanism for the
6281target (see below), then this has no effect. If the default
6282mechanism for the target is longjmp/setjmp exceptions, then
6283this switch can be used to modify this default, but it must be
6284used for all units in the partition, including all run-time
6285library units. One way to achieve this is to use the
6286@option{-a} and @option{-f} switches for @code{gnatmake}.
6287This option can only be used if the zero cost approach
6288is available for the target in use (see below).
6289@end table
6290
6291@noindent
6292The @code{longjmp/setjmp} approach is available on all targets, but
6293the @code{zero cost} approach is only available on selected targets.
6294To determine whether zero cost exceptions can be used for a
6295particular target, look at the private part of the file system.ads.
6296Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6297be True to use the zero cost approach. If both of these switches
6298are set to False, this means that zero cost exception handling
6299is not yet available for that target. The switch
6300@code{ZCX_By_Default} indicates the default approach. If this
6301switch is set to True, then the @code{zero cost} approach is
6302used by default.
6303
6304@node Units to Sources Mapping Files
6305@subsection Units to Sources Mapping Files
6306
6307@table @option
6308
6309@item -gnatem^^=^@var{path}
6310@cindex @option{-gnatem} (@code{gcc})
6311A mapping file is a way to communicate to the compiler two mappings:
6312from unit names to file names (without any directory information) and from
6313file names to path names (with full directory information). These mappings
6314are used by the compiler to short-circuit the path search.
6315
6316The use of mapping files is not required for correct operation of the
6317compiler, but mapping files can improve efficiency, particularly when
6318sources are read over a slow network connection. In normal operation,
6319you need not be concerned with the format or use of mapping files,
6320and the @option{-gnatem} switch is not a switch that you would use
6321explicitly. it is intended only for use by automatic tools such as
6322@code{gnatmake} running under the project file facility. The
6323description here of the format of mapping files is provided
6324for completeness and for possible use by other tools.
6325
6326A mapping file is a sequence of sets of three lines. In each set,
6327the first line is the unit name, in lower case, with ``@code{%s}''
6328appended for
6329specifications and ``@code{%b}'' appended for bodies; the second line is the
6330file name; and the third line is the path name.
6331
6332Example:
6333@smallexample
6334   main%b
6335   main.2.ada
6336   /gnat/project1/sources/main.2.ada
6337@end smallexample
6338
6339When the switch @option{-gnatem} is specified, the compiler will create
6340in memory the two mappings from the specified file. If there is any problem
6341(non existent file, truncated file or duplicate entries), no mapping
6342will be created.
6343
6344Several @option{-gnatem} switches may be specified; however, only the last
6345one on the command line will be taken into account.
6346
6347When using a project file, @code{gnatmake} create a temporary mapping file
6348and communicates it to the compiler using this switch.
6349
6350@end table
6351
6352
6353@node Integrated Preprocessing
6354@subsection Integrated Preprocessing
6355
6356@noindent
6357GNAT sources may be preprocessed immediately before compilation; the actual
6358text of the source is not the text of the source file, but is derived from it
6359through a process called preprocessing. Integrated preprocessing is specified
6360through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6361indicates, through a text file, the preprocessing data to be used.
6362@option{-gnateD} specifies or modifies the values of preprocessing symbol.
6363
6364@noindent
6365It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6366used when Integrated Preprocessing is used. The reason is that preprocessing
6367with another Preprocessing Data file without changing the sources will
6368not trigger recompilation without this switch.
6369
6370@noindent
6371Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6372always trigger recompilation for sources that are preprocessed,
6373because @code{gnatmake} cannot compute the checksum of the source after
6374preprocessing.
6375
6376@noindent
6377The actual preprocessing function is described in details in section
6378@ref{Preprocessing Using gnatprep}. This section only describes how integrated
6379preprocessing is triggered and parameterized.
6380
6381@table @code
6382
6383@item -gnatep=@var{file}
6384@cindex @option{-gnatep} (@code{gcc})
6385This switch indicates to the compiler the file name (without directory
6386information) of the preprocessor data file to use. The preprocessor data file
6387should be found in the source directories.
6388
6389@noindent
6390A preprocessing data file is a text file with significant lines indicating
6391how should be preprocessed either a specific source or all sources not
6392mentioned in other lines. A significant line is a non empty, non comment line.
6393Comments are similar to Ada comments.
6394
6395@noindent
6396Each significant line starts with either a literal string or the character '*'.
6397A literal string is the file name (without directory information) of the source
6398to preprocess. A character '*' indicates the preprocessing for all the sources
6399that are not specified explicitly on other lines (order of the lines is not
6400significant). It is an error to have two lines with the same file name or two
6401lines starting with the character '*'.
6402
6403@noindent
6404After the file name or the character '*', another optional literal string
6405indicating the file name of the definition file to be used for preprocessing.
6406(see @ref{Form of Definitions File}. The definition files are found by the
6407compiler in one of the source directories. In some cases, when compiling
6408a source in a directory other than the current directory, if the definition
6409file is in the current directory, it may be necessary to add the current
6410directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6411the compiler would not find the definition file.
6412
6413@noindent
6414Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6415be found. Those ^switches^switches^ are:
6416
6417@table @code
6418
6419@item -b
6420Causes both preprocessor lines and the lines deleted by
6421preprocessing to be replaced by blank lines, preserving the line number.
6422This ^switch^switch^ is always implied; however, if specified after @option{-c}
6423it cancels the effect of @option{-c}.
6424
6425@item -c
6426Causes both preprocessor lines and the lines deleted
6427by preprocessing to be retained as comments marked
6428with the special string ``@code{--! }''.
6429
6430@item -Dsymbol=value
6431Define or redefine a symbol, associated with value. A symbol is an Ada
6432identifier, or an Ada reserved word, with the exception of @code{if},
6433@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6434@code{value} is either a literal string, an Ada identifier or any Ada reserved
6435word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6436same name defined in a definition file.
6437
6438@item -s
6439Causes a sorted list of symbol names and values to be
6440listed on the standard output file.
6441
6442@item -u
6443Causes undefined symbols to be treated as having the value @code{FALSE}
6444in the context
6445of a preprocessor test. In the absence of this option, an undefined symbol in
6446a @code{#if} or @code{#elsif} test will be treated as an error.
6447
6448@end table
6449
6450@noindent
6451Examples of valid lines in a preprocessor data file:
6452
6453@smallexample
6454  "toto.adb"  "prep.def" -u
6455  --  preprocess "toto.adb", using definition file "prep.def",
6456  --  undefined symbol are False.
6457
6458  * -c -DVERSION=V101
6459  --  preprocess all other sources without a definition file;
6460  --  suppressed lined are commented; symbol VERSION has the value V101.
6461
6462  "titi.adb" "prep2.def" -s
6463  --  preprocess "titi.adb", using definition file "prep2.def";
6464  --  list all symbols with their values.
6465@end smallexample
6466
6467@item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6468@cindex @option{-gnateD} (@code{gcc})
6469Define or redefine a preprocessing symbol, associated with value. If no value
6470is given on the command line, then the value of the symbol is @code{True}.
6471A symbol is an identifier, following normal Ada (case-insensitive)
6472rules for its syntax, and value is any sequence (including an empty sequence)
6473of characters from the set (letters, digits, period, underline).
6474Ada reserved words may be used as symbols, with the exceptions of @code{if},
6475@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6476
6477@noindent
6478A symbol declared with this ^switch^switch^ on the command line replaces a
6479symbol with the same name either in a definition file or specified with a
6480^switch^switch^ -D in the preprocessor data file.
6481
6482@noindent
6483This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6484
6485@end table
6486
6487@ifset vms
6488@node Return Codes
6489@subsection Return Codes
6490@cindex Return Codes
6491@cindex @option{/RETURN_CODES=VMS}
6492
6493@noindent
6494On VMS, GNAT compiled programs return POSIX-style codes by default,
6495e.g. @option{/RETURN_CODES=POSIX}.
6496
6497To enable VMS style return codes, GNAT LINK with the option
6498@option{/RETURN_CODES=VMS}. For example:
6499
6500@smallexample
6501GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6502@end smallexample
6503
6504@noindent
6505Programs built with /RETURN_CODES=VMS are suitable to be called in
6506VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6507are suitable for spawning with appropriate GNAT RTL routines.
6508
6509@end ifset
6510
6511
6512@node Search Paths and the Run-Time Library (RTL)
6513@section Search Paths and the Run-Time Library (RTL)
6514
6515@noindent
6516With the GNAT source-based library system, the compiler must be able to
6517find source files for units that are needed by the unit being compiled.
6518Search paths are used to guide this process.
6519
6520The compiler compiles one source file whose name must be given
6521explicitly on the command line. In other words, no searching is done
6522for this file. To find all other source files that are needed (the most
6523common being the specs of units), the compiler examines the following
6524directories, in the following order:
6525
6526@enumerate
6527@item
6528The directory containing the source file of the main unit being compiled
6529(the file name on the command line).
6530
6531@item
6532Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6533@code{gcc} command line, in the order given.
6534
6535@item
6536@findex ADA_INCLUDE_PATH
6537Each of the directories listed in the value of the
6538@code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6539@ifclear vms
6540Construct this value
6541exactly as the @code{PATH} environment variable: a list of directory
6542names separated by colons (semicolons when working with the NT version).
6543@end ifclear
6544@ifset vms
6545Normally, define this value as a logical name containing a comma separated
6546list of directory names.
6547
6548This variable can also be defined by means of an environment string
6549(an argument to the DEC C exec* set of functions).
6550
6551Logical Name:
6552@smallexample
6553DEFINE ANOTHER_PATH FOO:[BAG]
6554DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6555@end smallexample
6556
6557By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6558first, followed by the standard Ada 95
6559libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6560If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6561(Text_IO, Sequential_IO, etc)
6562instead of the Ada95 packages. Thus, in order to get the Ada 95
6563packages by default, ADA_INCLUDE_PATH must be redefined.
6564@end ifset
6565
6566@item
6567@findex ADA_PRJ_INCLUDE_FILE
6568Each of the directories listed in the text file whose name is given
6569by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6570
6571@noindent
6572@code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6573driver when project files are used. It should not normally be set
6574by other means.
6575
6576@item
6577The content of the @file{ada_source_path} file which is part of the GNAT
6578installation tree and is used to store standard libraries such as the
6579GNAT Run Time Library (RTL) source files.
6580@ifclear vms
6581@ref{Installing an Ada Library}
6582@end ifclear
6583@end enumerate
6584
6585@noindent
6586Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6587inhibits the use of the directory
6588containing the source file named in the command line. You can still
6589have this directory on your search path, but in this case it must be
6590explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6591
6592Specifying the switch @option{-nostdinc}
6593inhibits the search of the default location for the GNAT Run Time
6594Library (RTL) source files.
6595
6596The compiler outputs its object files and ALI files in the current
6597working directory.
6598@ifclear vms
6599Caution: The object file can be redirected with the @option{-o} switch;
6600however, @code{gcc} and @code{gnat1} have not been coordinated on this
6601so the @file{ALI} file will not go to the right place. Therefore, you should
6602avoid using the @option{-o} switch.
6603@end ifclear
6604
6605@findex System.IO
6606The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6607children make up the GNAT RTL, together with the simple @code{System.IO}
6608package used in the @code{"Hello World"} example. The sources for these units
6609are needed by the compiler and are kept together in one directory. Not
6610all of the bodies are needed, but all of the sources are kept together
6611anyway. In a normal installation, you need not specify these directory
6612names when compiling or binding. Either the environment variables or
6613the built-in defaults cause these files to be found.
6614
6615In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6616@code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6617consisting of child units of @code{GNAT}. This is a collection of generally
6618useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6619further details.
6620
6621Besides simplifying access to the RTL, a major use of search paths is
6622in compiling sources from multiple directories. This can make
6623development environments much more flexible.
6624
6625
6626@node Order of Compilation Issues
6627@section Order of Compilation Issues
6628
6629@noindent
6630If, in our earlier example, there was a spec for the @code{hello}
6631procedure, it would be contained in the file @file{hello.ads}; yet this
6632file would not have to be explicitly compiled. This is the result of the
6633model we chose to implement library management. Some of the consequences
6634of this model are as follows:
6635
6636@itemize @bullet
6637@item
6638There is no point in compiling specs (except for package
6639specs with no bodies) because these are compiled as needed by clients. If
6640you attempt a useless compilation, you will receive an error message.
6641It is also useless to compile subunits because they are compiled as needed
6642by the parent.
6643
6644@item
6645There are no order of compilation requirements: performing a
6646compilation never obsoletes anything. The only way you can obsolete
6647something and require recompilations is to modify one of the
6648source files on which it depends.
6649
6650@item
6651There is no library as such, apart from the ALI files
6652(@pxref{The Ada Library Information Files}, for information on the format
6653of these files). For now we find it convenient to create separate ALI files,
6654but eventually the information therein may be incorporated into the object
6655file directly.
6656
6657@item
6658When you compile a unit, the source files for the specs of all units
6659that it @code{with}'s, all its subunits, and the bodies of any generics it
6660instantiates must be available (reachable by the search-paths mechanism
6661described above), or you will receive a fatal error message.
6662@end itemize
6663
6664@node Examples
6665@section Examples
6666
6667@noindent
6668The following are some typical Ada compilation command line examples:
6669
6670@table @code
6671@item $ gcc -c xyz.adb
6672Compile body in file @file{xyz.adb} with all default options.
6673
6674@ifclear vms
6675@item $ gcc -c -O2 -gnata xyz-def.adb
6676@end ifclear
6677@ifset vms
6678@item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6679@end ifset
6680
6681Compile the child unit package in file @file{xyz-def.adb} with extensive
6682optimizations, and pragma @code{Assert}/@code{Debug} statements
6683enabled.
6684
6685@item $ gcc -c -gnatc abc-def.adb
6686Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6687mode.
6688@end table
6689
6690@node Binding Using gnatbind
6691@chapter Binding Using @code{gnatbind}
6692@findex gnatbind
6693
6694@menu
6695* Running gnatbind::
6696* Switches for gnatbind::
6697* Command-Line Access::
6698* Search Paths for gnatbind::
6699* Examples of gnatbind Usage::
6700@end menu
6701
6702@noindent
6703This chapter describes the GNAT binder, @code{gnatbind}, which is used
6704to bind compiled GNAT objects. The @code{gnatbind} program performs
6705four separate functions:
6706
6707@enumerate
6708@item
6709Checks that a program is consistent, in accordance with the rules in
6710Chapter 10 of the Ada 95 Reference Manual. In particular, error
6711messages are generated if a program uses inconsistent versions of a
6712given unit.
6713
6714@item
6715Checks that an acceptable order of elaboration exists for the program
6716and issues an error message if it cannot find an order of elaboration
6717that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6718
6719@item
6720Generates a main program incorporating the given elaboration order.
6721This program is a small Ada package (body and spec) that
6722must be subsequently compiled
6723using the GNAT compiler. The necessary compilation step is usually
6724performed automatically by @code{gnatlink}. The two most important
6725functions of this program
6726are to call the elaboration routines of units in an appropriate order
6727and to call the main program.
6728
6729@item
6730Determines the set of object files required by the given main program.
6731This information is output in the forms of comments in the generated program,
6732to be read by the @code{gnatlink} utility used to link the Ada application.
6733@end enumerate
6734
6735
6736@node Running gnatbind
6737@section Running @code{gnatbind}
6738
6739@noindent
6740The form of the @code{gnatbind} command is
6741
6742@smallexample
6743$ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6744@end smallexample
6745
6746@noindent
6747where @file{@i{mainprog}.adb} is the Ada file containing the main program
6748unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6749package in two files whose names are
6750@file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6751For example, if given the
6752parameter @file{hello.ali}, for a main program contained in file
6753@file{hello.adb}, the binder output files would be @file{b~hello.ads}
6754and @file{b~hello.adb}.
6755
6756When doing consistency checking, the binder takes into consideration
6757any source files it can locate. For example, if the binder determines
6758that the given main program requires the package @code{Pack}, whose
6759@file{.ALI}
6760file is @file{pack.ali} and whose corresponding source spec file is
6761@file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6762(using the same search path conventions as previously described for the
6763@code{gcc} command). If it can locate this source file, it checks that
6764the time stamps
6765or source checksums of the source and its references to in @file{ALI} files
6766match. In other words, any @file{ALI} files that mentions this spec must have
6767resulted from compiling this version of the source file (or in the case
6768where the source checksums match, a version close enough that the
6769difference does not matter).
6770
6771@cindex Source files, use by binder
6772The effect of this consistency checking, which includes source files, is
6773that the binder ensures that the program is consistent with the latest
6774version of the source files that can be located at bind time. Editing a
6775source file without compiling files that depend on the source file cause
6776error messages to be generated by the binder.
6777
6778For example, suppose you have a main program @file{hello.adb} and a
6779package @code{P}, from file @file{p.ads} and you perform the following
6780steps:
6781
6782@enumerate
6783@item
6784Enter @code{gcc -c hello.adb} to compile the main program.
6785
6786@item
6787Enter @code{gcc -c p.ads} to compile package @code{P}.
6788
6789@item
6790Edit file @file{p.ads}.
6791
6792@item
6793Enter @code{gnatbind hello}.
6794@end enumerate
6795
6796@noindent
6797At this point, the file @file{p.ali} contains an out-of-date time stamp
6798because the file @file{p.ads} has been edited. The attempt at binding
6799fails, and the binder generates the following error messages:
6800
6801@smallexample
6802error: "hello.adb" must be recompiled ("p.ads" has been modified)
6803error: "p.ads" has been modified and must be recompiled
6804@end smallexample
6805
6806@noindent
6807Now both files must be recompiled as indicated, and then the bind can
6808succeed, generating a main program. You need not normally be concerned
6809with the contents of this file, but for reference purposes a sample
6810binder output file is given in @ref{Example of Binder Output File}.
6811
6812In most normal usage, the default mode of @command{gnatbind} which is to
6813generate the main package in Ada, as described in the previous section.
6814In particular, this means that any Ada programmer can read and understand
6815the generated main program. It can also be debugged just like any other
6816Ada code provided the @option{^-g^/DEBUG^} switch is used for
6817@command{gnatbind} and @command{gnatlink}.
6818
6819However for some purposes it may be convenient to generate the main
6820program in C rather than Ada. This may for example be helpful when you
6821are generating a mixed language program with the main program in C. The
6822GNAT compiler itself is an example.
6823The use of the @option{^-C^/BIND_FILE=C^} switch
6824for both @code{gnatbind} and @code{gnatlink} will cause the program to
6825be generated in C (and compiled using the gnu C compiler).
6826
6827
6828@node Switches for gnatbind
6829@section Switches for @command{gnatbind}
6830
6831@noindent
6832The following switches are available with @code{gnatbind}; details will
6833be presented in subsequent sections.
6834
6835@menu
6836* Consistency-Checking Modes::
6837* Binder Error Message Control::
6838* Elaboration Control::
6839* Output Control::
6840* Binding with Non-Ada Main Programs::
6841* Binding Programs with No Main Subprogram::
6842@end menu
6843
6844@table @option
6845@c !sort!
6846@item ^-aO^/OBJECT_SEARCH^
6847@cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6848Specify directory to be searched for ALI files.
6849
6850@item ^-aI^/SOURCE_SEARCH^
6851@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6852Specify directory to be searched for source file.
6853
6854@item ^-A^/BIND_FILE=ADA^
6855@cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6856Generate binder program in Ada (default)
6857
6858@item ^-b^/REPORT_ERRORS=BRIEF^
6859@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6860Generate brief messages to @file{stderr} even if verbose mode set.
6861
6862@item ^-c^/NOOUTPUT^
6863@cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6864Check only, no generation of binder output file.
6865
6866@item ^-C^/BIND_FILE=C^
6867@cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6868Generate binder program in C
6869
6870@item ^-e^/ELABORATION_DEPENDENCIES^
6871@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6872Output complete list of elaboration-order dependencies.
6873
6874@item ^-E^/STORE_TRACEBACKS^
6875@cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6876Store tracebacks in exception occurrences when the target supports it.
6877This is the default with the zero cost exception mechanism.
6878@ignore
6879@c The following may get moved to an appendix
6880This option is currently supported on the following targets:
6881all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6882@end ignore
6883See also the packages @code{GNAT.Traceback} and
6884@code{GNAT.Traceback.Symbolic} for more information.
6885@ifclear vms
6886Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6887@code{gcc} option.
6888@end ifclear vms
6889
6890@item ^-F^/FORCE_ELABS_FLAGS^
6891@cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6892Force the checks of elaboration flags. @command{gnatbind} does not normally
6893generate checks of elaboration flags for the main executable, except when
6894a Stand-Alone Library is used. However, there are cases when this cannot be
6895detected by gnatbind. An example is importing an interface of a Stand-Alone
6896Library through a pragma Import and only specifying through a linker switch
6897this Stand-Alone Library. This switch is used to guarantee that elaboration
6898flag checks are generated.
6899
6900@item ^-h^/HELP^
6901@cindex @option{^-h^/HELP^} (@command{gnatbind})
6902Output usage (help) information
6903
6904@item ^-I^/SEARCH^
6905@cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6906Specify directory to be searched for source and ALI files.
6907
6908@item ^-I-^/NOCURRENT_DIRECTORY^
6909@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6910Do not look for sources in the current directory where @code{gnatbind} was
6911invoked, and do not look for ALI files in the directory containing the
6912ALI file named in the @code{gnatbind} command line.
6913
6914@item ^-l^/ORDER_OF_ELABORATION^
6915@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
6916Output chosen elaboration order.
6917
6918@item ^-Lxxx^/BUILD_LIBRARY=xxx^
6919@cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
6920Binds the units for library building. In this case the adainit and
6921adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6922are renamed to ^xxxinit^XXXINIT^ and
6923^xxxfinal^XXXFINAL^.
6924Implies ^-n^/NOCOMPILE^.
6925@ifclear vms
6926(@pxref{GNAT and Libraries}, for more details.)
6927@end ifclear
6928@ifset vms
6929On OpenVMS, these init and final procedures are exported in uppercase
6930letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
6931the init procedure will be "TOTOINIT" and the exported name of the final
6932procedure will be "TOTOFINAL".
6933@end ifset
6934
6935@item ^-Mxyz^/RENAME_MAIN=xyz^
6936@cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
6937Rename generated main program from main to xyz
6938
6939@item ^-m^/ERROR_LIMIT=^@var{n}
6940@cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
6941Limit number of detected errors to @var{n}, where @var{n} is
6942in the range 1..999_999. The default value if no switch is
6943given is 9999. Binding is terminated if the limit is exceeded.
6944@ifset unw
6945Furthermore, under Windows, the sources pointed to by the libraries path
6946set in the registry are not searched for.
6947@end ifset
6948
6949@item ^-n^/NOMAIN^
6950@cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
6951No main program.
6952
6953@item -nostdinc
6954@cindex @option{-nostdinc} (@command{gnatbind})
6955Do not look for sources in the system default directory.
6956
6957@item -nostdlib
6958@cindex @option{-nostdlib} (@command{gnatbind})
6959Do not look for library files in the system default directory.
6960
6961@item --RTS=@var{rts-path}
6962@cindex @option{--RTS} (@code{gnatbind})
6963Specifies the default location of the runtime library. Same meaning as the
6964equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6965
6966@item ^-o ^/OUTPUT=^@var{file}
6967@cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
6968Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6969Note that if this option is used, then linking must be done manually,
6970gnatlink cannot be used.
6971
6972@item ^-O^/OBJECT_LIST^
6973@cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
6974Output object list.
6975
6976@item ^-p^/PESSIMISTIC_ELABORATION^
6977@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
6978Pessimistic (worst-case) elaboration order
6979
6980@item ^-s^/READ_SOURCES=ALL^
6981@cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
6982Require all source files to be present.
6983
6984@item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
6985@cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
6986Specifies the value to be used when detecting uninitialized scalar
6987objects with pragma Initialize_Scalars.
6988The @var{xxx} ^string specified with the switch^option^ may be either
6989@itemize @bullet
6990@item ``@option{^in^INVALID^}'' requesting an invalid value where possible
6991@item ``@option{^lo^LOW^}'' for the lowest possible value
6992possible, and the low
6993@item ``@option{^hi^HIGH^}'' for the highest possible value
6994@item ``@option{xx}'' for a value consisting of repeated bytes with the
6995value 16#xx# (i.e. xx is a string of two hexadecimal digits).
6996@end itemize
6997
6998In addition, you can specify @option{-Sev} to indicate that the value is
6999to be set at run time. In this case, the program will look for an environment
7000@cindex GNAT_INIT_SCALARS
7001variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7002of @option{in/lo/hi/xx} with the same meanings as above.
7003If no environment variable is found, or if it does not have a valid value,
7004then the default is @option{in} (invalid values).
7005
7006@ifclear vms
7007@item -static
7008@cindex @option{-static} (@code{gnatbind})
7009Link against a static GNAT run time.
7010
7011@item -shared
7012@cindex @option{-shared} (@code{gnatbind})
7013Link against a shared GNAT run time when available.
7014@end ifclear
7015
7016@item ^-t^/NOTIME_STAMP_CHECK^
7017@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7018Tolerate time stamp and other consistency errors
7019
7020@item ^-T@var{n}^/TIME_SLICE=@var{n}^
7021@cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7022Set the time slice value to @var{n} milliseconds. If the system supports
7023the specification of a specific time slice value, then the indicated value
7024is used. If the system does not support specific time slice values, but
7025does support some general notion of round-robin scheduling, then any
7026non-zero value will activate round-robin scheduling.
7027
7028A value of zero is treated specially. It turns off time
7029slicing, and in addition, indicates to the tasking run time that the
7030semantics should match as closely as possible the Annex D
7031requirements of the Ada RM, and in particular sets the default
7032scheduling policy to @code{FIFO_Within_Priorities}.
7033
7034@item ^-v^/REPORT_ERRORS=VERBOSE^
7035@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7036Verbose mode. Write error messages, header, summary output to
7037@file{stdout}.
7038
7039@ifclear vms
7040@item -w@var{x}
7041@cindex @option{-w} (@code{gnatbind})
7042Warning mode (@var{x}=s/e for suppress/treat as error)
7043@end ifclear
7044
7045@ifset vms
7046@item /WARNINGS=NORMAL
7047@cindex @option{/WARNINGS} (@code{gnatbind})
7048Normal warnings mode. Warnings are issued but ignored
7049
7050@item /WARNINGS=SUPPRESS
7051@cindex @option{/WARNINGS} (@code{gnatbind})
7052All warning messages are suppressed
7053
7054@item /WARNINGS=ERROR
7055@cindex @option{/WARNINGS} (@code{gnatbind})
7056Warning messages are treated as fatal errors
7057@end ifset
7058
7059@item ^-x^/READ_SOURCES=NONE^
7060@cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7061Exclude source files (check object consistency only).
7062
7063@ifset vms
7064@item /READ_SOURCES=AVAILABLE
7065@cindex @option{/READ_SOURCES} (@code{gnatbind})
7066Default mode, in which sources are checked for consistency only if
7067they are available.
7068@end ifset
7069
7070@item ^-z^/ZERO_MAIN^
7071@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7072No main subprogram.
7073@end table
7074
7075@ifclear vms
7076@noindent
7077You may obtain this listing of switches by running @code{gnatbind} with
7078no arguments.
7079@end ifclear
7080
7081
7082@node Consistency-Checking Modes
7083@subsection Consistency-Checking Modes
7084
7085@noindent
7086As described earlier, by default @code{gnatbind} checks
7087that object files are consistent with one another and are consistent
7088with any source files it can locate. The following switches control binder
7089access to sources.
7090
7091@table @option
7092@c !sort!
7093@item ^-s^/READ_SOURCES=ALL^
7094@cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7095Require source files to be present. In this mode, the binder must be
7096able to locate all source files that are referenced, in order to check
7097their consistency. In normal mode, if a source file cannot be located it
7098is simply ignored. If you specify this switch, a missing source
7099file is an error.
7100
7101@item ^-x^/READ_SOURCES=NONE^
7102@cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7103Exclude source files. In this mode, the binder only checks that ALI
7104files are consistent with one another. Source files are not accessed.
7105The binder runs faster in this mode, and there is still a guarantee that
7106the resulting program is self-consistent.
7107If a source file has been edited since it was last compiled, and you
7108specify this switch, the binder will not detect that the object
7109file is out of date with respect to the source file. Note that this is the
7110mode that is automatically used by @code{gnatmake} because in this
7111case the checking against sources has already been performed by
7112@code{gnatmake} in the course of compilation (i.e. before binding).
7113
7114@ifset vms
7115@item /READ_SOURCES=AVAILABLE
7116@cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7117This is the default mode in which source files are checked if they are
7118available, and ignored if they are not available.
7119@end ifset
7120@end table
7121
7122@node Binder Error Message Control
7123@subsection Binder Error Message Control
7124
7125@noindent
7126The following switches provide control over the generation of error
7127messages from the binder:
7128
7129@table @option
7130@c !sort!
7131@item ^-v^/REPORT_ERRORS=VERBOSE^
7132@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7133Verbose mode. In the normal mode, brief error messages are generated to
7134@file{stderr}. If this switch is present, a header is written
7135to @file{stdout} and any error messages are directed to @file{stdout}.
7136All that is written to @file{stderr} is a brief summary message.
7137
7138@item ^-b^/REPORT_ERRORS=BRIEF^
7139@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7140Generate brief error messages to @file{stderr} even if verbose mode is
7141specified. This is relevant only when used with the
7142@option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7143
7144@ifclear vms
7145@item -m@var{n}
7146@cindex @option{-m} (@code{gnatbind})
7147Limits the number of error messages to @var{n}, a decimal integer in the
7148range 1-999. The binder terminates immediately if this limit is reached.
7149
7150@item -M@var{xxx}
7151@cindex @option{-M} (@code{gnatbind})
7152Renames the generated main program from @code{main} to @code{xxx}.
7153This is useful in the case of some cross-building environments, where
7154the actual main program is separate from the one generated
7155by @code{gnatbind}.
7156@end ifclear
7157
7158@item ^-ws^/WARNINGS=SUPPRESS^
7159@cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7160@cindex Warnings
7161Suppress all warning messages.
7162
7163@item ^-we^/WARNINGS=ERROR^
7164@cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7165Treat any warning messages as fatal errors.
7166
7167@ifset vms
7168@item /WARNINGS=NORMAL
7169Standard mode with warnings generated, but warnings do not get treated
7170as errors.
7171@end ifset
7172
7173@item ^-t^/NOTIME_STAMP_CHECK^
7174@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7175@cindex Time stamp checks, in binder
7176@cindex Binder consistency checks
7177@cindex Consistency checks, in binder
7178The binder performs a number of consistency checks including:
7179
7180@itemize @bullet
7181@item
7182Check that time stamps of a given source unit are consistent
7183@item
7184Check that checksums of a given source unit are consistent
7185@item
7186Check that consistent versions of @code{GNAT} were used for compilation
7187@item
7188Check consistency of configuration pragmas as required
7189@end itemize
7190
7191@noindent
7192Normally failure of such checks, in accordance with the consistency
7193requirements of the Ada Reference Manual, causes error messages to be
7194generated which abort the binder and prevent the output of a binder
7195file and subsequent link to obtain an executable.
7196
7197The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7198into warnings, so that
7199binding and linking can continue to completion even in the presence of such
7200errors. The result may be a failed link (due to missing symbols), or a
7201non-functional executable which has undefined semantics.
7202@emph{This means that
7203@option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7204with extreme care.}
7205@end table
7206
7207@node Elaboration Control
7208@subsection Elaboration Control
7209
7210@noindent
7211The following switches provide additional control over the elaboration
7212order. For full details see @xref{Elaboration Order Handling in GNAT}.
7213
7214@table @option
7215@item ^-p^/PESSIMISTIC_ELABORATION^
7216@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7217Normally the binder attempts to choose an elaboration order that is
7218likely to minimize the likelihood of an elaboration order error resulting
7219in raising a @code{Program_Error} exception. This switch reverses the
7220action of the binder, and requests that it deliberately choose an order
7221that is likely to maximize the likelihood of an elaboration error.
7222This is useful in ensuring portability and avoiding dependence on
7223accidental fortuitous elaboration ordering.
7224
7225Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7226switch if dynamic
7227elaboration checking is used (@option{-gnatE} switch used for compilation).
7228This is because in the default static elaboration mode, all necessary
7229@code{Elaborate_All} pragmas are implicitly inserted.
7230These implicit pragmas are still respected by the binder in
7231@option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7232safe elaboration order is assured.
7233@end table
7234
7235@node Output Control
7236@subsection Output Control
7237
7238@noindent
7239The following switches allow additional control over the output
7240generated by the binder.
7241
7242@table @option
7243@c !sort!
7244
7245@item ^-A^/BIND_FILE=ADA^
7246@cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7247Generate binder program in Ada (default). The binder program is named
7248@file{b~@var{mainprog}.adb} by default. This can be changed with
7249@option{^-o^/OUTPUT^} @code{gnatbind} option.
7250
7251@item ^-c^/NOOUTPUT^
7252@cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7253Check only. Do not generate the binder output file. In this mode the
7254binder performs all error checks but does not generate an output file.
7255
7256@item ^-C^/BIND_FILE=C^
7257@cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7258Generate binder program in C. The binder program is named
7259@file{b_@var{mainprog}.c}.
7260This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7261option.
7262
7263@item ^-e^/ELABORATION_DEPENDENCIES^
7264@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7265Output complete list of elaboration-order dependencies, showing the
7266reason for each dependency. This output can be rather extensive but may
7267be useful in diagnosing problems with elaboration order. The output is
7268written to @file{stdout}.
7269
7270@item ^-h^/HELP^
7271@cindex @option{^-h^/HELP^} (@code{gnatbind})
7272Output usage information. The output is written to @file{stdout}.
7273
7274@item ^-K^/LINKER_OPTION_LIST^
7275@cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7276Output linker options to @file{stdout}. Includes library search paths,
7277contents of pragmas Ident and Linker_Options, and libraries added
7278by @code{gnatbind}.
7279
7280@item ^-l^/ORDER_OF_ELABORATION^
7281@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7282Output chosen elaboration order. The output is written to @file{stdout}.
7283
7284@item ^-O^/OBJECT_LIST^
7285@cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7286Output full names of all the object files that must be linked to provide
7287the Ada component of the program. The output is written to @file{stdout}.
7288This list includes the files explicitly supplied and referenced by the user
7289as well as implicitly referenced run-time unit files. The latter are
7290omitted if the corresponding units reside in shared libraries. The
7291directory names for the run-time units depend on the system configuration.
7292
7293@item ^-o ^/OUTPUT=^@var{file}
7294@cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7295Set name of output file to @var{file} instead of the normal
7296@file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7297binder generated body filename. In C mode you would normally give
7298@var{file} an extension of @file{.c} because it will be a C source program.
7299Note that if this option is used, then linking must be done manually.
7300It is not possible to use gnatlink in this case, since it cannot locate
7301the binder file.
7302
7303@item ^-r^/RESTRICTION_LIST^
7304@cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7305Generate list of @code{pragma Restrictions} that could be applied to
7306the current unit. This is useful for code audit purposes, and also may
7307be used to improve code generation in some cases.
7308
7309@end table
7310
7311@node Binding with Non-Ada Main Programs
7312@subsection Binding with Non-Ada Main Programs
7313
7314@noindent
7315In our description so far we have assumed that the main
7316program is in Ada, and that the task of the binder is to generate a
7317corresponding function @code{main} that invokes this Ada main
7318program. GNAT also supports the building of executable programs where
7319the main program is not in Ada, but some of the called routines are
7320written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7321The following switch is used in this situation:
7322
7323@table @option
7324@item ^-n^/NOMAIN^
7325@cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7326No main program. The main program is not in Ada.
7327@end table
7328
7329@noindent
7330In this case, most of the functions of the binder are still required,
7331but instead of generating a main program, the binder generates a file
7332containing the following callable routines:
7333
7334@table @code
7335@item adainit
7336@findex adainit
7337You must call this routine to initialize the Ada part of the program by
7338calling the necessary elaboration routines. A call to @code{adainit} is
7339required before the first call to an Ada subprogram.
7340
7341Note that it is assumed that the basic execution environment must be setup
7342to be appropriate for Ada execution at the point where the first Ada
7343subprogram is called. In particular, if the Ada code will do any
7344floating-point operations, then the FPU must be setup in an appropriate
7345manner. For the case of the x86, for example, full precision mode is
7346required. The procedure GNAT.Float_Control.Reset may be used to ensure
7347that the FPU is in the right state.
7348
7349@item adafinal
7350@findex adafinal
7351You must call this routine to perform any library-level finalization
7352required by the Ada subprograms. A call to @code{adafinal} is required
7353after the last call to an Ada subprogram, and before the program
7354terminates.
7355@end table
7356
7357@noindent
7358If the @option{^-n^/NOMAIN^} switch
7359@cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7360@cindex Binder, multiple input files
7361is given, more than one ALI file may appear on
7362the command line for @code{gnatbind}. The normal @dfn{closure}
7363calculation is performed for each of the specified units. Calculating
7364the closure means finding out the set of units involved by tracing
7365@code{with} references. The reason it is necessary to be able to
7366specify more than one ALI file is that a given program may invoke two or
7367more quite separate groups of Ada units.
7368
7369The binder takes the name of its output file from the last specified ALI
7370file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7371@cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7372The output is an Ada unit in source form that can
7373be compiled with GNAT unless the -C switch is used in which case the
7374output is a C source file, which must be compiled using the C compiler.
7375This compilation occurs automatically as part of the @code{gnatlink}
7376processing.
7377
7378Currently the GNAT run time requires a FPU using 80 bits mode
7379precision. Under targets where this is not the default it is required to
7380call GNAT.Float_Control.Reset before using floating point numbers (this
7381include float computation, float input and output) in the Ada code. A
7382side effect is that this could be the wrong mode for the foreign code
7383where floating point computation could be broken after this call.
7384
7385@node Binding Programs with No Main Subprogram
7386@subsection Binding Programs with No Main Subprogram
7387
7388@noindent
7389It is possible to have an Ada program which does not have a main
7390subprogram. This program will call the elaboration routines of all the
7391packages, then the finalization routines.
7392
7393The following switch is used to bind programs organized in this manner:
7394
7395@table @option
7396@item ^-z^/ZERO_MAIN^
7397@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7398Normally the binder checks that the unit name given on the command line
7399corresponds to a suitable main subprogram. When this switch is used,
7400a list of ALI files can be given, and the execution of the program
7401consists of elaboration of these units in an appropriate order.
7402@end table
7403
7404
7405@node Command-Line Access
7406@section Command-Line Access
7407
7408@noindent
7409The package @code{Ada.Command_Line} provides access to the command-line
7410arguments and program name. In order for this interface to operate
7411correctly, the two variables
7412
7413@smallexample
7414@group
7415int gnat_argc;
7416char **gnat_argv;
7417@end group
7418@end smallexample
7419
7420@noindent
7421@findex gnat_argv
7422@findex gnat_argc
7423are declared in one of the GNAT library routines. These variables must
7424be set from the actual @code{argc} and @code{argv} values passed to the
7425main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7426generates the C main program to automatically set these variables.
7427If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7428set these variables. If they are not set, the procedures in
7429@code{Ada.Command_Line} will not be available, and any attempt to use
7430them will raise @code{Constraint_Error}. If command line access is
7431required, your main program must set @code{gnat_argc} and
7432@code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7433it.
7434
7435
7436@node Search Paths for gnatbind
7437@section Search Paths for @code{gnatbind}
7438
7439@noindent
7440The binder takes the name of an ALI file as its argument and needs to
7441locate source files as well as other ALI files to verify object consistency.
7442
7443For source files, it follows exactly the same search rules as @code{gcc}
7444(@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7445directories searched are:
7446
7447@enumerate
7448@item
7449The directory containing the ALI file named in the command line, unless
7450the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7451
7452@item
7453All directories specified by @option{^-I^/SEARCH^}
7454switches on the @code{gnatbind}
7455command line, in the order given.
7456
7457@item
7458@findex ADA_OBJECTS_PATH
7459Each of the directories listed in the value of the
7460@code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7461@ifset unw
7462Construct this value
7463exactly as the @code{PATH} environment variable: a list of directory
7464names separated by colons (semicolons when working with the NT version
7465of GNAT).
7466@end ifset
7467@ifset vms
7468Normally, define this value as a logical name containing a comma separated
7469list of directory names.
7470
7471This variable can also be defined by means of an environment string
7472(an argument to the DEC C exec* set of functions).
7473
7474Logical Name:
7475@smallexample
7476DEFINE ANOTHER_PATH FOO:[BAG]
7477DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7478@end smallexample
7479
7480By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7481first, followed by the standard Ada 95
7482libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7483If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7484(Text_IO, Sequential_IO, etc)
7485instead of the Ada95 packages. Thus, in order to get the Ada 95
7486packages by default, ADA_OBJECTS_PATH must be redefined.
7487@end ifset
7488
7489@item
7490@findex ADA_PRJ_OBJECTS_FILE
7491Each of the directories listed in the text file whose name is given
7492by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7493
7494@noindent
7495@code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7496driver when project files are used. It should not normally be set
7497by other means.
7498
7499@item
7500The content of the @file{ada_object_path} file which is part of the GNAT
7501installation tree and is used to store standard libraries such as the
7502GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7503specified.
7504@ifclear vms
7505@ref{Installing an Ada Library}
7506@end ifclear
7507@end enumerate
7508
7509@noindent
7510In the binder the switch @option{^-I^/SEARCH^}
7511@cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7512is used to specify both source and
7513library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7514@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7515instead if you want to specify
7516source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7517@cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7518if you want to specify library paths
7519only. This means that for the binder
7520@option{^-I^/SEARCH=^}@var{dir} is equivalent to
7521@option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7522@option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7523The binder generates the bind file (a C language source file) in the
7524current working directory.
7525
7526@findex Ada
7527@findex System
7528@findex Interfaces
7529@findex GNAT
7530The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7531children make up the GNAT Run-Time Library, together with the package
7532GNAT and its children, which contain a set of useful additional
7533library functions provided by GNAT. The sources for these units are
7534needed by the compiler and are kept together in one directory. The ALI
7535files and object files generated by compiling the RTL are needed by the
7536binder and the linker and are kept together in one directory, typically
7537different from the directory containing the sources. In a normal
7538installation, you need not specify these directory names when compiling
7539or binding. Either the environment variables or the built-in defaults
7540cause these files to be found.
7541
7542Besides simplifying access to the RTL, a major use of search paths is
7543in compiling sources from multiple directories. This can make
7544development environments much more flexible.
7545
7546@node Examples of gnatbind Usage
7547@section Examples of @code{gnatbind} Usage
7548
7549@noindent
7550This section contains a number of examples of using the GNAT binding
7551utility @code{gnatbind}.
7552
7553@table @code
7554@item gnatbind hello
7555The main program @code{Hello} (source program in @file{hello.adb}) is
7556bound using the standard switch settings. The generated main program is
7557@file{b~hello.adb}. This is the normal, default use of the binder.
7558
7559@ifclear vms
7560@item gnatbind hello -o mainprog.adb
7561@end ifclear
7562@ifset vms
7563@item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7564@end ifset
7565The main program @code{Hello} (source program in @file{hello.adb}) is
7566bound using the standard switch settings. The generated main program is
7567@file{mainprog.adb} with the associated spec in
7568@file{mainprog.ads}. Note that you must specify the body here not the
7569spec, in the case where the output is in Ada. Note that if this option
7570is used, then linking must be done manually, since gnatlink will not
7571be able to find the generated file.
7572
7573@ifclear vms
7574@item gnatbind main -C -o mainprog.c -x
7575@end ifclear
7576@ifset vms
7577@item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7578@end ifset
7579The main program @code{Main} (source program in
7580@file{main.adb}) is bound, excluding source files from the
7581consistency checking, generating
7582the file @file{mainprog.c}.
7583
7584@ifclear vms
7585@item gnatbind -x main_program -C -o mainprog.c
7586This command is exactly the same as the previous example. Switches may
7587appear anywhere in the command line, and single letter switches may be
7588combined into a single switch.
7589@end ifclear
7590
7591@ifclear vms
7592@item gnatbind -n math dbase -C -o ada-control.c
7593@end ifclear
7594@ifset vms
7595@item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7596@end ifset
7597The main program is in a language other than Ada, but calls to
7598subprograms in packages @code{Math} and @code{Dbase} appear. This call
7599to @code{gnatbind} generates the file @file{ada-control.c} containing
7600the @code{adainit} and @code{adafinal} routines to be called before and
7601after accessing the Ada units.
7602@end table
7603
7604
7605@c ------------------------------------
7606@node Linking Using gnatlink
7607@chapter Linking Using @code{gnatlink}
7608@c ------------------------------------
7609@findex gnatlink
7610
7611@noindent
7612This chapter discusses @code{gnatlink}, a tool that links
7613an Ada program and builds an executable file. This utility
7614invokes the system linker ^(via the @code{gcc} command)^^
7615with a correct list of object files and library references.
7616@code{gnatlink} automatically determines the list of files and
7617references for the Ada part of a program. It uses the binder file
7618generated by the @command{gnatbind} to determine this list.
7619
7620@menu
7621* Running gnatlink::
7622* Switches for gnatlink::
7623* Setting Stack Size from gnatlink::
7624* Setting Heap Size from gnatlink::
7625@end menu
7626
7627@node Running gnatlink
7628@section Running @code{gnatlink}
7629
7630@noindent
7631The form of the @code{gnatlink} command is
7632
7633@smallexample
7634$ gnatlink [@var{switches}] @var{mainprog}[.ali]
7635           [@var{non-Ada objects}] [@var{linker options}]
7636@end smallexample
7637
7638@noindent
7639The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7640non-Ada objects
7641or linker options) may be in any order, provided that no non-Ada object may
7642be mistaken for a main @file{ALI} file.
7643Any file name @file{F} without the @file{.ali}
7644extension will be taken as the main @file{ALI} file if a file exists
7645whose name is the concatenation of @file{F} and @file{.ali}.
7646
7647@noindent
7648@file{@var{mainprog}.ali} references the ALI file of the main program.
7649The @file{.ali} extension of this file can be omitted. From this
7650reference, @code{gnatlink} locates the corresponding binder file
7651@file{b~@var{mainprog}.adb} and, using the information in this file along
7652with the list of non-Ada objects and linker options, constructs a
7653linker command file to create the executable.
7654
7655The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7656file are passed to the linker uninterpreted.
7657They typically include the names of
7658object files for units written in other languages than Ada and any library
7659references required to resolve references in any of these foreign language
7660units, or in @code{Import} pragmas in any Ada units.
7661
7662@var{linker options} is an optional list of linker specific
7663switches.
7664The default linker called by gnatlink is @var{gcc} which in
7665turn calls the appropriate system linker.
7666Standard options for the linker such as @option{-lmy_lib} or
7667@option{-Ldir} can be added as is.
7668For options that are not recognized by
7669@var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7670@option{-Wl,}.
7671Refer to the GCC documentation for
7672details. Here is an example showing how to generate a linker map:
7673
7674@ifclear vms
7675@smallexample
7676$ gnatlink my_prog -Wl,-Map,MAPFILE
7677@end smallexample
7678@end ifclear
7679
7680@ifset vms
7681<<Need example for VMS>>
7682@end ifset
7683
7684Using @var{linker options} it is possible to set the program stack and
7685heap size. See @ref{Setting Stack Size from gnatlink}, and
7686@ref{Setting Heap Size from gnatlink}.
7687
7688@code{gnatlink} determines the list of objects required by the Ada
7689program and prepends them to the list of objects passed to the linker.
7690@code{gnatlink} also gathers any arguments set by the use of
7691@code{pragma Linker_Options} and adds them to the list of arguments
7692presented to the linker.
7693
7694@ifset vms
7695@code{gnatlink} accepts the following types of extra files on the command
7696line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7697options files (.OPT). These are recognized and handled according to their
7698extension.
7699@end ifset
7700
7701@node Switches for gnatlink
7702@section Switches for @code{gnatlink}
7703
7704@noindent
7705The following switches are available with the @code{gnatlink} utility:
7706
7707@table @option
7708@c !sort!
7709
7710@item ^-A^/BIND_FILE=ADA^
7711@cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7712The binder has generated code in Ada. This is the default.
7713
7714@item ^-C^/BIND_FILE=C^
7715@cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7716If instead of generating a file in Ada, the binder has generated one in
7717C, then the linker needs to know about it. Use this switch to signal
7718to @code{gnatlink} that the binder has generated C code rather than
7719Ada code.
7720
7721@item ^-f^/FORCE_OBJECT_FILE_LIST^
7722@cindex Command line length
7723@cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7724On some targets, the command line length is limited, and @code{gnatlink}
7725will generate a separate file for the linker if the list of object files
7726is too long.
7727The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7728to be generated even if
7729the limit is not exceeded. This is useful in some cases to deal with
7730special situations where the command line length is exceeded.
7731
7732@item ^-g^/DEBUG^
7733@cindex Debugging information, including
7734@cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7735The option to include debugging information causes the Ada bind file (in
7736other words, @file{b~@var{mainprog}.adb}) to be compiled with
7737@option{^-g^/DEBUG^}.
7738In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7739@file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7740Without @option{^-g^/DEBUG^}, the binder removes these files by
7741default. The same procedure apply if a C bind file was generated using
7742@option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7743are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7744
7745@item ^-n^/NOCOMPILE^
7746@cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7747Do not compile the file generated by the binder. This may be used when
7748a link is rerun with different options, but there is no need to recompile
7749the binder file.
7750
7751@item ^-v^/VERBOSE^
7752@cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7753Causes additional information to be output, including a full list of the
7754included object files. This switch option is most useful when you want
7755to see what set of object files are being used in the link step.
7756
7757@item ^-v -v^/VERBOSE/VERBOSE^
7758@cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7759Very verbose mode. Requests that the compiler operate in verbose mode when
7760it compiles the binder file, and that the system linker run in verbose mode.
7761
7762@item ^-o ^/EXECUTABLE=^@var{exec-name}
7763@cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7764@var{exec-name} specifies an alternate name for the generated
7765executable program. If this switch is omitted, the executable has the same
7766name as the main unit. For example, @code{gnatlink try.ali} creates
7767an executable called @file{^try^TRY.EXE^}.
7768
7769@ifclear vms
7770@item -b @var{target}
7771@cindex @option{-b} (@code{gnatlink})
7772Compile your program to run on @var{target}, which is the name of a
7773system configuration. You must have a GNAT cross-compiler built if
7774@var{target} is not the same as your host system.
7775
7776@item -B@var{dir}
7777@cindex @option{-B} (@code{gnatlink})
7778Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7779from @var{dir} instead of the default location. Only use this switch
7780when multiple versions of the GNAT compiler are available. See the
7781@code{gcc} manual page for further details. You would normally use the
7782@option{-b} or @option{-V} switch instead.
7783
7784@item --GCC=@var{compiler_name}
7785@cindex @option{--GCC=compiler_name} (@code{gnatlink})
7786Program used for compiling the binder file. The default is
7787`@code{gcc}'. You need to use quotes around @var{compiler_name} if
7788@code{compiler_name} contains spaces or other separator characters. As
7789an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7790@code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7791inserted after your command name. Thus in the above example the compiler
7792command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7793If several @option{--GCC=compiler_name} are used, only the last
7794@var{compiler_name} is taken into account. However, all the additional
7795switches are also taken into account. Thus,
7796@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7797@option{--GCC="bar -x -y -z -t"}.
7798
7799@item --LINK=@var{name}
7800@cindex @option{--LINK=} (@code{gnatlink})
7801@var{name} is the name of the linker to be invoked. This is especially
7802useful in mixed language programs since languages such as C++ require
7803their own linker to be used. When this switch is omitted, the default
7804name for the linker is (@file{gcc}). When this switch is used, the
7805specified linker is called instead of (@file{gcc}) with exactly the same
7806parameters that would have been passed to (@file{gcc}) so if the desired
7807linker requires different parameters it is necessary to use a wrapper
7808script that massages the parameters before invoking the real linker. It
7809may be useful to control the exact invocation by using the verbose
7810switch.
7811
7812@end ifclear
7813
7814@ifset vms
7815@item /DEBUG=TRACEBACK
7816@cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7817This qualifier causes sufficient information to be included in the
7818executable file to allow a traceback, but does not include the full
7819symbol information needed by the debugger.
7820
7821@item /IDENTIFICATION="<string>"
7822@code{"<string>"} specifies the string to be stored in the image file
7823identification field in the image header.
7824It overrides any pragma @code{Ident} specified string.
7825
7826@item /NOINHIBIT-EXEC
7827Generate the executable file even if there are linker warnings.
7828
7829@item /NOSTART_FILES
7830Don't link in the object file containing the ``main'' transfer address.
7831Used when linking with a foreign language main program compiled with a
7832Digital compiler.
7833
7834@item /STATIC
7835Prefer linking with object libraries over sharable images, even without
7836/DEBUG.
7837@end ifset
7838
7839@end table
7840
7841@node Setting Stack Size from gnatlink
7842@section Setting Stack Size from @code{gnatlink}
7843
7844@noindent
7845Under Windows systems, it is possible to specify the program stack size from
7846@code{gnatlink} using either:
7847
7848@itemize @bullet
7849
7850@item using @option{-Xlinker} linker option
7851
7852@smallexample
7853$ gnatlink hello -Xlinker --stack=0x10000,0x1000
7854@end smallexample
7855
7856This sets the stack reserve size to 0x10000 bytes and the stack commit
7857size to 0x1000 bytes.
7858
7859@item using @option{-Wl} linker option
7860
7861@smallexample
7862$ gnatlink hello -Wl,--stack=0x1000000
7863@end smallexample
7864
7865This sets the stack reserve size to 0x1000000 bytes. Note that with
7866@option{-Wl} option it is not possible to set the stack commit size
7867because the coma is a separator for this option.
7868
7869@end itemize
7870
7871@node Setting Heap Size from gnatlink
7872@section Setting Heap Size from @code{gnatlink}
7873
7874@noindent
7875Under Windows systems, it is possible to specify the program heap size from
7876@code{gnatlink} using either:
7877
7878@itemize @bullet
7879
7880@item using @option{-Xlinker} linker option
7881
7882@smallexample
7883$ gnatlink hello -Xlinker --heap=0x10000,0x1000
7884@end smallexample
7885
7886This sets the heap reserve size to 0x10000 bytes and the heap commit
7887size to 0x1000 bytes.
7888
7889@item using @option{-Wl} linker option
7890
7891@smallexample
7892$ gnatlink hello -Wl,--heap=0x1000000
7893@end smallexample
7894
7895This sets the heap reserve size to 0x1000000 bytes. Note that with
7896@option{-Wl} option it is not possible to set the heap commit size
7897because the coma is a separator for this option.
7898
7899@end itemize
7900
7901@node The GNAT Make Program gnatmake
7902@chapter The GNAT Make Program @code{gnatmake}
7903@findex gnatmake
7904
7905@menu
7906* Running gnatmake::
7907* Switches for gnatmake::
7908* Mode Switches for gnatmake::
7909* Notes on the Command Line::
7910* How gnatmake Works::
7911* Examples of gnatmake Usage::
7912@end menu
7913@noindent
7914A typical development cycle when working on an Ada program consists of
7915the following steps:
7916
7917@enumerate
7918@item
7919Edit some sources to fix bugs.
7920
7921@item
7922Add enhancements.
7923
7924@item
7925Compile all sources affected.
7926
7927@item
7928Rebind and relink.
7929
7930@item
7931Test.
7932@end enumerate
7933
7934@noindent
7935The third step can be tricky, because not only do the modified files
7936@cindex Dependency rules
7937have to be compiled, but any files depending on these files must also be
7938recompiled. The dependency rules in Ada can be quite complex, especially
7939in the presence of overloading, @code{use} clauses, generics and inlined
7940subprograms.
7941
7942@code{gnatmake} automatically takes care of the third and fourth steps
7943of this process. It determines which sources need to be compiled,
7944compiles them, and binds and links the resulting object files.
7945
7946Unlike some other Ada make programs, the dependencies are always
7947accurately recomputed from the new sources. The source based approach of
7948the GNAT compilation model makes this possible. This means that if
7949changes to the source program cause corresponding changes in
7950dependencies, they will always be tracked exactly correctly by
7951@code{gnatmake}.
7952
7953@node Running gnatmake
7954@section Running @code{gnatmake}
7955
7956@noindent
7957The usual form of the @code{gnatmake} command is
7958
7959@smallexample
7960$ gnatmake [@var{switches}] @var{file_name}
7961      [@var{file_names}] [@var{mode_switches}]
7962@end smallexample
7963
7964@noindent
7965The only required argument is one @var{file_name}, which specifies
7966a compilation unit that is a main program. Several @var{file_names} can be
7967specified: this will result in several executables being built.
7968If @code{switches} are present, they can be placed before the first
7969@var{file_name}, between @var{file_names} or after the last @var{file_name}.
7970If @var{mode_switches} are present, they must always be placed after
7971the last @var{file_name} and all @code{switches}.
7972
7973If you are using standard file extensions (.adb and .ads), then the
7974extension may be omitted from the @var{file_name} arguments. However, if
7975you are using non-standard extensions, then it is required that the
7976extension be given. A relative or absolute directory path can be
7977specified in a @var{file_name}, in which case, the input source file will
7978be searched for in the specified directory only. Otherwise, the input
7979source file will first be searched in the directory where
7980@code{gnatmake} was invoked and if it is not found, it will be search on
7981the source path of the compiler as described in
7982@ref{Search Paths and the Run-Time Library (RTL)}.
7983
7984All @code{gnatmake} output (except when you specify
7985@option{^-M^/DEPENDENCIES_LIST^}) is to
7986@file{stderr}. The output produced by the
7987@option{^-M^/DEPENDENCIES_LIST^} switch is send to
7988@file{stdout}.
7989
7990@node Switches for gnatmake
7991@section Switches for @code{gnatmake}
7992
7993@noindent
7994You may specify any of the following switches to @code{gnatmake}:
7995
7996@table @option
7997@c !sort!
7998@ifclear vms
7999@item --GCC=@var{compiler_name}
8000@cindex @option{--GCC=compiler_name} (@code{gnatmake})
8001Program used for compiling. The default is `@code{gcc}'. You need to use
8002quotes around @var{compiler_name} if @code{compiler_name} contains
8003spaces or other separator characters. As an example @option{--GCC="foo -x
8004-y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8005compiler. Note that switch @option{-c} is always inserted after your
8006command name. Thus in the above example the compiler command that will
8007be used by @code{gnatmake} will be @code{foo -c -x -y}.
8008If several @option{--GCC=compiler_name} are used, only the last
8009@var{compiler_name} is taken into account. However, all the additional
8010switches are also taken into account. Thus,
8011@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8012@option{--GCC="bar -x -y -z -t"}.
8013
8014@item --GNATBIND=@var{binder_name}
8015@cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8016Program used for binding. The default is `@code{gnatbind}'. You need to
8017use quotes around @var{binder_name} if @var{binder_name} contains spaces
8018or other separator characters. As an example @option{--GNATBIND="bar -x
8019-y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8020binder. Binder switches that are normally appended by @code{gnatmake} to
8021`@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8022
8023@item --GNATLINK=@var{linker_name}
8024@cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8025Program used for linking. The default is `@code{gnatlink}'. You need to
8026use quotes around @var{linker_name} if @var{linker_name} contains spaces
8027or other separator characters. As an example @option{--GNATLINK="lan -x
8028-y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8029linker. Linker switches that are normally appended by @code{gnatmake} to
8030`@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8031
8032@end ifclear
8033
8034@item ^-a^/ALL_FILES^
8035@cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8036Consider all files in the make process, even the GNAT internal system
8037files (for example, the predefined Ada library files), as well as any
8038locked files. Locked files are files whose ALI file is write-protected.
8039By default,
8040@code{gnatmake} does not check these files,
8041because the assumption is that the GNAT internal files are properly up
8042to date, and also that any write protected ALI files have been properly
8043installed. Note that if there is an installation problem, such that one
8044of these files is not up to date, it will be properly caught by the
8045binder.
8046You may have to specify this switch if you are working on GNAT
8047itself. The switch @option{^-a^/ALL_FILES^} is also useful
8048in conjunction with @option{^-f^/FORCE_COMPILE^}
8049if you need to recompile an entire application,
8050including run-time files, using special configuration pragmas,
8051such as a @code{Normalize_Scalars} pragma.
8052
8053By default
8054@code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8055internal files with
8056@ifclear vms
8057@code{gcc -c -gnatpg} rather than @code{gcc -c}.
8058@end ifclear
8059@ifset vms
8060the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8061@end ifset
8062
8063@item ^-b^/ACTIONS=BIND^
8064@cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8065Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8066compilation and binding, but no link.
8067Can be combined with @option{^-l^/ACTIONS=LINK^}
8068to do binding and linking. When not combined with
8069@option{^-c^/ACTIONS=COMPILE^}
8070all the units in the closure of the main program must have been previously
8071compiled and must be up to date. The root unit specified by @var{file_name}
8072may be given without extension, with the source extension or, if no GNAT
8073Project File is specified, with the ALI file extension.
8074
8075@item ^-c^/ACTIONS=COMPILE^
8076@cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8077Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8078is also specified. Do not perform linking, except if both
8079@option{^-b^/ACTIONS=BIND^} and
8080 @option{^-l^/ACTIONS=LINK^} are also specified.
8081If the root unit specified by @var{file_name} is not a main unit, this is the
8082default. Otherwise @code{gnatmake} will attempt binding and linking
8083unless all objects are up to date and the executable is more recent than
8084the objects.
8085
8086@item ^-C^/MAPPING^
8087@cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8088Use a temporary mapping file. A mapping file is a way to communicate to the
8089compiler two mappings: from unit names to file names (without any directory
8090information) and from file names to path names (with full directory
8091information). These mappings are used by the compiler to short-circuit the path
8092search. When @code{gnatmake} is invoked with this switch, it will create
8093a temporary mapping file, initially populated by the project manager,
8094if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8095Each invocation of the compiler will add the newly accessed sources to the
8096mapping file. This will improve the source search during the next invocation
8097of the compiler.
8098
8099@item ^-C=^/USE_MAPPING_FILE=^@var{file}
8100@cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8101Use a specific mapping file. The file, specified as a path name (absolute or
8102relative) by this switch, should already exist, otherwise the switch is
8103ineffective. The specified mapping file will be communicated to the compiler.
8104This switch is not compatible with a project file
8105(^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8106(^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8107
8108@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8109@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8110Put all object files and ALI file in directory @var{dir}.
8111If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8112and ALI files go in the current working directory.
8113
8114This switch cannot be used when using a project file.
8115
8116@item ^-f^/FORCE_COMPILE^
8117@cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8118Force recompilations. Recompile all sources, even though some object
8119files may be up to date, but don't recompile predefined or GNAT internal
8120files or locked files (files with a write-protected ALI file),
8121unless the @option{^-a^/ALL_FILES^} switch is also specified.
8122
8123@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8124@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8125When using project files, if some errors or warnings are detected during
8126parsing and verbose mode is not in effect (no use of switch
8127^-v^/VERBOSE^), then error lines start with the full path name of the project
8128file, rather than its simple file name.
8129
8130@item ^-i^/IN_PLACE^
8131@cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8132In normal mode, @code{gnatmake} compiles all object files and ALI files
8133into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8134then instead object files and ALI files that already exist are overwritten
8135in place. This means that once a large project is organized into separate
8136directories in the desired manner, then @code{gnatmake} will automatically
8137maintain and update this organization. If no ALI files are found on the
8138Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8139the new object and ALI files are created in the
8140directory containing the source being compiled. If another organization
8141is desired, where objects and sources are kept in different directories,
8142a useful technique is to create dummy ALI files in the desired directories.
8143When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8144the corresponding source file, and it will be put the resulting object
8145and ALI files in the directory where it found the dummy file.
8146
8147@item ^-j^/PROCESSES=^@var{n}
8148@cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8149@cindex Parallel make
8150Use @var{n} processes to carry out the (re)compilations. On a
8151multiprocessor machine compilations will occur in parallel. In the
8152event of compilation errors, messages from various compilations might
8153get interspersed (but @code{gnatmake} will give you the full ordered
8154list of failing compiles at the end). If this is problematic, rerun
8155the make process with n set to 1 to get a clean list of messages.
8156
8157@item ^-k^/CONTINUE_ON_ERROR^
8158@cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8159Keep going. Continue as much as possible after a compilation error. To
8160ease the programmer's task in case of compilation errors, the list of
8161sources for which the compile fails is given when @code{gnatmake}
8162terminates.
8163
8164If @code{gnatmake} is invoked with several @file{file_names} and with this
8165switch, if there are compilation errors when building an executable,
8166@code{gnatmake} will not attempt to build the following executables.
8167
8168@item ^-l^/ACTIONS=LINK^
8169@cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8170Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8171and linking. Linking will not be performed if combined with
8172@option{^-c^/ACTIONS=COMPILE^}
8173but not with @option{^-b^/ACTIONS=BIND^}.
8174When not combined with @option{^-b^/ACTIONS=BIND^}
8175all the units in the closure of the main program must have been previously
8176compiled and must be up to date, and the main program need to have been bound.
8177The root unit specified by @var{file_name}
8178may be given without extension, with the source extension or, if no GNAT
8179Project File is specified, with the ALI file extension.
8180
8181@item ^-m^/MINIMAL_RECOMPILATION^
8182@cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8183Specifies that the minimum necessary amount of recompilations
8184be performed. In this mode @code{gnatmake} ignores time
8185stamp differences when the only
8186modifications to a source file consist in adding/removing comments,
8187empty lines, spaces or tabs. This means that if you have changed the
8188comments in a source file or have simply reformatted it, using this
8189switch will tell gnatmake not to recompile files that depend on it
8190(provided other sources on which these files depend have undergone no
8191semantic modifications). Note that the debugging information may be
8192out of date with respect to the sources if the @option{-m} switch causes
8193a compilation to be switched, so the use of this switch represents a
8194trade-off between compilation time and accurate debugging information.
8195
8196@item ^-M^/DEPENDENCIES_LIST^
8197@cindex Dependencies, producing list
8198@cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8199Check if all objects are up to date. If they are, output the object
8200dependences to @file{stdout} in a form that can be directly exploited in
8201a @file{Makefile}. By default, each source file is prefixed with its
8202(relative or absolute) directory name. This name is whatever you
8203specified in the various @option{^-aI^/SOURCE_SEARCH^}
8204and @option{^-I^/SEARCH^} switches. If you use
8205@code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8206@option{^-q^/QUIET^}
8207(see below), only the source file names,
8208without relative paths, are output. If you just specify the
8209@option{^-M^/DEPENDENCIES_LIST^}
8210switch, dependencies of the GNAT internal system files are omitted. This
8211is typically what you want. If you also specify
8212the @option{^-a^/ALL_FILES^} switch,
8213dependencies of the GNAT internal files are also listed. Note that
8214dependencies of the objects in external Ada libraries (see switch
8215@option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8216are never reported.
8217
8218@item ^-n^/DO_OBJECT_CHECK^
8219@cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8220Don't compile, bind, or link. Checks if all objects are up to date.
8221If they are not, the full name of the first file that needs to be
8222recompiled is printed.
8223Repeated use of this option, followed by compiling the indicated source
8224file, will eventually result in recompiling all required units.
8225
8226@item ^-o ^/EXECUTABLE=^@var{exec_name}
8227@cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8228Output executable name. The name of the final executable program will be
8229@var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8230name for the executable will be the name of the input file in appropriate form
8231for an executable file on the host system.
8232
8233This switch cannot be used when invoking @code{gnatmake} with several
8234@file{file_names}.
8235
8236@item ^-P^/PROJECT_FILE=^@var{project}
8237@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8238Use project file @var{project}. Only one such switch can be used.
8239See @ref{gnatmake and Project Files}.
8240
8241@item ^-q^/QUIET^
8242@cindex @option{^-q^/QUIET^} (@code{gnatmake})
8243Quiet. When this flag is not set, the commands carried out by
8244@code{gnatmake} are displayed.
8245
8246@item ^-s^/SWITCH_CHECK/^
8247@cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8248Recompile if compiler switches have changed since last compilation.
8249All compiler switches but -I and -o are taken into account in the
8250following way:
8251orders between different ``first letter'' switches are ignored, but
8252orders between same switches are taken into account. For example,
8253@option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8254is equivalent to @option{-O -g}.
8255
8256This switch is recommended when Integrated Preprocessing is used.
8257
8258@item ^-u^/UNIQUE^
8259@cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8260Unique. Recompile at most the main files. It implies -c. Combined with
8261-f, it is equivalent to calling the compiler directly. Note that using
8262^-u^/UNIQUE^ with a project file and no main has a special meaning
8263(see @ref{Project Files and Main Subprograms}).
8264
8265@item ^-U^/ALL_PROJECTS^
8266@cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8267When used without a project file or with one or several mains on the command
8268line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8269on the command line, all sources of all project files are checked and compiled
8270if not up to date, and libraries are rebuilt, if necessary.
8271
8272@item ^-v^/REASONS^
8273@cindex @option{^-v^/REASONS^} (@code{gnatmake})
8274Verbose. Displays the reason for all recompilations @code{gnatmake}
8275decides are necessary.
8276
8277@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8278Indicates the verbosity of the parsing of GNAT project files.
8279See @ref{Switches Related to Project Files}.
8280
8281@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8282Indicates that external variable @var{name} has the value @var{value}.
8283The Project Manager will use this value for occurrences of
8284@code{external(name)} when parsing the project file.
8285See @ref{Switches Related to Project Files}.
8286
8287@item ^-z^/NOMAIN^
8288@cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8289No main subprogram. Bind and link the program even if the unit name
8290given on the command line is a package name. The resulting executable
8291will execute the elaboration routines of the package and its closure,
8292then the finalization routines.
8293
8294@item ^-g^/DEBUG^
8295@cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8296Enable debugging. This switch is simply passed to the compiler and to the
8297linker.
8298
8299@end table
8300
8301@table @asis
8302@item @code{gcc} @asis{switches}
8303@ifclear vms
8304Any uppercase switch (other than @option{-A},
8305@option{-L} or
8306@option{-S}) or any switch that is more than one character is passed to
8307@code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8308@end ifclear
8309@ifset vms
8310Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8311but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8312automatically treated as a compiler switch, and passed on to all
8313compilations that are carried out.
8314@end ifset
8315@end table
8316
8317@noindent
8318Source and library search path switches:
8319
8320@table @option
8321@c !sort!
8322@item ^-aI^/SOURCE_SEARCH=^@var{dir}
8323@cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8324When looking for source files also look in directory @var{dir}.
8325The order in which source files search is undertaken is
8326described in @ref{Search Paths and the Run-Time Library (RTL)}.
8327
8328@item ^-aL^/SKIP_MISSING=^@var{dir}
8329@cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8330Consider @var{dir} as being an externally provided Ada library.
8331Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8332files have been located in directory @var{dir}. This allows you to have
8333missing bodies for the units in @var{dir} and to ignore out of date bodies
8334for the same units. You still need to specify
8335the location of the specs for these units by using the switches
8336@option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8337or @option{^-I^/SEARCH=^@var{dir}}.
8338Note: this switch is provided for compatibility with previous versions
8339of @code{gnatmake}. The easier method of causing standard libraries
8340to be excluded from consideration is to write-protect the corresponding
8341ALI files.
8342
8343@item ^-aO^/OBJECT_SEARCH=^@var{dir}
8344@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8345When searching for library and object files, look in directory
8346@var{dir}. The order in which library files are searched is described in
8347@ref{Search Paths for gnatbind}.
8348
8349@item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8350@cindex Search paths, for @code{gnatmake}
8351@cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8352Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8353^-aI^/SOURCE_SEARCH=^@var{dir}}.
8354
8355@item ^-I^/SEARCH=^@var{dir}
8356@cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8357Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8358^-aI^/SOURCE_SEARCH=^@var{dir}}.
8359
8360@item ^-I-^/NOCURRENT_DIRECTORY^
8361@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8362@cindex Source files, suppressing search
8363Do not look for source files in the directory containing the source
8364file named in the command line.
8365Do not look for ALI or object files in the directory
8366where @code{gnatmake} was invoked.
8367
8368@item ^-L^/LIBRARY_SEARCH=^@var{dir}
8369@cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8370@cindex Linker libraries
8371Add directory @var{dir} to the list of directories in which the linker
8372will search for libraries. This is equivalent to
8373@option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8374@ifclear vms
8375Furthermore, under Windows, the sources pointed to by the libraries path
8376set in the registry are not searched for.
8377@end ifclear
8378
8379@item -nostdinc
8380@cindex @option{-nostdinc} (@code{gnatmake})
8381Do not look for source files in the system default directory.
8382
8383@item -nostdlib
8384@cindex @option{-nostdlib} (@code{gnatmake})
8385Do not look for library files in the system default directory.
8386
8387@item --RTS=@var{rts-path}
8388@cindex @option{--RTS} (@code{gnatmake})
8389Specifies the default location of the runtime library. GNAT looks for the
8390runtime
8391in the following directories, and stops as soon as a valid runtime is found
8392(@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8393@file{ada_object_path} present):
8394
8395@itemize @bullet
8396@item <current directory>/$rts_path
8397
8398@item <default-search-dir>/$rts_path
8399
8400@item <default-search-dir>/rts-$rts_path
8401@end itemize
8402
8403@noindent
8404The selected path is handled like a normal RTS path.
8405
8406@end table
8407
8408@node Mode Switches for gnatmake
8409@section Mode Switches for @code{gnatmake}
8410
8411@noindent
8412The mode switches (referred to as @code{mode_switches}) allow the
8413inclusion of switches that are to be passed to the compiler itself, the
8414binder or the linker. The effect of a mode switch is to cause all
8415subsequent switches up to the end of the switch list, or up to the next
8416mode switch, to be interpreted as switches to be passed on to the
8417designated component of GNAT.
8418
8419@table @option
8420@c !sort!
8421@item -cargs @var{switches}
8422@cindex @option{-cargs} (@code{gnatmake})
8423Compiler switches. Here @var{switches} is a list of switches
8424that are valid switches for @code{gcc}. They will be passed on to
8425all compile steps performed by @code{gnatmake}.
8426
8427@item -bargs @var{switches}
8428@cindex @option{-bargs} (@code{gnatmake})
8429Binder switches. Here @var{switches} is a list of switches
8430that are valid switches for @code{gnatbind}. They will be passed on to
8431all bind steps performed by @code{gnatmake}.
8432
8433@item -largs @var{switches}
8434@cindex @option{-largs} (@code{gnatmake})
8435Linker switches. Here @var{switches} is a list of switches
8436that are valid switches for @code{gnatlink}. They will be passed on to
8437all link steps performed by @code{gnatmake}.
8438
8439@item -margs @var{switches}
8440@cindex @option{-margs} (@code{gnatmake})
8441Make switches. The switches are directly interpreted by @code{gnatmake},
8442regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8443or @option{-largs}.
8444@end table
8445
8446@node Notes on the Command Line
8447@section Notes on the Command Line
8448
8449@noindent
8450This section contains some additional useful notes on the operation
8451of the @code{gnatmake} command.
8452
8453@itemize @bullet
8454@item
8455@cindex Recompilation, by @code{gnatmake}
8456If @code{gnatmake} finds no ALI files, it recompiles the main program
8457and all other units required by the main program.
8458This means that @code{gnatmake}
8459can be used for the initial compile, as well as during subsequent steps of
8460the development cycle.
8461
8462@item
8463If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8464is a subunit or body of a generic unit, @code{gnatmake} recompiles
8465@file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8466warning.
8467
8468@item
8469In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8470is used to specify both source and
8471library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8472instead if you just want to specify
8473source paths only and @option{^-aO^/OBJECT_SEARCH^}
8474if you want to specify library paths
8475only.
8476
8477@item
8478@code{gnatmake} examines both an ALI file and its corresponding object file
8479for consistency. If an ALI is more recent than its corresponding object,
8480or if the object file is missing, the corresponding source will be recompiled.
8481Note that @code{gnatmake} expects an ALI and the corresponding object file
8482to be in the same directory.
8483
8484@item
8485@code{gnatmake} will ignore any files whose ALI file is write-protected.
8486This may conveniently be used to exclude standard libraries from
8487consideration and in particular it means that the use of the
8488@option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8489unless @option{^-a^/ALL_FILES^} is also specified.
8490
8491@item
8492@code{gnatmake} has been designed to make the use of Ada libraries
8493particularly convenient. Assume you have an Ada library organized
8494as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8495of your Ada compilation units,
8496whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8497specs of these units, but no bodies. Then to compile a unit
8498stored in @code{main.adb}, which uses this Ada library you would just type
8499
8500@smallexample
8501@ifclear vms
8502$ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8503@end ifclear
8504@ifset vms
8505$ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8506           /SKIP_MISSING=@i{[OBJ_DIR]} main
8507@end ifset
8508@end smallexample
8509
8510@item
8511Using @code{gnatmake} along with the
8512@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8513switch provides a mechanism for avoiding unnecessary rcompilations. Using
8514this switch,
8515you can update the comments/format of your
8516source files without having to recompile everything. Note, however, that
8517adding or deleting lines in a source files may render its debugging
8518info obsolete. If the file in question is a spec, the impact is rather
8519limited, as that debugging info will only be useful during the
8520elaboration phase of your program. For bodies the impact can be more
8521significant. In all events, your debugger will warn you if a source file
8522is more recent than the corresponding object, and alert you to the fact
8523that the debugging information may be out of date.
8524@end itemize
8525
8526@node How gnatmake Works
8527@section How @code{gnatmake} Works
8528
8529@noindent
8530Generally @code{gnatmake} automatically performs all necessary
8531recompilations and you don't need to worry about how it works. However,
8532it may be useful to have some basic understanding of the @code{gnatmake}
8533approach and in particular to understand how it uses the results of
8534previous compilations without incorrectly depending on them.
8535
8536First a definition: an object file is considered @dfn{up to date} if the
8537corresponding ALI file exists and its time stamp predates that of the
8538object file and if all the source files listed in the
8539dependency section of this ALI file have time stamps matching those in
8540the ALI file. This means that neither the source file itself nor any
8541files that it depends on have been modified, and hence there is no need
8542to recompile this file.
8543
8544@code{gnatmake} works by first checking if the specified main unit is up
8545to date. If so, no compilations are required for the main unit. If not,
8546@code{gnatmake} compiles the main program to build a new ALI file that
8547reflects the latest sources. Then the ALI file of the main unit is
8548examined to find all the source files on which the main program depends,
8549and @code{gnatmake} recursively applies the above procedure on all these files.
8550
8551This process ensures that @code{gnatmake} only trusts the dependencies
8552in an existing ALI file if they are known to be correct. Otherwise it
8553always recompiles to determine a new, guaranteed accurate set of
8554dependencies. As a result the program is compiled ``upside down'' from what may
8555be more familiar as the required order of compilation in some other Ada
8556systems. In particular, clients are compiled before the units on which
8557they depend. The ability of GNAT to compile in any order is critical in
8558allowing an order of compilation to be chosen that guarantees that
8559@code{gnatmake} will recompute a correct set of new dependencies if
8560necessary.
8561
8562When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8563imported by several of the executables, it will be recompiled at most once.
8564
8565Note: when using non-standard naming conventions
8566(See @ref{Using Other File Names}), changing through a configuration pragmas
8567file the version of a source and invoking @code{gnatmake} to recompile may
8568have no effect, if the previous version of the source is still accessible
8569by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8570
8571@node Examples of gnatmake Usage
8572@section Examples of @code{gnatmake} Usage
8573
8574@table @code
8575@item gnatmake hello.adb
8576Compile all files necessary to bind and link the main program
8577@file{hello.adb} (containing unit @code{Hello}) and bind and link the
8578resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8579
8580@item gnatmake main1 main2 main3
8581Compile all files necessary to bind and link the main programs
8582@file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8583(containing unit @code{Main2}) and @file{main3.adb}
8584(containing unit @code{Main3}) and bind and link the resulting object files
8585to generate three executable files @file{^main1^MAIN1.EXE^},
8586@file{^main2^MAIN2.EXE^}
8587and @file{^main3^MAIN3.EXE^}.
8588
8589@ifclear vms
8590@item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8591@end ifclear
8592
8593@ifset vms
8594@item gnatmake Main_Unit /QUIET
8595   /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8596   /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8597@end ifset
8598Compile all files necessary to bind and link the main program unit
8599@code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8600be done with optimization level 2 and the order of elaboration will be
8601listed by the binder. @code{gnatmake} will operate in quiet mode, not
8602displaying commands it is executing.
8603@end table
8604
8605
8606@c *************************
8607@node Improving Performance
8608@chapter Improving Performance
8609@cindex Improving performance
8610
8611@noindent
8612This chapter presents several topics related to program performance.
8613It first describes some of the tradeoffs that need to be considered
8614and some of the techniques for making your program run faster.
8615It then documents the @command{gnatelim} tool, which can reduce
8616the size of program executables.
8617
8618@ifnottex
8619@menu
8620* Performance Considerations::
8621* Reducing the Size of Ada Executables with gnatelim::
8622@end menu
8623@end ifnottex
8624
8625
8626@c *****************************
8627@node Performance Considerations
8628@section Performance Considerations
8629
8630@noindent
8631The GNAT system provides a number of options that allow a trade-off
8632between
8633
8634@itemize @bullet
8635@item
8636performance of the generated code
8637
8638@item
8639speed of compilation
8640
8641@item
8642minimization of dependences and recompilation
8643
8644@item
8645the degree of run-time checking.
8646@end itemize
8647
8648@noindent
8649The defaults (if no options are selected) aim at improving the speed
8650of compilation and minimizing dependences, at the expense of performance
8651of the generated code:
8652
8653@itemize @bullet
8654@item
8655no optimization
8656
8657@item
8658no inlining of subprogram calls
8659
8660@item
8661all run-time checks enabled except overflow and elaboration checks
8662@end itemize
8663
8664@noindent
8665These options are suitable for most program development purposes. This
8666chapter describes how you can modify these choices, and also provides
8667some guidelines on debugging optimized code.
8668
8669@menu
8670* Controlling Run-Time Checks::
8671* Use of Restrictions::
8672* Optimization Levels::
8673* Debugging Optimized Code::
8674* Inlining of Subprograms::
8675@ifset vms
8676* Coverage Analysis::
8677@end ifset
8678@end menu
8679
8680@node Controlling Run-Time Checks
8681@subsection Controlling Run-Time Checks
8682
8683@noindent
8684By default, GNAT generates all run-time checks, except arithmetic overflow
8685checking for integer operations and checks for access before elaboration on
8686subprogram calls. The latter are not required in default mode, because all
8687necessary checking is done at compile time.
8688@cindex @option{-gnatp} (@code{gcc})
8689@cindex @option{-gnato} (@code{gcc})
8690Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8691be modified. @xref{Run-Time Checks}.
8692
8693Our experience is that the default is suitable for most development
8694purposes.
8695
8696We treat integer overflow specially because these
8697are quite expensive and in our experience are not as important as other
8698run-time checks in the development process. Note that division by zero
8699is not considered an overflow check, and divide by zero checks are
8700generated where required by default.
8701
8702Elaboration checks are off by default, and also not needed by default, since
8703GNAT uses a static elaboration analysis approach that avoids the need for
8704run-time checking. This manual contains a full chapter discussing the issue
8705of elaboration checks, and if the default is not satisfactory for your use,
8706you should read this chapter.
8707
8708For validity checks, the minimal checks required by the Ada Reference
8709Manual (for case statements and assignments to array elements) are on
8710by default. These can be suppressed by use of the @option{-gnatVn} switch.
8711Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8712is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8713it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8714are also suppressed entirely if @option{-gnatp} is used.
8715
8716@cindex Overflow checks
8717@cindex Checks, overflow
8718@findex Suppress
8719@findex Unsuppress
8720@cindex pragma Suppress
8721@cindex pragma Unsuppress
8722Note that the setting of the switches controls the default setting of
8723the checks. They may be modified using either @code{pragma Suppress} (to
8724remove checks) or @code{pragma Unsuppress} (to add back suppressed
8725checks) in the program source.
8726
8727@node Use of Restrictions
8728@subsection Use of Restrictions
8729
8730@noindent
8731The use of pragma Restrictions allows you to control which features are
8732permitted in your program. Apart from the obvious point that if you avoid
8733relatively expensive features like finalization (enforceable by the use
8734of pragma Restrictions (No_Finalization), the use of this pragma does not
8735affect the generated code in most cases.
8736
8737One notable exception to this rule is that the possibility of task abort
8738results in some distributed overhead, particularly if finalization or
8739exception handlers are used. The reason is that certain sections of code
8740have to be marked as non-abortable.
8741
8742If you use neither the @code{abort} statement, nor asynchronous transfer
8743of control (@code{select .. then abort}), then this distributed overhead
8744is removed, which may have a general positive effect in improving
8745overall performance.  Especially code involving frequent use of tasking
8746constructs and controlled types will show much improved performance.
8747The relevant restrictions pragmas are
8748
8749@smallexample
8750   pragma Restrictions (No_Abort_Statements);
8751   pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8752@end smallexample
8753
8754@noindent
8755It is recommended that these restriction pragmas be used if possible. Note
8756that this also means that you can write code without worrying about the
8757possibility of an immediate abort at any point.
8758
8759@node Optimization Levels
8760@subsection Optimization Levels
8761@cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8762
8763@noindent
8764The default is optimization off. This results in the fastest compile
8765times, but GNAT makes absolutely no attempt to optimize, and the
8766generated programs are considerably larger and slower than when
8767optimization is enabled. You can use the
8768@ifclear vms
8769@option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8770@end ifclear
8771@ifset vms
8772@code{OPTIMIZE} qualifier
8773@end ifset
8774to @code{gcc} to control the optimization level:
8775
8776@table @option
8777@item ^-O0^/OPTIMIZE=NONE^
8778No optimization (the default);
8779generates unoptimized code but has
8780the fastest compilation time.
8781
8782@item ^-O1^/OPTIMIZE=SOME^
8783Medium level optimization;
8784optimizes reasonably well but does not
8785degrade compilation time significantly.
8786
8787@item ^-O2^/OPTIMIZE=ALL^
8788@ifset vms
8789@itemx /OPTIMIZE=DEVELOPMENT
8790@end ifset
8791Full optimization;
8792generates highly optimized code and has
8793the slowest compilation time.
8794
8795@item ^-O3^/OPTIMIZE=INLINING^
8796Full optimization as in @option{-O2},
8797and also attempts automatic inlining of small
8798subprograms within a unit (@pxref{Inlining of Subprograms}).
8799@end table
8800
8801@noindent
8802Higher optimization levels perform more global transformations on the
8803program and apply more expensive analysis algorithms in order to generate
8804faster and more compact code. The price in compilation time, and the
8805resulting improvement in execution time,
8806both depend on the particular application and the hardware environment.
8807You should experiment to find the best level for your application.
8808
8809Since the precise set of optimizations done at each level will vary from
8810release to release (and sometime from target to target), it is best to think
8811of the optimization settings in general terms.
8812The @cite{Using GNU GCC} manual contains details about
8813^the @option{-O} settings and a number of @option{-f} options that^how to^
8814individually enable or disable specific optimizations.
8815
8816Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8817been tested extensively at all optimization levels. There are some bugs
8818which appear only with optimization turned on, but there have also been
8819bugs which show up only in @emph{unoptimized} code. Selecting a lower
8820level of optimization does not improve the reliability of the code
8821generator, which in practice is highly reliable at all optimization
8822levels.
8823
8824Note regarding the use of @option{-O3}: The use of this optimization level
8825is generally discouraged with GNAT, since it often results in larger
8826executables which run more slowly. See further discussion of this point
8827in @pxref{Inlining of Subprograms}.
8828
8829
8830@node Debugging Optimized Code
8831@subsection Debugging Optimized Code
8832@cindex Debugging optimized code
8833@cindex Optimization and debugging
8834
8835@noindent
8836Although it is possible to do a reasonable amount of debugging at
8837@ifclear vms
8838non-zero optimization levels,
8839the higher the level the more likely that
8840@end ifclear
8841@ifset vms
8842@option{/OPTIMIZE} settings other than @code{NONE},
8843such settings will make it more likely that
8844@end ifset
8845source-level constructs will have been eliminated by optimization.
8846For example, if a loop is strength-reduced, the loop
8847control variable may be completely eliminated and thus cannot be
8848displayed in the debugger.
8849This can only happen at @option{-O2} or @option{-O3}.
8850Explicit temporary variables that you code might be eliminated at
8851^level^setting^ @option{-O1} or higher.
8852
8853The use of the @option{^-g^/DEBUG^} switch,
8854@cindex @option{^-g^/DEBUG^} (@code{gcc})
8855which is needed for source-level debugging,
8856affects the size of the program executable on disk,
8857and indeed the debugging information can be quite large.
8858However, it has no effect on the generated code (and thus does not
8859degrade performance)
8860
8861Since the compiler generates debugging tables for a compilation unit before
8862it performs optimizations, the optimizing transformations may invalidate some
8863of the debugging data.  You therefore need to anticipate certain
8864anomalous situations that may arise while debugging optimized code.
8865These are the most common cases:
8866
8867@enumerate
8868@item
8869@i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8870commands show
8871the PC bouncing back and forth in the code.  This may result from any of
8872the following optimizations:
8873
8874@itemize @bullet
8875@item
8876@i{Common subexpression elimination:} using a single instance of code for a
8877quantity that the source computes several times.  As a result you
8878may not be able to stop on what looks like a statement.
8879
8880@item
8881@i{Invariant code motion:} moving an expression that does not change within a
8882loop, to the beginning of the loop.
8883
8884@item
8885@i{Instruction scheduling:} moving instructions so as to
8886overlap loads and stores (typically) with other code, or in
8887general to move computations of values closer to their uses. Often
8888this causes you to pass an assignment statement without the assignment
8889happening and then later bounce back to the statement when the
8890value is actually needed.  Placing a breakpoint on a line of code
8891and then stepping over it may, therefore, not always cause all the
8892expected side-effects.
8893@end itemize
8894
8895@item
8896@i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8897two identical pieces of code are merged and the program counter suddenly
8898jumps to a statement that is not supposed to be executed, simply because
8899it (and the code following) translates to the same thing as the code
8900that @emph{was} supposed to be executed.  This effect is typically seen in
8901sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8902a @code{break} in a C @code{^switch^switch^} statement.
8903
8904@item
8905@i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8906There are various reasons for this effect:
8907
8908@itemize @bullet
8909@item
8910In a subprogram prologue, a parameter may not yet have been moved to its
8911``home''.
8912
8913@item
8914A variable may be dead, and its register re-used.  This is
8915probably the most common cause.
8916
8917@item
8918As mentioned above, the assignment of a value to a variable may
8919have been moved.
8920
8921@item
8922A variable may be eliminated entirely by value propagation or
8923other means.  In this case, GCC may incorrectly generate debugging
8924information for the variable
8925@end itemize
8926
8927@noindent
8928In general, when an unexpected value appears for a local variable or parameter
8929you should first ascertain if that value was actually computed by
8930your program, as opposed to being incorrectly reported by the debugger.
8931Record fields or
8932array elements in an object designated by an access value
8933are generally less of a problem, once you have ascertained that the access
8934value is sensible.
8935Typically, this means checking variables in the preceding code and in the
8936calling subprogram to verify that the value observed is explainable from other
8937values (one must apply the procedure recursively to those
8938other values); or re-running the code and stopping a little earlier
8939(perhaps before the call) and stepping to better see how the variable obtained
8940the value in question; or continuing to step @emph{from} the point of the
8941strange value to see if code motion had simply moved the variable's
8942assignments later.
8943@end enumerate
8944
8945@noindent
8946In light of such anomalies, a recommended technique is to use @option{-O0}
8947early in the software development cycle, when extensive debugging capabilities
8948are most needed, and then move to @option{-O1} and later @option{-O2} as
8949the debugger becomes less critical.
8950Whether to use the @option{^-g^/DEBUG^} switch in the release version is
8951a release management issue.
8952@ifclear vms
8953Note that if you use @option{-g} you can then use the @command{strip} program
8954on the resulting executable,
8955which removes both debugging information and global symbols.
8956@end ifclear
8957
8958
8959@node Inlining of Subprograms
8960@subsection Inlining of Subprograms
8961
8962@noindent
8963A call to a subprogram in the current unit is inlined if all the
8964following conditions are met:
8965
8966@itemize @bullet
8967@item
8968The optimization level is at least @option{-O1}.
8969
8970@item
8971The called subprogram is suitable for inlining: It must be small enough
8972and not contain nested subprograms or anything else that @code{gcc}
8973cannot support in inlined subprograms.
8974
8975@item
8976The call occurs after the definition of the body of the subprogram.
8977
8978@item
8979@cindex pragma Inline
8980@findex Inline
8981Either @code{pragma Inline} applies to the subprogram or it is
8982small and automatic inlining (optimization level @option{-O3}) is
8983specified.
8984@end itemize
8985
8986@noindent
8987Calls to subprograms in @code{with}'ed units are normally not inlined.
8988To achieve this level of inlining, the following conditions must all be
8989true:
8990
8991@itemize @bullet
8992@item
8993The optimization level is at least @option{-O1}.
8994
8995@item
8996The called subprogram is suitable for inlining: It must be small enough
8997and not contain nested subprograms or anything else @code{gcc} cannot
8998support in inlined subprograms.
8999
9000@item
9001The call appears in a body (not in a package spec).
9002
9003@item
9004There is a @code{pragma Inline} for the subprogram.
9005
9006@item
9007@cindex @option{-gnatn} (@code{gcc})
9008The @option{^-gnatn^/INLINE^} switch
9009is used in the @code{gcc} command line
9010@end itemize
9011
9012Note that specifying the @option{-gnatn} switch causes additional
9013compilation dependencies. Consider the following:
9014
9015@smallexample @c ada
9016@cartouche
9017package R is
9018   procedure Q;
9019   pragma Inline (Q);
9020end R;
9021package body R is
9022   ...
9023end R;
9024
9025with R;
9026procedure Main is
9027begin
9028   ...
9029   R.Q;
9030end Main;
9031@end cartouche
9032@end smallexample
9033
9034@noindent
9035With the default behavior (no @option{-gnatn} switch specified), the
9036compilation of the @code{Main} procedure depends only on its own source,
9037@file{main.adb}, and the spec of the package in file @file{r.ads}. This
9038means that editing the body of @code{R} does not require recompiling
9039@code{Main}.
9040
9041On the other hand, the call @code{R.Q} is not inlined under these
9042circumstances. If the @option{-gnatn} switch is present when @code{Main}
9043is compiled, the call will be inlined if the body of @code{Q} is small
9044enough, but now @code{Main} depends on the body of @code{R} in
9045@file{r.adb} as well as on the spec. This means that if this body is edited,
9046the main program must be recompiled. Note that this extra dependency
9047occurs whether or not the call is in fact inlined by @code{gcc}.
9048
9049The use of front end inlining with @option{-gnatN} generates similar
9050additional dependencies.
9051
9052@cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9053Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9054can be used to prevent
9055all inlining. This switch overrides all other conditions and ensures
9056that no inlining occurs. The extra dependences resulting from
9057@option{-gnatn} will still be active, even if
9058this switch is used to suppress the resulting inlining actions.
9059
9060Note regarding the use of @option{-O3}: There is no difference in inlining
9061behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9062pragma @code{Inline} assuming the use of @option{-gnatn}
9063or @option{-gnatN} (the switches that activate inlining). If you have used
9064pragma @code{Inline} in appropriate cases, then it is usually much better
9065to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9066in this case only has the effect of inlining subprograms you did not
9067think should be inlined. We often find that the use of @option{-O3} slows
9068down code by performing excessive inlining, leading to increased instruction
9069cache pressure from the increased code size. So the bottom line here is
9070that you should not automatically assume that @option{-O3} is better than
9071@option{-O2}, and indeed you should use @option{-O3} only if tests show that
9072it actually improves performance.
9073
9074@ifset vms
9075@node Coverage Analysis
9076@subsection Coverage Analysis
9077
9078@noindent
9079GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9080the user to determine the distribution of execution time across a program,
9081@pxref{Profiling} for details of usage.
9082@end ifset
9083
9084@node Reducing the Size of Ada Executables with gnatelim
9085@section Reducing the Size of Ada Executables with @code{gnatelim}
9086@findex gnatelim
9087
9088@noindent
9089This section describes @command{gnatelim}, a tool which detects unused
9090subprograms and helps the compiler to create a smaller executable for your
9091program.
9092
9093@menu
9094* About gnatelim::
9095* Running gnatelim::
9096* Correcting the List of Eliminate Pragmas::
9097* Making Your Executables Smaller::
9098* Summary of the gnatelim Usage Cycle::
9099@end menu
9100
9101@node About gnatelim
9102@subsection About @code{gnatelim}
9103
9104@noindent
9105When a program shares a set of Ada
9106packages with other programs, it may happen that this program uses
9107only a fraction of the subprograms defined in these packages. The code
9108created for these unused subprograms increases the size of the executable.
9109
9110@code{gnatelim} tracks unused subprograms in an Ada program and
9111outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9112subprograms that are declared but never called. By placing the list of
9113@code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9114recompiling your program, you may decrease the size of its executable,
9115because the compiler will not generate the code for 'eliminated' subprograms.
9116See GNAT Reference Manual for more information about this pragma.
9117
9118@code{gnatelim} needs as its input data the name of the main subprogram
9119and a bind file for a main subprogram.
9120
9121To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9122the main subprogram. @code{gnatelim} can work with both Ada and C
9123bind files; when both are present, it uses the Ada bind file.
9124The following commands will build the program and create the bind file:
9125
9126@smallexample
9127$ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9128$ gnatbind main_prog
9129@end smallexample
9130
9131Note that @code{gnatelim} needs neither object nor ALI files.
9132
9133@node Running gnatelim
9134@subsection Running @code{gnatelim}
9135
9136@noindent
9137@code{gnatelim} has the following command-line interface:
9138
9139@smallexample
9140$ gnatelim [options] name
9141@end smallexample
9142
9143@noindent
9144@code{name} should be a name of a source file that contains the main subprogram
9145of a program (partition).
9146
9147@code{gnatelim} has the following switches:
9148
9149@table @option
9150@c !sort!
9151@item ^-q^/QUIET^
9152@cindex @option{^-q^/QUIET^} (@command{gnatelim})
9153Quiet mode: by default @code{gnatelim} outputs to the standard error
9154stream the number of program units left to be processed. This option turns
9155this trace off.
9156
9157@item ^-v^/VERBOSE^
9158@cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9159Verbose mode: @code{gnatelim} version information is printed as Ada
9160comments to the standard output stream. Also, in addition to the number of
9161program units left @code{gnatelim} will output the name of the current unit
9162being processed.
9163
9164@item ^-a^/ALL^
9165@cindex @option{^-a^/ALL^} (@command{gnatelim})
9166Also look for subprograms from the GNAT run time that can be eliminated. Note
9167that when @file{gnat.adc} is produced using this switch, the entire program
9168must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9169
9170@item ^-I^/INCLUDE_DIRS=^@var{dir}
9171@cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9172When looking for source files also look in directory @var{dir}. Specifying
9173@option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9174sources in the current directory.
9175
9176@item ^-b^/BIND_FILE=^@var{bind_file}
9177@cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9178Specifies @var{bind_file} as the bind file to process. If not set, the name
9179of the bind file is computed from the full expanded Ada name
9180of a main subprogram.
9181
9182@item ^-C^/CONFIG_FILE=^@var{config_file}
9183@cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9184Specifies a file @var{config_file} that contains configuration pragmas. The
9185file must be specified with full path.
9186
9187@item ^--GCC^/COMPILER^=@var{compiler_name}
9188@cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9189Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9190available on the path.
9191
9192@item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9193@cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9194Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9195available on the path.
9196
9197@item -d@var{x}
9198@cindex @option{-d@var{x}} (@command{gnatelim})
9199Activate internal debugging switches. @var{x} is a letter or digit, or
9200string of letters or digits, which specifies the type of debugging
9201mode desired.  Normally these are used only for internal development
9202or system debugging purposes. You can find full documentation for these
9203switches in the spec of the @code{Gnatelim} unit in the compiler
9204source file @file{gnatelim.ads}.
9205@end table
9206
9207@noindent
9208@code{gnatelim} sends its output to the standard output stream, and all the
9209tracing and debug information is sent to the standard error stream.
9210In order to produce a proper GNAT configuration file
9211@file{gnat.adc}, redirection must be used:
9212
9213@smallexample
9214@ifset vms
9215$ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9216@end ifset
9217@ifclear vms
9218$ gnatelim main_prog.adb > gnat.adc
9219@end ifclear
9220@end smallexample
9221
9222@ifclear vms
9223@noindent
9224or
9225
9226@smallexample
9227$ gnatelim main_prog.adb >> gnat.adc
9228@end smallexample
9229
9230@noindent
9231in order to append the @code{gnatelim} output to the existing contents of
9232@file{gnat.adc}.
9233@end ifclear
9234
9235@node Correcting the List of Eliminate Pragmas
9236@subsection Correcting the List of Eliminate Pragmas
9237
9238@noindent
9239In some rare cases @code{gnatelim} may try to eliminate
9240subprograms that are actually called in the program. In this case, the
9241compiler will generate an error message of the form:
9242
9243@smallexample
9244file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9245@end smallexample
9246
9247@noindent
9248You will need to manually remove the wrong @code{Eliminate} pragmas from
9249the @file{gnat.adc} file. You should recompile your program
9250from scratch after that, because you need a consistent @file{gnat.adc} file
9251during the entire compilation.
9252
9253
9254@node Making Your Executables Smaller
9255@subsection Making Your Executables Smaller
9256
9257@noindent
9258In order to get a smaller executable for your program you now have to
9259recompile the program completely with the new @file{gnat.adc} file
9260created by @code{gnatelim} in your current directory:
9261
9262@smallexample
9263$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9264@end smallexample
9265
9266@noindent
9267(Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9268recompile everything
9269with the set of pragmas @code{Eliminate} that you have obtained with
9270@command{gnatelim}).
9271
9272Be aware that the set of @code{Eliminate} pragmas is specific to each
9273program. It is not recommended to merge sets of @code{Eliminate}
9274pragmas created for different programs in one @file{gnat.adc} file.
9275
9276@node Summary of the gnatelim Usage Cycle
9277@subsection Summary of the gnatelim Usage Cycle
9278
9279@noindent
9280Here is a quick summary of the steps to be taken in order to reduce
9281the size of your executables with @code{gnatelim}. You may use
9282other GNAT options to control the optimization level,
9283to produce the debugging information, to set search path, etc.
9284
9285@enumerate
9286@item
9287Produce a bind file
9288
9289@smallexample
9290$ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9291$ gnatbind main_prog
9292@end smallexample
9293
9294@item
9295Generate a list of @code{Eliminate} pragmas
9296@smallexample
9297@ifset vms
9298$ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9299@end ifset
9300@ifclear vms
9301$ gnatelim main_prog >[>] gnat.adc
9302@end ifclear
9303@end smallexample
9304
9305@item
9306Recompile the application
9307
9308@smallexample
9309$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9310@end smallexample
9311
9312@end enumerate
9313
9314
9315
9316
9317@c ********************************
9318@node Renaming Files Using gnatchop
9319@chapter Renaming Files Using @code{gnatchop}
9320@findex gnatchop
9321
9322@noindent
9323This chapter discusses how to handle files with multiple units by using
9324the @code{gnatchop} utility. This utility is also useful in renaming
9325files to meet the standard GNAT default file naming conventions.
9326
9327@menu
9328* Handling Files with Multiple Units::
9329* Operating gnatchop in Compilation Mode::
9330* Command Line for gnatchop::
9331* Switches for gnatchop::
9332* Examples of gnatchop Usage::
9333@end menu
9334
9335@node Handling Files with Multiple Units
9336@section Handling Files with Multiple Units
9337
9338@noindent
9339The basic compilation model of GNAT requires that a file submitted to the
9340compiler have only one unit and there be a strict correspondence
9341between the file name and the unit name.
9342
9343The @code{gnatchop} utility allows both of these rules to be relaxed,
9344allowing GNAT to process files which contain multiple compilation units
9345and files with arbitrary file names. @code{gnatchop}
9346reads the specified file and generates one or more output files,
9347containing one unit per file. The unit and the file name correspond,
9348as required by GNAT.
9349
9350If you want to permanently restructure a set of ``foreign'' files so that
9351they match the GNAT rules, and do the remaining development using the
9352GNAT structure, you can simply use @command{gnatchop} once, generate the
9353new set of files and work with them from that point on.
9354
9355Alternatively, if you want to keep your files in the ``foreign'' format,
9356perhaps to maintain compatibility with some other Ada compilation
9357system, you can set up a procedure where you use @command{gnatchop} each
9358time you compile, regarding the source files that it writes as temporary
9359files that you throw away.
9360
9361
9362@node Operating gnatchop in Compilation Mode
9363@section Operating gnatchop in Compilation Mode
9364
9365@noindent
9366The basic function of @code{gnatchop} is to take a file with multiple units
9367and split it into separate files. The boundary between files is reasonably
9368clear, except for the issue of comments and pragmas. In default mode, the
9369rule is that any pragmas between units belong to the previous unit, except
9370that configuration pragmas always belong to the following unit. Any comments
9371belong to the following unit. These rules
9372almost always result in the right choice of
9373the split point without needing to mark it explicitly and most users will
9374find this default to be what they want. In this default mode it is incorrect to
9375submit a file containing only configuration pragmas, or one that ends in
9376configuration pragmas, to @code{gnatchop}.
9377
9378However, using a special option to activate ``compilation mode'',
9379@code{gnatchop}
9380can perform another function, which is to provide exactly the semantics
9381required by the RM for handling of configuration pragmas in a compilation.
9382In the absence of configuration pragmas (at the main file level), this
9383option has no effect, but it causes such configuration pragmas to be handled
9384in a quite different manner.
9385
9386First, in compilation mode, if @code{gnatchop} is given a file that consists of
9387only configuration pragmas, then this file is appended to the
9388@file{gnat.adc} file in the current directory. This behavior provides
9389the required behavior described in the RM for the actions to be taken
9390on submitting such a file to the compiler, namely that these pragmas
9391should apply to all subsequent compilations in the same compilation
9392environment. Using GNAT, the current directory, possibly containing a
9393@file{gnat.adc} file is the representation
9394of a compilation environment. For more information on the
9395@file{gnat.adc} file, see the section on handling of configuration
9396pragmas @pxref{Handling of Configuration Pragmas}.
9397
9398Second, in compilation mode, if @code{gnatchop}
9399is given a file that starts with
9400configuration pragmas, and contains one or more units, then these
9401configuration pragmas are prepended to each of the chopped files. This
9402behavior provides the required behavior described in the RM for the
9403actions to be taken on compiling such a file, namely that the pragmas
9404apply to all units in the compilation, but not to subsequently compiled
9405units.
9406
9407Finally, if configuration pragmas appear between units, they are appended
9408to the previous unit. This results in the previous unit being illegal,
9409since the compiler does not accept configuration pragmas that follow
9410a unit. This provides the required RM behavior that forbids configuration
9411pragmas other than those preceding the first compilation unit of a
9412compilation.
9413
9414For most purposes, @code{gnatchop} will be used in default mode. The
9415compilation mode described above is used only if you need exactly
9416accurate behavior with respect to compilations, and you have files
9417that contain multiple units and configuration pragmas. In this
9418circumstance the use of @code{gnatchop} with the compilation mode
9419switch provides the required behavior, and is for example the mode
9420in which GNAT processes the ACVC tests.
9421
9422@node Command Line for gnatchop
9423@section Command Line for @code{gnatchop}
9424
9425@noindent
9426The @code{gnatchop} command has the form:
9427
9428@smallexample
9429$ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9430      [@var{directory}]
9431@end smallexample
9432
9433@noindent
9434The only required argument is the file name of the file to be chopped.
9435There are no restrictions on the form of this file name. The file itself
9436contains one or more Ada units, in normal GNAT format, concatenated
9437together. As shown, more than one file may be presented to be chopped.
9438
9439When run in default mode, @code{gnatchop} generates one output file in
9440the current directory for each unit in each of the files.
9441
9442@var{directory}, if specified, gives the name of the directory to which
9443the output files will be written. If it is not specified, all files are
9444written to the current directory.
9445
9446For example, given a
9447file called @file{hellofiles} containing
9448
9449@smallexample @c ada
9450@group
9451@cartouche
9452procedure hello;
9453
9454with Text_IO; use Text_IO;
9455procedure hello is
9456begin
9457   Put_Line ("Hello");
9458end hello;
9459@end cartouche
9460@end group
9461@end smallexample
9462
9463@noindent
9464the command
9465
9466@smallexample
9467$ gnatchop ^hellofiles^HELLOFILES.^
9468@end smallexample
9469
9470@noindent
9471generates two files in the current directory, one called
9472@file{hello.ads} containing the single line that is the procedure spec,
9473and the other called @file{hello.adb} containing the remaining text. The
9474original file is not affected. The generated files can be compiled in
9475the normal manner.
9476
9477@noindent
9478When gnatchop is invoked on a file that is empty or that contains only empty
9479lines and/or comments, gnatchop will not fail, but will not produce any
9480new sources.
9481
9482For example, given a
9483file called @file{toto.txt} containing
9484
9485@smallexample @c ada
9486@group
9487@cartouche
9488--  Just a comment
9489@end cartouche
9490@end group
9491@end smallexample
9492
9493@noindent
9494the command
9495
9496@smallexample
9497$ gnatchop ^toto.txt^TOT.TXT^
9498@end smallexample
9499
9500@noindent
9501will not produce any new file and will result in the following warnings:
9502
9503@smallexample
9504toto.txt:1:01: warning: empty file, contains no compilation units
9505no compilation units found
9506no source files written
9507@end smallexample
9508
9509@node Switches for gnatchop
9510@section Switches for @code{gnatchop}
9511
9512@noindent
9513@command{gnatchop} recognizes the following switches:
9514
9515@table @option
9516@c !sort!
9517
9518@item ^-c^/COMPILATION^
9519@cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9520Causes @code{gnatchop} to operate in compilation mode, in which
9521configuration pragmas are handled according to strict RM rules. See
9522previous section for a full description of this mode.
9523
9524@ifclear vms
9525@item -gnatxxx
9526This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9527used to parse the given file. Not all @code{xxx} options make sense,
9528but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9529process a source file that uses Latin-2 coding for identifiers.
9530@end ifclear
9531
9532@item ^-h^/HELP^
9533Causes @code{gnatchop} to generate a brief help summary to the standard
9534output file showing usage information.
9535
9536@item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9537@cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9538Limit generated file names to the specified number @code{mm}
9539of characters.
9540This is useful if the
9541resulting set of files is required to be interoperable with systems
9542which limit the length of file names.
9543@ifset vms
9544If no value is given, or
9545if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9546a default of 39, suitable for OpenVMS Alpha
9547Systems, is assumed
9548@end ifset
9549@ifclear vms
9550No space is allowed between the @option{-k} and the numeric value. The numeric
9551value may be omitted in which case a default of @option{-k8},
9552suitable for use
9553with DOS-like file systems, is used. If no @option{-k} switch
9554is present then
9555there is no limit on the length of file names.
9556@end ifclear
9557
9558@item ^-p^/PRESERVE^
9559@cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9560Causes the file ^modification^creation^ time stamp of the input file to be
9561preserved and used for the time stamp of the output file(s). This may be
9562useful for preserving coherency of time stamps in an environment where
9563@code{gnatchop} is used as part of a standard build process.
9564
9565@item ^-q^/QUIET^
9566@cindex @option{^-q^/QUIET^} (@code{gnatchop})
9567Causes output of informational messages indicating the set of generated
9568files to be suppressed. Warnings and error messages are unaffected.
9569
9570@item ^-r^/REFERENCE^
9571@cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9572@findex Source_Reference
9573Generate @code{Source_Reference} pragmas. Use this switch if the output
9574files are regarded as temporary and development is to be done in terms
9575of the original unchopped file. This switch causes
9576@code{Source_Reference} pragmas to be inserted into each of the
9577generated files to refers back to the original file name and line number.
9578The result is that all error messages refer back to the original
9579unchopped file.
9580In addition, the debugging information placed into the object file (when
9581the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9582also refers back to this original file so that tools like profilers and
9583debuggers will give information in terms of the original unchopped file.
9584
9585If the original file to be chopped itself contains
9586a @code{Source_Reference}
9587pragma referencing a third file, then gnatchop respects
9588this pragma, and the generated @code{Source_Reference} pragmas
9589in the chopped file refer to the original file, with appropriate
9590line numbers. This is particularly useful when @code{gnatchop}
9591is used in conjunction with @code{gnatprep} to compile files that
9592contain preprocessing statements and multiple units.
9593
9594@item ^-v^/VERBOSE^
9595@cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9596Causes @code{gnatchop} to operate in verbose mode. The version
9597number and copyright notice are output, as well as exact copies of
9598the gnat1 commands spawned to obtain the chop control information.
9599
9600@item ^-w^/OVERWRITE^
9601@cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9602Overwrite existing file names. Normally @code{gnatchop} regards it as a
9603fatal error if there is already a file with the same name as a
9604file it would otherwise output, in other words if the files to be
9605chopped contain duplicated units. This switch bypasses this
9606check, and causes all but the last instance of such duplicated
9607units to be skipped.
9608
9609@ifclear vms
9610@item --GCC=xxxx
9611@cindex @option{--GCC=} (@code{gnatchop})
9612Specify the path of the GNAT parser to be used. When this switch is used,
9613no attempt is made to add the prefix to the GNAT parser executable.
9614@end ifclear
9615@end table
9616
9617@node Examples of gnatchop Usage
9618@section Examples of @code{gnatchop} Usage
9619
9620@table @code
9621@ifset vms
9622@item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9623@end ifset
9624@ifclear vms
9625@item gnatchop -w hello_s.ada prerelease/files
9626@end ifclear
9627
9628Chops the source file @file{hello_s.ada}. The output files will be
9629placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9630overwriting any
9631files with matching names in that directory (no files in the current
9632directory are modified).
9633
9634@item gnatchop ^archive^ARCHIVE.^
9635Chops the source file @file{^archive^ARCHIVE.^}
9636into the current directory. One
9637useful application of @code{gnatchop} is in sending sets of sources
9638around, for example in email messages. The required sources are simply
9639concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9640command), and then
9641@code{gnatchop} is used at the other end to reconstitute the original
9642file names.
9643
9644@item gnatchop file1 file2 file3 direc
9645Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9646the resulting files in the directory @file{direc}. Note that if any units
9647occur more than once anywhere within this set of files, an error message
9648is generated, and no files are written. To override this check, use the
9649@option{^-w^/OVERWRITE^} switch,
9650in which case the last occurrence in the last file will
9651be the one that is output, and earlier duplicate occurrences for a given
9652unit will be skipped.
9653@end table
9654
9655@node Configuration Pragmas
9656@chapter Configuration Pragmas
9657@cindex Configuration pragmas
9658@cindex Pragmas, configuration
9659
9660@noindent
9661In Ada 95, configuration pragmas include those pragmas described as
9662such in the Ada 95 Reference Manual, as well as
9663implementation-dependent pragmas that are configuration pragmas. See the
9664individual descriptions of pragmas in the GNAT Reference Manual for
9665details on these additional GNAT-specific configuration pragmas. Most
9666notably, the pragma @code{Source_File_Name}, which allows
9667specifying non-default names for source files, is a configuration
9668pragma. The following is a complete list of configuration pragmas
9669recognized by @code{GNAT}:
9670
9671@smallexample
9672   Ada_83
9673   Ada_95
9674   C_Pass_By_Copy
9675   Component_Alignment
9676   Discard_Names
9677   Elaboration_Checks
9678   Eliminate
9679   Extend_System
9680   Extensions_Allowed
9681   External_Name_Casing
9682   Float_Representation
9683   Initialize_Scalars
9684   License
9685   Locking_Policy
9686   Long_Float
9687   Normalize_Scalars
9688   Polling
9689   Propagate_Exceptions
9690   Queuing_Policy
9691   Ravenscar
9692   Restricted_Run_Time
9693   Restrictions
9694   Reviewable
9695   Source_File_Name
9696   Style_Checks
9697   Suppress
9698   Task_Dispatching_Policy
9699   Universal_Data
9700   Unsuppress
9701   Use_VADS_Size
9702   Warnings
9703   Validity_Checks
9704@end smallexample
9705
9706@menu
9707* Handling of Configuration Pragmas::
9708* The Configuration Pragmas Files::
9709@end menu
9710
9711@node Handling of Configuration Pragmas
9712@section Handling of Configuration Pragmas
9713
9714Configuration pragmas may either appear at the start of a compilation
9715unit, in which case they apply only to that unit, or they may apply to
9716all compilations performed in a given compilation environment.
9717
9718GNAT also provides the @code{gnatchop} utility to provide an automatic
9719way to handle configuration pragmas following the semantics for
9720compilations (that is, files with multiple units), described in the RM.
9721See section @pxref{Operating gnatchop in Compilation Mode} for details.
9722However, for most purposes, it will be more convenient to edit the
9723@file{gnat.adc} file that contains configuration pragmas directly,
9724as described in the following section.
9725
9726@node The Configuration Pragmas Files
9727@section The Configuration Pragmas Files
9728@cindex @file{gnat.adc}
9729
9730@noindent
9731In GNAT a compilation environment is defined by the current
9732directory at the time that a compile command is given. This current
9733directory is searched for a file whose name is @file{gnat.adc}. If
9734this file is present, it is expected to contain one or more
9735configuration pragmas that will be applied to the current compilation.
9736However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
9737considered.
9738
9739Configuration pragmas may be entered into the @file{gnat.adc} file
9740either by running @code{gnatchop} on a source file that consists only of
9741configuration pragmas, or more conveniently  by
9742direct editing of the @file{gnat.adc} file, which is a standard format
9743source file.
9744
9745In addition to @file{gnat.adc}, one additional file containing configuration
9746pragmas may be applied to the current compilation using the switch
9747@option{-gnatec}@var{path}. @var{path} must designate an existing file that
9748contains only configuration pragmas. These configuration pragmas are
9749in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
9750is present and switch @option{-gnatA} is not used).
9751
9752It is allowed to specify several switches @option{-gnatec}, however only
9753the last one on the command line will be taken into account.
9754
9755If you are using project file, a separate mechanism is provided using
9756project attributes, see @ref{Specifying Configuration Pragmas} for more
9757details.
9758
9759@ifset vms
9760Of special interest to GNAT OpenVMS Alpha is the following
9761configuration pragma:
9762
9763@smallexample @c ada
9764@cartouche
9765pragma Extend_System (Aux_DEC);
9766@end cartouche
9767@end smallexample
9768
9769@noindent
9770In the presence of this pragma, GNAT adds to the definition of the
9771predefined package SYSTEM all the additional types and subprograms that are
9772defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
9773@end ifset
9774
9775@node Handling Arbitrary File Naming Conventions Using gnatname
9776@chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
9777@cindex Arbitrary File Naming Conventions
9778
9779@menu
9780* Arbitrary File Naming Conventions::
9781* Running gnatname::
9782* Switches for gnatname::
9783* Examples of gnatname Usage::
9784@end menu
9785
9786@node Arbitrary File Naming Conventions
9787@section Arbitrary File Naming Conventions
9788
9789@noindent
9790The GNAT compiler must be able to know the source file name of a compilation
9791unit.  When using the standard GNAT default file naming conventions
9792(@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
9793does not need additional information.
9794
9795@noindent
9796When the source file names do not follow the standard GNAT default file naming
9797conventions, the GNAT compiler must be given additional information through
9798a configuration pragmas file (see @ref{Configuration Pragmas})
9799or a project file.
9800When the non standard file naming conventions are well-defined,
9801a small number of pragmas @code{Source_File_Name} specifying a naming pattern
9802(see @ref{Alternative File Naming Schemes}) may be sufficient. However,
9803if the file naming conventions are irregular or arbitrary, a number
9804of pragma @code{Source_File_Name} for individual compilation units
9805must be defined.
9806To help maintain the correspondence between compilation unit names and
9807source file names within the compiler,
9808GNAT provides a tool @code{gnatname} to generate the required pragmas for a
9809set of files.
9810
9811@node Running gnatname
9812@section Running @code{gnatname}
9813
9814@noindent
9815The usual form of the @code{gnatname} command is
9816
9817@smallexample
9818$ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
9819@end smallexample
9820
9821@noindent
9822All of the arguments are optional. If invoked without any argument,
9823@code{gnatname} will display its usage.
9824
9825@noindent
9826When used with at least one naming pattern, @code{gnatname} will attempt to
9827find all the compilation units in files that follow at least one of the
9828naming patterns. To find these compilation units,
9829@code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
9830regular files.
9831
9832@noindent
9833One or several Naming Patterns may be given as arguments to @code{gnatname}.
9834Each Naming Pattern is enclosed between double quotes.
9835A Naming Pattern is a regular expression similar to the wildcard patterns
9836used in file names by the Unix shells or the DOS prompt.
9837
9838@noindent
9839Examples of Naming Patterns are
9840
9841@smallexample
9842   "*.[12].ada"
9843   "*.ad[sb]*"
9844   "body_*"    "spec_*"
9845@end smallexample
9846
9847@noindent
9848For a more complete description of the syntax of Naming Patterns,
9849see the second kind of regular expressions described in @file{g-regexp.ads}
9850(the ``Glob'' regular expressions).
9851
9852@noindent
9853When invoked with no switches, @code{gnatname} will create a configuration
9854pragmas file @file{gnat.adc} in the current working directory, with pragmas
9855@code{Source_File_Name} for each file that contains a valid Ada unit.
9856
9857@node Switches for gnatname
9858@section Switches for @code{gnatname}
9859
9860@noindent
9861Switches for @code{gnatname} must precede any specified Naming Pattern.
9862
9863@noindent
9864You may specify any of the following switches to @code{gnatname}:
9865
9866@table @option
9867@c !sort!
9868
9869@item ^-c^/CONFIG_FILE=^@file{file}
9870@cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
9871Create a configuration pragmas file @file{file} (instead of the default
9872@file{gnat.adc}).
9873@ifclear vms
9874There may be zero, one or more space between @option{-c} and
9875@file{file}.
9876@end ifclear
9877@file{file} may include directory information. @file{file} must be
9878writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
9879When a switch @option{^-c^/CONFIG_FILE^} is
9880specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
9881
9882@item ^-d^/SOURCE_DIRS=^@file{dir}
9883@cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
9884Look for source files in directory @file{dir}. There may be zero, one or more
9885spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
9886When a switch @option{^-d^/SOURCE_DIRS^}
9887is specified, the current working directory will not be searched for source
9888files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
9889or @option{^-D^/DIR_FILES^} switch.
9890Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
9891If @file{dir} is a relative path, it is relative to the directory of
9892the configuration pragmas file specified with switch
9893@option{^-c^/CONFIG_FILE^},
9894or to the directory of the project file specified with switch
9895@option{^-P^/PROJECT_FILE^} or,
9896if neither switch @option{^-c^/CONFIG_FILE^}
9897nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
9898current working directory. The directory
9899specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
9900
9901@item ^-D^/DIRS_FILE=^@file{file}
9902@cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
9903Look for source files in all directories listed in text file @file{file}.
9904There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
9905and @file{file}.
9906@file{file} must be an existing, readable text file.
9907Each non empty line in @file{file} must be a directory.
9908Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
9909switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
9910@file{file}.
9911
9912@item ^-f^/FOREIGN_PATTERN=^@file{pattern}
9913@cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
9914Foreign patterns. Using this switch, it is possible to add sources of languages
9915other than Ada to the list of sources of a project file.
9916It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
9917For example,
9918@smallexample
9919gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
9920@end smallexample
9921@noindent
9922will look for Ada units in all files with the @file{.ada} extension,
9923and will add to the list of file for project @file{prj.gpr} the C files
9924with extension ".^c^C^".
9925
9926@item ^-h^/HELP^
9927@cindex @option{^-h^/HELP^} (@code{gnatname})
9928Output usage (help) information. The output is written to @file{stdout}.
9929
9930@item ^-P^/PROJECT_FILE=^@file{proj}
9931@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
9932Create or update project file @file{proj}. There may be zero, one or more space
9933between @option{-P} and @file{proj}. @file{proj} may include directory
9934information. @file{proj} must be writable.
9935There may be only one switch @option{^-P^/PROJECT_FILE^}.
9936When a switch @option{^-P^/PROJECT_FILE^} is specified,
9937no switch @option{^-c^/CONFIG_FILE^} may be specified.
9938
9939@item ^-v^/VERBOSE^
9940@cindex @option{^-v^/VERBOSE^} (@code{gnatname})
9941Verbose mode. Output detailed explanation of behavior to @file{stdout}.
9942This includes name of the file written, the name of the directories to search
9943and, for each file in those directories whose name matches at least one of
9944the Naming Patterns, an indication of whether the file contains a unit,
9945and if so the name of the unit.
9946
9947@item ^-v -v^/VERBOSE /VERBOSE^
9948@cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
9949Very Verbose mode. In addition to the output produced in verbose mode,
9950for each file in the searched directories whose name matches none of
9951the Naming Patterns, an indication is given that there is no match.
9952
9953@item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
9954@cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
9955Excluded patterns. Using this switch, it is possible to exclude some files
9956that would match the name patterns. For example,
9957@smallexample
9958gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
9959@end smallexample
9960@noindent
9961will look for Ada units in all files with the @file{.ada} extension,
9962except those whose names end with @file{_nt.ada}.
9963
9964@end table
9965
9966@node Examples of gnatname Usage
9967@section Examples of @code{gnatname} Usage
9968
9969@ifset vms
9970@smallexample
9971$ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
9972@end smallexample
9973@end ifset
9974
9975@ifclear vms
9976@smallexample
9977$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
9978@end smallexample
9979@end ifclear
9980
9981@noindent
9982In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
9983and be writable. In addition, the directory
9984@file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
9985@option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
9986
9987@ifclear vms
9988Note the optional spaces after @option{-c} and @option{-d}.
9989@end ifclear
9990
9991@smallexample
9992@ifclear vms
9993$ gnatname -P/home/me/proj -x "*_nt_body.ada"
9994  -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
9995@end ifclear
9996@ifset vms
9997$ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
9998  /EXCLUDED_PATTERN=*_nt_body.ada
9999  /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10000  /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10001@end ifset
10002@end smallexample
10003
10004Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10005even in conjunction with one or several switches
10006@option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10007are used in this example.
10008
10009
10010@c *****************************************
10011@c * G N A T  P r o j e c t  M a n a g e r *
10012@c *****************************************
10013@node GNAT Project Manager
10014@chapter GNAT Project Manager
10015
10016@menu
10017* Introduction::
10018* Examples of Project Files::
10019* Project File Syntax::
10020* Objects and Sources in Project Files::
10021* Importing Projects::
10022* Project Extension::
10023* External References in Project Files::
10024* Packages in Project Files::
10025* Variables from Imported Projects::
10026* Naming Schemes::
10027* Library Projects::
10028* Using Third-Party Libraries through Projects::
10029* Stand-alone Library Projects::
10030* Switches Related to Project Files::
10031* Tools Supporting Project Files::
10032* An Extended Example::
10033* Project File Complete Syntax::
10034@end menu
10035
10036@c ****************
10037@c * Introduction *
10038@c ****************
10039
10040@node Introduction
10041@section Introduction
10042
10043@noindent
10044This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10045you to manage complex builds involving a number of source files, directories,
10046and compilation options for different system configurations. In particular,
10047project files allow you to specify:
10048@itemize @bullet
10049@item
10050The directory or set of directories containing the source files, and/or the
10051names of the specific source files themselves
10052@item
10053The directory in which the compiler's output
10054(@file{ALI} files, object files, tree files) is to be placed
10055@item
10056The directory in which the executable programs is to be placed
10057@item
10058^Switch^Switch^ settings for any of the project-enabled tools
10059(@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10060@code{gnatfind}); you can apply these settings either globally or to individual
10061compilation units.
10062@item
10063The source files containing the main subprogram(s) to be built
10064@item
10065The source programming language(s) (currently Ada and/or C)
10066@item
10067Source file naming conventions; you can specify these either globally or for
10068individual compilation units
10069@end itemize
10070
10071@menu
10072* Project Files::
10073@end menu
10074
10075@node Project Files
10076@subsection Project Files
10077
10078@noindent
10079Project files are written in a syntax close to that of Ada, using  familiar
10080notions such as packages, context clauses, declarations, default values,
10081assignments, and inheritance. Finally, project files can be built
10082hierarchically from other project files, simplifying complex system
10083integration and project reuse.
10084
10085A @dfn{project} is a specific set of values for various compilation properties.
10086The settings for a given project are described by means of
10087a @dfn{project file}, which is a text file written in an Ada-like syntax.
10088Property values in project files are either strings or lists of strings.
10089Properties that are not explicitly set receive default values.  A project
10090file may interrogate the values of @dfn{external variables} (user-defined
10091command-line switches or environment variables), and it may specify property
10092settings conditionally, based on the value of such variables.
10093
10094In simple cases, a project's source files depend only on other source files
10095in the same project, or on the predefined libraries.  (@emph{Dependence} is
10096used in
10097the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10098the Project Manager also allows more sophisticated arrangements,
10099where the source files in one project depend on source files in other
10100projects:
10101@itemize @bullet
10102@item
10103One project can @emph{import} other projects containing needed source files.
10104@item
10105You can organize GNAT projects in a hierarchy: a @emph{child} project
10106can extend a @emph{parent} project, inheriting the parent's source files and
10107optionally overriding any of them with alternative versions
10108@end itemize
10109
10110@noindent
10111More generally, the Project Manager lets you structure large development
10112efforts into hierarchical subsystems, where build decisions are delegated
10113to the subsystem level, and thus different compilation environments
10114(^switch^switch^ settings) used for different subsystems.
10115
10116The Project Manager is invoked through the
10117@option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10118switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10119@ifclear vms
10120There may be zero, one or more spaces between @option{-P} and
10121@option{@emph{projectfile}}.
10122@end ifclear
10123If you want to define (on the command line) an external variable that is
10124queried by the project file, you must use the
10125@option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10126The Project Manager parses and interprets the project file, and drives the
10127invoked tool based on the project settings.
10128
10129The Project Manager supports a wide range of development strategies,
10130for systems of all sizes.  Here are some typical practices that are
10131easily handled:
10132@itemize @bullet
10133@item
10134Using a common set of source files, but generating object files in different
10135directories via different ^switch^switch^ settings
10136@item
10137Using a mostly-shared set of source files, but with different versions of
10138some unit or units
10139@end itemize
10140
10141@noindent
10142The destination of an executable can be controlled inside a project file
10143using the @option{^-o^-o^}
10144^switch^switch^.
10145In the absence of such a ^switch^switch^ either inside
10146the project file or on the command line, any executable files generated by
10147@command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10148in the project file. If no @code{Exec_Dir} is specified, they will be placed
10149in the object directory of the project.
10150
10151You can use project files to achieve some of the effects of a source
10152versioning system (for example, defining separate projects for
10153the different sets of sources that comprise different releases) but the
10154Project Manager is independent of any source configuration management tools
10155that might be used by the developers.
10156
10157The next section introduces the main features of GNAT's project facility
10158through a sequence of examples; subsequent sections will present the syntax
10159and semantics in more detail. A more formal description of the project
10160facility appears in the GNAT Reference Manual.
10161
10162@c *****************************
10163@c * Examples of Project Files *
10164@c *****************************
10165
10166@node Examples of Project Files
10167@section Examples of Project Files
10168@noindent
10169This section illustrates some of the typical uses of project files and
10170explains their basic structure and behavior.
10171
10172@menu
10173* Common Sources with Different ^Switches^Switches^ and Directories::
10174* Using External Variables::
10175* Importing Other Projects::
10176* Extending a Project::
10177@end menu
10178
10179@node Common Sources with Different ^Switches^Switches^ and Directories
10180@subsection Common Sources with Different ^Switches^Switches^ and Directories
10181
10182@menu
10183* Source Files::
10184* Specifying the Object Directory::
10185* Specifying the Exec Directory::
10186* Project File Packages::
10187* Specifying ^Switch^Switch^ Settings::
10188* Main Subprograms::
10189* Executable File Names::
10190* Source File Naming Conventions::
10191* Source Language(s)::
10192@end menu
10193
10194@noindent
10195Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10196@file{proc.adb} are in the @file{/common} directory.  The file
10197@file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10198package @code{Pack}.  We want to compile these source files under two sets
10199of ^switches^switches^:
10200@itemize @bullet
10201@item
10202When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10203and the @option{^-gnata^-gnata^},
10204@option{^-gnato^-gnato^},
10205and @option{^-gnatE^-gnatE^} switches to the
10206compiler; the compiler's output is to appear in @file{/common/debug}
10207@item
10208When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10209to the compiler; the compiler's output is to appear in @file{/common/release}
10210@end itemize
10211
10212@noindent
10213The GNAT project files shown below, respectively @file{debug.gpr} and
10214@file{release.gpr} in the @file{/common} directory, achieve these effects.
10215
10216Schematically:
10217@smallexample
10218@group
10219^/common^[COMMON]^
10220  debug.gpr
10221  release.gpr
10222  pack.ads
10223  pack.adb
10224  proc.adb
10225@end group
10226@group
10227^/common/debug^[COMMON.DEBUG]^
10228  proc.ali, proc.o
10229  pack.ali, pack.o
10230@end group
10231@group
10232^/common/release^[COMMON.RELEASE]^
10233  proc.ali, proc.o
10234  pack.ali, pack.o
10235@end group
10236@end smallexample
10237Here are the corresponding project files:
10238
10239@smallexample @c projectfile
10240@group
10241project Debug is
10242  for Object_Dir use "debug";
10243  for Main use ("proc");
10244
10245  package Builder is
10246    for ^Default_Switches^Default_Switches^ ("Ada")
10247        use ("^-g^-g^");
10248    for Executable ("proc.adb") use "proc1";
10249  end Builder;
10250@end group
10251
10252@group
10253  package Compiler is
10254    for ^Default_Switches^Default_Switches^ ("Ada")
10255       use ("-fstack-check",
10256            "^-gnata^-gnata^",
10257            "^-gnato^-gnato^",
10258            "^-gnatE^-gnatE^");
10259  end Compiler;
10260end Debug;
10261@end group
10262@end smallexample
10263
10264@smallexample @c projectfile
10265@group
10266project Release is
10267  for Object_Dir use "release";
10268  for Exec_Dir use ".";
10269  for Main use ("proc");
10270
10271  package Compiler is
10272    for ^Default_Switches^Default_Switches^ ("Ada")
10273        use ("^-O2^-O2^");
10274  end Compiler;
10275end Release;
10276@end group
10277@end smallexample
10278
10279@noindent
10280The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10281insensitive), and analogously the project defined by @file{release.gpr} is
10282@code{"Release"}.  For consistency the file should have the same name as the
10283project, and the project file's extension should be @code{"gpr"}. These
10284conventions are not required, but a warning is issued if they are not followed.
10285
10286If the current directory is @file{^/temp^[TEMP]^}, then the command
10287@smallexample
10288gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10289@end smallexample
10290
10291@noindent
10292generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10293as well as the @code{^proc1^PROC1.EXE^} executable,
10294using the ^switch^switch^ settings defined in the project file.
10295
10296Likewise, the command
10297@smallexample
10298gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10299@end smallexample
10300
10301@noindent
10302generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10303and the @code{^proc^PROC.EXE^}
10304executable in @file{^/common^[COMMON]^},
10305using the ^switch^switch^ settings from the project file.
10306
10307@node Source Files
10308@unnumberedsubsubsec Source Files
10309
10310@noindent
10311If a project file does not explicitly specify a set of source directories or
10312a set of source files, then by default the project's source files are the
10313Ada source files in the project file directory.  Thus @file{pack.ads},
10314@file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10315
10316@node Specifying the Object Directory
10317@unnumberedsubsubsec Specifying the Object Directory
10318
10319@noindent
10320Several project properties are modeled by Ada-style @emph{attributes};
10321a property is defined by supplying the equivalent of an Ada attribute
10322definition clause in the project file.
10323A project's object directory is another such a property; the corresponding
10324attribute is @code{Object_Dir}, and its value is also a string expression,
10325specified either as absolute or relative. In the later case,
10326it is relative to the project file directory. Thus the compiler's
10327output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10328(for the @code{Debug} project)
10329and to @file{^/common/release^[COMMON.RELEASE]^}
10330(for the @code{Release} project).
10331If @code{Object_Dir} is not specified, then the default is the project file
10332directory itself.
10333
10334@node Specifying the Exec Directory
10335@unnumberedsubsubsec Specifying the Exec Directory
10336
10337@noindent
10338A project's exec directory is another property; the corresponding
10339attribute is @code{Exec_Dir}, and its value is also a string expression,
10340either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10341then the default is the object directory (which may also be the project file
10342directory if attribute @code{Object_Dir} is not specified). Thus the executable
10343is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10344for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10345and in @file{^/common^[COMMON]^} for the @code{Release} project.
10346
10347@node Project File Packages
10348@unnumberedsubsubsec Project File Packages
10349
10350@noindent
10351A GNAT tool that is integrated with the Project Manager is modeled by a
10352corresponding package in the project file. In the example above,
10353The @code{Debug} project defines the packages @code{Builder}
10354(for @command{gnatmake}) and @code{Compiler};
10355the @code{Release} project defines only the @code{Compiler} package.
10356
10357The Ada-like package syntax is not to be taken literally.  Although packages in
10358project files bear a surface resemblance to packages in Ada source code, the
10359notation is simply a way to convey a grouping of properties for a named
10360entity.  Indeed, the package names permitted in project files are restricted
10361to a predefined set, corresponding to the project-aware tools, and the contents
10362of packages are limited to a small set of constructs.
10363The packages in the example above contain attribute definitions.
10364
10365@node Specifying ^Switch^Switch^ Settings
10366@unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10367
10368@noindent
10369^Switch^Switch^ settings for a project-aware tool can be specified through
10370attributes in the package that corresponds to the tool.
10371The example above illustrates one of the relevant attributes,
10372@code{^Default_Switches^Default_Switches^}, which is defined in packages
10373in both project files.
10374Unlike simple attributes like @code{Source_Dirs},
10375@code{^Default_Switches^Default_Switches^} is
10376known as an @emph{associative array}.  When you define this attribute, you must
10377supply an ``index'' (a literal string), and the effect of the attribute
10378definition is to set the value of the array at the specified index.
10379For the @code{^Default_Switches^Default_Switches^} attribute,
10380the index is a programming language (in our case, Ada),
10381and the value specified (after @code{use}) must be a list
10382of string expressions.
10383
10384The attributes permitted in project files are restricted to a predefined set.
10385Some may appear at project level, others in packages.
10386For any attribute that is an associative array, the index must always be a
10387literal string, but the restrictions on this string (e.g., a file name or a
10388language name) depend on the individual attribute.
10389Also depending on the attribute, its specified value will need to be either a
10390string or a string list.
10391
10392In the @code{Debug} project, we set the switches for two tools,
10393@command{gnatmake} and the compiler, and thus we include the two corresponding
10394packages; each package defines the @code{^Default_Switches^Default_Switches^}
10395attribute with index @code{"Ada"}.
10396Note that the package corresponding to
10397@command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10398similar, but only includes the @code{Compiler} package.
10399
10400In project @code{Debug} above, the ^switches^switches^ starting with
10401@option{-gnat} that are specified in package @code{Compiler}
10402could have been placed in package @code{Builder}, since @command{gnatmake}
10403transmits all such ^switches^switches^ to the compiler.
10404
10405@node Main Subprograms
10406@unnumberedsubsubsec Main Subprograms
10407
10408@noindent
10409One of the specifiable properties of a project is a list of files that contain
10410main subprograms.  This property is captured in the @code{Main} attribute,
10411whose value is a list of strings.  If a project defines the @code{Main}
10412attribute, it is not necessary to identify the main subprogram(s) when
10413invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10414
10415@node Executable File Names
10416@unnumberedsubsubsec Executable File Names
10417
10418@noindent
10419By default, the executable file name corresponding to a main source is
10420deducted from the main source file name. Through the attributes
10421@code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10422it is possible to change this default.
10423In project @code{Debug} above, the executable file name
10424for main source @file{^proc.adb^PROC.ADB^} is
10425@file{^proc1^PROC1.EXE^}.
10426Attribute @code{Executable_Suffix}, when specified, may change the suffix
10427of the the executable files, when no attribute @code{Executable} applies:
10428its value replace the platform-specific executable suffix.
10429Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10430specify a non default executable file name when several mains are built at once
10431in a single @command{gnatmake} command.
10432
10433@node Source File Naming Conventions
10434@unnumberedsubsubsec Source File Naming Conventions
10435
10436@noindent
10437Since the project files above do not specify any source file naming
10438conventions, the GNAT defaults are used.  The mechanism for defining source
10439file naming conventions -- a package named @code{Naming} --
10440is described below (@pxref{Naming Schemes}).
10441
10442@node Source Language(s)
10443@unnumberedsubsubsec Source Language(s)
10444
10445@noindent
10446Since the project files do not specify a @code{Languages} attribute, by
10447default the GNAT tools assume that the language of the project file is Ada.
10448More generally, a project can comprise source files
10449in Ada, C, and/or other languages.
10450
10451@node Using External Variables
10452@subsection Using External Variables
10453
10454@noindent
10455Instead of supplying different project files for debug and release, we can
10456define a single project file that queries an external variable (set either
10457on the command line or via an ^environment variable^logical name^) in order to
10458conditionally define the appropriate settings.  Again, assume that the
10459source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10460located in directory @file{^/common^[COMMON]^}.  The following project file,
10461@file{build.gpr}, queries the external variable named @code{STYLE} and
10462defines an object directory and ^switch^switch^ settings based on whether
10463the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10464the default is @code{"deb"}.
10465
10466@smallexample @c projectfile
10467@group
10468project Build is
10469  for Main use ("proc");
10470
10471  type Style_Type is ("deb", "rel");
10472  Style : Style_Type := external ("STYLE", "deb");
10473
10474  case Style is
10475    when "deb" =>
10476      for Object_Dir use "debug";
10477
10478    when "rel" =>
10479      for Object_Dir use "release";
10480      for Exec_Dir use ".";
10481  end case;
10482@end group
10483
10484@group
10485  package Builder is
10486
10487    case Style is
10488      when "deb" =>
10489        for ^Default_Switches^Default_Switches^ ("Ada")
10490            use ("^-g^-g^");
10491        for Executable ("proc") use "proc1";
10492    end case;
10493
10494  end Builder;
10495@end group
10496
10497@group
10498  package Compiler is
10499
10500    case Style is
10501      when "deb" =>
10502        for ^Default_Switches^Default_Switches^ ("Ada")
10503            use ("^-gnata^-gnata^",
10504                 "^-gnato^-gnato^",
10505                 "^-gnatE^-gnatE^");
10506
10507      when "rel" =>
10508        for ^Default_Switches^Default_Switches^ ("Ada")
10509            use ("^-O2^-O2^");
10510    end case;
10511
10512  end Compiler;
10513
10514end Build;
10515@end group
10516@end smallexample
10517
10518@noindent
10519@code{Style_Type} is an example of a @emph{string type}, which is the project
10520file analog of an Ada enumeration type but whose components are string literals
10521rather than identifiers.  @code{Style} is declared as a variable of this type.
10522
10523The form @code{external("STYLE", "deb")} is known as an
10524@emph{external reference}; its first argument is the name of an
10525@emph{external variable}, and the second argument is a default value to be
10526used if the external variable doesn't exist.  You can define an external
10527variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10528or you can use ^an environment variable^a logical name^
10529as an external variable.
10530
10531Each @code{case} construct is expanded by the Project Manager based on the
10532value of @code{Style}. Thus the command
10533@ifclear vms
10534@smallexample
10535gnatmake -P/common/build.gpr -XSTYLE=deb
10536@end smallexample
10537@end ifclear
10538
10539@ifset vms
10540@smallexample
10541gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10542@end smallexample
10543@end ifset
10544
10545@noindent
10546is equivalent to the @command{gnatmake} invocation using the project file
10547@file{debug.gpr} in the earlier example.  So is the command
10548@smallexample
10549gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10550@end smallexample
10551
10552@noindent
10553since @code{"deb"} is the default for @code{STYLE}.
10554
10555Analogously,
10556
10557@ifclear vms
10558@smallexample
10559gnatmake -P/common/build.gpr -XSTYLE=rel
10560@end smallexample
10561@end ifclear
10562
10563@ifset vms
10564@smallexample
10565GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10566@end smallexample
10567@end ifset
10568
10569@noindent
10570is equivalent to the @command{gnatmake} invocation using the project file
10571@file{release.gpr} in the earlier example.
10572
10573@node Importing Other Projects
10574@subsection Importing Other Projects
10575
10576@noindent
10577A compilation unit in a source file in one project may depend on compilation
10578units in source files in other projects.  To compile this unit under
10579control of a project file, the
10580dependent project must @emph{import} the projects containing the needed source
10581files.
10582This effect is obtained using syntax similar to an Ada @code{with} clause,
10583but where @code{with}ed entities are strings that denote project files.
10584
10585As an example, suppose that the two projects @code{GUI_Proj} and
10586@code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10587@file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10588and @file{^/comm^[COMM]^}, respectively.
10589Suppose that the source files for @code{GUI_Proj} are
10590@file{gui.ads} and @file{gui.adb}, and that the source files for
10591@code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10592files is located in its respective project file directory.  Schematically:
10593
10594@smallexample
10595@group
10596^/gui^[GUI]^
10597  gui_proj.gpr
10598  gui.ads
10599  gui.adb
10600@end group
10601
10602@group
10603^/comm^[COMM]^
10604  comm_proj.gpr
10605  comm.ads
10606  comm.adb
10607@end group
10608@end smallexample
10609
10610@noindent
10611We want to develop an application in directory @file{^/app^[APP]^} that
10612@code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10613the corresponding project files (e.g. the ^switch^switch^ settings
10614and object directory).
10615Skeletal code for a main procedure might be something like the following:
10616
10617@smallexample @c ada
10618@group
10619with GUI, Comm;
10620procedure App_Main is
10621   ...
10622begin
10623   ...
10624end App_Main;
10625@end group
10626@end smallexample
10627
10628@noindent
10629Here is a project file, @file{app_proj.gpr}, that achieves the desired
10630effect:
10631
10632@smallexample @c projectfile
10633@group
10634with "/gui/gui_proj", "/comm/comm_proj";
10635project App_Proj is
10636   for Main use ("app_main");
10637end App_Proj;
10638@end group
10639@end smallexample
10640
10641@noindent
10642Building an executable is achieved through the command:
10643@smallexample
10644gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10645@end smallexample
10646@noindent
10647which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10648in the directory where @file{app_proj.gpr} resides.
10649
10650If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10651(as illustrated above) the @code{with} clause can omit the extension.
10652
10653Our example specified an absolute path for each imported project file.
10654Alternatively, the directory name of an imported object can be omitted
10655if either
10656@itemize @bullet
10657@item
10658The imported project file is in the same directory as the importing project
10659file, or
10660@item
10661You have defined ^an environment variable^a logical name^
10662that includes the directory containing
10663the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10664the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10665directory names separated by colons (semicolons on Windows).
10666@end itemize
10667
10668@noindent
10669Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10670@file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10671as follows:
10672
10673@smallexample @c projectfile
10674@group
10675with "gui_proj", "comm_proj";
10676project App_Proj is
10677   for Main use ("app_main");
10678end App_Proj;
10679@end group
10680@end smallexample
10681
10682@noindent
10683Importing other projects can create ambiguities.
10684For example, the same unit might be present in different imported projects, or
10685it might be present in both the importing project and in an imported project.
10686Both of these conditions are errors.  Note that in the current version of
10687the Project Manager, it is illegal to have an ambiguous unit even if the
10688unit is never referenced by the importing project.  This restriction may be
10689relaxed in a future release.
10690
10691@node Extending a Project
10692@subsection Extending a Project
10693
10694@noindent
10695In large software systems it is common to have multiple
10696implementations of a common interface; in Ada terms, multiple versions of a
10697package body for the same specification.  For example, one implementation
10698might be safe for use in tasking programs, while another might only be used
10699in sequential applications.  This can be modeled in GNAT using the concept
10700of @emph{project extension}.  If one project (the ``child'') @emph{extends}
10701another project (the ``parent'') then by default all source files of the
10702parent project are inherited by the child, but the child project can
10703override any of the parent's source files with new versions, and can also
10704add new files.  This facility is the project analog of a type extension in
10705Object-Oriented Programming.  Project hierarchies are permitted (a child
10706project may be the parent of yet another project), and a project that
10707inherits one project can also import other projects.
10708
10709As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
10710file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
10711@file{pack.adb}, and @file{proc.adb}:
10712
10713@smallexample
10714@group
10715^/seq^[SEQ]^
10716  pack.ads
10717  pack.adb
10718  proc.adb
10719  seq_proj.gpr
10720@end group
10721@end smallexample
10722
10723@noindent
10724Note that the project file can simply be empty (that is, no attribute or
10725package is defined):
10726
10727@smallexample @c projectfile
10728@group
10729project Seq_Proj is
10730end Seq_Proj;
10731@end group
10732@end smallexample
10733
10734@noindent
10735implying that its source files are all the Ada source files in the project
10736directory.
10737
10738Suppose we want to supply an alternate version of @file{pack.adb}, in
10739directory @file{^/tasking^[TASKING]^}, but use the existing versions of
10740@file{pack.ads} and @file{proc.adb}.  We can define a project
10741@code{Tasking_Proj} that inherits @code{Seq_Proj}:
10742
10743@smallexample
10744@group
10745^/tasking^[TASKING]^
10746  pack.adb
10747  tasking_proj.gpr
10748@end group
10749
10750@group
10751project Tasking_Proj extends "/seq/seq_proj" is
10752end Tasking_Proj;
10753@end group
10754@end smallexample
10755
10756@noindent
10757The version of @file{pack.adb} used in a build depends on which project file
10758is specified.
10759
10760Note that we could have obtained the desired behavior using project import
10761rather than project inheritance; a @code{base} project would contain the
10762sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
10763import @code{base} and add @file{pack.adb}, and likewise a tasking project
10764would import @code{base} and add a different version of @file{pack.adb}.  The
10765choice depends on whether other sources in the original project need to be
10766overridden.  If they do, then project extension is necessary, otherwise,
10767importing is sufficient.
10768
10769@noindent
10770In a project file that extends another project file, it is possible to
10771indicate that an inherited source is not part of the sources of the extending
10772project. This is necessary sometimes when a package spec has been overloaded
10773and no longer requires a body: in this case, it is necessary to indicate that
10774the inherited body is not part of the sources of the project, otherwise there
10775will be a compilation error when compiling the spec.
10776
10777For that purpose, the attribute @code{Locally_Removed_Files} is used.
10778Its value is a string list: a list of file names.
10779
10780@smallexample @c @projectfile
10781project B extends "a" is
10782   for Source_Files use ("pkg.ads");
10783   --  New spec of Pkg does not need a completion
10784   for Locally_Removed_Files use ("pkg.adb");
10785end B;
10786@end smallexample
10787
10788Attribute @code{Locally_Removed_Files} may also be used to check if a source
10789is still needed: if it is possible to build using @code{gnatmake} when such
10790a source is put in attribute @code{Locally_Removed_Files} of a project P, then
10791it is possible to remove the source completely from a system that includes
10792project P.
10793
10794@c ***********************
10795@c * Project File Syntax *
10796@c ***********************
10797
10798@node Project File Syntax
10799@section Project File Syntax
10800
10801@menu
10802* Basic Syntax::
10803* Packages::
10804* Expressions::
10805* String Types::
10806* Variables::
10807* Attributes::
10808* Associative Array Attributes::
10809* case Constructions::
10810@end menu
10811
10812@noindent
10813This section describes the structure of project files.
10814
10815A project may be an @emph{independent project}, entirely defined by a single
10816project file. Any Ada source file in an independent project depends only
10817on the predefined library and other Ada source files in the same project.
10818
10819@noindent
10820A project may also @dfn{depend on} other projects, in either or both of
10821the following ways:
10822@itemize @bullet
10823@item It may import any number of projects
10824@item It may extend at most one other project
10825@end itemize
10826
10827@noindent
10828The dependence relation is a directed acyclic graph (the subgraph reflecting
10829the ``extends'' relation is a tree).
10830
10831A project's @dfn{immediate sources} are the source files directly defined by
10832that project, either implicitly by residing in the project file's directory,
10833or explicitly through any of the source-related attributes described below.
10834More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
10835of @var{proj} together with the immediate sources (unless overridden) of any
10836project on which @var{proj} depends (either directly or indirectly).
10837
10838@node Basic Syntax
10839@subsection Basic Syntax
10840
10841@noindent
10842As seen in the earlier examples, project files have an Ada-like syntax.
10843The minimal project file is:
10844@smallexample @c projectfile
10845@group
10846project Empty is
10847
10848end Empty;
10849@end group
10850@end smallexample
10851
10852@noindent
10853The identifier @code{Empty} is the name of the project.
10854This project name must be present after the reserved
10855word @code{end} at the end of the project file, followed by a semi-colon.
10856
10857Any name in a project file, such as the project name or a variable name,
10858has the same syntax as an Ada identifier.
10859
10860The reserved words of project files are the Ada reserved words plus
10861@code{extends}, @code{external}, and @code{project}.  Note that the only Ada
10862reserved words currently used in project file syntax are:
10863
10864@itemize @bullet
10865@item
10866@code{case}
10867@item
10868@code{end}
10869@item
10870@code{for}
10871@item
10872@code{is}
10873@item
10874@code{others}
10875@item
10876@code{package}
10877@item
10878@code{renames}
10879@item
10880@code{type}
10881@item
10882@code{use}
10883@item
10884@code{when}
10885@item
10886@code{with}
10887@end itemize
10888
10889@noindent
10890Comments in project files have the same syntax as in Ada, two consecutives
10891hyphens through the end of the line.
10892
10893@node Packages
10894@subsection Packages
10895
10896@noindent
10897A project file may contain @emph{packages}. The name of a package must be one
10898of the identifiers from the following list. A package
10899with a given name may only appear once in a project file. Package names are
10900case insensitive. The following package names are legal:
10901
10902@itemize @bullet
10903@item
10904@code{Naming}
10905@item
10906@code{Builder}
10907@item
10908@code{Compiler}
10909@item
10910@code{Binder}
10911@item
10912@code{Linker}
10913@item
10914@code{Finder}
10915@item
10916@code{Cross_Reference}
10917@item
10918@code{Eliminate}
10919@item
10920@code{gnatls}
10921@item
10922@code{gnatstub}
10923@item
10924@code{IDE}
10925@end itemize
10926
10927@noindent
10928In its simplest form, a package may be empty:
10929
10930@smallexample @c projectfile
10931@group
10932project Simple is
10933  package Builder is
10934  end Builder;
10935end Simple;
10936@end group
10937@end smallexample
10938
10939@noindent
10940A package may contain @emph{attribute declarations},
10941@emph{variable declarations} and @emph{case constructions}, as will be
10942described below.
10943
10944When there is ambiguity between a project name and a package name,
10945the name always designates the project. To avoid possible confusion, it is
10946always a good idea to avoid naming a project with one of the
10947names allowed for packages or any name that starts with @code{gnat}.
10948
10949@node Expressions
10950@subsection Expressions
10951
10952@noindent
10953An @emph{expression} is either a @emph{string expression} or a
10954@emph{string list expression}.
10955
10956A @emph{string expression} is either a @emph{simple string expression} or a
10957@emph{compound string expression}.
10958
10959A @emph{simple string expression} is one of the following:
10960@itemize @bullet
10961@item A literal string; e.g.@code{"comm/my_proj.gpr"}
10962@item A string-valued variable reference (see @ref{Variables})
10963@item A string-valued attribute reference (see @ref{Attributes})
10964@item An external reference (see @ref{External References in Project Files})
10965@end itemize
10966
10967@noindent
10968A @emph{compound string expression} is a concatenation of string expressions,
10969using the operator @code{"&"}
10970@smallexample
10971       Path & "/" & File_Name & ".ads"
10972@end smallexample
10973
10974@noindent
10975A @emph{string list expression} is either a
10976@emph{simple string list expression} or a
10977@emph{compound string list expression}.
10978
10979A @emph{simple string list expression} is one of the following:
10980@itemize @bullet
10981@item A parenthesized list of zero or more string expressions,
10982separated by commas
10983@smallexample
10984   File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
10985   Empty_List := ();
10986@end smallexample
10987@item A string list-valued variable reference
10988@item A string list-valued attribute reference
10989@end itemize
10990
10991@noindent
10992A @emph{compound string list expression} is the concatenation (using
10993@code{"&"}) of a simple string list expression and an expression.  Note that
10994each term in a compound string list expression, except the first, may be
10995either a string expression or a string list expression.
10996
10997@smallexample @c projectfile
10998@group
10999   File_Name_List := () & File_Name; --  One string in this list
11000   Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11001   --  Two strings
11002   Big_List := File_Name_List & Extended_File_Name_List;
11003   --  Concatenation of two string lists: three strings
11004   Illegal_List := "gnat.adc" & Extended_File_Name_List;
11005   --  Illegal: must start with a string list
11006@end group
11007@end smallexample
11008
11009@node String Types
11010@subsection String Types
11011
11012@noindent
11013A @emph{string type declaration} introduces a discrete set of string literals.
11014If a string variable is declared to have this type, its value
11015is restricted to the given set of literals.
11016
11017Here is an example of a string type declaration:
11018
11019@smallexample @c projectfile
11020   type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11021@end smallexample
11022
11023@noindent
11024Variables of a string type are called @emph{typed variables}; all other
11025variables are called @emph{untyped variables}. Typed variables are
11026particularly useful in @code{case} constructions, to support conditional
11027attribute declarations.
11028(see @ref{case Constructions}).
11029
11030The string literals in the list are case sensitive and must all be different.
11031They may include any graphic characters allowed in Ada, including spaces.
11032
11033A string type may only be declared at the project level, not inside a package.
11034
11035A string type may be referenced by its name if it has been declared in the same
11036project file, or by an expanded name whose prefix is the name of the project
11037in which it is declared.
11038
11039@node Variables
11040@subsection Variables
11041
11042@noindent
11043A variable may be declared at the project file level, or within a package.
11044Here are some examples of variable declarations:
11045
11046@smallexample @c projectfile
11047@group
11048   This_OS : OS := external ("OS"); --  a typed variable declaration
11049   That_OS := "GNU/Linux";          --  an untyped variable declaration
11050@end group
11051@end smallexample
11052
11053@noindent
11054The syntax of a @emph{typed variable declaration} is identical to the Ada
11055syntax for an object declaration. By contrast, the syntax of an untyped
11056variable declaration is identical to an Ada assignment statement. In fact,
11057variable declarations in project files have some of the characteristics of
11058an assignment, in that successive declarations for the same variable are
11059allowed. Untyped variable declarations do establish the expected kind of the
11060variable (string or string list), and successive declarations for it must
11061respect the initial kind.
11062
11063@noindent
11064A string variable declaration (typed or untyped) declares a variable
11065whose value is a string. This variable may be used as a string expression.
11066@smallexample @c projectfile
11067   File_Name       := "readme.txt";
11068   Saved_File_Name := File_Name & ".saved";
11069@end smallexample
11070
11071@noindent
11072A string list variable declaration declares a variable whose value is a list
11073of strings. The list may contain any number (zero or more) of strings.
11074
11075@smallexample @c projectfile
11076   Empty_List := ();
11077   List_With_One_Element := ("^-gnaty^-gnaty^");
11078   List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11079   Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11080                 "pack2.ada", "util_.ada", "util.ada");
11081@end smallexample
11082
11083@noindent
11084The same typed variable may not be declared more than once at project level,
11085and it may not be declared more than once in any package; it is in effect
11086a constant.
11087
11088The same untyped variable may be declared several times. Declarations are
11089elaborated in the order in which they appear, so  the new value replaces
11090the old one, and any subsequent reference to the variable uses the new value.
11091However, as noted above, if a variable has been declared as a string, all
11092subsequent
11093declarations must give it a string value. Similarly, if a variable has
11094been declared as a string list, all subsequent declarations
11095must give it a string list value.
11096
11097A @emph{variable reference} may take several forms:
11098
11099@itemize @bullet
11100@item The simple variable name, for a variable in the current package (if any)
11101or in the current project
11102@item An expanded name, whose prefix is a context name.
11103@end itemize
11104
11105@noindent
11106A @emph{context} may be one of the following:
11107
11108@itemize @bullet
11109@item The name of an existing package in the current project
11110@item The name of an imported project of the current project
11111@item The name of an ancestor project (i.e., a project extended by the current
11112project, either directly or indirectly)
11113@item An expanded name whose prefix is an imported/parent project name, and
11114whose selector is a package name in that project.
11115@end itemize
11116
11117@noindent
11118A variable reference may be used in an expression.
11119
11120@node Attributes
11121@subsection Attributes
11122
11123@noindent
11124A project (and its packages) may have @emph{attributes} that define
11125the project's properties.  Some attributes have values that are strings;
11126others have values that are string lists.
11127
11128There are two categories of attributes: @emph{simple attributes}
11129and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11130
11131Legal project attribute names, and attribute names for each legal package are
11132listed below. Attributes names are case-insensitive.
11133
11134The following attributes are defined on projects (all are simple attributes):
11135
11136@multitable @columnfractions .4 .3
11137@item @emph{Attribute Name}
11138@tab @emph{Value}
11139@item @code{Source_Files}
11140@tab string list
11141@item @code{Source_Dirs}
11142@tab string list
11143@item @code{Source_List_File}
11144@tab string
11145@item @code{Object_Dir}
11146@tab string
11147@item @code{Exec_Dir}
11148@tab string
11149@item @code{Locally_Removed_Files}
11150@tab string list
11151@item @code{Main}
11152@tab string list
11153@item @code{Languages}
11154@tab string list
11155@item @code{Main_Language}
11156@tab string
11157@item @code{Library_Dir}
11158@tab string
11159@item @code{Library_Name}
11160@tab string
11161@item @code{Library_Kind}
11162@tab string
11163@item @code{Library_Version}
11164@tab string
11165@item @code{Library_Interface}
11166@tab string
11167@item @code{Library_Auto_Init}
11168@tab string
11169@item @code{Library_Options}
11170@tab string list
11171@item @code{Library_GCC}
11172@tab string
11173@end multitable
11174
11175@noindent
11176The following attributes are defined for package  @code{Naming}
11177(see @ref{Naming Schemes}):
11178
11179@multitable @columnfractions .4 .2 .2 .2
11180@item Attribute Name @tab Category @tab Index @tab Value
11181@item @code{Spec_Suffix}
11182@tab associative array
11183@tab language name
11184@tab string
11185@item @code{Body_Suffix}
11186@tab associative array
11187@tab language name
11188@tab string
11189@item @code{Separate_Suffix}
11190@tab simple attribute
11191@tab n/a
11192@tab string
11193@item @code{Casing}
11194@tab simple attribute
11195@tab n/a
11196@tab string
11197@item @code{Dot_Replacement}
11198@tab simple attribute
11199@tab n/a
11200@tab string
11201@item @code{Spec}
11202@tab associative array
11203@tab Ada unit name
11204@tab string
11205@item @code{Body}
11206@tab associative array
11207@tab Ada unit name
11208@tab string
11209@item @code{Specification_Exceptions}
11210@tab associative array
11211@tab language name
11212@tab string list
11213@item @code{Implementation_Exceptions}
11214@tab associative array
11215@tab language name
11216@tab string list
11217@end multitable
11218
11219@noindent
11220The following attributes are defined for packages @code{Builder},
11221@code{Compiler}, @code{Binder},
11222@code{Linker}, @code{Cross_Reference}, and @code{Finder}
11223(see @ref{^Switches^Switches^ and Project Files}).
11224
11225@multitable @columnfractions .4 .2 .2 .2
11226@item Attribute Name @tab Category @tab Index @tab Value
11227@item @code{^Default_Switches^Default_Switches^}
11228@tab associative array
11229@tab language name
11230@tab string list
11231@item @code{^Switches^Switches^}
11232@tab associative array
11233@tab file name
11234@tab string list
11235@end multitable
11236
11237@noindent
11238In addition, package @code{Compiler} has a single string attribute
11239@code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11240string attribute @code{Global_Configuration_Pragmas}.
11241
11242@noindent
11243Each simple attribute has a default value: the empty string (for string-valued
11244attributes) and the empty list (for string list-valued attributes).
11245
11246An attribute declaration defines a new value for an attribute.
11247
11248Examples of simple attribute declarations:
11249
11250@smallexample @c projectfile
11251   for Object_Dir use "objects";
11252   for Source_Dirs use ("units", "test/drivers");
11253@end smallexample
11254
11255@noindent
11256The syntax of a @dfn{simple attribute declaration} is similar to that of an
11257attribute definition clause in Ada.
11258
11259Attributes references may be appear in expressions.
11260The general form for such a reference is @code{<entity>'<attribute>}:
11261Associative array attributes are functions. Associative
11262array attribute references must have an argument that is a string literal.
11263
11264Examples are:
11265
11266@smallexample @c projectfile
11267  project'Object_Dir
11268  Naming'Dot_Replacement
11269  Imported_Project'Source_Dirs
11270  Imported_Project.Naming'Casing
11271  Builder'^Default_Switches^Default_Switches^("Ada")
11272@end smallexample
11273
11274@noindent
11275The prefix of an attribute may be:
11276@itemize @bullet
11277@item @code{project} for an attribute of the current project
11278@item The name of an existing package of the current project
11279@item The name of an imported project
11280@item The name of a parent project that is extended by the current project
11281@item An expanded name whose prefix is imported/parent project name,
11282      and whose selector is a package name
11283@end itemize
11284
11285@noindent
11286Example:
11287@smallexample @c projectfile
11288@group
11289   project Prj is
11290     for Source_Dirs use project'Source_Dirs & "units";
11291     for Source_Dirs use project'Source_Dirs & "test/drivers"
11292   end Prj;
11293@end group
11294@end smallexample
11295
11296@noindent
11297In the first attribute declaration, initially the attribute @code{Source_Dirs}
11298has the default value: an empty string list. After this declaration,
11299@code{Source_Dirs} is a string list of one element: @code{"units"}.
11300After the second attribute declaration @code{Source_Dirs} is a string list of
11301two elements: @code{"units"} and @code{"test/drivers"}.
11302
11303Note: this example is for illustration only. In practice,
11304the project file would contain only one attribute declaration:
11305
11306@smallexample @c projectfile
11307   for Source_Dirs use ("units", "test/drivers");
11308@end smallexample
11309
11310@node Associative Array Attributes
11311@subsection Associative Array Attributes
11312
11313@noindent
11314Some attributes are defined as @emph{associative arrays}. An associative
11315array may be regarded as a function that takes a string as a parameter
11316and delivers a string or string list value as its result.
11317
11318Here are some examples of single associative array attribute associations:
11319
11320@smallexample @c projectfile
11321   for Body ("main") use "Main.ada";
11322   for ^Switches^Switches^ ("main.ada")
11323       use ("^-v^-v^",
11324            "^-gnatv^-gnatv^");
11325   for ^Switches^Switches^ ("main.ada")
11326            use Builder'^Switches^Switches^ ("main.ada")
11327              & "^-g^-g^";
11328@end smallexample
11329
11330@noindent
11331Like untyped variables and simple attributes, associative array attributes
11332may be declared several times. Each declaration supplies a new value for the
11333attribute, and replaces the previous setting.
11334
11335@noindent
11336An associative array attribute may be declared as a full associative array
11337declaration, with the value of the same attribute in an imported or extended
11338project.
11339
11340@smallexample @c projectfile
11341   package Builder is
11342      for Default_Switches use Default.Builder'Default_Switches;
11343   end Builder;
11344@end smallexample
11345
11346@noindent
11347In this example, @code{Default} must be either an project imported by the
11348current project, or the project that the current project extends. If the
11349attribute is in a package (in this case, in package @code{Builder}), the same
11350package needs to be specified.
11351
11352@noindent
11353A full associative array declaration replaces any other declaration for the
11354attribute, including other full associative array declaration. Single
11355associative array associations may be declare after a full associative
11356declaration, modifying the value for a single association of the attribute.
11357
11358@node case Constructions
11359@subsection @code{case} Constructions
11360
11361@noindent
11362A @code{case} construction is used in a project file to effect conditional
11363behavior.
11364Here is a typical example:
11365
11366@smallexample @c projectfile
11367@group
11368project MyProj is
11369   type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11370
11371   OS : OS_Type := external ("OS", "GNU/Linux");
11372@end group
11373
11374@group
11375   package Compiler is
11376     case OS is
11377       when "GNU/Linux" | "Unix" =>
11378         for ^Default_Switches^Default_Switches^ ("Ada")
11379             use ("^-gnath^-gnath^");
11380       when "NT" =>
11381         for ^Default_Switches^Default_Switches^ ("Ada")
11382             use ("^-gnatP^-gnatP^");
11383       when others =>
11384     end case;
11385   end Compiler;
11386end MyProj;
11387@end group
11388@end smallexample
11389
11390@noindent
11391The syntax of a @code{case} construction is based on the Ada case statement
11392(although there is no @code{null} construction for empty alternatives).
11393
11394The case expression must a typed string variable.
11395Each alternative comprises the reserved word @code{when}, either a list of
11396literal strings separated by the @code{"|"} character or the reserved word
11397@code{others},  and the @code{"=>"} token.
11398Each literal string must belong to the string type that is the type of the
11399case variable.
11400An @code{others} alternative, if present, must occur last.
11401
11402After each @code{=>}, there are zero or more constructions.  The only
11403constructions allowed in a case construction are other case constructions and
11404attribute declarations. String type declarations, variable declarations and
11405package declarations are not allowed.
11406
11407The value of the case variable is often given by an external reference
11408(see @ref{External References in Project Files}).
11409
11410@c ****************************************
11411@c * Objects and Sources in Project Files *
11412@c ****************************************
11413
11414@node Objects and Sources in Project Files
11415@section Objects and Sources in Project Files
11416
11417@menu
11418* Object Directory::
11419* Exec Directory::
11420* Source Directories::
11421* Source File Names::
11422@end menu
11423
11424@noindent
11425Each project has exactly one object directory and one or more source
11426directories. The source directories must contain at least one source file,
11427unless  the project file explicitly specifies that no source files are present
11428(see @ref{Source File Names}).
11429
11430@node Object Directory
11431@subsection Object Directory
11432
11433@noindent
11434The object directory for a project is the directory containing the compiler's
11435output (such as @file{ALI} files and object files) for the project's immediate
11436sources.
11437
11438The object directory is given by the value of the attribute @code{Object_Dir}
11439in the project file.
11440
11441@smallexample @c projectfile
11442   for Object_Dir use "objects";
11443@end smallexample
11444
11445@noindent
11446The attribute @var{Object_Dir} has a string value, the path name of the object
11447directory. The path name may be absolute or relative to the directory of the
11448project file. This directory must already exist, and be readable and writable.
11449
11450By default, when the attribute @code{Object_Dir} is not given an explicit value
11451or when its value is the empty string, the object directory is the same as the
11452directory containing the project file.
11453
11454@node Exec Directory
11455@subsection Exec Directory
11456
11457@noindent
11458The exec directory for a project is the directory containing the executables
11459for the project's main subprograms.
11460
11461The exec directory is given by the value of the attribute @code{Exec_Dir}
11462in the project file.
11463
11464@smallexample @c projectfile
11465   for Exec_Dir use "executables";
11466@end smallexample
11467
11468@noindent
11469The attribute @var{Exec_Dir} has a string value, the path name of the exec
11470directory. The path name may be absolute or relative to the directory of the
11471project file. This directory must already exist, and be writable.
11472
11473By default, when the attribute @code{Exec_Dir} is not given an explicit value
11474or when its value is the empty string, the exec directory is the same as the
11475object directory of the project file.
11476
11477@node Source Directories
11478@subsection Source Directories
11479
11480@noindent
11481The source directories of a project are specified by the project file
11482attribute @code{Source_Dirs}.
11483
11484This attribute's value is a string list. If the attribute is not given an
11485explicit value, then there is only one source directory, the one where the
11486project file resides.
11487
11488A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11489as in
11490
11491@smallexample @c projectfile
11492    for Source_Dirs use ();
11493@end smallexample
11494
11495@noindent
11496indicates that the project contains no source files.
11497
11498Otherwise, each string in the string list designates one or more
11499source directories.
11500
11501@smallexample @c projectfile
11502   for Source_Dirs use ("sources", "test/drivers");
11503@end smallexample
11504
11505@noindent
11506If a string in the list ends with @code{"/**"},  then the directory whose path
11507name precedes the two asterisks, as well as all its subdirectories
11508(recursively), are source directories.
11509
11510@smallexample @c projectfile
11511   for Source_Dirs use ("/system/sources/**");
11512@end smallexample
11513
11514@noindent
11515Here the directory @code{/system/sources} and all of its subdirectories
11516(recursively) are source directories.
11517
11518To specify that the source directories are the directory of the project file
11519and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11520@smallexample @c projectfile
11521   for Source_Dirs use ("./**");
11522@end smallexample
11523
11524@noindent
11525Each of the source directories must exist and be readable.
11526
11527@node Source File Names
11528@subsection Source File Names
11529
11530@noindent
11531In a project that contains source files, their names may be specified by the
11532attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11533(a string). Source file names never include any directory information.
11534
11535If the attribute @code{Source_Files} is given an explicit value, then each
11536element of the list is a source file name.
11537
11538@smallexample @c projectfile
11539   for Source_Files use ("main.adb");
11540   for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11541@end smallexample
11542
11543@noindent
11544If the attribute @code{Source_Files} is not given an explicit value,
11545but the attribute @code{Source_List_File} is given a string value,
11546then the source file names are contained in the text file whose path name
11547(absolute or relative to the directory of the project file) is the
11548value of the attribute @code{Source_List_File}.
11549
11550Each line in the file that is not empty or is not a comment
11551contains a source file name.
11552
11553@smallexample @c projectfile
11554   for Source_List_File use "source_list.txt";
11555@end smallexample
11556
11557@noindent
11558By default, if neither the attribute @code{Source_Files} nor the attribute
11559@code{Source_List_File} is given an explicit value, then each file in the
11560source directories that conforms to the project's naming scheme
11561(see @ref{Naming Schemes}) is an immediate source of the project.
11562
11563A warning is issued if both attributes @code{Source_Files} and
11564@code{Source_List_File} are given explicit values. In this case, the attribute
11565@code{Source_Files} prevails.
11566
11567Each source file name must be the name of one existing source file
11568in one of the source directories.
11569
11570A @code{Source_Files} attribute whose value is an empty list
11571indicates that there are no source files in the project.
11572
11573If the order of the source directories is known statically, that is if
11574@code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11575be several files with the same source file name. In this case, only the file
11576in the first directory is considered as an immediate source of the project
11577file. If the order of the source directories is not known statically, it is
11578an error to have several files with the same source file name.
11579
11580Projects can be specified to have no Ada source
11581files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11582list, or the @code{"Ada"} may be absent from @code{Languages}:
11583
11584@smallexample @c projectfile
11585   for Source_Dirs use ();
11586   for Source_Files use ();
11587   for Languages use ("C", "C++");
11588@end smallexample
11589
11590@noindent
11591Otherwise, a project must contain at least one immediate source.
11592
11593Projects with no source files are useful as template packages
11594(see @ref{Packages in Project Files}) for other projects; in particular to
11595define a package @code{Naming} (see @ref{Naming Schemes}).
11596
11597@c ****************************
11598@c * Importing Projects *
11599@c ****************************
11600
11601@node  Importing Projects
11602@section Importing Projects
11603
11604@noindent
11605An immediate source of a project P may depend on source files that
11606are neither immediate sources of P nor in the predefined library.
11607To get this effect, P must @emph{import} the projects that contain the needed
11608source files.
11609
11610@smallexample @c projectfile
11611@group
11612  with "project1", "utilities.gpr";
11613  with "/namings/apex.gpr";
11614  project Main is
11615    ...
11616@end group
11617@end smallexample
11618
11619@noindent
11620As can be seen in this example, the syntax for importing projects is similar
11621to the syntax for importing compilation units in Ada. However, project files
11622use literal strings instead of names, and the @code{with} clause identifies
11623project files rather than packages.
11624
11625Each literal string is the file name or path name (absolute or relative) of a
11626project file. If a string is simply a file name, with no path, then its
11627location is determined by the @emph{project path}:
11628
11629@itemize @bullet
11630@item
11631If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11632then the project path includes all the directories in this
11633^environment variable^logical name^, plus the directory of the project file.
11634
11635@item
11636If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11637exist, then the project path contains only one directory, namely the one where
11638the project file is located.
11639@end itemize
11640
11641@noindent
11642If a relative pathname is used, as in
11643
11644@smallexample @c projectfile
11645  with "tests/proj";
11646@end smallexample
11647
11648@noindent
11649then the path is relative to the directory where the importing project file is
11650located. Any symbolic link will be fully resolved in the directory
11651of the importing project file before the imported project file is examined.
11652
11653If the @code{with}'ed project file name does not have an extension,
11654the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11655then the file name as specified in the @code{with} clause (no extension) will
11656be used. In the above example, if a file @code{project1.gpr} is found, then it
11657will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11658then it will be used; if neither file exists, this is an error.
11659
11660A warning is issued if the name of the project file does not match the
11661name of the project; this check is case insensitive.
11662
11663Any source file that is an immediate source of the imported project can be
11664used by the immediate sources of the importing project, transitively. Thus
11665if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11666sources of @code{A} may depend on the immediate sources of @code{C}, even if
11667@code{A} does not import @code{C} explicitly. However, this is not recommended,
11668because if and when @code{B} ceases to import @code{C}, some sources in
11669@code{A} will no longer compile.
11670
11671A side effect of this capability is that normally cyclic dependencies are not
11672permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11673is not allowed to import @code{A}. However, there are cases when cyclic
11674dependencies would be beneficial. For these cases, another form of import
11675between projects exists, the @code{limited with}: a project @code{A} that
11676imports a project @code{B} with a straigh @code{with} may also be imported,
11677directly or indirectly, by @code{B} on the condition that imports from @code{B}
11678to @code{A} include at least one @code{limited with}.
11679
11680@smallexample @c 0projectfile
11681with "../b/b.gpr";
11682with "../c/c.gpr";
11683project A is
11684end A;
11685
11686limited with "../a/a.gpr";
11687project B is
11688end B;
11689
11690with "../d/d.gpr";
11691project C is
11692end C;
11693
11694limited with "../a/a.gpr";
11695project D is
11696end D;
11697@end smallexample
11698
11699@noindent
11700In the above legal example, there are two project cycles:
11701@itemize @bullet
11702@item A-> B-> A
11703@item A -> C -> D -> A
11704@end itemize
11705
11706@noindent
11707In each of these cycle there is one @code{limited with}: import of @code{A}
11708from @code{B} and import of @code{A} from @code{D}.
11709
11710The difference between straight @code{with} and @code{limited with} is that
11711the name of a project imported with a @code{limited with} cannot be used in the
11712project that imports it. In particular, its packages cannot be renamed and
11713its variables cannot be referred to.
11714
11715An exception to the above rules for @code{limited with} is that for the main
11716project specified to @command{gnatmake} or to the @command{GNAT} driver a
11717@code{limited with} is equivalent to a straight @code{with}. For example,
11718in the example above, projects @code{B} and @code{D} could not be main
11719projects for @command{gnatmake} or to the @command{GNAT} driver, because they
11720each have a @code{limited with} that is the only one in a cycle of importing
11721projects.
11722
11723@c *********************
11724@c * Project Extension *
11725@c *********************
11726
11727@node Project Extension
11728@section Project Extension
11729
11730@noindent
11731During development of a large system, it is sometimes necessary to use
11732modified versions of some of the source files, without changing the original
11733sources. This can be achieved through the @emph{project extension} facility.
11734
11735@smallexample @c projectfile
11736   project Modified_Utilities extends "/baseline/utilities.gpr" is ...
11737@end smallexample
11738
11739@noindent
11740A project extension declaration introduces an extending project
11741(the @emph{child}) and a project being extended (the @emph{parent}).
11742
11743By default, a child project inherits all the sources of its parent.
11744However, inherited sources can be overridden: a unit in a parent is hidden
11745by a unit of the same name in the child.
11746
11747Inherited sources are considered to be sources (but not immediate sources)
11748of the child project; see @ref{Project File Syntax}.
11749
11750An inherited source file retains any switches specified in the parent project.
11751
11752For example if the project @code{Utilities} contains the specification and the
11753body of an Ada package @code{Util_IO}, then the project
11754@code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
11755The original body of @code{Util_IO} will not be considered in program builds.
11756However, the package specification will still be found in the project
11757@code{Utilities}.
11758
11759A child project can have only one parent but it may import any number of other
11760projects.
11761
11762A project is not allowed to import directly or indirectly at the same time a
11763child project and any of its ancestors.
11764
11765@c ****************************************
11766@c * External References in Project Files *
11767@c ****************************************
11768
11769@node  External References in Project Files
11770@section External References in Project Files
11771
11772@noindent
11773A project file may contain references to external variables; such references
11774are called @emph{external references}.
11775
11776An external variable is either defined as part of the environment (an
11777environment variable in Unix, for example) or else specified on the command
11778line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11779If both, then the command line value is used.
11780
11781The value of an external reference is obtained by means of the built-in
11782function @code{external}, which returns a string value.
11783This function has two forms:
11784@itemize @bullet
11785@item @code{external (external_variable_name)}
11786@item @code{external (external_variable_name, default_value)}
11787@end itemize
11788
11789@noindent
11790Each parameter must be a string literal.  For example:
11791
11792@smallexample @c projectfile
11793   external ("USER")
11794   external ("OS", "GNU/Linux")
11795@end smallexample
11796
11797@noindent
11798In the form with one parameter, the function returns the value of
11799the external variable given as parameter. If this name is not present in the
11800environment, the function returns an empty string.
11801
11802In the form with two string parameters, the second argument is
11803the value returned when the variable given as the first argument is not
11804present in the environment. In the example above, if @code{"OS"} is not
11805the name of ^an environment variable^a logical name^ and is not passed on
11806the command line, then the returned value is @code{"GNU/Linux"}.
11807
11808An external reference may be part of a string expression or of a string
11809list expression, and can therefore appear in a variable declaration or
11810an attribute declaration.
11811
11812@smallexample @c projectfile
11813@group
11814   type Mode_Type is ("Debug", "Release");
11815   Mode : Mode_Type := external ("MODE");
11816   case Mode is
11817     when "Debug" =>
11818        ...
11819@end group
11820@end smallexample
11821
11822@c *****************************
11823@c * Packages in Project Files *
11824@c *****************************
11825
11826@node  Packages in Project Files
11827@section Packages in Project Files
11828
11829@noindent
11830A @emph{package} defines the settings for project-aware tools within a
11831project.
11832For each such tool one can declare a package; the names for these
11833packages are preset (see @ref{Packages}).
11834A package may contain variable declarations, attribute declarations, and case
11835constructions.
11836
11837@smallexample @c projectfile
11838@group
11839   project Proj is
11840      package Builder is  -- used by gnatmake
11841         for ^Default_Switches^Default_Switches^ ("Ada")
11842             use ("^-v^-v^",
11843                  "^-g^-g^");
11844      end Builder;
11845   end Proj;
11846@end group
11847@end smallexample
11848
11849@noindent
11850The syntax of package declarations mimics that of package in Ada.
11851
11852Most of the packages have an attribute
11853@code{^Default_Switches^Default_Switches^}.
11854This attribute is an associative array, and its value is a string list.
11855The index of the associative array is the name of a programming language (case
11856insensitive). This attribute indicates the ^switch^switch^
11857or ^switches^switches^ to be used
11858with the corresponding tool.
11859
11860Some packages also have another attribute, @code{^Switches^Switches^},
11861an associative array whose value is a string list.
11862The index is the name of a source file.
11863This attribute indicates the ^switch^switch^
11864or ^switches^switches^ to be used by the corresponding
11865tool when dealing with this specific file.
11866
11867Further information on these ^switch^switch^-related attributes is found in
11868@ref{^Switches^Switches^ and Project Files}.
11869
11870A package may be declared as a @emph{renaming} of another package; e.g., from
11871the project file for an imported project.
11872
11873@smallexample @c projectfile
11874@group
11875  with "/global/apex.gpr";
11876  project Example is
11877    package Naming renames Apex.Naming;
11878    ...
11879  end Example;
11880@end group
11881@end smallexample
11882
11883@noindent
11884Packages that are renamed in other project files often come from project files
11885that have no sources: they are just used as templates. Any modification in the
11886template will be reflected automatically in all the project files that rename
11887a package from the template.
11888
11889In addition to the tool-oriented packages, you can also declare a package
11890named @code{Naming} to establish specialized source file naming conventions
11891(see @ref{Naming Schemes}).
11892
11893@c ************************************
11894@c * Variables from Imported Projects *
11895@c ************************************
11896
11897@node Variables from Imported Projects
11898@section Variables from Imported Projects
11899
11900@noindent
11901An attribute or variable defined in an imported or parent project can
11902be used in expressions in the importing / extending project.
11903Such an attribute or variable is denoted by an expanded name whose prefix
11904is either the name of the project or the expanded name of a package within
11905a project.
11906
11907@smallexample @c projectfile
11908@group
11909  with "imported";
11910  project Main extends "base" is
11911     Var1 := Imported.Var;
11912     Var2 := Base.Var & ".new";
11913@end group
11914
11915@group
11916     package Builder is
11917        for ^Default_Switches^Default_Switches^ ("Ada")
11918            use Imported.Builder.Ada_^Switches^Switches^ &
11919                "^-gnatg^-gnatg^" &
11920                "^-v^-v^";
11921     end Builder;
11922@end group
11923
11924@group
11925     package Compiler is
11926        for ^Default_Switches^Default_Switches^ ("Ada")
11927            use Base.Compiler.Ada_^Switches^Switches^;
11928     end Compiler;
11929  end Main;
11930@end group
11931@end smallexample
11932
11933@noindent
11934In this example:
11935
11936@itemize @bullet
11937@item
11938The value of @code{Var1} is a copy of the variable @code{Var} defined
11939in the project file @file{"imported.gpr"}
11940@item
11941the value of @code{Var2} is a copy of the value of variable @code{Var}
11942defined in the project file @file{base.gpr}, concatenated with @code{".new"}
11943@item
11944attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
11945@code{Builder} is a string list that includes in its value a copy of the value
11946of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
11947in project file @file{imported.gpr} plus two new elements:
11948@option{"^-gnatg^-gnatg^"}
11949and @option{"^-v^-v^"};
11950@item
11951attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
11952@code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
11953defined in the @code{Compiler} package in project file @file{base.gpr},
11954the project being extended.
11955@end itemize
11956
11957@c ******************
11958@c * Naming Schemes *
11959@c ******************
11960
11961@node  Naming Schemes
11962@section Naming Schemes
11963
11964@noindent
11965Sometimes an Ada software system is ported from a foreign compilation
11966environment to GNAT, and the file names do not use the default GNAT
11967conventions. Instead of changing all the file names (which for a variety
11968of reasons might not be possible), you can define the relevant file
11969naming scheme in the @code{Naming} package in your project file.
11970
11971@noindent
11972Note that the use of pragmas described in @ref{Alternative
11973File Naming Schemes} by mean of a configuration pragmas file is not
11974supported when using project files. You must use the features described
11975in this paragraph. You can however use specify other configuration
11976pragmas (see @ref{Specifying Configuration Pragmas}).
11977
11978@ifclear vms
11979For example, the following
11980package models the Apex file naming rules:
11981
11982@smallexample @c projectfile
11983@group
11984  package Naming is
11985    for Casing               use "lowercase";
11986    for Dot_Replacement      use ".";
11987    for Spec_Suffix ("Ada")  use ".1.ada";
11988    for Body_Suffix ("Ada")  use ".2.ada";
11989  end Naming;
11990@end group
11991@end smallexample
11992@end ifclear
11993
11994@ifset vms
11995For example, the following package models the DEC Ada file naming rules:
11996
11997@smallexample @c projectfile
11998@group
11999  package Naming is
12000    for Casing               use "lowercase";
12001    for Dot_Replacement      use "__";
12002    for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12003    for Body_Suffix ("Ada")  use ".^ada^ada^";
12004  end Naming;
12005@end group
12006@end smallexample
12007
12008@noindent
12009(Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12010names in lower case)
12011@end ifset
12012
12013@noindent
12014You can define the following attributes in package @code{Naming}:
12015
12016@table @code
12017
12018@item @var{Casing}
12019This must be a string with one of the three values @code{"lowercase"},
12020@code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12021
12022@noindent
12023If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12024
12025@item @var{Dot_Replacement}
12026This must be a string whose value satisfies the following conditions:
12027
12028@itemize @bullet
12029@item It must not be empty
12030@item It cannot start or end with an alphanumeric character
12031@item It cannot be a single underscore
12032@item It cannot start with an underscore followed by an alphanumeric
12033@item It cannot contain a dot @code{'.'} except if the entire string
12034is @code{"."}
12035@end itemize
12036
12037@noindent
12038If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12039
12040@item @var{Spec_Suffix}
12041This is an associative array (indexed by the programming language name, case
12042insensitive) whose value is a string that must satisfy the following
12043conditions:
12044
12045@itemize @bullet
12046@item It must not be empty
12047@item It must include at least one dot
12048@end itemize
12049@noindent
12050If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12051@code{"^.ads^.ADS^"}.
12052
12053@item @var{Body_Suffix}
12054This is an associative array (indexed by the programming language name, case
12055insensitive) whose value is a string that must satisfy the following
12056conditions:
12057
12058@itemize @bullet
12059@item It must not be empty
12060@item It must include at least one dot
12061@item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12062@end itemize
12063@noindent
12064If @code{Body_Suffix ("Ada")} is not specified, then the default is
12065@code{"^.adb^.ADB^"}.
12066
12067@item @var{Separate_Suffix}
12068This must be a string whose value satisfies the same conditions as
12069@code{Body_Suffix}.
12070
12071@noindent
12072If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12073value as @code{Body_Suffix ("Ada")}.
12074
12075@item @var{Spec}
12076@noindent
12077You can use the associative array attribute @code{Spec}  to define
12078the source file name for an individual Ada compilation unit's spec. The array
12079index must be a string literal that identifies the Ada unit (case insensitive).
12080The value of this attribute must be a string that identifies the file that
12081contains this unit's spec (case sensitive or insensitive depending on the
12082operating system).
12083
12084@smallexample @c projectfile
12085   for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12086@end smallexample
12087
12088@item @var{Body}
12089
12090You can use the associative array attribute @code{Body} to
12091define the source file name for an individual Ada compilation unit's body
12092(possibly a subunit).  The array index must be a string literal that identifies
12093the Ada unit (case insensitive).  The value of this attribute must be a string
12094that identifies the file that contains this unit's body or subunit (case
12095sensitive or insensitive depending on the operating system).
12096
12097@smallexample @c projectfile
12098   for Body ("MyPack.MyChild") use "mypack.mychild.body";
12099@end smallexample
12100@end table
12101
12102@c ********************
12103@c * Library Projects *
12104@c ********************
12105
12106@node Library Projects
12107@section Library Projects
12108
12109@noindent
12110@emph{Library projects} are projects whose object code is placed in a library.
12111(Note that this facility is not yet supported on all platforms)
12112
12113To create a library project, you need to define in its project file
12114two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12115Additionally, you may define the library-related attributes
12116@code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12117@code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12118
12119The @code{Library_Name} attribute has a string value. There is no restriction
12120on the name of a library. It is the responsability of the developer to
12121choose a name that will be accepted by the platform. It is recommanded to
12122choose names that could be Ada identifiers; such names are almost guaranteed
12123to be acceptable on all platforms.
12124
12125The @code{Library_Dir} attribute has a string value that designates the path
12126(absolute or relative) of the directory where the library will reside.
12127It must designate an existing directory, and this directory must be
12128different from the project's object directory. It also needs to be writable.
12129
12130If both @code{Library_Name} and @code{Library_Dir} are specified and
12131are legal, then the project file defines a library project.  The optional
12132library-related attributes are checked only for such project files.
12133
12134The @code{Library_Kind} attribute has a string value that must be one of the
12135following (case insensitive): @code{"static"}, @code{"dynamic"} or
12136@code{"relocatable"}. If this attribute is not specified, the library is a
12137static library, that is an archive of object files that can be potentially
12138linked into an static executable. Otherwise, the library may be dynamic or
12139relocatable, that is a library that is loaded only at the start of execution.
12140Depending on the operating system, there may or may not be a distinction
12141between dynamic and relocatable libraries. For Unix and VMS Unix there is no
12142such distinction.
12143
12144If you need to build both a static and a dynamic library, you should use two
12145different object directories, since in some cases some extra code needs to
12146be generated for the latter. For such cases, it is recommended to either use
12147two different project files, or a single one which uses external variables
12148to indicate what kind of library should be build.
12149
12150The @code{Library_Version} attribute has a string value whose interpretation
12151is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12152used only for dynamic/relocatable libraries as the internal name of the
12153library (the @code{"soname"}). If the library file name (built from the
12154@code{Library_Name}) is different from the @code{Library_Version}, then the
12155library file will be a symbolic link to the actual file whose name will be
12156@code{Library_Version}.
12157
12158Example (on Unix):
12159
12160@smallexample @c projectfile
12161@group
12162project Plib is
12163
12164   Version := "1";
12165
12166   for Library_Dir use "lib_dir";
12167   for Library_Name use "dummy";
12168   for Library_Kind use "relocatable";
12169   for Library_Version use "libdummy.so." & Version;
12170
12171end Plib;
12172@end group
12173@end smallexample
12174
12175@noindent
12176Directory @file{lib_dir} will contain the internal library file whose name
12177will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12178@file{libdummy.so.1}.
12179
12180When @command{gnatmake} detects that a project file
12181is a library project file, it will check all immediate sources of the project
12182and rebuild the library if any of the sources have been recompiled.
12183
12184When a library is built or rebuilt, an attempt is made to delete all
12185files in the library directory.
12186All @file{ALI} files will also be copied from the object directory to the
12187library directory. To build executables, @command{gnatmake} will use the
12188library rather than the individual object files. The copy of the @file{ALI}
12189files are made read-only.
12190
12191
12192@c **********************************************
12193@c * Using Third-Party Libraries through Projects
12194@c **********************************************
12195@node Using Third-Party Libraries through Projects
12196@section Using Third-Party Libraries through Projects
12197
12198Whether you are exporting your own library to make it available to
12199clients, or you are using a library provided by a third party, it is
12200convenient to have project files that automatically set the correct
12201command line switches for the compiler and linker.
12202
12203Such project files are very similar to the library project files;
12204@xref{Library Projects}. The only difference is that you set the
12205@code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12206directories where, respectively, the sources and the read-only ALI files have
12207been installed.
12208
12209If you need to interface with a set of libraries, as opposed to a
12210single one, you need to create one library project for each of the
12211libraries. In addition, a top-level project that imports all these
12212library projects should be provided, so that the user of your library
12213has a single @code{with} clause to add to his own projects.
12214
12215For instance, let's assume you are providing two static libraries
12216@file{liba.a} and @file{libb.a}. The user needs to link with
12217both of these libraries. Each of these is associated with its
12218own set of header files. Let's assume furthermore that all the
12219header files for the two libraries have been installed in the same
12220directory @file{headers}. The @file{ALI} files are found in the same
12221@file{headers} directory.
12222
12223In this case, you should provide the following three projects:
12224
12225@smallexample @c projectfile
12226@group
12227with "liba", "libb";
12228project My_Library is
12229  for Source_Dirs use ("headers");
12230  for Object_Dir  use "headers";
12231end My_Library;
12232@end group
12233
12234@group
12235project Liba is
12236   for Source_Dirs use ();
12237   for Library_Dir use "lib";
12238   for Library_Name use "a";
12239   for Library_Kind use "static";
12240end Liba;
12241@end group
12242
12243@group
12244project Libb is
12245   for Source_Dirs use ();
12246   for Library_Dir use "lib";
12247   for Library_Name use "b";
12248   for Library_Kind use "static";
12249end Libb;
12250@end group
12251@end smallexample
12252
12253@c *******************************
12254@c * Stand-alone Library Projects *
12255@c *******************************
12256
12257@node Stand-alone Library Projects
12258@section Stand-alone Library Projects
12259
12260@noindent
12261A Stand-alone Library is a library that contains the necessary code to
12262elaborate the Ada units that are included in the library. A Stand-alone
12263Library is suitable to be used in an executable when the main is not
12264in Ada. However, Stand-alone Libraries may also be used with an Ada main
12265subprogram.
12266
12267A Stand-alone Library Project is a Library Project where the library is
12268a Stand-alone Library.
12269
12270To be a Stand-alone Library Project, in addition to the two attributes
12271that make a project a Library Project (@code{Library_Name} and
12272@code{Library_Dir}, see @ref{Library Projects}), the attribute
12273@code{Library_Interface} must be defined.
12274
12275@smallexample @c projectfile
12276@group
12277   for Library_Dir use "lib_dir";
12278   for Library_Name use "dummy";
12279   for Library_Interface use ("int1", "int1.child");
12280@end group
12281@end smallexample
12282
12283Attribute @code{Library_Interface} has a non empty string list value,
12284each string in the list designating a unit contained in an immediate source
12285of the project file.
12286
12287When a Stand-alone Library is built, first the binder is invoked to build
12288a package whose name depends on the library name
12289(^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12290This binder-generated package includes initialization and
12291finalization procedures whose
12292names depend on the library name (dummyinit and dummyfinal in the example
12293above). The object corresponding to this package is included in the library.
12294
12295A dynamic or relocatable Stand-alone Library is automatically initialized
12296if automatic initialization of Stand-alone Libraries is supported on the
12297platform and if attribute @code{Library_Auto_Init} is not specified or
12298is specified with the value "true". A static Stand-alone Library is never
12299automatically initialized.
12300
12301Single string attribute @code{Library_Auto_Init} may be specified with only
12302two possible values: "false" or "true" (case-insensitive). Specifying
12303"false" for attribute @code{Library_Auto_Init} will prevent automatic
12304initialization of dynamic or relocatable libraries.
12305
12306When a non automatically initialized Stand-alone Library is used
12307in an executable, its initialization procedure must be called before
12308any service of the library is used.
12309When the main subprogram is in Ada, it may mean that the initialization
12310procedure has to be called during elaboration of another package.
12311
12312For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12313(those that are listed in attribute @code{Library_Interface}) are copied to
12314the Library Directory. As a consequence, only the Interface Units may be
12315imported from Ada units outside of the library. If other units are imported,
12316the binding phase will fail.
12317
12318When a Stand-Alone Library is bound, the switches that are specified in
12319the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12320used in the call to @command{gnatbind}.
12321
12322The string list attribute @code{Library_Options} may be used to specified
12323additional switches to the call to @command{gcc} to link the library.
12324
12325The attribute @code{Library_Src_Dir}, may be specified for a
12326Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12327single string value. Its value must be the path (absolute or relative to the
12328project directory) of an existing directory. This directory cannot be the
12329object directory or one of the source directories, but it can be the same as
12330the library directory. The sources of the Interface
12331Units of the library, necessary to an Ada client of the library, will be
12332copied to the designated directory, called Interface Copy directory.
12333These sources includes the specs of the Interface Units, but they may also
12334include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12335are used, or when there is a generic units in the spec. Before the sources
12336are copied to the Interface Copy directory, an attempt is made to delete all
12337files in the Interface Copy directory.
12338
12339@c *************************************
12340@c * Switches Related to Project Files *
12341@c *************************************
12342@node Switches Related to Project Files
12343@section Switches Related to Project Files
12344
12345@noindent
12346The following switches are used by GNAT tools that support project files:
12347
12348@table @option
12349
12350@item ^-P^/PROJECT_FILE=^@var{project}
12351@cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12352Indicates the name of a project file. This project file will be parsed with
12353the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12354if any, and using the external references indicated
12355by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12356@ifclear vms
12357There may zero, one or more spaces between @option{-P} and @var{project}.
12358@end ifclear
12359
12360@noindent
12361There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12362
12363@noindent
12364Since the Project Manager parses the project file only after all the switches
12365on the command line are checked, the order of the switches
12366@option{^-P^/PROJECT_FILE^},
12367@option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12368or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12369
12370@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12371@cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12372Indicates that external variable @var{name} has the value @var{value}.
12373The Project Manager will use this value for occurrences of
12374@code{external(name)} when parsing the project file.
12375
12376@ifclear vms
12377@noindent
12378If @var{name} or @var{value} includes a space, then @var{name=value} should be
12379put between quotes.
12380@smallexample
12381  -XOS=NT
12382  -X"user=John Doe"
12383@end smallexample
12384@end ifclear
12385
12386@noindent
12387Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12388If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12389@var{name}, only the last one is used.
12390
12391@noindent
12392An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12393takes precedence over the value of the same name in the environment.
12394
12395@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12396@cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12397@c Previous line uses code vs option command, to stay less than 80 chars
12398Indicates the verbosity of the parsing of GNAT project files.
12399
12400@ifclear vms
12401@option{-vP0} means Default;
12402@option{-vP1} means Medium;
12403@option{-vP2} means High.
12404@end ifclear
12405
12406@ifset vms
12407There are three possible options for this qualifier: DEFAULT, MEDIUM and
12408HIGH.
12409@end ifset
12410
12411@noindent
12412The default is ^Default^DEFAULT^: no output for syntactically correct
12413project files.
12414@noindent
12415If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12416only the last one is used.
12417
12418@end table
12419
12420@c **********************************
12421@c * Tools Supporting Project Files *
12422@c **********************************
12423
12424@node  Tools Supporting Project Files
12425@section Tools Supporting Project Files
12426
12427@menu
12428* gnatmake and Project Files::
12429* The GNAT Driver and Project Files::
12430@ifclear vms
12431* Glide and Project Files::
12432@end ifclear
12433@end menu
12434
12435@node gnatmake and Project Files
12436@subsection gnatmake and Project Files
12437
12438@noindent
12439This section covers several topics related to @command{gnatmake} and
12440project files: defining ^switches^switches^ for @command{gnatmake}
12441and for the tools that it invokes; specifying configuration pragmas;
12442the use of the @code{Main} attribute; building and rebuilding library project
12443files.
12444
12445@menu
12446* ^Switches^Switches^ and Project Files::
12447* Specifying Configuration Pragmas::
12448* Project Files and Main Subprograms::
12449* Library Project Files::
12450@end menu
12451
12452@node ^Switches^Switches^ and Project Files
12453@subsubsection ^Switches^Switches^ and Project Files
12454
12455@ifset vms
12456It is not currently possible to specify VMS style qualifiers in the project
12457files; only Unix style ^switches^switches^ may be specified.
12458@end ifset
12459
12460@noindent
12461For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12462@code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12463attribute, a @code{^Switches^Switches^} attribute, or both;
12464as their names imply, these ^switch^switch^-related
12465attributes affect the ^switches^switches^ that are used for each of these GNAT
12466components when
12467@command{gnatmake} is invoked.  As will be explained below, these
12468component-specific ^switches^switches^ precede
12469the ^switches^switches^ provided on the @command{gnatmake} command line.
12470
12471The @code{^Default_Switches^Default_Switches^} attribute is an associative
12472array indexed by language name (case insensitive) whose value is a string list.
12473For example:
12474
12475@smallexample @c projectfile
12476@group
12477package Compiler is
12478  for ^Default_Switches^Default_Switches^ ("Ada")
12479      use ("^-gnaty^-gnaty^",
12480           "^-v^-v^");
12481end Compiler;
12482@end group
12483@end smallexample
12484
12485@noindent
12486The @code{^Switches^Switches^} attribute is also an associative array,
12487indexed by a file name (which may or may not be case sensitive, depending
12488on the operating system) whose value is a string list.  For example:
12489
12490@smallexample @c projectfile
12491@group
12492package Builder is
12493   for ^Switches^Switches^ ("main1.adb")
12494       use ("^-O2^-O2^");
12495   for ^Switches^Switches^ ("main2.adb")
12496       use ("^-g^-g^");
12497end Builder;
12498@end group
12499@end smallexample
12500
12501@noindent
12502For the @code{Builder} package, the file names must designate source files
12503for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12504file names must designate @file{ALI} or source files for main subprograms.
12505In each case just the file name without an explicit extension is acceptable.
12506
12507For each tool used in a program build (@command{gnatmake}, the compiler, the
12508binder, and the linker), the corresponding package @dfn{contributes} a set of
12509^switches^switches^ for each file on which the tool is invoked, based on the
12510^switch^switch^-related attributes defined in the package.
12511In particular, the ^switches^switches^
12512that each of these packages contributes for a given file @var{f} comprise:
12513
12514@itemize @bullet
12515@item
12516the value of attribute @code{^Switches^Switches^ (@var{f})},
12517if it is specified in the package for the given file,
12518@item
12519otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12520if it is specified in the package.
12521@end itemize
12522
12523@noindent
12524If neither of these attributes is defined in the package, then the package does
12525not contribute any ^switches^switches^ for the given file.
12526
12527When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12528two sets, in the following order: those contributed for the file
12529by the @code{Builder} package;
12530and the switches passed on the command line.
12531
12532When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12533the ^switches^switches^ passed to the tool comprise three sets,
12534in the following order:
12535
12536@enumerate
12537@item
12538the applicable ^switches^switches^ contributed for the file
12539by the @code{Builder} package in the project file supplied on the command line;
12540
12541@item
12542those contributed for the file by the package (in the relevant project file --
12543see below) corresponding to the tool; and
12544
12545@item
12546the applicable switches passed on the command line.
12547@end enumerate
12548
12549@noindent
12550The term @emph{applicable ^switches^switches^} reflects the fact that
12551@command{gnatmake} ^switches^switches^ may or may not be passed to individual
12552tools, depending on the individual ^switch^switch^.
12553
12554@command{gnatmake} may invoke the compiler on source files from different
12555projects. The Project Manager will use the appropriate project file to
12556determine the @code{Compiler} package for each source file being compiled.
12557Likewise for the @code{Binder} and @code{Linker} packages.
12558
12559As an example, consider the following package in a project file:
12560
12561@smallexample @c projectfile
12562@group
12563project Proj1 is
12564   package Compiler is
12565      for ^Default_Switches^Default_Switches^ ("Ada")
12566          use ("^-g^-g^");
12567      for ^Switches^Switches^ ("a.adb")
12568          use ("^-O1^-O1^");
12569      for ^Switches^Switches^ ("b.adb")
12570          use ("^-O2^-O2^",
12571               "^-gnaty^-gnaty^");
12572   end Compiler;
12573end Proj1;
12574@end group
12575@end smallexample
12576
12577@noindent
12578If @command{gnatmake} is invoked with this project file, and it needs to
12579compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12580@file{a.adb} will be compiled with the ^switch^switch^
12581@option{^-O1^-O1^},
12582@file{b.adb} with ^switches^switches^
12583@option{^-O2^-O2^}
12584and @option{^-gnaty^-gnaty^},
12585and @file{c.adb} with @option{^-g^-g^}.
12586
12587The following example illustrates the ordering of the ^switches^switches^
12588contributed by different packages:
12589
12590@smallexample @c projectfile
12591@group
12592project Proj2 is
12593   package Builder is
12594      for ^Switches^Switches^ ("main.adb")
12595          use ("^-g^-g^",
12596               "^-O1^-)1^",
12597               "^-f^-f^");
12598   end Builder;
12599@end group
12600
12601@group
12602   package Compiler is
12603      for ^Switches^Switches^ ("main.adb")
12604          use ("^-O2^-O2^");
12605   end Compiler;
12606end Proj2;
12607@end group
12608@end smallexample
12609
12610@noindent
12611If you issue the command:
12612
12613@smallexample
12614    gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12615@end smallexample
12616
12617@noindent
12618then the compiler will be invoked on @file{main.adb} with the following
12619sequence of ^switches^switches^
12620
12621@smallexample
12622   ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12623@end smallexample
12624
12625with the last @option{^-O^-O^}
12626^switch^switch^ having precedence over the earlier ones;
12627several other ^switches^switches^
12628(such as @option{^-c^-c^}) are added implicitly.
12629
12630The ^switches^switches^
12631@option{^-g^-g^}
12632and @option{^-O1^-O1^} are contributed by package
12633@code{Builder},  @option{^-O2^-O2^} is contributed
12634by the package @code{Compiler}
12635and @option{^-O0^-O0^} comes from the command line.
12636
12637The @option{^-g^-g^}
12638^switch^switch^ will also be passed in the invocation of
12639@command{Gnatlink.}
12640
12641A final example illustrates switch contributions from packages in different
12642project files:
12643
12644@smallexample @c projectfile
12645@group
12646project Proj3 is
12647   for Source_Files use ("pack.ads", "pack.adb");
12648   package Compiler is
12649      for ^Default_Switches^Default_Switches^ ("Ada")
12650          use ("^-gnata^-gnata^");
12651   end Compiler;
12652end Proj3;
12653@end group
12654
12655@group
12656with "Proj3";
12657project Proj4 is
12658   for Source_Files use ("foo_main.adb", "bar_main.adb");
12659   package Builder is
12660      for ^Switches^Switches^ ("foo_main.adb")
12661          use ("^-s^-s^",
12662               "^-g^-g^");
12663   end Builder;
12664end Proj4;
12665@end group
12666
12667@group
12668-- Ada source file:
12669with Pack;
12670procedure Foo_Main is
12671   ...
12672end Foo_Main;
12673@end group
12674@end smallexample
12675
12676If the command is
12677@smallexample
12678gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12679@end smallexample
12680
12681@noindent
12682then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12683@option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12684@option{^-gnato^-gnato^} (passed on the command line).
12685When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12686are @option{^-g^-g^} from @code{Proj4.Builder},
12687@option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12688and @option{^-gnato^-gnato^} from the command line.
12689
12690@noindent
12691When using @command{gnatmake} with project files, some ^switches^switches^ or
12692arguments may be expressed as relative paths. As the working directory where
12693compilation occurs may change, these relative paths are converted to absolute
12694paths. For the ^switches^switches^ found in a project file, the relative paths
12695are relative to the project file directory, for the switches on the command
12696line, they are relative to the directory where @command{gnatmake} is invoked.
12697The ^switches^switches^ for which this occurs are:
12698^-I^-I^,
12699^-A^-A^,
12700^-L^-L^,
12701^-aO^-aO^,
12702^-aL^-aL^,
12703^-aI^-aI^, as well as all arguments that are not switches (arguments to
12704^switch^switch^
12705^-o^-o^, object files specified in package @code{Linker} or after
12706-largs on the command line). The exception to this rule is the ^switch^switch^
12707^--RTS=^--RTS=^ for which a relative path argument is never converted.
12708
12709@node Specifying Configuration Pragmas
12710@subsubsection Specifying Configuration Pragmas
12711
12712When using @command{gnatmake} with project files, if there exists a file
12713@file{gnat.adc} that contains configuration pragmas, this file will be
12714ignored.
12715
12716Configuration pragmas can be defined by means of the following attributes in
12717project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12718and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12719
12720Both these attributes are single string attributes. Their values is the path
12721name of a file containing configuration pragmas. If a path name is relative,
12722then it is relative to the project directory of the project file where the
12723attribute is defined.
12724
12725When compiling a source, the configuration pragmas used are, in order,
12726those listed in the file designated by attribute
12727@code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12728project file, if it is specified, and those listed in the file designated by
12729attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12730the project file of the source, if it exists.
12731
12732@node Project Files and Main Subprograms
12733@subsubsection Project Files and Main Subprograms
12734
12735@noindent
12736When using a project file, you can invoke @command{gnatmake}
12737with one or several main subprograms, by specifying their source files on the
12738command line.
12739
12740@smallexample
12741    gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
12742@end smallexample
12743
12744@noindent
12745Each of these needs to be a source file of the same project, except
12746when the switch ^-u^/UNIQUE^ is used.
12747
12748@noindent
12749When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12750same project, one of the project in the tree rooted at the project specified
12751on the command line. The package @code{Builder} of this common project, the
12752"main project" is the one that is considered by @command{gnatmake}.
12753
12754@noindent
12755When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12756imported directly or indirectly by the project specified on the command line.
12757Note that if such a source file is not part of the project specified on the
12758command line, the ^switches^switches^ found in package @code{Builder} of the
12759project specified on the command line, if any, that are transmitted
12760to the compiler will still be used, not those found in the project file of
12761the source file.
12762
12763@noindent
12764When using a project file, you can also invoke @command{gnatmake} without
12765explicitly specifying any main, and the effect depends on whether you have
12766defined the @code{Main} attribute.  This attribute has a string list value,
12767where each element in the list is the name of a source file (the file
12768extension is optional) that contains a unit that can be a main subprogram.
12769
12770If the @code{Main} attribute is defined in a project file as a non-empty
12771string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12772line, then invoking @command{gnatmake} with this project file but without any
12773main on the command line is equivalent to invoking @command{gnatmake} with all
12774the file names in the @code{Main} attribute on the command line.
12775
12776Example:
12777@smallexample @c projectfile
12778@group
12779   project Prj is
12780      for Main use ("main1", "main2", "main3");
12781   end Prj;
12782@end group
12783@end smallexample
12784
12785@noindent
12786With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12787is equivalent to
12788@code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
12789
12790When the project attribute @code{Main} is not specified, or is specified
12791as an empty string list, or when the switch @option{-u} is used on the command
12792line, then invoking @command{gnatmake} with no main on the command line will
12793result in all immediate sources of the project file being checked, and
12794potentially recompiled. Depending on the presence of the switch @option{-u},
12795sources from other project files on which the immediate sources of the main
12796project file depend are also checked and potentially recompiled. In other
12797words, the @option{-u} switch is applied to all of the immediate sources of the
12798main project file.
12799
12800When no main is specified on the command line and attribute @code{Main} exists
12801and includes several mains, or when several mains are specified on the
12802command line, the default ^switches^switches^ in package @code{Builder} will
12803be used for all mains, even if there are specific ^switches^switches^
12804specified for one or several mains.
12805
12806But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12807the specific ^switches^switches^ for each main, if they are specified.
12808
12809@node Library Project Files
12810@subsubsection Library Project Files
12811
12812@noindent
12813When @command{gnatmake} is invoked with a main project file that is a library
12814project file, it is not allowed to specify one or more mains on the command
12815line.
12816
12817@noindent
12818When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12819^-l^/ACTION=LINK^ have special meanings.
12820
12821@itemize @bullet
12822@item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates
12823to @command{gnatmake} that @command{gnatbind} should be invoked for the
12824library.
12825
12826@item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12827to @command{gnatmake} that the binder generated file should be compiled
12828(in the case of a stand-alone library) and that the library should be built.
12829
12830@end itemize
12831
12832@node The GNAT Driver and Project Files
12833@subsection The GNAT Driver and Project Files
12834
12835@noindent
12836A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12837are project-aware:
12838@command{^gnatbind^gnatbind^},
12839@command{^gnatfind^gnatfind^},
12840@command{^gnatlink^gnatlink^},
12841@command{^gnatls^gnatls^},
12842@command{^gnatelim^gnatelim^},
12843and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
12844directly with a project file switch (@option{^-P^"-P"^}).
12845They must be invoked through the @command{gnat} driver.
12846
12847The @command{gnat} driver is a front-end that accepts a number of commands and
12848call the corresponding tool. It has been designed initially for VMS to convert
12849VMS style qualifiers to Unix style switches, but it is now available to all
12850the GNAT supported platforms.
12851
12852On non VMS platforms, the @command{gnat} driver accepts the following commands
12853(case insensitive):
12854
12855@itemize @bullet
12856@item
12857BIND to invoke @command{^gnatbind^gnatbind^}
12858@item
12859CHOP to invoke @command{^gnatchop^gnatchop^}
12860@item
12861CLEAN to invoke @command{^gnatclean^gnatclean^}
12862@item
12863COMP or COMPILE to invoke the compiler
12864@item
12865ELIM to invoke @command{^gnatelim^gnatelim^}
12866@item
12867FIND to invoke @command{^gnatfind^gnatfind^}
12868@item
12869KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12870@item
12871LINK to invoke @command{^gnatlink^gnatlink^}
12872@item
12873LS or LIST to invoke @command{^gnatls^gnatls^}
12874@item
12875MAKE to invoke @command{^gnatmake^gnatmake^}
12876@item
12877NAME to invoke @command{^gnatname^gnatname^}
12878@item
12879PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12880@item
12881PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12882@item
12883STUB to invoke @command{^gnatstub^gnatstub^}
12884@item
12885XREF to invoke @command{^gnatxref^gnatxref^}
12886@end itemize
12887
12888@noindent
12889Note that the compiler is invoked using the command
12890@command{^gnatmake -f -u -c^gnatmake -f -u -c^}.
12891
12892@noindent
12893The command may be followed by switches and arguments for the invoked
12894tool.
12895
12896@smallexample
12897  gnat bind -C main.ali
12898  gnat ls -a main
12899  gnat chop foo.txt
12900@end smallexample
12901
12902@noindent
12903In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12904PP or PRETTY and XREF, the project file related switches
12905(@option{^-P^/PROJECT_FILE^},
12906@option{^-X^/EXTERNAL_REFERENCE^} and
12907@option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12908the switches of the invoking tool.
12909
12910@noindent
12911For each of these commands, there is optionally a corresponding  package
12912in the main project.
12913
12914@itemize @bullet
12915@item
12916package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12917
12918@item
12919package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12920
12921@item
12922package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12923
12924@item
12925package @code{Eliminate} for command ELIM (invoking
12926@code{^gnatelim^gnatelim^})
12927
12928@item
12929package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12930
12931@item
12932package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12933
12934@item
12935package @code{Pretty_Printer} for command PP or PRETTY
12936(invoking @code{^gnatpp^gnatpp^})
12937
12938@item
12939package @code{Cross_Reference} for command XREF (invoking
12940@code{^gnatxref^gnatxref^})
12941
12942@end itemize
12943
12944@noindent
12945Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
12946a simple variable with a string list value. It contains ^switches^switches^
12947for the invocation of @code{^gnatls^gnatls^}.
12948
12949@smallexample @c projectfile
12950@group
12951project Proj1 is
12952   package gnatls is
12953      for ^Switches^Switches^
12954          use ("^-a^-a^",
12955               "^-v^-v^");
12956   end gnatls;
12957end Proj1;
12958@end group
12959@end smallexample
12960
12961@noindent
12962All other packages have two attribute @code{^Switches^Switches^} and
12963@code{^Default_Switches^Default_Switches^}.
12964
12965@noindent
12966@code{^Switches^Switches^} is an associated array attribute, indexed by the
12967source file name, that has a string list value: the ^switches^switches^ to be
12968used when the tool corresponding to the package is invoked for the specific
12969source file.
12970
12971@noindent
12972@code{^Default_Switches^Default_Switches^} is an associative array attribute,
12973indexed by  the programming language that has a string list value.
12974@code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12975^switches^switches^ for the invocation of the tool corresponding
12976to the package, except if a specific @code{^Switches^Switches^} attribute
12977is specified for the source file.
12978
12979@smallexample @c projectfile
12980@group
12981project Proj is
12982
12983   for Source_Dirs use ("./**");
12984
12985   package gnatls is
12986      for ^Switches^Switches^ use
12987          ("^-a^-a^",
12988           "^-v^-v^");
12989   end gnatls;
12990@end group
12991@group
12992
12993   package Compiler is
12994      for ^Default_Switches^Default_Switches^ ("Ada")
12995          use ("^-gnatv^-gnatv^",
12996               "^-gnatwa^-gnatwa^");
12997   end Binder;
12998@end group
12999@group
13000
13001   package Binder is
13002      for ^Default_Switches^Default_Switches^ ("Ada")
13003          use ("^-C^-C^",
13004               "^-e^-e^");
13005   end Binder;
13006@end group
13007@group
13008
13009   package Linker is
13010      for ^Default_Switches^Default_Switches^ ("Ada")
13011          use ("^-C^-C^");
13012      for ^Switches^Switches^ ("main.adb")
13013          use ("^-C^-C^",
13014               "^-v^-v^",
13015               "^-v^-v^");
13016   end Linker;
13017@end group
13018@group
13019
13020   package Finder is
13021      for ^Default_Switches^Default_Switches^ ("Ada")
13022           use ("^-a^-a^",
13023                "^-f^-f^");
13024   end Finder;
13025@end group
13026@group
13027
13028   package Cross_Reference is
13029      for ^Default_Switches^Default_Switches^ ("Ada")
13030          use ("^-a^-a^",
13031               "^-f^-f^",
13032               "^-d^-d^",
13033               "^-u^-u^");
13034   end Cross_Reference;
13035end Proj;
13036@end group
13037@end smallexample
13038
13039@noindent
13040With the above project file, commands such as
13041
13042@smallexample
13043   ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13044   ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13045   ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13046   ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13047   ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13048@end smallexample
13049
13050@noindent
13051will set up the environment properly and invoke the tool with the switches
13052found in the package corresponding to the tool:
13053@code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13054except @code{^Switches^Switches^ ("main.adb")}
13055for @code{^gnatlink^gnatlink^}.
13056
13057@ifclear vms
13058@node Glide and Project Files
13059@subsection Glide and Project Files
13060
13061@noindent
13062Glide will automatically recognize the @file{.gpr} extension for
13063project files, and will
13064convert them to its own internal format automatically. However, it
13065doesn't provide a syntax-oriented editor for modifying these
13066files.
13067The project file will be loaded as text when you select the menu item
13068@code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13069You can edit this text and save the @file{gpr} file;
13070when you next select this project file in Glide it
13071will be automatically reloaded.
13072@end ifclear
13073
13074@c **********************
13075@node An Extended Example
13076@section An Extended Example
13077
13078@noindent
13079Suppose that we have two programs, @var{prog1} and @var{prog2},
13080whose sources are in corresponding directories. We would like
13081to build them with a single @command{gnatmake} command, and we want to place
13082their object files into @file{build} subdirectories of the source directories.
13083Furthermore, we want to have to have two separate subdirectories
13084in @file{build}  -- @file{release} and @file{debug} -- which will contain
13085the object files compiled with different set of compilation flags.
13086
13087In other words, we have the following structure:
13088
13089@smallexample
13090@group
13091   main
13092     |- prog1
13093     |    |- build
13094     |         | debug
13095     |         | release
13096     |- prog2
13097          |- build
13098               | debug
13099               | release
13100@end group
13101@end smallexample
13102
13103@noindent
13104Here are the project files that we must place in a directory @file{main}
13105to maintain this structure:
13106
13107@enumerate
13108
13109@item We create a @code{Common} project with a package @code{Compiler} that
13110specifies the compilation ^switches^switches^:
13111
13112@smallexample
13113File "common.gpr":
13114@group
13115@b{project} Common @b{is}
13116
13117   @b{for} Source_Dirs @b{use} (); -- No source files
13118@end group
13119
13120@group
13121   @b{type} Build_Type @b{is} ("release", "debug");
13122   Build : Build_Type := External ("BUILD", "debug");
13123@end group
13124@group
13125   @b{package} Compiler @b{is}
13126      @b{case} Build @b{is}
13127         @b{when} "release" =>
13128           @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13129                   @b{use} ("^-O2^-O2^");
13130         @b{when} "debug"   =>
13131           @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13132                   @b{use} ("^-g^-g^");
13133      @b{end case};
13134   @b{end} Compiler;
13135
13136@b{end} Common;
13137@end group
13138@end smallexample
13139
13140@item We create separate projects for the two programs:
13141
13142@smallexample
13143@group
13144File "prog1.gpr":
13145
13146@b{with} "common";
13147@b{project} Prog1 @b{is}
13148
13149    @b{for} Source_Dirs @b{use} ("prog1");
13150    @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13151
13152    @b{package} Compiler @b{renames} Common.Compiler;
13153
13154@b{end} Prog1;
13155@end group
13156@end smallexample
13157
13158@smallexample
13159@group
13160File "prog2.gpr":
13161
13162@b{with} "common";
13163@b{project} Prog2 @b{is}
13164
13165    @b{for} Source_Dirs @b{use} ("prog2");
13166    @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13167
13168    @b{package} Compiler @b{renames} Common.Compiler;
13169
13170@end group
13171@b{end} Prog2;
13172@end smallexample
13173
13174@item We create a wrapping project @code{Main}:
13175
13176@smallexample
13177@group
13178File "main.gpr":
13179
13180@b{with} "common";
13181@b{with} "prog1";
13182@b{with} "prog2";
13183@b{project} Main @b{is}
13184
13185   @b{package} Compiler @b{renames} Common.Compiler;
13186
13187@b{end} Main;
13188@end group
13189@end smallexample
13190
13191@item Finally we need to create a dummy procedure that @code{with}s (either
13192explicitly or implicitly) all the sources of our two programs.
13193
13194@end enumerate
13195
13196@noindent
13197Now we can build the programs using the command
13198
13199@smallexample
13200   gnatmake ^-P^/PROJECT_FILE=^main dummy
13201@end smallexample
13202
13203@noindent
13204for the Debug mode, or
13205
13206@ifclear vms
13207@smallexample
13208   gnatmake -Pmain -XBUILD=release
13209@end smallexample
13210@end ifclear
13211
13212@ifset vms
13213@smallexample
13214   GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13215@end smallexample
13216@end ifset
13217
13218@noindent
13219for the Release mode.
13220
13221@c ********************************
13222@c * Project File Complete Syntax *
13223@c ********************************
13224
13225@node Project File Complete Syntax
13226@section Project File Complete Syntax
13227
13228@smallexample
13229project ::=
13230  context_clause project_declaration
13231
13232context_clause ::=
13233  @{with_clause@}
13234
13235with_clause ::=
13236  @b{with} path_name @{ , path_name @} ;
13237
13238path_name ::=
13239   string_literal
13240
13241project_declaration ::=
13242  simple_project_declaration | project_extension
13243
13244simple_project_declaration ::=
13245  @b{project} <project_>simple_name @b{is}
13246    @{declarative_item@}
13247  @b{end} <project_>simple_name;
13248
13249project_extension ::=
13250  @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13251    @{declarative_item@}
13252  @b{end} <project_>simple_name;
13253
13254declarative_item ::=
13255  package_declaration |
13256  typed_string_declaration |
13257  other_declarative_item
13258
13259package_declaration ::=
13260  package_specification | package_renaming
13261
13262package_specification ::=
13263  @b{package} package_identifier @b{is}
13264    @{simple_declarative_item@}
13265  @b{end} package_identifier ;
13266
13267package_identifier ::=
13268  @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13269  @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13270  @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13271
13272package_renaming ::==
13273  @b{package} package_identifier @b{renames}
13274       <project_>simple_name.package_identifier ;
13275
13276typed_string_declaration ::=
13277  @b{type} <typed_string_>_simple_name @b{is}
13278   ( string_literal @{, string_literal@} );
13279
13280other_declarative_item ::=
13281  attribute_declaration |
13282  typed_variable_declaration |
13283  variable_declaration |
13284  case_construction
13285
13286attribute_declaration ::=
13287  full_associative_array_declaration |
13288  @b{for} attribute_designator @b{use} expression ;
13289
13290full_associative_array_declaration ::=
13291  @b{for} <associative_array_attribute_>simple_name @b{use}
13292  <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13293
13294attribute_designator ::=
13295  <simple_attribute_>simple_name |
13296  <associative_array_attribute_>simple_name ( string_literal )
13297
13298typed_variable_declaration ::=
13299  <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13300
13301variable_declaration ::=
13302  <variable_>simple_name := expression;
13303
13304expression ::=
13305  term @{& term@}
13306
13307term ::=
13308  literal_string |
13309  string_list |
13310  <variable_>name |
13311  external_value |
13312  attribute_reference
13313
13314string_literal ::=
13315  (same as Ada)
13316
13317string_list ::=
13318  ( <string_>expression @{ , <string_>expression @} )
13319
13320external_value ::=
13321  @b{external} ( string_literal [, string_literal] )
13322
13323attribute_reference ::=
13324  attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13325
13326attribute_prefix ::=
13327  @b{project} |
13328  <project_>simple_name | package_identifier |
13329  <project_>simple_name . package_identifier
13330
13331case_construction ::=
13332  @b{case} <typed_variable_>name @b{is}
13333    @{case_item@}
13334  @b{end case} ;
13335
13336case_item ::=
13337  @b{when} discrete_choice_list =>
13338      @{case_construction | attribute_declaration@}
13339
13340discrete_choice_list ::=
13341  string_literal @{| string_literal@} |
13342  @b{others}
13343
13344name ::=
13345  simple_name @{. simple_name@}
13346
13347simple_name ::=
13348  identifier (same as Ada)
13349
13350@end smallexample
13351
13352
13353@node The Cross-Referencing Tools gnatxref and gnatfind
13354@chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13355@findex gnatxref
13356@findex gnatfind
13357
13358@noindent
13359The compiler generates cross-referencing information (unless
13360you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13361This information indicates where in the source each entity is declared and
13362referenced. Note that entities in package Standard are not included, but
13363entities in all other predefined units are included in the output.
13364
13365Before using any of these two tools, you need to compile successfully your
13366application, so that GNAT gets a chance to generate the cross-referencing
13367information.
13368
13369The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13370information to provide the user with the capability to easily locate the
13371declaration and references to an entity. These tools are quite similar,
13372the difference being that @code{gnatfind} is intended for locating
13373definitions and/or references to a specified entity or entities, whereas
13374@code{gnatxref} is oriented to generating a full report of all
13375cross-references.
13376
13377To use these tools, you must not compile your application using the
13378@option{-gnatx} switch on the @file{gnatmake} command line
13379(see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13380information will not be generated.
13381
13382@menu
13383* gnatxref Switches::
13384* gnatfind Switches::
13385* Project Files for gnatxref and gnatfind::
13386* Regular Expressions in gnatfind and gnatxref::
13387* Examples of gnatxref Usage::
13388* Examples of gnatfind Usage::
13389@end menu
13390
13391@node gnatxref Switches
13392@section @code{gnatxref} Switches
13393
13394@noindent
13395The command invocation for @code{gnatxref} is:
13396@smallexample
13397$ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13398@end smallexample
13399
13400@noindent
13401where
13402
13403@table @code
13404@item sourcefile1, sourcefile2
13405identifies the source files for which a report is to be generated. The
13406``with''ed units will be processed too. You must provide at least one file.
13407
13408These file names are considered to be regular expressions, so for instance
13409specifying @file{source*.adb} is the same as giving every file in the current
13410directory whose name starts with @file{source} and whose extension is
13411@file{adb}.
13412
13413@end table
13414
13415@noindent
13416The switches can be :
13417@table @option
13418@c !sort!
13419@item ^-a^/ALL_FILES^
13420@cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13421If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13422the read-only files found in the library search path. Otherwise, these files
13423will be ignored. This option can be used to protect Gnat sources or your own
13424libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13425much faster, and their output much smaller. Read-only here refers to access
13426or permissions status in the file system for the current user.
13427
13428@item -aIDIR
13429@cindex @option{-aIDIR} (@command{gnatxref})
13430When looking for source files also look in directory DIR. The order in which
13431source file search is undertaken is the same as for @file{gnatmake}.
13432
13433@item -aODIR
13434@cindex @option{-aODIR} (@command{gnatxref})
13435When searching for library and object files, look in directory
13436DIR. The order in which library files are searched is the same as for
13437@file{gnatmake}.
13438
13439@item -nostdinc
13440@cindex @option{-nostdinc} (@command{gnatxref})
13441Do not look for sources in the system default directory.
13442
13443@item -nostdlib
13444@cindex @option{-nostdlib} (@command{gnatxref})
13445Do not look for library files in the system default directory.
13446
13447@item --RTS=@var{rts-path}
13448@cindex @option{--RTS} (@command{gnatxref})
13449Specifies the default location of the runtime library. Same meaning as the
13450equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13451
13452@item ^-d^/DERIVED_TYPES^
13453@cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13454If this switch is set @code{gnatxref} will output the parent type
13455reference for each matching derived types.
13456
13457@item ^-f^/FULL_PATHNAME^
13458@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13459If this switch is set, the output file names will be preceded by their
13460directory (if the file was found in the search path). If this switch is
13461not set, the directory will not be printed.
13462
13463@item ^-g^/IGNORE_LOCALS^
13464@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13465If this switch is set, information is output only for library-level
13466entities, ignoring local entities. The use of this switch may accelerate
13467@code{gnatfind} and @code{gnatxref}.
13468
13469@item -IDIR
13470@cindex @option{-IDIR} (@command{gnatxref})
13471Equivalent to @samp{-aODIR -aIDIR}.
13472
13473@item -pFILE
13474@cindex @option{-pFILE} (@command{gnatxref})
13475Specify a project file to use @xref{Project Files}. These project files are
13476the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13477project files, you should use gnatxref through the GNAT driver
13478(@command{gnat xref -Pproject}).
13479
13480By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13481project file in the current directory.
13482
13483If a project file is either specified or found by the tools, then the content
13484of the source directory and object directory lines are added as if they
13485had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13486and @samp{^-aO^OBJECT_SEARCH^}.
13487@item ^-u^/UNUSED^
13488Output only unused symbols. This may be really useful if you give your
13489main compilation unit on the command line, as @code{gnatxref} will then
13490display every unused entity and 'with'ed package.
13491
13492@ifclear vms
13493@item -v
13494Instead of producing the default output, @code{gnatxref} will generate a
13495@file{tags} file that can be used by vi. For examples how to use this
13496feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13497to the standard output, thus you will have to redirect it to a file.
13498@end ifclear
13499
13500@end table
13501
13502@noindent
13503All these switches may be in any order on the command line, and may even
13504appear after the file names. They need not be separated by spaces, thus
13505you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13506@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13507
13508@node gnatfind Switches
13509@section @code{gnatfind} Switches
13510
13511@noindent
13512The command line for @code{gnatfind} is:
13513
13514@smallexample
13515$ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13516      [file1 file2 ...]
13517@end smallexample
13518
13519@noindent
13520where
13521
13522@table @code
13523@item pattern
13524An entity will be output only if it matches the regular expression found
13525in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13526
13527Omitting the pattern is equivalent to specifying @samp{*}, which
13528will match any entity. Note that if you do not provide a pattern, you
13529have to provide both a sourcefile and a line.
13530
13531Entity names are given in Latin-1, with uppercase/lowercase equivalence
13532for matching purposes. At the current time there is no support for
135338-bit codes other than Latin-1, or for wide characters in identifiers.
13534
13535@item sourcefile
13536@code{gnatfind} will look for references, bodies or declarations
13537of symbols referenced in @file{sourcefile}, at line @samp{line}
13538and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13539for syntax examples.
13540
13541@item line
13542is a decimal integer identifying the line number containing
13543the reference to the entity (or entities) to be located.
13544
13545@item column
13546is a decimal integer identifying the exact location on the
13547line of the first character of the identifier for the
13548entity reference. Columns are numbered from 1.
13549
13550@item file1 file2 ...
13551The search will be restricted to these source files. If none are given, then
13552the search will be done for every library file in the search path.
13553These file must appear only after the pattern or sourcefile.
13554
13555These file names are considered to be regular expressions, so for instance
13556specifying 'source*.adb' is the same as giving every file in the current
13557directory whose name starts with 'source' and whose extension is 'adb'.
13558
13559The location of the spec of the entity will always be displayed, even if it
13560isn't in one of file1, file2,... The occurrences of the entity in the
13561separate units of the ones given on the command line will also be displayed.
13562
13563Note that if you specify at least one file in this part, @code{gnatfind} may
13564sometimes not be able to find the body of the subprograms...
13565
13566@end table
13567
13568@noindent
13569At least one of 'sourcefile' or 'pattern' has to be present on
13570the command line.
13571
13572The following switches are available:
13573@table @option
13574@c !sort!
13575
13576@item ^-a^/ALL_FILES^
13577@cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13578If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13579the read-only files found in the library search path. Otherwise, these files
13580will be ignored. This option can be used to protect Gnat sources or your own
13581libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13582much faster, and their output much smaller. Read-only here refers to access
13583or permission status in the file system for the current user.
13584
13585@item -aIDIR
13586@cindex @option{-aIDIR} (@command{gnatfind})
13587When looking for source files also look in directory DIR. The order in which
13588source file search is undertaken is the same as for @file{gnatmake}.
13589
13590@item -aODIR
13591@cindex @option{-aODIR} (@command{gnatfind})
13592When searching for library and object files, look in directory
13593DIR. The order in which library files are searched is the same as for
13594@file{gnatmake}.
13595
13596@item -nostdinc
13597@cindex @option{-nostdinc} (@command{gnatfind})
13598Do not look for sources in the system default directory.
13599
13600@item -nostdlib
13601@cindex @option{-nostdlib} (@command{gnatfind})
13602Do not look for library files in the system default directory.
13603
13604@item --RTS=@var{rts-path}
13605@cindex @option{--RTS} (@command{gnatfind})
13606Specifies the default location of the runtime library. Same meaning as the
13607equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13608
13609@item ^-d^/DERIVED_TYPE_INFORMATION^
13610@cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13611If this switch is set, then @code{gnatfind} will output the parent type
13612reference for each matching derived types.
13613
13614@item ^-e^/EXPRESSIONS^
13615@cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13616By default, @code{gnatfind} accept the simple regular expression set for
13617@samp{pattern}. If this switch is set, then the pattern will be
13618considered as full Unix-style regular expression.
13619
13620@item ^-f^/FULL_PATHNAME^
13621@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13622If this switch is set, the output file names will be preceded by their
13623directory (if the file was found in the search path). If this switch is
13624not set, the directory will not be printed.
13625
13626@item ^-g^/IGNORE_LOCALS^
13627@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13628If this switch is set, information is output only for library-level
13629entities, ignoring local entities. The use of this switch may accelerate
13630@code{gnatfind} and @code{gnatxref}.
13631
13632@item -IDIR
13633@cindex @option{-IDIR} (@command{gnatfind})
13634Equivalent to @samp{-aODIR -aIDIR}.
13635
13636@item -pFILE
13637@cindex @option{-pFILE} (@command{gnatfind})
13638Specify a project file (@pxref{Project Files}) to use.
13639By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13640project file in the current directory.
13641
13642If a project file is either specified or found by the tools, then the content
13643of the source directory and object directory lines are added as if they
13644had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13645@samp{^-aO^/OBJECT_SEARCH^}.
13646
13647@item ^-r^/REFERENCES^
13648@cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13649By default, @code{gnatfind} will output only the information about the
13650declaration, body or type completion of the entities. If this switch is
13651set, the @code{gnatfind} will locate every reference to the entities in
13652the files specified on the command line (or in every file in the search
13653path if no file is given on the command line).
13654
13655@item ^-s^/PRINT_LINES^
13656@cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13657If this switch is set, then @code{gnatfind} will output the content
13658of the Ada source file lines were the entity was found.
13659
13660@item ^-t^/TYPE_HIERARCHY^
13661@cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13662If this switch is set, then @code{gnatfind} will output the type hierarchy for
13663the specified type. It act like -d option but recursively from parent
13664type to parent type. When this switch is set it is not possible to
13665specify more than one file.
13666
13667@end table
13668
13669@noindent
13670All these switches may be in any order on the command line, and may even
13671appear after the file names. They need not be separated by spaces, thus
13672you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13673@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13674
13675As stated previously, gnatfind will search in every directory in the
13676search path. You can force it to look only in the current directory if
13677you specify @code{*} at the end of the command line.
13678
13679@node Project Files for gnatxref and gnatfind
13680@section Project Files for @command{gnatxref} and @command{gnatfind}
13681
13682@noindent
13683Project files allow a programmer to specify how to compile its
13684application, where to find sources, etc.  These files are used
13685@ifclear vms
13686primarily by the Glide Ada mode, but they can also be used
13687@end ifclear
13688by the two tools
13689@code{gnatxref} and @code{gnatfind}.
13690
13691A project file name must end with @file{.gpr}. If a single one is
13692present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13693extract the information from it. If multiple project files are found, none of
13694them is read, and you have to use the @samp{-p} switch to specify the one
13695you want to use.
13696
13697The following lines can be included, even though most of them have default
13698values which can be used in most cases.
13699The lines can be entered in any order in the file.
13700Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13701each line. If you have multiple instances, only the last one is taken into
13702account.
13703
13704@table @code
13705@item src_dir=DIR
13706[default: @code{"^./^[]^"}]
13707specifies a directory where to look for source files. Multiple @code{src_dir}
13708lines can be specified and they will be searched in the order they
13709are specified.
13710
13711@item obj_dir=DIR
13712[default: @code{"^./^[]^"}]
13713specifies a directory where to look for object and library files. Multiple
13714@code{obj_dir} lines can be specified, and they will be searched in the order
13715they are specified
13716
13717@item comp_opt=SWITCHES
13718[default: @code{""}]
13719creates a variable which can be referred to subsequently by using
13720the @code{$@{comp_opt@}} notation. This is intended to store the default
13721switches given to @command{gnatmake} and @command{gcc}.
13722
13723@item bind_opt=SWITCHES
13724[default: @code{""}]
13725creates a variable which can be referred to subsequently by using
13726the @samp{$@{bind_opt@}} notation. This is intended to store the default
13727switches given to @command{gnatbind}.
13728
13729@item link_opt=SWITCHES
13730[default: @code{""}]
13731creates a variable which can be referred to subsequently by using
13732the @samp{$@{link_opt@}} notation. This is intended to store the default
13733switches given to @command{gnatlink}.
13734
13735@item main=EXECUTABLE
13736[default: @code{""}]
13737specifies the name of the executable for the application. This variable can
13738be referred to in the following lines by using the @samp{$@{main@}} notation.
13739
13740@ifset vms
13741@item comp_cmd=COMMAND
13742[default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13743@end ifset
13744@ifclear vms
13745@item comp_cmd=COMMAND
13746[default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13747@end ifclear
13748specifies the command used to compile a single file in the application.
13749
13750@ifset vms
13751@item make_cmd=COMMAND
13752[default: @code{"GNAT MAKE $@{main@}
13753/SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13754/DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13755/BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13756@end ifset
13757@ifclear vms
13758@item make_cmd=COMMAND
13759[default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13760 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13761 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13762@end ifclear
13763specifies the command used to recompile the whole application.
13764
13765@item run_cmd=COMMAND
13766[default: @code{"$@{main@}"}]
13767specifies the command used to run the application.
13768
13769@item debug_cmd=COMMAND
13770[default: @code{"gdb $@{main@}"}]
13771specifies the command used to debug the application
13772
13773@end table
13774
13775@noindent
13776@command{gnatxref} and @command{gnatfind} only take into account the
13777@code{src_dir} and @code{obj_dir} lines, and ignore the others.
13778
13779@node Regular Expressions in gnatfind and gnatxref
13780@section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13781
13782@noindent
13783As specified in the section about @command{gnatfind}, the pattern can be a
13784regular expression. Actually, there are to set of regular expressions
13785which are recognized by the program :
13786
13787@table @code
13788@item globbing patterns
13789These are the most usual regular expression. They are the same that you
13790generally used in a Unix shell command line, or in a DOS session.
13791
13792Here is a more formal grammar :
13793@smallexample
13794@group
13795@iftex
13796@leftskip=.5cm
13797@end iftex
13798regexp ::= term
13799term   ::= elmt            -- matches elmt
13800term   ::= elmt elmt       -- concatenation (elmt then elmt)
13801term   ::= *               -- any string of 0 or more characters
13802term   ::= ?               -- matches any character
13803term   ::= [char @{char@}] -- matches any character listed
13804term   ::= [char - char]   -- matches any character in range
13805@end group
13806@end smallexample
13807
13808@item full regular expression
13809The second set of regular expressions is much more powerful. This is the
13810type of regular expressions recognized by utilities such a @file{grep}.
13811
13812The following is the form of a regular expression, expressed in Ada
13813reference manual style BNF is as follows
13814
13815@smallexample
13816@iftex
13817@leftskip=.5cm
13818@end iftex
13819@group
13820regexp ::= term @{| term@} -- alternation (term or term ...)
13821
13822term ::= item @{item@}     -- concatenation (item then item)
13823
13824item ::= elmt              -- match elmt
13825item ::= elmt *            -- zero or more elmt's
13826item ::= elmt +            -- one or more elmt's
13827item ::= elmt ?            -- matches elmt or nothing
13828@end group
13829@group
13830elmt ::= nschar            -- matches given character
13831elmt ::= [nschar @{nschar@}]   -- matches any character listed
13832elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13833elmt ::= [char - char]     -- matches chars in given range
13834elmt ::= \ char            -- matches given character
13835elmt ::= .                 -- matches any single character
13836elmt ::= ( regexp )        -- parens used for grouping
13837
13838char ::= any character, including special characters
13839nschar ::= any character except ()[].*+?^^^
13840@end group
13841@end smallexample
13842
13843Following are a few examples :
13844
13845@table @samp
13846@item abcde|fghi
13847will match any of the two strings 'abcde' and 'fghi'.
13848
13849@item abc*d
13850will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13851
13852@item [a-z]+
13853will match any string which has only lowercase characters in it (and at
13854least one character
13855
13856@end table
13857@end table
13858
13859@node Examples of gnatxref Usage
13860@section Examples of @code{gnatxref} Usage
13861
13862@subsection General Usage
13863
13864@noindent
13865For the following examples, we will consider the following units :
13866
13867@smallexample @c ada
13868@group
13869@cartouche
13870main.ads:
138711: with Bar;
138722: package Main is
138733:     procedure Foo (B : in Integer);
138744:     C : Integer;
138755: private
138766:     D : Integer;
138777: end Main;
13878
13879main.adb:
138801: package body Main is
138812:     procedure Foo (B : in Integer) is
138823:     begin
138834:        C := B;
138845:        D := B;
138856:        Bar.Print (B);
138867:        Bar.Print (C);
138878:     end Foo;
138889: end Main;
13889
13890bar.ads:
138911: package Bar is
138922:     procedure Print (B : Integer);
138933: end bar;
13894@end cartouche
13895@end group
13896@end smallexample
13897
13898@table @code
13899
13900@noindent
13901The first thing to do is to recompile your application (for instance, in
13902that case just by doing a @samp{gnatmake main}, so that GNAT generates
13903the cross-referencing information.
13904You can then issue any of the following commands:
13905
13906@item gnatxref main.adb
13907@code{gnatxref} generates cross-reference information for main.adb
13908and every unit 'with'ed by main.adb.
13909
13910The output would be:
13911@smallexample
13912@iftex
13913@leftskip=0cm
13914@end iftex
13915B                                                      Type: Integer
13916  Decl: bar.ads           2:22
13917B                                                      Type: Integer
13918  Decl: main.ads          3:20
13919  Body: main.adb          2:20
13920  Ref:  main.adb          4:13     5:13     6:19
13921Bar                                                    Type: Unit
13922  Decl: bar.ads           1:9
13923  Ref:  main.adb          6:8      7:8
13924       main.ads           1:6
13925C                                                      Type: Integer
13926  Decl: main.ads          4:5
13927  Modi: main.adb          4:8
13928  Ref:  main.adb          7:19
13929D                                                      Type: Integer
13930  Decl: main.ads          6:5
13931  Modi: main.adb          5:8
13932Foo                                                    Type: Unit
13933  Decl: main.ads          3:15
13934  Body: main.adb          2:15
13935Main                                                    Type: Unit
13936  Decl: main.ads          2:9
13937  Body: main.adb          1:14
13938Print                                                   Type: Unit
13939  Decl: bar.ads           2:15
13940  Ref:  main.adb          6:12     7:12
13941@end smallexample
13942
13943@noindent
13944that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13945its body is in main.adb, line 1, column 14 and is not referenced any where.
13946
13947The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13948it referenced in main.adb, line 6 column 12 and line 7 column 12.
13949
13950@item gnatxref package1.adb package2.ads
13951@code{gnatxref} will generates cross-reference information for
13952package1.adb, package2.ads and any other package 'with'ed by any
13953of these.
13954
13955@end table
13956
13957@ifclear vms
13958@subsection Using gnatxref with vi
13959
13960@code{gnatxref} can generate a tags file output, which can be used
13961directly from @file{vi}. Note that the standard version of @file{vi}
13962will not work properly with overloaded symbols. Consider using another
13963free implementation of @file{vi}, such as @file{vim}.
13964
13965@smallexample
13966$ gnatxref -v gnatfind.adb > tags
13967@end smallexample
13968
13969@noindent
13970will generate the tags file for @code{gnatfind} itself (if the sources
13971are in the search path!).
13972
13973From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13974(replacing @i{entity} by whatever you are looking for), and vi will
13975display a new file with the corresponding declaration of entity.
13976@end ifclear
13977
13978@node Examples of gnatfind Usage
13979@section Examples of @code{gnatfind} Usage
13980
13981@table @code
13982
13983@item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13984Find declarations for all entities xyz referenced at least once in
13985main.adb. The references are search in every library file in the search
13986path.
13987
13988The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13989switch is set)
13990
13991The output will look like:
13992@smallexample
13993^directory/^[directory]^main.ads:106:14: xyz <= declaration
13994^directory/^[directory]^main.adb:24:10: xyz <= body
13995^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13996@end smallexample
13997
13998@noindent
13999that is to say, one of the entities xyz found in main.adb is declared at
14000line 12 of main.ads (and its body is in main.adb), and another one is
14001declared at line 45 of foo.ads
14002
14003@item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14004This is the same command as the previous one, instead @code{gnatfind} will
14005display the content of the Ada source file lines.
14006
14007The output will look like:
14008
14009@smallexample
14010^directory/^[directory]^main.ads:106:14: xyz <= declaration
14011   procedure xyz;
14012^directory/^[directory]^main.adb:24:10: xyz <= body
14013   procedure xyz is
14014^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14015   xyz : Integer;
14016@end smallexample
14017
14018@noindent
14019This can make it easier to find exactly the location your are looking
14020for.
14021
14022@item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14023Find references to all entities containing an x that are
14024referenced on line 123 of main.ads.
14025The references will be searched only in main.ads and foo.adb.
14026
14027@item gnatfind main.ads:123
14028Find declarations and bodies for all entities that are referenced on
14029line 123 of main.ads.
14030
14031This is the same as @code{gnatfind "*":main.adb:123}.
14032
14033@item gnatfind ^mydir/^[mydir]^main.adb:123:45
14034Find the declaration for the entity referenced at column 45 in
14035line 123 of file main.adb in directory mydir. Note that it
14036is usual to omit the identifier name when the column is given,
14037since the column position identifies a unique reference.
14038
14039The column has to be the beginning of the identifier, and should not
14040point to any character in the middle of the identifier.
14041
14042@end table
14043
14044
14045@c *********************************
14046@node The GNAT Pretty-Printer gnatpp
14047@chapter The GNAT Pretty-Printer @command{gnatpp}
14048@findex gnatpp
14049@cindex Pretty-Printer
14050
14051@noindent
14052^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14053for source reformatting / pretty-printing.
14054It takes an Ada source file as input and generates a reformatted
14055version as output.
14056You can specify various style directives via switches; e.g.,
14057identifier case conventions, rules of indentation, and comment layout.
14058
14059To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14060tree for the input source and thus requires the input to be syntactically and
14061semantically legal.
14062If this condition is not met, @command{gnatpp} will terminate with an
14063error message; no output file will be generated.
14064
14065If the compilation unit
14066contained in the input source depends semantically upon units located
14067outside the current directory, you have to provide the source search path
14068when invoking @command{gnatpp}; see the description of the @command{gnatpp}
14069switches below.
14070
14071The @command{gnatpp} command has the form
14072
14073@smallexample
14074$ gnatpp [@var{switches}] @var{filename}
14075@end smallexample
14076
14077@noindent
14078where
14079@itemize @bullet
14080@item
14081@var{switches} is an optional sequence of switches defining such properties as
14082the formatting rules, the source search path, and the destination for the
14083output source file
14084
14085@item
14086@var{filename} is the name (including the extension) of the source file to
14087reformat; ``wildcards'' are not permitted.  The file name may contain path
14088information; it does not have to follow the GNAT file naming rules
14089@end itemize
14090
14091
14092@menu
14093* Switches for gnatpp::
14094* Formatting Rules::
14095@end menu
14096
14097@node Switches for gnatpp
14098@section Switches for @command{gnatpp}
14099
14100@noindent
14101The following subsections describe the various switches accepted by
14102@command{gnatpp}, organized by category.
14103
14104@ifclear vms
14105You specify a switch by supplying a name and generally also a value.
14106In many cases the values for a switch with a given name are incompatible with
14107each other
14108(for example the switch that controls the casing of a reserved word may have
14109exactly one value: upper case, lower case, or
14110mixed case) and thus exactly one such switch can be in effect for an
14111invocation of @command{gnatpp}.
14112If more than one is supplied, the last one is used.
14113However, some values for the same switch are mutually compatible.
14114You may supply several such switches to @command{gnatpp}, but then
14115each must be specified in full, with both the name and the value.
14116Abbreviated forms (the name appearing once, followed by each value) are
14117not permitted.
14118For example, to set
14119the alignment of the assignment delimiter both in declarations and in
14120assignment statements, you must write @option{-A2A3}
14121(or @option{-A2 -A3}), but not @option{-A23}.
14122@end ifclear
14123
14124@ifset vms
14125In many cases the set of options for a given qualifier are incompatible with
14126each other (for example the qualifier that controls the casing of a reserved
14127word may have exactly one option, which specifies either upper case, lower
14128case, or mixed case), and thus exactly one such option can be in effect for
14129an invocation of @command{gnatpp}.
14130If more than one is supplied, the last one is used.
14131However, some qualifiers have options that are mutually compatible,
14132and then you may then supply several such options when invoking
14133@command{gnatpp}.
14134@end ifset
14135
14136In most cases, it is obvious whether or not the
14137^values for a switch with a given name^options for a given qualifier^
14138are compatible with each other.
14139When the semantics might not be evident, the summaries below explicitly
14140indicate the effect.
14141
14142@menu
14143* Alignment Control::
14144* Casing Control::
14145* Construct Layout Control::
14146* General Text Layout Control::
14147* Other Formatting Options::
14148* Setting the Source Search Path::
14149* Output File Control::
14150* Other gnatpp Switches::
14151@end menu
14152
14153
14154@node Alignment Control
14155@subsection Alignment Control
14156@cindex Alignment control in @command{gnatpp}
14157
14158@noindent
14159Programs can be easier to read if certain constructs are vertically aligned.
14160By default all alignments are set ON.
14161Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14162OFF, and then use one or more of the other
14163^@option{-A@var{n}} switches^@option{/ALIGN} options^
14164to activate alignment for specific constructs.
14165
14166@table @option
14167@cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14168
14169@ifset vms
14170@item /ALIGN=ON
14171Set all alignments to ON
14172@end ifset
14173
14174@item ^-A0^/ALIGN=OFF^
14175Set all alignments to OFF
14176
14177@item ^-A1^/ALIGN=COLONS^
14178Align @code{:} in declarations
14179
14180@item ^-A2^/ALIGN=DECLARATIONS^
14181Align @code{:=} in initializations in declarations
14182
14183@item ^-A3^/ALIGN=STATEMENTS^
14184Align @code{:=} in assignment statements
14185
14186@item ^-A4^/ALIGN=ARROWS^
14187Align @code{=>} in associations
14188@end table
14189
14190@noindent
14191The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14192is allowed.
14193
14194
14195@node Casing Control
14196@subsection Casing Control
14197@cindex Casing control in @command{gnatpp}
14198
14199@noindent
14200@command{gnatpp} allows you to specify the casing for reserved words,
14201pragma names, attribute designators and identifiers.
14202For identifiers you may define a
14203general rule for name casing but also override this rule
14204via a set of dictionary files.
14205
14206Three types of casing are supported: lower case, upper case, and mixed case.
14207Lower and upper case are self-explanatory (but since some letters in
14208Latin1 and other GNAT-supported character sets
14209exist only in lower-case form, an upper case conversion will have no
14210effect on them.)
14211``Mixed case'' means that the first letter, and also each letter immediately
14212following an underscore, are converted to their uppercase forms;
14213all the other letters are converted to their lowercase forms.
14214
14215@table @option
14216@cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14217@item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14218Attribute designators are lower case
14219
14220@item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14221Attribute designators are upper case
14222
14223@item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14224Attribute designators are mixed case (this is the default)
14225
14226@cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14227@item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14228Keywords (technically, these are known in Ada as @emph{reserved words}) are
14229lower case (this is the default)
14230
14231@item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14232Keywords are upper case
14233
14234@cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14235@item ^-nD^/NAME_CASING=AS_DECLARED^
14236Name casing for defining occurrences are as they appear in the source file
14237(this is the default)
14238
14239@item ^-nU^/NAME_CASING=UPPER_CASE^
14240Names are in upper case
14241
14242@item ^-nL^/NAME_CASING=LOWER_CASE^
14243Names are in lower case
14244
14245@item ^-nM^/NAME_CASING=MIXED_CASE^
14246Names are in mixed case
14247
14248@cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14249@item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14250Pragma names are lower case
14251
14252@item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14253Pragma names are upper case
14254
14255@item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14256Pragma names are mixed case (this is the default)
14257
14258@item ^-D@var{file}^/DICTIONARY=@var{file}^
14259@cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14260Use @var{file} as a @emph{dictionary file} that defines
14261the casing for a set of specified names,
14262thereby overriding the effect on these names by
14263any explicit or implicit
14264^-n^/NAME_CASING^ switch.
14265To supply more than one dictionary file,
14266use ^several @option{-D} switches^a list of files as options^.
14267
14268@noindent
14269@option{gnatpp} implicitly uses a @emph{default dictionary file}
14270to define the casing for the Ada predefined names and
14271the names declared in the GNAT libraries.
14272
14273@item ^-D-^/SPECIFIC_CASING^
14274@cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14275Do not use the default dictionary file;
14276instead, use the casing
14277defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14278dictionary file(s)
14279@end table
14280
14281@noindent
14282The structure of a dictionary file, and details on the conventions
14283used in the default dictionary file, are defined in @ref{Name Casing}.
14284
14285The @option{^-D-^/SPECIFIC_CASING^} and
14286@option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14287compatible.
14288
14289
14290@node Construct Layout Control
14291@subsection Construct Layout Control
14292@cindex Layout control in @command{gnatpp}
14293
14294@noindent
14295This group of @command{gnatpp} switches controls the layout of comments and
14296complex syntactic constructs.  See @ref{Formatting Comments}, for details
14297on their effect.
14298
14299@table @option
14300@cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14301@item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14302GNAT-style comment line indentation (this is the default).
14303
14304@item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14305Reference-manual comment line indentation.
14306
14307@item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14308GNAT-style comment beginning
14309
14310@item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14311Reformat comment blocks
14312
14313@cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14314@item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14315GNAT-style layout (this is the default)
14316
14317@item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14318Compact layout
14319
14320@item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14321Uncompact layout
14322@end table
14323
14324@ifclear vms
14325@noindent
14326The @option{-c1} and @option{-c2} switches are incompatible.
14327The @option{-c3} and @option{-c4} switches are compatible with each other and
14328also with @option{-c1} and @option{-c2}.
14329
14330The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14331@end ifclear
14332
14333@ifset vms
14334@noindent
14335For the @option{/COMMENTS_LAYOUT} qualifier:
14336@itemize @bullet
14337@item
14338The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14339@item
14340The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14341each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14342@end itemize
14343
14344@noindent
14345The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14346@option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14347@end ifset
14348
14349@node General Text Layout Control
14350@subsection General Text Layout Control
14351
14352@noindent
14353These switches allow control over line length and indentation.
14354
14355@table @option
14356@item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14357@cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14358Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14359
14360@item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14361@cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14362Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14363
14364@item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14365@cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14366Indentation level for continuation lines (relative to the line being
14367continued), @i{nnn} from 1 .. 9.
14368The default
14369value is one less then the (normal) indentation level, unless the
14370indentation is set to 1 (in which case the default value for continuation
14371line indentation is also 1)
14372@end table
14373
14374
14375@node Other Formatting Options
14376@subsection Other Formatting Options
14377
14378@noindent
14379These switches control the inclusion of missing end/exit labels, and
14380the indentation level in @b{case} statements.
14381
14382@table @option
14383@item ^-e^/NO_MISSED_LABELS^
14384@cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14385Do not insert missing end/exit labels. An end label is the name of
14386a construct that may optionally be repeated at the end of the
14387construct's declaration;
14388e.g., the names of packages, subprograms, and tasks.
14389An exit label is the name of a loop that may appear as target
14390of an exit statement within the loop.
14391By default, @command{gnatpp} inserts these end/exit labels when
14392they are absent from the original source. This option suppresses such
14393insertion, so that the formatted source reflects the original.
14394
14395@item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14396@cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14397Insert a Form Feed character after a pragma Page.
14398
14399@item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14400@cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14401Do not use an additional indentation level for @b{case} alternatives
14402and variants if there are @i{nnn} or more (the default
14403value is 10).
14404If @i{nnn} is 0, an additional indentation level is
14405used for @b{case} alternatives and variants regardless of their number.
14406@end table
14407
14408@node Setting the Source Search Path
14409@subsection Setting the Source Search Path
14410
14411@noindent
14412To define the search path for the input source file, @command{gnatpp}
14413uses the same switches as the GNAT compiler, with the same effects.
14414
14415@table @option
14416@item ^-I^/SEARCH=^@var{dir}
14417@cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14418The same as the corresponding gcc switch
14419
14420@item ^-I-^/NOCURRENT_DIRECTORY^
14421@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14422The same as the corresponding gcc switch
14423
14424@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14425@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14426The same as the corresponding gcc switch
14427@end table
14428
14429
14430@node Output File Control
14431@subsection Output File Control
14432
14433@noindent
14434By default the output is sent to the file whose name is obtained by appending
14435the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14436(if the file with this name already exists, it is unconditionally overwritten).
14437Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14438@command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14439as output file.
14440The output may be redirected by the following switches:
14441
14442@table @option
14443@item ^-pipe^/STANDARD_OUTPUT^
14444@cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14445Send the output to @code{Standard_Output}
14446
14447@item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14448@cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14449Write the output into @var{output_file}.
14450If @var{output_file} already exists, @command{gnatpp} terminates without
14451reading or processing the input file.
14452
14453@item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14454@cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14455Write the output into @var{output_file}, overwriting the existing file
14456(if one is present).
14457
14458@item ^-r^/REPLACE^
14459@cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14460Replace the input source file with the reformatted output, and copy the
14461original input source into the file whose name is obtained by appending the
14462^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14463If a file with this name already exists, @command{gnatpp} terminates without
14464reading or processing the input file.
14465
14466@item ^-rf^/OVERRIDING_REPLACE^
14467@cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14468Like @option{^-r^/REPLACE^} except that if the file with the specified name
14469already exists, it is overwritten.
14470@end table
14471
14472
14473@node Other gnatpp Switches
14474@subsection Other @code{gnatpp} Switches
14475
14476@noindent
14477The additional @command{gnatpp} switches are defined in this subsection.
14478
14479@table @option
14480@item ^-v^/VERBOSE^
14481@cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14482Verbose mode;
14483@command{gnatpp} generates version information and then
14484a trace of the actions it takes to produce or obtain the ASIS tree.
14485
14486@item ^-w^/WARNINGS^
14487@cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14488Warning mode;
14489@command{gnatpp} generates a warning whenever it can not provide
14490a required layout in the result source.
14491@end table
14492
14493
14494@node Formatting Rules
14495@section Formatting Rules
14496
14497@noindent
14498The following subsections show how @command{gnatpp} treats ``white space'',
14499comments, program layout, and name casing.
14500They provide the detailed descriptions of the switches shown above.
14501
14502@menu
14503* White Space and Empty Lines::
14504* Formatting Comments::
14505* Construct Layout::
14506* Name Casing::
14507@end menu
14508
14509
14510@node White Space and Empty Lines
14511@subsection White Space and Empty Lines
14512
14513@noindent
14514@command{gnatpp} does not have an option to control space characters.
14515It will add or remove spaces according to the style illustrated by the
14516examples in the @cite{Ada Reference Manual}.
14517
14518The only format effectors
14519(see @cite{Ada Reference Manual}, paragraph 2.1(13))
14520that will appear in the output file are platform-specific line breaks,
14521and also format effectors within (but not at the end of) comments.
14522In particular, each horizontal tab character that is not inside
14523a comment will be treated as a space and thus will appear in the
14524output file as zero or more spaces depending on
14525the reformatting of the line in which it appears.
14526The only exception is a Form Feed character, which is inserted after a
14527pragma @code{Page} when @option{-ff} is set.
14528
14529The output file will contain no lines with trailing ``white space'' (spaces,
14530format effectors).
14531
14532Empty lines in the original source are preserved
14533only if they separate declarations or statements.
14534In such contexts, a
14535sequence of two or more empty lines is replaced by exactly one empty line.
14536Note that a blank line will be removed if it separates two ``comment blocks''
14537(a comment block is a sequence of whole-line comments).
14538In order to preserve a visual separation between comment blocks, use an
14539``empty comment'' (a line comprising only hyphens) rather than an empty line.
14540Likewise, if for some reason you wish to have a sequence of empty lines,
14541use a sequence of empty comments instead.
14542
14543
14544@node Formatting Comments
14545@subsection Formatting Comments
14546
14547@noindent
14548Comments in Ada code are of two kinds:
14549@itemize @bullet
14550@item
14551a @emph{whole-line comment}, which appears by itself (possibly preceded by
14552``white space'') on a line
14553
14554@item
14555an @emph{end-of-line comment}, which follows some other Ada lexical element
14556on the same line.
14557@end itemize
14558
14559@noindent
14560The indentation of a whole-line comment is that of either
14561the preceding or following line in
14562the formatted source, depending on switch settings as will be described below.
14563
14564For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14565between the end of the preceding Ada lexical element and the beginning
14566of the comment as appear in the original source,
14567unless either the comment has to be split to
14568satisfy the line length limitation, or else the next line contains a
14569whole line comment that is considered a continuation of this end-of-line
14570comment (because it starts at the same position).
14571In the latter two
14572cases, the start of the end-of-line comment is moved right to the nearest
14573multiple of the indentation level.
14574This may result in a ``line overflow'' (the right-shifted comment extending
14575beyond the maximum line length), in which case the comment is split as
14576described below.
14577
14578There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14579(GNAT-style comment line indentation)
14580and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14581(reference-manual comment line indentation).
14582With reference-manual style, a whole-line comment is indented as if it
14583were a declaration or statement at the same place
14584(i.e., according to the indentation of the preceding line(s)).
14585With GNAT style, a whole-line comment that is immediately followed by an
14586@b{if} or @b{case} statement alternative, a record variant, or the reserved
14587word @b{begin}, is indented based on the construct that follows it.
14588
14589For example:
14590@smallexample @c ada
14591@cartouche
14592if A then
14593    null;
14594       -- some comment
14595else
14596   null;
14597end if;
14598@end cartouche
14599@end smallexample
14600
14601@noindent
14602Reference-manual indentation produces:
14603
14604@smallexample @c ada
14605@cartouche
14606if A then
14607   null;
14608   --  some comment
14609else
14610   null;
14611end if;
14612@end cartouche
14613@end smallexample
14614
14615@noindent
14616while GNAT-style indentation produces:
14617
14618@smallexample @c ada
14619@cartouche
14620if A then
14621   null;
14622--  some comment
14623else
14624   null;
14625end if;
14626@end cartouche
14627@end smallexample
14628
14629@noindent
14630The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14631(GNAT style comment beginning) has the following
14632effect:
14633
14634@itemize @bullet
14635@item
14636For each whole-line comment that does not end with two hyphens,
14637@command{gnatpp} inserts spaces if necessary after the starting two hyphens
14638to ensure that there are at least two spaces between these hyphens and the
14639first non-blank character of the comment.
14640@end itemize
14641
14642@noindent
14643For an end-of-line comment, if in the original source the next line is a
14644whole-line comment that starts at the same position
14645as the end-of-line comment,
14646then the whole-line comment (and all whole-line comments
14647that follow it and that start at the same position)
14648will start at this position in the output file.
14649
14650@noindent
14651That is, if in the original source we have:
14652
14653@smallexample @c ada
14654@cartouche
14655begin
14656A := B + C;            --  B must be in the range Low1..High1
14657                       --  C must be in the range Low2..High2
14658             --B+C will be in the range Low1+Low2..High1+High2
14659X := X + 1;
14660@end cartouche
14661@end smallexample
14662
14663@noindent
14664Then in the formatted source we get
14665
14666@smallexample @c ada
14667@cartouche
14668begin
14669   A := B + C;            --  B must be in the range Low1..High1
14670                          --  C must be in the range Low2..High2
14671   --  B+C will be in the range Low1+Low2..High1+High2
14672   X := X + 1;
14673@end cartouche
14674@end smallexample
14675
14676@noindent
14677A comment that exceeds the line length limit will be split.
14678Unless switch
14679@option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14680the line belongs to a reformattable block, splitting the line generates a
14681@command{gnatpp} warning.
14682The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14683comments may be reformatted in typical
14684word processor style (that is, moving words between lines and putting as
14685many words in a line as possible).
14686
14687
14688@node Construct Layout
14689@subsection Construct Layout
14690
14691@noindent
14692The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14693and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14694layout on the one hand, and uncompact layout
14695@option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14696can be illustrated by the following examples:
14697
14698@iftex
14699@cartouche
14700@multitable @columnfractions .5 .5
14701@item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14702
14703@item
14704@smallexample @c ada
14705type q is record
14706   a : integer;
14707   b : integer;
14708end record;
14709@end smallexample
14710@tab
14711@smallexample @c ada
14712type q is
14713   record
14714      a : integer;
14715      b : integer;
14716   end record;
14717@end smallexample
14718
14719@item
14720@smallexample @c ada
14721Block : declare
14722   A : Integer := 3;
14723begin
14724   Proc (A, A);
14725end Block;
14726@end smallexample
14727@tab
14728@smallexample @c ada
14729Block :
14730   declare
14731      A : Integer := 3;
14732   begin
14733      Proc (A, A);
14734   end Block;
14735@end smallexample
14736
14737@item
14738@smallexample @c ada
14739Clear : for J in 1 .. 10 loop
14740   A (J) := 0;
14741end loop Clear;
14742@end smallexample
14743@tab
14744@smallexample @c ada
14745Clear :
14746   for J in 1 .. 10 loop
14747      A (J) := 0;
14748   end loop Clear;
14749@end smallexample
14750@end multitable
14751@end cartouche
14752@end iftex
14753
14754@ifnottex
14755@smallexample
14756@cartouche
14757GNAT style, compact layout              Uncompact layout
14758
14759type q is record                        type q is
14760   a : integer;                            record
14761   b : integer;                               a : integer;
14762end record;                                   b : integer;
14763                                           end record;
14764
14765
14766Block : declare                         Block :
14767   A : Integer := 3;                       declare
14768begin                                         A : Integer := 3;
14769   Proc (A, A);                            begin
14770end Block;                                    Proc (A, A);
14771                                           end Block;
14772
14773Clear : for J in 1 .. 10 loop           Clear :
14774   A (J) := 0;                             for J in 1 .. 10 loop
14775end loop Clear;                               A (J) := 0;
14776                                           end loop Clear;
14777@end cartouche
14778@end smallexample
14779@end ifnottex
14780
14781@noindent
14782A further difference between GNAT style layout and compact layout is that
14783GNAT style layout inserts empty lines as separation for
14784compound statements, return statements and bodies.
14785
14786
14787@node Name Casing
14788@subsection Name Casing
14789
14790@noindent
14791@command{gnatpp} always converts the usage occurrence of a (simple) name to
14792the same casing as the corresponding defining identifier.
14793
14794You control the casing for defining occurrences via the
14795@option{^-n^/NAME_CASING^} switch.
14796@ifclear vms
14797With @option{-nD} (``as declared'', which is the default),
14798@end ifclear
14799@ifset vms
14800With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14801@end ifset
14802defining occurrences appear exactly as in the source file
14803where they are declared.
14804The other ^values for this switch^options for this qualifier^ ---
14805@option{^-nU^UPPER_CASE^},
14806@option{^-nL^LOWER_CASE^},
14807@option{^-nM^MIXED_CASE^} ---
14808result in
14809^upper, lower, or mixed case, respectively^the corresponding casing^.
14810If @command{gnatpp} changes the casing of a defining
14811occurrence, it analogously changes the casing of all the
14812usage occurrences of this name.
14813
14814If the defining occurrence of a name is not in the source compilation unit
14815currently being processed by @command{gnatpp}, the casing of each reference to
14816this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14817switch (subject to the dictionary file mechanism described below).
14818Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14819had affected the
14820casing for the defining occurrence of the name.
14821
14822Some names may need to be spelled with casing conventions that are not
14823covered by the upper-, lower-, and mixed-case transformations.
14824You can arrange correct casing by placing such names in a
14825@emph{dictionary file},
14826and then supplying a @option{^-D^/DICTIONARY^} switch.
14827The casing of names from dictionary files overrides
14828any @option{^-n^/NAME_CASING^} switch.
14829
14830To handle the casing of Ada predefined names and the names from GNAT libraries,
14831@command{gnatpp} assumes a default dictionary file.
14832The name of each predefined entity is spelled with the same casing as is used
14833for the entity in the @cite{Ada Reference Manual}.
14834The name of each entity in the GNAT libraries is spelled with the same casing
14835as is used in the declaration of that entity.
14836
14837The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14838default dictionary file.
14839Instead, the casing for predefined and GNAT-defined names will be established
14840by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14841For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14842will appear as just shown,
14843even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14844To ensure that even such names are rendered in uppercase,
14845additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14846(or else, less conveniently, place these names in upper case in a dictionary
14847file).
14848
14849A dictionary file is
14850a plain text file; each line in this file can be either a blank line
14851(containing only space characters and ASCII.HT characters), an Ada comment
14852line, or the specification of exactly one @emph{casing schema}.
14853
14854A casing schema is a string that has the following syntax:
14855
14856@smallexample
14857@cartouche
14858  @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
14859
14860  @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14861@end cartouche
14862@end smallexample
14863
14864@noindent
14865(The @code{[]} metanotation stands for an optional part;
14866see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14867@var{identifier} lexical element and the @var{letter_or_digit} category).
14868
14869The casing schema string can be followed by white space and/or an Ada-style
14870comment; any amount of white space is allowed before the string.
14871
14872If a dictionary file is passed as
14873@ifclear vms
14874the value of a @option{-D@var{file}} switch
14875@end ifclear
14876@ifset vms
14877an option to the @option{/DICTIONARY} qualifier
14878@end ifset
14879then for every
14880simple name and every identifier, @command{gnatpp} checks if the dictionary
14881defines the casing for the name or for some of its parts (the term ``subword''
14882is used below to denote the part of a name which is delimited by ``_'' or by
14883the beginning or end of the word and which does not contain any ``_'' inside):
14884
14885@itemize @bullet
14886@item
14887if the whole name is in the dictionary, @command{gnatpp} uses for this name
14888the casing defined by the dictionary; no subwords are checked for this word
14889
14890@item
14891for the first subword (that is, for the subword preceding the leftmost
14892``_''), @command{gnatpp} checks if the dictionary contains the corresponding
14893string of the form @code{@var{simple_identifier}*}, and if it does, the
14894casing of this @var{simple_identifier} is used for this subword
14895
14896@item
14897for the last subword (following the rightmost ``_'') @command{gnatpp}
14898checks if the dictionary contains the corresponding string of the form
14899@code{*@var{simple_identifier}}, and if it does, the casing of this
14900@var{simple_identifier} is used for this subword
14901
14902@item
14903for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
14904if the dictionary contains the corresponding string of the form
14905@code{*@var{simple_identifier}*}, and if it does, the casing of this
14906simple_identifier is used for this subword
14907
14908@item
14909if more than one dictionary file is passed as @command{gnatpp} switches, each
14910dictionary adds new casing exceptions and overrides all the existing casing
14911exceptions set by the previous dictionaries
14912
14913@item
14914when @command{gnatpp} checks if the word or subword is in the dictionary,
14915this check is not case sensitive
14916@end itemize
14917
14918@noindent
14919For example, suppose we have the following source to reformat:
14920
14921@smallexample @c ada
14922@cartouche
14923procedure test is
14924   name1 : integer := 1;
14925   name4_name3_name2 : integer := 2;
14926   name2_name3_name4 : Boolean;
14927   name1_var : Float;
14928begin
14929   name2_name3_name4 := name4_name3_name2 > name1;
14930end;
14931@end cartouche
14932@end smallexample
14933
14934@noindent
14935And suppose we have two dictionaries:
14936
14937@smallexample
14938@cartouche
14939@i{dict1:}
14940   NAME1
14941   *NaMe3*
14942   *NAME2
14943@end cartouche
14944
14945@cartouche
14946@i{dict2:}
14947  *NAME3*
14948@end cartouche
14949@end smallexample
14950
14951@noindent
14952If @command{gnatpp} is called with the following switches:
14953
14954@smallexample
14955@ifclear vms
14956@command{gnatpp -nM -D dict1 -D dict2 test.adb}
14957@end ifclear
14958@ifset vms
14959@command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14960@end ifset
14961@end smallexample
14962
14963@noindent
14964then we will get the following name casing in the @command{gnatpp} output:
14965
14966@smallexample @c ada
14967@cartouche
14968procedure Test is
14969   NAME1             : Integer := 1;
14970   Name4_NAME3_NAME2 : integer := 2;
14971   Name2_NAME3_Name4 : Boolean;
14972   Name1_Var         : Float;
14973begin
14974   Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
14975end Test;
14976@end cartouche
14977@end smallexample
14978
14979
14980
14981@c ***********************************
14982@node File Name Krunching Using gnatkr
14983@chapter File Name Krunching Using @code{gnatkr}
14984@findex gnatkr
14985
14986@noindent
14987This chapter discusses the method used by the compiler to shorten
14988the default file names chosen for Ada units so that they do not
14989exceed the maximum length permitted. It also describes the
14990@code{gnatkr} utility that can be used to determine the result of
14991applying this shortening.
14992@menu
14993* About gnatkr::
14994* Using gnatkr::
14995* Krunching Method::
14996* Examples of gnatkr Usage::
14997@end menu
14998
14999@node About gnatkr
15000@section About @code{gnatkr}
15001
15002@noindent
15003The default file naming rule in GNAT
15004is that the file name must be derived from
15005the unit name. The exact default rule is as follows:
15006@itemize @bullet
15007@item
15008Take the unit name and replace all dots by hyphens.
15009@item
15010If such a replacement occurs in the
15011second character position of a name, and the first character is
15012^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15013^~ (tilde)^$ (dollar sign)^
15014instead of a minus.
15015@end itemize
15016The reason for this exception is to avoid clashes
15017with the standard names for children of System, Ada, Interfaces,
15018and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15019respectively.
15020
15021The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15022switch of the compiler activates a ``krunching''
15023circuit that limits file names to nn characters (where nn is a decimal
15024integer). For example, using OpenVMS,
15025where the maximum file name length is
1502639, the value of nn is usually set to 39, but if you want to generate
15027a set of files that would be usable if ported to a system with some
15028different maximum file length, then a different value can be specified.
15029The default value of 39 for OpenVMS need not be specified.
15030
15031The @code{gnatkr} utility can be used to determine the krunched name for
15032a given file, when krunched to a specified maximum length.
15033
15034@node Using gnatkr
15035@section Using @code{gnatkr}
15036
15037@noindent
15038The @code{gnatkr} command has the form
15039
15040@ifclear vms
15041@smallexample
15042$ gnatkr @var{name} [@var{length}]
15043@end smallexample
15044@end ifclear
15045
15046@ifset vms
15047@smallexample
15048$ gnatkr @var{name} /COUNT=nn
15049@end smallexample
15050@end ifset
15051
15052@noindent
15053@var{name} is the uncrunched file name, derived from the name of the unit
15054in the standard manner described in the previous section (i.e. in particular
15055all dots are replaced by hyphens). The file name may or may not have an
15056extension (defined as a suffix of the form period followed by arbitrary
15057characters other than period). If an extension is present then it will
15058be preserved in the output. For example, when krunching @file{hellofile.ads}
15059to eight characters, the result will be hellofil.ads.
15060
15061Note: for compatibility with previous versions of @code{gnatkr} dots may
15062appear in the name instead of hyphens, but the last dot will always be
15063taken as the start of an extension. So if @code{gnatkr} is given an argument
15064such as @file{Hello.World.adb} it will be treated exactly as if the first
15065period had been a hyphen, and for example krunching to eight characters
15066gives the result @file{hellworl.adb}.
15067
15068Note that the result is always all lower case (except on OpenVMS where it is
15069all upper case). Characters of the other case are folded as required.
15070
15071@var{length} represents the length of the krunched name. The default
15072when no argument is given is ^8^39^ characters. A length of zero stands for
15073unlimited, in other words do not chop except for system files where the
15074impled crunching length is always eight characters.
15075
15076@noindent
15077The output is the krunched name. The output has an extension only if the
15078original argument was a file name with an extension.
15079
15080@node Krunching Method
15081@section Krunching Method
15082
15083@noindent
15084The initial file name is determined by the name of the unit that the file
15085contains. The name is formed by taking the full expanded name of the
15086unit and replacing the separating dots with hyphens and
15087using ^lowercase^uppercase^
15088for all letters, except that a hyphen in the second character position is
15089replaced by a ^tilde^dollar sign^ if the first character is
15090^a, i, g, or s^A, I, G, or S^.
15091The extension is @code{.ads} for a
15092specification and @code{.adb} for a body.
15093Krunching does not affect the extension, but the file name is shortened to
15094the specified length by following these rules:
15095
15096@itemize @bullet
15097@item
15098The name is divided into segments separated by hyphens, tildes or
15099underscores and all hyphens, tildes, and underscores are
15100eliminated. If this leaves the name short enough, we are done.
15101
15102@item
15103If the name is too long, the longest segment is located (left-most
15104if there are two of equal length), and shortened by dropping
15105its last character. This is repeated until the name is short enough.
15106
15107As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15108to fit the name into 8 characters as required by some operating systems.
15109
15110@smallexample
15111our-strings-wide_fixed 22
15112our strings wide fixed 19
15113our string  wide fixed 18
15114our strin   wide fixed 17
15115our stri    wide fixed 16
15116our stri    wide fixe  15
15117our str     wide fixe  14
15118our str     wid  fixe  13
15119our str     wid  fix   12
15120ou  str     wid  fix   11
15121ou  st      wid  fix   10
15122ou  st      wi   fix   9
15123ou  st      wi   fi    8
15124Final file name: oustwifi.adb
15125@end smallexample
15126
15127@item
15128The file names for all predefined units are always krunched to eight
15129characters. The krunching of these predefined units uses the following
15130special prefix replacements:
15131
15132@table @file
15133@item ada-
15134replaced by @file{^a^A^-}
15135
15136@item gnat-
15137replaced by @file{^g^G^-}
15138
15139@item interfaces-
15140replaced by @file{^i^I^-}
15141
15142@item system-
15143replaced by @file{^s^S^-}
15144@end table
15145
15146These system files have a hyphen in the second character position. That
15147is why normal user files replace such a character with a
15148^tilde^dollar sign^, to
15149avoid confusion with system file names.
15150
15151As an example of this special rule, consider
15152@*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15153
15154@smallexample
15155ada-strings-wide_fixed 22
15156a-  strings wide fixed 18
15157a-  string  wide fixed 17
15158a-  strin   wide fixed 16
15159a-  stri    wide fixed 15
15160a-  stri    wide fixe  14
15161a-  str     wide fixe  13
15162a-  str     wid  fixe  12
15163a-  str     wid  fix   11
15164a-  st      wid  fix   10
15165a-  st      wi   fix   9
15166a-  st      wi   fi    8
15167Final file name: a-stwifi.adb
15168@end smallexample
15169@end itemize
15170
15171Of course no file shortening algorithm can guarantee uniqueness over all
15172possible unit names, and if file name krunching is used then it is your
15173responsibility to ensure that no name clashes occur. The utility
15174program @code{gnatkr} is supplied for conveniently determining the
15175krunched name of a file.
15176
15177@node Examples of gnatkr Usage
15178@section Examples of @code{gnatkr} Usage
15179
15180@smallexample
15181@iftex
15182@leftskip=0cm
15183@end iftex
15184@ifclear vms
15185$ gnatkr very_long_unit_name.ads      --> velounna.ads
15186$ gnatkr grandparent-parent-child.ads --> grparchi.ads
15187$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15188$ gnatkr grandparent-parent-child     --> grparchi
15189@end ifclear
15190$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15191$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15192@end smallexample
15193
15194@node Preprocessing Using gnatprep
15195@chapter Preprocessing Using @code{gnatprep}
15196@findex gnatprep
15197
15198@noindent
15199The @code{gnatprep} utility provides
15200a simple preprocessing capability for Ada programs.
15201It is designed for use with GNAT, but is not dependent on any special
15202features of GNAT.
15203
15204@menu
15205* Using gnatprep::
15206* Switches for gnatprep::
15207* Form of Definitions File::
15208* Form of Input Text for gnatprep::
15209@end menu
15210
15211@node Using gnatprep
15212@section Using @code{gnatprep}
15213
15214@noindent
15215To call @code{gnatprep} use
15216
15217@smallexample
15218$ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15219@end smallexample
15220
15221@noindent
15222where
15223@table @code
15224@item infile
15225is the full name of the input file, which is an Ada source
15226file containing preprocessor directives.
15227
15228@item outfile
15229is the full name of the output file, which is an Ada source
15230in standard Ada form. When used with GNAT, this file name will
15231normally have an ads or adb suffix.
15232
15233@item deffile
15234is the full name of a text file containing definitions of
15235symbols to be referenced by the preprocessor. This argument is
15236optional, and can be replaced by the use of the @option{-D} switch.
15237
15238@item switches
15239is an optional sequence of switches as described in the next section.
15240@end table
15241
15242@node Switches for gnatprep
15243@section Switches for @code{gnatprep}
15244
15245@table @option
15246@c !sort!
15247
15248@item ^-b^/BLANK_LINES^
15249@cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15250Causes both preprocessor lines and the lines deleted by
15251preprocessing to be replaced by blank lines in the output source file,
15252preserving line numbers in the output file.
15253
15254@item ^-c^/COMMENTS^
15255@cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15256Causes both preprocessor lines and the lines deleted
15257by preprocessing to be retained in the output source as comments marked
15258with the special string @code{"--! "}. This option will result in line numbers
15259being preserved in the output file.
15260
15261@item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15262@cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15263Defines a new symbol, associated with value. If no value is given on the
15264command line, then symbol is considered to be @code{True}. This switch
15265can be used in place of a definition file.
15266
15267@ifset vms
15268@item /REMOVE
15269@cindex @option{/REMOVE} (@command{gnatprep})
15270This is the default setting which causes lines deleted by preprocessing
15271to be entirely removed from the output file.
15272@end ifset
15273
15274@item ^-r^/REFERENCE^
15275@cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15276Causes a @code{Source_Reference} pragma to be generated that
15277references the original input file, so that error messages will use
15278the file name of this original file. The use of this switch implies
15279that preprocessor lines are not to be removed from the file, so its
15280use will force @option{^-b^/BLANK_LINES^} mode if
15281@option{^-c^/COMMENTS^}
15282has not been specified explicitly.
15283
15284Note that if the file to be preprocessed contains multiple units, then
15285it will be necessary to @code{gnatchop} the output file from
15286@code{gnatprep}. If a @code{Source_Reference} pragma is present
15287in the preprocessed file, it will be respected by
15288@code{gnatchop ^-r^/REFERENCE^}
15289so that the final chopped files will correctly refer to the original
15290input source file for @code{gnatprep}.
15291
15292@item ^-s^/SYMBOLS^
15293@cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15294Causes a sorted list of symbol names and values to be
15295listed on the standard output file.
15296
15297@item ^-u^/UNDEFINED^
15298@cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15299Causes undefined symbols to be treated as having the value FALSE in the context
15300of a preprocessor test. In the absence of this option, an undefined symbol in
15301a @code{#if} or @code{#elsif} test will be treated as an error.
15302
15303@end table
15304
15305@ifclear vms
15306@noindent
15307Note: if neither @option{-b} nor @option{-c} is present,
15308then preprocessor lines and
15309deleted lines are completely removed from the output, unless -r is
15310specified, in which case -b is assumed.
15311@end ifclear
15312
15313@node Form of Definitions File
15314@section Form of Definitions File
15315
15316@noindent
15317The definitions file contains lines of the form
15318
15319@smallexample
15320symbol := value
15321@end smallexample
15322
15323@noindent
15324where symbol is an identifier, following normal Ada (case-insensitive)
15325rules for its syntax, and value is one of the following:
15326
15327@itemize @bullet
15328@item
15329Empty, corresponding to a null substitution
15330@item
15331A string literal using normal Ada syntax
15332@item
15333Any sequence of characters from the set
15334(letters, digits, period, underline).
15335@end itemize
15336
15337@noindent
15338Comment lines may also appear in the definitions file, starting with
15339the usual @code{--},
15340and comments may be added to the definitions lines.
15341
15342@node Form of Input Text for gnatprep
15343@section Form of Input Text for @code{gnatprep}
15344
15345@noindent
15346The input text may contain preprocessor conditional inclusion lines,
15347as well as general symbol substitution sequences.
15348
15349The preprocessor conditional inclusion commands have the form
15350
15351@smallexample
15352@group
15353@cartouche
15354#if @i{expression} [then]
15355   lines
15356#elsif @i{expression} [then]
15357   lines
15358#elsif @i{expression} [then]
15359   lines
15360...
15361#else
15362   lines
15363#end if;
15364@end cartouche
15365@end group
15366@end smallexample
15367
15368@noindent
15369In this example, @i{expression} is defined by the following grammar:
15370@smallexample
15371@i{expression} ::=  <symbol>
15372@i{expression} ::=  <symbol> = "<value>"
15373@i{expression} ::=  <symbol> = <symbol>
15374@i{expression} ::=  <symbol> 'Defined
15375@i{expression} ::=  not @i{expression}
15376@i{expression} ::=  @i{expression} and @i{expression}
15377@i{expression} ::=  @i{expression} or @i{expression}
15378@i{expression} ::=  @i{expression} and then @i{expression}
15379@i{expression} ::=  @i{expression} or else @i{expression}
15380@i{expression} ::=  ( @i{expression} )
15381@end smallexample
15382
15383@noindent
15384For the first test (@i{expression} ::= <symbol>) the symbol must have
15385either the value true or false, that is to say the right-hand of the
15386symbol definition must be one of the (case-insensitive) literals
15387@code{True} or @code{False}. If the value is true, then the
15388corresponding lines are included, and if the value is false, they are
15389excluded.
15390
15391The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15392the symbol has been defined in the definition file or by a @option{-D}
15393switch on the command line. Otherwise, the test is false.
15394
15395The equality tests are case insensitive, as are all the preprocessor lines.
15396
15397If the symbol referenced is not defined in the symbol definitions file,
15398then the effect depends on whether or not switch @option{-u}
15399is specified. If so, then the symbol is treated as if it had the value
15400false and the test fails. If this switch is not specified, then
15401it is an error to reference an undefined symbol. It is also an error to
15402reference a symbol that is defined with a value other than @code{True}
15403or @code{False}.
15404
15405The use of the @code{not} operator inverts the sense of this logical test, so
15406that the lines are included only if the symbol is not defined.
15407The @code{then} keyword is optional as shown
15408
15409The @code{#} must be the first non-blank character on a line, but
15410otherwise the format is free form. Spaces or tabs may appear between
15411the @code{#} and the keyword. The keywords and the symbols are case
15412insensitive as in normal Ada code. Comments may be used on a
15413preprocessor line, but other than that, no other tokens may appear on a
15414preprocessor line. Any number of @code{elsif} clauses can be present,
15415including none at all. The @code{else} is optional, as in Ada.
15416
15417The @code{#} marking the start of a preprocessor line must be the first
15418non-blank character on the line, i.e. it must be preceded only by
15419spaces or horizontal tabs.
15420
15421Symbol substitution outside of preprocessor lines is obtained by using
15422the sequence
15423
15424@smallexample
15425$symbol
15426@end smallexample
15427
15428@noindent
15429anywhere within a source line, except in a comment or within a
15430string literal. The identifier
15431following the @code{$} must match one of the symbols defined in the symbol
15432definition file, and the result is to substitute the value of the
15433symbol in place of @code{$symbol} in the output file.
15434
15435Note that although the substitution of strings within a string literal
15436is not possible, it is possible to have a symbol whose defined value is
15437a string literal. So instead of setting XYZ to @code{hello} and writing:
15438
15439@smallexample
15440Header : String := "$XYZ";
15441@end smallexample
15442
15443@noindent
15444you should set XYZ to @code{"hello"} and write:
15445
15446@smallexample
15447Header : String := $XYZ;
15448@end smallexample
15449
15450@noindent
15451and then the substitution will occur as desired.
15452
15453@ifset vms
15454@node The GNAT Run-Time Library Builder gnatlbr
15455@chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15456@findex gnatlbr
15457@cindex Library builder
15458
15459@noindent
15460@code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15461supplied configuration pragmas.
15462
15463@menu
15464* Running gnatlbr::
15465* Switches for gnatlbr::
15466* Examples of gnatlbr Usage::
15467@end menu
15468
15469@node Running gnatlbr
15470@section Running @code{gnatlbr}
15471
15472@noindent
15473The @code{gnatlbr} command has the form
15474
15475@smallexample
15476$ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15477@end smallexample
15478
15479@node Switches for gnatlbr
15480@section Switches for @code{gnatlbr}
15481
15482@noindent
15483@code{gnatlbr} recognizes the following switches:
15484
15485@table @option
15486@c !sort!
15487@item /CREATE=directory
15488@cindex @code{/CREATE} (@code{gnatlbr})
15489     Create the new run-time library in the specified directory.
15490
15491@item /SET=directory
15492@cindex @code{/SET} (@code{gnatlbr})
15493     Make the library in the specified directory the current run-time
15494     library.
15495
15496@item /DELETE=directory
15497@cindex @code{/DELETE} (@code{gnatlbr})
15498     Delete the run-time library in the specified directory.
15499
15500@item /CONFIG=file
15501@cindex @code{/CONFIG} (@code{gnatlbr})
15502     With /CREATE:
15503     Use the configuration pragmas in the specified file when building
15504     the library.
15505
15506     With /SET:
15507     Use the configuration pragmas in the specified file when compiling.
15508
15509@end table
15510
15511@node Examples of gnatlbr Usage
15512@section Example of @code{gnatlbr} Usage
15513
15514@smallexample
15515Contents of VAXFLOAT.ADC:
15516pragma Float_Representation (VAX_Float);
15517
15518$ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15519
15520GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15521
15522@end smallexample
15523@end ifset
15524
15525@node The GNAT Library Browser gnatls
15526@chapter The GNAT Library Browser @code{gnatls}
15527@findex gnatls
15528@cindex Library browser
15529
15530@noindent
15531@code{gnatls} is a tool that outputs information about compiled
15532units. It gives the relationship between objects, unit names and source
15533files. It can also be used to check the source dependencies of a unit
15534as well as various characteristics.
15535
15536@menu
15537* Running gnatls::
15538* Switches for gnatls::
15539* Examples of gnatls Usage::
15540@end menu
15541
15542@node Running gnatls
15543@section Running @code{gnatls}
15544
15545@noindent
15546The @code{gnatls} command has the form
15547
15548@smallexample
15549$ gnatls switches @var{object_or_ali_file}
15550@end smallexample
15551
15552@noindent
15553The main argument is the list of object or @file{ali} files
15554(@pxref{The Ada Library Information Files})
15555for which information is requested.
15556
15557In normal mode, without additional option, @code{gnatls} produces a
15558four-column listing. Each line represents information for a specific
15559object. The first column gives the full path of the object, the second
15560column gives the name of the principal unit in this object, the third
15561column gives the status of the source and the fourth column gives the
15562full path of the source representing this unit.
15563Here is a simple example of use:
15564
15565@smallexample
15566$ gnatls *.o
15567^./^[]^demo1.o            demo1            DIF demo1.adb
15568^./^[]^demo2.o            demo2             OK demo2.adb
15569^./^[]^hello.o            h1                OK hello.adb
15570^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15571^./^[]^instr.o            instr             OK instr.adb
15572^./^[]^tef.o              tef              DIF tef.adb
15573^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15574^./^[]^tgef.o             tgef             DIF tgef.adb
15575@end smallexample
15576
15577@noindent
15578The first line can be interpreted as follows: the main unit which is
15579contained in
15580object file @file{demo1.o} is demo1, whose main source is in
15581@file{demo1.adb}. Furthermore, the version of the source used for the
15582compilation of demo1 has been modified (DIF). Each source file has a status
15583qualifier which can be:
15584
15585@table @code
15586@item OK (unchanged)
15587The version of the source file used for the compilation of the
15588specified unit corresponds exactly to the actual source file.
15589
15590@item MOK (slightly modified)
15591The version of the source file used for the compilation of the
15592specified unit differs from the actual source file but not enough to
15593require recompilation. If you use gnatmake with the qualifier
15594@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15595MOK will not be recompiled.
15596
15597@item DIF (modified)
15598No version of the source found on the path corresponds to the source
15599used to build this object.
15600
15601@item ??? (file not found)
15602No source file was found for this unit.
15603
15604@item HID (hidden,  unchanged version not first on PATH)
15605The version of the source that corresponds exactly to the source used
15606for compilation has been found on the path but it is hidden by another
15607version of the same source that has been modified.
15608
15609@end table
15610
15611@node Switches for gnatls
15612@section Switches for @code{gnatls}
15613
15614@noindent
15615@code{gnatls} recognizes the following switches:
15616
15617@table @option
15618@c !sort!
15619@item ^-a^/ALL_UNITS^
15620@cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15621Consider all units, including those of the predefined Ada library.
15622Especially useful with @option{^-d^/DEPENDENCIES^}.
15623
15624@item ^-d^/DEPENDENCIES^
15625@cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15626List sources from which specified units depend on.
15627
15628@item ^-h^/OUTPUT=OPTIONS^
15629@cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15630Output the list of options.
15631
15632@item ^-o^/OUTPUT=OBJECTS^
15633@cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15634Only output information about object files.
15635
15636@item ^-s^/OUTPUT=SOURCES^
15637@cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15638Only output information about source files.
15639
15640@item ^-u^/OUTPUT=UNITS^
15641@cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15642Only output information about compilation units.
15643
15644@item ^-aO^/OBJECT_SEARCH=^@var{dir}
15645@itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15646@itemx ^-I^/SEARCH=^@var{dir}
15647@itemx  ^-I-^/NOCURRENT_DIRECTORY^
15648@itemx -nostdinc
15649@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15650@cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15651@cindex @option{^-I^/SEARCH^} (@code{gnatls})
15652@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15653Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
15654(see @ref{Switches for gnatmake}).
15655
15656@item --RTS=@var{rts-path}
15657@cindex @option{--RTS} (@code{gnatls})
15658Specifies the default location of the runtime library. Same meaning as the
15659equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
15660
15661@item ^-v^/OUTPUT=VERBOSE^
15662@cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15663Verbose mode. Output the complete source and object paths. Do not use
15664the default column layout but instead use long format giving as much as
15665information possible on each requested units, including special
15666characteristics such as:
15667
15668@table @code
15669@item  Preelaborable
15670The unit is preelaborable in the Ada 95 sense.
15671
15672@item No_Elab_Code
15673No elaboration code has been produced by the compiler for this unit.
15674
15675@item Pure
15676The unit is pure in the Ada 95 sense.
15677
15678@item Elaborate_Body
15679The unit contains a pragma Elaborate_Body.
15680
15681@item Remote_Types
15682The unit contains a pragma Remote_Types.
15683
15684@item Shared_Passive
15685The unit contains a pragma Shared_Passive.
15686
15687@item Predefined
15688This unit is part of the predefined environment and cannot be modified
15689by the user.
15690
15691@item Remote_Call_Interface
15692The unit contains a pragma Remote_Call_Interface.
15693
15694@end table
15695
15696@end table
15697
15698@node Examples of gnatls Usage
15699@section Example of @code{gnatls} Usage
15700@ifclear vms
15701
15702@noindent
15703Example of using the verbose switch. Note how the source and
15704object paths are affected by the -I switch.
15705
15706@smallexample
15707$ gnatls -v -I.. demo1.o
15708
15709GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
15710
15711Source Search Path:
15712   <Current_Directory>
15713   ../
15714   /home/comar/local/adainclude/
15715
15716Object Search Path:
15717   <Current_Directory>
15718   ../
15719   /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
15720
15721./demo1.o
15722   Unit =>
15723     Name   => demo1
15724     Kind   => subprogram body
15725     Flags  => No_Elab_Code
15726     Source => demo1.adb    modified
15727@end smallexample
15728
15729@noindent
15730The following is an example of use of the dependency list.
15731Note the use of the -s switch
15732which gives a straight list of source files. This can be useful for
15733building specialized scripts.
15734
15735@smallexample
15736$ gnatls -d demo2.o
15737./demo2.o   demo2        OK demo2.adb
15738                         OK gen_list.ads
15739                         OK gen_list.adb
15740                         OK instr.ads
15741                         OK instr-child.ads
15742
15743$ gnatls -d -s -a demo1.o
15744demo1.adb
15745/home/comar/local/adainclude/ada.ads
15746/home/comar/local/adainclude/a-finali.ads
15747/home/comar/local/adainclude/a-filico.ads
15748/home/comar/local/adainclude/a-stream.ads
15749/home/comar/local/adainclude/a-tags.ads
15750gen_list.ads
15751gen_list.adb
15752/home/comar/local/adainclude/gnat.ads
15753/home/comar/local/adainclude/g-io.ads
15754instr.ads
15755/home/comar/local/adainclude/system.ads
15756/home/comar/local/adainclude/s-exctab.ads
15757/home/comar/local/adainclude/s-finimp.ads
15758/home/comar/local/adainclude/s-finroo.ads
15759/home/comar/local/adainclude/s-secsta.ads
15760/home/comar/local/adainclude/s-stalib.ads
15761/home/comar/local/adainclude/s-stoele.ads
15762/home/comar/local/adainclude/s-stratt.ads
15763/home/comar/local/adainclude/s-tasoli.ads
15764/home/comar/local/adainclude/s-unstyp.ads
15765/home/comar/local/adainclude/unchconv.ads
15766@end smallexample
15767@end ifclear
15768
15769@ifset vms
15770@smallexample
15771GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15772
15773GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15774GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15775GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15776GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15777GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15778demo1.adb
15779gen_list.ads
15780gen_list.adb
15781GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15782GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15783instr.ads
15784GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15785GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15786GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15787GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15788GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15789GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15790GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15791GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15792GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15793GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15794GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15795@end smallexample
15796@end ifset
15797
15798@node Cleaning Up Using gnatclean
15799@chapter Cleaning Up Using @code{gnatclean}
15800@findex gnatclean
15801@cindex Cleaning tool
15802
15803@noindent
15804@code{gnatclean} is a tool that allows the deletion of files produced by the
15805compiler, binder and linker, including ALI files, object files, tree files,
15806expanded source files, library files, interface copy source files, binder
15807generated files and executable files.
15808
15809@menu
15810* Running gnatclean::
15811* Switches for gnatclean::
15812* Examples of gnatclean Usage::
15813@end menu
15814
15815@node Running gnatclean
15816@section Running @code{gnatclean}
15817
15818@noindent
15819The @code{gnatclean} command has the form:
15820
15821@smallexample
15822$ gnatclean switches @var{names}
15823@end smallexample
15824
15825@noindent
15826@var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15827@code{^adb^ADB^} may be omitted. If a project file is specified using switch
15828@code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15829
15830@noindent
15831In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15832if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15833the linker. In informative-only mode, specified by switch
15834@code{^-n^/NODELETE^}, the list of files that would have been deleted in
15835normal mode is listed, but no file is actually deleted.
15836
15837@node Switches for gnatclean
15838@section Switches for @code{gnatclean}
15839
15840@noindent
15841@code{gnatclean} recognizes the following switches:
15842
15843@table @option
15844@c !sort!
15845@item ^-c^/COMPILER_FILES_ONLY^
15846@cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15847Only attempt to delete the files produced by the compiler, not those produced
15848by the binder or the linker. The files that are not to be deleted are library
15849files, interface copy files, binder generated files and executable files.
15850
15851@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15852@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15853Indicate that ALI and object files should normally be found in directory
15854@var{dir}.
15855
15856@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15857@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15858When using project files, if some errors or warnings are detected during
15859parsing and verbose mode is not in effect (no use of switch
15860^-v^/VERBOSE^), then error lines start with the full path name of the project
15861file, rather than its simple file name.
15862
15863@item ^-h^/HELP^
15864@cindex @option{^-h^/HELP^} (@code{gnatclean})
15865Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15866
15867@item ^-n^/NODELETE^
15868@cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15869Informative-only mode. Do not delete any files. Output the list of the files
15870that would have been deleted if this switch was not specified.
15871
15872@item ^-P^/PROJECT_FILE=^@var{project}
15873@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15874Use project file @var{project}. Only one such switch can be used.
15875When cleaning a project file, the files produced by the compilation of the
15876immediate sources or inherited sources of the project files are to be
15877deleted. This is not depending on the presence or not of executable names
15878on the command line.
15879
15880@item ^-q^/QUIET^
15881@cindex @option{^-q^/QUIET^} (@code{gnatclean})
15882Quiet output. If there are no error, do not ouuput anything, except in
15883verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15884(switch ^-n^/NODELETE^).
15885
15886@item ^-r^/RECURSIVE^
15887@cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15888When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15889clean all imported and extended project files, recursively. If this switch
15890is not specified, only the files related to the main project file are to be
15891deleted. This switch has no effect if no project file is specified.
15892
15893@item ^-v^/VERBOSE^
15894@cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15895Verbose mode.
15896
15897@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15898@cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15899Indicates the verbosity of the parsing of GNAT project files.
15900See @ref{Switches Related to Project Files}.
15901
15902@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15903@cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15904Indicates that external variable @var{name} has the value @var{value}.
15905The Project Manager will use this value for occurrences of
15906@code{external(name)} when parsing the project file.
15907See @ref{Switches Related to Project Files}.
15908
15909@item ^-aO^/OBJECT_SEARCH=^@var{dir}
15910@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15911When searching for ALI and object files, look in directory
15912@var{dir}.
15913
15914@item ^-I^/SEARCH=^@var{dir}
15915@cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15916Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15917
15918@item ^-I-^/NOCURRENT_DIRECTORY^
15919@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15920@cindex Source files, suppressing search
15921Do not look for ALI or object files in the directory
15922where @code{gnatclean} was invoked.
15923
15924@end table
15925
15926@node Examples of gnatclean Usage
15927@section Examples of @code{gnatclean} Usage
15928
15929@ifclear vms
15930@node GNAT and Libraries
15931@chapter GNAT and Libraries
15932@cindex Library, building, installing
15933
15934@noindent
15935This chapter addresses some of the issues related to building and using
15936a library with GNAT. It also shows how the GNAT run-time library can be
15937recompiled.
15938
15939@menu
15940* Creating an Ada Library::
15941* Installing an Ada Library::
15942* Using an Ada Library::
15943* Creating an Ada Library to be Used in a Non-Ada Context::
15944* Rebuilding the GNAT Run-Time Library::
15945@end menu
15946
15947@node Creating an Ada Library
15948@section Creating an Ada Library
15949
15950@noindent
15951In the GNAT environment, a library has two components:
15952@itemize @bullet
15953@item
15954Source files.
15955@item
15956Compiled code and Ali files. See @ref{The Ada Library Information Files}.
15957@end itemize
15958
15959@noindent
15960In order to use other packages @ref{The GNAT Compilation Model}
15961requires a certain number of sources to be available to the compiler.
15962The minimal set of
15963sources required includes the specs of all the packages that make up the
15964visible part of the library as well as all the sources upon which they
15965depend. The bodies of all visible generic units must also be provided.
15966@noindent
15967Although it is not strictly mandatory, it is recommended that all sources
15968needed to recompile the library be provided, so that the user can make
15969full use of inter-unit inlining and source-level debugging. This can also
15970make the situation easier for users that need to upgrade their compilation
15971toolchain and thus need to recompile the library from sources.
15972
15973@noindent
15974The compiled code can be provided in different ways. The simplest way is
15975to provide directly the set of objects produced by the compiler during
15976the compilation of the library. It is also possible to group the objects
15977into an archive using whatever commands are provided by the operating
15978system. Finally, it is also possible to create a shared library (see
15979option -shared in the GCC manual).
15980
15981@noindent
15982There are various possibilities for compiling the units that make up the
15983library: for example with a Makefile @ref{Using the GNU make Utility},
15984or with a conventional script.
15985For simple libraries, it is also possible to create a
15986dummy main program which depends upon all the packages that comprise the
15987interface of the library. This dummy main program can then be given to
15988gnatmake, in order to build all the necessary objects. Here is an example
15989of such a dummy program and the generic commands used to build an
15990archive or a shared library.
15991
15992@smallexample @c ada
15993@iftex
15994@leftskip=.7cm
15995@end iftex
15996with My_Lib.Service1;
15997with My_Lib.Service2;
15998with My_Lib.Service3;
15999procedure My_Lib_Dummy is
16000begin
16001   null;
16002end;
16003@end smallexample
16004
16005@smallexample
16006# compiling the library
16007$ gnatmake -c my_lib_dummy.adb
16008
16009# we don't need the dummy object itself
16010$ rm my_lib_dummy.o my_lib_dummy.ali
16011
16012# create an archive with the remaining objects
16013$ ar rc libmy_lib.a *.o
16014# some systems may require "ranlib" to be run as well
16015
16016# or create a shared library
16017$ gcc -shared -o libmy_lib.so *.o
16018# some systems may require the code to have been compiled with -fPIC
16019
16020# remove the object files that are now in the library
16021$ rm *.o
16022
16023# Make the ALI files read-only so that gnatmake will not try to
16024# regenerate the objects that are in the library
16025$ chmod -w *.ali
16026
16027@end smallexample
16028
16029@noindent
16030When the objects are grouped in an archive or a shared library, the user
16031needs to specify the desired library at link time, unless a pragma
16032linker_options has been used in one of the sources:
16033@smallexample @c ada
16034pragma Linker_Options ("-lmy_lib");
16035@end smallexample
16036
16037@noindent
16038Please note that the library must have a name of the form libxxx.a or
16039libxxx.so in order to be accessed by the directive -lxxx at link
16040time.
16041
16042@node Installing an Ada Library
16043@section Installing an Ada Library
16044
16045@noindent
16046In the GNAT model, installing a library consists in copying into a specific
16047location the files that make up this library. It is possible to install
16048the sources in a different directory from the other files (ALI, objects,
16049archives) since the source path and the object path can easily be
16050specified separately.
16051
16052@noindent
16053For general purpose libraries, it is possible for the system
16054administrator to put those libraries in the default compiler paths. To
16055achieve this, he must specify their location in the configuration files
16056@file{ada_source_path} and @file{ada_object_path} that must be located in
16057the GNAT
16058installation tree at the same place as the gcc spec file. The location of
16059the gcc spec file can be determined as follows:
16060@smallexample
16061$ gcc -v
16062@end smallexample
16063
16064@noindent
16065The configuration files mentioned above have simple format: each line in them
16066must contain one unique
16067directory name. Those names are added to the corresponding path
16068in their order of appearance in the file. The names can be either absolute
16069or relative, in the latter case, they are relative to where theses files
16070are located.
16071
16072@noindent
16073@file{ada_source_path} and @file{ada_object_path} might actually not be
16074present in a
16075GNAT installation, in which case, GNAT will look for its run-time library in
16076he directories @file{adainclude} for the sources and @file{adalib} for the
16077objects and @file{ALI} files. When the files exist, the compiler does not
16078look in @file{adainclude} and @file{adalib} at all, and thus the
16079@file{ada_source_path} file
16080must contain the location for the GNAT run-time sources (which can simply
16081be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16082contain the location for the GNAT run-time objects (which can simply
16083be @file{adalib}).
16084
16085@noindent
16086You can also specify a new default path to the runtime library at compilation
16087time with the switch @option{--RTS=rts-path}. You can easily choose and change
16088the runtime you want your program to be compiled with. This switch is
16089recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
16090
16091@noindent
16092It is possible to install a library before or after the standard GNAT
16093library, by reordering the lines in the configuration files. In general, a
16094library must be installed before the GNAT library if it redefines
16095any part of it.
16096
16097@node Using an Ada Library
16098@section Using an Ada Library
16099
16100@noindent
16101In order to use a Ada library, you need to make sure that this
16102library is on both your source and object path
16103@ref{Search Paths and the Run-Time Library (RTL)}
16104and @ref{Search Paths for gnatbind}. For
16105instance, you can use the library @file{mylib} installed in
16106@file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16107
16108@smallexample
16109$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16110  -largs -lmy_lib
16111@end smallexample
16112
16113@noindent
16114This can be simplified down to the following:
16115@smallexample
16116$ gnatmake my_appl
16117@end smallexample
16118when the following conditions are met:
16119@itemize @bullet
16120@item
16121@file{/dir/my_lib_src} has been added by the user to the environment
16122variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16123@file{ada_source_path}
16124@item
16125@file{/dir/my_lib_obj} has been added by the user to the environment
16126variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16127@file{ada_object_path}
16128@item
16129a pragma @code{Linker_Options}, as mentioned in @ref{Creating an Ada Library},
16130has been added to the sources.
16131@end itemize
16132@noindent
16133
16134@node Creating an Ada Library to be Used in a Non-Ada Context
16135@section Creating an Ada Library to be Used in a Non-Ada Context
16136
16137@noindent
16138The previous sections detailed how to create and install a library that
16139was usable from an Ada main program. Using this library in a non-Ada
16140context is not possible, because the elaboration of the library is
16141automatically done as part of the main program elaboration.
16142
16143GNAT also provides the ability to build libraries that can be used both
16144in an Ada and non-Ada context.  This section describes how to build such
16145a library, and then how to use it from a C program. The method for
16146interfacing with the library from other languages such as Fortran for
16147instance remains the same.
16148
16149@subsection Creating the Library
16150
16151@itemize @bullet
16152@item Identify the units representing the interface of the library.
16153
16154Here is an example of simple library interface:
16155
16156@smallexample @c ada
16157package Interface is
16158
16159   procedure Do_Something;
16160
16161   procedure Do_Something_Else;
16162
16163end Interface;
16164@end smallexample
16165
16166@item Use @code{pragma Export} or @code{pragma Convention} for the
16167exported entities.
16168
16169Our package @code{Interface} is then updated as follow:
16170@smallexample @c ada
16171package Interface is
16172
16173   procedure Do_Something;
16174   pragma Export (C, Do_Something, "do_something");
16175
16176   procedure Do_Something_Else;
16177   pragma Export (C, Do_Something_Else, "do_something_else");
16178
16179end Interface;
16180@end smallexample
16181
16182@item Compile all the units composing the library.
16183
16184@item Bind the library objects.
16185
16186This step is performed by invoking gnatbind with the @option{-L<prefix>}
16187switch. @code{gnatbind} will then generate the library elaboration
16188procedure (named @code{<prefix>init}) and the run-time finalization
16189procedure (named @code{<prefix>final}).
16190
16191@smallexample
16192# generate the binder file in Ada
16193$ gnatbind -Lmylib interface
16194
16195# generate the binder file in C
16196$ gnatbind -C -Lmylib interface
16197@end smallexample
16198
16199@item Compile the files generated by the binder
16200
16201@smallexample
16202$ gcc -c b~interface.adb
16203@end smallexample
16204
16205@item Create the library;
16206
16207The procedure is identical to the procedure explained in
16208@ref{Creating an Ada Library},
16209except that @file{b~interface.o} needs to be added to
16210the list of objects.
16211
16212@smallexample
16213# create an archive file
16214$ ar cr libmylib.a b~interface.o <other object files>
16215
16216# create a shared library
16217$ gcc -shared -o libmylib.so b~interface.o <other object files>
16218@end smallexample
16219
16220@item Provide a ``foreign'' view of the library interface;
16221
16222The example below shows the content of @code{mylib_interface.h} (note
16223that there is no rule for the naming of this file, any name can be used)
16224@smallexample
16225/* the library elaboration procedure */
16226extern void mylibinit (void);
16227
16228/* the library finalization procedure */
16229extern void mylibfinal (void);
16230
16231/* the interface exported by the library */
16232extern void do_something (void);
16233extern void do_something_else (void);
16234@end smallexample
16235@end itemize
16236
16237@subsection Using the Library
16238
16239@noindent
16240Libraries built as explained above can be used from any program, provided
16241that the elaboration procedures (named @code{mylibinit} in the previous
16242example) are called before the library services are used. Any number of
16243libraries can be used simultaneously, as long as the elaboration
16244procedure of each library is called.
16245
16246Below is an example of C program that uses our @code{mylib} library.
16247
16248@smallexample
16249#include "mylib_interface.h"
16250
16251int
16252main (void)
16253@{
16254   /* First, elaborate the library before using it */
16255   mylibinit ();
16256
16257   /* Main program, using the library exported entities */
16258   do_something ();
16259   do_something_else ();
16260
16261   /* Library finalization at the end of the program */
16262   mylibfinal ();
16263   return 0;
16264@}
16265@end smallexample
16266
16267@noindent
16268Note that this same library can be used from an equivalent Ada main
16269program. In addition, if the libraries are installed as detailed in
16270@ref{Installing an Ada Library}, it is not necessary to invoke the
16271library elaboration and finalization routines. The binder will ensure
16272that this is done as part of the main program elaboration and
16273finalization phases.
16274
16275@subsection The Finalization Phase
16276
16277@noindent
16278Invoking any library finalization procedure generated by @code{gnatbind}
16279shuts down the Ada run time permanently. Consequently, the finalization
16280of all Ada libraries must be performed at the end of the program. No
16281call to these libraries nor the Ada run time should be made past the
16282finalization phase.
16283
16284@subsection Restrictions in Libraries
16285
16286@noindent
16287The pragmas listed below should be used with caution inside libraries,
16288as they can create incompatibilities with other Ada libraries:
16289@itemize @bullet
16290@item pragma @code{Locking_Policy}
16291@item pragma @code{Queuing_Policy}
16292@item pragma @code{Task_Dispatching_Policy}
16293@item pragma @code{Unreserve_All_Interrupts}
16294@end itemize
16295When using a library that contains such pragmas, the user must make sure
16296that all libraries use the same pragmas with the same values. Otherwise,
16297a @code{Program_Error} will
16298be raised during the elaboration of the conflicting
16299libraries. The usage of these pragmas and its consequences for the user
16300should therefore be well documented.
16301
16302Similarly, the traceback in exception occurrences mechanism should be
16303enabled or disabled in a consistent manner across all libraries.
16304Otherwise, a Program_Error will be raised during the elaboration of the
16305conflicting libraries.
16306
16307If the @code{'Version} and @code{'Body_Version}
16308attributes are used inside a library, then it is necessary to
16309perform a @code{gnatbind} step that mentions all @file{ALI} files in all
16310libraries, so that version identifiers can be properly computed.
16311In practice these attributes are rarely used, so this is unlikely
16312to be a consideration.
16313
16314@node  Rebuilding the GNAT Run-Time Library
16315@section Rebuilding the GNAT Run-Time Library
16316
16317@noindent
16318It may be useful to recompile the GNAT library in various contexts, the
16319most important one being the use of partition-wide configuration pragmas
16320such as Normalize_Scalar. A special Makefile called
16321@code{Makefile.adalib} is provided to that effect and can be found in
16322the directory containing the GNAT library. The location of this
16323directory depends on the way the GNAT environment has been installed and can
16324be determined by means of the command:
16325
16326@smallexample
16327$ gnatls -v
16328@end smallexample
16329
16330@noindent
16331The last entry in the object search path usually contains the
16332gnat library. This Makefile contains its own documentation and in
16333particular the set of instructions needed to rebuild a new library and
16334to use it.
16335
16336@node Using the GNU make Utility
16337@chapter Using the GNU @code{make} Utility
16338@findex make
16339
16340@noindent
16341This chapter offers some examples of makefiles that solve specific
16342problems. It does not explain how to write a makefile (see the GNU make
16343documentation), nor does it try to replace the @code{gnatmake} utility
16344(@pxref{The GNAT Make Program gnatmake}).
16345
16346All the examples in this section are specific to the GNU version of
16347make. Although @code{make} is a standard utility, and the basic language
16348is the same, these examples use some advanced features found only in
16349@code{GNU make}.
16350
16351@menu
16352* Using gnatmake in a Makefile::
16353* Automatically Creating a List of Directories::
16354* Generating the Command Line Switches::
16355* Overcoming Command Line Length Limits::
16356@end menu
16357
16358@node Using gnatmake in a Makefile
16359@section Using gnatmake in a Makefile
16360@findex makefile
16361@cindex GNU make
16362
16363@noindent
16364Complex project organizations can be handled in a very powerful way by
16365using GNU make combined with gnatmake. For instance, here is a Makefile
16366which allows you to build each subsystem of a big project into a separate
16367shared library. Such a makefile allows you to significantly reduce the link
16368time of very big applications while maintaining full coherence at
16369each step of the build process.
16370
16371The list of dependencies are handled automatically by
16372@code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16373the appropriate directories.
16374
16375Note that you should also read the example on how to automatically
16376create the list of directories
16377(@pxref{Automatically Creating a List of Directories})
16378which might help you in case your project has a lot of subdirectories.
16379
16380@smallexample
16381@iftex
16382@leftskip=0cm
16383@font@heightrm=cmr8
16384@heightrm
16385@end iftex
16386## This Makefile is intended to be used with the following directory
16387## configuration:
16388##  - The sources are split into a series of csc (computer software components)
16389##    Each of these csc is put in its own directory.
16390##    Their name are referenced by the directory names.
16391##    They will be compiled into shared library (although this would also work
16392##    with static libraries
16393##  - The main program (and possibly other packages that do not belong to any
16394##    csc is put in the top level directory (where the Makefile is).
16395##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16396##                    \_ second_csc (sources) __ lib (will contain the library)
16397##                    \_ ...
16398## Although this Makefile is build for shared library, it is easy to modify
16399## to build partial link objects instead (modify the lines with -shared and
16400## gnatlink below)
16401##
16402## With this makefile, you can change any file in the system or add any new
16403## file, and everything will be recompiled correctly (only the relevant shared
16404## objects will be recompiled, and the main program will be re-linked).
16405
16406# The list of computer software component for your project. This might be
16407# generated automatically.
16408CSC_LIST=aa bb cc
16409
16410# Name of the main program (no extension)
16411MAIN=main
16412
16413# If we need to build objects with -fPIC, uncomment the following line
16414#NEED_FPIC=-fPIC
16415
16416# The following variable should give the directory containing libgnat.so
16417# You can get this directory through 'gnatls -v'. This is usually the last
16418# directory in the Object_Path.
16419GLIB=...
16420
16421# The directories for the libraries
16422# (This macro expands the list of CSC to the list of shared libraries, you
16423# could simply use the expanded form :
16424# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16425LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16426
16427$@{MAIN@}: objects $@{LIB_DIR@}
16428    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16429    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16430
16431objects::
16432    # recompile the sources
16433    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16434
16435# Note: In a future version of GNAT, the following commands will be simplified
16436# by a new tool, gnatmlib
16437$@{LIB_DIR@}:
16438    mkdir -p $@{dir $@@ @}
16439    cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16440    cd $@{dir $@@ @}; cp -f ../*.ali .
16441
16442# The dependencies for the modules
16443# Note that we have to force the expansion of *.o, since in some cases
16444# make won't be able to do it itself.
16445aa/lib/libaa.so: $@{wildcard aa/*.o@}
16446bb/lib/libbb.so: $@{wildcard bb/*.o@}
16447cc/lib/libcc.so: $@{wildcard cc/*.o@}
16448
16449# Make sure all of the shared libraries are in the path before starting the
16450# program
16451run::
16452    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16453
16454clean::
16455    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16456    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16457    $@{RM@} $@{CSC_LIST:%=%/*.o@}
16458    $@{RM@} *.o *.ali $@{MAIN@}
16459@end smallexample
16460
16461@node Automatically Creating a List of Directories
16462@section Automatically Creating a List of Directories
16463
16464@noindent
16465In most makefiles, you will have to specify a list of directories, and
16466store it in a variable. For small projects, it is often easier to
16467specify each of them by hand, since you then have full control over what
16468is the proper order for these directories, which ones should be
16469included...
16470
16471However, in larger projects, which might involve hundreds of
16472subdirectories, it might be more convenient to generate this list
16473automatically.
16474
16475The example below presents two methods. The first one, although less
16476general, gives you more control over the list. It involves wildcard
16477characters, that are automatically expanded by @code{make}. Its
16478shortcoming is that you need to explicitly specify some of the
16479organization of your project, such as for instance the directory tree
16480depth, whether some directories are found in a separate tree,...
16481
16482The second method is the most general one. It requires an external
16483program, called @code{find}, which is standard on all Unix systems. All
16484the directories found under a given root directory will be added to the
16485list.
16486
16487@smallexample
16488@iftex
16489@leftskip=0cm
16490@font@heightrm=cmr8
16491@heightrm
16492@end iftex
16493# The examples below are based on the following directory hierarchy:
16494# All the directories can contain any number of files
16495# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16496#                       ->  ab
16497#                       ->  ac
16498#                ->  b  ->  ba  ->  baa
16499#                       ->  bb
16500#                       ->  bc
16501# This Makefile creates a variable called DIRS, that can be reused any time
16502# you need this list (see the other examples in this section)
16503
16504# The root of your project's directory hierarchy
16505ROOT_DIRECTORY=.
16506
16507####
16508# First method: specify explicitly the list of directories
16509# This allows you to specify any subset of all the directories you need.
16510####
16511
16512DIRS := a/aa/ a/ab/ b/ba/
16513
16514####
16515# Second method: use wildcards
16516# Note that the argument(s) to wildcard below should end with a '/'.
16517# Since wildcards also return file names, we have to filter them out
16518# to avoid duplicate directory names.
16519# We thus use make's @code{dir} and @code{sort} functions.
16520# It sets DIRs to the following value (note that the directories aaa and baa
16521# are not given, unless you change the arguments to wildcard).
16522# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16523####
16524
16525DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16526                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16527
16528####
16529# Third method: use an external program
16530# This command is much faster if run on local disks, avoiding NFS slowdowns.
16531# This is the most complete command: it sets DIRs to the following value:
16532# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16533####
16534
16535DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16536
16537@end smallexample
16538
16539@node Generating the Command Line Switches
16540@section Generating the Command Line Switches
16541
16542@noindent
16543Once you have created the list of directories as explained in the
16544previous section (@pxref{Automatically Creating a List of Directories}),
16545you can easily generate the command line arguments to pass to gnatmake.
16546
16547For the sake of completeness, this example assumes that the source path
16548is not the same as the object path, and that you have two separate lists
16549of directories.
16550
16551@smallexample
16552# see "Automatically creating a list of directories" to create
16553# these variables
16554SOURCE_DIRS=
16555OBJECT_DIRS=
16556
16557GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16558GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16559
16560all:
16561        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16562@end smallexample
16563
16564@node Overcoming Command Line Length Limits
16565@section Overcoming Command Line Length Limits
16566
16567@noindent
16568One problem that might be encountered on big projects is that many
16569operating systems limit the length of the command line. It is thus hard to give
16570gnatmake the list of source and object directories.
16571
16572This example shows how you can set up environment variables, which will
16573make @code{gnatmake} behave exactly as if the directories had been
16574specified on the command line, but have a much higher length limit (or
16575even none on most systems).
16576
16577It assumes that you have created a list of directories in your Makefile,
16578using one of the methods presented in
16579@ref{Automatically Creating a List of Directories}.
16580For the sake of completeness, we assume that the object
16581path (where the ALI files are found) is different from the sources patch.
16582
16583Note a small trick in the Makefile below: for efficiency reasons, we
16584create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16585expanded immediately by @code{make}. This way we overcome the standard
16586make behavior which is to expand the variables only when they are
16587actually used.
16588
16589On Windows, if you are using the standard Windows command shell, you must
16590replace colons with semicolons in the assignments to these variables.
16591
16592@smallexample
16593@iftex
16594@leftskip=0cm
16595@font@heightrm=cmr8
16596@heightrm
16597@end iftex
16598# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16599# This is the same thing as putting the -I arguments on the command line.
16600# (the equivalent of using -aI on the command line would be to define
16601#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16602# You can of course have different values for these variables.
16603#
16604# Note also that we need to keep the previous values of these variables, since
16605# they might have been set before running 'make' to specify where the GNAT
16606# library is installed.
16607
16608# see "Automatically creating a list of directories" to create these
16609# variables
16610SOURCE_DIRS=
16611OBJECT_DIRS=
16612
16613empty:=
16614space:=$@{empty@} $@{empty@}
16615SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16616OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16617ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16618ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16619export ADA_INCLUDE_PATH
16620export ADA_OBJECT_PATH
16621
16622all:
16623        gnatmake main_unit
16624@end smallexample
16625@end ifclear
16626
16627
16628@node Finding Memory Problems
16629@chapter Finding Memory Problems
16630
16631@noindent
16632This chapter describes
16633@ifclear vms
16634the @command{gnatmem} tool, which can be used to track down
16635``memory leaks'', and
16636@end ifclear
16637the GNAT Debug Pool facility, which can be used to detect incorrect uses of
16638access values (including ``dangling references'').
16639
16640@menu
16641@ifclear vms
16642* The gnatmem Tool::
16643@end ifclear
16644* The GNAT Debug Pool Facility::
16645@end menu
16646
16647
16648@ifclear vms
16649@node The gnatmem Tool
16650@section The @command{gnatmem} Tool
16651@findex gnatmem
16652
16653@noindent
16654The @code{gnatmem} utility monitors dynamic allocation and
16655deallocation activity in a program, and displays information about
16656incorrect deallocations and possible sources of memory leaks.
16657It provides three type of information:
16658@itemize @bullet
16659@item
16660General information concerning memory management, such as the total
16661number of allocations and deallocations, the amount of allocated
16662memory and the high water mark, i.e. the largest amount of allocated
16663memory in the course of program execution.
16664
16665@item
16666Backtraces for all incorrect deallocations, that is to say deallocations
16667which do not correspond to a valid allocation.
16668
16669@item
16670Information on each allocation that is potentially the origin of a memory
16671leak.
16672@end itemize
16673
16674@menu
16675* Running gnatmem::
16676* Switches for gnatmem::
16677* Example of gnatmem Usage::
16678@end menu
16679
16680@node Running gnatmem
16681@subsection Running @code{gnatmem}
16682
16683@noindent
16684@code{gnatmem} makes use of the output created by the special version of
16685allocation and deallocation routines that record call information. This
16686allows to obtain accurate dynamic memory usage history at a minimal cost to
16687the execution speed. Note however, that @code{gnatmem} is not supported on
16688all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
16689Solaris (sparc and x86) and Windows NT/2000/XP (x86).
16690
16691@noindent
16692The @code{gnatmem} command has the form
16693
16694@smallexample
16695   $ gnatmem [switches] user_program
16696@end smallexample
16697
16698@noindent
16699The program must have been linked with the instrumented version of the
16700allocation and deallocation routines. This is done by linking with the
16701@file{libgmem.a} library. For correct symbolic backtrace information,
16702the user program should be compiled with debugging options
16703@ref{Switches for gcc}. For example to build @file{my_program}:
16704
16705@smallexample
16706$ gnatmake -g my_program -largs -lgmem
16707@end smallexample
16708
16709@noindent
16710When running @file{my_program} the file @file{gmem.out} is produced. This file
16711contains information about all allocations and deallocations done by the
16712program. It is produced by the instrumented allocations and
16713deallocations routines and will be used by @code{gnatmem}.
16714
16715@noindent
16716Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16717examine. If the location of @file{gmem.out} file was not explicitly supplied by
16718@code{-i} switch, gnatmem will assume that this file can be found in the
16719current directory. For example, after you have executed @file{my_program},
16720@file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16721
16722@smallexample
16723$ gnatmem my_program
16724@end smallexample
16725
16726@noindent
16727This will produce the output with the following format:
16728
16729*************** debut cc
16730@smallexample
16731$ gnatmem my_program
16732
16733Global information
16734------------------
16735   Total number of allocations        :  45
16736   Total number of deallocations      :   6
16737   Final Water Mark (non freed mem)   :  11.29 Kilobytes
16738   High Water Mark                    :  11.40 Kilobytes
16739
16740.
16741.
16742.
16743Allocation Root # 2
16744-------------------
16745 Number of non freed allocations    :  11
16746 Final Water Mark (non freed mem)   :   1.16 Kilobytes
16747 High Water Mark                    :   1.27 Kilobytes
16748 Backtrace                          :
16749   my_program.adb:23 my_program.alloc
16750.
16751.
16752.
16753@end smallexample
16754
16755The first block of output gives general information. In this case, the
16756Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16757Unchecked_Deallocation routine occurred.
16758
16759@noindent
16760Subsequent paragraphs display  information on all allocation roots.
16761An allocation root is a specific point in the execution of the program
16762that generates some dynamic allocation, such as a ``@code{@b{new}}''
16763construct. This root is represented by an execution backtrace (or subprogram
16764call stack). By default the backtrace depth for allocations roots is 1, so
16765that a root corresponds exactly to a source location. The backtrace can
16766be made deeper, to make the root more specific.
16767
16768@node Switches for gnatmem
16769@subsection Switches for @code{gnatmem}
16770
16771@noindent
16772@code{gnatmem} recognizes the following switches:
16773
16774@table @option
16775
16776@item -q
16777@cindex @option{-q} (@code{gnatmem})
16778Quiet. Gives the minimum output needed to identify the origin of the
16779memory leaks. Omits statistical information.
16780
16781@item @var{N}
16782@cindex @var{N} (@code{gnatmem})
16783N is an integer literal (usually between 1 and 10) which controls the
16784depth of the backtraces defining allocation root. The default value for
16785N is 1. The deeper the backtrace, the more precise the localization of
16786the root. Note that the total number of roots can depend on this
16787parameter. This parameter must be specified @emph{before} the name of the
16788executable to be analyzed, to avoid ambiguity.
16789
16790@item -b n
16791@cindex @option{-b} (@code{gnatmem})
16792This switch has the same effect as just depth parameter.
16793
16794@item -i @var{file}
16795@cindex @option{-i} (@code{gnatmem})
16796Do the @code{gnatmem} processing starting from @file{file}, rather than
16797@file{gmem.out} in the current directory.
16798
16799@item -m n
16800@cindex @option{-m} (@code{gnatmem})
16801This switch causes @code{gnatmem} to mask the allocation roots that have less
16802than n leaks. The default value is 1. Specifying the value of 0 will allow to
16803examine even the roots that didn't result in leaks.
16804
16805@item -s order
16806@cindex @option{-s} (@code{gnatmem})
16807This switch causes @code{gnatmem} to sort the allocation roots according to the
16808specified order of sort criteria, each identified by a single letter. The
16809currently supported criteria are @code{n, h, w} standing respectively for
16810number of unfreed allocations, high watermark, and final watermark
16811corresponding to a specific root. The default order is @code{nwh}.
16812
16813@end table
16814
16815@node Example of gnatmem Usage
16816@subsection Example of @code{gnatmem} Usage
16817
16818@noindent
16819The following example shows the use of @code{gnatmem}
16820on a simple memory-leaking program.
16821Suppose that we have the following Ada program:
16822
16823@smallexample @c ada
16824@group
16825@cartouche
16826with Unchecked_Deallocation;
16827procedure Test_Gm is
16828
16829   type T is array (1..1000) of Integer;
16830   type Ptr is access T;
16831   procedure Free is new Unchecked_Deallocation (T, Ptr);
16832   A : Ptr;
16833
16834   procedure My_Alloc is
16835   begin
16836      A := new T;
16837   end My_Alloc;
16838
16839   procedure My_DeAlloc is
16840      B : Ptr := A;
16841   begin
16842      Free (B);
16843   end My_DeAlloc;
16844
16845begin
16846   My_Alloc;
16847   for I in 1 .. 5 loop
16848      for J in I .. 5 loop
16849         My_Alloc;
16850      end loop;
16851      My_Dealloc;
16852   end loop;
16853end;
16854@end cartouche
16855@end group
16856@end smallexample
16857
16858@noindent
16859The program needs to be compiled with debugging option and linked with
16860@code{gmem} library:
16861
16862@smallexample
16863$ gnatmake -g test_gm -largs -lgmem
16864@end smallexample
16865
16866@noindent
16867Then we execute the program as usual:
16868
16869@smallexample
16870$ test_gm
16871@end smallexample
16872
16873@noindent
16874Then @code{gnatmem} is invoked simply with
16875@smallexample
16876$ gnatmem test_gm
16877@end smallexample
16878
16879@noindent
16880which produces the following output (result may vary on different platforms):
16881
16882@smallexample
16883Global information
16884------------------
16885   Total number of allocations        :  18
16886   Total number of deallocations      :   5
16887   Final Water Mark (non freed mem)   :  53.00 Kilobytes
16888   High Water Mark                    :  56.90 Kilobytes
16889
16890Allocation Root # 1
16891-------------------
16892 Number of non freed allocations    :  11
16893 Final Water Mark (non freed mem)   :  42.97 Kilobytes
16894 High Water Mark                    :  46.88 Kilobytes
16895 Backtrace                          :
16896   test_gm.adb:11 test_gm.my_alloc
16897
16898Allocation Root # 2
16899-------------------
16900 Number of non freed allocations    :   1
16901 Final Water Mark (non freed mem)   :  10.02 Kilobytes
16902 High Water Mark                    :  10.02 Kilobytes
16903 Backtrace                          :
16904   s-secsta.adb:81 system.secondary_stack.ss_init
16905
16906Allocation Root # 3
16907-------------------
16908 Number of non freed allocations    :   1
16909 Final Water Mark (non freed mem)   :  12 Bytes
16910 High Water Mark                    :  12 Bytes
16911 Backtrace                          :
16912   s-secsta.adb:181 system.secondary_stack.ss_init
16913@end smallexample
16914
16915@noindent
16916Note that the GNAT run time contains itself a certain number of
16917allocations that have no  corresponding deallocation,
16918as shown here for root #2 and root
16919#3. This is a normal behavior when the number of non freed allocations
16920is one, it allocates dynamic data structures that the run time needs for
16921the complete lifetime of the program. Note also that there is only one
16922allocation root in the user program with a single line back trace:
16923test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16924program shows that 'My_Alloc' is called at 2 different points in the
16925source (line 21 and line 24). If those two allocation roots need to be
16926distinguished, the backtrace depth parameter can be used:
16927
16928@smallexample
16929$ gnatmem 3 test_gm
16930@end smallexample
16931
16932@noindent
16933which will give the following output:
16934
16935@smallexample
16936Global information
16937------------------
16938   Total number of allocations        :  18
16939   Total number of deallocations      :   5
16940   Final Water Mark (non freed mem)   :  53.00 Kilobytes
16941   High Water Mark                    :  56.90 Kilobytes
16942
16943Allocation Root # 1
16944-------------------
16945 Number of non freed allocations    :  10
16946 Final Water Mark (non freed mem)   :  39.06 Kilobytes
16947 High Water Mark                    :  42.97 Kilobytes
16948 Backtrace                          :
16949   test_gm.adb:11 test_gm.my_alloc
16950   test_gm.adb:24 test_gm
16951   b_test_gm.c:52 main
16952
16953Allocation Root # 2
16954-------------------
16955 Number of non freed allocations    :   1
16956 Final Water Mark (non freed mem)   :  10.02 Kilobytes
16957 High Water Mark                    :  10.02 Kilobytes
16958 Backtrace                          :
16959   s-secsta.adb:81  system.secondary_stack.ss_init
16960   s-secsta.adb:283 <system__secondary_stack___elabb>
16961   b_test_gm.c:33   adainit
16962
16963Allocation Root # 3
16964-------------------
16965 Number of non freed allocations    :   1
16966 Final Water Mark (non freed mem)   :   3.91 Kilobytes
16967 High Water Mark                    :   3.91 Kilobytes
16968 Backtrace                          :
16969   test_gm.adb:11 test_gm.my_alloc
16970   test_gm.adb:21 test_gm
16971   b_test_gm.c:52 main
16972
16973Allocation Root # 4
16974-------------------
16975 Number of non freed allocations    :   1
16976 Final Water Mark (non freed mem)   :  12 Bytes
16977 High Water Mark                    :  12 Bytes
16978 Backtrace                          :
16979   s-secsta.adb:181 system.secondary_stack.ss_init
16980   s-secsta.adb:283 <system__secondary_stack___elabb>
16981   b_test_gm.c:33   adainit
16982@end smallexample
16983
16984@noindent
16985The allocation root #1 of the first example has been split in 2 roots #1
16986and #3 thanks to the more precise associated backtrace.
16987
16988@end ifclear
16989
16990
16991@node The GNAT Debug Pool Facility
16992@section The GNAT Debug Pool Facility
16993@findex Debug Pool
16994@cindex storage, pool, memory corruption
16995
16996@noindent
16997The use of unchecked deallocation and unchecked conversion can easily
16998lead to incorrect memory references. The problems generated by such
16999references are usually difficult to tackle because the symptoms can be
17000very remote from the origin of the problem. In such cases, it is
17001very helpful to detect the problem as early as possible. This is the
17002purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17003
17004In order to use the GNAT specific debugging pool, the user must
17005associate a debug pool object with each of the access types that may be
17006related to suspected memory problems. See Ada Reference Manual 13.11.
17007@smallexample @c ada
17008type Ptr is access Some_Type;
17009Pool : GNAT.Debug_Pools.Debug_Pool;
17010for Ptr'Storage_Pool use Pool;
17011@end smallexample
17012
17013@noindent
17014@code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17015pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17016allow the user to redefine allocation and deallocation strategies. They
17017also provide a checkpoint for each dereference, through the use of
17018the primitive operation @code{Dereference} which is implicitly called at
17019each dereference of an access value.
17020
17021Once an access type has been associated with a debug pool, operations on
17022values of the type may raise four distinct exceptions,
17023which correspond to four potential kinds of memory corruption:
17024@itemize @bullet
17025@item
17026@code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17027@item
17028@code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17029@item
17030@code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17031@item
17032@code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17033@end itemize
17034
17035@noindent
17036For types associated with a Debug_Pool, dynamic allocation is performed using
17037the standard
17038GNAT allocation routine. References to all allocated chunks of memory
17039are kept in an internal dictionary.
17040Several deallocation strategies are provided, whereupon the user can choose
17041to release the memory to the system, keep it allocated for further invalid
17042access checks, or fill it with an easily recognizable pattern for debug
17043sessions.
17044The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17045
17046See the documentation in the file g-debpoo.ads for more information on the
17047various strategies.
17048
17049Upon each dereference, a check is made that the access value denotes a
17050properly allocated memory location. Here is a complete example of use of
17051@code{Debug_Pools}, that includes typical instances of  memory corruption:
17052@smallexample @c ada
17053@iftex
17054@leftskip=0cm
17055@end iftex
17056with Gnat.Io; use Gnat.Io;
17057with Unchecked_Deallocation;
17058with Unchecked_Conversion;
17059with GNAT.Debug_Pools;
17060with System.Storage_Elements;
17061with Ada.Exceptions; use Ada.Exceptions;
17062procedure Debug_Pool_Test is
17063
17064   type T is access Integer;
17065   type U is access all T;
17066
17067   P : GNAT.Debug_Pools.Debug_Pool;
17068   for T'Storage_Pool use P;
17069
17070   procedure Free is new Unchecked_Deallocation (Integer, T);
17071   function UC is new Unchecked_Conversion (U, T);
17072   A, B : aliased T;
17073
17074   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17075
17076begin
17077   Info (P);
17078   A := new Integer;
17079   B := new Integer;
17080   B := A;
17081   Info (P);
17082   Free (A);
17083   begin
17084      Put_Line (Integer'Image(B.all));
17085   exception
17086      when E : others => Put_Line ("raised: " & Exception_Name (E));
17087   end;
17088   begin
17089      Free (B);
17090   exception
17091      when E : others => Put_Line ("raised: " & Exception_Name (E));
17092   end;
17093   B := UC(A'Access);
17094   begin
17095      Put_Line (Integer'Image(B.all));
17096   exception
17097      when E : others => Put_Line ("raised: " & Exception_Name (E));
17098   end;
17099   begin
17100      Free (B);
17101   exception
17102      when E : others => Put_Line ("raised: " & Exception_Name (E));
17103   end;
17104   Info (P);
17105end Debug_Pool_Test;
17106@end smallexample
17107
17108@noindent
17109The debug pool mechanism provides the following precise diagnostics on the
17110execution of this erroneous program:
17111@smallexample
17112Debug Pool info:
17113  Total allocated bytes :  0
17114  Total deallocated bytes :  0
17115  Current Water Mark:  0
17116  High Water Mark:  0
17117
17118Debug Pool info:
17119  Total allocated bytes :  8
17120  Total deallocated bytes :  0
17121  Current Water Mark:  8
17122  High Water Mark:  8
17123
17124raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17125raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17126raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17127raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17128Debug Pool info:
17129  Total allocated bytes :  8
17130  Total deallocated bytes :  4
17131  Current Water Mark:  4
17132  High Water Mark:  8
17133@end smallexample
17134
17135
17136@node Creating Sample Bodies Using gnatstub
17137@chapter Creating Sample Bodies Using @command{gnatstub}
17138@findex gnatstub
17139
17140@noindent
17141@command{gnatstub} creates body stubs, that is, empty but compilable bodies
17142for library unit declarations.
17143
17144To create a body stub, @command{gnatstub} has to compile the library
17145unit declaration. Therefore, bodies can be created only for legal
17146library units. Moreover, if a library unit depends semantically upon
17147units located outside the current directory, you have to provide
17148the source search path when calling @command{gnatstub}, see the description
17149of @command{gnatstub} switches below.
17150
17151@menu
17152* Running gnatstub::
17153* Switches for gnatstub::
17154@end menu
17155
17156@node Running gnatstub
17157@section Running @command{gnatstub}
17158
17159@noindent
17160@command{gnatstub} has the command-line interface of the form
17161
17162@smallexample
17163$ gnatstub [switches] filename [directory]
17164@end smallexample
17165
17166@noindent
17167where
17168@table @emph
17169@item filename
17170is the name of the source file that contains a library unit declaration
17171for which a body must be created. The file name may contain the path
17172information.
17173The file name does not have to follow the GNAT file name conventions. If the
17174name
17175does not follow GNAT file naming conventions, the name of the body file must
17176be provided
17177explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17178If the file name follows the GNAT file naming
17179conventions and the name of the body file is not provided,
17180@command{gnatstub}
17181creates the name
17182of the body file from the argument file name by replacing the @file{.ads}
17183suffix
17184with the @file{.adb} suffix.
17185
17186@item directory
17187indicates the directory in which the body stub is to be placed (the default
17188is the
17189current directory)
17190
17191@item switches
17192is an optional sequence of switches as described in the next section
17193@end table
17194
17195@node Switches for gnatstub
17196@section Switches for @command{gnatstub}
17197
17198@table @option
17199@c !sort!
17200
17201@item ^-f^/FULL^
17202@cindex @option{^-f^/FULL^} (@command{gnatstub})
17203If the destination directory already contains a file with the name of the
17204body file
17205for the argument spec file, replace it with the generated body stub.
17206
17207@item ^-hs^/HEADER=SPEC^
17208@cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17209Put the comment header (i.e., all the comments preceding the
17210compilation unit) from the source of the library unit declaration
17211into the body stub.
17212
17213@item ^-hg^/HEADER=GENERAL^
17214@cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17215Put a sample comment header into the body stub.
17216
17217@ifclear vms
17218@item -IDIR
17219@cindex @option{-IDIR} (@command{gnatstub})
17220@itemx -I-
17221@cindex @option{-I-} (@command{gnatstub})
17222@end ifclear
17223@ifset vms
17224@item /NOCURRENT_DIRECTORY
17225@cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17226@end ifset
17227^These switches have ^This switch has^ the same meaning as in calls to
17228@command{gcc}.
17229^They define ^It defines ^ the source search path in the call to
17230@command{gcc} issued
17231by @command{gnatstub} to compile an argument source file.
17232
17233@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17234@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17235This switch has the same meaning as in calls to @command{gcc}.
17236It defines the additional configuration file to be passed to the call to
17237@command{gcc} issued
17238by @command{gnatstub} to compile an argument source file.
17239
17240@item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17241@cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17242(@var{n} is a non-negative integer). Set the maximum line length in the
17243body stub to @var{n}; the default is 79. The maximum value that can be
17244specified is 32767.
17245
17246@item ^-gnaty^/STYLE_CHECKS=^@var{n}
17247@cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17248(@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17249the generated body sample to @var{n}.
17250The default indentation is 3.
17251
17252@item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17253@cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17254Order local bodies alphabetically. (By default local bodies are ordered
17255in the same way as the corresponding local specs in the argument spec file.)
17256
17257@item ^-i^/INDENTATION=^@var{n}
17258@cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17259Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17260
17261@item ^-k^/TREE_FILE=SAVE^
17262@cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17263Do not remove the tree file (i.e., the snapshot of the compiler internal
17264structures used by @command{gnatstub}) after creating the body stub.
17265
17266@item ^-l^/LINE_LENGTH=^@var{n}
17267@cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17268Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17269
17270@item ^-o^/BODY=^@var{body-name}
17271@cindex @option{^-o^/BODY^} (@command{gnatstub})
17272Body file name.  This should be set if the argument file name does not
17273follow
17274the GNAT file naming
17275conventions. If this switch is omitted the default name for the body will be
17276obtained
17277from the argument file name according to the GNAT file naming conventions.
17278
17279@item ^-q^/QUIET^
17280@cindex @option{^-q^/QUIET^} (@command{gnatstub})
17281Quiet mode: do not generate a confirmation when a body is
17282successfully created, and do not generate a message when a body is not
17283required for an
17284argument unit.
17285
17286@item ^-r^/TREE_FILE=REUSE^
17287@cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17288Reuse the tree file (if it exists) instead of creating it.  Instead of
17289creating the tree file for the library unit declaration, @command{gnatstub}
17290tries to find it in the current directory and use it for creating
17291a body. If the tree file is not found, no body is created. This option
17292also implies @option{^-k^/SAVE^}, whether or not
17293the latter is set explicitly.
17294
17295@item ^-t^/TREE_FILE=OVERWRITE^
17296@cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17297Overwrite the existing tree file.  If the current directory already
17298contains the file which, according to the GNAT file naming rules should
17299be considered as a tree file for the argument source file,
17300@command{gnatstub}
17301will refuse to create the tree file needed to create a sample body
17302unless this option is set.
17303
17304@item ^-v^/VERBOSE^
17305@cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17306Verbose mode: generate version information.
17307
17308@end table
17309
17310
17311@node Other Utility Programs
17312@chapter Other Utility Programs
17313
17314@noindent
17315This chapter discusses some other utility programs available in the Ada
17316environment.
17317
17318@menu
17319* Using Other Utility Programs with GNAT::
17320* The External Symbol Naming Scheme of GNAT::
17321@ifclear vms
17322* Ada Mode for Glide::
17323@end ifclear
17324* Converting Ada Files to html with gnathtml::
17325* Installing gnathtml::
17326@ifset vms
17327* LSE::
17328* Profiling::
17329@end ifset
17330@end menu
17331
17332@node Using Other Utility Programs with GNAT
17333@section Using Other Utility Programs with GNAT
17334
17335@noindent
17336The object files generated by GNAT are in standard system format and in
17337particular the debugging information uses this format. This means
17338programs generated by GNAT can be used with existing utilities that
17339depend on these formats.
17340
17341@ifclear vms
17342In general, any utility program that works with C will also often work with
17343Ada programs generated by GNAT. This includes software utilities such as
17344gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17345as Purify.
17346@end ifclear
17347
17348@node The External Symbol Naming Scheme of GNAT
17349@section The External Symbol Naming Scheme of GNAT
17350
17351@noindent
17352In order to interpret the output from GNAT, when using tools that are
17353originally intended for use with other languages, it is useful to
17354understand the conventions used to generate link names from the Ada
17355entity names.
17356
17357All link names are in all lowercase letters. With the exception of library
17358procedure names, the mechanism used is simply to use the full expanded
17359Ada name with dots replaced by double underscores. For example, suppose
17360we have the following package spec:
17361
17362@smallexample @c ada
17363@group
17364@cartouche
17365package QRS is
17366   MN : Integer;
17367end QRS;
17368@end cartouche
17369@end group
17370@end smallexample
17371
17372@noindent
17373The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17374the corresponding link name is @code{qrs__mn}.
17375@findex Export
17376Of course if a @code{pragma Export} is used this may be overridden:
17377
17378@smallexample @c ada
17379@group
17380@cartouche
17381package Exports is
17382   Var1 : Integer;
17383   pragma Export (Var1, C, External_Name => "var1_name");
17384   Var2 : Integer;
17385   pragma Export (Var2, C, Link_Name => "var2_link_name");
17386end Exports;
17387@end cartouche
17388@end group
17389@end smallexample
17390
17391@noindent
17392In this case, the link name for @var{Var1} is whatever link name the
17393C compiler would assign for the C function @var{var1_name}. This typically
17394would be either @var{var1_name} or @var{_var1_name}, depending on operating
17395system conventions, but other possibilities exist. The link name for
17396@var{Var2} is @var{var2_link_name}, and this is not operating system
17397dependent.
17398
17399@findex _main
17400One exception occurs for library level procedures. A potential ambiguity
17401arises between the required name @code{_main} for the C main program,
17402and the name we would otherwise assign to an Ada library level procedure
17403called @code{Main} (which might well not be the main program).
17404
17405To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17406names. So if we have a library level procedure such as
17407
17408@smallexample @c ada
17409@group
17410@cartouche
17411procedure Hello (S : String);
17412@end cartouche
17413@end group
17414@end smallexample
17415
17416@noindent
17417the external name of this procedure will be @var{_ada_hello}.
17418
17419@ifclear vms
17420@node Ada Mode for Glide
17421@section Ada Mode for @code{Glide}
17422@cindex Ada mode (for Glide)
17423
17424@noindent
17425The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
17426user to understand and navigate existing code, and facilitates writing
17427new code. It furthermore provides some utility functions for easier
17428integration of standard Emacs features when programming in Ada.
17429
17430Its general features include:
17431
17432@itemize @bullet
17433@item
17434An Integrated Development Environment with functionality such as the
17435following
17436
17437@itemize @bullet
17438@item
17439``Project files'' for configuration-specific aspects
17440(e.g. directories and compilation options)
17441
17442@item
17443Compiling and stepping through error messages.
17444
17445@item
17446Running and debugging an applications within Glide.
17447@end itemize
17448
17449@item
17450Pull-down menus
17451
17452@item
17453User configurability
17454@end itemize
17455
17456Some of the specific Ada mode features are:
17457
17458@itemize @bullet
17459@item
17460Functions for easy and quick stepping through Ada code
17461
17462@item
17463Getting cross reference information for identifiers (e.g., finding a
17464defining occurrence)
17465
17466@item
17467Displaying an index menu of types and subprograms, allowing
17468direct selection for browsing
17469
17470@item
17471Automatic color highlighting of the various Ada entities
17472@end itemize
17473
17474Glide directly supports writing Ada code, via several facilities:
17475
17476@itemize @bullet
17477@item
17478Switching between spec and body files with possible
17479autogeneration of body files
17480
17481@item
17482Automatic formating of subprogram parameter lists
17483
17484@item
17485Automatic indentation according to Ada syntax
17486
17487@item
17488Automatic completion of identifiers
17489
17490@item
17491Automatic (and configurable) casing of identifiers, keywords, and attributes
17492
17493@item
17494Insertion of syntactic templates
17495
17496@item
17497Block commenting / uncommenting
17498@end itemize
17499
17500@noindent
17501For more information, please refer to the online documentation
17502available in the @code{Glide} @result{} @code{Help} menu.
17503@end ifclear
17504
17505
17506@node Converting Ada Files to html with gnathtml
17507@section Converting Ada Files to HTML with @code{gnathtml}
17508
17509@noindent
17510This @code{Perl} script allows Ada source files to be browsed using
17511standard Web browsers. For installation procedure, see the section
17512@xref{Installing gnathtml}.
17513
17514Ada reserved keywords are highlighted in a bold font and Ada comments in
17515a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17516switch to suppress the generation of cross-referencing information, user
17517defined variables and types will appear in a different color; you will
17518be able to click on any identifier and go to its declaration.
17519
17520The command line is as follow:
17521@smallexample
17522$ perl gnathtml.pl [switches] ada-files
17523@end smallexample
17524
17525@noindent
17526You can pass it as many Ada files as you want. @code{gnathtml} will generate
17527an html file for every ada file, and a global file called @file{index.htm}.
17528This file is an index of every identifier defined in the files.
17529
17530The available switches are the following ones :
17531
17532@table @option
17533@item -83
17534@cindex @option{-83} (@code{gnathtml})
17535Only the subset on the Ada 83 keywords will be highlighted, not the full
17536Ada 95 keywords set.
17537
17538@item -cc @var{color}
17539@cindex @option{-cc} (@code{gnathtml})
17540This option allows you to change the color used for comments. The default
17541value is green. The color argument can be any name accepted by html.
17542
17543@item -d
17544@cindex @option{-d} (@code{gnathtml})
17545If the ada files depend on some other files (using for instance the
17546@code{with} command, the latter will also be converted to html.
17547Only the files in the user project will be converted to html, not the files
17548in the run-time library itself.
17549
17550@item -D
17551@cindex @option{-D} (@code{gnathtml})
17552This command is the same as @option{-d} above, but @command{gnathtml} will
17553also look for files in the run-time library, and generate html files for them.
17554
17555@item -ext @var{extension}
17556@cindex @option{-ext} (@code{gnathtml})
17557This option allows you to change the extension of the generated HTML files.
17558If you do not specify an extension, it will default to @file{htm}.
17559
17560@item -f
17561@cindex @option{-f} (@code{gnathtml})
17562By default, gnathtml will generate html links only for global entities
17563('with'ed units, global variables and types,...). If you specify the
17564@option{-f} on the command line, then links will be generated for local
17565entities too.
17566
17567@item -l @var{number}
17568@cindex @option{-l} (@code{gnathtml})
17569If this switch is provided and @var{number} is not 0, then @code{gnathtml}
17570will number the html files every @var{number} line.
17571
17572@item -I @var{dir}
17573@cindex @option{-I} (@code{gnathtml})
17574Specify a directory to search for library files (@file{.ALI} files) and
17575source files. You can provide several -I switches on the command line,
17576and the directories will be parsed in the order of the command line.
17577
17578@item -o @var{dir}
17579@cindex @option{-o} (@code{gnathtml})
17580Specify the output directory for html files. By default, gnathtml will
17581saved the generated html files in a subdirectory named @file{html/}.
17582
17583@item -p @var{file}
17584@cindex @option{-p} (@code{gnathtml})
17585If you are using Emacs and the most recent Emacs Ada mode, which provides
17586a full Integrated Development Environment for compiling, checking,
17587running and debugging applications, you may use @file{.gpr} files
17588to give the directories where Emacs can find sources and object files.
17589
17590Using this switch, you can tell gnathtml to use these files. This allows
17591you to get an html version of your application, even if it is spread
17592over multiple directories.
17593
17594@item -sc @var{color}
17595@cindex @option{-sc} (@code{gnathtml})
17596This option allows you to change the color used for symbol definitions.
17597The default value is red. The color argument can be any name accepted by html.
17598
17599@item -t @var{file}
17600@cindex @option{-t} (@code{gnathtml})
17601This switch provides the name of a file. This file contains a list of
17602file names to be converted, and the effect is exactly as though they had
17603appeared explicitly on the command line. This
17604is the recommended way to work around the command line length limit on some
17605systems.
17606
17607@end table
17608
17609@node Installing gnathtml
17610@section Installing @code{gnathtml}
17611
17612@noindent
17613@code{Perl} needs to be installed on your machine to run this script.
17614@code{Perl} is freely available for almost every architecture and
17615Operating System via the Internet.
17616
17617On Unix systems, you  may want to modify  the  first line of  the script
17618@code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17619is. The syntax of this line is :
17620@smallexample
17621#!full_path_name_to_perl
17622@end smallexample
17623
17624@noindent
17625Alternatively, you may run the script using the following command line:
17626
17627@smallexample
17628$ perl gnathtml.pl [switches] files
17629@end smallexample
17630
17631@ifset vms
17632@node LSE
17633@section LSE
17634@findex LSE
17635
17636@noindent
17637The GNAT distribution provides an Ada 95 template for the Digital Language
17638Sensitive Editor (LSE), a component of DECset. In order to
17639access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
17640
17641@node Profiling
17642@section Profiling
17643@findex PCA
17644
17645@noindent
17646GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
17647of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
17648the collection phase with the /DEBUG qualifier.
17649
17650@smallexample
17651$ GNAT MAKE /DEBUG <PROGRAM_NAME>
17652$ DEFINE LIB$DEBUG PCA$COLLECTOR
17653$ RUN/DEBUG <PROGRAM_NAME>
17654@end smallexample
17655@noindent
17656@end ifset
17657
17658@node Running and Debugging Ada Programs
17659@chapter Running and Debugging Ada Programs
17660@cindex Debugging
17661
17662@noindent
17663This chapter discusses how to debug Ada programs. An incorrect Ada program
17664may be handled in three ways by the GNAT compiler:
17665
17666@enumerate
17667@item
17668The illegality may be a violation of the static semantics of Ada. In
17669that case GNAT diagnoses the constructs in the program that are illegal.
17670It is then a straightforward matter for the user to modify those parts of
17671the program.
17672
17673@item
17674The illegality may be a violation of the dynamic semantics of Ada. In
17675that case the program compiles and executes, but may generate incorrect
17676results, or may terminate abnormally with some exception.
17677
17678@item
17679When presented with a program that contains convoluted errors, GNAT
17680itself may terminate abnormally without providing full diagnostics on
17681the incorrect user program.
17682@end enumerate
17683
17684@menu
17685* The GNAT Debugger GDB::
17686* Running GDB::
17687* Introduction to GDB Commands::
17688* Using Ada Expressions::
17689* Calling User-Defined Subprograms::
17690* Using the Next Command in a Function::
17691* Ada Exceptions::
17692* Ada Tasks::
17693* Debugging Generic Units::
17694* GNAT Abnormal Termination or Failure to Terminate::
17695* Naming Conventions for GNAT Source Files::
17696* Getting Internal Debugging Information::
17697* Stack Traceback::
17698@end menu
17699
17700@cindex Debugger
17701@findex gdb
17702
17703@node The GNAT Debugger GDB
17704@section The GNAT Debugger GDB
17705
17706@noindent
17707@code{GDB} is a general purpose, platform-independent debugger that
17708can be used to debug mixed-language programs compiled with @code{GCC},
17709and in particular is capable of debugging Ada programs compiled with
17710GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
17711complex Ada data structures.
17712
17713The manual @cite{Debugging with GDB}
17714@ifset vms
17715, located in the GNU:[DOCS] directory,
17716@end ifset
17717contains full details on the usage of @code{GDB}, including a section on
17718its usage on programs. This manual should be consulted for full
17719details. The section that follows is a brief introduction to the
17720philosophy and use of @code{GDB}.
17721
17722When GNAT programs are compiled, the compiler optionally writes debugging
17723information into the generated object file, including information on
17724line numbers, and on declared types and variables. This information is
17725separate from the generated code. It makes the object files considerably
17726larger, but it does not add to the size of the actual executable that
17727will be loaded into memory, and has no impact on run-time performance. The
17728generation of debug information is triggered by the use of the
17729^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
17730the compilations. It is important to emphasize that the use of these
17731options does not change the generated code.
17732
17733The debugging information is written in standard system formats that
17734are used by many tools, including debuggers and profilers. The format
17735of the information is typically designed to describe C types and
17736semantics, but GNAT implements a translation scheme which allows full
17737details about Ada types and variables to be encoded into these
17738standard C formats. Details of this encoding scheme may be found in
17739the file exp_dbug.ads in the GNAT source distribution. However, the
17740details of this encoding are, in general, of no interest to a user,
17741since @code{GDB} automatically performs the necessary decoding.
17742
17743When a program is bound and linked, the debugging information is
17744collected from the object files, and stored in the executable image of
17745the program. Again, this process significantly increases the size of
17746the generated executable file, but it does not increase the size of
17747the executable program itself. Furthermore, if this program is run in
17748the normal manner, it runs exactly as if the debug information were
17749not present, and takes no more actual memory.
17750
17751However, if the program is run under control of @code{GDB}, the
17752debugger is activated.  The image of the program is loaded, at which
17753point it is ready to run.  If a run command is given, then the program
17754will run exactly as it would have if @code{GDB} were not present. This
17755is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
17756entirely non-intrusive until a breakpoint is encountered.  If no
17757breakpoint is ever hit, the program will run exactly as it would if no
17758debugger were present. When a breakpoint is hit, @code{GDB} accesses
17759the debugging information and can respond to user commands to inspect
17760variables, and more generally to report on the state of execution.
17761
17762@c **************
17763@node Running GDB
17764@section Running GDB
17765
17766@noindent
17767The debugger can be launched directly and simply from @code{glide} or
17768through its graphical interface: @code{gvd}. It can also be used
17769directly in text mode. Here is described the basic use of @code{GDB}
17770in text mode. All the commands described below can be used in the
17771@code{gvd} console window even though there is usually other more
17772graphical ways to achieve the same goals.
17773
17774@ifclear vms
17775@noindent
17776The command to run the graphical interface of the debugger is
17777@smallexample
17778$ gvd program
17779@end smallexample
17780@end ifclear
17781
17782@noindent
17783The command to run @code{GDB} in text mode is
17784
17785@smallexample
17786$ ^gdb program^$ GDB PROGRAM^
17787@end smallexample
17788
17789@noindent
17790where @code{^program^PROGRAM^} is the name of the executable file. This
17791activates the debugger and results in a prompt for debugger commands.
17792The simplest command is simply @code{run}, which causes the program to run
17793exactly as if the debugger were not present. The following section
17794describes some of the additional commands that can be given to @code{GDB}.
17795
17796
17797@c *******************************
17798@node Introduction to GDB Commands
17799@section Introduction to GDB Commands
17800
17801@noindent
17802@code{GDB} contains a large repertoire of commands. The manual
17803@cite{Debugging with GDB}
17804@ifset vms
17805, located in the GNU:[DOCS] directory,
17806@end ifset
17807includes extensive documentation on the use
17808of these commands, together with examples of their use. Furthermore,
17809the command @var{help} invoked from within @code{GDB} activates a simple help
17810facility which summarizes the available commands and their options.
17811In this section we summarize a few of the most commonly
17812used commands to give an idea of what @code{GDB} is about. You should create
17813a simple program with debugging information and experiment with the use of
17814these @code{GDB} commands on the program as you read through the
17815following section.
17816
17817@table @code
17818@item set args @var{arguments}
17819The @var{arguments} list above is a list of arguments to be passed to
17820the program on a subsequent run command, just as though the arguments
17821had been entered on a normal invocation of the program. The @code{set args}
17822command is not needed if the program does not require arguments.
17823
17824@item run
17825The @code{run} command causes execution of the program to start from
17826the beginning. If the program is already running, that is to say if
17827you are currently positioned at a breakpoint, then a prompt will ask
17828for confirmation that you want to abandon the current execution and
17829restart.
17830
17831@item breakpoint @var{location}
17832The breakpoint command sets a breakpoint, that is to say a point at which
17833execution will halt and @code{GDB} will await further
17834commands. @var{location} is
17835either a line number within a file, given in the format @code{file:linenumber},
17836or it is the name of a subprogram. If you request that a breakpoint be set on
17837a subprogram that is overloaded, a prompt will ask you to specify on which of
17838those subprograms you want to breakpoint. You can also
17839specify that all of them should be breakpointed. If the program is run
17840and execution encounters the breakpoint, then the program
17841stops and @code{GDB} signals that the breakpoint was encountered by
17842printing the line of code before which the program is halted.
17843
17844@item breakpoint exception @var{name}
17845A special form of the breakpoint command which breakpoints whenever
17846exception @var{name} is raised.
17847If @var{name} is omitted,
17848then a breakpoint will occur when any exception is raised.
17849
17850@item print @var{expression}
17851This will print the value of the given expression. Most simple
17852Ada expression formats are properly handled by @code{GDB}, so the expression
17853can contain function calls, variables, operators, and attribute references.
17854
17855@item continue
17856Continues execution following a breakpoint, until the next breakpoint or the
17857termination of the program.
17858
17859@item step
17860Executes a single line after a breakpoint. If the next statement
17861is a subprogram call, execution continues into (the first statement of)
17862the called subprogram.
17863
17864@item next
17865Executes a single line. If this line is a subprogram call, executes and
17866returns from the call.
17867
17868@item list
17869Lists a few lines around the current source location. In practice, it
17870is usually more convenient to have a separate edit window open with the
17871relevant source file displayed. Successive applications of this command
17872print subsequent lines. The command can be given an argument which is a
17873line number, in which case it displays a few lines around the specified one.
17874
17875@item backtrace
17876Displays a backtrace of the call chain. This command is typically
17877used after a breakpoint has occurred, to examine the sequence of calls that
17878leads to the current breakpoint. The display includes one line for each
17879activation record (frame) corresponding to an active subprogram.
17880
17881@item up
17882At a breakpoint, @code{GDB} can display the values of variables local
17883to the current frame. The command @code{up} can be used to
17884examine the contents of other active frames, by moving the focus up
17885the stack, that is to say from callee to caller, one frame at a time.
17886
17887@item down
17888Moves the focus of @code{GDB} down from the frame currently being
17889examined to the frame of its callee (the reverse of the previous command),
17890
17891@item frame @var{n}
17892Inspect the frame with the given number. The value 0 denotes the frame
17893of the current breakpoint, that is to say the top of the call stack.
17894
17895@end table
17896
17897The above list is a very short introduction to the commands that
17898@code{GDB} provides. Important additional capabilities, including conditional
17899breakpoints, the ability to execute command sequences on a breakpoint,
17900the ability to debug at the machine instruction level and many other
17901features are described in detail in @cite{Debugging with GDB}.
17902Note that most commands can be abbreviated
17903(for example, c for continue, bt for backtrace).
17904
17905@node Using Ada Expressions
17906@section Using Ada Expressions
17907@cindex Ada expressions
17908
17909@noindent
17910@code{GDB} supports a fairly large subset of Ada expression syntax, with some
17911extensions. The philosophy behind the design of this subset is
17912
17913@itemize @bullet
17914@item
17915That @code{GDB} should provide basic literals and access to operations for
17916arithmetic, dereferencing, field selection, indexing, and subprogram calls,
17917leaving more sophisticated computations to subprograms written into the
17918program (which therefore may be called from @code{GDB}).
17919
17920@item
17921That type safety and strict adherence to Ada language restrictions
17922are not particularly important to the @code{GDB} user.
17923
17924@item
17925That brevity is important to the @code{GDB} user.
17926@end itemize
17927
17928Thus, for brevity, the debugger acts as if there were
17929implicit @code{with} and @code{use} clauses in effect for all user-written
17930packages, thus making it unnecessary to fully qualify most names with
17931their packages, regardless of context. Where this causes ambiguity,
17932@code{GDB} asks the user's intent.
17933
17934For details on the supported Ada syntax, see @cite{Debugging with GDB}.
17935
17936@node Calling User-Defined Subprograms
17937@section Calling User-Defined Subprograms
17938
17939@noindent
17940An important capability of @code{GDB} is the ability to call user-defined
17941subprograms while debugging. This is achieved simply by entering
17942a subprogram call statement in the form:
17943
17944@smallexample
17945call subprogram-name (parameters)
17946@end smallexample
17947
17948@noindent
17949The keyword @code{call} can be omitted in the normal case where the
17950@code{subprogram-name} does not coincide with any of the predefined
17951@code{GDB} commands.
17952
17953The effect is to invoke the given subprogram, passing it the
17954list of parameters that is supplied. The parameters can be expressions and
17955can include variables from the program being debugged. The
17956subprogram must be defined
17957at the library level within your program, and @code{GDB} will call the
17958subprogram within the environment of your program execution (which
17959means that the subprogram is free to access or even modify variables
17960within your program).
17961
17962The most important use of this facility is in allowing the inclusion of
17963debugging routines that are tailored to particular data structures
17964in your program. Such debugging routines can be written to provide a suitably
17965high-level description of an abstract type, rather than a low-level dump
17966of its physical layout. After all, the standard
17967@code{GDB print} command only knows the physical layout of your
17968types, not their abstract meaning. Debugging routines can provide information
17969at the desired semantic level and are thus enormously useful.
17970
17971For example, when debugging GNAT itself, it is crucial to have access to
17972the contents of the tree nodes used to represent the program internally.
17973But tree nodes are represented simply by an integer value (which in turn
17974is an index into a table of nodes).
17975Using the @code{print} command on a tree node would simply print this integer
17976value, which is not very useful. But the PN routine (defined in file
17977treepr.adb in the GNAT sources) takes a tree node as input, and displays
17978a useful high level representation of the tree node, which includes the
17979syntactic category of the node, its position in the source, the integers
17980that denote descendant nodes and parent node, as well as varied
17981semantic information. To study this example in more detail, you might want to
17982look at the body of the PN procedure in the stated file.
17983
17984@node Using the Next Command in a Function
17985@section Using the Next Command in a Function
17986
17987@noindent
17988When you use the @code{next} command in a function, the current source
17989location will advance to the next statement as usual. A special case
17990arises in the case of a @code{return} statement.
17991
17992Part of the code for a return statement is the ``epilog'' of the function.
17993This is the code that returns to the caller. There is only one copy of
17994this epilog code, and it is typically associated with the last return
17995statement in the function if there is more than one return. In some
17996implementations, this epilog is associated with the first statement
17997of the function.
17998
17999The result is that if you use the @code{next} command from a return
18000statement that is not the last return statement of the function you
18001may see a strange apparent jump to the last return statement or to
18002the start of the function. You should simply ignore this odd jump.
18003The value returned is always that from the first return statement
18004that was stepped through.
18005
18006@node Ada Exceptions
18007@section Breaking on Ada Exceptions
18008@cindex Exceptions
18009
18010@noindent
18011You can set breakpoints that trip when your program raises
18012selected exceptions.
18013
18014@table @code
18015@item break exception
18016Set a breakpoint that trips whenever (any task in the) program raises
18017any exception.
18018
18019@item break exception @var{name}
18020Set a breakpoint that trips whenever (any task in the) program raises
18021the exception @var{name}.
18022
18023@item break exception unhandled
18024Set a breakpoint that trips whenever (any task in the) program raises an
18025exception for which there is no handler.
18026
18027@item info exceptions
18028@itemx info exceptions @var{regexp}
18029The @code{info exceptions} command permits the user to examine all defined
18030exceptions within Ada programs. With a regular expression, @var{regexp}, as
18031argument, prints out only those exceptions whose name matches @var{regexp}.
18032@end table
18033
18034@node Ada Tasks
18035@section Ada Tasks
18036@cindex Tasks
18037
18038@noindent
18039@code{GDB} allows the following task-related commands:
18040
18041@table @code
18042@item info tasks
18043This command shows a list of current Ada tasks, as in the following example:
18044
18045@smallexample
18046@iftex
18047@leftskip=0cm
18048@end iftex
18049(gdb) info tasks
18050  ID       TID P-ID   Thread Pri State                 Name
18051   1   8088000   0   807e000  15 Child Activation Wait main_task
18052   2   80a4000   1   80ae000  15 Accept/Select Wait    b
18053   3   809a800   1   80a4800  15 Child Activation Wait a
18054*  4   80ae800   3   80b8000  15 Running               c
18055@end smallexample
18056
18057@noindent
18058In this listing, the asterisk before the first task indicates it to be the
18059currently running task. The first column lists the task ID that is used
18060to refer to tasks in the following commands.
18061
18062@item break @var{linespec} task @var{taskid}
18063@itemx break @var{linespec} task @var{taskid} if @dots{}
18064@cindex Breakpoints and tasks
18065These commands are like the @code{break @dots{} thread @dots{}}.
18066@var{linespec} specifies source lines.
18067
18068Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18069to specify that you only want @code{GDB} to stop the program when a
18070particular Ada task reaches this breakpoint. @var{taskid} is one of the
18071numeric task identifiers assigned by @code{GDB}, shown in the first
18072column of the @samp{info tasks} display.
18073
18074If you do not specify @samp{task @var{taskid}} when you set a
18075breakpoint, the breakpoint applies to @emph{all} tasks of your
18076program.
18077
18078You can use the @code{task} qualifier on conditional breakpoints as
18079well; in this case, place @samp{task @var{taskid}} before the
18080breakpoint condition (before the @code{if}).
18081
18082@item task @var{taskno}
18083@cindex Task switching
18084
18085This command allows to switch to the task referred by @var{taskno}. In
18086particular, This allows to browse the backtrace of the specified
18087task. It is advised to switch back to the original task before
18088continuing execution otherwise the scheduling of the program may be
18089perturbated.
18090@end table
18091
18092@noindent
18093For more detailed information on the tasking support,
18094see @cite{Debugging with GDB}.
18095
18096@node Debugging Generic Units
18097@section Debugging Generic Units
18098@cindex Debugging Generic Units
18099@cindex Generics
18100
18101@noindent
18102GNAT always uses code expansion for generic instantiation. This means that
18103each time an instantiation occurs, a complete copy of the original code is
18104made, with appropriate substitutions of formals by actuals.
18105
18106It is not possible to refer to the original generic entities in
18107@code{GDB}, but it is always possible to debug a particular instance of
18108a generic, by using the appropriate expanded names. For example, if we have
18109
18110@smallexample @c ada
18111@group
18112@cartouche
18113procedure g is
18114
18115   generic package k is
18116      procedure kp (v1 : in out integer);
18117   end k;
18118
18119   package body k is
18120      procedure kp (v1 : in out integer) is
18121      begin
18122         v1 := v1 + 1;
18123      end kp;
18124   end k;
18125
18126   package k1 is new k;
18127   package k2 is new k;
18128
18129   var : integer := 1;
18130
18131begin
18132   k1.kp (var);
18133   k2.kp (var);
18134   k1.kp (var);
18135   k2.kp (var);
18136end;
18137@end cartouche
18138@end group
18139@end smallexample
18140
18141@noindent
18142Then to break on a call to procedure kp in the k2 instance, simply
18143use the command:
18144
18145@smallexample
18146(gdb) break g.k2.kp
18147@end smallexample
18148
18149@noindent
18150When the breakpoint occurs, you can step through the code of the
18151instance in the normal manner and examine the values of local variables, as for
18152other units.
18153
18154@node GNAT Abnormal Termination or Failure to Terminate
18155@section GNAT Abnormal Termination or Failure to Terminate
18156@cindex GNAT Abnormal Termination or Failure to Terminate
18157
18158@noindent
18159When presented with programs that contain serious errors in syntax
18160or semantics,
18161GNAT may on rare occasions  experience problems in operation, such
18162as aborting with a
18163segmentation fault or illegal memory access, raising an internal
18164exception, terminating abnormally, or failing to terminate at all.
18165In such cases, you can activate
18166various features of GNAT that can help you pinpoint the construct in your
18167program that is the likely source of the problem.
18168
18169The following strategies are presented in increasing order of
18170difficulty, corresponding to your experience in using GNAT and your
18171familiarity with compiler internals.
18172
18173@enumerate
18174@item
18175Run @code{gcc} with the @option{-gnatf}. This first
18176switch causes all errors on a given line to be reported. In its absence,
18177only the first error on a line is displayed.
18178
18179The @option{-gnatdO} switch causes errors to be displayed as soon as they
18180are encountered, rather than after compilation is terminated. If GNAT
18181terminates prematurely or goes into an infinite loop, the last error
18182message displayed may help to pinpoint the culprit.
18183
18184@item
18185Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18186@code{gcc} produces ongoing information about the progress of the
18187compilation and provides the name of each procedure as code is
18188generated. This switch allows you to find which Ada procedure was being
18189compiled when it encountered a code generation problem.
18190
18191@item
18192@cindex @option{-gnatdc} switch
18193Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18194switch that does for the front-end what @option{^-v^VERBOSE^} does
18195for the back end. The system prints the name of each unit,
18196either a compilation unit or nested unit, as it is being analyzed.
18197@item
18198Finally, you can start
18199@code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18200front-end of GNAT, and can be run independently (normally it is just
18201called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18202would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18203@code{where} command is the first line of attack; the variable
18204@code{lineno} (seen by @code{print lineno}), used by the second phase of
18205@code{gnat1} and by the @code{gcc} backend, indicates the source line at
18206which the execution stopped, and @code{input_file name} indicates the name of
18207the source file.
18208@end enumerate
18209
18210@node Naming Conventions for GNAT Source Files
18211@section Naming Conventions for GNAT Source Files
18212
18213@noindent
18214In order to examine the workings of the GNAT system, the following
18215brief description of its organization may be helpful:
18216
18217@itemize @bullet
18218@item
18219Files with prefix @file{^sc^SC^} contain the lexical scanner.
18220
18221@item
18222All files prefixed with @file{^par^PAR^} are components of the parser. The
18223numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18224parsing of select statements can be found in @file{par-ch9.adb}.
18225
18226@item
18227All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18228numbers correspond to chapters of the Ada standard. For example, all
18229issues involving context clauses can be found in @file{sem_ch10.adb}. In
18230addition, some features of the language require sufficient special processing
18231to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18232dynamic dispatching, etc.
18233
18234@item
18235All files prefixed with @file{^exp^EXP^} perform normalization and
18236expansion of the intermediate representation (abstract syntax tree, or AST).
18237these files use the same numbering scheme as the parser and semantics files.
18238For example, the construction of record initialization procedures is done in
18239@file{exp_ch3.adb}.
18240
18241@item
18242The files prefixed with @file{^bind^BIND^} implement the binder, which
18243verifies the consistency of the compilation, determines an order of
18244elaboration, and generates the bind file.
18245
18246@item
18247The files @file{atree.ads} and @file{atree.adb} detail the low-level
18248data structures used by the front-end.
18249
18250@item
18251The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18252the abstract syntax tree as produced by the parser.
18253
18254@item
18255The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18256all entities, computed during semantic analysis.
18257
18258@item
18259Library management issues are dealt with in files with prefix
18260@file{^lib^LIB^}.
18261
18262@item
18263@findex Ada
18264@cindex Annex A
18265Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18266defined in Annex A.
18267
18268@item
18269@findex Interfaces
18270@cindex Annex B
18271Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18272defined in Annex B.
18273
18274@item
18275@findex System
18276Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18277both language-defined children and GNAT run-time routines.
18278
18279@item
18280@findex GNAT
18281Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18282general-purpose packages, fully documented in their specifications. All
18283the other @file{.c} files are modifications of common @code{gcc} files.
18284@end itemize
18285
18286@node Getting Internal Debugging Information
18287@section Getting Internal Debugging Information
18288
18289@noindent
18290Most compilers have internal debugging switches and modes. GNAT
18291does also, except GNAT internal debugging switches and modes are not
18292secret. A summary and full description of all the compiler and binder
18293debug flags are in the file @file{debug.adb}. You must obtain the
18294sources of the compiler to see the full detailed effects of these flags.
18295
18296The switches that print the source of the program (reconstructed from
18297the internal tree) are of general interest for user programs, as are the
18298options to print
18299the full internal tree, and the entity table (the symbol table
18300information). The reconstructed source provides a readable version of the
18301program after the front-end has completed analysis and  expansion,
18302and is useful when studying the performance of specific constructs.
18303For example, constraint checks are indicated, complex aggregates
18304are replaced with loops and assignments, and tasking primitives
18305are replaced with run-time calls.
18306
18307@node Stack Traceback
18308@section Stack Traceback
18309@cindex traceback
18310@cindex stack traceback
18311@cindex stack unwinding
18312
18313@noindent
18314Traceback is a mechanism to display the sequence of subprogram calls that
18315leads to a specified execution point in a program. Often (but not always)
18316the execution point is an instruction at which an exception has been raised.
18317This mechanism is also known as @i{stack unwinding} because it obtains
18318its information by scanning the run-time stack and recovering the activation
18319records of all active subprograms. Stack unwinding is one of the most
18320important tools for program debugging.
18321
18322@noindent
18323The first entry stored in traceback corresponds to the deepest calling level,
18324that is to say the subprogram currently executing the instruction
18325from which we want to obtain the traceback.
18326
18327@noindent
18328Note that there is no runtime performance penalty when stack traceback
18329is enabled and no exception are raised during program execution.
18330
18331@menu
18332* Non-Symbolic Traceback::
18333* Symbolic Traceback::
18334@end menu
18335
18336@node Non-Symbolic Traceback
18337@subsection Non-Symbolic Traceback
18338@cindex traceback, non-symbolic
18339
18340@noindent
18341Note: this feature is not supported on all platforms. See
18342@file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18343platforms.
18344
18345@menu
18346* Tracebacks From an Unhandled Exception::
18347* Tracebacks From Exception Occurrences (non-symbolic)::
18348* Tracebacks From Anywhere in a Program (non-symbolic)::
18349@end menu
18350
18351@node Tracebacks From an Unhandled Exception
18352@subsubsection Tracebacks From an Unhandled Exception
18353
18354@noindent
18355A runtime non-symbolic traceback is a list of addresses of call instructions.
18356To enable this feature you must use the @option{-E}
18357@code{gnatbind}'s option. With this option a stack traceback is stored as part
18358of exception information. It is possible to retrieve this information using the
18359standard @code{Ada.Exception.Exception_Information} routine.
18360
18361@noindent
18362Let's have a look at a simple example:
18363
18364@smallexample @c ada
18365@cartouche
18366procedure STB is
18367
18368   procedure P1 is
18369   begin
18370      raise Constraint_Error;
18371   end P1;
18372
18373   procedure P2 is
18374   begin
18375      P1;
18376   end P2;
18377
18378begin
18379   P2;
18380end STB;
18381@end cartouche
18382@end smallexample
18383
18384@smallexample
18385$ gnatmake stb -bargs -E
18386$ stb
18387
18388Execution terminated by unhandled exception
18389Exception name: CONSTRAINT_ERROR
18390Message: stb.adb:5
18391Call stack traceback locations:
183920x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18393@end smallexample
18394
18395@noindent
18396As we see the traceback lists a sequence of addresses for the unhandled
18397exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18398guess that this exception come from procedure P1. To translate these
18399addresses into the source lines where the calls appear, the
18400@code{addr2line} tool, described below, is invaluable. The use of this tool
18401requires the program to be compiled with debug information.
18402
18403@smallexample
18404$ gnatmake -g stb -bargs -E
18405$ stb
18406
18407Execution terminated by unhandled exception
18408Exception name: CONSTRAINT_ERROR
18409Message: stb.adb:5
18410Call stack traceback locations:
184110x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18412
18413$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18414   0x4011f1 0x77e892a4
18415
1841600401373 at d:/stb/stb.adb:5
184170040138B at d:/stb/stb.adb:10
184180040139C at d:/stb/stb.adb:14
1841900401335 at d:/stb/b~stb.adb:104
18420004011C4 at /build/.../crt1.c:200
18421004011F1 at /build/.../crt1.c:222
1842277E892A4 in ?? at ??:0
18423@end smallexample
18424
18425@noindent
18426@code{addr2line} has a number of other useful options:
18427
18428@table @code
18429@item --functions
18430to get the function name corresponding to any location
18431
18432@item --demangle=gnat
18433to use the @b{gnat} decoding mode for the function names. Note that
18434for binutils version 2.9.x the option is simply @option{--demangle}.
18435@end table
18436
18437@smallexample
18438$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18439   0x40139c 0x401335 0x4011c4 0x4011f1
18440
1844100401373 in stb.p1 at d:/stb/stb.adb:5
184420040138B in stb.p2 at d:/stb/stb.adb:10
184430040139C in stb at d:/stb/stb.adb:14
1844400401335 in main at d:/stb/b~stb.adb:104
18445004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18446004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18447@end smallexample
18448
18449@noindent
18450From this traceback we can see that the exception was raised in
18451@file{stb.adb} at line 5, which was reached from a procedure call in
18452@file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
18453which contains the call to the main program.
18454@pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
18455and the output will vary from platform to platform.
18456
18457@noindent
18458It is also possible to use @code{GDB} with these traceback addresses to debug
18459the program. For example, we can break at a given code location, as reported
18460in the stack traceback:
18461
18462@smallexample
18463$ gdb -nw stb
18464@ifclear vms
18465@noindent
18466Furthermore, this feature is not implemented inside Windows DLL. Only
18467the non-symbolic traceback is reported in this case.
18468@end ifclear
18469
18470(gdb) break *0x401373
18471Breakpoint 1 at 0x401373: file stb.adb, line 5.
18472@end smallexample
18473
18474@noindent
18475It is important to note that the stack traceback addresses
18476do not change when debug information is included. This is particularly useful
18477because it makes it possible to release software without debug information (to
18478minimize object size), get a field report that includes a stack traceback
18479whenever an internal bug occurs, and then be able to retrieve the sequence
18480of calls with the same program compiled with debug information.
18481
18482@node Tracebacks From Exception Occurrences (non-symbolic)
18483@subsubsection Tracebacks From Exception Occurrences
18484
18485@noindent
18486Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
18487The stack traceback is attached to the exception information string, and can
18488be retrieved in an exception handler within the Ada program, by means of the
18489Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
18490
18491@smallexample @c ada
18492with Ada.Text_IO;
18493with Ada.Exceptions;
18494
18495procedure STB is
18496
18497   use Ada;
18498   use Ada.Exceptions;
18499
18500   procedure P1 is
18501      K : Positive := 1;
18502   begin
18503      K := K - 1;
18504   exception
18505      when E : others =>
18506         Text_IO.Put_Line (Exception_Information (E));
18507   end P1;
18508
18509   procedure P2 is
18510   begin
18511      P1;
18512   end P2;
18513
18514begin
18515   P2;
18516end STB;
18517@end smallexample
18518
18519@noindent
18520This program will output:
18521
18522@smallexample
18523$ stb
18524
18525Exception name: CONSTRAINT_ERROR
18526Message: stb.adb:12
18527Call stack traceback locations:
185280x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
18529@end smallexample
18530
18531@node Tracebacks From Anywhere in a Program (non-symbolic)
18532@subsubsection Tracebacks From Anywhere in a Program
18533
18534@noindent
18535It is also possible to retrieve a stack traceback from anywhere in a
18536program. For this you need to
18537use the @code{GNAT.Traceback} API. This package includes a procedure called
18538@code{Call_Chain} that computes a complete stack traceback, as well as useful
18539display procedures described below. It is not necessary to use the
18540@option{-E gnatbind} option in this case, because the stack traceback mechanism
18541is invoked explicitly.
18542
18543@noindent
18544In the following example we compute a traceback at a specific location in
18545the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
18546convert addresses to strings:
18547
18548@smallexample @c ada
18549with Ada.Text_IO;
18550with GNAT.Traceback;
18551with GNAT.Debug_Utilities;
18552
18553procedure STB is
18554
18555   use Ada;
18556   use GNAT;
18557   use GNAT.Traceback;
18558
18559   procedure P1 is
18560      TB  : Tracebacks_Array (1 .. 10);
18561      --  We are asking for a maximum of 10 stack frames.
18562      Len : Natural;
18563      --  Len will receive the actual number of stack frames returned.
18564   begin
18565      Call_Chain (TB, Len);
18566
18567      Text_IO.Put ("In STB.P1 : ");
18568
18569      for K in 1 .. Len loop
18570         Text_IO.Put (Debug_Utilities.Image (TB (K)));
18571         Text_IO.Put (' ');
18572      end loop;
18573
18574      Text_IO.New_Line;
18575   end P1;
18576
18577   procedure P2 is
18578   begin
18579      P1;
18580   end P2;
18581
18582begin
18583   P2;
18584end STB;
18585@end smallexample
18586
18587@smallexample
18588$ gnatmake stb
18589$ stb
18590
18591In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
1859216#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
18593@end smallexample
18594
18595@node Symbolic Traceback
18596@subsection Symbolic Traceback
18597@cindex traceback, symbolic
18598
18599@noindent
18600A symbolic traceback is a stack traceback in which procedure names are
18601associated with each code location.
18602
18603@noindent
18604Note that this feature is not supported on all platforms. See
18605@file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
18606list of currently supported platforms.
18607
18608@noindent
18609Note that the symbolic traceback requires that the program be compiled
18610with debug information. If it is not compiled with debug information
18611only the non-symbolic information will be valid.
18612
18613@menu
18614* Tracebacks From Exception Occurrences (symbolic)::
18615* Tracebacks From Anywhere in a Program (symbolic)::
18616@end menu
18617
18618@node Tracebacks From Exception Occurrences (symbolic)
18619@subsubsection Tracebacks From Exception Occurrences
18620
18621@smallexample @c ada
18622with Ada.Text_IO;
18623with GNAT.Traceback.Symbolic;
18624
18625procedure STB is
18626
18627   procedure P1 is
18628   begin
18629      raise Constraint_Error;
18630   end P1;
18631
18632   procedure P2 is
18633   begin
18634      P1;
18635   end P2;
18636
18637   procedure P3 is
18638   begin
18639      P2;
18640   end P3;
18641
18642begin
18643   P3;
18644exception
18645   when E : others =>
18646      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
18647end STB;
18648@end smallexample
18649
18650@smallexample
18651$ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
18652$ stb
18653
186540040149F in stb.p1 at stb.adb:8
18655004014B7 in stb.p2 at stb.adb:13
18656004014CF in stb.p3 at stb.adb:18
18657004015DD in ada.stb at stb.adb:22
1865800401461 in main at b~stb.adb:168
18659004011C4 in __mingw_CRTStartup at crt1.c:200
18660004011F1 in mainCRTStartup at crt1.c:222
1866177E892A4 in ?? at ??:0
18662@end smallexample
18663
18664@noindent
18665The exact sequence of linker options may vary from platform to platform.
18666The above @option{-largs} section is for Windows platforms. By contrast,
18667under Unix there is no need for the @option{-largs} section.
18668Differences across platforms are due to details of linker implementation.
18669
18670@node Tracebacks From Anywhere in a Program (symbolic)
18671@subsubsection Tracebacks From Anywhere in a Program
18672
18673@noindent
18674It is possible to get a symbolic stack traceback
18675from anywhere in a program, just as for non-symbolic tracebacks.
18676The first step is to obtain a non-symbolic
18677traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
18678information. Here is an example:
18679
18680@smallexample @c ada
18681with Ada.Text_IO;
18682with GNAT.Traceback;
18683with GNAT.Traceback.Symbolic;
18684
18685procedure STB is
18686
18687   use Ada;
18688   use GNAT.Traceback;
18689   use GNAT.Traceback.Symbolic;
18690
18691   procedure P1 is
18692      TB  : Tracebacks_Array (1 .. 10);
18693      --  We are asking for a maximum of 10 stack frames.
18694      Len : Natural;
18695      --  Len will receive the actual number of stack frames returned.
18696   begin
18697      Call_Chain (TB, Len);
18698      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
18699   end P1;
18700
18701   procedure P2 is
18702   begin
18703      P1;
18704   end P2;
18705
18706begin
18707   P2;
18708end STB;
18709@end smallexample
18710
18711@ifset vms
18712@node Compatibility with DEC Ada
18713@chapter Compatibility with DEC Ada
18714@cindex Compatibility
18715
18716@noindent
18717This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
18718OpenVMS Alpha. GNAT achieves a high level of compatibility
18719with DEC Ada, and it should generally be straightforward to port code
18720from the DEC Ada environment to GNAT. However, there are a few language
18721and implementation differences of which the user must be aware. These
18722differences are discussed in this section. In
18723addition, the operating environment and command structure for the
18724compiler are different, and these differences are also discussed.
18725
18726Note that this discussion addresses specifically the implementation
18727of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
18728of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
18729GNAT always follows the Alpha implementation.
18730
18731@menu
18732* Ada 95 Compatibility::
18733* Differences in the Definition of Package System::
18734* Language-Related Features::
18735* The Package STANDARD::
18736* The Package SYSTEM::
18737* Tasking and Task-Related Features::
18738* Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
18739* Pragmas and Pragma-Related Features::
18740* Library of Predefined Units::
18741* Bindings::
18742* Main Program Definition::
18743* Implementation-Defined Attributes::
18744* Compiler and Run-Time Interfacing::
18745* Program Compilation and Library Management::
18746* Input-Output::
18747* Implementation Limits::
18748* Tools::
18749@end menu
18750
18751@node Ada 95 Compatibility
18752@section Ada 95 Compatibility
18753
18754@noindent
18755GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
18756compiler. Ada 95 is almost completely upwards compatible
18757with Ada 83, and therefore Ada 83 programs will compile
18758and run under GNAT with
18759no changes or only minor changes. The Ada 95 Reference
18760Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
18761incompatibilities.
18762
18763GNAT provides the switch /83 on the GNAT COMPILE command,
18764as well as the pragma ADA_83, to force the compiler to
18765operate in Ada 83 mode. This mode does not guarantee complete
18766conformance to Ada 83, but in practice is sufficient to
18767eliminate most sources of incompatibilities.
18768In particular, it eliminates the recognition of the
18769additional Ada 95 keywords, so that their use as identifiers
18770in Ada83 program is legal, and handles the cases of packages
18771with optional bodies, and generics that instantiate unconstrained
18772types without the use of @code{(<>)}.
18773
18774@node Differences in the Definition of Package System
18775@section Differences in the Definition of Package System
18776
18777@noindent
18778Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
18779implementation-dependent declarations to package System. In normal mode,
18780GNAT does not take advantage of this permission, and the version of System
18781provided by GNAT exactly matches that in the Ada 95 Reference Manual.
18782
18783However, DEC Ada adds an extensive set of declarations to package System,
18784as fully documented in the DEC Ada manuals. To minimize changes required
18785for programs that make use of these extensions, GNAT provides the pragma
18786Extend_System for extending the definition of package System. By using:
18787
18788@smallexample @c ada
18789@group
18790@cartouche
18791pragma Extend_System (Aux_DEC);
18792@end cartouche
18793@end group
18794@end smallexample
18795
18796@noindent
18797The set of definitions in System is extended to include those in package
18798@code{System.Aux_DEC}.
18799These definitions are incorporated directly into package
18800System, as though they had been declared there in the first place. For a
18801list of the declarations added, see the specification of this package,
18802which can be found in the file @code{s-auxdec.ads} in the GNAT library.
18803The pragma Extend_System is a configuration pragma, which means that
18804it can be placed in the file @file{gnat.adc}, so that it will automatically
18805apply to all subsequent compilations. See the section on Configuration
18806Pragmas for further details.
18807
18808An alternative approach that avoids the use of the non-standard
18809Extend_System pragma is to add a context clause to the unit that
18810references these facilities:
18811
18812@smallexample @c ada
18813@group
18814@cartouche
18815with System.Aux_DEC;
18816use  System.Aux_DEC;
18817@end cartouche
18818@end group
18819@end smallexample
18820
18821@noindent
18822The effect is not quite semantically identical to incorporating
18823the declarations directly into package @code{System},
18824but most programs will not notice a difference
18825unless they use prefix notation (e.g. @code{System.Integer_8})
18826to reference the
18827entities directly in package @code{System}.
18828For units containing such references,
18829the prefixes must either be removed, or the pragma @code{Extend_System}
18830must be used.
18831
18832@node Language-Related Features
18833@section Language-Related Features
18834
18835@noindent
18836The following sections highlight differences in types,
18837representations of types, operations, alignment, and
18838related topics.
18839
18840@menu
18841* Integer Types and Representations::
18842* Floating-Point Types and Representations::
18843* Pragmas Float_Representation and Long_Float::
18844* Fixed-Point Types and Representations::
18845* Record and Array Component Alignment::
18846* Address Clauses::
18847* Other Representation Clauses::
18848@end menu
18849
18850@node Integer Types and Representations
18851@subsection Integer Types and Representations
18852
18853@noindent
18854The set of predefined integer types is identical in DEC Ada and GNAT.
18855Furthermore the representation of these integer types is also identical,
18856including the capability of size clauses forcing biased representation.
18857
18858In addition,
18859DEC Ada for OpenVMS Alpha systems has defined the
18860following additional integer types in package System:
18861
18862@itemize @bullet
18863
18864@item
18865INTEGER_8
18866
18867@item
18868INTEGER_16
18869
18870@item
18871INTEGER_32
18872
18873@item
18874INTEGER_64
18875
18876@item
18877LARGEST_INTEGER
18878@end itemize
18879
18880@noindent
18881When using GNAT, the first four of these types may be obtained from the
18882standard Ada 95 package @code{Interfaces}.
18883Alternatively, by use of the pragma
18884@code{Extend_System}, identical
18885declarations can be referenced directly in package @code{System}.
18886On both GNAT and DEC Ada, the maximum integer size is 64 bits.
18887
18888@node Floating-Point Types and Representations
18889@subsection Floating-Point Types and Representations
18890@cindex Floating-Point types
18891
18892@noindent
18893The set of predefined floating-point types is identical in DEC Ada and GNAT.
18894Furthermore the representation of these floating-point
18895types is also identical. One important difference is that the default
18896representation for DEC Ada is VAX_Float, but the default representation
18897for GNAT is IEEE.
18898
18899Specific types may be declared to be VAX_Float or IEEE, using the pragma
18900@code{Float_Representation} as described in the DEC Ada documentation.
18901For example, the declarations:
18902
18903@smallexample @c ada
18904@group
18905@cartouche
18906type F_Float is digits 6;
18907pragma Float_Representation (VAX_Float, F_Float);
18908@end cartouche
18909@end group
18910@end smallexample
18911
18912@noindent
18913declare a type F_Float that will be represented in VAX_Float format.
18914This set of declarations actually appears in System.Aux_DEC, which provides
18915the full set of additional floating-point declarations provided in
18916the DEC Ada version of package
18917System. This and similar declarations may be accessed in a user program
18918by using pragma @code{Extend_System}. The use of this
18919pragma, and the related pragma @code{Long_Float} is described in further
18920detail in the following section.
18921
18922@node Pragmas Float_Representation and Long_Float
18923@subsection Pragmas Float_Representation and Long_Float
18924
18925@noindent
18926DEC Ada provides the pragma @code{Float_Representation}, which
18927acts as a program library switch to allow control over
18928the internal representation chosen for the predefined
18929floating-point types declared in the package @code{Standard}.
18930The format of this pragma is as follows:
18931
18932@smallexample
18933@group
18934@cartouche
18935@b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
18936@end cartouche
18937@end group
18938@end smallexample
18939
18940@noindent
18941This pragma controls the representation of floating-point
18942types as follows:
18943
18944@itemize @bullet
18945@item
18946@code{VAX_Float} specifies that floating-point
18947types are represented by default with the VAX hardware types
18948F-floating, D-floating, G-floating. Note that the H-floating
18949type is available only on DIGITAL Vax systems, and is not available
18950in either DEC Ada or GNAT for Alpha systems.
18951
18952@item
18953@code{IEEE_Float} specifies that floating-point
18954types are represented by default with the IEEE single and
18955double floating-point types.
18956@end itemize
18957
18958@noindent
18959GNAT provides an identical implementation of the pragma
18960@code{Float_Representation}, except that it functions as a
18961configuration pragma, as defined by Ada 95. Note that the
18962notion of configuration pragma corresponds closely to the
18963DEC Ada notion of a program library switch.
18964
18965When no pragma is used in GNAT, the default is IEEE_Float, which is different
18966from DEC Ada 83, where the default is VAX_Float. In addition, the
18967predefined libraries in GNAT are built using IEEE_Float, so it is not
18968advisable to change the format of numbers passed to standard library
18969routines, and if necessary explicit type conversions may be needed.
18970
18971The use of IEEE_Float is recommended in GNAT since it is more efficient,
18972and (given that it conforms to an international standard) potentially more
18973portable. The situation in which VAX_Float may be useful is in interfacing
18974to existing code and data that expects the use of VAX_Float. There are
18975two possibilities here. If the requirement for the use of VAX_Float is
18976localized, then the best approach is to use the predefined VAX_Float
18977types in package @code{System}, as extended by
18978@code{Extend_System}. For example, use @code{System.F_Float}
18979to specify the 32-bit @code{F-Float} format.
18980
18981Alternatively, if an entire program depends heavily on the use of
18982the @code{VAX_Float} and in particular assumes that the types in
18983package @code{Standard} are in @code{Vax_Float} format, then it
18984may be desirable to reconfigure GNAT to assume Vax_Float by default.
18985This is done by using the GNAT LIBRARY command to rebuild the library, and
18986then using the general form of the @code{Float_Representation}
18987pragma to ensure that this default format is used throughout.
18988The form of the GNAT LIBRARY command is:
18989
18990@smallexample
18991GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
18992@end smallexample
18993
18994@noindent
18995where @i{file} contains the new configuration pragmas
18996and @i{directory} is the directory to be created to contain
18997the new library.
18998
18999@noindent
19000On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19001to allow control over the internal representation chosen
19002for the predefined type @code{Long_Float} and for floating-point
19003type declarations with digits specified in the range 7 .. 15.
19004The format of this pragma is as follows:
19005
19006@smallexample @c ada
19007@cartouche
19008pragma Long_Float (D_FLOAT | G_FLOAT);
19009@end cartouche
19010@end smallexample
19011
19012@node Fixed-Point Types and Representations
19013@subsection Fixed-Point Types and Representations
19014
19015@noindent
19016On DEC Ada for OpenVMS Alpha systems, rounding is
19017away from zero for both positive and negative numbers.
19018Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19019
19020On GNAT for OpenVMS Alpha, the results of operations
19021on fixed-point types are in accordance with the Ada 95
19022rules. In particular, results of operations on decimal
19023fixed-point types are truncated.
19024
19025@node Record and Array Component Alignment
19026@subsection Record and Array Component Alignment
19027
19028@noindent
19029On DEC Ada for OpenVMS Alpha, all non composite components
19030are aligned on natural boundaries. For example, 1-byte
19031components are aligned on byte boundaries, 2-byte
19032components on 2-byte boundaries, 4-byte components on 4-byte
19033byte boundaries, and so on. The OpenVMS Alpha hardware
19034runs more efficiently with naturally aligned data.
19035
19036ON GNAT for OpenVMS Alpha, alignment rules are compatible
19037with DEC Ada for OpenVMS Alpha.
19038
19039@node Address Clauses
19040@subsection Address Clauses
19041
19042@noindent
19043In DEC Ada and GNAT, address clauses are supported for
19044objects and imported subprograms.
19045The predefined type @code{System.Address} is a private type
19046in both compilers, with the same representation (it is simply
19047a machine pointer). Addition, subtraction, and comparison
19048operations are available in the standard Ada 95 package
19049@code{System.Storage_Elements}, or in package @code{System}
19050if it is extended to include @code{System.Aux_DEC} using a
19051pragma @code{Extend_System} as previously described.
19052
19053Note that code that with's both this extended package @code{System}
19054and the package @code{System.Storage_Elements} should not @code{use}
19055both packages, or ambiguities will result. In general it is better
19056not to mix these two sets of facilities. The Ada 95 package was
19057designed specifically to provide the kind of features that DEC Ada
19058adds directly to package @code{System}.
19059
19060GNAT is compatible with DEC Ada in its handling of address
19061clauses, except for some limitations in
19062the form of address clauses for composite objects with
19063initialization. Such address clauses are easily replaced
19064by the use of an explicitly-defined constant as described
19065in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19066of declarations:
19067
19068@smallexample @c ada
19069@cartouche
19070X, Y : Integer := Init_Func;
19071Q : String (X .. Y) := "abc";
19072...
19073for Q'Address use Compute_Address;
19074@end cartouche
19075@end smallexample
19076
19077@noindent
19078will be rejected by GNAT, since the address cannot be computed at the time
19079that Q is declared. To achieve the intended effect, write instead:
19080
19081@smallexample @c ada
19082@group
19083@cartouche
19084X, Y : Integer := Init_Func;
19085Q_Address : constant Address := Compute_Address;
19086Q : String (X .. Y) := "abc";
19087...
19088for Q'Address use Q_Address;
19089@end cartouche
19090@end group
19091@end smallexample
19092
19093@noindent
19094which will be accepted by GNAT (and other Ada 95 compilers), and is also
19095backwards compatible with Ada 83. A fuller description of the restrictions
19096on address specifications is found in the GNAT Reference Manual.
19097
19098@node Other Representation Clauses
19099@subsection Other Representation Clauses
19100
19101@noindent
19102GNAT supports in a compatible manner all the representation
19103clauses supported by DEC Ada. In addition, it
19104supports representation clause forms that are new in Ada 95
19105including COMPONENT_SIZE and SIZE clauses for objects.
19106
19107@node The Package STANDARD
19108@section The Package STANDARD
19109
19110@noindent
19111The package STANDARD, as implemented by DEC Ada, is fully
19112described in the Reference Manual for the Ada Programming
19113Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19114Language Reference Manual. As implemented by GNAT, the
19115package STANDARD is described in the Ada 95 Reference
19116Manual.
19117
19118In addition, DEC Ada supports the Latin-1 character set in
19119the type CHARACTER. GNAT supports the Latin-1 character set
19120in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19121the type WIDE_CHARACTER.
19122
19123The floating-point types supported by GNAT are those
19124supported by DEC Ada, but defaults are different, and are controlled by
19125pragmas. See @pxref{Floating-Point Types and Representations} for details.
19126
19127@node The Package SYSTEM
19128@section The Package SYSTEM
19129
19130@noindent
19131DEC Ada provides a system-specific version of the package
19132SYSTEM for each platform on which the language ships.
19133For the complete specification of the package SYSTEM, see
19134Appendix F of the DEC Ada Language Reference Manual.
19135
19136On DEC Ada, the package SYSTEM includes the following conversion functions:
19137@itemize @bullet
19138@item TO_ADDRESS(INTEGER)
19139
19140@item  TO_ADDRESS(UNSIGNED_LONGWORD)
19141
19142@item  TO_ADDRESS(universal_integer)
19143
19144@item  TO_INTEGER(ADDRESS)
19145
19146@item  TO_UNSIGNED_LONGWORD(ADDRESS)
19147
19148@item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19149                 functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19150@end itemize
19151
19152@noindent
19153By default, GNAT supplies a version of SYSTEM that matches
19154the definition given in the Ada 95 Reference Manual.
19155This
19156is a subset of the DIGITAL system definitions, which is as
19157close as possible to the original definitions. The only difference
19158is that the definition of SYSTEM_NAME is different:
19159
19160@smallexample @c ada
19161@group
19162@cartouche
19163type Name is (SYSTEM_NAME_GNAT);
19164System_Name : constant Name := SYSTEM_NAME_GNAT;
19165@end cartouche
19166@end group
19167@end smallexample
19168
19169@noindent
19170Also, GNAT adds the new Ada 95 declarations for
19171BIT_ORDER and DEFAULT_BIT_ORDER.
19172
19173However, the use of the following pragma causes GNAT
19174to extend the definition of package SYSTEM so that it
19175encompasses the full set of DIGITAL-specific extensions,
19176including the functions listed above:
19177
19178@smallexample @c ada
19179@cartouche
19180pragma Extend_System (Aux_DEC);
19181@end cartouche
19182@end smallexample
19183
19184@noindent
19185The pragma Extend_System is a configuration pragma that
19186is most conveniently placed in the @file{gnat.adc} file. See the
19187GNAT Reference Manual for further details.
19188
19189DEC Ada does not allow the recompilation of the package
19190SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19191NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19192the package SYSTEM. On OpenVMS Alpha systems, the pragma
19193SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19194its single argument.
19195
19196GNAT does permit the recompilation of package SYSTEM using
19197a special switch (@option{-gnatg}) and this switch can be used if
19198it is necessary to modify the definitions in SYSTEM. GNAT does
19199not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19200or MEMORY_SIZE by any other means.
19201
19202On GNAT systems, the pragma SYSTEM_NAME takes the
19203enumeration literal SYSTEM_NAME_GNAT.
19204
19205The definitions provided by the use of
19206
19207@smallexample @c ada
19208pragma Extend_System (AUX_Dec);
19209@end smallexample
19210
19211@noindent
19212are virtually identical to those provided by the DEC Ada 83 package
19213System. One important difference is that the name of the TO_ADDRESS
19214function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19215See the GNAT Reference manual for a discussion of why this change was
19216necessary.
19217
19218@noindent
19219The version of TO_ADDRESS taking a universal integer argument is in fact
19220an extension to Ada 83 not strictly compatible with the reference manual.
19221In GNAT, we are constrained to be exactly compatible with the standard,
19222and this means we cannot provide this capability. In DEC Ada 83, the
19223point of this definition is to deal with a call like:
19224
19225@smallexample @c ada
19226TO_ADDRESS (16#12777#);
19227@end smallexample
19228
19229@noindent
19230Normally, according to the Ada 83 standard, one would expect this to be
19231ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19232of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19233definition using universal_integer takes precedence.
19234
19235In GNAT, since the version with universal_integer cannot be supplied, it is
19236not possible to be 100% compatible. Since there are many programs using
19237numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19238to change the name of the function in the UNSIGNED_LONGWORD case, so the
19239declarations provided in the GNAT version of AUX_Dec are:
19240
19241@smallexample @c ada
19242function To_Address (X : Integer) return Address;
19243pragma Pure_Function (To_Address);
19244
19245function To_Address_Long (X : Unsigned_Longword) return Address;
19246pragma Pure_Function (To_Address_Long);
19247@end smallexample
19248
19249@noindent
19250This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19251change the name to TO_ADDRESS_LONG.
19252
19253@node Tasking and Task-Related Features
19254@section Tasking and Task-Related Features
19255
19256@noindent
19257The concepts relevant to a comparison of tasking on GNAT
19258and on DEC Ada for OpenVMS Alpha systems are discussed in
19259the following sections.
19260
19261For detailed information on concepts related to tasking in
19262DEC Ada, see the DEC Ada Language Reference Manual and the
19263relevant run-time reference manual.
19264
19265@node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19266@section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19267
19268@noindent
19269On OpenVMS Alpha systems, each Ada task (except a passive
19270task) is implemented as a single stream of execution
19271that is created and managed by the kernel. On these
19272systems, DEC Ada tasking support is based on DECthreads,
19273an implementation of the POSIX standard for threads.
19274
19275Although tasks are implemented as threads, all tasks in
19276an Ada program are part of the same process. As a result,
19277resources such as open files and virtual memory can be
19278shared easily among tasks. Having all tasks in one process
19279allows better integration with the programming environment
19280(the shell and the debugger, for example).
19281
19282Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19283code that calls DECthreads routines can be used together.
19284The interaction between Ada tasks and DECthreads routines
19285can have some benefits. For example when on OpenVMS Alpha,
19286DEC Ada can call C code that is already threaded.
19287GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19288and Ada tasks are mapped to threads.
19289
19290@menu
19291* Assigning Task IDs::
19292* Task IDs and Delays::
19293* Task-Related Pragmas::
19294* Scheduling and Task Priority::
19295* The Task Stack::
19296* External Interrupts::
19297@end menu
19298
19299@node Assigning Task IDs
19300@subsection Assigning Task IDs
19301
19302@noindent
19303The DEC Ada Run-Time Library always assigns %TASK 1 to
19304the environment task that executes the main program. On
19305OpenVMS Alpha systems, %TASK 0 is often used for tasks
19306that have been created but are not yet activated.
19307
19308On OpenVMS Alpha systems, task IDs are assigned at
19309activation. On GNAT systems, task IDs are also assigned at
19310task creation but do not have the same form or values as
19311task ID values in DEC Ada. There is no null task, and the
19312environment task does not have a specific task ID value.
19313
19314@node Task IDs and Delays
19315@subsection Task IDs and Delays
19316
19317@noindent
19318On OpenVMS Alpha systems, tasking delays are implemented
19319using Timer System Services. The Task ID is used for the
19320identification of the timer request (the REQIDT parameter).
19321If Timers are used in the application take care not to use
193220 for the identification, because cancelling such a timer
19323will cancel all timers and may lead to unpredictable results.
19324
19325@node Task-Related Pragmas
19326@subsection Task-Related Pragmas
19327
19328@noindent
19329Ada supplies the pragma TASK_STORAGE, which allows
19330specification of the size of the guard area for a task
19331stack. (The guard area forms an area of memory that has no
19332read or write access and thus helps in the detection of
19333stack overflow.) On OpenVMS Alpha systems, if the pragma
19334TASK_STORAGE specifies a value of zero, a minimal guard
19335area is created. In the absence of a pragma TASK_STORAGE, a default guard
19336area is created.
19337
19338GNAT supplies the following task-related pragmas:
19339
19340@itemize @bullet
19341@item  TASK_INFO
19342
19343              This pragma appears within a task definition and
19344              applies to the task in which it appears. The argument
19345              must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19346
19347@item  TASK_STORAGE
19348
19349              GNAT implements pragma TASK_STORAGE in the same way as
19350              DEC Ada.
19351              Both DEC Ada and GNAT supply the pragmas PASSIVE,
19352              SUPPRESS, and VOLATILE.
19353@end itemize
19354@node Scheduling and Task Priority
19355@subsection Scheduling and Task Priority
19356
19357@noindent
19358DEC Ada implements the Ada language requirement that
19359when two tasks are eligible for execution and they have
19360different priorities, the lower priority task does not
19361execute while the higher priority task is waiting. The DEC
19362Ada Run-Time Library keeps a task running until either the
19363task is suspended or a higher priority task becomes ready.
19364
19365On OpenVMS Alpha systems, the default strategy is round-
19366robin with preemption. Tasks of equal priority take turns
19367at the processor. A task is run for a certain period of
19368time and then placed at the rear of the ready queue for
19369its priority level.
19370
19371DEC Ada provides the implementation-defined pragma TIME_SLICE,
19372which can be used to enable or disable round-robin
19373scheduling of tasks with the same priority.
19374See the relevant DEC Ada run-time reference manual for
19375information on using the pragmas to control DEC Ada task
19376scheduling.
19377
19378GNAT follows the scheduling rules of Annex D (real-time
19379Annex) of the Ada 95 Reference Manual. In general, this
19380scheduling strategy is fully compatible with DEC Ada
19381although it provides some additional constraints (as
19382fully documented in Annex D).
19383GNAT implements time slicing control in a manner compatible with
19384DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19385to the DEC Ada 83 pragma of the same name.
19386Note that it is not possible to mix GNAT tasking and
19387DEC Ada 83 tasking in the same program, since the two run times are
19388not compatible.
19389
19390@node The Task Stack
19391@subsection The Task Stack
19392
19393@noindent
19394In DEC Ada, a task stack is allocated each time a
19395non passive task is activated. As soon as the task is
19396terminated, the storage for the task stack is deallocated.
19397If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19398a default stack size is used. Also, regardless of the size
19399specified, some additional space is allocated for task
19400management purposes. On OpenVMS Alpha systems, at least
19401one page is allocated.
19402
19403GNAT handles task stacks in a similar manner. According to
19404the Ada 95 rules, it provides the pragma STORAGE_SIZE as
19405an alternative method for controlling the task stack size.
19406The specification of the attribute T'STORAGE_SIZE is also
19407supported in a manner compatible with DEC Ada.
19408
19409@node External Interrupts
19410@subsection External Interrupts
19411
19412@noindent
19413On DEC Ada, external interrupts can be associated with task entries.
19414GNAT is compatible with DEC Ada in its handling of external interrupts.
19415
19416@node Pragmas and Pragma-Related Features
19417@section Pragmas and Pragma-Related Features
19418
19419@noindent
19420Both DEC Ada and GNAT supply all language-defined pragmas
19421as specified by the Ada 83 standard. GNAT also supplies all
19422language-defined pragmas specified in the Ada 95 Reference Manual.
19423In addition, GNAT implements the implementation-defined pragmas
19424from DEC Ada 83.
19425
19426@itemize @bullet
19427@item  AST_ENTRY
19428
19429@item  COMMON_OBJECT
19430
19431@item  COMPONENT_ALIGNMENT
19432
19433@item  EXPORT_EXCEPTION
19434
19435@item  EXPORT_FUNCTION
19436
19437@item  EXPORT_OBJECT
19438
19439@item  EXPORT_PROCEDURE
19440
19441@item  EXPORT_VALUED_PROCEDURE
19442
19443@item  FLOAT_REPRESENTATION
19444
19445@item  IDENT
19446
19447@item  IMPORT_EXCEPTION
19448
19449@item  IMPORT_FUNCTION
19450
19451@item  IMPORT_OBJECT
19452
19453@item  IMPORT_PROCEDURE
19454
19455@item  IMPORT_VALUED_PROCEDURE
19456
19457@item  INLINE_GENERIC
19458
19459@item  INTERFACE_NAME
19460
19461@item  LONG_FLOAT
19462
19463@item  MAIN_STORAGE
19464
19465@item  PASSIVE
19466
19467@item  PSET_OBJECT
19468
19469@item  SHARE_GENERIC
19470
19471@item  SUPPRESS_ALL
19472
19473@item  TASK_STORAGE
19474
19475@item  TIME_SLICE
19476
19477@item  TITLE
19478@end itemize
19479
19480@noindent
19481These pragmas are all fully implemented, with the exception of @code{Title},
19482@code{Passive}, and @code{Share_Generic}, which are
19483recognized, but which have no
19484effect in GNAT. The effect of @code{Passive} may be obtained by the
19485use of protected objects in Ada 95. In GNAT, all generics are inlined.
19486
19487Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
19488a separate subprogram specification which must appear before the
19489subprogram body.
19490
19491GNAT also supplies a number of implementation-defined pragmas as follows:
19492@itemize @bullet
19493@item  C_PASS_BY_COPY
19494
19495@item  EXTEND_SYSTEM
19496
19497@item  SOURCE_FILE_NAME
19498
19499@item  UNSUPPRESS
19500
19501@item  WARNINGS
19502
19503@item  ABORT_DEFER
19504
19505@item  ADA_83
19506
19507@item  ADA_95
19508
19509@item  ANNOTATE
19510
19511@item  ASSERT
19512
19513@item  CPP_CLASS
19514
19515@item  CPP_CONSTRUCTOR
19516
19517@item  CPP_DESTRUCTOR
19518
19519@item  CPP_VIRTUAL
19520
19521@item  CP_VTABLE
19522
19523@item  DEBUG
19524
19525@item  LINKER_ALIAS
19526
19527@item  LINKER_SECTION
19528
19529@item  MACHINE_ATTRIBUTE
19530
19531@item  NO_RETURN
19532
19533@item  PURE_FUNCTION
19534
19535@item  SOURCE_REFERENCE
19536
19537@item  TASK_INFO
19538
19539@item  UNCHECKED_UNION
19540
19541@item  UNIMPLEMENTED_UNIT
19542
19543@item  UNIVERSAL_DATA
19544
19545@item  WEAK_EXTERNAL
19546@end itemize
19547
19548@noindent
19549For full details on these GNAT implementation-defined pragmas, see
19550the GNAT Reference Manual.
19551
19552@menu
19553* Restrictions on the Pragma INLINE::
19554* Restrictions on the Pragma INTERFACE::
19555* Restrictions on the Pragma SYSTEM_NAME::
19556@end menu
19557
19558@node Restrictions on the Pragma INLINE
19559@subsection Restrictions on the Pragma INLINE
19560
19561@noindent
19562DEC Ada applies the following restrictions to the pragma INLINE:
19563@itemize @bullet
19564@item  Parameters cannot be a task type.
19565
19566@item  Function results cannot be task types, unconstrained
19567array types, or unconstrained types with discriminants.
19568
19569@item  Bodies cannot declare the following:
19570@itemize @bullet
19571@item  Subprogram body or stub (imported subprogram is allowed)
19572
19573@item  Tasks
19574
19575@item  Generic declarations
19576
19577@item  Instantiations
19578
19579@item  Exceptions
19580
19581@item  Access types (types derived from access types allowed)
19582
19583@item  Array or record types
19584
19585@item  Dependent tasks
19586
19587@item  Direct recursive calls of subprogram or containing
19588subprogram, directly or via a renaming
19589
19590@end itemize
19591@end itemize
19592
19593@noindent
19594In GNAT, the only restriction on pragma INLINE is that the
19595body must occur before the call if both are in the same
19596unit, and the size must be appropriately small. There are
19597no other specific restrictions which cause subprograms to
19598be incapable of being inlined.
19599
19600@node  Restrictions on the Pragma INTERFACE
19601@subsection  Restrictions on the Pragma INTERFACE
19602
19603@noindent
19604The following lists and describes the restrictions on the
19605pragma INTERFACE on DEC Ada and GNAT:
19606@itemize @bullet
19607@item  Languages accepted: Ada, Bliss, C, Fortran, Default.
19608Default is the default on OpenVMS Alpha systems.
19609
19610@item  Parameter passing: Language specifies default
19611mechanisms but can be overridden with an EXPORT pragma.
19612
19613@itemize @bullet
19614@item  Ada: Use internal Ada rules.
19615
19616@item  Bliss, C: Parameters must be mode @code{in}; cannot be
19617record or task type. Result cannot be a string, an
19618array, or a record.
19619
19620@item  Fortran: Parameters cannot be a task. Result cannot
19621be a string, an array, or a record.
19622@end itemize
19623@end itemize
19624
19625@noindent
19626GNAT is entirely upwards compatible with DEC Ada, and in addition allows
19627record parameters for all languages.
19628
19629@node  Restrictions on the Pragma SYSTEM_NAME
19630@subsection  Restrictions on the Pragma SYSTEM_NAME
19631
19632@noindent
19633For DEC Ada for OpenVMS Alpha, the enumeration literal
19634for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
19635literal for the type NAME is SYSTEM_NAME_GNAT.
19636
19637@node  Library of Predefined Units
19638@section  Library of Predefined Units
19639
19640@noindent
19641A library of predefined units is provided as part of the
19642DEC Ada and GNAT implementations. DEC Ada does not provide
19643the package MACHINE_CODE but instead recommends importing
19644assembler code.
19645
19646The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
19647units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
19648version. During GNAT installation, the DEC Ada Predefined
19649Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
19650(aka DECLIB) directory and patched to remove Ada 95 incompatibilities
19651and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
19652for details.
19653
19654The GNAT RTL is contained in
19655the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
19656the default search path is set up to find DECLIB units in preference
19657to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
19658for example).
19659
19660However, it is possible to change the default so that the
19661reverse is true, or even to mix them using child package
19662notation. The DEC Ada 83 units are available as DEC.xxx where xxx
19663is the package name, and the Ada units are available in the
19664standard manner defined for Ada 95, that is to say as Ada.xxx. To
19665change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
19666appropriately. For example, to change the default to use the Ada95
19667versions do:
19668
19669@smallexample
19670$ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
19671                          GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19672$ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
19673                          GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19674@end smallexample
19675
19676@menu
19677* Changes to DECLIB::
19678@end menu
19679
19680@node Changes to DECLIB
19681@subsection Changes to DECLIB
19682
19683@noindent
19684The changes made to the DEC Ada predefined library for GNAT and Ada 95
19685compatibility are minor and include the following:
19686
19687@itemize @bullet
19688@item  Adjusting the location of pragmas and record representation
19689clauses to obey Ada 95 rules
19690
19691@item  Adding the proper notation to generic formal parameters
19692that take unconstrained types in instantiation
19693
19694@item  Adding pragma ELABORATE_BODY to package specifications
19695that have package bodies not otherwise allowed
19696
19697@item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
19698@code{"PROTECTD"}.
19699Currently these are found only in the STARLET package spec.
19700@end itemize
19701
19702@noindent
19703None of the above changes is visible to users.
19704
19705@node Bindings
19706@section Bindings
19707
19708@noindent
19709On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
19710@itemize @bullet
19711
19712@item  Command Language Interpreter (CLI interface)
19713
19714@item  DECtalk Run-Time Library (DTK interface)
19715
19716@item  Librarian utility routines (LBR interface)
19717
19718@item  General Purpose Run-Time Library (LIB interface)
19719
19720@item  Math Run-Time Library (MTH interface)
19721
19722@item  National Character Set Run-Time Library (NCS interface)
19723
19724@item  Compiled Code Support Run-Time Library (OTS interface)
19725
19726@item  Parallel Processing Run-Time Library (PPL interface)
19727
19728@item  Screen Management Run-Time Library (SMG interface)
19729
19730@item  Sort Run-Time Library (SOR interface)
19731
19732@item  String Run-Time Library (STR interface)
19733
19734@item STARLET System Library
19735@findex Starlet
19736
19737@item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
19738
19739@item  X Windows Toolkit (XT interface)
19740
19741@item  X/Motif Version 1.1.3 and 1.2 (XM interface)
19742@end itemize
19743
19744@noindent
19745GNAT provides implementations of these DEC bindings in the DECLIB directory.
19746
19747The X/Motif bindings used to build DECLIB are whatever versions are in the
19748DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
19749The build script will
19750automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
19751and @code{X_Lib}
19752causing the default X/Motif sharable image libraries to be linked in. This
19753is done via options files named @file{xm.opt}, @file{xt.opt}, and
19754@file{x_lib.opt} (also located in the @file{DECLIB} directory).
19755
19756It may be necessary to edit these options files to update or correct the
19757library names if, for example, the newer X/Motif bindings from
19758@file{ADA$EXAMPLES}
19759had been (previous to installing GNAT) copied and renamed to supersede the
19760default @file{ADA$PREDEFINED} versions.
19761
19762@menu
19763* Shared Libraries and Options Files::
19764* Interfaces to C::
19765@end menu
19766
19767@node Shared Libraries and Options Files
19768@subsection Shared Libraries and Options Files
19769
19770@noindent
19771When using the DEC Ada
19772predefined X and Motif bindings, the linking with their sharable images is
19773done automatically by @command{GNAT LINK}.
19774When using other X and Motif bindings, you need
19775to add the corresponding sharable images to the command line for
19776@code{GNAT LINK}. When linking with shared libraries, or with
19777@file{.OPT} files, you must
19778also add them to the command line for @command{GNAT LINK}.
19779
19780A shared library to be used with GNAT is built in the same way as other
19781libraries under VMS. The VMS Link command can be used in standard fashion.
19782
19783@node Interfaces to C
19784@subsection Interfaces to C
19785
19786@noindent
19787DEC Ada
19788provides the following Ada types and operations:
19789
19790@itemize @bullet
19791@item C types package (C_TYPES)
19792
19793@item C strings (C_TYPES.NULL_TERMINATED)
19794
19795@item Other_types (SHORT_INT)
19796@end itemize
19797
19798@noindent
19799Interfacing to C with GNAT, one can use the above approach
19800described for DEC Ada or the facilities of Annex B of
19801the Ada 95 Reference Manual (packages INTERFACES.C,
19802INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
19803information, see the section ``Interfacing to C'' in the
19804@cite{GNAT Reference Manual}.
19805
19806The @option{-gnatF} qualifier forces default and explicit
19807@code{External_Name} parameters in pragmas Import and Export
19808to be uppercased for compatibility with the default behavior
19809of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
19810
19811@node Main Program Definition
19812@section Main Program Definition
19813
19814@noindent
19815The following section discusses differences in the
19816definition of main programs on DEC Ada and GNAT.
19817On DEC Ada, main programs are defined to meet the
19818following conditions:
19819@itemize @bullet
19820@item  Procedure with no formal parameters (returns 0 upon
19821       normal completion)
19822
19823@item  Procedure with no formal parameters (returns 42 when
19824       unhandled exceptions are raised)
19825
19826@item  Function with no formal parameters whose returned value
19827       is of a discrete type
19828
19829@item  Procedure with one OUT formal of a discrete type for
19830       which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
19831
19832@end itemize
19833
19834@noindent
19835When declared with the pragma EXPORT_VALUED_PROCEDURE,
19836a main function or main procedure returns a discrete
19837value whose size is less than 64 bits (32 on VAX systems),
19838the value is zero- or sign-extended as appropriate.
19839On GNAT, main programs are defined as follows:
19840@itemize @bullet
19841@item  Must be a non-generic, parameter-less subprogram that
19842is either a procedure or function returning an Ada
19843STANDARD.INTEGER (the predefined type)
19844
19845@item  Cannot be a generic subprogram or an instantiation of a
19846generic subprogram
19847@end itemize
19848
19849@node Implementation-Defined Attributes
19850@section Implementation-Defined Attributes
19851
19852@noindent
19853GNAT provides all DEC Ada implementation-defined
19854attributes.
19855
19856@node Compiler and Run-Time Interfacing
19857@section Compiler and Run-Time Interfacing
19858
19859@noindent
19860DEC Ada provides the following ways to pass options to the linker
19861(ACS LINK):
19862@itemize @bullet
19863@item  /WAIT and /SUBMIT qualifiers
19864
19865@item  /COMMAND qualifier
19866
19867@item  /[NO]MAP qualifier
19868
19869@item  /OUTPUT=file-spec
19870
19871@item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19872@end itemize
19873
19874@noindent
19875To pass options to the linker, GNAT provides the following
19876switches:
19877
19878@itemize @bullet
19879@item   @option{/EXECUTABLE=exec-name}
19880
19881@item   @option{/VERBOSE qualifier}
19882
19883@item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
19884@end itemize
19885
19886@noindent
19887For more information on these switches, see
19888@ref{Switches for gnatlink}.
19889In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
19890to control optimization. DEC Ada also supplies the
19891following pragmas:
19892@itemize @bullet
19893@item  @code{OPTIMIZE}
19894
19895@item  @code{INLINE}
19896
19897@item  @code{INLINE_GENERIC}
19898
19899@item  @code{SUPPRESS_ALL}
19900
19901@item  @code{PASSIVE}
19902@end itemize
19903
19904@noindent
19905In GNAT, optimization is controlled strictly by command
19906line parameters, as described in the corresponding section of this guide.
19907The DIGITAL pragmas for control of optimization are
19908recognized but ignored.
19909
19910Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
19911the default is that optimization is turned on.
19912
19913@node Program Compilation and Library Management
19914@section Program Compilation and Library Management
19915
19916@noindent
19917DEC Ada and GNAT provide a comparable set of commands to
19918build programs. DEC Ada also provides a program library,
19919which is a concept that does not exist on GNAT. Instead,
19920GNAT provides directories of sources that are compiled as
19921needed.
19922
19923The following table summarizes
19924the DEC Ada commands and provides
19925equivalent GNAT commands. In this table, some GNAT
19926equivalents reflect the fact that GNAT does not use the
19927concept of a program library. Instead, it uses a model
19928in which collections of source and object files are used
19929in a manner consistent with other languages like C and
19930Fortran. Therefore, standard system file commands are used
19931to manipulate these elements. Those GNAT commands are marked with
19932an asterisk.
19933Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
19934
19935@need 1500
19936@multitable @columnfractions .35 .65
19937
19938@item @emph{DEC Ada Command}
19939@tab @emph{GNAT Equivalent / Description}
19940
19941@item @command{ADA}
19942@tab @command{GNAT COMPILE}@*
19943Invokes the compiler to compile one or more Ada source files.
19944
19945@item @command{ACS ATTACH}@*
19946@tab [No equivalent]@*
19947Switches control of terminal from current process running the program
19948library manager.
19949
19950@item @command{ACS CHECK}
19951@tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
19952Forms the execution closure of one
19953or more compiled units and checks completeness and currency.
19954
19955@item @command{ACS COMPILE}
19956@tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
19957Forms the execution closure of one or
19958more specified units, checks completeness and currency,
19959identifies units that have revised source files, compiles same,
19960and recompiles units that are or will become obsolete.
19961Also completes incomplete generic instantiations.
19962
19963@item @command{ACS COPY FOREIGN}
19964@tab Copy (*)@*
19965Copies a foreign object file into the program library as a
19966library unit body.
19967
19968@item @command{ACS COPY UNIT}
19969@tab Copy (*)@*
19970Copies a compiled unit from one program library to another.
19971
19972@item @command{ACS CREATE LIBRARY}
19973@tab Create /directory (*)@*
19974Creates a program library.
19975
19976@item @command{ACS CREATE SUBLIBRARY}
19977@tab Create /directory (*)@*
19978Creates a program sublibrary.
19979
19980@item @command{ACS DELETE LIBRARY}
19981@tab @*
19982Deletes a program library and its contents.
19983
19984@item @command{ACS DELETE SUBLIBRARY}
19985@tab @*
19986Deletes a program sublibrary and its contents.
19987
19988@item @command{ACS DELETE UNIT}
19989@tab Delete file (*)@*
19990On OpenVMS systems, deletes one or more compiled units from
19991the current program library.
19992
19993@item @command{ACS DIRECTORY}
19994@tab Directory (*)@*
19995On OpenVMS systems, lists units contained in the current
19996program library.
19997
19998@item @command{ACS ENTER FOREIGN}
19999@tab Copy (*)@*
20000Allows the import of a foreign body as an Ada library
20001specification and enters a reference to a pointer.
20002
20003@item @command{ACS ENTER UNIT}
20004@tab Copy (*)@*
20005Enters a reference (pointer) from the current program library to
20006a unit compiled into another program library.
20007
20008@item @command{ACS EXIT}
20009@tab [No equivalent]@*
20010Exits from the program library manager.
20011
20012@item @command{ACS EXPORT}
20013@tab Copy (*)@*
20014Creates an object file that contains system-specific object code
20015for one or more units. With GNAT, object files can simply be copied
20016into the desired directory.
20017
20018@item @command{ACS EXTRACT SOURCE}
20019@tab Copy (*)@*
20020Allows access to the copied source file for each Ada compilation unit
20021
20022@item @command{ACS HELP}
20023@tab @command{HELP GNAT}@*
20024Provides online help.
20025
20026@item @command{ACS LINK}
20027@tab @command{GNAT LINK}@*
20028Links an object file containing Ada units into an executable file.
20029
20030@item @command{ACS LOAD}
20031@tab Copy (*)@*
20032Loads (partially compiles) Ada units into the program library.
20033Allows loading a program from a collection of files into a library
20034without knowing the relationship among units.
20035
20036@item @command{ACS MERGE}
20037@tab Copy (*)@*
20038Merges into the current program library, one or more units from
20039another library where they were modified.
20040
20041@item @command{ACS RECOMPILE}
20042@tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20043Recompiles from   external or copied source files any obsolete
20044unit in the closure. Also, completes any incomplete generic
20045instantiations.
20046
20047@item @command{ACS REENTER}
20048@tab @command{GNAT MAKE}@*
20049Reenters current references to units compiled after last entered
20050with the @command{ACS ENTER UNIT} command.
20051
20052@item @command{ACS SET LIBRARY}
20053@tab Set default (*)@*
20054Defines a program library to be the compilation context as well
20055as the target library for compiler output and commands in general.
20056
20057@item @command{ACS SET PRAGMA}
20058@tab Edit @file{gnat.adc} (*)@*
20059Redefines specified  values of the library characteristics
20060@code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20061and @code{Float_Representation}.
20062
20063@item @command{ACS SET SOURCE}
20064@tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20065Defines the source file search list for the @command{ACS COMPILE} command.
20066
20067@item @command{ACS SHOW LIBRARY}
20068@tab Directory (*)@*
20069Lists information about one or more program libraries.
20070
20071@item @command{ACS SHOW PROGRAM}
20072@tab [No equivalent]@*
20073Lists information about the execution closure of one or
20074more units in the program library.
20075
20076@item @command{ACS SHOW SOURCE}
20077@tab Show logical @code{ADA_INCLUDE_PATH}@*
20078Shows the source file search used when compiling units.
20079
20080@item @command{ACS SHOW VERSION}
20081@tab Compile with @option{VERBOSE} option
20082Displays the version number of the compiler and program library
20083manager used.
20084
20085@item @command{ACS SPAWN}
20086@tab [No equivalent]@*
20087Creates a subprocess of the current process (same as @command{DCL SPAWN}
20088command).
20089
20090@item @command{ACS VERIFY}
20091@tab [No equivalent]@*
20092Performs a series of consistency checks on a program library to
20093determine whether the library structure and library files are in
20094valid form.
20095@end multitable
20096
20097@noindent
20098
20099@node Input-Output
20100@section Input-Output
20101
20102@noindent
20103On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20104Management Services (RMS) to perform operations on
20105external files.
20106
20107@noindent
20108DEC Ada and GNAT predefine an identical set of input-
20109output packages. To make the use of the
20110generic TEXT_IO operations more convenient, DEC Ada
20111provides predefined library packages that instantiate the
20112integer and floating-point operations for the predefined
20113integer and floating-point types as shown in the following table.
20114
20115@multitable @columnfractions .45 .55
20116@item @emph{Package Name} @tab Instantiation
20117
20118@item @code{INTEGER_TEXT_IO}
20119@tab @code{INTEGER_IO(INTEGER)}
20120
20121@item @code{SHORT_INTEGER_TEXT_IO}
20122@tab @code{INTEGER_IO(SHORT_INTEGER)}
20123
20124@item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20125@tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20126
20127@item @code{FLOAT_TEXT_IO}
20128@tab @code{FLOAT_IO(FLOAT)}
20129
20130@item @code{LONG_FLOAT_TEXT_IO}
20131@tab @code{FLOAT_IO(LONG_FLOAT)}
20132@end multitable
20133
20134@noindent
20135The DEC Ada predefined packages and their operations
20136are implemented using OpenVMS Alpha files and input-
20137output facilities. DEC Ada supports asynchronous input-
20138output on OpenVMS Alpha. Familiarity with the following is
20139recommended:
20140@itemize @bullet
20141@item  RMS file organizations and access methods
20142
20143@item  OpenVMS file specifications and directories
20144
20145@item  OpenVMS File Definition Language (FDL)
20146@end itemize
20147
20148@noindent
20149GNAT provides I/O facilities that are completely
20150compatible with DEC Ada. The distribution includes the
20151standard DEC Ada versions of all I/O packages, operating
20152in a manner compatible with DEC Ada. In particular, the
20153following packages are by default the DEC Ada (Ada 83)
20154versions of these packages rather than the renamings
20155suggested in annex J of the Ada 95 Reference Manual:
20156@itemize @bullet
20157@item  @code{TEXT_IO}
20158
20159@item  @code{SEQUENTIAL_IO}
20160
20161@item  @code{DIRECT_IO}
20162@end itemize
20163
20164@noindent
20165The use of the standard Ada 95 syntax for child packages (for
20166example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20167packages, as defined in the Ada 95 Reference Manual.
20168GNAT provides DIGITAL-compatible predefined instantiations
20169of the @code{TEXT_IO} packages, and also
20170provides the standard predefined instantiations required
20171by the Ada 95 Reference Manual.
20172
20173For further information on how GNAT interfaces to the file
20174system or how I/O is implemented in programs written in
20175mixed languages, see the chapter ``Implementation of the
20176Standard I/O'' in the @cite{GNAT Reference Manual}.
20177This chapter covers the following:
20178@itemize @bullet
20179@item  Standard I/O packages
20180
20181@item  @code{FORM} strings
20182
20183@item  @code{ADA.DIRECT_IO}
20184
20185@item  @code{ADA.SEQUENTIAL_IO}
20186
20187@item  @code{ADA.TEXT_IO}
20188
20189@item  Stream pointer positioning
20190
20191@item  Reading and writing non-regular files
20192
20193@item  @code{GET_IMMEDIATE}
20194
20195@item  Treating @code{TEXT_IO} files as streams
20196
20197@item  Shared files
20198
20199@item  Open modes
20200@end itemize
20201
20202@node Implementation Limits
20203@section Implementation Limits
20204
20205@noindent
20206The following table lists implementation limits for DEC Ada
20207and GNAT systems.
20208@multitable @columnfractions .60 .20 .20
20209@sp 1
20210@item  @emph{Compilation Parameter}
20211@tab   @emph{DEC Ada}
20212@tab   @emph{GNAT}
20213@sp 1
20214
20215@item  In a subprogram or entry  declaration, maximum number of
20216       formal parameters that are of an unconstrained record type
20217@tab   32
20218@tab   No set limit
20219@sp 1
20220
20221@item  Maximum identifier length (number of characters)
20222@tab   255
20223@tab   255
20224@sp 1
20225
20226@item  Maximum number of characters in a source line
20227@tab   255
20228@tab   255
20229@sp 1
20230
20231@item  Maximum collection size   (number of bytes)
20232@tab   2**31-1
20233@tab   2**31-1
20234@sp 1
20235
20236@item  Maximum number of discriminants for a record type
20237@tab   245
20238@tab   No set limit
20239@sp 1
20240
20241@item  Maximum number of formal parameters in an entry or
20242       subprogram declaration
20243@tab   246
20244@tab    No set limit
20245@sp 1
20246
20247@item  Maximum number of dimensions in an array type
20248@tab   255
20249@tab   No set limit
20250@sp 1
20251
20252@item  Maximum number of library  units and subunits in a compilation.
20253@tab   4095
20254@tab   No set limit
20255@sp 1
20256
20257@item  Maximum number of library units and subunits in an execution.
20258@tab   16383
20259@tab   No set limit
20260@sp 1
20261
20262@item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20263       or @code{PSECT_OBJECT}
20264@tab   32757
20265@tab   No set limit
20266@sp 1
20267
20268@item  Maximum number of enumeration literals in an enumeration type
20269       definition
20270@tab   65535
20271@tab   No set limit
20272@sp 1
20273
20274@item  Maximum number of lines in a source file
20275@tab   65534
20276@tab   No set limit
20277@sp 1
20278
20279@item  Maximum number of bits in any object
20280@tab   2**31-1
20281@tab   2**31-1
20282@sp 1
20283
20284@item  Maximum size of the static portion of a stack frame (approximate)
20285@tab   2**31-1
20286@tab   2**31-1
20287@end multitable
20288
20289@node  Tools
20290@section Tools
20291
20292@end ifset
20293
20294
20295@c **************************************
20296@node Platform-Specific Information for the Run-Time Libraries
20297@appendix Platform-Specific Information for the Run-Time Libraries
20298@cindex Tasking and threads libraries
20299@cindex Threads libraries and tasking
20300@cindex Run-time libraries (platform-specific information)
20301
20302@noindent
20303The GNAT run-time implementation
20304may vary with respect to both the underlying threads library and
20305the exception handling scheme.
20306For threads support, one or more of the following are supplied:
20307@itemize @bullet
20308@item @b{native threads library}, a binding to the thread package from
20309the underlying operating system
20310
20311@item @b{FSU threads library}, a binding to the Florida State University
20312threads implementation, which complies fully with the requirements of Annex D
20313
20314@item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20315POSIX thread package
20316@end itemize
20317
20318@noindent
20319For exception handling, either or both of two models are supplied:
20320@itemize @bullet
20321@item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20322Most programs should experience a substantial speed improvement by
20323being compiled with a ZCX run-time.
20324This is especially true for
20325tasking applications or applications with many exception handlers.}
20326@cindex Zero-Cost Exceptions
20327@cindex ZCX (Zero-Cost Exceptions)
20328which uses binder-generated tables that
20329are interrogated at run time to locate a handler
20330
20331@item @b{setjmp / longjmp} (``SJLJ''),
20332@cindex setjmp/longjmp Exception Model
20333@cindex SJLJ (setjmp/longjmp Exception Model)
20334which uses dynamically-set data to establish
20335the set of handlers
20336@end itemize
20337
20338@noindent
20339This appendix summarizes which combinations of threads and exception support
20340are supplied on various GNAT platforms.
20341It then shows how to select a particular library either
20342permanently or temporarily,
20343explains the properties of (and tradeoffs among) the various threads
20344libraries, and provides some additional
20345information about several specific platforms.
20346
20347@menu
20348* Summary of Run-Time Configurations::
20349* Specifying a Run-Time Library::
20350* Choosing between Native and FSU Threads Libraries::
20351* Choosing the Scheduling Policy::
20352* Solaris-Specific Considerations::
20353* IRIX-Specific Considerations::
20354* Linux-Specific Considerations::
20355@end menu
20356
20357
20358@node Summary of Run-Time Configurations
20359@section Summary of Run-Time Configurations
20360
20361
20362@multitable @columnfractions .30 .70
20363@item @b{alpha-openvms}
20364@item @code{@ @ }@i{rts-native (default)}
20365@item @code{@ @ @ @ }Tasking    @tab native VMS threads
20366@item @code{@ @ @ @ }Exceptions @tab ZCX
20367@*
20368@item @b{pa-hpux}
20369@item @code{@ @ }@i{rts-native (default)}
20370@item @code{@ @ @ @ }Tasking    @tab native HP threads library
20371@item @code{@ @ @ @ }Exceptions @tab ZCX
20372@*
20373@item @code{@ @ }@i{rts-sjlj}
20374@item @code{@ @ @ @ }Tasking    @tab native HP threads library
20375@item @code{@ @ @ @ }Exceptions @tab SJLJ
20376@*
20377@item @b{sparc-solaris}  @tab
20378@item @code{@ @ }@i{rts-native (default)}
20379@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20380@item @code{@ @ @ @ }Exceptions @tab ZCX
20381@*
20382@item @code{@ @ }@i{rts-fsu}    @tab
20383@item @code{@ @ @ @ }Tasking    @tab FSU threads library
20384@item @code{@ @ @ @ }Exceptions @tab SJLJ
20385@*
20386@item @code{@ @ }@i{rts-m64}
20387@item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20388@item @code{@ @ @ @ }Exceptions  @tab ZCX
20389@item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20390@item    @tab Use only on Solaris 8 or later.
20391@item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20392@*
20393@item @code{@ @ }@i{rts-pthread}
20394@item @code{@ @ @ @ }Tasking    @tab pthreads library
20395@item @code{@ @ @ @ }Exceptions @tab ZCX
20396@*
20397@item @code{@ @ }@i{rts-sjlj}
20398@item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20399@item @code{@ @ @ @ }Exceptions @tab SJLJ
20400@*
20401@item @b{x86-linux}
20402@item @code{@ @ }@i{rts-native (default)}
20403@item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20404@item @code{@ @ @ @ }Exceptions @tab ZCX
20405@*
20406@item @code{@ @ }@i{rts-fsu}
20407@item @code{@ @ @ @ }Tasking    @tab FSU threads library
20408@item @code{@ @ @ @ }Exceptions @tab SJLJ
20409@*
20410@item @code{@ @ }@i{rts-sjlj}
20411@item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20412@item @code{@ @ @ @ }Exceptions @tab SJLJ
20413@*
20414@item @b{x86-windows}
20415@item @code{@ @ }@i{rts-native (default)}
20416@item @code{@ @ @ @ }Tasking    @tab native Win32 threads
20417@item @code{@ @ @ @ }Exceptions @tab SJLJ
20418@*
20419@end multitable
20420
20421
20422
20423@node Specifying a Run-Time Library
20424@section Specifying a Run-Time Library
20425
20426@noindent
20427The @file{adainclude} subdirectory containing the sources of the GNAT
20428run-time library, and the @file{adalib} subdirectory containing the
20429@file{ALI} files and the static and/or shared GNAT library, are located
20430in the gcc target-dependent area:
20431
20432@smallexample
20433target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
20434@end smallexample
20435
20436@noindent
20437As indicated above, on some platforms several run-time libraries are supplied.
20438These libraries are installed in the target dependent area and
20439contain a complete source and binary subdirectory. The detailed description
20440below explains the differences between the different libraries in terms of
20441their thread support.
20442
20443The default run-time library (when GNAT is installed) is @emph{rts-native}.
20444This default run time is selected by the means of soft links.
20445For example on x86-linux:
20446
20447@smallexample
20448@group
20449 $(target-dir)
20450     |
20451     +--- adainclude----------+
20452     |                        |
20453     +--- adalib-----------+  |
20454     |                     |  |
20455     +--- rts-native       |  |
20456     |    |                |  |
20457     |    +--- adainclude <---+
20458     |    |                |
20459     |    +--- adalib <----+
20460     |
20461     +--- rts-fsu
20462     |    |
20463     |    +--- adainclude
20464     |    |
20465     |    +--- adalib
20466     |
20467     +--- rts-sjlj
20468          |
20469          +--- adainclude
20470          |
20471          +--- adalib
20472@end group
20473@end smallexample
20474
20475@noindent
20476If the @i{rts-fsu} library is to be selected on a permanent basis,
20477these soft links can be modified with the following commands:
20478
20479@smallexample
20480$ cd $target
20481$ rm -f adainclude adalib
20482$ ln -s rts-fsu/adainclude adainclude
20483$ ln -s rts-fsu/adalib adalib
20484@end smallexample
20485
20486@noindent
20487Alternatively, you can specify @file{rts-fsu/adainclude} in the file
20488@file{$target/ada_source_path} and @file{rts-fsu/adalib} in
20489@file{$target/ada_object_path}.
20490
20491Selecting another run-time library temporarily can be
20492achieved by the regular mechanism for GNAT object or source path selection:
20493
20494@itemize @bullet
20495@item
20496Set the environment variables:
20497
20498@smallexample
20499$ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
20500$ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
20501$ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
20502@end smallexample
20503
20504@item
20505Use @option{-aI$target/rts-fsu/adainclude}
20506and @option{-aO$target/rts-fsu/adalib}
20507on the @command{gnatmake} command line
20508
20509@item
20510Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
20511@cindex @option{--RTS} option
20512@end itemize
20513
20514@noindent
20515You can similarly switch to @emph{rts-sjlj}.
20516
20517@node Choosing between Native and FSU Threads Libraries
20518@section Choosing between Native and FSU Threads Libraries
20519@cindex Native threads library
20520@cindex FSU threads library
20521
20522@noindent
20523Some GNAT implementations offer a choice between
20524native threads and FSU threads.
20525
20526@itemize @bullet
20527@item
20528The @emph{native threads} library correspond to the standard system threads
20529implementation (e.g. LinuxThreads on GNU/Linux,
20530@cindex LinuxThreads library
20531POSIX threads on AIX, or
20532Solaris threads on Solaris). When this option is chosen, GNAT provides
20533a full and accurate implementation of the core language tasking model
20534as described in Chapter 9 of the Ada Reference Manual,
20535but might not (and probably does not) implement
20536the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
20537@cindex Annex D (Real-Time Systems Annex) compliance
20538@cindex Real-Time Systems Annex compliance
20539Indeed, the reason that a choice of libraries is offered
20540on a given target is because some of the
20541ACATS tests for @w{Annex D} fail using the native threads library.
20542As far as possible, this library is implemented
20543in accordance with Ada semantics (e.g., modifying priorities as required
20544to simulate ceiling locking),
20545but there are often slight inaccuracies, most often in the area of
20546absolutely respecting the priority rules on a single
20547processor.
20548Moreover, it is not possible in general to define the exact behavior,
20549because the native threads implementations
20550are not well enough documented.
20551
20552On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
20553@cindex POSIX scheduling policies
20554@cindex @code{SCHED_FIFO} scheduling policy
20555native threads will provide a behavior very close to the @w{Annex D}
20556requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
20557on some systems (in particular GNU/Linux and Solaris), you need to have root
20558privileges to use the @code{SCHED_FIFO} policy.
20559
20560@item
20561The @emph{FSU threads} library provides a completely accurate implementation
20562of @w{Annex D}.
20563Thus, operating with this library, GNAT is 100% compliant with both the core
20564and all @w{Annex D}
20565requirements.
20566The formal validations for implementations offering
20567a choice of threads packages are always carried out using the FSU
20568threads option.
20569@end itemize
20570
20571@noindent
20572From these considerations, it might seem that FSU threads are the
20573better choice,
20574but that is by no means always the case. The FSU threads package
20575operates with all Ada tasks appearing to the system to be a single
20576thread. This is often considerably more efficient than operating
20577with separate threads, since for example, switching between tasks
20578can be accomplished without the (in some cases considerable)
20579overhead of a context switch between two system threads. However,
20580it means that you may well lose concurrency at the system
20581level. Notably, some system operations (such as I/O) may block all
20582tasks in a program and not just the calling task. More
20583significantly, the FSU threads approach likely means you cannot
20584take advantage of multiple processors, since for this you need
20585separate threads (or even separate processes) to operate on
20586different processors.
20587
20588For most programs, the native threads library is
20589usually the better choice. Use the FSU threads if absolute
20590conformance to @w{Annex D} is important for your application, or if
20591you find that the improved efficiency of FSU threads is significant to you.
20592
20593Note also that to take full advantage of Florist and Glade, it is highly
20594recommended that you use native threads.
20595
20596
20597@node Choosing the Scheduling Policy
20598@section Choosing the Scheduling Policy
20599
20600@noindent
20601When using a POSIX threads implementation, you have a choice of several
20602scheduling policies: @code{SCHED_FIFO},
20603@cindex @code{SCHED_FIFO} scheduling policy
20604@code{SCHED_RR}
20605@cindex @code{SCHED_RR} scheduling policy
20606and @code{SCHED_OTHER}.
20607@cindex @code{SCHED_OTHER} scheduling policy
20608Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
20609or @code{SCHED_RR} requires special (e.g., root) privileges.
20610
20611By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
20612@code{SCHED_FIFO},
20613@cindex @code{SCHED_FIFO} scheduling policy
20614you can use one of the following:
20615
20616@itemize @bullet
20617@item
20618@code{pragma Time_Slice (0.0)}
20619@cindex pragma Time_Slice
20620@item
20621the corresponding binder option @option{-T0}
20622@cindex @option{-T0} option
20623@item
20624@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
20625@cindex pragma Task_Dispatching_Policy
20626@end itemize
20627
20628@noindent
20629To specify @code{SCHED_RR},
20630@cindex @code{SCHED_RR} scheduling policy
20631you should use @code{pragma Time_Slice} with a
20632value greater than @code{0.0}, or else use the corresponding @option{-T}
20633binder option.
20634
20635
20636
20637@node Solaris-Specific Considerations
20638@section Solaris-Specific Considerations
20639@cindex Solaris Sparc threads libraries
20640
20641@noindent
20642This section addresses some topics related to the various threads libraries
20643on Sparc Solaris and then provides some information on building and
20644debugging 64-bit applications.
20645
20646@menu
20647* Solaris Threads Issues::
20648* Building and Debugging 64-bit Applications::
20649@end menu
20650
20651
20652@node Solaris Threads Issues
20653@subsection Solaris Threads Issues
20654
20655@noindent
20656Starting with version 3.14, GNAT under Solaris comes with a new tasking
20657run-time library based on POSIX threads --- @emph{rts-pthread}.
20658@cindex rts-pthread threads library
20659This run-time library has the advantage of being mostly shared across all
20660POSIX-compliant thread implementations, and it also provides under
20661@w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
20662@cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
20663and @code{PTHREAD_PRIO_PROTECT}
20664@cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
20665semantics that can be selected using the predefined pragma
20666@code{Locking_Policy}
20667@cindex pragma Locking_Policy (under rts-pthread)
20668with respectively
20669@code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
20670@cindex @code{Inheritance_Locking} (under rts-pthread)
20671@cindex @code{Ceiling_Locking} (under rts-pthread)
20672
20673As explained above, the native run-time library is based on the Solaris thread
20674library (@code{libthread}) and is the default library.
20675The FSU run-time library is based on the FSU threads.
20676@cindex FSU threads library
20677
20678Starting with Solaris 2.5.1, when the Solaris threads library is used
20679(this is the default), programs
20680compiled with GNAT can automatically take advantage of
20681and can thus execute on multiple processors.
20682The user can alternatively specify a processor on which the program should run
20683to emulate a single-processor system. The multiprocessor / uniprocessor choice
20684is made by
20685setting the environment variable @code{GNAT_PROCESSOR}
20686@cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
20687to one of the following:
20688
20689@table @code
20690@item -2
20691Use the default configuration (run the program on all
20692         available processors) - this is the same as having
20693         @code{GNAT_PROCESSOR} unset
20694
20695@item -1
20696Let the run-time implementation choose one processor and run the program on
20697         that processor
20698
20699@item 0 .. Last_Proc
20700Run the program on the specified processor.
20701  @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
20702(where @code{_SC_NPROCESSORS_CONF} is a system variable).
20703@end table
20704
20705
20706@node Building and Debugging 64-bit Applications
20707@subsection Building and Debugging 64-bit Applications
20708
20709@noindent
20710In a 64-bit application, all the sources involved must be compiled with the
20711@option{-m64} command-line option, and a specific GNAT library (compiled with
20712this option) is required.
20713The easiest way to build a 64bit application is to add
20714@option{-m64 --RTS=m64} to the @command{gnatmake} flags.
20715
20716To debug these applications, dwarf-2 debug information is required, so you
20717have to add @option{-gdwarf-2} to your gnatmake arguments.
20718In addition, a special
20719version of gdb, called @command{gdb64}, needs to be used.
20720
20721To summarize, building and debugging a ``Hello World'' program in 64-bit mode
20722amounts to:
20723
20724@smallexample
20725     $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
20726     $ gdb64 hello
20727@end smallexample
20728
20729
20730
20731@node IRIX-Specific Considerations
20732@section IRIX-Specific Considerations
20733@cindex IRIX thread library
20734
20735@noindent
20736On SGI IRIX, the thread library depends on which compiler is used.
20737The @emph{o32 ABI} compiler comes with a run-time library based on the
20738user-level @code{athread}
20739library. Thus kernel-level capabilities such as nonblocking system
20740calls or time slicing can only be achieved reliably by specifying different
20741@code{sprocs} via the pragma @code{Task_Info}
20742@cindex pragma Task_Info (and IRIX threads)
20743and the
20744@code{System.Task_Info} package.
20745@cindex @code{System.Task_Info} package (and IRIX threads)
20746See the @cite{GNAT Reference Manual} for further information.
20747
20748The @emph{n32 ABI} compiler comes with a run-time library based on the
20749kernel POSIX threads and thus does not have the limitations mentioned above.
20750
20751
20752@node Linux-Specific Considerations
20753@section Linux-Specific Considerations
20754@cindex Linux threads libraries
20755
20756@noindent
20757The default thread library under GNU/Linux has the following disadvantages
20758compared to other native thread libraries:
20759
20760@itemize @bullet
20761@item The size of the task's stack is limited to 2 megabytes.
20762@item  The signal model is not POSIX compliant, which means that to send a
20763  signal to the process, you need to send the signal to all threads,
20764  e.g. by using @code{killpg()}.
20765@end itemize
20766
20767
20768
20769@c *******************************
20770@node Example of Binder Output File
20771@appendix Example of Binder Output File
20772
20773@noindent
20774This Appendix displays the source code for @command{gnatbind}'s output
20775file generated for a simple ``Hello World'' program.
20776Comments have been added for clarification purposes.
20777
20778
20779@smallexample @c adanocomment
20780@iftex
20781@leftskip=0cm
20782@end iftex
20783--  The package is called Ada_Main unless this name is actually used
20784--  as a unit name in the partition, in which case some other unique
20785--  name is used.
20786
20787with System;
20788package ada_main is
20789
20790   Elab_Final_Code : Integer;
20791   pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
20792
20793   --  The main program saves the parameters (argument count,
20794   --  argument values, environment pointer) in global variables
20795   --  for later access by other units including
20796   --  Ada.Command_Line.
20797
20798   gnat_argc : Integer;
20799   gnat_argv : System.Address;
20800   gnat_envp : System.Address;
20801
20802   --  The actual variables are stored in a library routine. This
20803   --  is useful for some shared library situations, where there
20804   --  are problems if variables are not in the library.
20805
20806   pragma Import (C, gnat_argc);
20807   pragma Import (C, gnat_argv);
20808   pragma Import (C, gnat_envp);
20809
20810   --  The exit status is similarly an external location
20811
20812   gnat_exit_status : Integer;
20813   pragma Import (C, gnat_exit_status);
20814
20815   GNAT_Version : constant String :=
20816                    "GNAT Version: 3.15w (20010315)";
20817   pragma Export (C, GNAT_Version, "__gnat_version");
20818
20819   --  This is the generated adafinal routine that performs
20820   --  finalization at the end of execution. In the case where
20821   --  Ada is the main program, this main program makes a call
20822   --  to adafinal at program termination.
20823
20824   procedure adafinal;
20825   pragma Export (C, adafinal, "adafinal");
20826
20827   --  This is the generated adainit routine that performs
20828   --  initialization at the start of execution. In the case
20829   --  where Ada is the main program, this main program makes
20830   --  a call to adainit at program startup.
20831
20832   procedure adainit;
20833   pragma Export (C, adainit, "adainit");
20834
20835   --  This routine is called at the start of execution. It is
20836   --  a dummy routine that is used by the debugger to breakpoint
20837   --  at the start of execution.
20838
20839   procedure Break_Start;
20840   pragma Import (C, Break_Start, "__gnat_break_start");
20841
20842   --  This is the actual generated main program (it would be
20843   --  suppressed if the no main program switch were used). As
20844   --  required by standard system conventions, this program has
20845   --  the external name main.
20846
20847   function main
20848     (argc : Integer;
20849      argv : System.Address;
20850      envp : System.Address)
20851      return Integer;
20852   pragma Export (C, main, "main");
20853
20854   --  The following set of constants give the version
20855   --  identification values for every unit in the bound
20856   --  partition. This identification is computed from all
20857   --  dependent semantic units, and corresponds to the
20858   --  string that would be returned by use of the
20859   --  Body_Version or Version attributes.
20860
20861   type Version_32 is mod 2 ** 32;
20862   u00001 : constant Version_32 := 16#7880BEB3#;
20863   u00002 : constant Version_32 := 16#0D24CBD0#;
20864   u00003 : constant Version_32 := 16#3283DBEB#;
20865   u00004 : constant Version_32 := 16#2359F9ED#;
20866   u00005 : constant Version_32 := 16#664FB847#;
20867   u00006 : constant Version_32 := 16#68E803DF#;
20868   u00007 : constant Version_32 := 16#5572E604#;
20869   u00008 : constant Version_32 := 16#46B173D8#;
20870   u00009 : constant Version_32 := 16#156A40CF#;
20871   u00010 : constant Version_32 := 16#033DABE0#;
20872   u00011 : constant Version_32 := 16#6AB38FEA#;
20873   u00012 : constant Version_32 := 16#22B6217D#;
20874   u00013 : constant Version_32 := 16#68A22947#;
20875   u00014 : constant Version_32 := 16#18CC4A56#;
20876   u00015 : constant Version_32 := 16#08258E1B#;
20877   u00016 : constant Version_32 := 16#367D5222#;
20878   u00017 : constant Version_32 := 16#20C9ECA4#;
20879   u00018 : constant Version_32 := 16#50D32CB6#;
20880   u00019 : constant Version_32 := 16#39A8BB77#;
20881   u00020 : constant Version_32 := 16#5CF8FA2B#;
20882   u00021 : constant Version_32 := 16#2F1EB794#;
20883   u00022 : constant Version_32 := 16#31AB6444#;
20884   u00023 : constant Version_32 := 16#1574B6E9#;
20885   u00024 : constant Version_32 := 16#5109C189#;
20886   u00025 : constant Version_32 := 16#56D770CD#;
20887   u00026 : constant Version_32 := 16#02F9DE3D#;
20888   u00027 : constant Version_32 := 16#08AB6B2C#;
20889   u00028 : constant Version_32 := 16#3FA37670#;
20890   u00029 : constant Version_32 := 16#476457A0#;
20891   u00030 : constant Version_32 := 16#731E1B6E#;
20892   u00031 : constant Version_32 := 16#23C2E789#;
20893   u00032 : constant Version_32 := 16#0F1BD6A1#;
20894   u00033 : constant Version_32 := 16#7C25DE96#;
20895   u00034 : constant Version_32 := 16#39ADFFA2#;
20896   u00035 : constant Version_32 := 16#571DE3E7#;
20897   u00036 : constant Version_32 := 16#5EB646AB#;
20898   u00037 : constant Version_32 := 16#4249379B#;
20899   u00038 : constant Version_32 := 16#0357E00A#;
20900   u00039 : constant Version_32 := 16#3784FB72#;
20901   u00040 : constant Version_32 := 16#2E723019#;
20902   u00041 : constant Version_32 := 16#623358EA#;
20903   u00042 : constant Version_32 := 16#107F9465#;
20904   u00043 : constant Version_32 := 16#6843F68A#;
20905   u00044 : constant Version_32 := 16#63305874#;
20906   u00045 : constant Version_32 := 16#31E56CE1#;
20907   u00046 : constant Version_32 := 16#02917970#;
20908   u00047 : constant Version_32 := 16#6CCBA70E#;
20909   u00048 : constant Version_32 := 16#41CD4204#;
20910   u00049 : constant Version_32 := 16#572E3F58#;
20911   u00050 : constant Version_32 := 16#20729FF5#;
20912   u00051 : constant Version_32 := 16#1D4F93E8#;
20913   u00052 : constant Version_32 := 16#30B2EC3D#;
20914   u00053 : constant Version_32 := 16#34054F96#;
20915   u00054 : constant Version_32 := 16#5A199860#;
20916   u00055 : constant Version_32 := 16#0E7F912B#;
20917   u00056 : constant Version_32 := 16#5760634A#;
20918   u00057 : constant Version_32 := 16#5D851835#;
20919
20920   --  The following Export pragmas export the version numbers
20921   --  with symbolic names ending in B (for body) or S
20922   --  (for spec) so that they can be located in a link. The
20923   --  information provided here is sufficient to track down
20924   --  the exact versions of units used in a given build.
20925
20926   pragma Export (C, u00001, "helloB");
20927   pragma Export (C, u00002, "system__standard_libraryB");
20928   pragma Export (C, u00003, "system__standard_libraryS");
20929   pragma Export (C, u00004, "adaS");
20930   pragma Export (C, u00005, "ada__text_ioB");
20931   pragma Export (C, u00006, "ada__text_ioS");
20932   pragma Export (C, u00007, "ada__exceptionsB");
20933   pragma Export (C, u00008, "ada__exceptionsS");
20934   pragma Export (C, u00009, "gnatS");
20935   pragma Export (C, u00010, "gnat__heap_sort_aB");
20936   pragma Export (C, u00011, "gnat__heap_sort_aS");
20937   pragma Export (C, u00012, "systemS");
20938   pragma Export (C, u00013, "system__exception_tableB");
20939   pragma Export (C, u00014, "system__exception_tableS");
20940   pragma Export (C, u00015, "gnat__htableB");
20941   pragma Export (C, u00016, "gnat__htableS");
20942   pragma Export (C, u00017, "system__exceptionsS");
20943   pragma Export (C, u00018, "system__machine_state_operationsB");
20944   pragma Export (C, u00019, "system__machine_state_operationsS");
20945   pragma Export (C, u00020, "system__machine_codeS");
20946   pragma Export (C, u00021, "system__storage_elementsB");
20947   pragma Export (C, u00022, "system__storage_elementsS");
20948   pragma Export (C, u00023, "system__secondary_stackB");
20949   pragma Export (C, u00024, "system__secondary_stackS");
20950   pragma Export (C, u00025, "system__parametersB");
20951   pragma Export (C, u00026, "system__parametersS");
20952   pragma Export (C, u00027, "system__soft_linksB");
20953   pragma Export (C, u00028, "system__soft_linksS");
20954   pragma Export (C, u00029, "system__stack_checkingB");
20955   pragma Export (C, u00030, "system__stack_checkingS");
20956   pragma Export (C, u00031, "system__tracebackB");
20957   pragma Export (C, u00032, "system__tracebackS");
20958   pragma Export (C, u00033, "ada__streamsS");
20959   pragma Export (C, u00034, "ada__tagsB");
20960   pragma Export (C, u00035, "ada__tagsS");
20961   pragma Export (C, u00036, "system__string_opsB");
20962   pragma Export (C, u00037, "system__string_opsS");
20963   pragma Export (C, u00038, "interfacesS");
20964   pragma Export (C, u00039, "interfaces__c_streamsB");
20965   pragma Export (C, u00040, "interfaces__c_streamsS");
20966   pragma Export (C, u00041, "system__file_ioB");
20967   pragma Export (C, u00042, "system__file_ioS");
20968   pragma Export (C, u00043, "ada__finalizationB");
20969   pragma Export (C, u00044, "ada__finalizationS");
20970   pragma Export (C, u00045, "system__finalization_rootB");
20971   pragma Export (C, u00046, "system__finalization_rootS");
20972   pragma Export (C, u00047, "system__finalization_implementationB");
20973   pragma Export (C, u00048, "system__finalization_implementationS");
20974   pragma Export (C, u00049, "system__string_ops_concat_3B");
20975   pragma Export (C, u00050, "system__string_ops_concat_3S");
20976   pragma Export (C, u00051, "system__stream_attributesB");
20977   pragma Export (C, u00052, "system__stream_attributesS");
20978   pragma Export (C, u00053, "ada__io_exceptionsS");
20979   pragma Export (C, u00054, "system__unsigned_typesS");
20980   pragma Export (C, u00055, "system__file_control_blockS");
20981   pragma Export (C, u00056, "ada__finalization__list_controllerB");
20982   pragma Export (C, u00057, "ada__finalization__list_controllerS");
20983
20984   -- BEGIN ELABORATION ORDER
20985   -- ada (spec)
20986   -- gnat (spec)
20987   -- gnat.heap_sort_a (spec)
20988   -- gnat.heap_sort_a (body)
20989   -- gnat.htable (spec)
20990   -- gnat.htable (body)
20991   -- interfaces (spec)
20992   -- system (spec)
20993   -- system.machine_code (spec)
20994   -- system.parameters (spec)
20995   -- system.parameters (body)
20996   -- interfaces.c_streams (spec)
20997   -- interfaces.c_streams (body)
20998   -- system.standard_library (spec)
20999   -- ada.exceptions (spec)
21000   -- system.exception_table (spec)
21001   -- system.exception_table (body)
21002   -- ada.io_exceptions (spec)
21003   -- system.exceptions (spec)
21004   -- system.storage_elements (spec)
21005   -- system.storage_elements (body)
21006   -- system.machine_state_operations (spec)
21007   -- system.machine_state_operations (body)
21008   -- system.secondary_stack (spec)
21009   -- system.stack_checking (spec)
21010   -- system.soft_links (spec)
21011   -- system.soft_links (body)
21012   -- system.stack_checking (body)
21013   -- system.secondary_stack (body)
21014   -- system.standard_library (body)
21015   -- system.string_ops (spec)
21016   -- system.string_ops (body)
21017   -- ada.tags (spec)
21018   -- ada.tags (body)
21019   -- ada.streams (spec)
21020   -- system.finalization_root (spec)
21021   -- system.finalization_root (body)
21022   -- system.string_ops_concat_3 (spec)
21023   -- system.string_ops_concat_3 (body)
21024   -- system.traceback (spec)
21025   -- system.traceback (body)
21026   -- ada.exceptions (body)
21027   -- system.unsigned_types (spec)
21028   -- system.stream_attributes (spec)
21029   -- system.stream_attributes (body)
21030   -- system.finalization_implementation (spec)
21031   -- system.finalization_implementation (body)
21032   -- ada.finalization (spec)
21033   -- ada.finalization (body)
21034   -- ada.finalization.list_controller (spec)
21035   -- ada.finalization.list_controller (body)
21036   -- system.file_control_block (spec)
21037   -- system.file_io (spec)
21038   -- system.file_io (body)
21039   -- ada.text_io (spec)
21040   -- ada.text_io (body)
21041   -- hello (body)
21042   -- END ELABORATION ORDER
21043
21044end ada_main;
21045
21046--  The following source file name pragmas allow the generated file
21047--  names to be unique for different main programs. They are needed
21048--  since the package name will always be Ada_Main.
21049
21050pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21051pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21052
21053--  Generated package body for Ada_Main starts here
21054
21055package body ada_main is
21056
21057   --  The actual finalization is performed by calling the
21058   --  library routine in System.Standard_Library.Adafinal
21059
21060   procedure Do_Finalize;
21061   pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21062
21063   -------------
21064   -- adainit --
21065   -------------
21066
21067@findex adainit
21068   procedure adainit is
21069
21070      --  These booleans are set to True once the associated unit has
21071      --  been elaborated. It is also used to avoid elaborating the
21072      --  same unit twice.
21073
21074      E040 : Boolean;
21075      pragma Import (Ada, E040, "interfaces__c_streams_E");
21076
21077      E008 : Boolean;
21078      pragma Import (Ada, E008, "ada__exceptions_E");
21079
21080      E014 : Boolean;
21081      pragma Import (Ada, E014, "system__exception_table_E");
21082
21083      E053 : Boolean;
21084      pragma Import (Ada, E053, "ada__io_exceptions_E");
21085
21086      E017 : Boolean;
21087      pragma Import (Ada, E017, "system__exceptions_E");
21088
21089      E024 : Boolean;
21090      pragma Import (Ada, E024, "system__secondary_stack_E");
21091
21092      E030 : Boolean;
21093      pragma Import (Ada, E030, "system__stack_checking_E");
21094
21095      E028 : Boolean;
21096      pragma Import (Ada, E028, "system__soft_links_E");
21097
21098      E035 : Boolean;
21099      pragma Import (Ada, E035, "ada__tags_E");
21100
21101      E033 : Boolean;
21102      pragma Import (Ada, E033, "ada__streams_E");
21103
21104      E046 : Boolean;
21105      pragma Import (Ada, E046, "system__finalization_root_E");
21106
21107      E048 : Boolean;
21108      pragma Import (Ada, E048, "system__finalization_implementation_E");
21109
21110      E044 : Boolean;
21111      pragma Import (Ada, E044, "ada__finalization_E");
21112
21113      E057 : Boolean;
21114      pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21115
21116      E055 : Boolean;
21117      pragma Import (Ada, E055, "system__file_control_block_E");
21118
21119      E042 : Boolean;
21120      pragma Import (Ada, E042, "system__file_io_E");
21121
21122      E006 : Boolean;
21123      pragma Import (Ada, E006, "ada__text_io_E");
21124
21125      --  Set_Globals is a library routine that stores away the
21126      --  value of the indicated set of global values in global
21127      --  variables within the library.
21128
21129      procedure Set_Globals
21130        (Main_Priority            : Integer;
21131         Time_Slice_Value         : Integer;
21132         WC_Encoding              : Character;
21133         Locking_Policy           : Character;
21134         Queuing_Policy           : Character;
21135         Task_Dispatching_Policy  : Character;
21136         Adafinal                 : System.Address;
21137         Unreserve_All_Interrupts : Integer;
21138         Exception_Tracebacks     : Integer);
21139@findex __gnat_set_globals
21140      pragma Import (C, Set_Globals, "__gnat_set_globals");
21141
21142      --  SDP_Table_Build is a library routine used to build the
21143      --  exception tables. See unit Ada.Exceptions in files
21144      --  a-except.ads/adb for full details of how zero cost
21145      --  exception handling works. This procedure, the call to
21146      --  it, and the two following tables are all omitted if the
21147      --  build is in longjmp/setjump exception mode.
21148
21149@findex SDP_Table_Build
21150@findex Zero Cost Exceptions
21151      procedure SDP_Table_Build
21152        (SDP_Addresses   : System.Address;
21153         SDP_Count       : Natural;
21154         Elab_Addresses  : System.Address;
21155         Elab_Addr_Count : Natural);
21156      pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21157
21158      --  Table of Unit_Exception_Table addresses. Used for zero
21159      --  cost exception handling to build the top level table.
21160
21161      ST : aliased constant array (1 .. 23) of System.Address := (
21162        Hello'UET_Address,
21163        Ada.Text_Io'UET_Address,
21164        Ada.Exceptions'UET_Address,
21165        Gnat.Heap_Sort_A'UET_Address,
21166        System.Exception_Table'UET_Address,
21167        System.Machine_State_Operations'UET_Address,
21168        System.Secondary_Stack'UET_Address,
21169        System.Parameters'UET_Address,
21170        System.Soft_Links'UET_Address,
21171        System.Stack_Checking'UET_Address,
21172        System.Traceback'UET_Address,
21173        Ada.Streams'UET_Address,
21174        Ada.Tags'UET_Address,
21175        System.String_Ops'UET_Address,
21176        Interfaces.C_Streams'UET_Address,
21177        System.File_Io'UET_Address,
21178        Ada.Finalization'UET_Address,
21179        System.Finalization_Root'UET_Address,
21180        System.Finalization_Implementation'UET_Address,
21181        System.String_Ops_Concat_3'UET_Address,
21182        System.Stream_Attributes'UET_Address,
21183        System.File_Control_Block'UET_Address,
21184        Ada.Finalization.List_Controller'UET_Address);
21185
21186      --  Table of addresses of elaboration routines. Used for
21187      --  zero cost exception handling to make sure these
21188      --  addresses are included in the top level procedure
21189      --  address table.
21190
21191      EA : aliased constant array (1 .. 23) of System.Address := (
21192        adainit'Code_Address,
21193        Do_Finalize'Code_Address,
21194        Ada.Exceptions'Elab_Spec'Address,
21195        System.Exceptions'Elab_Spec'Address,
21196        Interfaces.C_Streams'Elab_Spec'Address,
21197        System.Exception_Table'Elab_Body'Address,
21198        Ada.Io_Exceptions'Elab_Spec'Address,
21199        System.Stack_Checking'Elab_Spec'Address,
21200        System.Soft_Links'Elab_Body'Address,
21201        System.Secondary_Stack'Elab_Body'Address,
21202        Ada.Tags'Elab_Spec'Address,
21203        Ada.Tags'Elab_Body'Address,
21204        Ada.Streams'Elab_Spec'Address,
21205        System.Finalization_Root'Elab_Spec'Address,
21206        Ada.Exceptions'Elab_Body'Address,
21207        System.Finalization_Implementation'Elab_Spec'Address,
21208        System.Finalization_Implementation'Elab_Body'Address,
21209        Ada.Finalization'Elab_Spec'Address,
21210        Ada.Finalization.List_Controller'Elab_Spec'Address,
21211        System.File_Control_Block'Elab_Spec'Address,
21212        System.File_Io'Elab_Body'Address,
21213        Ada.Text_Io'Elab_Spec'Address,
21214        Ada.Text_Io'Elab_Body'Address);
21215
21216   --  Start of processing for adainit
21217
21218   begin
21219
21220      --  Call SDP_Table_Build to build the top level procedure
21221      --  table for zero cost exception handling (omitted in
21222      --  longjmp/setjump mode).
21223
21224      SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21225
21226      --  Call Set_Globals to record various information for
21227      --  this partition.  The values are derived by the binder
21228      --  from information stored in the ali files by the compiler.
21229
21230@findex __gnat_set_globals
21231      Set_Globals
21232        (Main_Priority            => -1,
21233         --  Priority of main program, -1 if no pragma Priority used
21234
21235         Time_Slice_Value         => -1,
21236         --  Time slice from Time_Slice pragma, -1 if none used
21237
21238         WC_Encoding              => 'b',
21239         --  Wide_Character encoding used, default is brackets
21240
21241         Locking_Policy           => ' ',
21242         --  Locking_Policy used, default of space means not
21243         --  specified, otherwise it is the first character of
21244         --  the policy name.
21245
21246         Queuing_Policy           => ' ',
21247         --  Queuing_Policy used, default of space means not
21248         --  specified, otherwise it is the first character of
21249         --  the policy name.
21250
21251         Task_Dispatching_Policy  => ' ',
21252         --  Task_Dispatching_Policy used, default of space means
21253         --  not specified, otherwise first character of the
21254         --  policy name.
21255
21256         Adafinal                 => System.Null_Address,
21257         --  Address of Adafinal routine, not used anymore
21258
21259         Unreserve_All_Interrupts => 0,
21260         --  Set true if pragma Unreserve_All_Interrupts was used
21261
21262         Exception_Tracebacks     => 0);
21263         --  Indicates if exception tracebacks are enabled
21264
21265      Elab_Final_Code := 1;
21266
21267      --  Now we have the elaboration calls for all units in the partition.
21268      --  The Elab_Spec and Elab_Body attributes generate references to the
21269      --  implicit elaboration procedures generated by the compiler for
21270      --  each unit that requires elaboration.
21271
21272      if not E040 then
21273         Interfaces.C_Streams'Elab_Spec;
21274      end if;
21275      E040 := True;
21276      if not E008 then
21277         Ada.Exceptions'Elab_Spec;
21278      end if;
21279      if not E014 then
21280         System.Exception_Table'Elab_Body;
21281         E014 := True;
21282      end if;
21283      if not E053 then
21284         Ada.Io_Exceptions'Elab_Spec;
21285         E053 := True;
21286      end if;
21287      if not E017 then
21288         System.Exceptions'Elab_Spec;
21289         E017 := True;
21290      end if;
21291      if not E030 then
21292         System.Stack_Checking'Elab_Spec;
21293      end if;
21294      if not E028 then
21295         System.Soft_Links'Elab_Body;
21296         E028 := True;
21297      end if;
21298      E030 := True;
21299      if not E024 then
21300         System.Secondary_Stack'Elab_Body;
21301         E024 := True;
21302      end if;
21303      if not E035 then
21304         Ada.Tags'Elab_Spec;
21305      end if;
21306      if not E035 then
21307         Ada.Tags'Elab_Body;
21308         E035 := True;
21309      end if;
21310      if not E033 then
21311         Ada.Streams'Elab_Spec;
21312         E033 := True;
21313      end if;
21314      if not E046 then
21315         System.Finalization_Root'Elab_Spec;
21316      end if;
21317      E046 := True;
21318      if not E008 then
21319         Ada.Exceptions'Elab_Body;
21320         E008 := True;
21321      end if;
21322      if not E048 then
21323         System.Finalization_Implementation'Elab_Spec;
21324      end if;
21325      if not E048 then
21326         System.Finalization_Implementation'Elab_Body;
21327         E048 := True;
21328      end if;
21329      if not E044 then
21330         Ada.Finalization'Elab_Spec;
21331      end if;
21332      E044 := True;
21333      if not E057 then
21334         Ada.Finalization.List_Controller'Elab_Spec;
21335      end if;
21336      E057 := True;
21337      if not E055 then
21338         System.File_Control_Block'Elab_Spec;
21339         E055 := True;
21340      end if;
21341      if not E042 then
21342         System.File_Io'Elab_Body;
21343         E042 := True;
21344      end if;
21345      if not E006 then
21346         Ada.Text_Io'Elab_Spec;
21347      end if;
21348      if not E006 then
21349         Ada.Text_Io'Elab_Body;
21350         E006 := True;
21351      end if;
21352
21353      Elab_Final_Code := 0;
21354   end adainit;
21355
21356   --------------
21357   -- adafinal --
21358   --------------
21359
21360@findex adafinal
21361   procedure adafinal is
21362   begin
21363      Do_Finalize;
21364   end adafinal;
21365
21366   ----------
21367   -- main --
21368   ----------
21369
21370   --  main is actually a function, as in the ANSI C standard,
21371   --  defined to return the exit status. The three parameters
21372   --  are the argument count, argument values and environment
21373   --  pointer.
21374
21375@findex Main Program
21376   function main
21377     (argc : Integer;
21378      argv : System.Address;
21379      envp : System.Address)
21380      return Integer
21381   is
21382      --  The initialize routine performs low level system
21383      --  initialization using a standard library routine which
21384      --  sets up signal handling and performs any other
21385      --  required setup. The routine can be found in file
21386      --  a-init.c.
21387
21388@findex __gnat_initialize
21389      procedure initialize;
21390      pragma Import (C, initialize, "__gnat_initialize");
21391
21392      --  The finalize routine performs low level system
21393      --  finalization using a standard library routine. The
21394      --  routine is found in file a-final.c and in the standard
21395      --  distribution is a dummy routine that does nothing, so
21396      --  really this is a hook for special user finalization.
21397
21398@findex __gnat_finalize
21399      procedure finalize;
21400      pragma Import (C, finalize, "__gnat_finalize");
21401
21402      --  We get to the main program of the partition by using
21403      --  pragma Import because if we try to with the unit and
21404      --  call it Ada style, then not only do we waste time
21405      --  recompiling it, but also, we don't really know the right
21406      --  switches (e.g. identifier character set) to be used
21407      --  to compile it.
21408
21409      procedure Ada_Main_Program;
21410      pragma Import (Ada, Ada_Main_Program, "_ada_hello");
21411
21412   --  Start of processing for main
21413
21414   begin
21415      --  Save global variables
21416
21417      gnat_argc := argc;
21418      gnat_argv := argv;
21419      gnat_envp := envp;
21420
21421      --  Call low level system initialization
21422
21423      Initialize;
21424
21425      --  Call our generated Ada initialization routine
21426
21427      adainit;
21428
21429      --  This is the point at which we want the debugger to get
21430      --  control
21431
21432      Break_Start;
21433
21434      --  Now we call the main program of the partition
21435
21436      Ada_Main_Program;
21437
21438      --  Perform Ada finalization
21439
21440      adafinal;
21441
21442      --  Perform low level system finalization
21443
21444      Finalize;
21445
21446      --  Return the proper exit status
21447      return (gnat_exit_status);
21448   end;
21449
21450--  This section is entirely comments, so it has no effect on the
21451--  compilation of the Ada_Main package. It provides the list of
21452--  object files and linker options, as well as some standard
21453--  libraries needed for the link. The gnatlink utility parses
21454--  this b~hello.adb file to read these comment lines to generate
21455--  the appropriate command line arguments for the call to the
21456--  system linker. The BEGIN/END lines are used for sentinels for
21457--  this parsing operation.
21458
21459--  The exact file names will of course depend on the environment,
21460--  host/target and location of files on the host system.
21461
21462@findex Object file list
21463-- BEGIN Object file/option list
21464   --   ./hello.o
21465   --   -L./
21466   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
21467   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
21468-- END Object file/option list
21469
21470end ada_main;
21471@end smallexample
21472
21473@noindent
21474The Ada code in the above example is exactly what is generated by the
21475binder. We have added comments to more clearly indicate the function
21476of each part of the generated @code{Ada_Main} package.
21477
21478The code is standard Ada in all respects, and can be processed by any
21479tools that handle Ada. In particular, it is possible to use the debugger
21480in Ada mode to debug the generated @code{Ada_Main} package. For example,
21481suppose that for reasons that you do not understand, your program is crashing
21482during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
21483you can place a breakpoint on the call:
21484
21485@smallexample @c ada
21486Ada.Text_Io'Elab_Body;
21487@end smallexample
21488
21489@noindent
21490and trace the elaboration routine for this package to find out where
21491the problem might be (more usually of course you would be debugging
21492elaboration code in your own application).
21493
21494
21495@node Elaboration Order Handling in GNAT
21496@appendix Elaboration Order Handling in GNAT
21497@cindex Order of elaboration
21498@cindex Elaboration control
21499
21500@menu
21501* Elaboration Code in Ada 95::
21502* Checking the Elaboration Order in Ada 95::
21503* Controlling the Elaboration Order in Ada 95::
21504* Controlling Elaboration in GNAT - Internal Calls::
21505* Controlling Elaboration in GNAT - External Calls::
21506* Default Behavior in GNAT - Ensuring Safety::
21507* Treatment of Pragma Elaborate::
21508* Elaboration Issues for Library Tasks::
21509* Mixing Elaboration Models::
21510* What to Do If the Default Elaboration Behavior Fails::
21511* Elaboration for Access-to-Subprogram Values::
21512* Summary of Procedures for Elaboration Control::
21513* Other Elaboration Order Considerations::
21514@end menu
21515
21516@noindent
21517This chapter describes the handling of elaboration code in Ada 95 and
21518in GNAT, and discusses how the order of elaboration of program units can
21519be controlled in GNAT, either automatically or with explicit programming
21520features.
21521
21522@node Elaboration Code in Ada 95
21523@section Elaboration Code in Ada 95
21524
21525@noindent
21526Ada 95 provides rather general mechanisms for executing code at elaboration
21527time, that is to say before the main program starts executing. Such code arises
21528in three contexts:
21529
21530@table @asis
21531@item Initializers for variables.
21532Variables declared at the library level, in package specs or bodies, can
21533require initialization that is performed at elaboration time, as in:
21534@smallexample @c ada
21535@cartouche
21536Sqrt_Half : Float := Sqrt (0.5);
21537@end cartouche
21538@end smallexample
21539
21540@item Package initialization code
21541Code in a @code{BEGIN-END} section at the outer level of a package body is
21542executed as part of the package body elaboration code.
21543
21544@item Library level task allocators
21545Tasks that are declared using task allocators at the library level
21546start executing immediately and hence can execute at elaboration time.
21547@end table
21548
21549@noindent
21550Subprogram calls are possible in any of these contexts, which means that
21551any arbitrary part of the program may be executed as part of the elaboration
21552code. It is even possible to write a program which does all its work at
21553elaboration time, with a null main program, although stylistically this
21554would usually be considered an inappropriate way to structure
21555a program.
21556
21557An important concern arises in the context of elaboration code:
21558we have to be sure that it is executed in an appropriate order. What we
21559have is a series of elaboration code sections, potentially one section
21560for each unit in the program. It is important that these execute
21561in the correct order. Correctness here means that, taking the above
21562example of the declaration of @code{Sqrt_Half},
21563if some other piece of
21564elaboration code references @code{Sqrt_Half},
21565then it must run after the
21566section of elaboration code that contains the declaration of
21567@code{Sqrt_Half}.
21568
21569There would never be any order of elaboration problem if we made a rule
21570that whenever you @code{with} a unit, you must elaborate both the spec and body
21571of that unit before elaborating the unit doing the @code{with}'ing:
21572
21573@smallexample @c ada
21574@group
21575@cartouche
21576with Unit_1;
21577package Unit_2 is ...
21578@end cartouche
21579@end group
21580@end smallexample
21581
21582@noindent
21583would require that both the body and spec of @code{Unit_1} be elaborated
21584before the spec of @code{Unit_2}. However, a rule like that would be far too
21585restrictive. In particular, it would make it impossible to have routines
21586in separate packages that were mutually recursive.
21587
21588You might think that a clever enough compiler could look at the actual
21589elaboration code and determine an appropriate correct order of elaboration,
21590but in the general case, this is not possible. Consider the following
21591example.
21592
21593In the body of @code{Unit_1}, we have a procedure @code{Func_1}
21594that references
21595the variable @code{Sqrt_1}, which is declared in the elaboration code
21596of the body of @code{Unit_1}:
21597
21598@smallexample @c ada
21599@cartouche
21600Sqrt_1 : Float := Sqrt (0.1);
21601@end cartouche
21602@end smallexample
21603
21604@noindent
21605The elaboration code of the body of @code{Unit_1} also contains:
21606
21607@smallexample @c ada
21608@group
21609@cartouche
21610if expression_1 = 1 then
21611   Q := Unit_2.Func_2;
21612end if;
21613@end cartouche
21614@end group
21615@end smallexample
21616
21617@noindent
21618@code{Unit_2} is exactly parallel,
21619it has a procedure @code{Func_2} that references
21620the variable @code{Sqrt_2}, which is declared in the elaboration code of
21621the body @code{Unit_2}:
21622
21623@smallexample @c ada
21624@cartouche
21625Sqrt_2 : Float := Sqrt (0.1);
21626@end cartouche
21627@end smallexample
21628
21629@noindent
21630The elaboration code of the body of @code{Unit_2} also contains:
21631
21632@smallexample @c ada
21633@group
21634@cartouche
21635if expression_2 = 2 then
21636   Q := Unit_1.Func_1;
21637end if;
21638@end cartouche
21639@end group
21640@end smallexample
21641
21642@noindent
21643Now the question is, which of the following orders of elaboration is
21644acceptable:
21645
21646@smallexample
21647@group
21648Spec of Unit_1
21649Spec of Unit_2
21650Body of Unit_1
21651Body of Unit_2
21652@end group
21653@end smallexample
21654
21655@noindent
21656or
21657
21658@smallexample
21659@group
21660Spec of Unit_2
21661Spec of Unit_1
21662Body of Unit_2
21663Body of Unit_1
21664@end group
21665@end smallexample
21666
21667@noindent
21668If you carefully analyze the flow here, you will see that you cannot tell
21669at compile time the answer to this question.
21670If @code{expression_1} is not equal to 1,
21671and @code{expression_2} is not equal to 2,
21672then either order is acceptable, because neither of the function calls is
21673executed. If both tests evaluate to true, then neither order is acceptable
21674and in fact there is no correct order.
21675
21676If one of the two expressions is true, and the other is false, then one
21677of the above orders is correct, and the other is incorrect. For example,
21678if @code{expression_1} = 1 and @code{expression_2} /= 2,
21679then the call to @code{Func_2}
21680will occur, but not the call to @code{Func_1.}
21681This means that it is essential
21682to elaborate the body of @code{Unit_1} before
21683the body of @code{Unit_2}, so the first
21684order of elaboration is correct and the second is wrong.
21685
21686By making @code{expression_1} and @code{expression_2}
21687depend on input data, or perhaps
21688the time of day, we can make it impossible for the compiler or binder
21689to figure out which of these expressions will be true, and hence it
21690is impossible to guarantee a safe order of elaboration at run time.
21691
21692@node Checking the Elaboration Order in Ada 95
21693@section Checking the Elaboration Order in Ada 95
21694
21695@noindent
21696In some languages that involve the same kind of elaboration problems,
21697e.g. Java and C++, the programmer is expected to worry about these
21698ordering problems himself, and it is common to
21699write a program in which an incorrect elaboration order  gives
21700surprising results, because it references variables before they
21701are initialized.
21702Ada 95 is designed to be a safe language, and a programmer-beware approach is
21703clearly not sufficient. Consequently, the language provides three lines
21704of defense:
21705
21706@table @asis
21707@item Standard rules
21708Some standard rules restrict the possible choice of elaboration
21709order. In particular, if you @code{with} a unit, then its spec is always
21710elaborated before the unit doing the @code{with}. Similarly, a parent
21711spec is always elaborated before the child spec, and finally
21712a spec is always elaborated before its corresponding body.
21713
21714@item Dynamic elaboration checks
21715@cindex Elaboration checks
21716@cindex Checks, elaboration
21717Dynamic checks are made at run time, so that if some entity is accessed
21718before it is elaborated (typically  by means of a subprogram call)
21719then the exception (@code{Program_Error}) is raised.
21720
21721@item Elaboration control
21722Facilities are provided for the programmer to specify the desired order
21723of elaboration.
21724@end table
21725
21726Let's look at these facilities in more detail. First, the rules for
21727dynamic checking. One possible rule would be simply to say that the
21728exception is raised if you access a variable which has not yet been
21729elaborated. The trouble with this approach is that it could require
21730expensive checks on every variable reference. Instead Ada 95 has two
21731rules which are a little more restrictive, but easier to check, and
21732easier to state:
21733
21734@table @asis
21735@item Restrictions on calls
21736A subprogram can only be called at elaboration time if its body
21737has been elaborated. The rules for elaboration given above guarantee
21738that the spec of the subprogram has been elaborated before the
21739call, but not the body. If this rule is violated, then the
21740exception @code{Program_Error} is raised.
21741
21742@item Restrictions on instantiations
21743A generic unit can only be instantiated if the body of the generic
21744unit has been elaborated. Again, the rules for elaboration given above
21745guarantee that the spec of the generic unit has been elaborated
21746before the instantiation, but not the body. If this rule is
21747violated, then the exception @code{Program_Error} is raised.
21748@end table
21749
21750@noindent
21751The idea is that if the body has been elaborated, then any variables
21752it references must have been elaborated; by checking for the body being
21753elaborated we guarantee that none of its references causes any
21754trouble. As we noted above, this is a little too restrictive, because a
21755subprogram that has no non-local references in its body may in fact be safe
21756to call. However, it really would be unsafe to rely on this, because
21757it would mean that the caller was aware of details of the implementation
21758in the body. This goes against the basic tenets of Ada.
21759
21760A plausible implementation can be described as follows.
21761A Boolean variable is associated with each subprogram
21762and each generic unit. This variable is initialized to False, and is set to
21763True at the point body is elaborated. Every call or instantiation checks the
21764variable, and raises @code{Program_Error} if the variable is False.
21765
21766Note that one might think that it would be good enough to have one Boolean
21767variable for each package, but that would not deal with cases of trying
21768to call a body in the same package as the call
21769that has not been elaborated yet.
21770Of course a compiler may be able to do enough analysis to optimize away
21771some of the Boolean variables as unnecessary, and @code{GNAT} indeed
21772does such optimizations, but still the easiest conceptual model is to
21773think of there being one variable per subprogram.
21774
21775@node Controlling the Elaboration Order in Ada 95
21776@section Controlling the Elaboration Order in Ada 95
21777
21778@noindent
21779In the previous section we discussed the rules in Ada 95 which ensure
21780that @code{Program_Error} is raised if an incorrect elaboration order is
21781chosen. This prevents erroneous executions, but we need mechanisms to
21782specify a correct execution and avoid the exception altogether.
21783To achieve this, Ada 95 provides a number of features for controlling
21784the order of elaboration. We discuss these features in this section.
21785
21786First, there are several ways of indicating to the compiler that a given
21787unit has no elaboration problems:
21788
21789@table @asis
21790@item packages that do not require a body
21791In Ada 95, a library package that does not require a body does not permit
21792a body. This means that if we have a such a package, as in:
21793
21794@smallexample @c ada
21795@group
21796@cartouche
21797package Definitions is
21798   generic
21799      type m is new integer;
21800   package Subp is
21801      type a is array (1 .. 10) of m;
21802      type b is array (1 .. 20) of m;
21803   end Subp;
21804end Definitions;
21805@end cartouche
21806@end group
21807@end smallexample
21808
21809@noindent
21810A package that @code{with}'s @code{Definitions} may safely instantiate
21811@code{Definitions.Subp} because the compiler can determine that there
21812definitely is no package body to worry about in this case
21813
21814@item pragma Pure
21815@cindex pragma Pure
21816@findex Pure
21817Places sufficient restrictions on a unit to guarantee that
21818no call to any subprogram in the unit can result in an
21819elaboration problem. This means that the compiler does not need
21820to worry about the point of elaboration of such units, and in
21821particular, does not need to check any calls to any subprograms
21822in this unit.
21823
21824@item pragma Preelaborate
21825@findex Preelaborate
21826@cindex pragma Preelaborate
21827This pragma places slightly less stringent restrictions on a unit than
21828does pragma Pure,
21829but these restrictions are still sufficient to ensure that there
21830are no elaboration problems with any calls to the unit.
21831
21832@item pragma Elaborate_Body
21833@findex Elaborate_Body
21834@cindex pragma Elaborate_Body
21835This pragma requires that the body of a unit be elaborated immediately
21836after its spec. Suppose a unit @code{A} has such a pragma,
21837and unit @code{B} does
21838a @code{with} of unit @code{A}. Recall that the standard rules require
21839the spec of unit @code{A}
21840to be elaborated before the @code{with}'ing unit; given the pragma in
21841@code{A}, we also know that the body of @code{A}
21842will be elaborated before @code{B}, so
21843that calls to @code{A} are safe and do not need a check.
21844@end table
21845
21846@noindent
21847Note that,
21848unlike pragma @code{Pure} and pragma @code{Preelaborate},
21849the use of
21850@code{Elaborate_Body} does not guarantee that the program is
21851free of elaboration problems, because it may not be possible
21852to satisfy the requested elaboration order.
21853Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
21854If a programmer
21855marks @code{Unit_1} as @code{Elaborate_Body},
21856and not @code{Unit_2,} then the order of
21857elaboration will be:
21858
21859@smallexample
21860@group
21861Spec of Unit_2
21862Spec of Unit_1
21863Body of Unit_1
21864Body of Unit_2
21865@end group
21866@end smallexample
21867
21868@noindent
21869Now that means that the call to @code{Func_1} in @code{Unit_2}
21870need not be checked,
21871it must be safe. But the call to @code{Func_2} in
21872@code{Unit_1} may still fail if
21873@code{Expression_1} is equal to 1,
21874and the programmer must still take
21875responsibility for this not being the case.
21876
21877If all units carry a pragma @code{Elaborate_Body}, then all problems are
21878eliminated, except for calls entirely within a body, which are
21879in any case fully under programmer control. However, using the pragma
21880everywhere is not always possible.
21881In particular, for our @code{Unit_1}/@code{Unit_2} example, if
21882we marked both of them as having pragma @code{Elaborate_Body}, then
21883clearly there would be no possible elaboration order.
21884
21885The above pragmas allow a server to guarantee safe use by clients, and
21886clearly this is the preferable approach. Consequently a good rule in
21887Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
21888and if this is not possible,
21889mark them as @code{Elaborate_Body} if possible.
21890As we have seen, there are situations where neither of these
21891three pragmas can be used.
21892So we also provide methods for clients to control the
21893order of elaboration of the servers on which they depend:
21894
21895@table @asis
21896@item pragma Elaborate (unit)
21897@findex Elaborate
21898@cindex pragma Elaborate
21899This pragma is placed in the context clause, after a @code{with} clause,
21900and it requires that the body of the named unit be elaborated before
21901the unit in which the pragma occurs. The idea is to use this pragma
21902if the current unit calls at elaboration time, directly or indirectly,
21903some subprogram in the named unit.
21904
21905@item pragma Elaborate_All (unit)
21906@findex Elaborate_All
21907@cindex pragma Elaborate_All
21908This is a stronger version of the Elaborate pragma. Consider the
21909following example:
21910
21911@smallexample
21912Unit A @code{with}'s unit B and calls B.Func in elab code
21913Unit B @code{with}'s unit C, and B.Func calls C.Func
21914@end smallexample
21915
21916@noindent
21917Now if we put a pragma @code{Elaborate (B)}
21918in unit @code{A}, this ensures that the
21919body of @code{B} is elaborated before the call, but not the
21920body of @code{C}, so
21921the call to @code{C.Func} could still cause @code{Program_Error} to
21922be raised.
21923
21924The effect of a pragma @code{Elaborate_All} is stronger, it requires
21925not only that the body of the named unit be elaborated before the
21926unit doing the @code{with}, but also the bodies of all units that the
21927named unit uses, following @code{with} links transitively. For example,
21928if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
21929then it requires
21930not only that the body of @code{B} be elaborated before @code{A},
21931but also the
21932body of @code{C}, because @code{B} @code{with}'s @code{C}.
21933@end table
21934
21935@noindent
21936We are now in a position to give a usage rule in Ada 95 for avoiding
21937elaboration problems, at least if dynamic dispatching and access to
21938subprogram values are not used. We will handle these cases separately
21939later.
21940
21941The rule is simple. If a unit has elaboration code that can directly or
21942indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
21943a generic unit in a @code{with}'ed unit,
21944then if the @code{with}'ed unit does not have
21945pragma @code{Pure} or @code{Preelaborate}, then the client should have
21946a pragma @code{Elaborate_All}
21947for the @code{with}'ed unit. By following this rule a client is
21948assured that calls can be made without risk of an exception.
21949If this rule is not followed, then a program may be in one of four
21950states:
21951
21952@table @asis
21953@item No order exists
21954No order of elaboration exists which follows the rules, taking into
21955account any @code{Elaborate}, @code{Elaborate_All},
21956or @code{Elaborate_Body} pragmas. In
21957this case, an Ada 95 compiler must diagnose the situation at bind
21958time, and refuse to build an executable program.
21959
21960@item One or more orders exist, all incorrect
21961One or more acceptable elaboration orders exists, and all of them
21962generate an elaboration order problem. In this case, the binder
21963can build an executable program, but @code{Program_Error} will be raised
21964when the program is run.
21965
21966@item Several orders exist, some right, some incorrect
21967One or more acceptable elaboration orders exists, and some of them
21968work, and some do not. The programmer has not controlled
21969the order of elaboration, so the binder may or may not pick one of
21970the correct orders, and the program may or may not raise an
21971exception when it is run. This is the worst case, because it means
21972that the program may fail when moved to another compiler, or even
21973another version of the same compiler.
21974
21975@item One or more orders exists, all correct
21976One ore more acceptable elaboration orders exist, and all of them
21977work. In this case the program runs successfully. This state of
21978affairs can be guaranteed by following the rule we gave above, but
21979may be true even if the rule is not followed.
21980@end table
21981
21982@noindent
21983Note that one additional advantage of following our Elaborate_All rule
21984is that the program continues to stay in the ideal (all orders OK) state
21985even if maintenance
21986changes some bodies of some subprograms. Conversely, if a program that does
21987not follow this rule happens to be safe at some point, this state of affairs
21988may deteriorate silently as a result of maintenance changes.
21989
21990You may have noticed that the above discussion did not mention
21991the use of @code{Elaborate_Body}. This was a deliberate omission. If you
21992@code{with} an @code{Elaborate_Body} unit, it still may be the case that
21993code in the body makes calls to some other unit, so it is still necessary
21994to use @code{Elaborate_All} on such units.
21995
21996@node Controlling Elaboration in GNAT - Internal Calls
21997@section Controlling Elaboration in GNAT - Internal Calls
21998
21999@noindent
22000In the case of internal calls, i.e. calls within a single package, the
22001programmer has full control over the order of elaboration, and it is up
22002to the programmer to elaborate declarations in an appropriate order. For
22003example writing:
22004
22005@smallexample @c ada
22006@group
22007@cartouche
22008function One return Float;
22009
22010Q : Float := One;
22011
22012function One return Float is
22013begin
22014     return 1.0;
22015end One;
22016@end cartouche
22017@end group
22018@end smallexample
22019
22020@noindent
22021will obviously raise @code{Program_Error} at run time, because function
22022One will be called before its body is elaborated. In this case GNAT will
22023generate a warning that the call will raise @code{Program_Error}:
22024
22025@smallexample
22026@group
22027@cartouche
22028 1. procedure y is
22029 2.    function One return Float;
22030 3.
22031 4.    Q : Float := One;
22032                    |
22033    >>> warning: cannot call "One" before body is elaborated
22034    >>> warning: Program_Error will be raised at run time
22035
22036 5.
22037 6.    function One return Float is
22038 7.    begin
22039 8.         return 1.0;
22040 9.    end One;
2204110.
2204211. begin
2204312.    null;
2204413. end;
22045@end cartouche
22046@end group
22047@end smallexample
22048
22049@noindent
22050Note that in this particular case, it is likely that the call is safe, because
22051the function @code{One} does not access any global variables.
22052Nevertheless in Ada 95, we do not want the validity of the check to depend on
22053the contents of the body (think about the separate compilation case), so this
22054is still wrong, as we discussed in the previous sections.
22055
22056The error is easily corrected by rearranging the declarations so that the
22057body of One appears before the declaration containing the call
22058(note that in Ada 95,
22059declarations can appear in any order, so there is no restriction that
22060would prevent this reordering, and if we write:
22061
22062@smallexample @c ada
22063@group
22064@cartouche
22065function One return Float;
22066
22067function One return Float is
22068begin
22069     return 1.0;
22070end One;
22071
22072Q : Float := One;
22073@end cartouche
22074@end group
22075@end smallexample
22076
22077@noindent
22078then all is well, no warning is generated, and no
22079@code{Program_Error} exception
22080will be raised.
22081Things are more complicated when a chain of subprograms is executed:
22082
22083@smallexample @c ada
22084@group
22085@cartouche
22086function A return Integer;
22087function B return Integer;
22088function C return Integer;
22089
22090function B return Integer is begin return A; end;
22091function C return Integer is begin return B; end;
22092
22093X : Integer := C;
22094
22095function A return Integer is begin return 1; end;
22096@end cartouche
22097@end group
22098@end smallexample
22099
22100@noindent
22101Now the call to @code{C}
22102at elaboration time in the declaration of @code{X} is correct, because
22103the body of @code{C} is already elaborated,
22104and the call to @code{B} within the body of
22105@code{C} is correct, but the call
22106to @code{A} within the body of @code{B} is incorrect, because the body
22107of @code{A} has not been elaborated, so @code{Program_Error}
22108will be raised on the call to @code{A}.
22109In this case GNAT will generate a
22110warning that @code{Program_Error} may be
22111raised at the point of the call. Let's look at the warning:
22112
22113@smallexample
22114@group
22115@cartouche
22116 1. procedure x is
22117 2.    function A return Integer;
22118 3.    function B return Integer;
22119 4.    function C return Integer;
22120 5.
22121 6.    function B return Integer is begin return A; end;
22122                                                    |
22123    >>> warning: call to "A" before body is elaborated may
22124                 raise Program_Error
22125    >>> warning: "B" called at line 7
22126    >>> warning: "C" called at line 9
22127
22128 7.    function C return Integer is begin return B; end;
22129 8.
22130 9.    X : Integer := C;
2213110.
2213211.    function A return Integer is begin return 1; end;
2213312.
2213413. begin
2213514.    null;
2213615. end;
22137@end cartouche
22138@end group
22139@end smallexample
22140
22141@noindent
22142Note that the message here says ``may raise'', instead of the direct case,
22143where the message says ``will be raised''. That's because whether
22144@code{A} is
22145actually called depends in general on run-time flow of control.
22146For example, if the body of @code{B} said
22147
22148@smallexample @c ada
22149@group
22150@cartouche
22151function B return Integer is
22152begin
22153   if some-condition-depending-on-input-data then
22154      return A;
22155   else
22156      return 1;
22157   end if;
22158end B;
22159@end cartouche
22160@end group
22161@end smallexample
22162
22163@noindent
22164then we could not know until run time whether the incorrect call to A would
22165actually occur, so @code{Program_Error} might
22166or might not be raised. It is possible for a compiler to
22167do a better job of analyzing bodies, to
22168determine whether or not @code{Program_Error}
22169might be raised, but it certainly
22170couldn't do a perfect job (that would require solving the halting problem
22171and is provably impossible), and because this is a warning anyway, it does
22172not seem worth the effort to do the analysis. Cases in which it
22173would be relevant are rare.
22174
22175In practice, warnings of either of the forms given
22176above will usually correspond to
22177real errors, and should be examined carefully and eliminated.
22178In the rare case where a warning is bogus, it can be suppressed by any of
22179the following methods:
22180
22181@itemize @bullet
22182@item
22183Compile with the @option{-gnatws} switch set
22184
22185@item
22186Suppress @code{Elaboration_Check} for the called subprogram
22187
22188@item
22189Use pragma @code{Warnings_Off} to turn warnings off for the call
22190@end itemize
22191
22192@noindent
22193For the internal elaboration check case,
22194GNAT by default generates the
22195necessary run-time checks to ensure
22196that @code{Program_Error} is raised if any
22197call fails an elaboration check. Of course this can only happen if a
22198warning has been issued as described above. The use of pragma
22199@code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22200some of these checks, meaning that it may be possible (but is not
22201guaranteed) for a program to be able to call a subprogram whose body
22202is not yet elaborated, without raising a @code{Program_Error} exception.
22203
22204@node Controlling Elaboration in GNAT - External Calls
22205@section Controlling Elaboration in GNAT - External Calls
22206
22207@noindent
22208The previous section discussed the case in which the execution of a
22209particular thread of elaboration code occurred entirely within a
22210single unit. This is the easy case to handle, because a programmer
22211has direct and total control over the order of elaboration, and
22212furthermore, checks need only be generated in cases which are rare
22213and which the compiler can easily detect.
22214The situation is more complex when separate compilation is taken into account.
22215Consider the following:
22216
22217@smallexample @c ada
22218@cartouche
22219@group
22220package Math is
22221   function Sqrt (Arg : Float) return Float;
22222end Math;
22223
22224package body Math is
22225   function Sqrt (Arg : Float) return Float is
22226   begin
22227         ...
22228   end Sqrt;
22229end Math;
22230@end group
22231@group
22232with Math;
22233package Stuff is
22234   X : Float := Math.Sqrt (0.5);
22235end Stuff;
22236
22237with Stuff;
22238procedure Main is
22239begin
22240   ...
22241end Main;
22242@end group
22243@end cartouche
22244@end smallexample
22245
22246@noindent
22247where @code{Main} is the main program. When this program is executed, the
22248elaboration code must first be executed, and one of the jobs of the
22249binder is to determine the order in which the units of a program are
22250to be elaborated. In this case we have four units: the spec and body
22251of @code{Math},
22252the spec of @code{Stuff} and the body of @code{Main}).
22253In what order should the four separate sections of elaboration code
22254be executed?
22255
22256There are some restrictions in the order of elaboration that the binder
22257can choose. In particular, if unit U has a @code{with}
22258for a package @code{X}, then you
22259are assured that the spec of @code{X}
22260is elaborated before U , but you are
22261not assured that the body of @code{X}
22262is elaborated before U.
22263This means that in the above case, the binder is allowed to choose the
22264order:
22265
22266@smallexample
22267spec of Math
22268spec of Stuff
22269body of Math
22270body of Main
22271@end smallexample
22272
22273@noindent
22274but that's not good, because now the call to @code{Math.Sqrt}
22275that happens during
22276the elaboration of the @code{Stuff}
22277spec happens before the body of @code{Math.Sqrt} is
22278elaborated, and hence causes @code{Program_Error} exception to be raised.
22279At first glance, one might say that the binder is misbehaving, because
22280obviously you want to elaborate the body of something you @code{with}
22281first, but
22282that is not a general rule that can be followed in all cases. Consider
22283
22284@smallexample @c ada
22285@group
22286@cartouche
22287package X is ...
22288
22289package Y is ...
22290
22291with X;
22292package body Y is ...
22293
22294with Y;
22295package body X is ...
22296@end cartouche
22297@end group
22298@end smallexample
22299
22300@noindent
22301This is a common arrangement, and, apart from the order of elaboration
22302problems that might arise in connection with elaboration code, this works fine.
22303A rule that says that you must first elaborate the body of anything you
22304@code{with} cannot work in this case:
22305the body of @code{X} @code{with}'s @code{Y},
22306which means you would have to
22307elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22308which means
22309you have to elaborate the body of @code{X} first, but ... and we have a
22310loop that cannot be broken.
22311
22312It is true that the binder can in many cases guess an order of elaboration
22313that is unlikely to cause a @code{Program_Error}
22314exception to be raised, and it tries to do so (in the
22315above example of @code{Math/Stuff/Spec}, the GNAT binder will
22316by default
22317elaborate the body of @code{Math} right after its spec, so all will be well).
22318
22319However, a program that blindly relies on the binder to be helpful can
22320get into trouble, as we discussed in the previous sections, so
22321GNAT
22322provides a number of facilities for assisting the programmer in
22323developing programs that are robust with respect to elaboration order.
22324
22325@node Default Behavior in GNAT - Ensuring Safety
22326@section Default Behavior in GNAT - Ensuring Safety
22327
22328@noindent
22329The default behavior in GNAT ensures elaboration safety. In its
22330default mode GNAT implements the
22331rule we previously described as the right approach. Let's restate it:
22332
22333@itemize
22334@item
22335@emph{If a unit has elaboration code that can directly or indirectly make a
22336call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22337in a @code{with}'ed unit, then if the @code{with}'ed unit
22338does not have pragma @code{Pure} or
22339@code{Preelaborate}, then the client should have an
22340@code{Elaborate_All} for the @code{with}'ed unit.}
22341@end itemize
22342
22343@noindent
22344By following this rule a client is assured that calls and instantiations
22345can be made without risk of an exception.
22346
22347In this mode GNAT traces all calls that are potentially made from
22348elaboration code, and puts in any missing implicit @code{Elaborate_All}
22349pragmas.
22350The advantage of this approach is that no elaboration problems
22351are possible if the binder can find an elaboration order that is
22352consistent with these implicit @code{Elaborate_All} pragmas. The
22353disadvantage of this approach is that no such order may exist.
22354
22355If the binder does not generate any diagnostics, then it means that it
22356has found an elaboration order that is guaranteed to be safe. However,
22357the binder may still be relying on implicitly generated
22358@code{Elaborate_All} pragmas so portability to other compilers than
22359GNAT is not guaranteed.
22360
22361If it is important to guarantee portability, then the compilations should
22362use the
22363@option{-gnatwl}
22364(warn on elaboration problems) switch. This will cause warning messages
22365to be generated indicating the missing @code{Elaborate_All} pragmas.
22366Consider the following source program:
22367
22368@smallexample @c ada
22369@group
22370@cartouche
22371with k;
22372package j is
22373  m : integer := k.r;
22374end;
22375@end cartouche
22376@end group
22377@end smallexample
22378
22379@noindent
22380where it is clear that there
22381should be a pragma @code{Elaborate_All}
22382for unit @code{k}. An implicit pragma will be generated, and it is
22383likely that the binder will be able to honor it. However, if you want
22384to port this program to some other Ada compiler than GNAT.
22385it is safer to include the pragma explicitly in the source. If this
22386unit is compiled with the
22387@option{-gnatwl}
22388switch, then the compiler outputs a warning:
22389
22390@smallexample
22391@group
22392@cartouche
223931. with k;
223942. package j is
223953.   m : integer := k.r;
22396                     |
22397   >>> warning: call to "r" may raise Program_Error
22398   >>> warning: missing pragma Elaborate_All for "k"
22399
224004. end;
22401@end cartouche
22402@end group
22403@end smallexample
22404
22405@noindent
22406and these warnings can be used as a guide for supplying manually
22407the missing pragmas. It is usually a bad idea to use this warning
22408option during development. That's because it will warn you when
22409you need to put in a pragma, but cannot warn you when it is time
22410to take it out. So the use of pragma Elaborate_All may lead to
22411unnecessary dependencies and even false circularities.
22412
22413This default mode is more restrictive than the Ada Reference
22414Manual, and it is possible to construct programs which will compile
22415using the dynamic model described there, but will run into a
22416circularity using the safer static model we have described.
22417
22418Of course any Ada compiler must be able to operate in a mode
22419consistent with the requirements of the Ada Reference Manual,
22420and in particular must have the capability of implementing the
22421standard dynamic model of elaboration with run-time checks.
22422
22423In GNAT, this standard mode can be achieved either by the use of
22424the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
22425command, or by the use of the configuration pragma:
22426
22427@smallexample @c ada
22428pragma Elaboration_Checks (RM);
22429@end smallexample
22430
22431@noindent
22432Either approach will cause the unit affected to be compiled using the
22433standard dynamic run-time elaboration checks described in the Ada
22434Reference Manual. The static model is generally preferable, since it
22435is clearly safer to rely on compile and link time checks rather than
22436run-time checks. However, in the case of legacy code, it may be
22437difficult to meet the requirements of the static model. This
22438issue is further discussed in
22439@ref{What to Do If the Default Elaboration Behavior Fails}.
22440
22441Note that the static model provides a strict subset of the allowed
22442behavior and programs of the Ada Reference Manual, so if you do
22443adhere to the static model and no circularities exist,
22444then you are assured that your program will
22445work using the dynamic model, providing that you remove any
22446pragma Elaborate statements from the source.
22447
22448@node Treatment of Pragma Elaborate
22449@section Treatment of Pragma Elaborate
22450@cindex Pragma Elaborate
22451
22452@noindent
22453The use of @code{pragma Elaborate}
22454should generally be avoided in Ada 95 programs.
22455The reason for this is that there is no guarantee that transitive calls
22456will be properly handled. Indeed at one point, this pragma was placed
22457in Annex J (Obsolescent Features), on the grounds that it is never useful.
22458
22459Now that's a bit restrictive. In practice, the case in which
22460@code{pragma Elaborate} is useful is when the caller knows that there
22461are no transitive calls, or that the called unit contains all necessary
22462transitive @code{pragma Elaborate} statements, and legacy code often
22463contains such uses.
22464
22465Strictly speaking the static mode in GNAT should ignore such pragmas,
22466since there is no assurance at compile time that the necessary safety
22467conditions are met. In practice, this would cause GNAT to be incompatible
22468with correctly written Ada 83 code that had all necessary
22469@code{pragma Elaborate} statements in place. Consequently, we made the
22470decision that GNAT in its default mode will believe that if it encounters
22471a @code{pragma Elaborate} then the programmer knows what they are doing,
22472and it will trust that no elaboration errors can occur.
22473
22474The result of this decision is two-fold. First to be safe using the
22475static mode, you should remove all @code{pragma Elaborate} statements.
22476Second, when fixing circularities in existing code, you can selectively
22477use @code{pragma Elaborate} statements to convince the static mode of
22478GNAT that it need not generate an implicit @code{pragma Elaborate_All}
22479statement.
22480
22481When using the static mode with @option{-gnatwl}, any use of
22482@code{pragma Elaborate} will generate a warning about possible
22483problems.
22484
22485@node Elaboration Issues for Library Tasks
22486@section Elaboration Issues for Library Tasks
22487@cindex Library tasks, elaboration issues
22488@cindex Elaboration of library tasks
22489
22490@noindent
22491In this section we examine special elaboration issues that arise for
22492programs that declare library level tasks.
22493
22494Generally the model of execution of an Ada program is that all units are
22495elaborated, and then execution of the program starts. However, the
22496declaration of library tasks definitely does not fit this model. The
22497reason for this is that library tasks start as soon as they are declared
22498(more precisely, as soon as the statement part of the enclosing package
22499body is reached), that is to say before elaboration
22500of the program is complete. This means that if such a task calls a
22501subprogram, or an entry in another task, the callee may or may not be
22502elaborated yet, and in the standard
22503Reference Manual model of dynamic elaboration checks, you can even
22504get timing dependent Program_Error exceptions, since there can be
22505a race between the elaboration code and the task code.
22506
22507The static model of elaboration in GNAT seeks to avoid all such
22508dynamic behavior, by being conservative, and the conservative
22509approach in this particular case is to assume that all the code
22510in a task body is potentially executed at elaboration time if
22511a task is declared at the library level.
22512
22513This can definitely result in unexpected circularities. Consider
22514the following example
22515
22516@smallexample @c ada
22517package Decls is
22518  task Lib_Task is
22519     entry Start;
22520  end Lib_Task;
22521
22522  type My_Int is new Integer;
22523
22524  function Ident (M : My_Int) return My_Int;
22525end Decls;
22526
22527with Utils;
22528package body Decls is
22529  task body Lib_Task is
22530  begin
22531     accept Start;
22532     Utils.Put_Val (2);
22533  end Lib_Task;
22534
22535  function Ident (M : My_Int) return My_Int is
22536  begin
22537     return M;
22538  end Ident;
22539end Decls;
22540
22541with Decls;
22542package Utils is
22543  procedure Put_Val (Arg : Decls.My_Int);
22544end Utils;
22545
22546with Text_IO;
22547package body Utils is
22548  procedure Put_Val (Arg : Decls.My_Int) is
22549  begin
22550     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
22551  end Put_Val;
22552end Utils;
22553
22554with Decls;
22555procedure Main is
22556begin
22557   Decls.Lib_Task.Start;
22558end;
22559@end smallexample
22560
22561@noindent
22562If the above example is compiled in the default static elaboration
22563mode, then a circularity occurs. The circularity comes from the call
22564@code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
22565this call occurs in elaboration code, we need an implicit pragma
22566@code{Elaborate_All} for @code{Utils}. This means that not only must
22567the spec and body of @code{Utils} be elaborated before the body
22568of @code{Decls}, but also the spec and body of any unit that is
22569@code{with'ed} by the body of @code{Utils} must also be elaborated before
22570the body of @code{Decls}. This is the transitive implication of
22571pragma @code{Elaborate_All} and it makes sense, because in general
22572the body of @code{Put_Val} might have a call to something in a
22573@code{with'ed} unit.
22574
22575In this case, the body of Utils (actually its spec) @code{with's}
22576@code{Decls}. Unfortunately this means that the body of @code{Decls}
22577must be elaborated before itself, in case there is a call from the
22578body of @code{Utils}.
22579
22580Here is the exact chain of events we are worrying about:
22581
22582@enumerate
22583@item
22584In the body of @code{Decls} a call is made from within the body of a library
22585task to a subprogram in the package @code{Utils}. Since this call may
22586occur at elaboration time (given that the task is activated at elaboration
22587time), we have to assume the worst, i.e. that the
22588call does happen at elaboration time.
22589
22590@item
22591This means that the body and spec of @code{Util} must be elaborated before
22592the body of @code{Decls} so that this call does not cause an access before
22593elaboration.
22594
22595@item
22596Within the body of @code{Util}, specifically within the body of
22597@code{Util.Put_Val} there may be calls to any unit @code{with}'ed
22598by this package.
22599
22600@item
22601One such @code{with}'ed package is package @code{Decls}, so there
22602might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
22603In fact there is such a call in this example, but we would have to
22604assume that there was such a call even if it were not there, since
22605we are not supposed to write the body of @code{Decls} knowing what
22606is in the body of @code{Utils}; certainly in the case of the
22607static elaboration model, the compiler does not know what is in
22608other bodies and must assume the worst.
22609
22610@item
22611This means that the spec and body of @code{Decls} must also be
22612elaborated before we elaborate the unit containing the call, but
22613that unit is @code{Decls}! This means that the body of @code{Decls}
22614must be elaborated before itself, and that's a circularity.
22615@end enumerate
22616
22617@noindent
22618Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
22619the body of @code{Decls} you will get a true Ada Reference Manual
22620circularity that makes the program illegal.
22621
22622In practice, we have found that problems with the static model of
22623elaboration in existing code often arise from library tasks, so
22624we must address this particular situation.
22625
22626Note that if we compile and run the program above, using the dynamic model of
22627elaboration (that is to say use the @option{-gnatE} switch),
22628then it compiles, binds,
22629links, and runs, printing the expected result of 2. Therefore in some sense
22630the circularity here is only apparent, and we need to capture
22631the properties of this program that  distinguish it from other library-level
22632tasks that have real elaboration problems.
22633
22634We have four possible answers to this question:
22635
22636@itemize @bullet
22637
22638@item
22639Use the dynamic model of elaboration.
22640
22641If we use the @option{-gnatE} switch, then as noted above, the program works.
22642Why is this? If we examine the task body, it is apparent that the task cannot
22643proceed past the
22644@code{accept} statement until after elaboration has been completed, because
22645the corresponding entry call comes from the main program, not earlier.
22646This is why the dynamic model works here. But that's really giving
22647up on a precise analysis, and we prefer to take this approach only if we cannot
22648solve the
22649problem in any other manner. So let us examine two ways to reorganize
22650the program to avoid the potential elaboration problem.
22651
22652@item
22653Split library tasks into separate packages.
22654
22655Write separate packages, so that library tasks are isolated from
22656other declarations as much as possible. Let us look at a variation on
22657the above program.
22658
22659@smallexample @c ada
22660package Decls1 is
22661  task Lib_Task is
22662     entry Start;
22663  end Lib_Task;
22664end Decls1;
22665
22666with Utils;
22667package body Decls1 is
22668  task body Lib_Task is
22669  begin
22670     accept Start;
22671     Utils.Put_Val (2);
22672  end Lib_Task;
22673end Decls1;
22674
22675package Decls2 is
22676  type My_Int is new Integer;
22677  function Ident (M : My_Int) return My_Int;
22678end Decls2;
22679
22680with Utils;
22681package body Decls2 is
22682  function Ident (M : My_Int) return My_Int is
22683  begin
22684     return M;
22685  end Ident;
22686end Decls2;
22687
22688with Decls2;
22689package Utils is
22690  procedure Put_Val (Arg : Decls2.My_Int);
22691end Utils;
22692
22693with Text_IO;
22694package body Utils is
22695  procedure Put_Val (Arg : Decls2.My_Int) is
22696  begin
22697     Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
22698  end Put_Val;
22699end Utils;
22700
22701with Decls1;
22702procedure Main is
22703begin
22704   Decls1.Lib_Task.Start;
22705end;
22706@end smallexample
22707
22708@noindent
22709All we have done is to split @code{Decls} into two packages, one
22710containing the library task, and one containing everything else. Now
22711there is no cycle, and the program compiles, binds, links and executes
22712using the default static model of elaboration.
22713
22714@item
22715Declare separate task types.
22716
22717A significant part of the problem arises because of the use of the
22718single task declaration form. This means that the elaboration of
22719the task type, and the elaboration of the task itself (i.e. the
22720creation of the task) happen at the same time. A good rule
22721of style in Ada 95 is to always create explicit task types. By
22722following the additional step of placing task objects in separate
22723packages from the task type declaration, many elaboration problems
22724are avoided. Here is another modified example of the example program:
22725
22726@smallexample @c ada
22727package Decls is
22728  task type Lib_Task_Type is
22729     entry Start;
22730  end Lib_Task_Type;
22731
22732  type My_Int is new Integer;
22733
22734  function Ident (M : My_Int) return My_Int;
22735end Decls;
22736
22737with Utils;
22738package body Decls is
22739  task body Lib_Task_Type is
22740  begin
22741     accept Start;
22742     Utils.Put_Val (2);
22743  end Lib_Task_Type;
22744
22745  function Ident (M : My_Int) return My_Int is
22746  begin
22747     return M;
22748  end Ident;
22749end Decls;
22750
22751with Decls;
22752package Utils is
22753  procedure Put_Val (Arg : Decls.My_Int);
22754end Utils;
22755
22756with Text_IO;
22757package body Utils is
22758  procedure Put_Val (Arg : Decls.My_Int) is
22759  begin
22760     Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
22761  end Put_Val;
22762end Utils;
22763
22764with Decls;
22765package Declst is
22766   Lib_Task : Decls.Lib_Task_Type;
22767end Declst;
22768
22769with Declst;
22770procedure Main is
22771begin
22772   Declst.Lib_Task.Start;
22773end;
22774@end smallexample
22775
22776@noindent
22777What we have done here is to replace the @code{task} declaration in
22778package @code{Decls} with a @code{task type} declaration. Then we
22779introduce a separate package @code{Declst} to contain the actual
22780task object. This separates the elaboration issues for
22781the @code{task type}
22782declaration, which causes no trouble, from the elaboration issues
22783of the task object, which is also unproblematic, since it is now independent
22784of the elaboration of  @code{Utils}.
22785This separation of concerns also corresponds to
22786a generally sound engineering principle of separating declarations
22787from instances. This version of the program also compiles, binds, links,
22788and executes, generating the expected output.
22789
22790@item
22791Use No_Entry_Calls_In_Elaboration_Code restriction.
22792@cindex No_Entry_Calls_In_Elaboration_Code
22793
22794The previous two approaches described how a program can be restructured
22795to avoid the special problems caused by library task bodies. in practice,
22796however, such restructuring may be difficult to apply to existing legacy code,
22797so we must consider solutions that do not require massive rewriting.
22798
22799Let us consider more carefully why our original sample program works
22800under the dynamic model of elaboration. The reason is that the code
22801in the task body blocks immediately on the @code{accept}
22802statement. Now of course there is nothing to prohibit elaboration
22803code from making entry calls (for example from another library level task),
22804so we cannot tell in isolation that
22805the task will not execute the accept statement  during elaboration.
22806
22807However, in practice it is very unusual to see elaboration code
22808make any entry calls, and the pattern of tasks starting
22809at elaboration time and then immediately blocking on @code{accept} or
22810@code{select} statements is very common. What this means is that
22811the compiler is being too pessimistic when it analyzes the
22812whole package body as though it might be executed at elaboration
22813time.
22814
22815If we know that the elaboration code contains no entry calls, (a very safe
22816assumption most of the time, that could almost be made the default
22817behavior), then we can compile all units of the program under control
22818of the following configuration pragma:
22819
22820@smallexample
22821pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
22822@end smallexample
22823
22824@noindent
22825This pragma can be placed in the @file{gnat.adc} file in the usual
22826manner. If we take our original unmodified program and compile it
22827in the presence of a @file{gnat.adc} containing the above pragma,
22828then once again, we can compile, bind, link, and execute, obtaining
22829the expected result. In the presence of this pragma, the compiler does
22830not trace calls in a task body, that appear after the first @code{accept}
22831or @code{select} statement, and therefore does not report a potential
22832circularity in the original program.
22833
22834The compiler will check to the extent it can that the above
22835restriction is not violated, but it is not always possible to do a
22836complete check at compile time, so it is important to use this
22837pragma only if the stated restriction is in fact met, that is to say
22838no task receives an entry call before elaboration of all units is completed.
22839
22840@end itemize
22841
22842@node Mixing Elaboration Models
22843@section Mixing Elaboration Models
22844@noindent
22845So far, we have assumed that the entire program is either compiled
22846using the dynamic model or static model, ensuring consistency. It
22847is possible to mix the two models, but rules have to be followed
22848if this mixing is done to ensure that elaboration checks are not
22849omitted.
22850
22851The basic rule is that @emph{a unit compiled with the static model cannot
22852be @code{with'ed} by a unit compiled with the dynamic model}. The
22853reason for this is that in the static model, a unit assumes that
22854its clients guarantee to use (the equivalent of) pragma
22855@code{Elaborate_All} so that no elaboration checks are required
22856in inner subprograms, and this assumption is violated if the
22857client is compiled with dynamic checks.
22858
22859The precise rule is as follows. A unit that is compiled with dynamic
22860checks can only @code{with} a unit that meets at least one of the
22861following criteria:
22862
22863@itemize @bullet
22864
22865@item
22866The @code{with'ed} unit is itself compiled with dynamic elaboration
22867checks (that is with the @option{-gnatE} switch.
22868
22869@item
22870The @code{with'ed} unit is an internal GNAT implementation unit from
22871the System, Interfaces, Ada, or GNAT hierarchies.
22872
22873@item
22874The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
22875
22876@item
22877The @code{with'ing} unit (that is the client) has an explicit pragma
22878@code{Elaborate_All} for the @code{with'ed} unit.
22879
22880@end itemize
22881
22882@noindent
22883If this rule is violated, that is if a unit with dynamic elaboration
22884checks @code{with's} a unit that does not meet one of the above four
22885criteria, then the binder (@code{gnatbind}) will issue a warning
22886similar to that in the following example:
22887
22888@smallexample
22889warning: "x.ads" has dynamic elaboration checks and with's
22890warning:   "y.ads" which has static elaboration checks
22891@end smallexample
22892
22893@noindent
22894These warnings indicate that the rule has been violated, and that as a result
22895elaboration checks may be missed in the resulting executable file.
22896This warning may be suppressed using the @option{-ws} binder switch
22897in the usual manner.
22898
22899One useful application of this mixing rule is in the case of a subsystem
22900which does not itself @code{with} units from the remainder of the
22901application. In this case, the entire subsystem can be compiled with
22902dynamic checks to resolve a circularity in the subsystem, while
22903allowing the main application that uses this subsystem to be compiled
22904using the more reliable default static model.
22905
22906@node What to Do If the Default Elaboration Behavior Fails
22907@section What to Do If the Default Elaboration Behavior Fails
22908
22909@noindent
22910If the binder cannot find an acceptable order, it outputs detailed
22911diagnostics. For example:
22912@smallexample
22913@group
22914@iftex
22915@leftskip=0cm
22916@end iftex
22917error: elaboration circularity detected
22918info:   "proc (body)" must be elaborated before "pack (body)"
22919info:     reason: Elaborate_All probably needed in unit "pack (body)"
22920info:     recompile "pack (body)" with -gnatwl
22921info:                             for full details
22922info:       "proc (body)"
22923info:         is needed by its spec:
22924info:       "proc (spec)"
22925info:         which is withed by:
22926info:       "pack (body)"
22927info:  "pack (body)" must be elaborated before "proc (body)"
22928info:     reason: pragma Elaborate in unit "proc (body)"
22929@end group
22930
22931@end smallexample
22932
22933@noindent
22934In this case we have a cycle that the binder cannot break. On the one
22935hand, there is an explicit pragma Elaborate in @code{proc} for
22936@code{pack}. This means that the body of @code{pack} must be elaborated
22937before the body of @code{proc}. On the other hand, there is elaboration
22938code in @code{pack} that calls a subprogram in @code{proc}. This means
22939that for maximum safety, there should really be a pragma
22940Elaborate_All in @code{pack} for @code{proc} which would require that
22941the body of @code{proc} be elaborated before the body of
22942@code{pack}. Clearly both requirements cannot be satisfied.
22943Faced with a circularity of this kind, you have three different options.
22944
22945@table @asis
22946@item Fix the program
22947The most desirable option from the point of view of long-term maintenance
22948is to rearrange the program so that the elaboration problems are avoided.
22949One useful technique is to place the elaboration code into separate
22950child packages. Another is to move some of the initialization code to
22951explicitly called subprograms, where the program controls the order
22952of initialization explicitly. Although this is the most desirable option,
22953it may be impractical and involve too much modification, especially in
22954the case of complex legacy code.
22955
22956@item Perform dynamic checks
22957If the compilations are done using the
22958@option{-gnatE}
22959(dynamic elaboration check) switch, then GNAT behaves in
22960a quite different manner. Dynamic checks are generated for all calls
22961that could possibly result in raising an exception. With this switch,
22962the compiler does not generate implicit @code{Elaborate_All} pragmas.
22963The behavior then is exactly as specified in the Ada 95 Reference Manual.
22964The binder will generate an executable program that may or may not
22965raise @code{Program_Error}, and then it is the programmer's job to ensure
22966that it does not raise an exception. Note that it is important to
22967compile all units with the switch, it cannot be used selectively.
22968
22969@item Suppress checks
22970The drawback of dynamic checks is that they generate a
22971significant overhead at run time, both in space and time. If you
22972are absolutely sure that your program cannot raise any elaboration
22973exceptions, and you still want to use the dynamic elaboration model,
22974then you can use the configuration pragma
22975@code{Suppress (Elaboration_Check)} to suppress all such checks. For
22976example this pragma could be placed in the @file{gnat.adc} file.
22977
22978@item Suppress checks selectively
22979When you know that certain calls in elaboration code cannot possibly
22980lead to an elaboration error, and the binder nevertheless generates warnings
22981on those calls and inserts Elaborate_All pragmas that lead to elaboration
22982circularities, it is possible to remove those warnings locally and obtain
22983a program that will bind. Clearly this can be unsafe, and it is the
22984responsibility of the programmer to make sure that the resulting program has
22985no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
22986be used with different granularity to suppress warnings and break
22987elaboration circularities:
22988
22989@itemize @bullet
22990@item
22991Place the pragma that names the called subprogram in the declarative part
22992that contains the call.
22993
22994@item
22995Place the pragma in the declarative part, without naming an entity. This
22996disables warnings on all calls in the corresponding  declarative region.
22997
22998@item
22999Place the pragma in the package spec that declares the called subprogram,
23000and name the subprogram. This disables warnings on all elaboration calls to
23001that subprogram.
23002
23003@item
23004Place the pragma in the package spec that declares the called subprogram,
23005without naming any entity. This disables warnings on all elaboration calls to
23006all subprograms declared in this spec.
23007
23008@item Use Pragma Elaborate
23009As previously described in section @xref{Treatment of Pragma Elaborate},
23010GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23011that no elaboration checks are required on calls to the designated unit.
23012There may be cases in which the caller knows that no transitive calls
23013can occur, so that a @code{pragma Elaborate} will be sufficient in a
23014case where @code{pragma Elaborate_All} would cause a circularity.
23015@end itemize
23016
23017@noindent
23018These five cases are listed in order of decreasing safety, and therefore
23019require increasing programmer care in their application. Consider the
23020following program:
23021
23022@smallexample @c adanocomment
23023package Pack1 is
23024  function F1 return Integer;
23025  X1 : Integer;
23026end Pack1;
23027
23028package Pack2 is
23029  function F2 return Integer;
23030  function Pure (x : integer) return integer;
23031  --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23032  --  pragma Suppress (Elaboration_Check);              -- (4)
23033end Pack2;
23034
23035with Pack2;
23036package body Pack1 is
23037  function F1 return Integer is
23038  begin
23039    return 100;
23040  end F1;
23041  Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23042begin
23043  declare
23044    --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23045    --  pragma Suppress(Elaboration_Check);             -- (2)
23046  begin
23047    X1 := Pack2.F2 + 1;                --  Elab. call (2)
23048  end;
23049end Pack1;
23050
23051with Pack1;
23052package body Pack2 is
23053  function F2 return Integer is
23054  begin
23055     return Pack1.F1;
23056  end F2;
23057  function Pure (x : integer) return integer is
23058  begin
23059     return x ** 3 - 3 * x;
23060  end;
23061end Pack2;
23062
23063with Pack1, Ada.Text_IO;
23064procedure Proc3 is
23065begin
23066  Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23067end Proc3;
23068@end smallexample
23069In the absence of any pragmas, an attempt to bind this program produces
23070the following diagnostics:
23071@smallexample
23072@group
23073@iftex
23074@leftskip=.5cm
23075@end iftex
23076error: elaboration circularity detected
23077info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23078info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23079info:       recompile "pack1 (body)" with -gnatwl for full details
23080info:          "pack1 (body)"
23081info:             must be elaborated along with its spec:
23082info:          "pack1 (spec)"
23083info:             which is withed by:
23084info:          "pack2 (body)"
23085info:             which must be elaborated along with its spec:
23086info:          "pack2 (spec)"
23087info:             which is withed by:
23088info:          "pack1 (body)"
23089@end group
23090@end smallexample
23091The sources of the circularity are the two calls to @code{Pack2.Pure} and
23092@code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23093F2 is safe, even though F2 calls F1, because the call appears after the
23094elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23095remove the warning on the call. It is also possible to use pragma (2)
23096because there are no other potentially unsafe calls in the block.
23097
23098@noindent
23099The call to @code{Pure} is safe because this function does not depend on the
23100state of @code{Pack2}. Therefore any call to this function is safe, and it
23101is correct to place pragma (3) in the corresponding package spec.
23102
23103@noindent
23104Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23105warnings on all calls to functions declared therein. Note that this is not
23106necessarily safe, and requires more detailed examination of the subprogram
23107bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23108be already elaborated.
23109@end table
23110
23111@noindent
23112It is hard to generalize on which of these four approaches should be
23113taken. Obviously if it is possible to fix the program so that the default
23114treatment works, this is preferable, but this may not always be practical.
23115It is certainly simple enough to use
23116@option{-gnatE}
23117but the danger in this case is that, even if the GNAT binder
23118finds a correct elaboration order, it may not always do so,
23119and certainly a binder from another Ada compiler might not. A
23120combination of testing and analysis (for which the warnings generated
23121with the
23122@option{-gnatwl}
23123switch can be useful) must be used to ensure that the program is free
23124of errors. One switch that is useful in this testing is the
23125@option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23126switch for
23127@code{gnatbind}.
23128Normally the binder tries to find an order that has the best chance of
23129of avoiding elaboration problems. With this switch, the binder
23130plays a devil's advocate role, and tries to choose the order that
23131has the best chance of failing. If your program works even with this
23132switch, then it has a better chance of being error free, but this is still
23133not a guarantee.
23134
23135For an example of this approach in action, consider the C-tests (executable
23136tests) from the ACVC suite. If these are compiled and run with the default
23137treatment, then all but one of them succeed without generating any error
23138diagnostics from the binder. However, there is one test that fails, and
23139this is not surprising, because the whole point of this test is to ensure
23140that the compiler can handle cases where it is impossible to determine
23141a correct order statically, and it checks that an exception is indeed
23142raised at run time.
23143
23144This one test must be compiled and run using the
23145@option{-gnatE}
23146switch, and then it passes. Alternatively, the entire suite can
23147be run using this switch. It is never wrong to run with the dynamic
23148elaboration switch if your code is correct, and we assume that the
23149C-tests are indeed correct (it is less efficient, but efficiency is
23150not a factor in running the ACVC tests.)
23151
23152@node Elaboration for Access-to-Subprogram Values
23153@section Elaboration for Access-to-Subprogram Values
23154@cindex Access-to-subprogram
23155
23156@noindent
23157The introduction of access-to-subprogram types in Ada 95 complicates
23158the handling of elaboration. The trouble is that it becomes
23159impossible to tell at compile time which procedure
23160is being called. This means that it is not possible for the binder
23161to analyze the elaboration requirements in this case.
23162
23163If at the point at which the access value is created
23164(i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23165the body of the subprogram is
23166known to have been elaborated, then the access value is safe, and its use
23167does not require a check. This may be achieved by appropriate arrangement
23168of the order of declarations if the subprogram is in the current unit,
23169or, if the subprogram is in another unit, by using pragma
23170@code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23171on the referenced unit.
23172
23173If the referenced body is not known to have been elaborated at the point
23174the access value is created, then any use of the access value must do a
23175dynamic check, and this dynamic check will fail and raise a
23176@code{Program_Error} exception if the body has not been elaborated yet.
23177GNAT will generate the necessary checks, and in addition, if the
23178@option{-gnatwl}
23179switch is set, will generate warnings that such checks are required.
23180
23181The use of dynamic dispatching for tagged types similarly generates
23182a requirement for dynamic checks, and premature calls to any primitive
23183operation of a tagged type before the body of the operation has been
23184elaborated, will result in the raising of @code{Program_Error}.
23185
23186@node Summary of Procedures for Elaboration Control
23187@section Summary of Procedures for Elaboration Control
23188@cindex Elaboration control
23189
23190@noindent
23191First, compile your program with the default options, using none of
23192the special elaboration control switches. If the binder successfully
23193binds your program, then you can be confident that, apart from issues
23194raised by the use of access-to-subprogram types and dynamic dispatching,
23195the program is free of elaboration errors. If it is important that the
23196program be portable, then use the
23197@option{-gnatwl}
23198switch to generate warnings about missing @code{Elaborate_All}
23199pragmas, and supply the missing pragmas.
23200
23201If the program fails to bind using the default static elaboration
23202handling, then you can fix the program to eliminate the binder
23203message, or recompile the entire program with the
23204@option{-gnatE} switch to generate dynamic elaboration checks,
23205and, if you are sure there really are no elaboration problems,
23206use a global pragma @code{Suppress (Elaboration_Check)}.
23207
23208@node Other Elaboration Order Considerations
23209@section Other Elaboration Order Considerations
23210@noindent
23211This section has been entirely concerned with the issue of finding a valid
23212elaboration order, as defined by the Ada Reference Manual. In a case
23213where several elaboration orders are valid, the task is to find one
23214of the possible valid elaboration orders (and the static model in GNAT
23215will ensure that this is achieved).
23216
23217The purpose of the elaboration rules in the Ada Reference Manual is to
23218make sure that no entity is accessed before it has been elaborated. For
23219a subprogram, this means that the spec and body must have been elaborated
23220before the subprogram is called. For an object, this means that the object
23221must have been elaborated before its value is read or written. A violation
23222of either of these two requirements is an access before elaboration order,
23223and this section has been all about avoiding such errors.
23224
23225In the case where more than one order of elaboration is possible, in the
23226sense that access before elaboration errors are avoided, then any one of
23227the orders is ``correct'' in the sense that it meets the requirements of
23228the Ada Reference Manual, and no such error occurs.
23229
23230However, it may be the case for a given program, that there are
23231constraints on the order of elaboration that come not from consideration
23232of avoiding elaboration errors, but rather from extra-lingual logic
23233requirements. Consider this example:
23234
23235@smallexample @c ada
23236with Init_Constants;
23237package Constants is
23238   X : Integer := 0;
23239   Y : Integer := 0;
23240end Constants;
23241
23242package Init_Constants is
23243   procedure P; -- require a body
23244end Init_Constants;
23245
23246with Constants;
23247package body Init_Constants is
23248   procedure P is begin null; end;
23249begin
23250   Constants.X := 3;
23251   Constants.Y := 4;
23252end Init_Constants;
23253
23254with Constants;
23255package Calc is
23256   Z : Integer := Constants.X + Constants.Y;
23257end Calc;
23258
23259with Calc;
23260with Text_IO; use Text_IO;
23261procedure Main is
23262begin
23263   Put_Line (Calc.Z'Img);
23264end Main;
23265@end smallexample
23266
23267@noindent
23268In this example, there is more than one valid order of elaboration. For
23269example both the following are correct orders:
23270
23271@smallexample
23272Init_Constants spec
23273Constants spec
23274Calc spec
23275Init_Constants body
23276Main body
23277
23278  and
23279
23280Init_Constants spec
23281Init_Constants body
23282Constants spec
23283Calc spec
23284Main body
23285@end smallexample
23286
23287@noindent
23288There is no language rule to prefer one or the other, both are correct
23289from an order of elaboration point of view. But the programmatic effects
23290of the two orders are very different. In the first, the elaboration routine
23291of @code{Calc} initializes @code{Z} to zero, and then the main program
23292runs with this value of zero. But in the second order, the elaboration
23293routine of @code{Calc} runs after the body of Init_Constants has set
23294@code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23295runs.
23296
23297One could perhaps by applying pretty clever non-artificial intelligence
23298to the situation guess that it is more likely that the second order of
23299elaboration is the one desired, but there is no formal linguistic reason
23300to prefer one over the other. In fact in this particular case, GNAT will
23301prefer the second order, because of the rule that bodies are elaborated
23302as soon as possible, but it's just luck that this is what was wanted
23303(if indeed the second order was preferred).
23304
23305If the program cares about the order of elaboration routines in a case like
23306this, it is important to specify the order required. In this particular
23307case, that could have been achieved by adding to the spec of Calc:
23308
23309@smallexample @c ada
23310pragma Elaborate_All (Constants);
23311@end smallexample
23312
23313@noindent
23314which requires that the body (if any) and spec of @code{Constants},
23315as well as the body and spec of any unit @code{with}'ed by
23316@code{Constants} be elaborated before @code{Calc} is elaborated.
23317
23318Clearly no automatic method can always guess which alternative you require,
23319and if you are working with legacy code that had constraints of this kind
23320which were not properly specified by adding @code{Elaborate} or
23321@code{Elaborate_All} pragmas, then indeed it is possible that two different
23322compilers can choose different orders.
23323
23324The @code{gnatbind}
23325@option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23326out problems. This switch causes bodies to be elaborated as late as possible
23327instead of as early as possible. In the example above, it would have forced
23328the choice of the first elaboration order. If you get different results
23329when using this switch, and particularly if one set of results is right,
23330and one is wrong as far as you are concerned, it shows that you have some
23331missing @code{Elaborate} pragmas. For the example above, we have the
23332following output:
23333
23334@smallexample
23335gnatmake -f -q main
23336main
23337 7
23338gnatmake -f -q main -bargs -p
23339main
23340 0
23341@end smallexample
23342
23343@noindent
23344It is of course quite unlikely that both these results are correct, so
23345it is up to you in a case like this to investigate the source of the
23346difference, by looking at the two elaboration orders that are chosen,
23347and figuring out which is correct, and then adding the necessary
23348@code{Elaborate_All} pragmas to ensure the desired order.
23349
23350
23351@node Inline Assembler
23352@appendix Inline Assembler
23353
23354@noindent
23355If you need to write low-level software that interacts directly
23356with the hardware, Ada provides two ways to incorporate assembly
23357language code into your program.  First, you can import and invoke
23358external routines written in assembly language, an Ada feature fully
23359supported by GNAT.  However, for small sections of code it may be simpler
23360or more efficient to include assembly language statements directly
23361in your Ada source program, using the facilities of the implementation-defined
23362package @code{System.Machine_Code}, which incorporates the gcc
23363Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23364including the following:
23365
23366@itemize @bullet
23367@item No need to use non-Ada tools
23368@item Consistent interface over different targets
23369@item Automatic usage of the proper calling conventions
23370@item Access to Ada constants and variables
23371@item Definition of intrinsic routines
23372@item Possibility of inlining a subprogram comprising assembler code
23373@item Code optimizer can take Inline Assembler code into account
23374@end itemize
23375
23376This chapter presents a series of examples to show you how to use
23377the Inline Assembler.  Although it focuses on the Intel x86,
23378the general approach applies also to other processors.
23379It is assumed that you are familiar with Ada
23380and with assembly language programming.
23381
23382@menu
23383* Basic Assembler Syntax::
23384* A Simple Example of Inline Assembler::
23385* Output Variables in Inline Assembler::
23386* Input Variables in Inline Assembler::
23387* Inlining Inline Assembler Code::
23388* Other Asm Functionality::
23389* A Complete Example::
23390@end menu
23391
23392@c ---------------------------------------------------------------------------
23393@node Basic Assembler Syntax
23394@section Basic Assembler Syntax
23395
23396@noindent
23397The assembler used by GNAT and gcc is based not on the Intel assembly
23398language, but rather on a language that descends from the AT&T Unix
23399assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
23400The following table summarizes the main features of @emph{as} syntax
23401and points out the differences from the Intel conventions.
23402See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
23403pre-processor) documentation for further information.
23404
23405@table @asis
23406@item Register names
23407gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
23408@*
23409Intel: No extra punctuation; for example @code{eax}
23410
23411@item Immediate operand
23412gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
23413@*
23414Intel: No extra punctuation; for example @code{4}
23415
23416@item Address
23417gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
23418@*
23419Intel: No extra punctuation; for example @code{loc}
23420
23421@item Memory contents
23422gcc / @emph{as}: No extra punctuation; for example @code{loc}
23423@*
23424Intel: Square brackets; for example @code{[loc]}
23425
23426@item Register contents
23427gcc / @emph{as}: Parentheses; for example @code{(%eax)}
23428@*
23429Intel: Square brackets; for example @code{[eax]}
23430
23431@item Hexadecimal numbers
23432gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
23433@*
23434Intel: Trailing ``h''; for example @code{A0h}
23435
23436@item Operand size
23437gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
23438a 16-bit word
23439@*
23440Intel: Implicit, deduced by assembler; for example @code{mov}
23441
23442@item Instruction repetition
23443gcc / @emph{as}: Split into two lines; for example
23444@*
23445@code{rep}
23446@*
23447@code{stosl}
23448@*
23449Intel: Keep on one line; for example @code{rep stosl}
23450
23451@item Order of operands
23452gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
23453@*
23454Intel: Destination first; for example @code{mov eax, 4}
23455@end table
23456
23457@c ---------------------------------------------------------------------------
23458@node A Simple Example of Inline Assembler
23459@section A Simple Example of Inline Assembler
23460
23461@noindent
23462The following example will generate a single assembly language statement,
23463@code{nop}, which does nothing.  Despite its lack of run-time effect,
23464the example will be useful in illustrating the basics of
23465the Inline Assembler facility.
23466
23467@smallexample @c ada
23468@group
23469with System.Machine_Code; use System.Machine_Code;
23470procedure Nothing is
23471begin
23472   Asm ("nop");
23473end Nothing;
23474@end group
23475@end smallexample
23476
23477@code{Asm} is a procedure declared in package @code{System.Machine_Code};
23478here it takes one parameter, a @emph{template string} that must be a static
23479expression and that will form the generated instruction.
23480@code{Asm} may be regarded as a compile-time procedure that parses
23481the template string and additional parameters (none here),
23482from which it generates a sequence of assembly language instructions.
23483
23484The examples in this chapter will illustrate several of the forms
23485for invoking @code{Asm}; a complete specification of the syntax
23486is found in the @cite{GNAT Reference Manual}.
23487
23488Under the standard GNAT conventions, the @code{Nothing} procedure
23489should be in a file named @file{nothing.adb}.
23490You can build the executable in the usual way:
23491@smallexample
23492gnatmake nothing
23493@end smallexample
23494However, the interesting aspect of this example is not its run-time behavior
23495but rather the generated assembly code.
23496To see this output, invoke the compiler as follows:
23497@smallexample
23498   gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
23499@end smallexample
23500where the options are:
23501
23502@table @code
23503@item -c
23504compile only (no bind or link)
23505@item -S
23506generate assembler listing
23507@item -fomit-frame-pointer
23508do not set up separate stack frames
23509@item -gnatp
23510do not add runtime checks
23511@end table
23512
23513This gives a human-readable assembler version of the code. The resulting
23514file will have the same name as the Ada source file, but with a @code{.s}
23515extension. In our example, the file @file{nothing.s} has the following
23516contents:
23517
23518@smallexample
23519@group
23520.file "nothing.adb"
23521gcc2_compiled.:
23522___gnu_compiled_ada:
23523.text
23524   .align 4
23525.globl __ada_nothing
23526__ada_nothing:
23527#APP
23528   nop
23529#NO_APP
23530   jmp L1
23531   .align 2,0x90
23532L1:
23533   ret
23534@end group
23535@end smallexample
23536
23537The assembly code you included is clearly indicated by
23538the compiler, between the @code{#APP} and @code{#NO_APP}
23539delimiters. The character before the 'APP' and 'NOAPP'
23540can differ on different targets. For example, GNU/Linux uses '#APP' while
23541on NT you will see '/APP'.
23542
23543If you make a mistake in your assembler code (such as using the
23544wrong size modifier, or using a wrong operand for the instruction) GNAT
23545will report this error in a temporary file, which will be deleted when
23546the compilation is finished.  Generating an assembler file will help
23547in such cases, since you can assemble this file separately using the
23548@emph{as} assembler that comes with gcc.
23549
23550Assembling the file using the command
23551
23552@smallexample
23553as @file{nothing.s}
23554@end smallexample
23555@noindent
23556will give you error messages whose lines correspond to the assembler
23557input file, so you can easily find and correct any mistakes you made.
23558If there are no errors, @emph{as} will generate an object file
23559@file{nothing.out}.
23560
23561@c ---------------------------------------------------------------------------
23562@node Output Variables in Inline Assembler
23563@section Output Variables in Inline Assembler
23564
23565@noindent
23566The examples in this section, showing how to access the processor flags,
23567illustrate how to specify the destination operands for assembly language
23568statements.
23569
23570@smallexample @c ada
23571@group
23572with Interfaces; use Interfaces;
23573with Ada.Text_IO; use Ada.Text_IO;
23574with System.Machine_Code; use System.Machine_Code;
23575procedure Get_Flags is
23576   Flags : Unsigned_32;
23577   use ASCII;
23578begin
23579   Asm ("pushfl"          & LF & HT & -- push flags on stack
23580        "popl %%eax"      & LF & HT & -- load eax with flags
23581        "movl %%eax, %0",             -- store flags in variable
23582        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23583   Put_Line ("Flags register:" & Flags'Img);
23584end Get_Flags;
23585@end group
23586@end smallexample
23587
23588In order to have a nicely aligned assembly listing, we have separated
23589multiple assembler statements in the Asm template string with linefeed
23590(ASCII.LF) and horizontal tab (ASCII.HT) characters.
23591The resulting section of the assembly output file is:
23592
23593@smallexample
23594@group
23595#APP
23596   pushfl
23597   popl %eax
23598   movl %eax, -40(%ebp)
23599#NO_APP
23600@end group
23601@end smallexample
23602
23603It would have been legal to write the Asm invocation as:
23604
23605@smallexample
23606Asm ("pushfl popl %%eax movl %%eax, %0")
23607@end smallexample
23608
23609but in the generated assembler file, this would come out as:
23610
23611@smallexample
23612#APP
23613   pushfl popl %eax movl %eax, -40(%ebp)
23614#NO_APP
23615@end smallexample
23616
23617which is not so convenient for the human reader.
23618
23619We use Ada comments
23620at the end of each line to explain what the assembler instructions
23621actually do.  This is a useful convention.
23622
23623When writing Inline Assembler instructions, you need to precede each register
23624and variable name with a percent sign.  Since the assembler already requires
23625a percent sign at the beginning of a register name, you need two consecutive
23626percent signs for such names in the Asm template string, thus @code{%%eax}.
23627In the generated assembly code, one of the percent signs will be stripped off.
23628
23629Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
23630variables: operands you later define using @code{Input} or @code{Output}
23631parameters to @code{Asm}.
23632An output variable is illustrated in
23633the third statement in the Asm template string:
23634@smallexample
23635movl %%eax, %0
23636@end smallexample
23637The intent is to store the contents of the eax register in a variable that can
23638be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
23639necessarily work, since the compiler might optimize by using a register
23640to hold Flags, and the expansion of the @code{movl} instruction would not be
23641aware of this optimization.  The solution is not to store the result directly
23642but rather to advise the compiler to choose the correct operand form;
23643that is the purpose of the @code{%0} output variable.
23644
23645Information about the output variable is supplied in the @code{Outputs}
23646parameter to @code{Asm}:
23647@smallexample
23648Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23649@end smallexample
23650
23651The output is defined by the @code{Asm_Output} attribute of the target type;
23652the general format is
23653@smallexample
23654Type'Asm_Output (constraint_string, variable_name)
23655@end smallexample
23656
23657The constraint string directs the compiler how
23658to store/access the associated variable.  In the example
23659@smallexample
23660Unsigned_32'Asm_Output ("=m", Flags);
23661@end smallexample
23662the @code{"m"} (memory) constraint tells the compiler that the variable
23663@code{Flags} should be stored in a memory variable, thus preventing
23664the optimizer from keeping it in a register.  In contrast,
23665@smallexample
23666Unsigned_32'Asm_Output ("=r", Flags);
23667@end smallexample
23668uses the @code{"r"} (register) constraint, telling the compiler to
23669store the variable in a register.
23670
23671If the constraint is preceded by the equal character (@strong{=}), it tells
23672the compiler that the variable will be used to store data into it.
23673
23674In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
23675allowing the optimizer to choose whatever it deems best.
23676
23677There are a fairly large number of constraints, but the ones that are
23678most useful (for the Intel x86 processor) are the following:
23679
23680@table @code
23681@item =
23682output constraint
23683@item g
23684global (i.e. can be stored anywhere)
23685@item m
23686in memory
23687@item I
23688a constant
23689@item a
23690use eax
23691@item b
23692use ebx
23693@item c
23694use ecx
23695@item d
23696use edx
23697@item S
23698use esi
23699@item D
23700use edi
23701@item r
23702use one of eax, ebx, ecx or edx
23703@item q
23704use one of eax, ebx, ecx, edx, esi or edi
23705@end table
23706
23707The full set of constraints is described in the gcc and @emph{as}
23708documentation; note that it is possible to combine certain constraints
23709in one constraint string.
23710
23711You specify the association of an output variable with an assembler operand
23712through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
23713integer.  Thus in
23714@smallexample @c ada
23715@group
23716Asm ("pushfl"          & LF & HT & -- push flags on stack
23717     "popl %%eax"      & LF & HT & -- load eax with flags
23718     "movl %%eax, %0",             -- store flags in variable
23719     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23720@end group
23721@end smallexample
23722@noindent
23723@code{%0} will be replaced in the expanded code by the appropriate operand,
23724whatever
23725the compiler decided for the @code{Flags} variable.
23726
23727In general, you may have any number of output variables:
23728@itemize @bullet
23729@item
23730Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
23731@item
23732Specify the @code{Outputs} parameter as a parenthesized comma-separated list
23733of @code{Asm_Output} attributes
23734@end itemize
23735
23736For example:
23737@smallexample @c ada
23738@group
23739Asm ("movl %%eax, %0" & LF & HT &
23740     "movl %%ebx, %1" & LF & HT &
23741     "movl %%ecx, %2",
23742     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
23743                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
23744                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
23745@end group
23746@end smallexample
23747@noindent
23748where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
23749in the Ada program.
23750
23751As a variation on the @code{Get_Flags} example, we can use the constraints
23752string to direct the compiler to store the eax register into the @code{Flags}
23753variable, instead of including the store instruction explicitly in the
23754@code{Asm} template string:
23755
23756@smallexample @c ada
23757@group
23758with Interfaces; use Interfaces;
23759with Ada.Text_IO; use Ada.Text_IO;
23760with System.Machine_Code; use System.Machine_Code;
23761procedure Get_Flags_2 is
23762   Flags : Unsigned_32;
23763   use ASCII;
23764begin
23765   Asm ("pushfl"      & LF & HT & -- push flags on stack
23766        "popl %%eax",             -- save flags in eax
23767        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
23768   Put_Line ("Flags register:" & Flags'Img);
23769end Get_Flags_2;
23770@end group
23771@end smallexample
23772
23773@noindent
23774The @code{"a"} constraint tells the compiler that the @code{Flags}
23775variable will come from the eax register. Here is the resulting code:
23776
23777@smallexample
23778@group
23779#APP
23780   pushfl
23781   popl %eax
23782#NO_APP
23783   movl %eax,-40(%ebp)
23784@end group
23785@end smallexample
23786
23787@noindent
23788The compiler generated the store of eax into Flags after
23789expanding the assembler code.
23790
23791Actually, there was no need to pop the flags into the eax register;
23792more simply, we could just pop the flags directly into the program variable:
23793
23794@smallexample @c ada
23795@group
23796with Interfaces; use Interfaces;
23797with Ada.Text_IO; use Ada.Text_IO;
23798with System.Machine_Code; use System.Machine_Code;
23799procedure Get_Flags_3 is
23800   Flags : Unsigned_32;
23801   use ASCII;
23802begin
23803   Asm ("pushfl"  & LF & HT & -- push flags on stack
23804        "pop %0",             -- save flags in Flags
23805        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23806   Put_Line ("Flags register:" & Flags'Img);
23807end Get_Flags_3;
23808@end group
23809@end smallexample
23810
23811@c ---------------------------------------------------------------------------
23812@node Input Variables in Inline Assembler
23813@section Input Variables in Inline Assembler
23814
23815@noindent
23816The example in this section illustrates how to specify the source operands
23817for assembly language statements.
23818The program simply increments its input value by 1:
23819
23820@smallexample @c ada
23821@group
23822with Interfaces; use Interfaces;
23823with Ada.Text_IO; use Ada.Text_IO;
23824with System.Machine_Code; use System.Machine_Code;
23825procedure Increment is
23826
23827   function Incr (Value : Unsigned_32) return Unsigned_32 is
23828      Result : Unsigned_32;
23829   begin
23830      Asm ("incl %0",
23831           Inputs  => Unsigned_32'Asm_Input ("a", Value),
23832           Outputs => Unsigned_32'Asm_Output ("=a", Result));
23833      return Result;
23834   end Incr;
23835
23836   Value : Unsigned_32;
23837
23838begin
23839   Value := 5;
23840   Put_Line ("Value before is" & Value'Img);
23841   Value := Incr (Value);
23842   Put_Line ("Value after is" & Value'Img);
23843end Increment;
23844@end group
23845@end smallexample
23846
23847The @code{Outputs} parameter to @code{Asm} specifies
23848that the result will be in the eax register and that it is to be stored
23849in the @code{Result} variable.
23850
23851The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
23852but with an @code{Asm_Input} attribute.
23853The @code{"="} constraint, indicating an output value, is not present.
23854
23855You can have multiple input variables, in the same way that you can have more
23856than one output variable.
23857
23858The parameter count (%0, %1) etc, now starts at the first input
23859statement, and continues with the output statements.
23860When both parameters use the same variable, the
23861compiler will treat them as the same %n operand, which is the case here.
23862
23863Just as the @code{Outputs} parameter causes the register to be stored into the
23864target variable after execution of the assembler statements, so does the
23865@code{Inputs} parameter cause its variable to be loaded into the register
23866before execution of the assembler statements.
23867
23868Thus the effect of the @code{Asm} invocation is:
23869@enumerate
23870@item load the 32-bit value of @code{Value} into eax
23871@item execute the @code{incl %eax} instruction
23872@item store the contents of eax into the @code{Result} variable
23873@end enumerate
23874
23875The resulting assembler file (with @option{-O2} optimization) contains:
23876@smallexample
23877@group
23878_increment__incr.1:
23879   subl $4,%esp
23880   movl 8(%esp),%eax
23881#APP
23882   incl %eax
23883#NO_APP
23884   movl %eax,%edx
23885   movl %ecx,(%esp)
23886   addl $4,%esp
23887   ret
23888@end group
23889@end smallexample
23890
23891@c ---------------------------------------------------------------------------
23892@node Inlining Inline Assembler Code
23893@section Inlining Inline Assembler Code
23894
23895@noindent
23896For a short subprogram such as the @code{Incr} function in the previous
23897section, the overhead of the call and return (creating / deleting the stack
23898frame) can be significant, compared to the amount of code in the subprogram
23899body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
23900which directs the compiler to expand invocations of the subprogram at the
23901point(s) of call, instead of setting up a stack frame for out-of-line calls.
23902Here is the resulting program:
23903
23904@smallexample @c ada
23905@group
23906with Interfaces; use Interfaces;
23907with Ada.Text_IO; use Ada.Text_IO;
23908with System.Machine_Code; use System.Machine_Code;
23909procedure Increment_2 is
23910
23911   function Incr (Value : Unsigned_32) return Unsigned_32 is
23912      Result : Unsigned_32;
23913   begin
23914      Asm ("incl %0",
23915           Inputs  => Unsigned_32'Asm_Input ("a", Value),
23916           Outputs => Unsigned_32'Asm_Output ("=a", Result));
23917      return Result;
23918   end Incr;
23919   pragma Inline (Increment);
23920
23921   Value : Unsigned_32;
23922
23923begin
23924   Value := 5;
23925   Put_Line ("Value before is" & Value'Img);
23926   Value := Increment (Value);
23927   Put_Line ("Value after is" & Value'Img);
23928end Increment_2;
23929@end group
23930@end smallexample
23931
23932Compile the program with both optimization (@option{-O2}) and inlining
23933enabled (@option{-gnatpn} instead of @option{-gnatp}).
23934
23935The @code{Incr} function is still compiled as usual, but at the
23936point in @code{Increment} where our function used to be called:
23937
23938@smallexample
23939@group
23940pushl %edi
23941call _increment__incr.1
23942@end group
23943@end smallexample
23944
23945@noindent
23946the code for the function body directly appears:
23947
23948@smallexample
23949@group
23950movl %esi,%eax
23951#APP
23952   incl %eax
23953#NO_APP
23954   movl %eax,%edx
23955@end group
23956@end smallexample
23957
23958@noindent
23959thus saving the overhead of stack frame setup and an out-of-line call.
23960
23961@c ---------------------------------------------------------------------------
23962@node Other Asm Functionality
23963@section Other @code{Asm} Functionality
23964
23965@noindent
23966This section describes two important parameters to the @code{Asm}
23967procedure: @code{Clobber}, which identifies register usage;
23968and @code{Volatile}, which inhibits unwanted optimizations.
23969
23970@menu
23971* The Clobber Parameter::
23972* The Volatile Parameter::
23973@end menu
23974
23975@c ---------------------------------------------------------------------------
23976@node The Clobber Parameter
23977@subsection The @code{Clobber} Parameter
23978
23979@noindent
23980One of the dangers of intermixing assembly language and a compiled language
23981such as Ada is that the compiler needs to be aware of which registers are
23982being used by the assembly code.  In some cases, such as the earlier examples,
23983the constraint string is sufficient to indicate register usage (e.g.,
23984@code{"a"} for
23985the eax register).  But more generally, the compiler needs an explicit
23986identification of the registers that are used by the Inline Assembly
23987statements.
23988
23989Using a register that the compiler doesn't know about
23990could be a side effect of an instruction (like @code{mull}
23991storing its result in both eax and edx).
23992It can also arise from explicit register usage in your
23993assembly code; for example:
23994@smallexample
23995@group
23996Asm ("movl %0, %%ebx" & LF & HT &
23997     "movl %%ebx, %1",
23998     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
23999     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24000@end group
24001@end smallexample
24002@noindent
24003where the compiler (since it does not analyze the @code{Asm} template string)
24004does not know you are using the ebx register.
24005
24006In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24007to identify the registers that will be used by your assembly code:
24008
24009@smallexample
24010@group
24011Asm ("movl %0, %%ebx" & LF & HT &
24012     "movl %%ebx, %1",
24013     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24014     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24015     Clobber => "ebx");
24016@end group
24017@end smallexample
24018
24019The Clobber parameter is a static string expression specifying the
24020register(s) you are using.  Note that register names are @emph{not} prefixed
24021by a percent sign. Also, if more than one register is used then their names
24022are separated by commas; e.g., @code{"eax, ebx"}
24023
24024The @code{Clobber} parameter has several additional uses:
24025@enumerate
24026@item Use ``register'' name @code{cc} to indicate that flags might have changed
24027@item Use ``register'' name @code{memory} if you changed a memory location
24028@end enumerate
24029
24030@c ---------------------------------------------------------------------------
24031@node The Volatile Parameter
24032@subsection The @code{Volatile} Parameter
24033@cindex Volatile parameter
24034
24035@noindent
24036Compiler optimizations in the presence of Inline Assembler may sometimes have
24037unwanted effects.  For example, when an @code{Asm} invocation with an input
24038variable is inside a loop, the compiler might move the loading of the input
24039variable outside the loop, regarding it as a one-time initialization.
24040
24041If this effect is not desired, you can disable such optimizations by setting
24042the @code{Volatile} parameter to @code{True}; for example:
24043
24044@smallexample @c ada
24045@group
24046Asm ("movl %0, %%ebx" & LF & HT &
24047     "movl %%ebx, %1",
24048     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24049     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24050     Clobber  => "ebx",
24051     Volatile => True);
24052@end group
24053@end smallexample
24054
24055By default, @code{Volatile} is set to @code{False} unless there is no
24056@code{Outputs} parameter.
24057
24058Although setting @code{Volatile} to @code{True} prevents unwanted
24059optimizations, it will also disable other optimizations that might be
24060important for efficiency. In general, you should set @code{Volatile}
24061to @code{True} only if the compiler's optimizations have created
24062problems.
24063
24064@c ---------------------------------------------------------------------------
24065@node A Complete Example
24066@section A Complete Example
24067
24068@noindent
24069This section contains a complete program illustrating a realistic usage
24070of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24071@code{Check_CPU} and a package @code{Intel_CPU}.
24072The package declares a collection of functions that detect the properties
24073of the 32-bit x86 processor that is running the program.
24074The main procedure invokes these functions and displays the information.
24075
24076The Intel_CPU package could be enhanced by adding functions to
24077detect the type of x386 co-processor, the processor caching options and
24078special operations such as the SIMD extensions.
24079
24080Although the Intel_CPU package has been written for 32-bit Intel
24081compatible CPUs, it is OS neutral. It has been tested on DOS,
24082Windows/NT and GNU/Linux.
24083
24084@menu
24085* Check_CPU Procedure::
24086* Intel_CPU Package Specification::
24087* Intel_CPU Package Body::
24088@end menu
24089
24090@c ---------------------------------------------------------------------------
24091@node Check_CPU Procedure
24092@subsection @code{Check_CPU} Procedure
24093@cindex Check_CPU procedure
24094
24095@smallexample @c adanocomment
24096---------------------------------------------------------------------
24097--                                                                 --
24098--  Uses the Intel_CPU package to identify the CPU the program is  --
24099--  running on, and some of the features it supports.              --
24100--                                                                 --
24101---------------------------------------------------------------------
24102
24103with Intel_CPU;                     --  Intel CPU detection functions
24104with Ada.Text_IO;                   --  Standard text I/O
24105with Ada.Command_Line;              --  To set the exit status
24106
24107procedure Check_CPU is
24108
24109   Type_Found : Boolean := False;
24110   --  Flag to indicate that processor was identified
24111
24112   Features   : Intel_CPU.Processor_Features;
24113   --  The processor features
24114
24115   Signature  : Intel_CPU.Processor_Signature;
24116   --  The processor type signature
24117
24118begin
24119
24120   -----------------------------------
24121   --  Display the program banner.  --
24122   -----------------------------------
24123
24124   Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24125                         ": check Intel CPU version and features, v1.0");
24126   Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24127   Ada.Text_IO.New_Line;
24128
24129   -----------------------------------------------------------------------
24130   --  We can safely start with the assumption that we are on at least  --
24131   --  a x386 processor. If the CPUID instruction is present, then we   --
24132   --  have a later processor type.                                     --
24133   -----------------------------------------------------------------------
24134
24135   if Intel_CPU.Has_CPUID = False then
24136
24137      --  No CPUID instruction, so we assume this is indeed a x386
24138      --  processor. We can still check if it has a FP co-processor.
24139      if Intel_CPU.Has_FPU then
24140         Ada.Text_IO.Put_Line
24141           ("x386-type processor with a FP co-processor");
24142      else
24143         Ada.Text_IO.Put_Line
24144           ("x386-type processor without a FP co-processor");
24145      end if;  --  check for FPU
24146
24147      --  Program done
24148      Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24149      return;
24150
24151   end if;  --  check for CPUID
24152
24153   -----------------------------------------------------------------------
24154   --  If CPUID is supported, check if this is a true Intel processor,  --
24155   --  if it is not, display a warning.                                 --
24156   -----------------------------------------------------------------------
24157
24158   if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24159      Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24160      Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24161   end if;  --  check if Intel
24162
24163   ----------------------------------------------------------------------
24164   --  With the CPUID instruction present, we can assume at least a    --
24165   --  x486 processor. If the CPUID support level is < 1 then we have  --
24166   --  to leave it at that.                                            --
24167   ----------------------------------------------------------------------
24168
24169   if Intel_CPU.CPUID_Level < 1 then
24170
24171      --  Ok, this is a x486 processor. we still can get the Vendor ID
24172      Ada.Text_IO.Put_Line ("x486-type processor");
24173      Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24174
24175      --  We can also check if there is a FPU present
24176      if Intel_CPU.Has_FPU then
24177         Ada.Text_IO.Put_Line ("Floating-Point support");
24178      else
24179         Ada.Text_IO.Put_Line ("No Floating-Point support");
24180      end if;  --  check for FPU
24181
24182      --  Program done
24183      Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24184      return;
24185
24186   end if;  --  check CPUID level
24187
24188   ---------------------------------------------------------------------
24189   --  With a CPUID level of 1 we can use the processor signature to  --
24190   --  determine it's exact type.                                     --
24191   ---------------------------------------------------------------------
24192
24193   Signature := Intel_CPU.Signature;
24194
24195   ----------------------------------------------------------------------
24196   --  Ok, now we go into a lot of messy comparisons to get the        --
24197   --  processor type. For clarity, no attememt to try to optimize the --
24198   --  comparisons has been made. Note that since Intel_CPU does not   --
24199   --  support getting cache info, we cannot distinguish between P5    --
24200   --  and Celeron types yet.                                          --
24201   ----------------------------------------------------------------------
24202
24203   --  x486SL
24204   if Signature.Processor_Type = 2#00#   and
24205     Signature.Family          = 2#0100# and
24206     Signature.Model           = 2#0100# then
24207      Type_Found := True;
24208      Ada.Text_IO.Put_Line ("x486SL processor");
24209   end if;
24210
24211   --  x486DX2 Write-Back
24212   if Signature.Processor_Type = 2#00#   and
24213     Signature.Family          = 2#0100# and
24214     Signature.Model           = 2#0111# then
24215      Type_Found := True;
24216      Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24217   end if;
24218
24219   --  x486DX4
24220   if Signature.Processor_Type = 2#00#   and
24221     Signature.Family          = 2#0100# and
24222     Signature.Model           = 2#1000# then
24223      Type_Found := True;
24224      Ada.Text_IO.Put_Line ("x486DX4 processor");
24225   end if;
24226
24227   --  x486DX4 Overdrive
24228   if Signature.Processor_Type = 2#01#   and
24229     Signature.Family          = 2#0100# and
24230     Signature.Model           = 2#1000# then
24231      Type_Found := True;
24232      Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24233   end if;
24234
24235   --  Pentium (60, 66)
24236   if Signature.Processor_Type = 2#00#   and
24237     Signature.Family          = 2#0101# and
24238     Signature.Model           = 2#0001# then
24239      Type_Found := True;
24240      Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24241   end if;
24242
24243   --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24244   if Signature.Processor_Type = 2#00#   and
24245     Signature.Family          = 2#0101# and
24246     Signature.Model           = 2#0010# then
24247      Type_Found := True;
24248      Ada.Text_IO.Put_Line
24249        ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24250   end if;
24251
24252   --  Pentium OverDrive (60, 66)
24253   if Signature.Processor_Type = 2#01#   and
24254     Signature.Family          = 2#0101# and
24255     Signature.Model           = 2#0001# then
24256      Type_Found := True;
24257      Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24258   end if;
24259
24260   --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24261   if Signature.Processor_Type = 2#01#   and
24262     Signature.Family          = 2#0101# and
24263     Signature.Model           = 2#0010# then
24264      Type_Found := True;
24265      Ada.Text_IO.Put_Line
24266        ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24267   end if;
24268
24269   --  Pentium OverDrive processor for x486 processor-based systems
24270   if Signature.Processor_Type = 2#01#   and
24271     Signature.Family          = 2#0101# and
24272     Signature.Model           = 2#0011# then
24273      Type_Found := True;
24274      Ada.Text_IO.Put_Line
24275        ("Pentium OverDrive processor for x486 processor-based systems");
24276   end if;
24277
24278   --  Pentium processor with MMX technology (166, 200)
24279   if Signature.Processor_Type = 2#00#   and
24280     Signature.Family          = 2#0101# and
24281     Signature.Model           = 2#0100# then
24282      Type_Found := True;
24283      Ada.Text_IO.Put_Line
24284        ("Pentium processor with MMX technology (166, 200)");
24285   end if;
24286
24287   --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24288   if Signature.Processor_Type = 2#01#   and
24289     Signature.Family          = 2#0101# and
24290     Signature.Model           = 2#0100# then
24291      Type_Found := True;
24292      Ada.Text_IO.Put_Line
24293        ("Pentium OverDrive processor with MMX " &
24294         "technology for Pentium processor (75, 90, 100, 120, 133)");
24295   end if;
24296
24297   --  Pentium Pro processor
24298   if Signature.Processor_Type = 2#00#   and
24299     Signature.Family          = 2#0110# and
24300     Signature.Model           = 2#0001# then
24301      Type_Found := True;
24302      Ada.Text_IO.Put_Line ("Pentium Pro processor");
24303   end if;
24304
24305   --  Pentium II processor, model 3
24306   if Signature.Processor_Type = 2#00#   and
24307     Signature.Family          = 2#0110# and
24308     Signature.Model           = 2#0011# then
24309      Type_Found := True;
24310      Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24311   end if;
24312
24313   --  Pentium II processor, model 5 or Celeron processor
24314   if Signature.Processor_Type = 2#00#   and
24315     Signature.Family          = 2#0110# and
24316     Signature.Model           = 2#0101# then
24317      Type_Found := True;
24318      Ada.Text_IO.Put_Line
24319        ("Pentium II processor, model 5 or Celeron processor");
24320   end if;
24321
24322   --  Pentium Pro OverDrive processor
24323   if Signature.Processor_Type = 2#01#   and
24324     Signature.Family          = 2#0110# and
24325     Signature.Model           = 2#0011# then
24326      Type_Found := True;
24327      Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24328   end if;
24329
24330   --  If no type recognized, we have an unknown. Display what
24331   --  we _do_ know
24332   if Type_Found = False then
24333      Ada.Text_IO.Put_Line ("Unknown processor");
24334   end if;
24335
24336   -----------------------------------------
24337   --  Display processor stepping level.  --
24338   -----------------------------------------
24339
24340   Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24341
24342   ---------------------------------
24343   --  Display vendor ID string.  --
24344   ---------------------------------
24345
24346   Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24347
24348   ------------------------------------
24349   --  Get the processors features.  --
24350   ------------------------------------
24351
24352   Features := Intel_CPU.Features;
24353
24354   -----------------------------
24355   --  Check for a FPU unit.  --
24356   -----------------------------
24357
24358   if Features.FPU = True then
24359      Ada.Text_IO.Put_Line ("Floating-Point unit available");
24360   else
24361      Ada.Text_IO.Put_Line ("no Floating-Point unit");
24362   end if;  --  check for FPU
24363
24364   --------------------------------
24365   --  List processor features.  --
24366   --------------------------------
24367
24368   Ada.Text_IO.Put_Line ("Supported features: ");
24369
24370   --  Virtual Mode Extension
24371   if Features.VME = True then
24372      Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24373   end if;
24374
24375   --  Debugging Extension
24376   if Features.DE = True then
24377      Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24378   end if;
24379
24380   --  Page Size Extension
24381   if Features.PSE = True then
24382      Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24383   end if;
24384
24385   --  Time Stamp Counter
24386   if Features.TSC = True then
24387      Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
24388   end if;
24389
24390   --  Model Specific Registers
24391   if Features.MSR = True then
24392      Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
24393   end if;
24394
24395   --  Physical Address Extension
24396   if Features.PAE = True then
24397      Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
24398   end if;
24399
24400   --  Machine Check Extension
24401   if Features.MCE = True then
24402      Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
24403   end if;
24404
24405   --  CMPXCHG8 instruction supported
24406   if Features.CX8 = True then
24407      Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
24408   end if;
24409
24410   --  on-chip APIC hardware support
24411   if Features.APIC = True then
24412      Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
24413   end if;
24414
24415   --  Fast System Call
24416   if Features.SEP = True then
24417      Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
24418   end if;
24419
24420   --  Memory Type Range Registers
24421   if Features.MTRR = True then
24422      Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
24423   end if;
24424
24425   --  Page Global Enable
24426   if Features.PGE = True then
24427      Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
24428   end if;
24429
24430   --  Machine Check Architecture
24431   if Features.MCA = True then
24432      Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
24433   end if;
24434
24435   --  Conditional Move Instruction Supported
24436   if Features.CMOV = True then
24437      Ada.Text_IO.Put_Line
24438        ("    CMOV   - Conditional Move Instruction Supported");
24439   end if;
24440
24441   --  Page Attribute Table
24442   if Features.PAT = True then
24443      Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
24444   end if;
24445
24446   --  36-bit Page Size Extension
24447   if Features.PSE_36 = True then
24448      Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
24449   end if;
24450
24451   --  MMX technology supported
24452   if Features.MMX = True then
24453      Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
24454   end if;
24455
24456   --  Fast FP Save and Restore
24457   if Features.FXSR = True then
24458      Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
24459   end if;
24460
24461   ---------------------
24462   --  Program done.  --
24463   ---------------------
24464
24465   Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24466
24467exception
24468
24469   when others =>
24470      Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
24471      raise;
24472
24473end Check_CPU;
24474@end smallexample
24475
24476@c ---------------------------------------------------------------------------
24477@node Intel_CPU Package Specification
24478@subsection @code{Intel_CPU} Package Specification
24479@cindex Intel_CPU package specification
24480
24481@smallexample @c adanocomment
24482-------------------------------------------------------------------------
24483--                                                                     --
24484--  file: intel_cpu.ads                                                --
24485--                                                                     --
24486--           *********************************************             --
24487--           * WARNING: for 32-bit Intel processors only *             --
24488--           *********************************************             --
24489--                                                                     --
24490--  This package contains a number of subprograms that are useful in   --
24491--  determining the Intel x86 CPU (and the features it supports) on    --
24492--  which the program is running.                                      --
24493--                                                                     --
24494--  The package is based upon the information given in the Intel       --
24495--  Application Note AP-485: "Intel Processor Identification and the   --
24496--  CPUID Instruction" as of April 1998. This application note can be  --
24497--  found on www.intel.com.                                            --
24498--                                                                     --
24499--  It currently deals with 32-bit processors only, will not detect    --
24500--  features added after april 1998, and does not guarantee proper     --
24501--  results on Intel-compatible processors.                            --
24502--                                                                     --
24503--  Cache info and x386 fpu type detection are not supported.          --
24504--                                                                     --
24505--  This package does not use any privileged instructions, so should   --
24506--  work on any OS running on a 32-bit Intel processor.                --
24507--                                                                     --
24508-------------------------------------------------------------------------
24509
24510with Interfaces;             use Interfaces;
24511--  for using unsigned types
24512
24513with System.Machine_Code;    use System.Machine_Code;
24514--  for using inline assembler code
24515
24516with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
24517--  for inserting control characters
24518
24519package Intel_CPU is
24520
24521   ----------------------
24522   --  Processor bits  --
24523   ----------------------
24524
24525   subtype Num_Bits is Natural range 0 .. 31;
24526   --  the number of processor bits (32)
24527
24528   --------------------------
24529   --  Processor register  --
24530   --------------------------
24531
24532   --  define a processor register type for easy access to
24533   --  the individual bits
24534
24535   type Processor_Register is array (Num_Bits) of Boolean;
24536   pragma Pack (Processor_Register);
24537   for Processor_Register'Size use 32;
24538
24539   -------------------------
24540   --  Unsigned register  --
24541   -------------------------
24542
24543   --  define a processor register type for easy access to
24544   --  the individual bytes
24545
24546   type Unsigned_Register is
24547      record
24548         L1 : Unsigned_8;
24549         H1 : Unsigned_8;
24550         L2 : Unsigned_8;
24551         H2 : Unsigned_8;
24552      end record;
24553
24554   for Unsigned_Register use
24555      record
24556         L1 at 0 range  0 ..  7;
24557         H1 at 0 range  8 .. 15;
24558         L2 at 0 range 16 .. 23;
24559         H2 at 0 range 24 .. 31;
24560      end record;
24561
24562   for Unsigned_Register'Size use 32;
24563
24564   ---------------------------------
24565   --  Intel processor vendor ID  --
24566   ---------------------------------
24567
24568   Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
24569   --  indicates an Intel manufactured processor
24570
24571   ------------------------------------
24572   --  Processor signature register  --
24573   ------------------------------------
24574
24575   --  a register type to hold the processor signature
24576
24577   type Processor_Signature is
24578      record
24579         Stepping       : Natural range 0 .. 15;
24580         Model          : Natural range 0 .. 15;
24581         Family         : Natural range 0 .. 15;
24582         Processor_Type : Natural range 0 .. 3;
24583         Reserved       : Natural range 0 .. 262143;
24584      end record;
24585
24586   for Processor_Signature use
24587      record
24588         Stepping       at 0 range  0 ..  3;
24589         Model          at 0 range  4 ..  7;
24590         Family         at 0 range  8 .. 11;
24591         Processor_Type at 0 range 12 .. 13;
24592         Reserved       at 0 range 14 .. 31;
24593      end record;
24594
24595   for Processor_Signature'Size use 32;
24596
24597   -----------------------------------
24598   --  Processor features register  --
24599   -----------------------------------
24600
24601   --  a processor register to hold the processor feature flags
24602
24603   type Processor_Features is
24604      record
24605         FPU    : Boolean;                --  floating point unit on chip
24606         VME    : Boolean;                --  virtual mode extension
24607         DE     : Boolean;                --  debugging extension
24608         PSE    : Boolean;                --  page size extension
24609         TSC    : Boolean;                --  time stamp counter
24610         MSR    : Boolean;                --  model specific registers
24611         PAE    : Boolean;                --  physical address extension
24612         MCE    : Boolean;                --  machine check extension
24613         CX8    : Boolean;                --  cmpxchg8 instruction
24614         APIC   : Boolean;                --  on-chip apic hardware
24615         Res_1  : Boolean;                --  reserved for extensions
24616         SEP    : Boolean;                --  fast system call
24617         MTRR   : Boolean;                --  memory type range registers
24618         PGE    : Boolean;                --  page global enable
24619         MCA    : Boolean;                --  machine check architecture
24620         CMOV   : Boolean;                --  conditional move supported
24621         PAT    : Boolean;                --  page attribute table
24622         PSE_36 : Boolean;                --  36-bit page size extension
24623         Res_2  : Natural range 0 .. 31;  --  reserved for extensions
24624         MMX    : Boolean;                --  MMX technology supported
24625         FXSR   : Boolean;                --  fast FP save and restore
24626         Res_3  : Natural range 0 .. 127; --  reserved for extensions
24627      end record;
24628
24629   for Processor_Features use
24630      record
24631         FPU    at 0 range  0 ..  0;
24632         VME    at 0 range  1 ..  1;
24633         DE     at 0 range  2 ..  2;
24634         PSE    at 0 range  3 ..  3;
24635         TSC    at 0 range  4 ..  4;
24636         MSR    at 0 range  5 ..  5;
24637         PAE    at 0 range  6 ..  6;
24638         MCE    at 0 range  7 ..  7;
24639         CX8    at 0 range  8 ..  8;
24640         APIC   at 0 range  9 ..  9;
24641         Res_1  at 0 range 10 .. 10;
24642         SEP    at 0 range 11 .. 11;
24643         MTRR   at 0 range 12 .. 12;
24644         PGE    at 0 range 13 .. 13;
24645         MCA    at 0 range 14 .. 14;
24646         CMOV   at 0 range 15 .. 15;
24647         PAT    at 0 range 16 .. 16;
24648         PSE_36 at 0 range 17 .. 17;
24649         Res_2  at 0 range 18 .. 22;
24650         MMX    at 0 range 23 .. 23;
24651         FXSR   at 0 range 24 .. 24;
24652         Res_3  at 0 range 25 .. 31;
24653      end record;
24654
24655   for Processor_Features'Size use 32;
24656
24657   -------------------
24658   --  Subprograms  --
24659   -------------------
24660
24661   function Has_FPU return Boolean;
24662   --  return True if a FPU is found
24663   --  use only if CPUID is not supported
24664
24665   function Has_CPUID return Boolean;
24666   --  return True if the processor supports the CPUID instruction
24667
24668   function CPUID_Level return Natural;
24669   --  return the CPUID support level (0, 1 or 2)
24670   --  can only be called if the CPUID instruction is supported
24671
24672   function Vendor_ID return String;
24673   --  return the processor vendor identification string
24674   --  can only be called if the CPUID instruction is supported
24675
24676   function Signature return Processor_Signature;
24677   --  return the processor signature
24678   --  can only be called if the CPUID instruction is supported
24679
24680   function Features return Processor_Features;
24681   --  return the processors features
24682   --  can only be called if the CPUID instruction is supported
24683
24684private
24685
24686   ------------------------
24687   --  EFLAGS bit names  --
24688   ------------------------
24689
24690   ID_Flag : constant Num_Bits := 21;
24691   --  ID flag bit
24692
24693end Intel_CPU;
24694@end smallexample
24695
24696@c ---------------------------------------------------------------------------
24697@node Intel_CPU Package Body
24698@subsection @code{Intel_CPU} Package Body
24699@cindex Intel_CPU package body
24700
24701@smallexample @c adanocomment
24702package body Intel_CPU is
24703
24704   ---------------------------
24705   --  Detect FPU presence  --
24706   ---------------------------
24707
24708   --  There is a FPU present if we can set values to the FPU Status
24709   --  and Control Words.
24710
24711   function Has_FPU return Boolean is
24712
24713      Register : Unsigned_16;
24714      --  processor register to store a word
24715
24716   begin
24717
24718      --  check if we can change the status word
24719      Asm (
24720
24721           --  the assembler code
24722           "finit"              & LF & HT &    --  reset status word
24723           "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
24724           "fnstsw %0"          & LF & HT &    --  save status word
24725           "movw %%ax, %0",                    --  store status word
24726
24727           --  output stored in Register
24728           --  register must be a memory location
24729           Outputs => Unsigned_16'Asm_output ("=m", Register),
24730
24731           --  tell compiler that we used eax
24732           Clobber => "eax");
24733
24734      --  if the status word is zero, there is no FPU
24735      if Register = 0 then
24736         return False;   --  no status word
24737      end if;  --  check status word value
24738
24739      --  check if we can get the control word
24740      Asm (
24741
24742           --  the assembler code
24743           "fnstcw %0",   --  save the control word
24744
24745           --  output into Register
24746           --  register must be a memory location
24747           Outputs => Unsigned_16'Asm_output ("=m", Register));
24748
24749      --  check the relevant bits
24750      if (Register and 16#103F#) /= 16#003F# then
24751         return False;   --  no control word
24752      end if;  --  check control word value
24753
24754      --  FPU found
24755      return True;
24756
24757   end Has_FPU;
24758
24759   --------------------------------
24760   --  Detect CPUID instruction  --
24761   --------------------------------
24762
24763   --  The processor supports the CPUID instruction if it is possible
24764   --  to change the value of ID flag bit in the EFLAGS register.
24765
24766   function Has_CPUID return Boolean is
24767
24768      Original_Flags, Modified_Flags : Processor_Register;
24769      --  EFLAG contents before and after changing the ID flag
24770
24771   begin
24772
24773      --  try flipping the ID flag in the EFLAGS register
24774      Asm (
24775
24776           --  the assembler code
24777           "pushfl"               & LF & HT &     --  push EFLAGS on stack
24778           "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
24779           "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
24780           "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
24781           "push %%eax"           & LF & HT &     --  push EFLAGS on stack
24782           "popfl"                & LF & HT &     --  load EFLAGS register
24783           "pushfl"               & LF & HT &     --  push EFLAGS on stack
24784           "pop %1",                              --  save EFLAGS content
24785
24786           --  output values, may be anything
24787           --  Original_Flags is %0
24788           --  Modified_Flags is %1
24789           Outputs =>
24790              (Processor_Register'Asm_output ("=g", Original_Flags),
24791               Processor_Register'Asm_output ("=g", Modified_Flags)),
24792
24793           --  tell compiler eax is destroyed
24794           Clobber => "eax");
24795
24796      --  check if CPUID is supported
24797      if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
24798         return True;   --  ID flag was modified
24799      else
24800         return False;  --  ID flag unchanged
24801      end if;  --  check for CPUID
24802
24803   end Has_CPUID;
24804
24805   -------------------------------
24806   --  Get CPUID support level  --
24807   -------------------------------
24808
24809   function CPUID_Level return Natural is
24810
24811      Level : Unsigned_32;
24812      --  returned support level
24813
24814   begin
24815
24816      --  execute CPUID, storing the results in the Level register
24817      Asm (
24818
24819           --  the assembler code
24820           "cpuid",    --  execute CPUID
24821
24822           --  zero is stored in eax
24823           --  returning the support level in eax
24824           Inputs => Unsigned_32'Asm_input ("a", 0),
24825
24826           --  eax is stored in Level
24827           Outputs => Unsigned_32'Asm_output ("=a", Level),
24828
24829           --  tell compiler ebx, ecx and edx registers are destroyed
24830           Clobber => "ebx, ecx, edx");
24831
24832      --  return the support level
24833      return Natural (Level);
24834
24835   end CPUID_Level;
24836
24837   --------------------------------
24838   --  Get CPU Vendor ID String  --
24839   --------------------------------
24840
24841   --  The vendor ID string is returned in the ebx, ecx and edx register
24842   --  after executing the CPUID instruction with eax set to zero.
24843   --  In case of a true Intel processor the string returned is
24844   --  "GenuineIntel"
24845
24846   function Vendor_ID return String is
24847
24848      Ebx, Ecx, Edx : Unsigned_Register;
24849      --  registers containing the vendor ID string
24850
24851      Vendor_ID : String (1 .. 12);
24852      -- the vendor ID string
24853
24854   begin
24855
24856      --  execute CPUID, storing the results in the processor registers
24857      Asm (
24858
24859           --  the assembler code
24860           "cpuid",    --  execute CPUID
24861
24862           --  zero stored in eax
24863           --  vendor ID string returned in ebx, ecx and edx
24864           Inputs => Unsigned_32'Asm_input ("a", 0),
24865
24866           --  ebx is stored in Ebx
24867           --  ecx is stored in Ecx
24868           --  edx is stored in Edx
24869           Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
24870                       Unsigned_Register'Asm_output ("=c", Ecx),
24871                       Unsigned_Register'Asm_output ("=d", Edx)));
24872
24873      --  now build the vendor ID string
24874      Vendor_ID( 1) := Character'Val (Ebx.L1);
24875      Vendor_ID( 2) := Character'Val (Ebx.H1);
24876      Vendor_ID( 3) := Character'Val (Ebx.L2);
24877      Vendor_ID( 4) := Character'Val (Ebx.H2);
24878      Vendor_ID( 5) := Character'Val (Edx.L1);
24879      Vendor_ID( 6) := Character'Val (Edx.H1);
24880      Vendor_ID( 7) := Character'Val (Edx.L2);
24881      Vendor_ID( 8) := Character'Val (Edx.H2);
24882      Vendor_ID( 9) := Character'Val (Ecx.L1);
24883      Vendor_ID(10) := Character'Val (Ecx.H1);
24884      Vendor_ID(11) := Character'Val (Ecx.L2);
24885      Vendor_ID(12) := Character'Val (Ecx.H2);
24886
24887      --  return string
24888      return Vendor_ID;
24889
24890   end Vendor_ID;
24891
24892   -------------------------------
24893   --  Get processor signature  --
24894   -------------------------------
24895
24896   function Signature return Processor_Signature is
24897
24898      Result : Processor_Signature;
24899      --  processor signature returned
24900
24901   begin
24902
24903      --  execute CPUID, storing the results in the Result variable
24904      Asm (
24905
24906           --  the assembler code
24907           "cpuid",    --  execute CPUID
24908
24909           --  one is stored in eax
24910           --  processor signature returned in eax
24911           Inputs => Unsigned_32'Asm_input ("a", 1),
24912
24913           --  eax is stored in Result
24914           Outputs => Processor_Signature'Asm_output ("=a", Result),
24915
24916           --  tell compiler that ebx, ecx and edx are also destroyed
24917           Clobber => "ebx, ecx, edx");
24918
24919      --  return processor signature
24920      return Result;
24921
24922   end Signature;
24923
24924   ------------------------------
24925   --  Get processor features  --
24926   ------------------------------
24927
24928   function Features return Processor_Features is
24929
24930      Result : Processor_Features;
24931      --  processor features returned
24932
24933   begin
24934
24935      --  execute CPUID, storing the results in the Result variable
24936      Asm (
24937
24938           --  the assembler code
24939           "cpuid",    --  execute CPUID
24940
24941           --  one stored in eax
24942           --  processor features returned in edx
24943           Inputs => Unsigned_32'Asm_input ("a", 1),
24944
24945           --  edx is stored in Result
24946           Outputs => Processor_Features'Asm_output ("=d", Result),
24947
24948           --  tell compiler that ebx and ecx are also destroyed
24949           Clobber => "ebx, ecx");
24950
24951      --  return processor signature
24952      return Result;
24953
24954   end Features;
24955
24956end Intel_CPU;
24957@end smallexample
24958@c END OF INLINE ASSEMBLER CHAPTER
24959@c ===============================
24960
24961
24962
24963@c ***********************************
24964@c * Compatibility and Porting Guide *
24965@c ***********************************
24966@node Compatibility and Porting Guide
24967@appendix Compatibility and Porting Guide
24968
24969@noindent
24970This chapter describes the compatibility issues that may arise between
24971GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
24972can expedite porting
24973applications developed in other Ada environments.
24974
24975@menu
24976* Compatibility with Ada 83::
24977* Implementation-dependent characteristics::
24978* Compatibility with DEC Ada 83::
24979* Compatibility with Other Ada 95 Systems::
24980* Representation Clauses::
24981@end menu
24982
24983@node Compatibility with Ada 83
24984@section Compatibility with Ada 83
24985@cindex Compatibility (between Ada 83 and Ada 95)
24986
24987@noindent
24988Ada 95 is designed to be highly upwards compatible with Ada 83.  In
24989particular, the design intention is that the difficulties associated
24990with moving from Ada 83 to Ada 95 should be no greater than those
24991that occur when moving from one Ada 83 system to another.
24992
24993However, there are a number of points at which there are minor
24994incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
24995full details of these issues,
24996and should be consulted for a complete treatment.
24997In practice the
24998following subsections treat the most likely issues to be encountered.
24999
25000@menu
25001* Legal Ada 83 programs that are illegal in Ada 95::
25002* More deterministic semantics::
25003* Changed semantics::
25004* Other language compatibility issues::
25005@end menu
25006
25007@node Legal Ada 83 programs that are illegal in Ada 95
25008@subsection Legal Ada 83 programs that are illegal in Ada 95
25009
25010@table @asis
25011@item Character literals
25012Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25013@code{Wide_Character} as a new predefined character type, some uses of
25014character literals that were legal in Ada 83 are illegal in Ada 95.
25015For example:
25016@smallexample @c ada
25017   for Char in 'A' .. 'Z' loop ... end loop;
25018@end smallexample
25019@noindent
25020The problem is that @code{'A'} and @code{'Z'} could be from either
25021@code{Character} or @code{Wide_Character}.  The simplest correction
25022is to make the type explicit; e.g.:
25023@smallexample @c ada
25024   for Char in Character range 'A' .. 'Z' loop ... end loop;
25025@end smallexample
25026
25027@item New reserved words
25028The identifiers @code{abstract}, @code{aliased}, @code{protected},
25029@code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25030Existing Ada 83 code using any of these identifiers must be edited to
25031use some alternative name.
25032
25033@item Freezing rules
25034The rules in Ada 95 are slightly different with regard to the point at
25035which entities are frozen, and representation pragmas and clauses are
25036not permitted past the freeze point.  This shows up most typically in
25037the form of an error message complaining that a representation item
25038appears too late, and the appropriate corrective action is to move
25039the item nearer to the declaration of the entity to which it refers.
25040
25041A particular case is that representation pragmas
25042@ifset vms
25043(including the
25044extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25045@end ifset
25046cannot be applied to a subprogram body.  If necessary, a separate subprogram
25047declaration must be introduced to which the pragma can be applied.
25048
25049@item Optional bodies for library packages
25050In Ada 83, a package that did not require a package body was nevertheless
25051allowed to have one.  This lead to certain surprises in compiling large
25052systems (situations in which the body could be unexpectedly ignored by the
25053binder).  In Ada 95, if a package does not require a body then it is not
25054permitted to have a body.  To fix this problem, simply remove a redundant
25055body if it is empty, or, if it is non-empty, introduce a dummy declaration
25056into the spec that makes the body required.  One approach is to add a private
25057part to the package declaration (if necessary), and define a parameterless
25058procedure called @code{Requires_Body}, which must then be given a dummy
25059procedure body in the package body, which then becomes required.
25060Another approach (assuming that this does not introduce elaboration
25061circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25062since one effect of this pragma is to require the presence of a package body.
25063
25064@item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25065In Ada 95, the exception @code{Numeric_Error} is a renaming of
25066@code{Constraint_Error}.
25067This means that it is illegal to have separate exception handlers for
25068the two exceptions.  The fix is simply to remove the handler for the
25069@code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25070@code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25071
25072@item Indefinite subtypes in generics
25073In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25074as the actual for a generic formal private type, but then the instantiation
25075would be illegal if there were any instances of declarations of variables
25076of this type in the generic body.  In Ada 95, to avoid this clear violation
25077of the methodological principle known as the ``contract model'',
25078the generic declaration explicitly indicates whether
25079or not such instantiations are permitted.  If a generic formal parameter
25080has explicit unknown discriminants, indicated by using @code{(<>)} after the
25081type name, then it can be instantiated with indefinite types, but no
25082stand-alone variables can be declared of this type.  Any attempt to declare
25083such a variable will result in an illegality at the time the generic is
25084declared.  If the @code{(<>)} notation is not used, then it is illegal
25085to instantiate the generic with an indefinite type.
25086This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25087It will show up as a compile time error, and
25088the fix is usually simply to add the @code{(<>)} to the generic declaration.
25089@end table
25090
25091@node More deterministic semantics
25092@subsection More deterministic semantics
25093
25094@table @asis
25095@item Conversions
25096Conversions from real types to integer types round away from 0.  In Ada 83
25097the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25098implementation freedom was intended to support unbiased rounding in
25099statistical applications, but in practice it interfered with portability.
25100In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25101is required.  Numeric code may be affected by this change in semantics.
25102Note, though, that this issue is no worse than already existed in Ada 83
25103when porting code from one vendor to another.
25104
25105@item Tasking
25106The Real-Time Annex introduces a set of policies that define the behavior of
25107features that were implementation dependent in Ada 83, such as the order in
25108which open select branches are executed.
25109@end table
25110
25111@node Changed semantics
25112@subsection Changed semantics
25113
25114@noindent
25115The worst kind of incompatibility is one where a program that is legal in
25116Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25117possible in Ada 83.  Fortunately this is extremely rare, but the one
25118situation that you should be alert to is the change in the predefined type
25119@code{Character} from 7-bit ASCII to 8-bit Latin-1.
25120
25121@table @asis
25122@item range of @code{Character}
25123The range of @code{Standard.Character} is now the full 256 characters
25124of Latin-1, whereas in most Ada 83 implementations it was restricted
25125to 128 characters. Although some of the effects of
25126this change will be manifest in compile-time rejection of legal
25127Ada 83 programs it is possible for a working Ada 83 program to have
25128a different effect in Ada 95, one that was not permitted in Ada 83.
25129As an example, the expression
25130@code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25131delivers @code{255} as its value.
25132In general, you should look at the logic of any
25133character-processing Ada 83 program and see whether it needs to be adapted
25134to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25135character handling package that may be relevant if code needs to be adapted
25136to account for the additional Latin-1 elements.
25137The desirable fix is to
25138modify the program to accommodate the full character set, but in some cases
25139it may be convenient to define a subtype or derived type of Character that
25140covers only the restricted range.
25141@cindex Latin-1
25142@end table
25143
25144@node Other language compatibility issues
25145@subsection Other language compatibility issues
25146@table @asis
25147@item @option{-gnat83 switch}
25148All implementations of GNAT provide a switch that causes GNAT to operate
25149in Ada 83 mode.  In this mode, some but not all compatibility problems
25150of the type described above are handled automatically.  For example, the
25151new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25152However,
25153in practice, it is usually advisable to make the necessary modifications
25154to the program to remove the need for using this switch.
25155See @ref{Compiling Ada 83 Programs}.
25156
25157@item Support for removed Ada 83 pragmas and attributes
25158A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25159generally because they have been replaced by other mechanisms.  Ada 95
25160compilers are allowed, but not required, to implement these missing
25161elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25162such pragmas and attributes, eliminating this compatibility concern.  These
25163include @code{pragma Interface} and the floating point type attributes
25164(@code{Emax}, @code{Mantissa}, etc.), among other items.
25165@end table
25166
25167
25168@node Implementation-dependent characteristics
25169@section Implementation-dependent characteristics
25170@noindent
25171Although the Ada language defines the semantics of each construct as
25172precisely as practical, in some situations (for example for reasons of
25173efficiency, or where the effect is heavily dependent on the host or target
25174platform) the implementation is allowed some freedom.  In porting Ada 83
25175code to GNAT, you need to be aware of whether / how the existing code
25176exercised such implementation dependencies.  Such characteristics fall into
25177several categories, and GNAT offers specific support in assisting the
25178transition from certain Ada 83 compilers.
25179
25180@menu
25181* Implementation-defined pragmas::
25182* Implementation-defined attributes::
25183* Libraries::
25184* Elaboration order::
25185* Target-specific aspects::
25186@end menu
25187
25188
25189@node Implementation-defined pragmas
25190@subsection Implementation-defined pragmas
25191
25192@noindent
25193Ada compilers are allowed to supplement the language-defined pragmas, and
25194these are a potential source of non-portability.  All GNAT-defined pragmas
25195are described in the GNAT Reference Manual, and these include several that
25196are specifically intended to correspond to other vendors' Ada 83 pragmas.
25197For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25198For
25199compatibility with DEC Ada 83, GNAT supplies the pragmas
25200@code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25201@code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25202and @code{Volatile}.
25203Other relevant pragmas include @code{External} and @code{Link_With}.
25204Some vendor-specific
25205Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25206recognized, thus
25207avoiding compiler rejection of units that contain such pragmas; they are not
25208relevant in a GNAT context and hence are not otherwise implemented.
25209
25210@node Implementation-defined attributes
25211@subsection Implementation-defined attributes
25212
25213Analogous to pragmas, the set of attributes may be extended by an
25214implementation.  All GNAT-defined attributes are described in the
25215@cite{GNAT Reference Manual}, and these include several that are specifically
25216intended
25217to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25218the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25219Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25220@code{Type_Class}.
25221
25222@node Libraries
25223@subsection Libraries
25224@noindent
25225Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25226code uses vendor-specific libraries then there are several ways to manage
25227this in Ada 95:
25228@enumerate
25229@item
25230If the source code for the libraries (specifications and bodies) are
25231available, then the libraries can be migrated in the same way as the
25232application.
25233@item
25234If the source code for the specifications but not the bodies are
25235available, then you can reimplement the bodies.
25236@item
25237Some new Ada 95 features obviate the need for library support.  For
25238example most Ada 83 vendors supplied a package for unsigned integers.  The
25239Ada 95 modular type feature is the preferred way to handle this need, so
25240instead of migrating or reimplementing the unsigned integer package it may
25241be preferable to retrofit the application using modular types.
25242@end enumerate
25243
25244@node Elaboration order
25245@subsection Elaboration order
25246@noindent
25247The implementation can choose any elaboration order consistent with the unit
25248dependency relationship.  This freedom means that some orders can result in
25249Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25250to invoke a subprogram its body has been elaborated, or to instantiate a
25251generic before the generic body has been elaborated.  By default GNAT
25252attempts to choose a safe order (one that will not encounter access before
25253elaboration problems) by implicitly inserting Elaborate_All pragmas where
25254needed.  However, this can lead to the creation of elaboration circularities
25255and a resulting rejection of the program by gnatbind.  This issue is
25256thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25257In brief, there are several
25258ways to deal with this situation:
25259
25260@itemize @bullet
25261@item
25262Modify the program to eliminate the circularities, e.g. by moving
25263elaboration-time code into explicitly-invoked procedures
25264@item
25265Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25266@code{Elaborate} pragmas, and then inhibit the generation of implicit
25267@code{Elaborate_All}
25268pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25269(by selectively suppressing elaboration checks via pragma
25270@code{Suppress(Elaboration_Check)} when it is safe to do so).
25271@end itemize
25272
25273@node Target-specific aspects
25274@subsection Target-specific aspects
25275@noindent
25276Low-level applications need to deal with machine addresses, data
25277representations, interfacing with assembler code, and similar issues.  If
25278such an Ada 83 application is being ported to different target hardware (for
25279example where the byte endianness has changed) then you will need to
25280carefully examine the program logic; the porting effort will heavily depend
25281on the robustness of the original design.  Moreover, Ada 95 is sometimes
25282incompatible with typical Ada 83 compiler practices regarding implicit
25283packing, the meaning of the Size attribute, and the size of access values.
25284GNAT's approach to these issues is described in @ref{Representation Clauses}.
25285
25286
25287@node Compatibility with Other Ada 95 Systems
25288@section Compatibility with Other Ada 95 Systems
25289
25290@noindent
25291Providing that programs avoid the use of implementation dependent and
25292implementation defined features of Ada 95, as documented in the Ada 95
25293reference manual, there should be a high degree of portability between
25294GNAT and other Ada 95 systems.  The following are specific items which
25295have proved troublesome in moving GNAT programs to other Ada 95
25296compilers, but do not affect porting code to GNAT@.
25297
25298@table @asis
25299@item Ada 83 Pragmas and Attributes
25300Ada 95 compilers are allowed, but not required, to implement the missing
25301Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25302GNAT implements all such pragmas and attributes, eliminating this as
25303a compatibility concern, but some other Ada 95 compilers reject these
25304pragmas and attributes.
25305
25306@item Special-needs Annexes
25307GNAT implements the full set of special needs annexes.  At the
25308current time, it is the only Ada 95 compiler to do so.  This means that
25309programs making use of these features may not be portable to other Ada
2531095 compilation systems.
25311
25312@item Representation Clauses
25313Some other Ada 95 compilers implement only the minimal set of
25314representation clauses required by the Ada 95 reference manual.  GNAT goes
25315far beyond this minimal set, as described in the next section.
25316@end table
25317
25318@node Representation Clauses
25319@section Representation Clauses
25320
25321@noindent
25322The Ada 83 reference manual was quite vague in describing both the minimal
25323required implementation of representation clauses, and also their precise
25324effects.  The Ada 95 reference manual is much more explicit, but the minimal
25325set of capabilities required in Ada 95 is quite limited.
25326
25327GNAT implements the full required set of capabilities described in the
25328Ada 95 reference manual, but also goes much beyond this, and in particular
25329an effort has been made to be compatible with existing Ada 83 usage to the
25330greatest extent possible.
25331
25332A few cases exist in which Ada 83 compiler behavior is incompatible with
25333requirements in the Ada 95 reference manual.  These are instances of
25334intentional or accidental dependence on specific implementation dependent
25335characteristics of these Ada 83 compilers.  The following is a list of
25336the cases most likely to arise in existing legacy Ada 83 code.
25337
25338@table @asis
25339@item Implicit Packing
25340Some Ada 83 compilers allowed a Size specification to cause implicit
25341packing of an array or record.  This could cause expensive implicit
25342conversions for change of representation in the presence of derived
25343types, and the Ada design intends to avoid this possibility.
25344Subsequent AI's were issued to make it clear that such implicit
25345change of representation in response to a Size clause is inadvisable,
25346and this recommendation is represented explicitly in the Ada 95 RM
25347as implementation advice that is followed by GNAT@.
25348The problem will show up as an error
25349message rejecting the size clause.  The fix is simply to provide
25350the explicit pragma @code{Pack}, or for more fine tuned control, provide
25351a Component_Size clause.
25352
25353@item Meaning of Size Attribute
25354The Size attribute in Ada 95 for discrete types is defined as being the
25355minimal number of bits required to hold values of the type.  For example,
25356on a 32-bit machine, the size of Natural will typically be 31 and not
2535732 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25358some 32 in this situation.  This problem will usually show up as a compile
25359time error, but not always.  It is a good idea to check all uses of the
25360'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25361Object_Size can provide a useful way of duplicating the behavior of
25362some Ada 83 compiler systems.
25363
25364@item Size of Access Types
25365A common assumption in Ada 83 code is that an access type is in fact a pointer,
25366and that therefore it will be the same size as a System.Address value.  This
25367assumption is true for GNAT in most cases with one exception.  For the case of
25368a pointer to an unconstrained array type (where the bounds may vary from one
25369value of the access type to another), the default is to use a ``fat pointer'',
25370which is represented as two separate pointers, one to the bounds, and one to
25371the array.  This representation has a number of advantages, including improved
25372efficiency.  However, it may cause some difficulties in porting existing Ada 83
25373code which makes the assumption that, for example, pointers fit in 32 bits on
25374a machine with 32-bit addressing.
25375
25376To get around this problem, GNAT also permits the use of ``thin pointers'' for
25377access types in this case (where the designated type is an unconstrained array
25378type).  These thin pointers are indeed the same size as a System.Address value.
25379To specify a thin pointer, use a size clause for the type, for example:
25380
25381@smallexample @c ada
25382type X is access all String;
25383for X'Size use Standard'Address_Size;
25384@end smallexample
25385
25386@noindent
25387which will cause the type X to be represented using a single pointer.
25388When using this representation, the bounds are right behind the array.
25389This representation is slightly less efficient, and does not allow quite
25390such flexibility in the use of foreign pointers or in using the
25391Unrestricted_Access attribute to create pointers to non-aliased objects.
25392But for any standard portable use of the access type it will work in
25393a functionally correct manner and allow porting of existing code.
25394Note that another way of forcing a thin pointer representation
25395is to use a component size clause for the element size in an array,
25396or a record representation clause for an access field in a record.
25397@end table
25398
25399@node Compatibility with DEC Ada 83
25400@section Compatibility with DEC Ada 83
25401
25402@noindent
25403The VMS version of GNAT fully implements all the pragmas and attributes
25404provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25405libraries, including Starlet.  In addition, data layouts and parameter
25406passing conventions are highly compatible.  This means that porting
25407existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25408most other porting efforts.  The following are some of the most
25409significant differences between GNAT and DEC Ada 83.
25410
25411@table @asis
25412@item Default floating-point representation
25413In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25414it is VMS format.  GNAT does implement the necessary pragmas
25415(Long_Float, Float_Representation) for changing this default.
25416
25417@item System
25418The package System in GNAT exactly corresponds to the definition in the
25419Ada 95 reference manual, which means that it excludes many of the
25420DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25421that contains the additional definitions, and a special pragma,
25422Extend_System allows this package to be treated transparently as an
25423extension of package System.
25424
25425@item To_Address
25426The definitions provided by Aux_DEC are exactly compatible with those
25427in the DEC Ada 83 version of System, with one exception.
25428DEC Ada provides the following declarations:
25429
25430@smallexample @c ada
25431TO_ADDRESS (INTEGER)
25432TO_ADDRESS (UNSIGNED_LONGWORD)
25433TO_ADDRESS (universal_integer)
25434@end smallexample
25435
25436@noindent
25437The version of TO_ADDRESS taking a universal integer argument is in fact
25438an extension to Ada 83 not strictly compatible with the reference manual.
25439In GNAT, we are constrained to be exactly compatible with the standard,
25440and this means we cannot provide this capability.  In DEC Ada 83, the
25441point of this definition is to deal with a call like:
25442
25443@smallexample @c ada
25444TO_ADDRESS (16#12777#);
25445@end smallexample
25446
25447@noindent
25448Normally, according to the Ada 83 standard, one would expect this to be
25449ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25450of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25451definition using universal_integer takes precedence.
25452
25453In GNAT, since the version with universal_integer cannot be supplied, it is
25454not possible to be 100% compatible.  Since there are many programs using
25455numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25456to change the name of the function in the UNSIGNED_LONGWORD case, so the
25457declarations provided in the GNAT version of AUX_Dec are:
25458
25459@smallexample @c ada
25460function To_Address (X : Integer) return Address;
25461pragma Pure_Function (To_Address);
25462
25463function To_Address_Long (X : Unsigned_Longword)
25464 return Address;
25465pragma Pure_Function (To_Address_Long);
25466@end smallexample
25467
25468@noindent
25469This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25470change the name to TO_ADDRESS_LONG@.
25471
25472@item Task_Id values
25473The Task_Id values assigned will be different in the two systems, and GNAT
25474does not provide a specified value for the Task_Id of the environment task,
25475which in GNAT is treated like any other declared task.
25476@end table
25477
25478For full details on these and other less significant compatibility issues,
25479see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25480Overview and Comparison on DIGITAL Platforms}.
25481
25482For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25483attributes are recognized, although only a subset of them can sensibly
25484be implemented.  The description of pragmas in this reference manual
25485indicates whether or not they are applicable to non-VMS systems.
25486
25487
25488
25489@ifset unw
25490@node Microsoft Windows Topics
25491@appendix Microsoft Windows Topics
25492@cindex Windows NT
25493@cindex Windows 95
25494@cindex Windows 98
25495
25496@noindent
25497This chapter describes topics that are specific to the Microsoft Windows
25498platforms (NT, 95 and 98).
25499
25500@menu
25501* Using GNAT on Windows::
25502* Using a network installation of GNAT::
25503* CONSOLE and WINDOWS subsystems::
25504* Temporary Files::
25505* Mixed-Language Programming on Windows::
25506* Windows Calling Conventions::
25507* Introduction to Dynamic Link Libraries (DLLs)::
25508* Using DLLs with GNAT::
25509* Building DLLs with GNAT::
25510* GNAT and Windows Resources::
25511* Debugging a DLL::
25512* GNAT and COM/DCOM Objects::
25513@end menu
25514
25515@node Using GNAT on Windows
25516@section Using GNAT on Windows
25517
25518@noindent
25519One of the strengths of the GNAT technology is that its tool set
25520(@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
25521@code{gdb} debugger, etc.) is used in the same way regardless of the
25522platform.
25523
25524On Windows this tool set is complemented by a number of Microsoft-specific
25525tools that have been provided to facilitate interoperability with Windows
25526when this is required. With these tools:
25527
25528@itemize @bullet
25529
25530@item
25531You can build applications using the @code{CONSOLE} or @code{WINDOWS}
25532subsystems.
25533
25534@item
25535You can use any Dynamically Linked Library (DLL) in your Ada code (both
25536relocatable and non-relocatable DLLs are supported).
25537
25538@item
25539You can build Ada DLLs for use in other applications. These applications
25540can be written in a language other than Ada (e.g., C, C++, etc). Again both
25541relocatable and non-relocatable Ada DLLs are supported.
25542
25543@item
25544You can include Windows resources in your Ada application.
25545
25546@item
25547You can use or create COM/DCOM objects.
25548@end itemize
25549
25550@noindent
25551Immediately below are listed all known general GNAT-for-Windows restrictions.
25552Other restrictions about specific features like Windows Resources and DLLs
25553are listed in separate sections below.
25554
25555@itemize @bullet
25556
25557@item
25558It is not possible to use @code{GetLastError} and @code{SetLastError}
25559when tasking, protected records, or exceptions are used. In these
25560cases, in order to implement Ada semantics, the GNAT run-time system
25561calls certain Win32 routines that set the last error variable to 0 upon
25562success. It should be possible to use @code{GetLastError} and
25563@code{SetLastError} when tasking, protected record, and exception
25564features are not used, but it is not guaranteed to work.
25565@end itemize
25566
25567@node Using a network installation of GNAT
25568@section Using a network installation of GNAT
25569
25570@noindent
25571Make sure the system on which GNAT is installed is accessible from the
25572current machine, i.e. the install location is shared over the network.
25573Shared resources are accessed on Windows by means of UNC paths, which
25574have the format @code{\\server\sharename\path}
25575
25576In order to use such a network installation, simply add the UNC path of the
25577@file{bin} directory of your GNAT installation in front of your PATH. For
25578example, if GNAT is installed in @file{\GNAT} directory of a share location
25579called @file{c-drive} on a machine @file{LOKI}, the following command will
25580make it available:
25581
25582@code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
25583
25584Be aware that every compilation using the network installation results in the
25585transfer of large amounts of data across the network and will likely cause
25586serious performance penalty.
25587
25588@node CONSOLE and WINDOWS subsystems
25589@section CONSOLE and WINDOWS subsystems
25590@cindex CONSOLE Subsystem
25591@cindex WINDOWS Subsystem
25592@cindex -mwindows
25593
25594@noindent
25595There are two main subsystems under Windows. The @code{CONSOLE} subsystem
25596(which is the default subsystem) will always create a console when
25597launching the application. This is not something desirable when the
25598application has a Windows GUI. To get rid of this console the
25599application must be using the @code{WINDOWS} subsystem. To do so
25600the @option{-mwindows} linker option must be specified.
25601
25602@smallexample
25603$ gnatmake winprog -largs -mwindows
25604@end smallexample
25605
25606@node Temporary Files
25607@section Temporary Files
25608@cindex Temporary files
25609
25610@noindent
25611It is possible to control where temporary files gets created by setting
25612the TMP environment variable. The file will be created:
25613
25614@itemize
25615@item Under the directory pointed to by the TMP environment variable if
25616this directory exists.
25617
25618@item Under c:\temp, if the TMP environment variable is not set (or not
25619pointing to a directory) and if this directory exists.
25620
25621@item Under the current working directory otherwise.
25622@end itemize
25623
25624@noindent
25625This allows you to determine exactly where the temporary
25626file will be created. This is particularly useful in networked
25627environments where you may not have write access to some
25628directories.
25629
25630@node Mixed-Language Programming on Windows
25631@section Mixed-Language Programming on Windows
25632
25633@noindent
25634Developing pure Ada applications on Windows is no different than on
25635other GNAT-supported platforms. However, when developing or porting an
25636application that contains a mix of Ada and C/C++, the choice of your
25637Windows C/C++ development environment conditions your overall
25638interoperability strategy.
25639
25640If you use @code{gcc} to compile the non-Ada part of your application,
25641there are no Windows-specific restrictions that affect the overall
25642interoperability with your Ada code. If you plan to use
25643Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
25644the following limitations:
25645
25646@itemize @bullet
25647@item
25648You cannot link your Ada code with an object or library generated with
25649Microsoft tools if these use the @code{.tls} section (Thread Local
25650Storage section) since the GNAT linker does not yet support this section.
25651
25652@item
25653You cannot link your Ada code with an object or library generated with
25654Microsoft tools if these use I/O routines other than those provided in
25655the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
25656uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
25657libraries can cause a conflict with @code{msvcrt.dll} services. For
25658instance Visual C++ I/O stream routines conflict with those in
25659@code{msvcrt.dll}.
25660@end itemize
25661
25662@noindent
25663If you do want to use the Microsoft tools for your non-Ada code and hit one
25664of the above limitations, you have two choices:
25665
25666@enumerate
25667@item
25668Encapsulate your non Ada code in a DLL to be linked with your Ada
25669application. In this case, use the Microsoft or whatever environment to
25670build the DLL and use GNAT to build your executable
25671(@pxref{Using DLLs with GNAT}).
25672
25673@item
25674Or you can encapsulate your Ada code in a DLL to be linked with the
25675other part of your application. In this case, use GNAT to build the DLL
25676(@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
25677environment to build your executable.
25678@end enumerate
25679
25680@node Windows Calling Conventions
25681@section Windows Calling Conventions
25682@findex Stdcall
25683@findex APIENTRY
25684
25685@menu
25686* C Calling Convention::
25687* Stdcall Calling Convention::
25688* DLL Calling Convention::
25689@end menu
25690
25691@noindent
25692When a subprogram @code{F} (caller) calls a subprogram @code{G}
25693(callee), there are several ways to push @code{G}'s parameters on the
25694stack and there are several possible scenarios to clean up the stack
25695upon @code{G}'s return. A calling convention is an agreed upon software
25696protocol whereby the responsibilities between the caller (@code{F}) and
25697the callee (@code{G}) are clearly defined. Several calling conventions
25698are available for Windows:
25699
25700@itemize @bullet
25701@item
25702@code{C} (Microsoft defined)
25703
25704@item
25705@code{Stdcall} (Microsoft defined)
25706
25707@item
25708@code{DLL} (GNAT specific)
25709@end itemize
25710
25711@node C Calling Convention
25712@subsection @code{C} Calling Convention
25713
25714@noindent
25715This is the default calling convention used when interfacing to C/C++
25716routines compiled with either @code{gcc} or Microsoft Visual C++.
25717
25718In the @code{C} calling convention subprogram parameters are pushed on the
25719stack by the caller from right to left. The caller itself is in charge of
25720cleaning up the stack after the call. In addition, the name of a routine
25721with @code{C} calling convention is mangled by adding a leading underscore.
25722
25723The name to use on the Ada side when importing (or exporting) a routine
25724with @code{C} calling convention is the name of the routine. For
25725instance the C function:
25726
25727@smallexample
25728int get_val (long);
25729@end smallexample
25730
25731@noindent
25732should be imported from Ada as follows:
25733
25734@smallexample @c ada
25735@group
25736function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
25737pragma Import (C, Get_Val, External_Name => "get_val");
25738@end group
25739@end smallexample
25740
25741@noindent
25742Note that in this particular case the @code{External_Name} parameter could
25743have been omitted since, when missing, this parameter is taken to be the
25744name of the Ada entity in lower case. When the @code{Link_Name} parameter
25745is missing, as in the above example, this parameter is set to be the
25746@code{External_Name} with a leading underscore.
25747
25748When importing a variable defined in C, you should always use the @code{C}
25749calling convention unless the object containing the variable is part of a
25750DLL (in which case you should use the @code{DLL} calling convention,
25751@pxref{DLL Calling Convention}).
25752
25753@node Stdcall Calling Convention
25754@subsection @code{Stdcall} Calling Convention
25755
25756@noindent
25757This convention, which was the calling convention used for Pascal
25758programs, is used by Microsoft for all the routines in the Win32 API for
25759efficiency reasons. It must be used to import any routine for which this
25760convention was specified.
25761
25762In the @code{Stdcall} calling convention subprogram parameters are pushed
25763on the stack by the caller from right to left. The callee (and not the
25764caller) is in charge of cleaning the stack on routine exit. In addition,
25765the name of a routine with @code{Stdcall} calling convention is mangled by
25766adding a leading underscore (as for the @code{C} calling convention) and a
25767trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
25768bytes) of the parameters passed to the routine.
25769
25770The name to use on the Ada side when importing a C routine with a
25771@code{Stdcall} calling convention is the name of the C routine. The leading
25772underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
25773the compiler. For instance the Win32 function:
25774
25775@smallexample
25776@b{APIENTRY} int get_val (long);
25777@end smallexample
25778
25779@noindent
25780should be imported from Ada as follows:
25781
25782@smallexample @c ada
25783@group
25784function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
25785pragma Import (Stdcall, Get_Val);
25786--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
25787@end group
25788@end smallexample
25789
25790@noindent
25791As for the @code{C} calling convention, when the @code{External_Name}
25792parameter is missing, it is taken to be the name of the Ada entity in lower
25793case. If instead of writing the above import pragma you write:
25794
25795@smallexample @c ada
25796@group
25797function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
25798pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
25799@end group
25800@end smallexample
25801
25802@noindent
25803then the imported routine is @code{_retrieve_val@@4}. However, if instead
25804of specifying the @code{External_Name} parameter you specify the
25805@code{Link_Name} as in the following example:
25806
25807@smallexample @c ada
25808@group
25809function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
25810pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
25811@end group
25812@end smallexample
25813
25814@noindent
25815then the imported routine is @code{retrieve_val@@4}, that is, there is no
25816trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
25817added at the end of the @code{Link_Name} by the compiler.
25818
25819@noindent
25820Note, that in some special cases a DLL's entry point name lacks a trailing
25821@code{@@}@code{@i{nn}} while the exported name generated for a call has it.
25822The @code{gnatdll} tool, which creates the import library for the DLL, is able
25823to handle those cases (see the description of the switches in
25824@pxref{Using gnatdll} section).
25825
25826@node DLL Calling Convention
25827@subsection @code{DLL} Calling Convention
25828
25829@noindent
25830This convention, which is GNAT-specific, must be used when you want to
25831import in Ada a variables defined in a DLL. For functions and procedures
25832this convention is equivalent to the @code{Stdcall} convention. As an
25833example, if a DLL contains a variable defined as:
25834
25835@smallexample
25836int my_var;
25837@end smallexample
25838
25839@noindent
25840then, to access this variable from Ada you should write:
25841
25842@smallexample @c ada
25843@group
25844My_Var : Interfaces.C.int;
25845pragma Import (DLL, My_Var);
25846@end group
25847@end smallexample
25848
25849The remarks concerning the @code{External_Name} and @code{Link_Name}
25850parameters given in the previous sections equally apply to the @code{DLL}
25851calling convention.
25852
25853@node Introduction to Dynamic Link Libraries (DLLs)
25854@section Introduction to Dynamic Link Libraries (DLLs)
25855@findex DLL
25856
25857@noindent
25858A Dynamically Linked Library (DLL) is a library that can be shared by
25859several applications running under Windows. A DLL can contain any number of
25860routines and variables.
25861
25862One advantage of DLLs is that you can change and enhance them without
25863forcing all the applications that depend on them to be relinked or
25864recompiled. However, you should be aware than all calls to DLL routines are
25865slower since, as you will understand below, such calls are indirect.
25866
25867To illustrate the remainder of this section, suppose that an application
25868wants to use the services of a DLL @file{API.dll}. To use the services
25869provided by @file{API.dll} you must statically link against an import
25870library which contains a jump table with an entry for each routine and
25871variable exported by the DLL. In the Microsoft world this import library is
25872called @file{API.lib}. When using GNAT this import library is called either
25873@file{libAPI.a} or @file{libapi.a} (names are case insensitive).
25874
25875After you have statically linked your application with the import library
25876and you run your application, here is what happens:
25877
25878@enumerate
25879@item
25880Your application is loaded into memory.
25881
25882@item
25883The DLL @file{API.dll} is mapped into the address space of your
25884application. This means that:
25885
25886@itemize @bullet
25887@item
25888The DLL will use the stack of the calling thread.
25889
25890@item
25891The DLL will use the virtual address space of the calling process.
25892
25893@item
25894The DLL will allocate memory from the virtual address space of the calling
25895process.
25896
25897@item
25898Handles (pointers) can be safely exchanged between routines in the DLL
25899routines and routines in the application using the DLL.
25900@end itemize
25901
25902@item
25903The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
25904part of your application are initialized with the addresses of the routines
25905and variables in @file{API.dll}.
25906
25907@item
25908If present in @file{API.dll}, routines @code{DllMain} or
25909@code{DllMainCRTStartup} are invoked. These routines typically contain
25910the initialization code needed for the well-being of the routines and
25911variables exported by the DLL.
25912@end enumerate
25913
25914@noindent
25915There is an additional point which is worth mentioning. In the Windows
25916world there are two kind of DLLs: relocatable and non-relocatable
25917DLLs. Non-relocatable DLLs can only be loaded at a very specific address
25918in the target application address space. If the addresses of two
25919non-relocatable DLLs overlap and these happen to be used by the same
25920application, a conflict will occur and the application will run
25921incorrectly. Hence, when possible, it is always preferable to use and
25922build relocatable DLLs. Both relocatable and non-relocatable DLLs are
25923supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
25924User's Guide) removes the debugging symbols from the DLL but the DLL can
25925still be relocated.
25926
25927As a side note, an interesting difference between Microsoft DLLs and
25928Unix shared libraries, is the fact that on most Unix systems all public
25929routines are exported by default in a Unix shared library, while under
25930Windows the exported routines must be listed explicitly in a definition
25931file (@pxref{The Definition File}).
25932
25933@node Using DLLs with GNAT
25934@section Using DLLs with GNAT
25935
25936@menu
25937* Creating an Ada Spec for the DLL Services::
25938* Creating an Import Library::
25939@end menu
25940
25941@noindent
25942To use the services of a DLL, say @file{API.dll}, in your Ada application
25943you must have:
25944
25945@enumerate
25946@item
25947The Ada spec for the routines and/or variables you want to access in
25948@file{API.dll}. If not available this Ada spec must be built from the C/C++
25949header files provided with the DLL.
25950
25951@item
25952The import library (@file{libAPI.a} or @file{API.lib}). As previously
25953mentioned an import library is a statically linked library containing the
25954import table which will be filled at load time to point to the actual
25955@file{API.dll} routines. Sometimes you don't have an import library for the
25956DLL you want to use. The following sections will explain how to build one.
25957
25958@item
25959The actual DLL, @file{API.dll}.
25960@end enumerate
25961
25962@noindent
25963Once you have all the above, to compile an Ada application that uses the
25964services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
25965you simply issue the command
25966
25967@smallexample
25968$ gnatmake my_ada_app -largs -lAPI
25969@end smallexample
25970
25971@noindent
25972The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
25973tells the GNAT linker to look first for a library named @file{API.lib}
25974(Microsoft-style name) and if not found for a library named @file{libAPI.a}
25975(GNAT-style name). Note that if the Ada package spec for @file{API.dll}
25976contains the following pragma
25977
25978@smallexample @c ada
25979pragma Linker_Options ("-lAPI");
25980@end smallexample
25981
25982@noindent
25983you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
25984command.
25985
25986If any one of the items above is missing you will have to create it
25987yourself. The following sections explain how to do so using as an
25988example a fictitious DLL called @file{API.dll}.
25989
25990@node Creating an Ada Spec for the DLL Services
25991@subsection Creating an Ada Spec for the DLL Services
25992
25993@noindent
25994A DLL typically comes with a C/C++ header file which provides the
25995definitions of the routines and variables exported by the DLL. The Ada
25996equivalent of this header file is a package spec that contains definitions
25997for the imported entities. If the DLL you intend to use does not come with
25998an Ada spec you have to generate one such spec yourself. For example if
25999the header file of @file{API.dll} is a file @file{api.h} containing the
26000following two definitions:
26001
26002@smallexample
26003@group
26004@cartouche
26005int some_var;
26006int get (char *);
26007@end cartouche
26008@end group
26009@end smallexample
26010
26011@noindent
26012then the equivalent Ada spec could be:
26013
26014@smallexample @c ada
26015@group
26016@cartouche
26017with Interfaces.C.Strings;
26018package API is
26019   use Interfaces;
26020
26021   Some_Var : C.int;
26022   function Get (Str : C.Strings.Chars_Ptr) return C.int;
26023
26024private
26025   pragma Import (C, Get);
26026   pragma Import (DLL, Some_Var);
26027end API;
26028@end cartouche
26029@end group
26030@end smallexample
26031
26032@noindent
26033Note that a variable is @strong{always imported with a DLL convention}. A
26034function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26035subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26036(@pxref{Windows Calling Conventions}).
26037
26038@node Creating an Import Library
26039@subsection Creating an Import Library
26040@cindex Import library
26041
26042@menu
26043* The Definition File::
26044* GNAT-Style Import Library::
26045* Microsoft-Style Import Library::
26046@end menu
26047
26048@noindent
26049If a Microsoft-style import library @file{API.lib} or a GNAT-style
26050import library @file{libAPI.a} is available with @file{API.dll} you
26051can skip this section. Otherwise read on.
26052
26053@node The Definition File
26054@subsubsection The Definition File
26055@cindex Definition file
26056@findex .def
26057
26058@noindent
26059As previously mentioned, and unlike Unix systems, the list of symbols
26060that are exported from a DLL must be provided explicitly in Windows.
26061The main goal of a definition file is precisely that: list the symbols
26062exported by a DLL. A definition file (usually a file with a @code{.def}
26063suffix) has the following structure:
26064
26065@smallexample
26066@group
26067@cartouche
26068[LIBRARY @i{name}]
26069[DESCRIPTION @i{string}]
26070EXPORTS
26071   @i{symbol1}
26072   @i{symbol2}
26073   ...
26074@end cartouche
26075@end group
26076@end smallexample
26077
26078@table @code
26079@item LIBRARY @i{name}
26080This section, which is optional, gives the name of the DLL.
26081
26082@item DESCRIPTION @i{string}
26083This section, which is optional, gives a description string that will be
26084embedded in the import library.
26085
26086@item EXPORTS
26087This section gives the list of exported symbols (procedures, functions or
26088variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26089section of @file{API.def} looks like:
26090
26091@smallexample
26092@group
26093@cartouche
26094EXPORTS
26095   some_var
26096   get
26097@end cartouche
26098@end group
26099@end smallexample
26100@end table
26101
26102@noindent
26103Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26104(@pxref{Windows Calling Conventions}) for a Stdcall
26105calling convention function in the exported symbols list.
26106
26107@noindent
26108There can actually be other sections in a definition file, but these
26109sections are not relevant to the discussion at hand.
26110
26111@node GNAT-Style Import Library
26112@subsubsection GNAT-Style Import Library
26113
26114@noindent
26115To create a static import library from @file{API.dll} with the GNAT tools
26116you should proceed as follows:
26117
26118@enumerate
26119@item
26120Create the definition file @file{API.def} (@pxref{The Definition File}).
26121For that use the @code{dll2def} tool as follows:
26122
26123@smallexample
26124$ dll2def API.dll > API.def
26125@end smallexample
26126
26127@noindent
26128@code{dll2def} is a very simple tool: it takes as input a DLL and prints
26129to standard output the list of entry points in the DLL. Note that if
26130some routines in the DLL have the @code{Stdcall} convention
26131(@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26132suffix then you'll have to edit @file{api.def} to add it.
26133
26134@noindent
26135Here are some hints to find the right @code{@@}@i{nn} suffix.
26136
26137@enumerate
26138@item
26139If you have the Microsoft import library (.lib), it is possible to get
26140the right symbols by using Microsoft @code{dumpbin} tool (see the
26141corresponding Microsoft documentation for further details).
26142
26143@smallexample
26144$ dumpbin /exports api.lib
26145@end smallexample
26146
26147@item
26148If you have a message about a missing symbol at link time the compiler
26149tells you what symbol is expected. You just have to go back to the
26150definition file and add the right suffix.
26151@end enumerate
26152
26153@item
26154Build the import library @code{libAPI.a}, using @code{gnatdll}
26155(@pxref{Using gnatdll}) as follows:
26156
26157@smallexample
26158$ gnatdll -e API.def -d API.dll
26159@end smallexample
26160
26161@noindent
26162@code{gnatdll} takes as input a definition file @file{API.def} and the
26163name of the DLL containing the services listed in the definition file
26164@file{API.dll}. The name of the static import library generated is
26165computed from the name of the definition file as follows: if the
26166definition file name is @i{xyz}@code{.def}, the import library name will
26167be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26168@option{-e} could have been removed because the name of the definition
26169file (before the ``@code{.def}'' suffix) is the same as the name of the
26170DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26171@end enumerate
26172
26173@node Microsoft-Style Import Library
26174@subsubsection Microsoft-Style Import Library
26175
26176@noindent
26177With GNAT you can either use a GNAT-style or Microsoft-style import
26178library. A Microsoft import library is needed only if you plan to make an
26179Ada DLL available to applications developed with Microsoft
26180tools (@pxref{Mixed-Language Programming on Windows}).
26181
26182To create a Microsoft-style import library for @file{API.dll} you
26183should proceed as follows:
26184
26185@enumerate
26186@item
26187Create the definition file @file{API.def} from the DLL. For this use either
26188the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26189tool (see the corresponding Microsoft documentation for further details).
26190
26191@item
26192Build the actual import library using Microsoft's @code{lib} utility:
26193
26194@smallexample
26195$ lib -machine:IX86 -def:API.def -out:API.lib
26196@end smallexample
26197
26198@noindent
26199If you use the above command the definition file @file{API.def} must
26200contain a line giving the name of the DLL:
26201
26202@smallexample
26203LIBRARY      "API"
26204@end smallexample
26205
26206@noindent
26207See the Microsoft documentation for further details about the usage of
26208@code{lib}.
26209@end enumerate
26210
26211@node Building DLLs with GNAT
26212@section Building DLLs with GNAT
26213@cindex DLLs, building
26214
26215@menu
26216* Limitations When Using Ada DLLs from Ada::
26217* Exporting Ada Entities::
26218* Ada DLLs and Elaboration::
26219* Ada DLLs and Finalization::
26220* Creating a Spec for Ada DLLs::
26221* Creating the Definition File::
26222* Using gnatdll::
26223@end menu
26224
26225@noindent
26226This section explains how to build DLLs containing Ada code. These DLLs
26227will be referred to as Ada DLLs in the remainder of this section.
26228
26229The steps required to build an Ada DLL that is to be used by Ada as well as
26230non-Ada applications are as follows:
26231
26232@enumerate
26233@item
26234You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26235@code{Stdcall} calling convention to avoid any Ada name mangling for the
26236entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26237skip this step if you plan to use the Ada DLL only from Ada applications.
26238
26239@item
26240Your Ada code must export an initialization routine which calls the routine
26241@code{adainit} generated by @code{gnatbind} to perform the elaboration of
26242the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26243routine exported by the Ada DLL must be invoked by the clients of the DLL
26244to initialize the DLL.
26245
26246@item
26247When useful, the DLL should also export a finalization routine which calls
26248routine @code{adafinal} generated by @code{gnatbind} to perform the
26249finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26250The finalization routine exported by the Ada DLL must be invoked by the
26251clients of the DLL when the DLL services are no further needed.
26252
26253@item
26254You must provide a spec for the services exported by the Ada DLL in each
26255of the programming languages to which you plan to make the DLL available.
26256
26257@item
26258You must provide a definition file listing the exported entities
26259(@pxref{The Definition File}).
26260
26261@item
26262Finally you must use @code{gnatdll} to produce the DLL and the import
26263library (@pxref{Using gnatdll}).
26264@end enumerate
26265
26266@node Limitations When Using Ada DLLs from Ada
26267@subsection Limitations When Using Ada DLLs from Ada
26268
26269@noindent
26270When using Ada DLLs from Ada applications there is a limitation users
26271should be aware of. Because on Windows the GNAT run time is not in a DLL of
26272its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26273each Ada DLL includes the services of the GNAT run time that are necessary
26274to the Ada code inside the DLL. As a result, when an Ada program uses an
26275Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26276one in the main program.
26277
26278It is therefore not possible to exchange GNAT run-time objects between the
26279Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26280handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26281types, etc.
26282
26283It is completely safe to exchange plain elementary, array or record types,
26284Windows object handles, etc.
26285
26286@node Exporting Ada Entities
26287@subsection Exporting Ada Entities
26288@cindex Export table
26289
26290@noindent
26291Building a DLL is a way to encapsulate a set of services usable from any
26292application. As a result, the Ada entities exported by a DLL should be
26293exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26294any Ada name mangling. Please note that the @code{Stdcall} convention
26295should only be used for subprograms, not for variables. As an example here
26296is an Ada package @code{API}, spec and body, exporting two procedures, a
26297function, and a variable:
26298
26299@smallexample @c ada
26300@group
26301@cartouche
26302with Interfaces.C; use Interfaces;
26303package API is
26304   Count : C.int := 0;
26305   function Factorial (Val : C.int) return C.int;
26306
26307   procedure Initialize_API;
26308   procedure Finalize_API;
26309   --  Initialization & Finalization routines. More in the next section.
26310private
26311   pragma Export (C, Initialize_API);
26312   pragma Export (C, Finalize_API);
26313   pragma Export (C, Count);
26314   pragma Export (C, Factorial);
26315end API;
26316@end cartouche
26317@end group
26318@end smallexample
26319
26320@smallexample @c ada
26321@group
26322@cartouche
26323package body API is
26324   function Factorial (Val : C.int) return C.int is
26325      Fact : C.int := 1;
26326   begin
26327      Count := Count + 1;
26328      for K in 1 .. Val loop
26329         Fact := Fact * K;
26330      end loop;
26331      return Fact;
26332   end Factorial;
26333
26334   procedure Initialize_API is
26335      procedure Adainit;
26336      pragma Import (C, Adainit);
26337   begin
26338      Adainit;
26339   end Initialize_API;
26340
26341   procedure Finalize_API is
26342      procedure Adafinal;
26343      pragma Import (C, Adafinal);
26344   begin
26345      Adafinal;
26346   end Finalize_API;
26347end API;
26348@end cartouche
26349@end group
26350@end smallexample
26351
26352@noindent
26353If the Ada DLL you are building will only be used by Ada applications
26354you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26355convention. As an example, the previous package could be written as
26356follows:
26357
26358@smallexample @c ada
26359@group
26360@cartouche
26361package API is
26362   Count : Integer := 0;
26363   function Factorial (Val : Integer) return Integer;
26364
26365   procedure Initialize_API;
26366   procedure Finalize_API;
26367   --  Initialization and Finalization routines.
26368end API;
26369@end cartouche
26370@end group
26371@end smallexample
26372
26373@smallexample @c ada
26374@group
26375@cartouche
26376package body API is
26377   function Factorial (Val : Integer) return Integer is
26378      Fact : Integer := 1;
26379   begin
26380      Count := Count + 1;
26381      for K in 1 .. Val loop
26382         Fact := Fact * K;
26383      end loop;
26384      return Fact;
26385      end Factorial;
26386
26387   ...
26388   --  The remainder of this package body is unchanged.
26389end API;
26390@end cartouche
26391@end group
26392@end smallexample
26393
26394@noindent
26395Note that if you do not export the Ada entities with a @code{C} or
26396@code{Stdcall} convention you will have to provide the mangled Ada names
26397in the definition file of the Ada DLL
26398(@pxref{Creating the Definition File}).
26399
26400@node Ada DLLs and Elaboration
26401@subsection Ada DLLs and Elaboration
26402@cindex DLLs and elaboration
26403
26404@noindent
26405The DLL that you are building contains your Ada code as well as all the
26406routines in the Ada library that are needed by it. The first thing a
26407user of your DLL must do is elaborate the Ada code
26408(@pxref{Elaboration Order Handling in GNAT}).
26409
26410To achieve this you must export an initialization routine
26411(@code{Initialize_API} in the previous example), which must be invoked
26412before using any of the DLL services. This elaboration routine must call
26413the Ada elaboration routine @code{adainit} generated by the GNAT binder
26414(@pxref{Binding with Non-Ada Main Programs}). See the body of
26415@code{Initialize_Api} for an example. Note that the GNAT binder is
26416automatically invoked during the DLL build process by the @code{gnatdll}
26417tool (@pxref{Using gnatdll}).
26418
26419When a DLL is loaded, Windows systematically invokes a routine called
26420@code{DllMain}. It would therefore be possible to call @code{adainit}
26421directly from @code{DllMain} without having to provide an explicit
26422initialization routine. Unfortunately, it is not possible to call
26423@code{adainit} from the @code{DllMain} if your program has library level
26424tasks because access to the @code{DllMain} entry point is serialized by
26425the system (that is, only a single thread can execute ``through'' it at a
26426time), which means that the GNAT run time will deadlock waiting for the
26427newly created task to complete its initialization.
26428
26429@node Ada DLLs and Finalization
26430@subsection Ada DLLs and Finalization
26431@cindex DLLs and finalization
26432
26433@noindent
26434When the services of an Ada DLL are no longer needed, the client code should
26435invoke the DLL finalization routine, if available. The DLL finalization
26436routine is in charge of releasing all resources acquired by the DLL. In the
26437case of the Ada code contained in the DLL, this is achieved by calling
26438routine @code{adafinal} generated by the GNAT binder
26439(@pxref{Binding with Non-Ada Main Programs}).
26440See the body of @code{Finalize_Api} for an
26441example. As already pointed out the GNAT binder is automatically invoked
26442during the DLL build process by the @code{gnatdll} tool
26443(@pxref{Using gnatdll}).
26444
26445@node Creating a Spec for Ada DLLs
26446@subsection Creating a Spec for Ada DLLs
26447
26448@noindent
26449To use the services exported by the Ada DLL from another programming
26450language (e.g. C), you have to translate the specs of the exported Ada
26451entities in that language. For instance in the case of @code{API.dll},
26452the corresponding C header file could look like:
26453
26454@smallexample
26455@group
26456@cartouche
26457extern int *_imp__count;
26458#define count (*_imp__count)
26459int factorial (int);
26460@end cartouche
26461@end group
26462@end smallexample
26463
26464@noindent
26465It is important to understand that when building an Ada DLL to be used by
26466other Ada applications, you need two different specs for the packages
26467contained in the DLL: one for building the DLL and the other for using
26468the DLL. This is because the @code{DLL} calling convention is needed to
26469use a variable defined in a DLL, but when building the DLL, the variable
26470must have either the @code{Ada} or @code{C} calling convention. As an
26471example consider a DLL comprising the following package @code{API}:
26472
26473@smallexample @c ada
26474@group
26475@cartouche
26476package API is
26477   Count : Integer := 0;
26478   ...
26479   --  Remainder of the package omitted.
26480end API;
26481@end cartouche
26482@end group
26483@end smallexample
26484
26485@noindent
26486After producing a DLL containing package @code{API}, the spec that
26487must be used to import @code{API.Count} from Ada code outside of the
26488DLL is:
26489
26490@smallexample @c ada
26491@group
26492@cartouche
26493package API is
26494   Count : Integer;
26495   pragma Import (DLL, Count);
26496end API;
26497@end cartouche
26498@end group
26499@end smallexample
26500
26501@node Creating the Definition File
26502@subsection Creating the Definition File
26503
26504@noindent
26505The definition file is the last file needed to build the DLL. It lists
26506the exported symbols. As an example, the definition file for a DLL
26507containing only package @code{API} (where all the entities are exported
26508with a @code{C} calling convention) is:
26509
26510@smallexample
26511@group
26512@cartouche
26513EXPORTS
26514    count
26515    factorial
26516    finalize_api
26517    initialize_api
26518@end cartouche
26519@end group
26520@end smallexample
26521
26522@noindent
26523If the @code{C} calling convention is missing from package @code{API},
26524then the definition file contains the mangled Ada names of the above
26525entities, which in this case are:
26526
26527@smallexample
26528@group
26529@cartouche
26530EXPORTS
26531    api__count
26532    api__factorial
26533    api__finalize_api
26534    api__initialize_api
26535@end cartouche
26536@end group
26537@end smallexample
26538
26539@node Using gnatdll
26540@subsection Using @code{gnatdll}
26541@findex gnatdll
26542
26543@menu
26544* gnatdll Example::
26545* gnatdll behind the Scenes::
26546* Using dlltool::
26547@end menu
26548
26549@noindent
26550@code{gnatdll} is a tool to automate the DLL build process once all the Ada
26551and non-Ada sources that make up your DLL have been compiled.
26552@code{gnatdll} is actually in charge of two distinct tasks: build the
26553static import library for the DLL and the actual DLL. The form of the
26554@code{gnatdll} command is
26555
26556@smallexample
26557@cartouche
26558$ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
26559@end cartouche
26560@end smallexample
26561
26562@noindent
26563where @i{list-of-files} is a list of ALI and object files. The object
26564file list must be the exact list of objects corresponding to the non-Ada
26565sources whose services are to be included in the DLL. The ALI file list
26566must be the exact list of ALI files for the corresponding Ada sources
26567whose services are to be included in the DLL. If @i{list-of-files} is
26568missing, only the static import library is generated.
26569
26570@noindent
26571You may specify any of the following switches to @code{gnatdll}:
26572
26573@table @code
26574@item -a[@var{address}]
26575@cindex @option{-a} (@code{gnatdll})
26576Build a non-relocatable DLL at @var{address}. If @var{address} is not
26577specified the default address @var{0x11000000} will be used. By default,
26578when this switch is missing, @code{gnatdll} builds relocatable DLL. We
26579advise the reader to build relocatable DLL.
26580
26581@item -b @var{address}
26582@cindex @option{-b} (@code{gnatdll})
26583Set the relocatable DLL base address. By default the address is
26584@var{0x11000000}.
26585
26586@item -bargs @var{opts}
26587@cindex @option{-bargs} (@code{gnatdll})
26588Binder options. Pass @var{opts} to the binder.
26589
26590@item -d @var{dllfile}
26591@cindex @option{-d} (@code{gnatdll})
26592@var{dllfile} is the name of the DLL. This switch must be present for
26593@code{gnatdll} to do anything. The name of the generated import library is
26594obtained algorithmically from @var{dllfile} as shown in the following
26595example: if @var{dllfile} is @code{xyz.dll}, the import library name is
26596@code{libxyz.a}. The name of the definition file to use (if not specified
26597by option @option{-e}) is obtained algorithmically from @var{dllfile}
26598as shown in the following example:
26599if @var{dllfile} is @code{xyz.dll}, the definition
26600file used is @code{xyz.def}.
26601
26602@item -e @var{deffile}
26603@cindex @option{-e} (@code{gnatdll})
26604@var{deffile} is the name of the definition file.
26605
26606@item -g
26607@cindex @option{-g} (@code{gnatdll})
26608Generate debugging information. This information is stored in the object
26609file and copied from there to the final DLL file by the linker,
26610where it can be read by the debugger. You must use the
26611@option{-g} switch if you plan on using the debugger or the symbolic
26612stack traceback.
26613
26614@item -h
26615@cindex @option{-h} (@code{gnatdll})
26616Help mode. Displays @code{gnatdll} switch usage information.
26617
26618@item -Idir
26619@cindex @option{-I} (@code{gnatdll})
26620Direct @code{gnatdll} to search the @var{dir} directory for source and
26621object files needed to build the DLL.
26622(@pxref{Search Paths and the Run-Time Library (RTL)}).
26623
26624@item -k
26625@cindex @option{-k} (@code{gnatdll})
26626Removes the @code{@@}@i{nn} suffix from the import library's exported
26627names. You must specified this option if you want to use a
26628@code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
26629has been removed. This is the case for most of the Windows NT DLL for
26630example. This option has no effect when @option{-n} option is specified.
26631
26632@item -l @var{file}
26633@cindex @option{-l} (@code{gnatdll})
26634The list of ALI and object files used to build the DLL are listed in
26635@var{file}, instead of being given in the command line. Each line in
26636@var{file} contains the name of an ALI or object file.
26637
26638@item -n
26639@cindex @option{-n} (@code{gnatdll})
26640No Import. Do not create the import library.
26641
26642@item -q
26643@cindex @option{-q} (@code{gnatdll})
26644Quiet mode. Do not display unnecessary messages.
26645
26646@item -v
26647@cindex @option{-v} (@code{gnatdll})
26648Verbose mode. Display extra information.
26649
26650@item -largs @var{opts}
26651@cindex @option{-largs} (@code{gnatdll})
26652Linker options. Pass @var{opts} to the linker.
26653@end table
26654
26655@node gnatdll Example
26656@subsubsection @code{gnatdll} Example
26657
26658@noindent
26659As an example the command to build a relocatable DLL from @file{api.adb}
26660once @file{api.adb} has been compiled and @file{api.def} created is
26661
26662@smallexample
26663$ gnatdll -d api.dll api.ali
26664@end smallexample
26665
26666@noindent
26667The above command creates two files: @file{libapi.a} (the import
26668library) and @file{api.dll} (the actual DLL). If you want to create
26669only the DLL, just type:
26670
26671@smallexample
26672$ gnatdll -d api.dll -n api.ali
26673@end smallexample
26674
26675@noindent
26676Alternatively if you want to create just the import library, type:
26677
26678@smallexample
26679$ gnatdll -d api.dll
26680@end smallexample
26681
26682@node gnatdll behind the Scenes
26683@subsubsection @code{gnatdll} behind the Scenes
26684
26685@noindent
26686This section details the steps involved in creating a DLL. @code{gnatdll}
26687does these steps for you. Unless you are interested in understanding what
26688goes on behind the scenes, you should skip this section.
26689
26690We use the previous example of a DLL containing the Ada package @code{API},
26691to illustrate the steps necessary to build a DLL. The starting point is a
26692set of objects that will make up the DLL and the corresponding ALI
26693files. In the case of this example this means that @file{api.o} and
26694@file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
26695the following:
26696
26697@enumerate
26698@item
26699@code{gnatdll} builds the base file (@file{api.base}). A base file gives
26700the information necessary to generate relocation information for the
26701DLL.
26702
26703@smallexample
26704@group
26705$ gnatbind -n api
26706$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
26707@end group
26708@end smallexample
26709
26710@noindent
26711In addition to the base file, the @code{gnatlink} command generates an
26712output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
26713asks @code{gnatlink} to generate the routines @code{DllMain} and
26714@code{DllMainCRTStartup} that are called by the Windows loader when the DLL
26715is loaded into memory.
26716
26717@item
26718@code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
26719export table (@file{api.exp}). The export table contains the relocation
26720information in a form which can be used during the final link to ensure
26721that the Windows loader is able to place the DLL anywhere in memory.
26722
26723@smallexample
26724@group
26725$ dlltool --dllname api.dll --def api.def --base-file api.base \
26726          --output-exp api.exp
26727@end group
26728@end smallexample
26729
26730@item
26731@code{gnatdll} builds the base file using the new export table. Note that
26732@code{gnatbind} must be called once again since the binder generated file
26733has been deleted during the previous call to @code{gnatlink}.
26734
26735@smallexample
26736@group
26737$ gnatbind -n api
26738$ gnatlink api -o api.jnk api.exp -mdll
26739      -Wl,--base-file,api.base
26740@end group
26741@end smallexample
26742
26743@item
26744@code{gnatdll} builds the new export table using the new base file and
26745generates the DLL import library @file{libAPI.a}.
26746
26747@smallexample
26748@group
26749$ dlltool --dllname api.dll --def api.def --base-file api.base \
26750          --output-exp api.exp --output-lib libAPI.a
26751@end group
26752@end smallexample
26753
26754@item
26755Finally @code{gnatdll} builds the relocatable DLL using the final export
26756table.
26757
26758@smallexample
26759@group
26760$ gnatbind -n api
26761$ gnatlink api api.exp -o api.dll -mdll
26762@end group
26763@end smallexample
26764@end enumerate
26765
26766@node Using dlltool
26767@subsubsection Using @code{dlltool}
26768
26769@noindent
26770@code{dlltool} is the low-level tool used by @code{gnatdll} to build
26771DLLs and static import libraries. This section summarizes the most
26772common @code{dlltool} switches. The form of the @code{dlltool} command
26773is
26774
26775@smallexample
26776$ dlltool [@var{switches}]
26777@end smallexample
26778
26779@noindent
26780@code{dlltool} switches include:
26781
26782@table @option
26783@item --base-file @var{basefile}
26784@cindex @option{--base-file} (@command{dlltool})
26785Read the base file @var{basefile} generated by the linker. This switch
26786is used to create a relocatable DLL.
26787
26788@item --def @var{deffile}
26789@cindex @option{--def} (@command{dlltool})
26790Read the definition file.
26791
26792@item --dllname @var{name}
26793@cindex @option{--dllname} (@command{dlltool})
26794Gives the name of the DLL. This switch is used to embed the name of the
26795DLL in the static import library generated by @code{dlltool} with switch
26796@option{--output-lib}.
26797
26798@item -k
26799@cindex @option{-k} (@command{dlltool})
26800Kill @code{@@}@i{nn} from exported names
26801(@pxref{Windows Calling Conventions}
26802for a discussion about @code{Stdcall}-style symbols.
26803
26804@item --help
26805@cindex @option{--help} (@command{dlltool})
26806Prints the @code{dlltool} switches with a concise description.
26807
26808@item --output-exp @var{exportfile}
26809@cindex @option{--output-exp} (@command{dlltool})
26810Generate an export file @var{exportfile}. The export file contains the
26811export table (list of symbols in the DLL) and is used to create the DLL.
26812
26813@item --output-lib @i{libfile}
26814@cindex @option{--output-lib} (@command{dlltool})
26815Generate a static import library @var{libfile}.
26816
26817@item -v
26818@cindex @option{-v} (@command{dlltool})
26819Verbose mode.
26820
26821@item --as @i{assembler-name}
26822@cindex @option{--as} (@command{dlltool})
26823Use @i{assembler-name} as the assembler. The default is @code{as}.
26824@end table
26825
26826@node GNAT and Windows Resources
26827@section GNAT and Windows Resources
26828@cindex Resources, windows
26829
26830@menu
26831* Building Resources::
26832* Compiling Resources::
26833* Using Resources::
26834@end menu
26835
26836@noindent
26837Resources are an easy way to add Windows specific objects to your
26838application. The objects that can be added as resources include:
26839
26840@itemize @bullet
26841@item
26842menus
26843
26844@item
26845accelerators
26846
26847@item
26848dialog boxes
26849
26850@item
26851string tables
26852
26853@item
26854bitmaps
26855
26856@item
26857cursors
26858
26859@item
26860icons
26861
26862@item
26863fonts
26864@end itemize
26865
26866@noindent
26867This section explains how to build, compile and use resources.
26868
26869@node Building Resources
26870@subsection Building Resources
26871@cindex Resources, building
26872
26873@noindent
26874A resource file is an ASCII file. By convention resource files have an
26875@file{.rc} extension.
26876The easiest way to build a resource file is to use Microsoft tools
26877such as @code{imagedit.exe} to build bitmaps, icons and cursors and
26878@code{dlgedit.exe} to build dialogs.
26879It is always possible to build an @file{.rc} file yourself by writing a
26880resource script.
26881
26882It is not our objective to explain how to write a resource file. A
26883complete description of the resource script language can be found in the
26884Microsoft documentation.
26885
26886@node Compiling Resources
26887@subsection Compiling Resources
26888@findex rc
26889@findex windres
26890@cindex Resources, compiling
26891
26892@noindent
26893This section describes how to build a GNAT-compatible (COFF) object file
26894containing the resources. This is done using the Resource Compiler
26895@code{windres} as follows:
26896
26897@smallexample
26898$ windres -i myres.rc -o myres.o
26899@end smallexample
26900
26901@noindent
26902By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
26903file. You can specify an alternate preprocessor (usually named
26904@file{cpp.exe}) using the @code{windres} @option{--preprocessor}
26905parameter. A list of all possible options may be obtained by entering
26906the command @code{windres} @option{--help}.
26907
26908It is also possible to use the Microsoft resource compiler @code{rc.exe}
26909to produce a @file{.res} file (binary resource file). See the
26910corresponding Microsoft documentation for further details. In this case
26911you need to use @code{windres} to translate the @file{.res} file to a
26912GNAT-compatible object file as follows:
26913
26914@smallexample
26915$ windres -i myres.res -o myres.o
26916@end smallexample
26917
26918@node Using Resources
26919@subsection Using Resources
26920@cindex Resources, using
26921
26922@noindent
26923To include the resource file in your program just add the
26924GNAT-compatible object file for the resource(s) to the linker
26925arguments. With @code{gnatmake} this is done by using the @option{-largs}
26926option:
26927
26928@smallexample
26929$ gnatmake myprog -largs myres.o
26930@end smallexample
26931
26932@node Debugging a DLL
26933@section Debugging a DLL
26934@cindex DLL debugging
26935
26936@menu
26937* Program and DLL Both Built with GCC/GNAT::
26938* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
26939@end menu
26940
26941@noindent
26942Debugging a DLL is similar to debugging a standard program. But
26943we have to deal with two different executable parts: the DLL and the
26944program that uses it. We have the following four possibilities:
26945
26946@enumerate 1
26947@item
26948The program and the DLL are built with @code{GCC/GNAT}.
26949@item
26950The program is built with foreign tools and the DLL is built with
26951@code{GCC/GNAT}.
26952@item
26953The program is built with @code{GCC/GNAT} and the DLL is built with
26954foreign tools.
26955@item
26956@end enumerate
26957
26958@noindent
26959In this section we address only cases one and two above.
26960There is no point in trying to debug
26961a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
26962information in it. To do so you must use a debugger compatible with the
26963tools suite used to build the DLL.
26964
26965@node Program and DLL Both Built with GCC/GNAT
26966@subsection Program and DLL Both Built with GCC/GNAT
26967
26968@noindent
26969This is the simplest case. Both the DLL and the program have @code{GDB}
26970compatible debugging information. It is then possible to break anywhere in
26971the process. Let's suppose here that the main procedure is named
26972@code{ada_main} and that in the DLL there is an entry point named
26973@code{ada_dll}.
26974
26975@noindent
26976The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
26977program must have been built with the debugging information (see GNAT -g
26978switch). Here are the step-by-step instructions for debugging it:
26979
26980@enumerate 1
26981@item Launch @code{GDB} on the main program.
26982
26983@smallexample
26984$ gdb -nw ada_main
26985@end smallexample
26986
26987@item Break on the main procedure and run the program.
26988
26989@smallexample
26990(gdb) break ada_main
26991(gdb) run
26992@end smallexample
26993
26994@noindent
26995This step is required to be able to set a breakpoint inside the DLL. As long
26996as the program is not run, the DLL is not loaded. This has the
26997consequence that the DLL debugging information is also not loaded, so it is not
26998possible to set a breakpoint in the DLL.
26999
27000@item Set a breakpoint inside the DLL
27001
27002@smallexample
27003(gdb) break ada_dll
27004(gdb) run
27005@end smallexample
27006
27007@end enumerate
27008
27009@noindent
27010At this stage a breakpoint is set inside the DLL. From there on
27011you can use the standard approach to debug the whole program
27012(@pxref{Running and Debugging Ada Programs}).
27013
27014@node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27015@subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27016
27017@menu
27018* Debugging the DLL Directly::
27019* Attaching to a Running Process::
27020@end menu
27021
27022@noindent
27023In this case things are slightly more complex because it is not possible to
27024start the main program and then break at the beginning to load the DLL and the
27025associated DLL debugging information. It is not possible to break at the
27026beginning of the program because there is no @code{GDB} debugging information,
27027and therefore there is no direct way of getting initial control. This
27028section addresses this issue by describing some methods that can be used
27029to break somewhere in the DLL to debug it.
27030
27031@noindent
27032First suppose that the main procedure is named @code{main} (this is for
27033example some C code built with Microsoft Visual C) and that there is a
27034DLL named @code{test.dll} containing an Ada entry point named
27035@code{ada_dll}.
27036
27037@noindent
27038The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27039been built with debugging information (see GNAT -g option).
27040
27041@node Debugging the DLL Directly
27042@subsubsection Debugging the DLL Directly
27043
27044@enumerate 1
27045@item
27046Launch the debugger on the DLL.
27047
27048@smallexample
27049$ gdb -nw test.dll
27050@end smallexample
27051
27052@item Set a breakpoint on a DLL subroutine.
27053
27054@smallexample
27055(gdb) break ada_dll
27056@end smallexample
27057
27058@item
27059Specify the executable file to @code{GDB}.
27060
27061@smallexample
27062(gdb) exec-file main.exe
27063@end smallexample
27064
27065@item
27066Run the program.
27067
27068@smallexample
27069(gdb) run
27070@end smallexample
27071
27072@noindent
27073This will run the program until it reaches the breakpoint that has been
27074set. From that point you can use the standard way to debug a program
27075as described in (@pxref{Running and Debugging Ada Programs}).
27076
27077@end enumerate
27078
27079@noindent
27080It is also possible to debug the DLL by attaching to a running process.
27081
27082@node Attaching to a Running Process
27083@subsubsection Attaching to a Running Process
27084@cindex DLL debugging, attach to process
27085
27086@noindent
27087With @code{GDB} it is always possible to debug a running process by
27088attaching to it. It is possible to debug a DLL this way. The limitation
27089of this approach is that the DLL must run long enough to perform the
27090attach operation. It may be useful for instance to insert a time wasting
27091loop in the code of the DLL to meet this criterion.
27092
27093@enumerate 1
27094
27095@item Launch the main program @file{main.exe}.
27096
27097@smallexample
27098$ main
27099@end smallexample
27100
27101@item Use the Windows @i{Task Manager} to find the process ID. Let's say
27102that the process PID for @file{main.exe} is 208.
27103
27104@item Launch gdb.
27105
27106@smallexample
27107$ gdb -nw
27108@end smallexample
27109
27110@item Attach to the running process to be debugged.
27111
27112@smallexample
27113(gdb) attach 208
27114@end smallexample
27115
27116@item Load the process debugging information.
27117
27118@smallexample
27119(gdb) symbol-file main.exe
27120@end smallexample
27121
27122@item Break somewhere in the DLL.
27123
27124@smallexample
27125(gdb) break ada_dll
27126@end smallexample
27127
27128@item Continue process execution.
27129
27130@smallexample
27131(gdb) continue
27132@end smallexample
27133
27134@end enumerate
27135
27136@noindent
27137This last step will resume the process execution, and stop at
27138the breakpoint we have set. From there you can use the standard
27139approach to debug a program as described in
27140(@pxref{Running and Debugging Ada Programs}).
27141
27142@node GNAT and COM/DCOM Objects
27143@section GNAT and COM/DCOM Objects
27144@findex COM
27145@findex DCOM
27146
27147@noindent
27148This section is temporarily left blank.
27149
27150@end ifset
27151
27152
27153@c **********************************
27154@c * GNU Free Documentation License *
27155@c **********************************
27156@include fdl.texi
27157@c GNU Free Documentation License
27158
27159@node Index,,GNU Free Documentation License, Top
27160@unnumbered Index
27161
27162@printindex cp
27163
27164@contents
27165@c Put table of contents at end, otherwise it precedes the "title page" in
27166@c the .txt version
27167@c Edit the pdf file to move the contents to the beginning, after the title
27168@c page
27169
27170@bye
27171