OSDN Git Service

7a3faa56a542ca97bc4aaaf5ff5846e3a0ffcb10
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ug_wnt.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                              G N A T _ U G                                 o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2002 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_UG 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
44 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
45 @c     command must be preceded by two empty lines
46 @c
47 @c  4. The @item command must be on a line of its own if it is in an
48 @c     @itemize or @enumerate command.
49 @c
50 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
51 @c     or "ali".
52 @c
53 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
54
55
56 @setfilename gnat_ug_wnt.info
57 @settitle GNAT User's Guide for Windows NT
58
59
60
61 @include gcc-common.texi
62
63 @setchapternewpage odd
64 @syncodeindex fn cp
65 @c %**end of header
66
67 @copying
68 Copyright @copyright{} 1995-2002, Free Software Foundation
69
70 Permission is granted to copy, distribute and/or modify this document
71 under the terms of the GNU Free Documentation License, Version 1.1
72 or any later version published by the Free Software Foundation;
73 with the Invariant Sections being ``GNU Free Documentation License'', with the
74 Front-Cover Texts being
75 ``GNAT User's Guide for Windows NT'',
76 and with no Back-Cover Texts.
77 A copy of the license is included in the section entitled ``GNU
78 Free Documentation License''.
79 @end copying
80
81 @titlepage
82
83
84 @title GNAT User's Guide
85 @center @titlefont{for Windows NT}
86
87
88
89 @subtitle GNAT, The GNU Ada 95 Compiler
90 @subtitle GNAT Version for GCC @value{version-GCC}
91
92 @author Ada Core Technologies, Inc.
93
94 @page
95 @vskip 0pt plus 1filll
96
97 @insertcopying
98
99 @end titlepage
100
101 @ifnottex
102 @node Top, About This Guide, (dir), (dir)
103 @top GNAT User's Guide
104
105
106 GNAT User's Guide for Windows NT
107
108
109
110 GNAT, The GNU Ada 95 Compiler
111
112 GNAT Version for GCC @value{version-GCC}
113
114 Ada Core Technologies, Inc.
115
116 @insertcopying
117
118 @menu
119 * About This Guide::
120 * Getting Started with GNAT::
121 * The GNAT Compilation Model::
122 * Compiling Using gcc::
123 * Binding Using gnatbind::
124 * Linking Using gnatlink::
125 * The GNAT Make Program gnatmake::
126 * Renaming Files Using gnatchop::
127 * Configuration Pragmas::
128 * Handling Arbitrary File Naming Conventions Using gnatname::
129 * GNAT Project Manager::
130 * Elaboration Order Handling in GNAT::
131 * The Cross-Referencing Tools gnatxref and gnatfind::
132 * File Name Krunching Using gnatkr::
133 * Preprocessing Using gnatprep::
134 * The GNAT Library Browser gnatls::
135 * GNAT and Libraries::
136 * Using the GNU make Utility::
137 * Finding Memory Problems with gnatmem::
138 * Finding Memory Problems with GNAT Debug Pool::
139 * Creating Sample Bodies Using gnatstub::
140 * Reducing the Size of Ada Executables with gnatelim::
141 * Other Utility Programs::
142 * Running and Debugging Ada Programs::
143 * Inline Assembler::
144 * Microsoft Windows Topics::
145 * Performance Considerations::
146 * GNU Free Documentation License::
147 * Index::
148
149  --- The Detailed Node Listing ---
150
151 About This Guide
152
153 * What This Guide Contains::
154 * What You Should Know before Reading This Guide::
155 * Related Information::
156 * Conventions::
157
158
159 Getting Started with GNAT
160
161 * Running GNAT::
162 * Running a Simple Ada Program::
163 * Running a Program with Multiple Units::
164 * Using the gnatmake Utility::
165
166 The GNAT Compilation Model
167
168 * Source Representation::
169 * Foreign Language Representation::
170 * File Naming Rules::
171 * Using Other File Names::
172 * Alternative File Naming Schemes::
173 * Generating Object Files::
174 * Source Dependencies::
175 * The Ada Library Information Files::
176 * Binding an Ada Program::
177 * Mixed Language Programming::
178 * Building Mixed Ada & C++ Programs::
179 * Comparison between GNAT and C/C++ Compilation Models::
180 * Comparison between GNAT and Conventional Ada Library Models::
181
182 Foreign Language Representation
183
184 * Latin-1::
185 * Other 8-Bit Codes::
186 * Wide Character Encodings::
187
188 Compiling Ada Programs With gcc
189
190 * Compiling Programs::
191 * Switches for gcc::
192 * Search Paths and the Run-Time Library (RTL)::
193 * Order of Compilation Issues::
194 * Examples::
195
196 Switches for gcc
197
198 * Output and Error Message Control::
199 * Debugging and Assertion Control::
200 * Run-Time Checks::
201 * Stack Overflow Checking::
202 * Run-Time Control::
203 * Validity Checking::
204 * Style Checking::
205 * Using gcc for Syntax Checking::
206 * Using gcc for Semantic Checking::
207 * Compiling Ada 83 Programs::
208 * Character Set Control::
209 * File Naming Control::
210 * Subprogram Inlining Control::
211 * Auxiliary Output Control::
212 * Debugging Control::
213 * Units to Sources Mapping Files::
214
215 Binding Ada Programs With gnatbind
216
217 * Running gnatbind::
218 * Generating the Binder Program in C::
219 * Consistency-Checking Modes::
220 * Binder Error Message Control::
221 * Elaboration Control::
222 * Output Control::
223 * Binding with Non-Ada Main Programs::
224 * Binding Programs with No Main Subprogram::
225 * Summary of Binder Switches::
226 * Command-Line Access::
227 * Search Paths for gnatbind::
228 * Examples of gnatbind Usage::
229
230 Linking Using gnatlink
231
232 * Running gnatlink::
233 * Switches for gnatlink::
234 * Setting Stack Size from gnatlink::
235 * Setting Heap Size from gnatlink::
236
237 The GNAT Make Program gnatmake
238
239 * Running gnatmake::
240 * Switches for gnatmake::
241 * Mode Switches for gnatmake::
242 * Notes on the Command Line::
243 * How gnatmake Works::
244 * Examples of gnatmake Usage::
245
246 Renaming Files Using gnatchop
247
248 * Handling Files with Multiple Units::
249 * Operating gnatchop in Compilation Mode::
250 * Command Line for gnatchop::
251 * Switches for gnatchop::
252 * Examples of gnatchop Usage::
253
254 Configuration Pragmas
255
256 * Handling of Configuration Pragmas::
257 * The Configuration Pragmas Files::
258
259 Handling Arbitrary File Naming Conventions Using gnatname
260
261 * Arbitrary File Naming Conventions::
262 * Running gnatname::
263 * Switches for gnatname::
264 * Examples of gnatname Usage::
265
266 GNAT Project Manager
267
268 * Introduction::
269 * Examples of Project Files::
270 * Project File Syntax::
271 * Objects and Sources in Project Files::
272 * Importing Projects::
273 * Project Extension::
274 * External References in Project Files::
275 * Packages in Project Files::
276 * Variables from Imported Projects::
277 * Naming Schemes::
278 * Library Projects::
279 * Switches Related to Project Files::
280 * Tools Supporting Project Files::
281 * An Extended Example::
282 * Project File Complete Syntax::
283
284 Elaboration Order Handling in GNAT
285
286 * Elaboration Code in Ada 95::
287 * Checking the Elaboration Order in Ada 95::
288 * Controlling the Elaboration Order in Ada 95::
289 * Controlling Elaboration in GNAT - Internal Calls::
290 * Controlling Elaboration in GNAT - External Calls::
291 * Default Behavior in GNAT - Ensuring Safety::
292 * Elaboration Issues for Library Tasks::
293 * Mixing Elaboration Models::
294 * What to Do If the Default Elaboration Behavior Fails::
295 * Elaboration for Access-to-Subprogram Values::
296 * Summary of Procedures for Elaboration Control::
297 * Other Elaboration Order Considerations::
298
299 The Cross-Referencing Tools gnatxref and gnatfind
300
301 * gnatxref Switches::
302 * gnatfind Switches::
303 * Project Files for gnatxref and gnatfind::
304 * Regular Expressions in gnatfind and gnatxref::
305 * Examples of gnatxref Usage::
306 * Examples of gnatfind Usage::
307
308 File Name Krunching Using gnatkr
309
310 * About gnatkr::
311 * Using gnatkr::
312 * Krunching Method::
313 * Examples of gnatkr Usage::
314
315 Preprocessing Using gnatprep
316
317 * Using gnatprep::
318 * Switches for gnatprep::
319 * Form of Definitions File::
320 * Form of Input Text for gnatprep::
321
322
323 The GNAT Library Browser gnatls
324
325 * Running gnatls::
326 * Switches for gnatls::
327 * Examples of gnatls Usage::
328
329
330 GNAT and Libraries
331
332 * Creating an Ada Library::
333 * Installing an Ada Library::
334 * Using an Ada Library::
335 * Creating an Ada Library to be Used in a Non-Ada Context::
336 * Rebuilding the GNAT Run-Time Library::
337
338 Using the GNU make Utility
339
340 * Using gnatmake in a Makefile::
341 * Automatically Creating a List of Directories::
342 * Generating the Command Line Switches::
343 * Overcoming Command Line Length Limits::
344
345 Finding Memory Problems with gnatmem
346
347 * Running gnatmem (GDB Mode)::
348 * Running gnatmem (GMEM Mode)::
349 * Switches for gnatmem::
350 * Examples of gnatmem Usage::
351 * GDB and GMEM Modes::
352 * Implementation Note::
353
354
355 Finding Memory Problems with GNAT Debug Pool
356
357 Creating Sample Bodies Using gnatstub
358
359 * Running gnatstub::
360 * Switches for gnatstub::
361
362 Reducing the Size of Ada Executables with gnatelim
363
364 * About gnatelim::
365 * Eliminate Pragma::
366 * Tree Files::
367 * Preparing Tree and Bind Files for gnatelim::
368 * Running gnatelim::
369 * Correcting the List of Eliminate Pragmas::
370 * Making Your Executables Smaller::
371 * Summary of the gnatelim Usage Cycle::
372
373 Other Utility Programs
374
375 * Using Other Utility Programs with GNAT::
376 * The gnatpsta Utility Program::
377 * The External Symbol Naming Scheme of GNAT::
378 * Ada Mode for Glide::
379 * Converting Ada Files to html with gnathtml::
380
381
382 Running and Debugging Ada Programs
383
384 * The GNAT Debugger GDB::
385 * Running GDB::
386 * Introduction to GDB Commands::
387 * Using Ada Expressions::
388 * Calling User-Defined Subprograms::
389 * Using the Next Command in a Function::
390 * Ada Exceptions::
391 * Ada Tasks::
392 * Debugging Generic Units::
393 * GNAT Abnormal Termination or Failure to Terminate::
394 * Naming Conventions for GNAT Source Files::
395 * Getting Internal Debugging Information::
396 * Stack Traceback::
397
398 Inline Assembler
399
400 * Basic Assembler Syntax::
401 * A Simple Example of Inline Assembler::
402 * Output Variables in Inline Assembler::
403 * Input Variables in Inline Assembler::
404 * Inlining Inline Assembler Code::
405 * Other Asm Functionality::
406 * A Complete Example::
407
408 Microsoft Windows Topics
409
410 * Using GNAT on Windows::
411 * GNAT Setup Tool::
412 * CONSOLE and WINDOWS subsystems::
413 * Temporary Files::
414 * Mixed-Language Programming on Windows::
415 * Windows Calling Conventions::
416 * Introduction to Dynamic Link Libraries (DLLs)::
417 * Using DLLs with GNAT::
418 * Building DLLs with GNAT::
419 * GNAT and Windows Resources::
420 * GNAT and COM/DCOM Objects::
421
422
423 Performance Considerations
424
425 * Controlling Run-Time Checks::
426 * Optimization Levels::
427 * Debugging Optimized Code::
428 * Inlining of Subprograms::
429
430 * Index::
431 @end menu
432 @end ifnottex
433
434 @node About This Guide
435 @unnumbered About This Guide
436
437 @noindent
438 This guide describes the use of GNAT, a compiler and software development
439 toolset for the full Ada 95 programming language.
440 It describes the features of the compiler and tools, and details
441 how to use them to build Ada 95 applications.
442
443 @menu
444 * What This Guide Contains::
445 * What You Should Know before Reading This Guide::
446 * Related Information::
447 * Conventions::
448 @end menu
449
450 @node What This Guide Contains
451 @unnumberedsec What This Guide Contains
452
453 @noindent
454 This guide contains the following chapters:
455 @itemize @bullet
456 @item
457 @ref{Getting Started with GNAT}, describes how to get started compiling
458 and running Ada programs with the GNAT Ada programming environment.
459 @item
460 @ref{The GNAT Compilation Model}, describes the compilation model used
461 by GNAT.
462 @item
463 @ref{Compiling Using gcc}, describes how to compile
464 Ada programs with @code{gcc}, the Ada compiler.
465 @item
466 @ref{Binding Using gnatbind}, describes how to
467 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
468 utility.
469 @item
470 @ref{Linking Using gnatlink},
471 describes @code{gnatlink}, a
472 program that provides for linking using the GNAT run-time library to
473 construct a program. @code{gnatlink} can also incorporate foreign language
474 object units into the executable.
475 @item
476 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
477 utility that automatically determines the set of sources
478 needed by an Ada compilation unit, and executes the necessary compilations
479 binding and link.
480 @item
481 @ref{Renaming Files Using gnatchop}, describes
482 @code{gnatchop}, a utility that allows you to preprocess a file that
483 contains Ada source code, and split it into one or more new files, one
484 for each compilation unit.
485 @item
486 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
487 @item
488 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
489 the default GNAT file naming conventions, either for an individual unit or globally.
490 @item
491 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
492 @item
493 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
494 elaboration order issues.
495 @item
496 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
497 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
498 way to navigate through sources.
499 @item
500 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
501 file name krunching utility, used to handle shortened
502 file names on operating systems with a limit on the length of names.
503 @item
504 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
505 preprocessor utility that allows a single source file to be used to
506 generate multiple or parameterized source files, by means of macro
507 substitution.
508 @item
509 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
510 utility that displays information about compiled units, including dependences
511 on the corresponding sources files, and consistency of compilations.
512 @item
513 @ref{GNAT and Libraries}, describes the process of creating and using
514 Libraries with GNAT. It also describes how to recompile the GNAT run-time
515 library.
516
517 @item
518 @ref{Using the GNU make Utility}, describes some techniques for using
519 the GNAT toolset in Makefiles.
520
521 @item
522 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
523 utility that monitors dynamic allocation and deallocation activity in a
524 program, and displays information about incorrect deallocations and sources
525 of possible memory leaks.
526 @item
527 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
528 use the GNAT-specific Debug Pool in order to detect as early as possible
529 the use of incorrect memory references.
530
531 @item
532 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
533 a utility that generates empty but compilable bodies for library units.
534
535 @item
536 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
537 @code{gnatelim}, a tool which detects unused subprograms and helps
538 the compiler to create a smaller executable for the program.
539
540 @item
541 @ref{Other Utility Programs}, discusses several other GNAT utilities,
542 including @code{gnatpsta}.
543
544 @item
545 @ref{Running and Debugging Ada Programs}, describes how to run and debug
546 Ada programs.
547
548 @item
549 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
550
551
552 @item
553 @ref{Performance Considerations}, reviews the trade offs between using
554 defaults or options in program development.
555 @end itemize
556
557 @node What You Should Know before Reading This Guide
558 @unnumberedsec What You Should Know before Reading This Guide
559
560 @cindex Ada 95 Language Reference Manual
561 @noindent
562 This user's guide assumes that you are familiar with Ada 95 language, as
563 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
564 1995.
565
566 @node Related Information
567 @unnumberedsec Related Information
568
569 @noindent
570 For further information about related tools, refer to the following
571 documents:
572
573 @itemize @bullet
574 @item
575 @cite{GNAT Reference Manual}, which contains all reference
576 material for the GNAT implementation of Ada 95.
577
578 @item
579 @cite{Ada 95 Language Reference Manual}, which contains all reference
580 material for the Ada 95 programming language.
581
582 @item
583 @cite{Debugging with GDB}
584 contains all details on the use of the GNU source-level debugger.
585
586 @item
587 @cite{GNU Emacs Manual}
588 contains full information on the extensible editor and programming
589 environment Emacs.
590
591 @end itemize
592
593 @node Conventions
594 @unnumberedsec Conventions
595 @cindex Conventions
596 @cindex Typographical conventions
597
598 @noindent
599 Following are examples of the typographical and graphic conventions used
600 in this guide:
601
602 @itemize @bullet
603 @item
604 @code{Functions}, @code{utility program names}, @code{standard names},
605 and @code{classes}.
606
607 @item
608 @samp{Option flags}
609
610 @item
611 @file{File Names}, @file{button names}, and @file{field names}.
612
613 @item
614 @var{Variables}.
615
616 @item
617 @emph{Emphasis}.
618
619 @item
620 [optional information or parameters]
621
622 @item
623 Examples are described by text
624 @smallexample
625 and then shown this way.
626 @end smallexample
627 @end itemize
628
629 @noindent
630 Commands that are entered by the user are preceded in this manual by the
631 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
632 uses this sequence as a prompt, then the commands will appear exactly as
633 you see them in the manual. If your system uses some other prompt, then
634 the command will appear with the @code{$} replaced by whatever prompt
635 character you are using.
636
637
638 @node Getting Started with GNAT
639 @chapter Getting Started with GNAT
640
641 @noindent
642 This chapter describes some simple ways of using GNAT to build
643 executable Ada programs.
644
645 @menu
646 * Running GNAT::
647 * Running a Simple Ada Program::
648
649 * Running a Program with Multiple Units::
650
651 * Using the gnatmake Utility::
652 * Introduction to Glide and GVD::
653 @end menu
654
655 @node Running GNAT
656 @section Running GNAT
657
658 @noindent
659 Three steps are needed to create an executable file from an Ada source
660 file:
661
662 @enumerate
663 @item
664 The source file(s) must be compiled.
665 @item
666 The file(s) must be bound using the GNAT binder.
667 @item
668 All appropriate object files must be linked to produce an executable.
669 @end enumerate
670
671 @noindent
672 All three steps are most commonly handled by using the @code{gnatmake}
673 utility program that, given the name of the main program, automatically
674 performs the necessary compilation, binding and linking steps.
675
676 @node Running a Simple Ada Program
677 @section Running a Simple Ada Program
678
679 @noindent
680 Any text editor may be used to prepare an Ada program. If @code{Glide} is
681 used, the optional Ada mode may be helpful in laying out the program. The
682 program text is a normal text file. We will suppose in our initial
683 example that you have used your editor to prepare the following
684 standard format text file:
685
686 @smallexample
687 @group
688 @cartouche
689 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
690 @b{procedure} Hello @b{is}
691 @b{begin}
692    Put_Line ("Hello WORLD!");
693 @b{end} Hello;
694 @end cartouche
695 @end group
696 @end smallexample
697
698 @noindent
699 This file should be named @file{hello.adb}.
700 With the normal default file naming conventions, GNAT requires
701 that each file
702 contain a single compilation unit whose file name is the
703 unit name,
704 with periods replaced by hyphens; the
705 extension is @file{ads} for a
706 spec and @file{adb} for a body.
707 You can override this default file naming convention by use of the
708 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
709 Alternatively, if you want to rename your files according to this default
710 convention, which is probably more convenient if you will be using GNAT
711 for all your compilations, then the @code{gnatchop} utility
712 can be used to generate correctly-named source files
713 (@pxref{Renaming Files Using gnatchop}).
714
715 You can compile the program using the following command (@code{$} is used
716 as the command prompt in the examples in this document):
717
718 @smallexample
719 $ gcc -c hello.adb
720 @end smallexample
721
722
723 @noindent
724 @code{gcc} is the command used to run the compiler. This compiler is
725 capable of compiling programs in several languages, including Ada 95 and
726 C. It assumes that you have given it an Ada program if the file extension is
727 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
728 the specified file.
729
730 The @option{-c} switch is required. It tells @command{gcc} to only do a
731 compilation. (For C programs, @command{gcc} can also do linking, but this
732 capability is not used directly for Ada programs, so the @option{-c}
733 switch must always be present.)
734
735 This compile command generates a file
736 @file{hello.o}, which is the object
737 file corresponding to your Ada program. It also generates an "Ada Library Information" file
738 @file{hello.ali},
739 which contains additional information used to check
740 that an Ada program is consistent.
741 To build an executable file,
742 use @code{gnatbind} to bind the program
743 and @code{gnatlink} to link it. The
744 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
745 @file{ali} file, but the default extension of @file{.ali} can
746 be omitted. This means that in the most common case, the argument
747 is simply the name of the main program:
748
749 @smallexample
750 $ gnatbind hello
751 $ gnatlink hello
752 @end smallexample
753
754
755 @noindent
756 A simpler method of carrying out these steps is to use
757 @command{gnatmake},
758 a master program that invokes all the required
759 compilation, binding and linking tools in the correct order. In particular,
760 @command{gnatmake} automatically recompiles any sources that have been modified
761 since they were last compiled, or sources that depend
762 on such modified sources, so that "version skew" is avoided.
763 @cindex Version skew (avoided by @command{gnatmake})
764
765 @smallexample
766 $ gnatmake hello.adb
767 @end smallexample
768
769
770 @noindent
771 The result is an executable program called @file{hello}, which can be
772 run by entering:
773
774 @c The following should be removed (BMB 2001-01-23)
775 @c @smallexample
776 @c $ ./hello
777 @c @end smallexample
778
779 @smallexample
780 $ hello
781 @end smallexample
782
783 @noindent
784 assuming that the current directory is on the search path for executable programs.
785
786 @noindent
787 and, if all has gone well, you will see
788
789 @smallexample
790 Hello WORLD!
791 @end smallexample
792
793 @noindent
794 appear in response to this command.
795
796
797
798
799 @node Running a Program with Multiple Units
800 @section Running a Program with Multiple Units
801
802 @noindent
803 Consider a slightly more complicated example that has three files: a
804 main program, and the spec and body of a package:
805
806 @smallexample
807 @cartouche
808 @group
809 @b{package} Greetings @b{is}
810    @b{procedure} Hello;
811    @b{procedure} Goodbye;
812 @b{end} Greetings;
813
814 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
815 @b{package} @b{body} Greetings @b{is}
816    @b{procedure} Hello @b{is}
817    @b{begin}
818       Put_Line ("Hello WORLD!");
819    @b{end} Hello;
820
821    @b{procedure} Goodbye @b{is}
822    @b{begin}
823       Put_Line ("Goodbye WORLD!");
824    @b{end} Goodbye;
825 @b{end} Greetings;
826 @end group
827
828 @group
829 @b{with} Greetings;
830 @b{procedure} Gmain @b{is}
831 @b{begin}
832    Greetings.Hello;
833    Greetings.Goodbye;
834 @b{end} Gmain;
835 @end group
836 @end cartouche
837 @end smallexample
838
839 @noindent
840 Following the one-unit-per-file rule, place this program in the
841 following three separate files:
842
843 @table @file
844 @item greetings.ads
845 spec of package @code{Greetings}
846
847 @item greetings.adb
848 body of package @code{Greetings}
849
850 @item gmain.adb
851 body of main program
852 @end table
853
854 @noindent
855 To build an executable version of
856 this program, we could use four separate steps to compile, bind, and link
857 the program, as follows:
858
859 @smallexample
860 $ gcc -c gmain.adb
861 $ gcc -c greetings.adb
862 $ gnatbind gmain
863 $ gnatlink gmain
864 @end smallexample
865
866
867 @noindent
868 Note that there is no required order of compilation when using GNAT.
869 In particular it is perfectly fine to compile the main program first.
870 Also, it is not necessary to compile package specs in the case where
871 there is an accompanying body; you only need to compile the body. If you want
872 to submit these files to the compiler for semantic checking and not code generation,
873 then use the
874 @option{-gnatc} switch:
875
876 @smallexample
877    $ gcc -c greetings.ads -gnatc
878 @end smallexample
879
880
881 @noindent
882 Although the compilation can be done in separate steps as in the
883 above example, in practice it is almost always more convenient
884 to use the @code{gnatmake} tool. All you need to know in this case
885 is the name of the main program's source file. The effect of the above four
886 commands can be achieved with a single one:
887
888 @smallexample
889 $ gnatmake gmain.adb
890 @end smallexample
891
892
893 @noindent
894 In the next section we discuss the advantages of using @code{gnatmake} in
895 more detail.
896
897 @node Using the gnatmake Utility
898 @section Using the @command{gnatmake} Utility
899
900 @noindent
901 If you work on a program by compiling single components at a time using
902 @code{gcc}, you typically keep track of the units you modify. In order to
903 build a consistent system, you compile not only these units, but also any
904 units that depend on the units you have modified.
905 For example, in the preceding case,
906 if you edit @file{gmain.adb}, you only need to recompile that file. But if
907 you edit @file{greetings.ads}, you must recompile both
908 @file{greetings.adb} and @file{gmain.adb}, because both files contain
909 units that depend on @file{greetings.ads}.
910
911 @code{gnatbind} will warn you if you forget one of these compilation
912 steps, so that it is impossible to generate an inconsistent program as a
913 result of forgetting to do a compilation. Nevertheless it is tedious and
914 error-prone to keep track of dependencies among units.
915 One approach to handle the dependency-bookkeeping is to use a
916 makefile. However, makefiles present maintenance problems of their own:
917 if the dependencies change as you change the program, you must make
918 sure that the makefile is kept up-to-date manually, which is also an
919 error-prone process.
920
921 The @code{gnatmake} utility takes care of these details automatically.
922 Invoke it using either one of the following forms:
923
924 @smallexample
925 $ gnatmake gmain.adb
926 $ gnatmake gmain
927 @end smallexample
928
929
930 @noindent
931 The argument is the name of the file containing the main program;
932 you may omit the extension. @code{gnatmake}
933 examines the environment, automatically recompiles any files that need
934 recompiling, and binds and links the resulting set of object files,
935 generating the executable file, @file{gmain}.
936 In a large program, it
937 can be extremely helpful to use @code{gnatmake}, because working out by hand
938 what needs to be recompiled can be difficult.
939
940 Note that @code{gnatmake}
941 takes into account all the Ada 95 rules that
942 establish dependencies among units. These include dependencies that result
943 from inlining subprogram bodies, and from
944 generic instantiation. Unlike some other
945 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
946 found by the compiler on a previous compilation, which may possibly
947 be wrong when sources change. @code{gnatmake} determines the exact set of
948 dependencies from scratch each time it is run.
949
950
951 @node Introduction to Glide and GVD
952 @section Introduction to Glide and GVD
953 @cindex Glide
954 @cindex GVD
955 @noindent
956 Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs.  This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger.  Additional information may be found in the on-line help for these tools.
957
958 @menu
959 * Building a New Program with Glide::
960 * Simple Debugging with GVD::
961 * Other Glide Features::
962 @end menu
963
964 @node Building a New Program with Glide
965 @subsection Building a New Program with Glide
966 @noindent
967 The simplest way to invoke Glide is to enter @command{glide} at the command prompt.  It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running:
968
969 @smallexample
970 $ glide&
971 @end smallexample
972
973 @noindent
974 Glide will start up with an initial screen displaying the top-level menu items as well as some other information.  The menu selections are as follows
975 @itemize @bullet
976 @item @code{Buffers}
977 @item @code{Files}
978 @item @code{Tools}
979 @item @code{Edit}
980 @item @code{Search}
981 @item @code{Mule}
982 @item @code{Glide}
983 @item @code{Help}
984 @end itemize
985
986 @noindent
987 For this introductory example, you will need to create a new Ada source file.  First, select the @code{Files} menu.  This will pop open a menu with around a dozen or so items.  To create a file, select the @code{Open file...} choice.  Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name.  Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name.  For this example enter @file{hello.adb} as the name of the file.
988
989 A new buffer will now appear, occupying the entire Glide window, with the file name at the top.  The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file.
990
991 You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines.  First, type the following text:
992 @smallexample
993 with Ada.Text_IO; use Ada.Text_IO;
994 procedure Hello is
995 begin
996 @end smallexample
997
998 @noindent
999 Observe that Glide uses different colors to distinguish reserved words from identifiers.  Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations.  When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left.  But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed.
1000
1001 The main part of the program will be a @code{for} loop.  Instead of entering the text explicitly, however, use a statement template.  Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives.  Choose @code{for loop}.  You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed.  You should see the beginning of a @code{for} loop appear in the source program window.  You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case).  Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction).  Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax.
1002
1003 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1004 @smallexample
1005 Put_Line("Hello, World" & Integer'Image(I))
1006 @end smallexample
1007
1008 @noindent
1009 Finally, type @code{end Hello;} as the last line in the program.  Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection.  You will see a message at the bottom of the buffer confirming that the file has been saved.
1010
1011 You are now ready to attempt to build the program.  Select the @code{Ada} item from the top menu bar.  Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable.  Thus select @code{Ada build}.  This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools.  Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window.  The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected.
1012
1013 Correct the error: type in a semicolon to terminate the statement.  Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file.  This time the build will succeed; the tool output window shows you the options that are supplied by default.  The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched.
1014
1015 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1016
1017 @smallexample
1018 Hello, world 1
1019 Hello, world 2
1020 Hello, world 3
1021 Hello, world 4
1022 Hello, world 5
1023 @end smallexample
1024
1025 @node Simple Debugging with GVD
1026 @subsection Simple Debugging with GVD
1027
1028 @noindent
1029 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1030
1031 In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}.  If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect.  You can then launch GVD, e.g. on the @code{hello} program, by issuing the command:
1032
1033 @smallexample
1034 $ gvd hello
1035 @end smallexample
1036
1037 @noindent
1038 If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build.  Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}.
1039
1040 GVD comes up in a multi-part window.  One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected.
1041
1042 To the left of the source file pane, you will notice green dots adjacent to some lines.  These are lines for which object code exists and where breakpoints can thus be set.  You set/reset a breakpoint by clicking the green dot.  When a breakpoint is set, the dot is replaced by an @code{X} in a red circle.  Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.
1043
1044 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1045
1046 Start program execution by selecting the @code{Run} button on the top menu bar.  (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.)  Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message.
1047
1048 You can examine the values of variables in several ways.  Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas.
1049
1050 Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger.  Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item.  Enter @code{2} as the new value, and press @command{OK}.  The box for @code{Ind} shows the update.
1051
1052 Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}.
1053
1054 Remove the breakpoint, and resume execution by selecting the @code{Cont} button.  You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.
1055
1056
1057 @node Other Glide Features
1058 @subsection Other Glide Features
1059
1060 @noindent
1061 You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.  These are @emph{shortcut keys} that you can use instead of selecting menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}.
1062
1063 To abort a Glide command, type @key{Ctrl-g}.
1064
1065 If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line:
1066
1067 @smallexample
1068 $ glide hello.adb&
1069 @end smallexample
1070
1071 @noindent
1072 While you are using Glide, a number of @emph{buffers} exist.  You create some explicitly; e.g., when you open/create a file.  Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build.  If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry.
1073
1074 If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}.
1075
1076 If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps:
1077 @itemize @bullet
1078 @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents)
1079 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1080 @end itemize
1081
1082 @noindent
1083 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1084
1085 @node The GNAT Compilation Model
1086 @chapter The GNAT Compilation Model
1087 @cindex GNAT compilation model
1088 @cindex Compilation model
1089
1090 @menu
1091 * Source Representation::
1092 * Foreign Language Representation::
1093 * File Naming Rules::
1094 * Using Other File Names::
1095 * Alternative File Naming Schemes::
1096 * Generating Object Files::
1097 * Source Dependencies::
1098 * The Ada Library Information Files::
1099 * Binding an Ada Program::
1100 * Mixed Language Programming::
1101 * Building Mixed Ada & C++ Programs::
1102 * Comparison between GNAT and C/C++ Compilation Models::
1103 * Comparison between GNAT and Conventional Ada Library Models::
1104 @end menu
1105
1106 @noindent
1107 This chapter describes the compilation model used by GNAT. Although
1108 similar to that used by other languages, such as C and C++, this model
1109 is substantially different from the traditional Ada compilation models,
1110 which are based on a library. The model is initially described without
1111 reference to the library-based model. If you have not previously used an
1112 Ada compiler, you need only read the first part of this chapter. The
1113 last section describes and discusses the differences between the GNAT
1114 model and the traditional Ada compiler models. If you have used other
1115 Ada compilers, this section will help you to understand those
1116 differences, and the advantages of the GNAT model.
1117
1118 @node Source Representation
1119 @section Source Representation
1120 @cindex Latin-1
1121
1122 @noindent
1123 Ada source programs are represented in standard text files, using
1124 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1125 7-bit ASCII set, plus additional characters used for
1126 representing foreign languages (@pxref{Foreign Language Representation}
1127 for support of non-USA character sets). The format effector characters
1128 are represented using their standard ASCII encodings, as follows:
1129
1130 @table @code
1131 @item VT
1132 @findex VT
1133 Vertical tab, @code{16#0B#}
1134
1135 @item HT
1136 @findex HT
1137 Horizontal tab, @code{16#09#}
1138
1139 @item CR
1140 @findex CR
1141 Carriage return, @code{16#0D#}
1142
1143 @item LF
1144 @findex LF
1145 Line feed, @code{16#0A#}
1146
1147 @item FF
1148 @findex FF
1149 Form feed, @code{16#0C#}
1150 @end table
1151
1152 @noindent
1153 Source files are in standard text file format. In addition, GNAT will
1154 recognize a wide variety of stream formats, in which the end of physical
1155 physical lines is marked by any of the following sequences:
1156 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1157 in accommodating files that are imported from other operating systems.
1158
1159 @cindex End of source file
1160 @cindex Source file, end
1161 @findex SUB
1162 The end of a source file is normally represented by the physical end of
1163 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1164 recognized as signalling the end of the source file. Again, this is
1165 provided for compatibility with other operating systems where this
1166 code is used to represent the end of file.
1167
1168 Each file contains a single Ada compilation unit, including any pragmas
1169 associated with the unit. For example, this means you must place a
1170 package declaration (a package @dfn{spec}) and the corresponding body in
1171 separate files. An Ada @dfn{compilation} (which is a sequence of
1172 compilation units) is represented using a sequence of files. Similarly,
1173 you will place each subunit or child unit in a separate file.
1174
1175 @node Foreign Language Representation
1176 @section Foreign Language Representation
1177
1178 @noindent
1179 GNAT supports the standard character sets defined in Ada 95 as well as
1180 several other non-standard character sets for use in localized versions
1181 of the compiler (@pxref{Character Set Control}).
1182 @menu
1183 * Latin-1::
1184 * Other 8-Bit Codes::
1185 * Wide Character Encodings::
1186 @end menu
1187
1188 @node Latin-1
1189 @subsection Latin-1
1190 @cindex Latin-1
1191
1192 @noindent
1193 The basic character set is Latin-1. This character set is defined by ISO
1194 standard 8859, part 1. The lower half (character codes @code{16#00#}
1195 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1196 used to represent additional characters. These include extended letters
1197 used by European languages, such as French accents, the vowels with umlauts
1198 used in German, and the extra letter A-ring used in Swedish.
1199
1200 @findex Ada.Characters.Latin_1
1201 For a complete list of Latin-1 codes and their encodings, see the source
1202 file of library unit @code{Ada.Characters.Latin_1} in file
1203 @file{a-chlat1.ads}.
1204 You may use any of these extended characters freely in character or
1205 string literals. In addition, the extended characters that represent
1206 letters can be used in identifiers.
1207
1208 @node Other 8-Bit Codes
1209 @subsection Other 8-Bit Codes
1210
1211 @noindent
1212 GNAT also supports several other 8-bit coding schemes:
1213
1214 @table @asis
1215 @cindex Latin-2
1216 @item Latin-2
1217 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1218 equivalence.
1219
1220 @item Latin-3
1221 @cindex Latin-3
1222 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1223 equivalence.
1224
1225 @item Latin-4
1226 @cindex Latin-4
1227 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1228 equivalence.
1229
1230 @item Latin-5
1231 @cindex Latin-5
1232 @cindex Cyrillic
1233 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1234 equivalence.
1235
1236 @item IBM PC (code page 437)
1237 @cindex code page 437
1238 This code page is the normal default for PCs in the U.S. It corresponds
1239 to the original IBM PC character set. This set has some, but not all, of
1240 the extended Latin-1 letters, but these letters do not have the same
1241 encoding as Latin-1. In this mode, these letters are allowed in
1242 identifiers with uppercase and lowercase equivalence.
1243
1244 @item IBM PC (code page 850)
1245 @cindex code page 850
1246 This code page is a modification of 437 extended to include all the
1247 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1248 mode, all these letters are allowed in identifiers with uppercase and
1249 lowercase equivalence.
1250
1251 @item Full Upper 8-bit
1252 Any character in the range 80-FF allowed in identifiers, and all are
1253 considered distinct. In other words, there are no uppercase and lowercase
1254 equivalences in this range. This is useful in conjunction with
1255 certain encoding schemes used for some foreign character sets (e.g.
1256 the typical method of representing Chinese characters on the PC).
1257
1258 @item No Upper-Half
1259 No upper-half characters in the range 80-FF are allowed in identifiers.
1260 This gives Ada 83 compatibility for identifier names.
1261 @end table
1262
1263 @noindent
1264 For precise data on the encodings permitted, and the uppercase and lowercase
1265 equivalences that are recognized, see the file @file{csets.adb} in
1266 the GNAT compiler sources. You will need to obtain a full source release
1267 of GNAT to obtain this file.
1268
1269 @node Wide Character Encodings
1270 @subsection Wide Character Encodings
1271
1272 @noindent
1273 GNAT allows wide character codes to appear in character and string
1274 literals, and also optionally in identifiers, by means of the following
1275 possible encoding schemes:
1276
1277 @table @asis
1278
1279 @item Hex Coding
1280 In this encoding, a wide character is represented by the following five
1281 character sequence:
1282
1283 @smallexample
1284 ESC a b c d
1285 @end smallexample
1286
1287 @noindent
1288 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1289 characters (using uppercase letters) of the wide character code. For
1290 example, ESC A345 is used to represent the wide character with code
1291 @code{16#A345#}.
1292 This scheme is compatible with use of the full Wide_Character set.
1293
1294 @item Upper-Half Coding
1295 @cindex Upper-Half Coding
1296 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1297 other words, "a" is in the range 8-F) is represented as two bytes,
1298 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1299 character, but is not required to be in the upper half. This method can
1300 be also used for shift-JIS or EUC, where the internal coding matches the
1301 external coding.
1302
1303 @item Shift JIS Coding
1304 @cindex Shift JIS Coding
1305 A wide character is represented by a two-character sequence,
1306 @code{16#ab#} and
1307 @code{16#cd#}, with the restrictions described for upper-half encoding as
1308 described above. The internal character code is the corresponding JIS
1309 character according to the standard algorithm for Shift-JIS
1310 conversion. Only characters defined in the JIS code set table can be
1311 used with this encoding method.
1312
1313 @item EUC Coding
1314 @cindex EUC Coding
1315 A wide character is represented by a two-character sequence
1316 @code{16#ab#} and
1317 @code{16#cd#}, with both characters being in the upper half. The internal
1318 character code is the corresponding JIS character according to the EUC
1319 encoding algorithm. Only characters defined in the JIS code set table
1320 can be used with this encoding method.
1321
1322 @item UTF-8 Coding
1323 A wide character is represented using
1324 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1325 10646-1/Am.2. Depending on the character value, the representation
1326 is a one, two, or three byte sequence:
1327 @smallexample
1328 @iftex
1329 @leftskip=.7cm
1330 @end iftex
1331 16#0000#-16#007f#: 2#0xxxxxxx#
1332 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1333 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1334
1335 @end smallexample
1336
1337 @noindent
1338 where the xxx bits correspond to the left-padded bits of the
1339 16-bit character value. Note that all lower half ASCII characters
1340 are represented as ASCII bytes and all upper half characters and
1341 other wide characters are represented as sequences of upper-half
1342 (The full UTF-8 scheme allows for encoding 31-bit characters as
1343 6-byte sequences, but in this implementation, all UTF-8 sequences
1344 of four or more bytes length will be treated as illegal).
1345 @item Brackets Coding
1346 In this encoding, a wide character is represented by the following eight
1347 character sequence:
1348
1349 @smallexample
1350 [ " a b c d " ]
1351 @end smallexample
1352
1353 @noindent
1354 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1355 characters (using uppercase letters) of the wide character code. For
1356 example, ["A345"] is used to represent the wide character with code
1357 @code{16#A345#}. It is also possible (though not required) to use the
1358 Brackets coding for upper half characters. For example, the code
1359 @code{16#A3#} can be represented as @code{["A3"]}.
1360
1361 This scheme is compatible with use of the full Wide_Character set,
1362 and is also the method used for wide character encoding in the standard
1363 ACVC (Ada Compiler Validation Capability) test suite distributions.
1364
1365 @end table
1366
1367 @noindent
1368 Note: Some of these coding schemes do not permit the full use of the
1369 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1370 use of the upper half of the Latin-1 set.
1371
1372 @node File Naming Rules
1373 @section File Naming Rules
1374
1375 @noindent
1376 The default file name is determined by the name of the unit that the
1377 file contains. The name is formed by taking the full expanded name of
1378 the unit and replacing the separating dots with hyphens and using
1379 lowercase for all letters.
1380
1381 An exception arises if the file name generated by the above rules starts
1382 with one of the characters
1383 a,g,i, or s,
1384 and the second character is a
1385 minus. In this case, the character tilde is used in place
1386 of the minus. The reason for this special rule is to avoid clashes with
1387 the standard names for child units of the packages System, Ada,
1388 Interfaces, and GNAT, which use the prefixes
1389 s- a- i- and g-
1390 respectively.
1391
1392 The file extension is @file{.ads} for a spec and
1393 @file{.adb} for a body. The following list shows some
1394 examples of these rules.
1395
1396 @table @file
1397 @item main.ads
1398 Main (spec)
1399 @item main.adb
1400 Main (body)
1401 @item arith_functions.ads
1402 Arith_Functions (package spec)
1403 @item arith_functions.adb
1404 Arith_Functions (package body)
1405 @item func-spec.ads
1406 Func.Spec (child package spec)
1407 @item func-spec.adb
1408 Func.Spec (child package body)
1409 @item main-sub.adb
1410 Sub (subunit of Main)
1411 @item a~bad.adb
1412 A.Bad (child package body)
1413 @end table
1414
1415 @noindent
1416 Following these rules can result in excessively long
1417 file names if corresponding
1418 unit names are long (for example, if child units or subunits are
1419 heavily nested). An option is available to shorten such long file names
1420 (called file name "krunching"). This may be particularly useful when
1421 programs being developed with GNAT are to be used on operating systems
1422 with limited file name lengths. @xref{Using gnatkr}.
1423
1424 Of course, no file shortening algorithm can guarantee uniqueness over
1425 all possible unit names; if file name krunching is used, it is your
1426 responsibility to ensure no name clashes occur. Alternatively you
1427 can specify the exact file names that you want used, as described
1428 in the next section. Finally, if your Ada programs are migrating from a
1429 compiler with a different naming convention, you can use the gnatchop
1430 utility to produce source files that follow the GNAT naming conventions.
1431 (For details @pxref{Renaming Files Using gnatchop}.)
1432
1433 @node Using Other File Names
1434 @section Using Other File Names
1435 @cindex File names
1436
1437 @noindent
1438 In the previous section, we have described the default rules used by
1439 GNAT to determine the file name in which a given unit resides. It is
1440 often convenient to follow these default rules, and if you follow them,
1441 the compiler knows without being explicitly told where to find all
1442 the files it needs.
1443
1444 However, in some cases, particularly when a program is imported from
1445 another Ada compiler environment, it may be more convenient for the
1446 programmer to specify which file names contain which units. GNAT allows
1447 arbitrary file names to be used by means of the Source_File_Name pragma.
1448 The form of this pragma is as shown in the following examples:
1449 @cindex Source_File_Name pragma
1450
1451 @smallexample
1452 @group
1453 @cartouche
1454 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1455   Spec_File_Name => "myutilst_a.ada");
1456 @b{pragma} Source_File_name (My_Utilities.Stacks,
1457   Body_File_Name => "myutilst.ada");
1458 @end cartouche
1459 @end group
1460 @end smallexample
1461
1462 @noindent
1463 As shown in this example, the first argument for the pragma is the unit
1464 name (in this example a child unit). The second argument has the form
1465 of a named association. The identifier
1466 indicates whether the file name is for a spec or a body;
1467 the file name itself is given by a string literal.
1468
1469 The source file name pragma is a configuration pragma, which means that
1470 normally it will be placed in the @file{gnat.adc}
1471 file used to hold configuration
1472 pragmas that apply to a complete compilation environment.
1473 For more details on how the @file{gnat.adc} file is created and used
1474 @pxref{Handling of Configuration Pragmas}
1475 @cindex @file{gnat.adc}
1476
1477 GNAT allows completely arbitrary file names to be specified using the
1478 source file name pragma. However, if the file name specified has an
1479 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1480 syntax when compiling the file. The name in this case must be preceded
1481 by the special sequence @code{-x} followed by a space and the name of the
1482 language, here @code{ada}, as in:
1483
1484 @smallexample
1485 $ gcc -c -x ada peculiar_file_name.sim
1486 @end smallexample
1487
1488 @noindent
1489 @code{gnatmake} handles non-standard file names in the usual manner (the
1490 non-standard file name for the main program is simply used as the
1491 argument to gnatmake). Note that if the extension is also non-standard,
1492 then it must be included in the gnatmake command, it may not be omitted.
1493
1494 @node Alternative File Naming Schemes
1495 @section Alternative File Naming Schemes
1496 @cindex File naming schemes, alternative
1497 @cindex File names
1498
1499 In the previous section, we described the use of the @code{Source_File_Name}
1500 pragma to allow arbitrary names to be assigned to individual source files.
1501 However, this approach requires one pragma for each file, and especially in
1502 large systems can result in very long @file{gnat.adc} files, and also create
1503 a maintenance problem.
1504
1505 GNAT also provides a facility for specifying systematic file naming schemes
1506 other than the standard default naming scheme previously described. An
1507 alternative scheme for naming is specified by the use of
1508 @code{Source_File_Name} pragmas having the following format:
1509 @cindex Source_File_Name pragma
1510
1511 @smallexample
1512 pragma Source_File_Name (
1513    Spec_File_Name  => FILE_NAME_PATTERN
1514  [,Casing          => CASING_SPEC]
1515  [,Dot_Replacement => STRING_LITERAL]);
1516
1517 pragma Source_File_Name (
1518    Body_File_Name  => FILE_NAME_PATTERN
1519  [,Casing          => CASING_SPEC]
1520  [,Dot_Replacement => STRING_LITERAL]);
1521
1522 pragma Source_File_Name (
1523    Subunit_File_Name  => FILE_NAME_PATTERN
1524  [,Casing             => CASING_SPEC]
1525  [,Dot_Replacement    => STRING_LITERAL]);
1526
1527 FILE_NAME_PATTERN ::= STRING_LITERAL
1528 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1529
1530 @end smallexample
1531
1532 @noindent
1533 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1534 It contains a single asterisk character, and the unit name is substituted
1535 systematically for this asterisk. The optional parameter
1536 @code{Casing} indicates
1537 whether the unit name is to be all upper-case letters, all lower-case letters,
1538 or mixed-case. If no
1539 @code{Casing} parameter is used, then the default is all
1540 lower-case.
1541
1542 The optional @code{Dot_Replacement} string is used to replace any periods
1543 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1544 argument is used then separating dots appear unchanged in the resulting
1545 file name.
1546 Although the above syntax indicates that the
1547 @code{Casing} argument must appear
1548 before the @code{Dot_Replacement} argument, but it
1549 is also permissible to write these arguments in the opposite order.
1550
1551 As indicated, it is possible to specify different naming schemes for
1552 bodies, specs, and subunits. Quite often the rule for subunits is the
1553 same as the rule for bodies, in which case, there is no need to give
1554 a separate @code{Subunit_File_Name} rule, and in this case the
1555 @code{Body_File_name} rule is used for subunits as well.
1556
1557 The separate rule for subunits can also be used to implement the rather
1558 unusual case of a compilation environment (e.g. a single directory) which
1559 contains a subunit and a child unit with the same unit name. Although
1560 both units cannot appear in the same partition, the Ada Reference Manual
1561 allows (but does not require) the possibility of the two units coexisting
1562 in the same environment.
1563
1564 The file name translation works in the following steps:
1565
1566 @itemize @bullet
1567
1568 @item
1569 If there is a specific @code{Source_File_Name} pragma for the given unit,
1570 then this is always used, and any general pattern rules are ignored.
1571
1572 @item
1573 If there is a pattern type @code{Source_File_Name} pragma that applies to
1574 the unit, then the resulting file name will be used if the file exists. If
1575 more than one pattern matches, the latest one will be tried first, and the
1576 first attempt resulting in a reference to a file that exists will be used.
1577
1578 @item
1579 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1580 for which the corresponding file exists, then the standard GNAT default
1581 naming rules are used.
1582
1583 @end itemize
1584
1585 @noindent
1586 As an example of the use of this mechanism, consider a commonly used scheme
1587 in which file names are all lower case, with separating periods copied
1588 unchanged to the resulting file name, and specs end with ".1.ada", and
1589 bodies end with ".2.ada". GNAT will follow this scheme if the following
1590 two pragmas appear:
1591
1592 @smallexample
1593 pragma Source_File_Name
1594   (Spec_File_Name => "*.1.ada");
1595 pragma Source_File_Name
1596   (Body_File_Name => "*.2.ada");
1597 @end smallexample
1598
1599 @noindent
1600 The default GNAT scheme is actually implemented by providing the following
1601 default pragmas internally:
1602
1603 @smallexample
1604 pragma Source_File_Name
1605   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1606 pragma Source_File_Name
1607   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1608 @end smallexample
1609
1610 @noindent
1611 Our final example implements a scheme typically used with one of the
1612 Ada 83 compilers, where the separator character for subunits was "__"
1613 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1614 by adding @file{.ADA}, and subunits by
1615 adding @file{.SEP}. All file names were
1616 upper case. Child units were not present of course since this was an
1617 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1618 the same double underscore separator for child units.
1619
1620 @smallexample
1621 pragma Source_File_Name
1622   (Spec_File_Name => "*_.ADA",
1623    Dot_Replacement => "__",
1624    Casing = Uppercase);
1625 pragma Source_File_Name
1626   (Body_File_Name => "*.ADA",
1627    Dot_Replacement => "__",
1628    Casing = Uppercase);
1629 pragma Source_File_Name
1630   (Subunit_File_Name => "*.SEP",
1631    Dot_Replacement => "__",
1632    Casing = Uppercase);
1633 @end smallexample
1634
1635 @node Generating Object Files
1636 @section Generating Object Files
1637
1638 @noindent
1639 An Ada program consists of a set of source files, and the first step in
1640 compiling the program is to generate the corresponding object files.
1641 These are generated by compiling a subset of these source files.
1642 The files you need to compile are the following:
1643
1644 @itemize @bullet
1645 @item
1646 If a package spec has no body, compile the package spec to produce the
1647 object file for the package.
1648
1649 @item
1650 If a package has both a spec and a body, compile the body to produce the
1651 object file for the package. The source file for the package spec need
1652 not be compiled in this case because there is only one object file, which
1653 contains the code for both the spec and body of the package.
1654
1655 @item
1656 For a subprogram, compile the subprogram body to produce the object file
1657 for the subprogram. The spec, if one is present, is as usual in a
1658 separate file, and need not be compiled.
1659
1660 @item
1661 @cindex Subunits
1662 In the case of subunits, only compile the parent unit. A single object
1663 file is generated for the entire subunit tree, which includes all the
1664 subunits.
1665
1666 @item
1667 Compile child units independently of their parent units
1668 (though, of course, the spec of all the ancestor unit must be present in order
1669 to compile a child unit).
1670
1671 @item
1672 @cindex Generics
1673 Compile generic units in the same manner as any other units. The object
1674 files in this case are small dummy files that contain at most the
1675 flag used for elaboration checking. This is because GNAT always handles generic
1676 instantiation by means of macro expansion. However, it is still necessary to
1677 compile generic units, for dependency checking and elaboration purposes.
1678 @end itemize
1679
1680 @noindent
1681 The preceding rules describe the set of files that must be compiled to
1682 generate the object files for a program. Each object file has the same
1683 name as the corresponding source file, except that the extension is
1684 @file{.o} as usual.
1685
1686 You may wish to compile other files for the purpose of checking their
1687 syntactic and semantic correctness. For example, in the case where a
1688 package has a separate spec and body, you would not normally compile the
1689 spec. However, it is convenient in practice to compile the spec to make
1690 sure it is error-free before compiling clients of this spec, because such
1691 compilations will fail if there is an error in the spec.
1692
1693 GNAT provides an option for compiling such files purely for the
1694 purposes of checking correctness; such compilations are not required as
1695 part of the process of building a program. To compile a file in this
1696 checking mode, use the @option{-gnatc} switch.
1697
1698 @node Source Dependencies
1699 @section Source Dependencies
1700
1701 @noindent
1702 A given object file clearly depends on the source file which is compiled
1703 to produce it. Here we are using @dfn{depends} in the sense of a typical
1704 @code{make} utility; in other words, an object file depends on a source
1705 file if changes to the source file require the object file to be
1706 recompiled.
1707 In addition to this basic dependency, a given object may depend on
1708 additional source files as follows:
1709
1710 @itemize @bullet
1711 @item
1712 If a file being compiled @code{with}'s a unit @var{X}, the object file
1713 depends on the file containing the spec of unit @var{X}. This includes
1714 files that are @code{with}'ed implicitly either because they are parents
1715 of @code{with}'ed child units or they are run-time units required by the
1716 language constructs used in a particular unit.
1717
1718 @item
1719 If a file being compiled instantiates a library level generic unit, the
1720 object file depends on both the spec and body files for this generic
1721 unit.
1722
1723 @item
1724 If a file being compiled instantiates a generic unit defined within a
1725 package, the object file depends on the body file for the package as
1726 well as the spec file.
1727
1728 @item
1729 @findex Inline
1730 @cindex @option{-gnatn} switch
1731 If a file being compiled contains a call to a subprogram for which
1732 pragma @code{Inline} applies and inlining is activated with the
1733 @option{-gnatn} switch, the object file depends on the file containing the
1734 body of this subprogram as well as on the file containing the spec. Note
1735 that for inlining to actually occur as a result of the use of this switch,
1736 it is necessary to compile in optimizing mode.
1737
1738 @cindex @option{-gnatN} switch
1739 The use of @option{-gnatN} activates a more extensive inlining optimization
1740 that is performed by the front end of the compiler. This inlining does
1741 not require that the code generation be optimized. Like @option{-gnatn},
1742 the use of this switch generates additional dependencies.
1743
1744 @item
1745 If an object file O  depends on the proper body of a subunit through inlining
1746 or instantiation, it depends on the parent unit of the subunit. This means that
1747 any modification of the parent unit or one of its subunits affects the
1748 compilation of O.
1749
1750 @item
1751 The object file for a parent unit depends on all its subunit body files.
1752
1753 @item
1754 The previous two rules meant that for purposes of computing dependencies and
1755 recompilation, a body and all its subunits are treated as an indivisible whole.
1756
1757 @noindent
1758 These rules are applied transitively: if unit @code{A} @code{with}'s
1759 unit @code{B}, whose elaboration calls an inlined procedure in package
1760 @code{C}, the object file for unit @code{A} will depend on the body of
1761 @code{C}, in file @file{c.adb}.
1762
1763 The set of dependent files described by these rules includes all the
1764 files on which the unit is semantically dependent, as described in the
1765 Ada 95 Language Reference Manual. However, it is a superset of what the
1766 ARM describes, because it includes generic, inline, and subunit dependencies.
1767
1768 An object file must be recreated by recompiling the corresponding source
1769 file if any of the source files on which it depends are modified. For
1770 example, if the @code{make} utility is used to control compilation,
1771 the rule for an Ada object file must mention all the source files on
1772 which the object file depends, according to the above definition.
1773 The determination of the necessary
1774 recompilations is done automatically when one uses @code{gnatmake}.
1775 @end itemize
1776
1777 @node The Ada Library Information Files
1778 @section The Ada Library Information Files
1779 @cindex Ada Library Information files
1780 @cindex @file{ali} files
1781
1782 @noindent
1783 Each compilation actually generates two output files. The first of these
1784 is the normal object file that has a @file{.o} extension. The second is a
1785 text file containing full dependency information. It has the same
1786 name as the source file, but an @file{.ali} extension.
1787 This file is known as the Ada Library Information (@file{ali}) file.
1788 The following information is contained in the @file{ali} file.
1789
1790 @itemize @bullet
1791 @item
1792 Version information (indicates which version of GNAT was used to compile
1793 the unit(s) in question)
1794
1795 @item
1796 Main program information (including priority and time slice settings,
1797 as well as the wide character encoding used during compilation).
1798
1799 @item
1800 List of arguments used in the @code{gcc} command for the compilation
1801
1802 @item
1803 Attributes of the unit, including configuration pragmas used, an indication
1804 of whether the compilation was successful, exception model used etc.
1805
1806 @item
1807 A list of relevant restrictions applying to the unit (used for consistency)
1808 checking.
1809
1810 @item
1811 Categorization information (e.g. use of pragma @code{Pure}).
1812
1813 @item
1814 Information on all @code{with}'ed units, including presence of
1815 @code{Elaborate} or @code{Elaborate_All} pragmas.
1816
1817 @item
1818 Information from any @code{Linker_Options} pragmas used in the unit
1819
1820 @item
1821 Information on the use of @code{Body_Version} or @code{Version}
1822 attributes in the unit.
1823
1824 @item
1825 Dependency information. This is a list of files, together with
1826 time stamp and checksum information. These are files on which
1827 the unit depends in the sense that recompilation is required
1828 if any of these units are modified.
1829
1830 @item
1831 Cross-reference data. Contains information on all entities referenced
1832 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1833 provide cross-reference information.
1834
1835 @end itemize
1836
1837 @noindent
1838 For a full detailed description of the format of the @file{ali} file,
1839 see the source of the body of unit @code{Lib.Writ}, contained in file
1840 @file{lib-writ.adb} in the GNAT compiler sources.
1841
1842 @node Binding an Ada Program
1843 @section Binding an Ada Program
1844
1845 @noindent
1846 When using languages such as C and C++, once the source files have been
1847 compiled the only remaining step in building an executable program
1848 is linking the object modules together. This means that it is possible to
1849 link an inconsistent version of a program, in which two units have
1850 included different versions of the same header.
1851
1852 The rules of Ada do not permit such an inconsistent program to be built.
1853 For example, if two clients have different versions of the same package,
1854 it is illegal to build a program containing these two clients.
1855 These rules are enforced by the GNAT binder, which also determines an
1856 elaboration order consistent with the Ada rules.
1857
1858 The GNAT binder is run after all the object files for a program have
1859 been created. It is given the name of the main program unit, and from
1860 this it determines the set of units required by the program, by reading the
1861 corresponding ALI files. It generates error messages if the program is
1862 inconsistent or if no valid order of elaboration exists.
1863
1864 If no errors are detected, the binder produces a main program, in Ada by
1865 default, that contains calls to the elaboration procedures of those
1866 compilation unit that require them, followed by
1867 a call to the main program. This Ada program is compiled to generate the
1868 object file for the main program. The name of
1869 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1870 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1871 main program unit.
1872
1873 Finally, the linker is used to build the resulting executable program,
1874 using the object from the main program from the bind step as well as the
1875 object files for the Ada units of the program.
1876
1877 @node Mixed Language Programming
1878 @section Mixed Language Programming
1879 @cindex Mixed Language Programming
1880
1881 @menu
1882 * Interfacing to C::
1883 * Calling Conventions::
1884 @end menu
1885
1886 @node Interfacing to C
1887 @subsection Interfacing to C
1888 @noindent
1889 There are two ways to
1890 build a program that contains some Ada files and some other language
1891 files depending on whether the main program is in Ada or not.
1892 If the main program is in Ada, you should proceed as follows:
1893
1894 @enumerate
1895 @item
1896 Compile the other language files to generate object files. For instance:
1897 @smallexample
1898 gcc -c file1.c
1899 gcc -c file2.c
1900 @end smallexample
1901
1902 @item
1903 Compile the Ada units to produce a set of object files and ALI
1904 files. For instance:
1905 @smallexample
1906 gnatmake -c my_main.adb
1907 @end smallexample
1908
1909 @item
1910 Run the Ada binder on the Ada main program. For instance:
1911 @smallexample
1912 gnatbind my_main.ali
1913 @end smallexample
1914
1915 @item
1916 Link the Ada main program, the Ada objects and the other language
1917 objects. For instance:
1918 @smallexample
1919 gnatlink my_main.ali file1.o file2.o
1920 @end smallexample
1921 @end enumerate
1922
1923 The three last steps can be grouped in a single command:
1924 @smallexample
1925 gnatmake my_main.adb -largs file1.o file2.o
1926 @end smallexample
1927
1928 @cindex Binder output file
1929 @noindent
1930 If the main program is in some language other than Ada, Then you may
1931 have more than one entry point in the Ada subsystem. You must use a
1932 special option of the binder to generate callable routines to initialize
1933 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
1934 Calls to the initialization and finalization routines must be inserted in
1935 the main program, or some other appropriate point in the code. The call to
1936 initialize the Ada units must occur before the first Ada subprogram is
1937 called, and the call to finalize the Ada units must occur after the last
1938 Ada subprogram returns. You use the same procedure for building the
1939 program as described previously. In this case, however, the binder
1940 only places the initialization and finalization subprograms into file
1941 @file{b~@var{xxx}.adb} instead of the main program.
1942 So, if the main program is not in Ada, you should proceed as follows:
1943
1944 @enumerate
1945 @item
1946 Compile the other language files to generate object files. For instance:
1947 @smallexample
1948 gcc -c file1.c
1949 gcc -c file2.c
1950 @end smallexample
1951
1952 @item
1953 Compile the Ada units to produce a set of object files and ALI
1954 files. For instance:
1955 @smallexample
1956 gnatmake -c entry_point1.adb
1957 gnatmake -c entry_point2.adb
1958 @end smallexample
1959
1960 @item
1961 Run the Ada binder on the Ada main program. For instance:
1962 @smallexample
1963 gnatbind -n entry_point1.ali entry_point2.ali
1964 @end smallexample
1965
1966 @item
1967 Link the Ada main program, the Ada objects and the other language
1968 objects. You only need to give the last entry point here. For instance:
1969 @smallexample
1970 gnatlink entry_point2.ali file1.o file2.o
1971 @end smallexample
1972 @end enumerate
1973
1974 @node Calling Conventions
1975 @subsection Calling Conventions
1976 @cindex Foreign Languages
1977 @cindex Calling Conventions
1978 GNAT follows standard calling sequence conventions and will thus interface
1979 to any other language that also follows these conventions. The following
1980 Convention identifiers are recognized by GNAT:
1981
1982 @itemize @bullet
1983 @cindex Interfacing to Ada
1984 @cindex Other Ada compilers
1985 @cindex Convention Ada
1986 @item
1987 Ada. This indicates that the standard Ada calling sequence will be
1988 used and all Ada data items may be passed without any limitations in the
1989 case where GNAT is used to generate both the caller and callee. It is also
1990 possible to mix GNAT generated code and code generated by another Ada
1991 compiler. In this case, the data types should be restricted to simple
1992 cases, including primitive types. Whether complex data types can be passed
1993 depends on the situation. Probably it is safe to pass simple arrays, such
1994 as arrays of integers or floats. Records may or may not work, depending
1995 on whether both compilers lay them out identically. Complex structures
1996 involving variant records, access parameters, tasks, or protected types,
1997 are unlikely to be able to be passed.
1998
1999 Note that in the case of GNAT running
2000 on a platform that supports DEC Ada 83, a higher degree of compatibility
2001 can be guaranteed, and in particular records are layed out in an identical
2002 manner in the two compilers. Note also that if output from two different
2003 compilers is mixed, the program is responsible for dealing with elaboration
2004 issues. Probably the safest approach is to write the main program in the
2005 version of Ada other than GNAT, so that it takes care of its own elaboration
2006 requirements, and then call the GNAT-generated adainit procedure to ensure
2007 elaboration of the GNAT components. Consult the documentation of the other
2008 Ada compiler for further details on elaboration.
2009
2010 However, it is not possible to mix the tasking run time of GNAT and
2011 DEC Ada 83, All the tasking operations must either be entirely within
2012 GNAT compiled sections of the program, or entirely within DEC Ada 83
2013 compiled sections of the program.
2014
2015 @cindex Interfacing to Assembly
2016 @cindex Convention Assembler
2017 @item
2018 Assembler. Specifies assembler as the convention. In practice this has the
2019 same effect as convention Ada (but is not equivalent in the sense of being
2020 considered the same convention).
2021
2022 @cindex Convention Asm
2023 @findex Asm
2024 @item
2025 Asm. Equivalent to Assembler.
2026
2027 @cindex Convention Asm
2028 @findex Asm
2029 @item
2030 Asm. Equivalent to Assembly.
2031
2032 @cindex Interfacing to COBOL
2033 @cindex Convention COBOL
2034 @findex COBOL
2035 @item
2036 COBOL. Data will be passed according to the conventions described
2037 in section B.4 of the Ada 95 Reference Manual.
2038
2039 @findex C
2040 @cindex Interfacing to C
2041 @cindex Convention C
2042 @item
2043 C. Data will be passed according to the conventions described
2044 in section B.3 of the Ada 95 Reference Manual.
2045
2046 @cindex Convention Default
2047 @findex Default
2048 @item
2049 Default. Equivalent to C.
2050
2051 @cindex Convention External
2052 @findex External
2053 @item
2054 External. Equivalent to C.
2055
2056 @findex C++
2057 @cindex Interfacing to C++
2058 @cindex Convention C++
2059 @item
2060 CPP. This stands for C++. For most purposes this is identical to C.
2061 See the separate description of the specialized GNAT pragmas relating to
2062 C++ interfacing for further details.
2063
2064 @findex Fortran
2065 @cindex Interfacing to Fortran
2066 @cindex Convention Fortran
2067 @item
2068 Fortran. Data will be passed according to the conventions described
2069 in section B.5 of the Ada 95 Reference Manual.
2070
2071 @item
2072 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2073 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2074 this means that the body of the subprogram is provided by the compiler itself,
2075 usually by means of an efficient code sequence, and that the user does not
2076 supply an explicit body for it. In an application program, the pragma can only
2077 be applied to the following two sets of names, which the GNAT compiler
2078 recognizes.
2079 @itemize @bullet
2080 @item
2081 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2082 Arithmetic.  The corresponding subprogram declaration must have
2083 two formal parameters. The
2084 first one must be a signed integer type or a modular type with a binary
2085 modulus, and the second parameter must be of type Natural.
2086 The return type must be the same as the type of the first argument. The size
2087 of this type can only be 8, 16, 32, or 64.
2088 @item binary arithmetic operators: "+", "-", "*", "/"
2089 The corresponding operator declaration must have parameters and result type
2090 that have the same root numeric type (for example, all three are long_float
2091 types). This simplifies the definition of operations that use type checking
2092 to perform dimensional checks:
2093 @smallexample
2094 type Distance is new Long_Float;
2095 type Time     is new Long_Float;
2096 type Velocity is new Long_Float;
2097 function "/" (D : Distance; T : Time)
2098   return Velocity;
2099 pragma Import (Intrinsic, "/");
2100 @end smallexample
2101 @noindent
2102 This common idiom is often programmed with a generic definition and an explicit
2103 body. The pragma makes it simpler to introduce such declarations. It incurs
2104 no overhead in compilation time or code size, because it is implemented as a
2105 single machine instruction.
2106 @end itemize
2107 @noindent
2108
2109 @findex Stdcall
2110 @cindex Convention Stdcall
2111 @item
2112 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2113 and specifies that the Stdcall calling sequence will be used, as defined
2114 by the NT API.
2115
2116 @findex DLL
2117 @cindex Convention DLL
2118 @item
2119 DLL. This is equivalent to Stdcall.
2120
2121 @findex Win32
2122 @cindex Convention Win32
2123 @item
2124 Win32. This is equivalent to Stdcall.
2125
2126 @findex Stubbed
2127 @cindex Convention Stubbed
2128 @item
2129 Stubbed. This is a special convention that indicates that the compiler
2130 should provide a stub body that raises @code{Program_Error}.
2131 @end itemize
2132
2133 @noindent
2134 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2135 that can be used to parametrize conventions and allow additional synonyms
2136 to be specified. For example if you have legacy code in which the convention
2137 identifier Fortran77 was used for Fortran, you can use the configuration
2138 pragma:
2139
2140 @smallexample
2141    pragma Convention_Identifier (Fortran77, Fortran);
2142 @end smallexample
2143
2144 @noindent
2145 And from now on the identifier Fortran77 may be used as a convention
2146 identifier (for example in an @code{Import} pragma) with the same
2147 meaning as Fortran.
2148
2149 @node Building Mixed Ada & C++ Programs
2150 @section Building Mixed Ada & C++ Programs
2151
2152 @noindent
2153 Building a mixed application containing both Ada and C++ code may be a
2154 challenge for the unaware programmer. As a matter of fact, this
2155 interfacing has not been standardized in the Ada 95 reference manual due
2156 to the immaturity and lack of standard of C++ at the time. This
2157 section gives a few hints that should make this task easier. In
2158 particular the first section addresses the differences with
2159 interfacing with C. The second section looks into the delicate problem
2160 of linking the complete application from its Ada and C++ parts. The last
2161 section give some hints on how the GNAT run time can be adapted in order
2162 to allow inter-language dispatching with a new C++ compiler.
2163
2164 @menu
2165 * Interfacing to C++::
2166 * Linking a Mixed C++ & Ada Program::
2167 * A Simple Example::
2168 * Adapting the Run Time to a New C++ Compiler::
2169 @end menu
2170
2171 @node Interfacing to C++
2172 @subsection Interfacing to C++
2173
2174 @noindent
2175 GNAT supports interfacing with C++ compilers generating code that is
2176 compatible with the standard Application Binary Interface of the given
2177 platform.
2178
2179 @noindent
2180 Interfacing can be done at 3 levels: simple data, subprograms and
2181 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2182 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2183 names of subprograms and currently GNAT does not provide any help to
2184 solve the demangling problem. This problem can be addressed in 2 ways:
2185 @itemize @bullet
2186 @item
2187 by modifying the C++ code in order to force a C convention using
2188 the @var{extern "C"} syntax.
2189
2190 @item
2191 by figuring out the mangled name and use it as the Link_Name argument of
2192 the pragma import.
2193 @end itemize
2194
2195 @noindent
2196 Interfacing at the class level can be achieved by using the GNAT specific
2197 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2198 Reference Manual for additional information.
2199
2200 @node Linking a Mixed C++ & Ada Program
2201 @subsection Linking a Mixed C++ & Ada Program
2202
2203 @noindent
2204 Usually the linker of the C++ development system must be used to link
2205 mixed applications because most C++ systems will resolve elaboration
2206 issues (such as calling constructors on global class instances)
2207 transparently during the link phase. GNAT has been adapted to ease the
2208 use of a foreign linker for the last phase. Three cases can be
2209 considered:
2210 @enumerate
2211
2212 @item
2213 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2214 installation. The c++ linker can simply be called by using the c++
2215 specific driver called @code{c++}. Note that this setup is not
2216 very common because it may request recompiling the whole GCC
2217 tree from sources and it does not allow to upgrade easily to a new
2218 version of one compiler for one of the two languages without taking the
2219 risk of destabilizing the other.
2220
2221 @smallexample
2222 $ c++ -c file1.C
2223 $ c++ -c file2.C
2224 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2225 @end smallexample
2226
2227 @item
2228 Using GNAT and G++ from 2 different GCC installations. If both compilers
2229 are on the PATH, the same method can be used. It is important to be
2230 aware that environment variables such as C_INCLUDE_PATH,
2231 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2232 the same time and thus may make one of the 2 compilers operate
2233 improperly if they are set for the other. In particular it is important
2234 that the link command has access to the proper gcc library @file{libgcc.a},
2235 that is to say the one that is part of the C++ compiler
2236 installation. The implicit link command as suggested in the gnatmake
2237 command from the former example can be replaced by an explicit link
2238 command with full verbosity in order to verify which library is used:
2239 @smallexample
2240 $ gnatbind ada_unit
2241 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2242 @end smallexample
2243 If there is a problem due to interfering environment variables, it can
2244 be workaround by using an intermediate script. The following example
2245 shows the proper script to use when GNAT has not been installed at its
2246 default location and g++ has been installed at its default location:
2247
2248 @smallexample
2249 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2250 $ cat ./my_script
2251 #!/bin/sh
2252 unset BINUTILS_ROOT
2253 unset GCC_ROOT
2254 c++ $*
2255 @end smallexample
2256
2257 @item
2258 Using a non GNU C++ compiler. The same set of command as previously
2259 described can be used to insure that the c++ linker is
2260 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2261 libraries needed by GNAT are located in this directory:
2262
2263 @smallexample
2264
2265 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2266 $ cat ./my_script
2267 #!/bin/sh
2268 CC $* `gcc -print-libgcc-file-name`
2269
2270 @end smallexample
2271
2272 Where CC is the name of the non GNU C++ compiler.
2273
2274 @end enumerate
2275
2276 @node A Simple Example
2277 @subsection  A Simple Example
2278 @noindent
2279 The following example, provided as part of the GNAT examples, show how
2280 to achieve procedural interfacing between Ada and C++ in both
2281 directions. The C++ class A has 2 methods. The first method is exported
2282 to Ada by the means of an extern C wrapper function. The second method
2283 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2284 a limited record with a layout comparable to the C++ class. The Ada
2285 subprogram, in turn, calls the c++ method. So from the C++ main program
2286 the code goes back and forth between the 2 languages.
2287
2288 @noindent
2289 Here are the compilation commands
2290 for native configurations:
2291 @smallexample
2292 $ gnatmake -c simple_cpp_interface
2293 $ c++ -c cpp_main.C
2294 $ c++ -c ex7.C
2295 $ gnatbind -n simple_cpp_interface
2296 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2297       -lstdc++ ex7.o cpp_main.o
2298 @end smallexample
2299 @noindent
2300 Here are the corresponding sources:
2301 @smallexample
2302
2303 //cpp_main.C
2304
2305 #include "ex7.h"
2306
2307 extern "C" @{
2308   void adainit (void);
2309   void adafinal (void);
2310   void method1 (A *t);
2311 @}
2312
2313 void method1 (A *t)
2314 @{
2315   t->method1 ();
2316 @}
2317
2318 int main ()
2319 @{
2320   A obj;
2321   adainit ();
2322   obj.method2 (3030);
2323   adafinal ();
2324 @}
2325
2326 //ex7.h
2327
2328 class Origin @{
2329  public:
2330   int o_value;
2331 @};
2332 class A : public Origin @{
2333  public:
2334   void method1 (void);
2335   virtual void method2 (int v);
2336   A();
2337   int   a_value;
2338 @};
2339
2340 //ex7.C
2341
2342 #include "ex7.h"
2343 #include <stdio.h>
2344
2345 extern "C" @{ void ada_method2 (A *t, int v);@}
2346
2347 void A::method1 (void)
2348 @{
2349   a_value = 2020;
2350   printf ("in A::method1, a_value = %d \n",a_value);
2351
2352 @}
2353
2354 void A::method2 (int v)
2355 @{
2356    ada_method2 (this, v);
2357    printf ("in A::method2, a_value = %d \n",a_value);
2358
2359 @}
2360
2361 A::A(void)
2362 @{
2363    a_value = 1010;
2364   printf ("in A::A, a_value = %d \n",a_value);
2365 @}
2366
2367 -- Ada sources
2368 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2369
2370    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2371    @b{begin}
2372       Method1 (This);
2373       This.A_Value := V;
2374    @b{end} Ada_Method2;
2375
2376 @b{end} Simple_Cpp_Interface;
2377
2378 @b{package} Simple_Cpp_Interface @b{is}
2379    @b{type} A @b{is} @b{limited}
2380       @b{record}
2381          O_Value : Integer;
2382          A_Value : Integer;
2383       @b{end} @b{record};
2384    @b{pragma} Convention (C, A);
2385
2386    @b{procedure} Method1 (This : @b{in} @b{out} A);
2387    @b{pragma} Import (C, Method1);
2388
2389    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2390    @b{pragma} Export (C, Ada_Method2);
2391
2392 @b{end} Simple_Cpp_Interface;
2393 @end smallexample
2394
2395 @node Adapting the Run Time to a New C++ Compiler
2396 @subsection Adapting the Run Time to a New C++ Compiler
2397 @noindent
2398 GNAT offers the capability to derive Ada 95 tagged types directly from
2399 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2400 reference manual. The mechanism used by GNAT for achieving such a goal
2401 has been made user configurable through a GNAT library unit
2402 @code{Interfaces.CPP}. The default version of this file is adapted to
2403 the GNU c++ compiler. Internal knowledge of the virtual
2404 table layout used by the new C++ compiler is needed to configure
2405 properly this unit. The Interface of this unit is known by the compiler
2406 and cannot be changed except for the value of the constants defining the
2407 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2408 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2409 of this unit for more details.
2410
2411 @node Comparison between GNAT and C/C++ Compilation Models
2412 @section Comparison between GNAT and C/C++ Compilation Models
2413
2414 @noindent
2415 The GNAT model of compilation is close to the C and C++ models. You can
2416 think of Ada specs as corresponding to header files in C. As in C, you
2417 don't need to compile specs; they are compiled when they are used. The
2418 Ada @code{with} is similar in effect to the @code{#include} of a C
2419 header.
2420
2421 One notable difference is that, in Ada, you may compile specs separately
2422 to check them for semantic and syntactic accuracy. This is not always
2423 possible with C headers because they are fragments of programs that have
2424 less specific syntactic or semantic rules.
2425
2426 The other major difference is the requirement for running the binder,
2427 which performs two important functions. First, it checks for
2428 consistency. In C or C++, the only defense against assembling
2429 inconsistent programs lies outside the compiler, in a makefile, for
2430 example. The binder satisfies the Ada requirement that it be impossible
2431 to construct an inconsistent program when the compiler is used in normal
2432 mode.
2433
2434 @cindex Elaboration order control
2435 The other important function of the binder is to deal with elaboration
2436 issues. There are also elaboration issues in C++ that are handled
2437 automatically. This automatic handling has the advantage of being
2438 simpler to use, but the C++ programmer has no control over elaboration.
2439 Where @code{gnatbind} might complain there was no valid order of
2440 elaboration, a C++ compiler would simply construct a program that
2441 malfunctioned at run time.
2442
2443 @node Comparison between GNAT and Conventional Ada Library Models
2444 @section Comparison between GNAT and Conventional Ada Library Models
2445
2446 @noindent
2447 This section is intended to be useful to Ada programmers who have
2448 previously used an Ada compiler implementing the traditional Ada library
2449 model, as described in the Ada 95 Language Reference Manual. If you
2450 have not used such a system, please go on to the next section.
2451
2452 @cindex GNAT library
2453 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2454 source files themselves acts as the library. Compiling Ada programs does
2455 not generate any centralized information, but rather an object file and
2456 a ALI file, which are of interest only to the binder and linker.
2457 In a traditional system, the compiler reads information not only from
2458 the source file being compiled, but also from the centralized library.
2459 This means that the effect of a compilation depends on what has been
2460 previously compiled. In particular:
2461
2462 @itemize @bullet
2463 @item
2464 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2465 to the version of the unit most recently compiled into the library.
2466
2467 @item
2468 Inlining is effective only if the necessary body has already been
2469 compiled into the library.
2470
2471 @item
2472 Compiling a unit may obsolete other units in the library.
2473 @end itemize
2474
2475 @noindent
2476 In GNAT, compiling one unit never affects the compilation of any other
2477 units because the compiler reads only source files. Only changes to source
2478 files can affect the results of a compilation. In particular:
2479
2480 @itemize @bullet
2481 @item
2482 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2483 to the source version of the unit that is currently accessible to the
2484 compiler.
2485
2486 @item
2487 @cindex Inlining
2488 Inlining requires the appropriate source files for the package or
2489 subprogram bodies to be available to the compiler. Inlining is always
2490 effective, independent of the order in which units are complied.
2491
2492 @item
2493 Compiling a unit never affects any other compilations. The editing of
2494 sources may cause previous compilations to be out of date if they
2495 depended on the source file being modified.
2496 @end itemize
2497
2498 @noindent
2499 The most important result of these differences is that order of compilation
2500 is never significant in GNAT. There is no situation in which one is
2501 required to do one compilation before another. What shows up as order of
2502 compilation requirements in the traditional Ada library becomes, in
2503 GNAT, simple source dependencies; in other words, there is only a set
2504 of rules saying what source files must be present when a file is
2505 compiled.
2506
2507 @node Compiling Using gcc
2508 @chapter Compiling Using @code{gcc}
2509
2510 @noindent
2511 This chapter discusses how to compile Ada programs using the @code{gcc}
2512 command. It also describes the set of switches
2513 that can be used to control the behavior of the compiler.
2514 @menu
2515 * Compiling Programs::
2516 * Switches for gcc::
2517 * Search Paths and the Run-Time Library (RTL)::
2518 * Order of Compilation Issues::
2519 * Examples::
2520 @end menu
2521
2522 @node Compiling Programs
2523 @section Compiling Programs
2524
2525 @noindent
2526 The first step in creating an executable program is to compile the units
2527 of the program using the @code{gcc} command. You must compile the
2528 following files:
2529
2530 @itemize @bullet
2531 @item
2532 the body file (@file{.adb}) for a library level subprogram or generic
2533 subprogram
2534
2535 @item
2536 the spec file (@file{.ads}) for a library level package or generic
2537 package that has no body
2538
2539 @item
2540 the body file (@file{.adb}) for a library level package
2541 or generic package that has a body
2542
2543 @end itemize
2544
2545 @noindent
2546 You need @emph{not} compile the following files
2547
2548 @itemize @bullet
2549
2550 @item
2551 the spec of a library unit which has a body
2552
2553 @item
2554 subunits
2555 @end itemize
2556
2557 @noindent
2558 because they are compiled as part of compiling related units. GNAT
2559 package specs
2560 when the corresponding body is compiled, and subunits when the parent is
2561 compiled.
2562 @cindex No code generated
2563 If you attempt to compile any of these files, you will get one of the
2564 following error messages (where fff is the name of the file you compiled):
2565
2566 @smallexample
2567 No code generated for file @var{fff} (@var{package spec})
2568 No code generated for file @var{fff} (@var{subunit})
2569 @end smallexample
2570
2571 @noindent
2572 The basic command for compiling a file containing an Ada unit is
2573
2574 @smallexample
2575 $ gcc -c [@var{switches}] @file{file name}
2576 @end smallexample
2577
2578 @noindent
2579 where @var{file name} is the name of the Ada file (usually
2580 having an extension
2581 @file{.ads} for a spec or @file{.adb} for a body).
2582 You specify the
2583 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2584 The result of a successful compilation is an object file, which has the
2585 same name as the source file but an extension of @file{.o} and an Ada
2586 Library Information (ALI) file, which also has the same name as the
2587 source file, but with @file{.ali} as the extension. GNAT creates these
2588 two output files in the current directory, but you may specify a source
2589 file in any directory using an absolute or relative path specification
2590 containing the directory information.
2591
2592 @findex gnat1
2593 @code{gcc} is actually a driver program that looks at the extensions of
2594 the file arguments and loads the appropriate compiler. For example, the
2595 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2596 These programs are in directories known to the driver program (in some
2597 configurations via environment variables you set), but need not be in
2598 your path. The @code{gcc} driver also calls the assembler and any other
2599 utilities needed to complete the generation of the required object
2600 files.
2601
2602 It is possible to supply several file names on the same @code{gcc}
2603 command. This causes @code{gcc} to call the appropriate compiler for
2604 each file. For example, the following command lists three separate
2605 files to be compiled:
2606
2607 @smallexample
2608 $ gcc -c x.adb y.adb z.c
2609 @end smallexample
2610
2611 @noindent
2612 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2613 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2614 The compiler generates three object files @file{x.o}, @file{y.o} and
2615 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2616 Ada compilations. Any switches apply to all the files listed,
2617 except for
2618 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2619
2620 @node Switches for gcc
2621 @section Switches for @code{gcc}
2622
2623 @noindent
2624 The @code{gcc} command accepts switches that control the
2625 compilation process. These switches are fully described in this section.
2626 First we briefly list all the switches, in alphabetical order, then we
2627 describe the switches in more detail in functionally grouped sections.
2628
2629 @menu
2630 * Output and Error Message Control::
2631 * Debugging and Assertion Control::
2632 * Run-Time Checks::
2633 * Stack Overflow Checking::
2634 * Run-Time Control::
2635 * Validity Checking::
2636 * Style Checking::
2637 * Using gcc for Syntax Checking::
2638 * Using gcc for Semantic Checking::
2639 * Compiling Ada 83 Programs::
2640 * Character Set Control::
2641 * File Naming Control::
2642 * Subprogram Inlining Control::
2643 * Auxiliary Output Control::
2644 * Debugging Control::
2645 * Units to Sources Mapping Files::
2646 @end menu
2647
2648 @table @code
2649 @cindex @code{-b} (@code{gcc})
2650 @item -b @var{target}
2651 Compile your program to run on @var{target}, which is the name of a
2652 system configuration. You must have a GNAT cross-compiler built if
2653 @var{target} is not the same as your host system.
2654
2655 @item -B@var{dir}
2656 @cindex @code{-B} (@code{gcc})
2657 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2658 from @var{dir} instead of the default location. Only use this switch
2659 when multiple versions of the GNAT compiler are available. See the
2660 @code{gcc} manual page for further details. You would normally use the
2661 @code{-b} or @code{-V} switch instead.
2662
2663 @item -c
2664 @cindex @code{-c} (@code{gcc})
2665 Compile. Always use this switch when compiling Ada programs.
2666
2667 Note: for some other languages when using @code{gcc}, notably in
2668 the case of C and C++, it is possible to use
2669 use @code{gcc} without a @code{-c} switch to
2670 compile and link in one step. In the case of GNAT, you
2671 cannot use this approach, because the binder must be run
2672 and @code{gcc} cannot be used to run the GNAT binder.
2673
2674 @item -g
2675 @cindex @code{-g} (@code{gcc})
2676 Generate debugging information. This information is stored in the object
2677 file and copied from there to the final executable file by the linker,
2678 where it can be read by the debugger. You must use the
2679 @code{-g} switch if you plan on using the debugger.
2680
2681 @item -I@var{dir}
2682 @cindex @code{-I} (@code{gcc})
2683 @cindex RTL
2684 Direct GNAT to search the @var{dir} directory for source files needed by
2685 the current compilation
2686 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2687
2688 @item -I-
2689 @cindex @code{-I-} (@code{gcc})
2690 @cindex RTL
2691 Except for the source file named in the command line, do not look for source files
2692 in the directory containing the source file named in the command line
2693 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2694
2695 @item -o @var{file}
2696 @cindex @code{-o} (@code{gcc})
2697 This switch is used in @code{gcc} to redirect the generated object file
2698 and its associated ALI file. Beware of this switch with GNAT, because it may
2699 cause the object file and ALI file to have different names which in turn
2700 may confuse the binder and the linker.
2701
2702 @item -O[@var{n}]
2703 @cindex @code{-O} (@code{gcc})
2704 @var{n} controls the optimization level.
2705
2706 @table @asis
2707 @item n = 0
2708 No optimization, the default setting if no @code{-O} appears
2709
2710 @item n = 1
2711 Normal optimization, the default if you specify @code{-O} without
2712 an operand.
2713
2714 @item n = 2
2715 Extensive optimization
2716
2717 @item n = 3
2718 Extensive optimization with automatic inlining. This applies only to
2719 inlining within a unit. For details on control of inter-unit inlining
2720 see @xref{Subprogram Inlining Control}.
2721 @end table
2722
2723
2724 @item --RTS=@var{rts-path}
2725 @cindex @code{--RTS} (@code{gcc})
2726 Specifies the default location of the runtime library. Same meaning as the
2727 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2728
2729 @item -S
2730 @cindex @code{-S} (@code{gcc})
2731 Used in place of @code{-c} to
2732 cause the assembler source file to be
2733 generated, using @file{.s} as the extension,
2734 instead of the object file.
2735 This may be useful if you need to examine the generated assembly code.
2736
2737 @item -v
2738 @cindex @code{-v} (@code{gcc})
2739 Show commands generated by the @code{gcc} driver. Normally used only for
2740 debugging purposes or if you need to be sure what version of the
2741 compiler you are executing.
2742
2743 @item -V @var{ver}
2744 @cindex @code{-V} (@code{gcc})
2745 Execute @var{ver} version of the compiler. This is the @code{gcc}
2746 version, not the GNAT version.
2747
2748 @item -gnata
2749 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2750 activated.
2751
2752 @item -gnatA
2753 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2754
2755 @item -gnatb
2756 Generate brief messages to @file{stderr} even if verbose mode set.
2757
2758 @item -gnatc
2759 Check syntax and semantics only (no code generation attempted).
2760
2761 @item -gnatC
2762 Compress debug information and external symbol name table entries.
2763
2764 @item -gnatD
2765 Output expanded source files for source level debugging. This switch
2766 also suppress generation of cross-reference information (see -gnatx).
2767
2768 @item -gnatec@var{path}
2769 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2770
2771 @item -gnatem@var{path}
2772 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2773
2774 @item -gnatE
2775 Full dynamic elaboration checks.
2776
2777 @item -gnatf
2778 Full errors. Multiple errors per line, all undefined references.
2779
2780 @item -gnatF
2781 Externals names are folded to all uppercase.
2782
2783 @item -gnatg
2784 Internal GNAT implementation mode. This should not be used for
2785 applications programs, it is intended only for use by the compiler
2786 and its run-time library. For documentation, see the GNAT sources.
2787
2788 @item -gnatG
2789 List generated expanded code in source form.
2790
2791 @item -gnati@var{c}
2792 Identifier character set
2793 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2794
2795 @item -gnath
2796 Output usage information. The output is written to @file{stdout}.
2797
2798 @item -gnatk@var{n}
2799 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2800
2801 @item -gnatl
2802 Output full source listing with embedded error messages.
2803
2804 @item -gnatm@var{n}
2805 Limit number of detected errors to @var{n} (1-999).
2806
2807 @item -gnatn
2808 Activate inlining across unit boundaries for subprograms for which
2809 pragma @code{inline} is specified.
2810
2811 @item -gnatN
2812 Activate front end inlining.
2813
2814 @item -fno-inline
2815 Suppresses all inlining, even if other optimization or inlining switches
2816 are set.
2817
2818 @item -fstack-check
2819 Activates stack checking. See separate section on stack checking for
2820 details of the use of this option.
2821
2822 @item -gnato
2823 Enable numeric overflow checking (which is not normally enabled by
2824 default). Not that division by zero is a separate check that is not
2825 controlled by this switch (division by zero checking is on by default).
2826
2827 @item -gnatp
2828 Suppress all checks.
2829
2830 @item -gnatq
2831 Don't quit; try semantics, even if parse errors.
2832
2833 @item -gnatQ
2834 Don't quit; generate @file{ali} and tree files even if illegalities.
2835
2836 @item -gnatP
2837 Enable polling. This is required on some systems (notably Windows NT) to
2838 obtain asynchronous abort and asynchronous transfer of control capability.
2839 See the description of pragma Polling in the GNAT Reference Manual for
2840 full details.
2841
2842 @item -gnatR[0/1/2/3][s]
2843 Output representation information for declared types and objects.
2844
2845 @item -gnats
2846 Syntax check only.
2847
2848 @item -gnatt
2849 Tree output file to be generated.
2850
2851 @item -gnatT nnn
2852 Set time slice to specified number of microseconds
2853
2854 @item -gnatu
2855 List units for this compilation.
2856
2857 @item -gnatU
2858 Tag all error messages with the unique string "error:"
2859
2860 @item -gnatv
2861 Verbose mode. Full error output with source lines to @file{stdout}.
2862
2863 @item -gnatV
2864 Control level of validity checking. See separate section describing
2865 this feature.
2866
2867 @item -gnatwxxx@var{xxx}
2868 Warning mode where
2869 @var{xxx} is a string of options describing the exact warnings that
2870 are enabled or disabled. See separate section on warning control.
2871
2872 @item -gnatW@var{e}
2873 Wide character encoding method
2874 (@var{e}=n/h/u/s/e/8).
2875
2876 @item -gnatx
2877 Suppress generation of cross-reference information.
2878
2879 @item -gnaty
2880 Enable built-in style checks. See separate section describing this feature.
2881
2882 @item -gnatz@var{m}
2883 Distribution stub generation and compilation
2884 (@var{m}=r/c for receiver/caller stubs).
2885
2886 @item -gnat83
2887 Enforce Ada 83 restrictions.
2888
2889 @item -pass-exit-codes
2890 Catch exit codes from the compiler and use the most meaningful as
2891 exit status.
2892 @end table
2893
2894 You may combine a sequence of GNAT switches into a single switch. For
2895 example, the combined switch
2896
2897 @cindex Combining GNAT switches
2898 @smallexample
2899 -gnatofi3
2900 @end smallexample
2901
2902 @noindent
2903 is equivalent to specifying the following sequence of switches:
2904
2905 @smallexample
2906 -gnato -gnatf -gnati3
2907 @end smallexample
2908
2909 @noindent
2910 The following restrictions apply to the combination of switches
2911 in this manner:
2912
2913 @itemize @bullet
2914 @item
2915 The switch @option{-gnatc} if combined with other switches must come
2916 first in the string.
2917
2918 @item
2919 The switch @option{-gnats} if combined with other switches must come
2920 first in the string.
2921
2922 @item
2923 Once a "y" appears in the string (that is a use of the @option{-gnaty}
2924 switch), then all further characters in the switch are interpreted
2925 as style modifiers (see description of @option{-gnaty}).
2926
2927 @item
2928 Once a "d" appears in the string (that is a use of the @option{-gnatd}
2929 switch), then all further characters in the switch are interpreted
2930 as debug flags (see description of @option{-gnatd}).
2931
2932 @item
2933 Once a "w" appears in the string (that is a use of the @option{-gnatw}
2934 switch), then all further characters in the switch are interpreted
2935 as warning mode modifiers (see description of @option{-gnatw}).
2936
2937 @item
2938 Once a "V" appears in the string (that is a use of the @option{-gnatV}
2939 switch), then all further characters in the switch are interpreted
2940 as validity checking options (see description of @option{-gnatV}).
2941
2942 @end itemize
2943
2944 @node Output and Error Message Control
2945 @subsection Output and Error Message Control
2946 @findex stderr
2947
2948 @noindent
2949 The standard default format for error messages is called "brief format."
2950 Brief format messages are written to @file{stderr} (the standard error
2951 file) and have the following form:
2952
2953 @smallexample
2954 @iftex
2955 @leftskip=.7cm
2956 @end iftex
2957 e.adb:3:04: Incorrect spelling of keyword "function"
2958 e.adb:4:20: ";" should be "is"
2959 @end smallexample
2960
2961 @noindent
2962 The first integer after the file name is the line number in the file,
2963 and the second integer is the column number within the line.
2964 @code{glide} can parse the error messages
2965 and point to the referenced character.
2966 The following switches provide control over the error message
2967 format:
2968
2969 @table @code
2970 @item -gnatv
2971 @cindex @option{-gnatv} (@code{gcc})
2972 @findex stdout
2973 The v stands for verbose.
2974 The effect of this setting is to write long-format error
2975 messages to @file{stdout} (the standard output file.
2976 The same program compiled with the
2977 @option{-gnatv} switch would generate:
2978
2979 @smallexample
2980 @group
2981 @cartouche
2982 3. funcion X (Q : Integer)
2983    |
2984 >>> Incorrect spelling of keyword "function"
2985 4. return Integer;
2986                  |
2987 >>> ";" should be "is"
2988 @end cartouche
2989 @end group
2990 @end smallexample
2991
2992 @noindent
2993 The vertical bar indicates the location of the error, and the @samp{>>>}
2994 prefix can be used to search for error messages. When this switch is
2995 used the only source lines output are those with errors.
2996
2997 @item -gnatl
2998 @cindex @option{-gnatl} (@code{gcc})
2999 The @code{l} stands for list.
3000 This switch causes a full listing of
3001 the file to be generated. The output might look as follows:
3002
3003 @smallexample
3004 @group
3005 @cartouche
3006  1. procedure E is
3007  2.    V : Integer;
3008  3.    funcion X (Q : Integer)
3009        |
3010     >>> Incorrect spelling of keyword "function"
3011  4.     return Integer;
3012                       |
3013     >>> ";" should be "is"
3014  5.    begin
3015  6.       return Q + Q;
3016  7.    end;
3017  8. begin
3018  9.    V := X + X;
3019 10.end E;
3020 @end cartouche
3021 @end group
3022 @end smallexample
3023
3024 @noindent
3025 @findex stderr
3026 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3027 standard output is redirected, a brief summary is written to
3028 @file{stderr} (standard error) giving the number of error messages and
3029 warning messages generated.
3030
3031 @item -gnatU
3032 @cindex @option{-gnatU} (@code{gcc})
3033 This switch forces all error messages to be preceded by the unique
3034 string "error:". This means that error messages take a few more
3035 characters in space, but allows easy searching for and identification
3036 of error messages.
3037
3038 @item -gnatb
3039 @cindex @option{-gnatb} (@code{gcc})
3040 The @code{b} stands for brief.
3041 This switch causes GNAT to generate the
3042 brief format error messages to @file{stderr} (the standard error
3043 file) as well as the verbose
3044 format message or full listing (which as usual is written to
3045 @file{stdout} (the standard output file).
3046
3047 @item -gnatm@var{n}
3048 @cindex @option{-gnatm} (@code{gcc})
3049 The @code{m} stands for maximum.
3050 @var{n} is a decimal integer in the
3051 range of 1 to 999 and limits the number of error messages to be
3052 generated. For example, using @option{-gnatm2} might yield
3053
3054 @smallexample
3055 @iftex
3056 @leftskip=.7cm
3057 @end iftex
3058 e.adb:3:04: Incorrect spelling of keyword "function"
3059 e.adb:5:35: missing ".."
3060 fatal error: maximum errors reached
3061 compilation abandoned
3062 @end smallexample
3063
3064 @item -gnatf
3065 @cindex @option{-gnatf} (@code{gcc})
3066 @cindex Error messages, suppressing
3067 The @code{f} stands for full.
3068 Normally, the compiler suppresses error messages that are likely to be
3069 redundant. This switch causes all error
3070 messages to be generated. In particular, in the case of
3071 references to undefined variables. If a given variable is referenced
3072 several times, the normal format of messages is
3073 @smallexample
3074 @iftex
3075 @leftskip=.7cm
3076 @end iftex
3077 e.adb:7:07: "V" is undefined (more references follow)
3078 @end smallexample
3079
3080 @noindent
3081 where the parenthetical comment warns that there are additional
3082 references to the variable @code{V}. Compiling the same program with the
3083 @option{-gnatf} switch yields
3084
3085 @smallexample
3086 e.adb:7:07: "V" is undefined
3087 e.adb:8:07: "V" is undefined
3088 e.adb:8:12: "V" is undefined
3089 e.adb:8:16: "V" is undefined
3090 e.adb:9:07: "V" is undefined
3091 e.adb:9:12: "V" is undefined
3092 @end smallexample
3093
3094 @item -gnatq
3095 @cindex @option{-gnatq} (@code{gcc})
3096 The @code{q} stands for quit (really "don't quit").
3097 In normal operation mode, the compiler first parses the program and
3098 determines if there are any syntax errors. If there are, appropriate
3099 error messages are generated and compilation is immediately terminated.
3100 This switch tells
3101 GNAT to continue with semantic analysis even if syntax errors have been
3102 found. This may enable the detection of more errors in a single run. On
3103 the other hand, the semantic analyzer is more likely to encounter some
3104 internal fatal error when given a syntactically invalid tree.
3105
3106 @item -gnatQ
3107 In normal operation mode, the @file{ali} file is not generated if any
3108 illegalities are detected in the program. The use of @option{-gnatQ} forces
3109 generation of the @file{ali} file. This file is marked as being in
3110 error, so it cannot be used for binding purposes, but it does contain
3111 reasonably complete cross-reference information, and thus may be useful
3112 for use by tools (e.g. semantic browsing tools or integrated development
3113 environments) that are driven from the @file{ali} file.
3114
3115 In addition, if @option{-gnatt} is also specified, then the tree file is
3116 generated even if there are illegalities. It may be useful in this case
3117 to also specify @option{-gnatq} to ensure that full semantic processing
3118 occurs. The resulting tree file can be processed by ASIS, for the purpose
3119 of providing partial information about illegal units, but if the error
3120 causes the tree to be badly malformed, then ASIS may crash during the
3121 analysis.
3122
3123 @end table
3124
3125 @noindent
3126 In addition to error messages, which correspond to illegalities as defined
3127 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3128 situations.
3129
3130 @cindex Warning messages
3131 First, the compiler considers some constructs suspicious and generates a
3132 warning message to alert you to a possible error. Second, if the
3133 compiler detects a situation that is sure to raise an exception at
3134 run time, it generates a warning message. The following shows an example
3135 of warning messages:
3136 @smallexample
3137 @iftex
3138 @leftskip=.2cm
3139 @end iftex
3140 e.adb:4:24: warning: creation of object may raise Storage_Error
3141 e.adb:10:17: warning: static value out of range
3142 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3143
3144 @end smallexample
3145
3146 @noindent
3147 GNAT considers a large number of situations as appropriate
3148 for the generation of warning messages. As always, warnings are not
3149 definite indications of errors. For example, if you do an out-of-range
3150 assignment with the deliberate intention of raising a
3151 @code{Constraint_Error} exception, then the warning that may be
3152 issued does not indicate an error. Some of the situations for which GNAT
3153 issues warnings (at least some of the time) are given in the following
3154 list, which is not necessarily complete.
3155
3156 @itemize @bullet
3157 @item
3158 Possible infinitely recursive calls
3159
3160 @item
3161 Out-of-range values being assigned
3162
3163 @item
3164 Possible order of elaboration problems
3165
3166 @item
3167 Unreachable code
3168
3169 @item
3170 Fixed-point type declarations with a null range
3171
3172 @item
3173 Variables that are never assigned a value
3174
3175 @item
3176 Variables that are referenced before being initialized
3177
3178 @item
3179 Task entries with no corresponding accept statement
3180
3181 @item
3182 Duplicate accepts for the same task entry in a select
3183
3184 @item
3185 Objects that take too much storage
3186
3187 @item
3188 Unchecked conversion between types of differing sizes
3189
3190 @item
3191 Missing return statements along some execution paths in a function
3192
3193 @item
3194 Incorrect (unrecognized) pragmas
3195
3196 @item
3197 Incorrect external names
3198
3199 @item
3200 Allocation from empty storage pool
3201
3202 @item
3203 Potentially blocking operations in protected types
3204
3205 @item
3206 Suspicious parenthesization of expressions
3207
3208 @item
3209 Mismatching bounds in an aggregate
3210
3211 @item
3212 Attempt to return local value by reference
3213
3214 @item
3215 Unrecognized pragmas
3216
3217 @item
3218 Premature instantiation of a generic body
3219
3220 @item
3221 Attempt to pack aliased components
3222
3223 @item
3224 Out of bounds array subscripts
3225
3226 @item
3227 Wrong length on string assignment
3228
3229 @item
3230 Violations of style rules if style checking is enabled
3231
3232 @item
3233 Unused with clauses
3234
3235 @item
3236 Bit_Order usage that does not have any effect
3237
3238 @item
3239 Compile time biased rounding of floating-point constant
3240
3241 @item
3242 Standard.Duration used to resolve universal fixed expression
3243
3244 @item
3245 Dereference of possibly null value
3246
3247 @item
3248 Declaration that is likely to cause storage error
3249
3250 @item
3251 Internal GNAT unit with'ed by application unit
3252
3253 @item
3254 Values known to be out of range at compile time
3255
3256 @item
3257 Unreferenced labels and variables
3258
3259 @item
3260 Address overlays that could clobber memory
3261
3262 @item
3263 Unexpected initialization when address clause present
3264
3265 @item
3266 Bad alignment for address clause
3267
3268 @item
3269 Useless type conversions
3270
3271 @item
3272 Redundant assignment statements
3273
3274 @item
3275 Accidental hiding of name by child unit
3276
3277 @item
3278 Unreachable code
3279
3280 @item
3281 Access before elaboration detected at compile time
3282
3283 @item
3284 A range in a @code{for} loop that is known to be null or might be null
3285
3286 @end itemize
3287
3288 @noindent
3289 The following switches are available to control the handling of
3290 warning messages:
3291
3292 @table @code
3293 @item -gnatwa (activate all optional errors)
3294 @cindex @option{-gnatwa} (@code{gcc})
3295 This switch activates most optional warning messages, see remaining list
3296 in this section for details on optional warning messages that can be
3297 individually controlled. The warnings that are not turned on by this
3298 switch are @option{-gnatwb} (biased rounding),
3299 @option{-gnatwd} (implicit dereferencing),
3300 and @option{-gnatwh} (hiding). All other optional warnings are
3301 turned on.
3302
3303 @item -gnatwA (suppress all optional errors)
3304 @cindex @option{-gnatwA} (@code{gcc})
3305 This switch suppresses all optional warning messages, see remaining list
3306 in this section for details on optional warning messages that can be
3307 individually controlled.
3308
3309 @item -gnatwb (activate warnings on biased rounding)
3310 @cindex @option{-gnatwb} (@code{gcc})
3311 @cindex Rounding, biased
3312 @cindex Biased rounding
3313 If a static floating-point expression has a value that is exactly half
3314 way between two adjacent machine numbers, then the rules of Ada
3315 (Ada Reference Manual, section 4.9(38)) require that this rounding
3316 be done away from zero, even if the normal unbiased rounding rules
3317 at run time would require rounding towards zero. This warning message
3318 alerts you to such instances where compile-time rounding and run-time
3319 rounding are not equivalent. If it is important to get proper run-time
3320 rounding, then you can force this by making one of the operands into
3321 a variable. The default is that such warnings are not generated.
3322 Note that @option{-gnatwa} does not affect the setting of
3323 this warning option.
3324
3325 @item -gnatwB (suppress warnings on biased rounding)
3326 @cindex @option{-gnatwB} (@code{gcc})
3327 This switch disables warnings on biased rounding.
3328
3329 @item -gnatwc (activate warnings on conditionals)
3330 @cindex @option{-gnatwc} (@code{gcc})
3331 @cindex Conditionals, constant
3332 This switch activates warnings for conditional expressions used in
3333 tests that are known to be True or False at compile time. The default
3334 is that such warnings are not generated.
3335 This warning can also be turned on using @option{-gnatwa}.
3336
3337 @item -gnatwC (suppress warnings on conditionals)
3338 @cindex @option{-gnatwC} (@code{gcc})
3339 This switch suppresses warnings for conditional expressions used in
3340 tests that are known to be True or False at compile time.
3341
3342 @item -gnatwd (activate warnings on implicit dereferencing)
3343 @cindex @option{-gnatwd} (@code{gcc})
3344 If this switch is set, then the use of a prefix of an access type
3345 in an indexed component, slice, or selected component without an
3346 explicit @code{.all} will generate a warning. With this warning
3347 enabled, access checks occur only at points where an explicit
3348 @code{.all} appears in the source code (assuming no warnings are
3349 generated as a result of this switch). The default is that such
3350 warnings are not generated.
3351 Note that @option{-gnatwa} does not affect the setting of
3352 this warning option.
3353
3354 @item -gnatwD (suppress warnings on implicit dereferencing)
3355 @cindex @option{-gnatwD} (@code{gcc})
3356 @cindex Implicit dereferencing
3357 @cindex Dereferencing, implicit
3358 This switch suppresses warnings for implicit deferences in
3359 indexed components, slices, and selected components.
3360
3361 @item -gnatwe (treat warnings as errors)
3362 @cindex @option{-gnatwe} (@code{gcc})
3363 @cindex Warnings, treat as error
3364 This switch causes warning messages to be treated as errors.
3365 The warning string still appears, but the warning messages are counted
3366 as errors, and prevent the generation of an object file.
3367
3368 @item -gnatwf (activate warnings on unreferenced formals)
3369 @cindex @option{-gnatwf} (@code{gcc})
3370 @cindex Formals, unreferenced
3371 This switch causes a warning to be generated if a formal parameter
3372 is not referenced in the body of the subprogram. This warning can
3373 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3374
3375 @item -gnatwF (suppress warnings on unreferenced formals)
3376 @cindex @option{-gnatwF} (@code{gcc})
3377 This switch suppresses warnings for unreferenced formal
3378 parameters. Note that the
3379 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3380 effect of warning on unreferenced entities other than subprogram
3381 formals.
3382
3383 @item -gnatwh (activate warnings on hiding)
3384 @cindex @option{-gnatwh} (@code{gcc})
3385 @cindex Hiding of Declarations
3386 This switch activates warnings on hiding declarations.
3387 A declaration is considered hiding
3388 if it is for a non-overloadable entity, and it declares an entity with the
3389 same name as some other entity that is directly or use-visible. The default
3390 is that such warnings are not generated.
3391 Note that @option{-gnatwa} does not affect the setting of this warning option.
3392
3393 @item -gnatwH (suppress warnings on hiding)
3394 @cindex @option{-gnatwH} (@code{gcc})
3395 This switch suppresses warnings on hiding declarations.
3396
3397 @item -gnatwi (activate warnings on implementation units).
3398 @cindex @option{-gnatwi} (@code{gcc})
3399 This switch activates warnings for a @code{with} of an internal GNAT
3400 implementation unit, defined as any unit from the @code{Ada},
3401 @code{Interfaces}, @code{GNAT},
3402  or @code{System}
3403 hierarchies that is not
3404 documented in either the Ada Reference Manual or the GNAT
3405 Programmer's Reference Manual. Such units are intended only
3406 for internal implementation purposes and should not be @code{with}'ed
3407 by user programs. The default is that such warnings are generated
3408 This warning can also be turned on using @option{-gnatwa}.
3409
3410 @item -gnatwI (disable warnings on implementation units).
3411 @cindex @option{-gnatwI} (@code{gcc})
3412 This switch disables warnings for a @code{with} of an internal GNAT
3413 implementation unit.
3414
3415 @item -gnatwl (activate warnings on elaboration pragmas)
3416 @cindex @option{-gnatwl} (@code{gcc})
3417 @cindex Elaboration, warnings
3418 This switch activates warnings on missing pragma Elaborate_All statements.
3419 See the section in this guide on elaboration checking for details on
3420 when such pragma should be used. The default is that such warnings
3421 are not generated.
3422 This warning can also be turned on using @option{-gnatwa}.
3423
3424 @item -gnatwL (suppress warnings on elaboration pragmas)
3425 @cindex @option{-gnatwL} (@code{gcc})
3426 This switch suppresses warnings on missing pragma Elaborate_All statements.
3427 See the section in this guide on elaboration checking for details on
3428 when such pragma should be used.
3429
3430 @item -gnatwo (activate warnings on address clause overlays)
3431 @cindex @option{-gnatwo} (@code{gcc})
3432 @cindex Address Clauses, warnings
3433 This switch activates warnings for possibly unintended initialization
3434 effects of defining address clauses that cause one variable to overlap
3435 another. The default is that such warnings are generated.
3436 This warning can also be turned on using @option{-gnatwa}.
3437
3438 @item -gnatwO (suppress warnings on address clause overlays)
3439 @cindex @option{-gnatwO} (@code{gcc})
3440 This switch suppresses warnings on possibly unintended initialization
3441 effects of defining address clauses that cause one variable to overlap
3442 another.
3443
3444 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3445 @cindex @option{-gnatwp} (@code{gcc})
3446 @cindex Inlining, warnings
3447 This switch activates warnings for failure of front end inlining
3448 (activated by @option{-gnatN}) to inline a particular call. There are
3449 many reasons for not being able to inline a call, including most
3450 commonly that the call is too complex to inline.
3451 This warning can also be turned on using @option{-gnatwa}.
3452
3453 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3454 @cindex @option{-gnatwP} (@code{gcc})
3455 This switch suppresses warnings on ineffective pragma Inlines. If the
3456 inlining mechanism cannot inline a call, it will simply ignore the
3457 request silently.
3458
3459 @item -gnatwr (activate warnings on redundant constructs)
3460 @cindex @option{-gnatwr} (@code{gcc})
3461 This switch activates warnings for redundant constructs. The following
3462 is the current list of constructs regarded as redundant:
3463 This warning can also be turned on using @option{-gnatwa}.
3464
3465 @itemize @bullet
3466 @item
3467 Assignment of an item to itself.
3468 @item
3469 Type conversion that converts an expression to its own type.
3470 @item
3471 Use of the attribute @code{Base} where @code{typ'Base} is the same
3472 as @code{typ}.
3473 @item
3474 Use of pragma @code{Pack} when all components are placed by a record
3475 representation clause.
3476 @end itemize
3477
3478 @item -gnatwR (suppress warnings on redundant constructs)
3479 @cindex @option{-gnatwR} (@code{gcc})
3480 This switch suppresses warnings for redundant constructs.
3481
3482 @item -gnatws (suppress all warnings)
3483 @cindex @option{-gnatws} (@code{gcc})
3484 This switch completely suppresses the
3485 output of all warning messages from the GNAT front end.
3486 Note that it does not suppress warnings from the @code{gcc} back end.
3487 To suppress these back end warnings as well, use the switch @code{-w}
3488 in addition to @option{-gnatws}.
3489
3490 @item -gnatwu (activate warnings on unused entities)
3491 @cindex @option{-gnatwu} (@code{gcc})
3492 This switch activates warnings to be generated for entities that
3493 are defined but not referenced, and for units that are @code{with}'ed
3494 and not
3495 referenced. In the case of packages, a warning is also generated if
3496 no entities in the package are referenced. This means that if the package
3497 is referenced but the only references are in @code{use}
3498 clauses or @code{renames}
3499 declarations, a warning is still generated. A warning is also generated
3500 for a generic package that is @code{with}'ed but never instantiated.
3501 In the case where a package or subprogram body is compiled, and there
3502 is a @code{with} on the corresponding spec
3503 that is only referenced in the body,
3504 a warning is also generated, noting that the
3505 @code{with} can be moved to the body. The default is that
3506 such warnings are not generated.
3507 This switch also activates warnings on unreferenced formals
3508 (it is includes the effect of @option{-gnatwf}).
3509 This warning can also be turned on using @option{-gnatwa}.
3510
3511 @item -gnatwU (suppress warnings on unused entities)
3512 @cindex @option{-gnatwU} (@code{gcc})
3513 This switch suppresses warnings for unused entities and packages.
3514 It also turns off warnings on unreferenced formals (and thus includes
3515 the effect of @option{-gnatwF}).
3516
3517 @noindent
3518 A string of warning parameters can be used in the same parameter. For example:
3519
3520 @smallexample
3521 -gnatwaLe
3522 @end smallexample
3523
3524 @noindent
3525 Would turn on all optional warnings except for elaboration pragma warnings,
3526 and also specify that warnings should be treated as errors.
3527
3528 @item -w
3529 @cindex @code{-w}
3530 This switch suppresses warnings from the @code{gcc} backend. It may be
3531 used in conjunction with @option{-gnatws} to ensure that all warnings
3532 are suppressed during the entire compilation process.
3533
3534 @end table
3535
3536 @node Debugging and Assertion Control
3537 @subsection Debugging and Assertion Control
3538
3539 @table @code
3540 @item -gnata
3541 @cindex @option{-gnata} (@code{gcc})
3542 @findex Assert
3543 @findex Debug
3544 @cindex Assertions
3545
3546 @noindent
3547 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3548 are ignored. This switch, where @samp{a} stands for assert, causes
3549 @code{Assert} and @code{Debug} pragmas to be activated.
3550
3551 The pragmas have the form:
3552
3553 @smallexample
3554 @group
3555 @cartouche
3556    @b{pragma} Assert (@var{Boolean-expression} [,
3557                       @var{static-string-expression}])
3558    @b{pragma} Debug (@var{procedure call})
3559 @end cartouche
3560 @end group
3561 @end smallexample
3562
3563 @noindent
3564 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3565 If the result is @code{True}, the pragma has no effect (other than
3566 possible side effects from evaluating the expression). If the result is
3567 @code{False}, the exception @code{Assert_Failure} declared in the package
3568 @code{System.Assertions} is
3569 raised (passing @var{static-string-expression}, if present, as the
3570 message associated with the exception). If no string expression is
3571 given the default is a string giving the file name and line number
3572 of the pragma.
3573
3574 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3575 @code{pragma Debug} may appear within a declaration sequence, allowing
3576 debugging procedures to be called between declarations.
3577
3578 @end table
3579
3580 @node Validity Checking
3581 @subsection Validity Checking
3582 @findex Validity Checking
3583
3584 @noindent
3585 The Ada 95 Reference Manual has specific requirements for checking
3586 for invalid values. In particular, RM 13.9.1 requires that the
3587 evaluation of invalid values (for example from unchecked conversions),
3588 not result in erroneous execution. In GNAT, the result of such an
3589 evaluation in normal default mode is to either use the value
3590 unmodified, or to raise Constraint_Error in those cases where use
3591 of the unmodified value would cause erroneous execution. The cases
3592 where unmodified values might lead to erroneous execution are case
3593 statements (where a wild jump might result from an invalid value),
3594 and subscripts on the left hand side (where memory corruption could
3595 occur as a result of an invalid value).
3596
3597 The @option{-gnatVx} switch allows more control over the validity checking
3598 mode. The @code{x} argument here is a string of letters which control which
3599 validity checks are performed in addition to the default checks described
3600 above.
3601
3602 @itemize @bullet
3603 @item
3604 @option{-gnatVc} Validity checks for copies
3605
3606 The right hand side of assignments, and the initializing values of
3607 object declarations are validity checked.
3608
3609 @item
3610 @option{-gnatVd} Default (RM) validity checks
3611
3612 Some validity checks are done by default following normal Ada semantics
3613 (RM 13.9.1 (9-11)).
3614 A check is done in case statements that the expression is within the range
3615 of the subtype. If it is not, Constraint_Error is raised.
3616 For assignments to array components, a check is done that the expression used
3617 as index is within the range. If it is not, Constraint_Error is raised.
3618 Both these validity checks may be turned off using switch @option{-gnatVD}.
3619 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3620 switch @option{-gnatVd} will leave the checks turned on.
3621 Switch @option{-gnatVD} should be used only if you are sure that all such
3622 expressions have valid values. If you use this switch and invalid values
3623 are present, then the program is erroneous, and wild jumps or memory
3624 overwriting may occur.
3625
3626 @item
3627 @option{-gnatVi} Validity checks for @code{in} mode parameters
3628
3629 Arguments for parameters of mode @code{in} are validity checked in function
3630 and procedure calls at the point of call.
3631
3632 @item
3633 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3634
3635 Arguments for parameters of mode @code{in out} are validity checked in
3636 procedure calls at the point of call. The @code{'m'} here stands for
3637 modify, since this concerns parameters that can be modified by the call.
3638 Note that there is no specific option to test @code{out} parameters,
3639 but any reference within the subprogram will be tested in the usual
3640 manner, and if an invalid value is copied back, any reference to it
3641 will be subject to validity checking.
3642
3643 @item
3644 @option{-gnatVo} Validity checks for operator and attribute operands
3645
3646 Arguments for predefined operators and attributes are validity checked.
3647 This includes all operators in package @code{Standard},
3648 the shift operators defined as intrinsic in package @code{Interfaces}
3649 and operands for attributes such as @code{Pos}.
3650
3651 @item
3652 @option{-gnatVr} Validity checks for function returns
3653
3654 The expression in @code{return} statements in functions is validity
3655 checked.
3656
3657 @item
3658 @option{-gnatVs} Validity checks for subscripts
3659
3660 All subscripts expressions are checked for validity, whether they appear
3661 on the right side or left side (in default mode only left side subscripts
3662 are validity checked).
3663
3664 @item
3665 @option{-gnatVt} Validity checks for tests
3666
3667 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3668 statements are checked, as well as guard expressions in entry calls.
3669
3670 @item
3671 @option{-gnatVf} Validity checks for floating-point values
3672
3673 In the absence of this switch, validity checking occurs only for discrete
3674 values. If @option{-gnatVf} is specified, then validity checking also applies
3675 for floating-point values, and NaN's and infinities are considered invalid,
3676 as well as out of range values for constrained types. Note that this means
3677 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3678 in which floating-point values are checked depends on the setting of other
3679 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3680 not matter) specifies that floating-point parameters of mode @code{in} should
3681 be validity checked.
3682
3683 @item
3684 @option{-gnatVa} All validity checks
3685
3686 All the above validity checks are turned on. That is @option{-gnatVa} is
3687 equivalent to @code{gnatVcdfimorst}.
3688
3689 @item
3690 @option{-gnatVn} No validity checks
3691
3692 This switch turns off all validity checking, including the default checking
3693 for case statements and left hand side subscripts. Note that the use of
3694 the switch @option{-gnatp} supresses all run-time checks, including
3695 validity checks, and thus implies @option{-gnatVn}.
3696
3697 @end itemize
3698
3699 The @option{-gnatV} switch may be followed by a string of letters to turn on
3700 a series of validity checking options. For example, @option{-gnatVcr} specifies
3701 that in addition to the default validity checking, copies and function
3702 return expressions be validity checked. In order to make it easier to specify
3703 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3704 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3705 on all validity checking options except for checking of @code{in out}
3706 procedure arguments.
3707
3708 The specification of additional validity checking generates extra code (and
3709 in the case of @option{-gnatva} the code expansion can be substantial. However,
3710 these additional checks can be very useful in smoking out cases of
3711 uninitialized variables, incorrect use of unchecked conversion, and other
3712 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3713 is useful in conjunction with the extra validity checking, since this
3714 ensures that wherever possible uninitialized variables have invalid values.
3715
3716 See also the pragma @code{Validity_Checks} which allows modification of
3717 the validity checking mode at the program source level, and also allows for
3718 temporary disabling of validity checks.
3719
3720 @node Style Checking
3721 @subsection Style Checking
3722 @findex Style checking
3723
3724 @noindent
3725 The -gnaty@var{x} switch causes the compiler to
3726 enforce specified style rules. A limited set of style rules has been used
3727 in writing the GNAT sources themselves. This switch allows user programs
3728 to activate all or some of these checks. If the source program fails a
3729 specified style check, an appropriate warning message is given, preceded by
3730 the character sequence "(style)".
3731 The string @var{x} is a sequence of letters or digits
3732 indicating the particular style
3733 checks to be performed. The following checks are defined:
3734
3735 @table @code
3736 @item 1-9 (specify indentation level)
3737 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3738 indentation is checked, with the digit indicating the indentation level
3739 required. The general style of required indentation is as specified by
3740 the examples in the Ada Reference Manual. Full line comments must be
3741 aligned with the @code{--} starting on a column that is a multiple of
3742 the alignment level.
3743
3744 @item a (check attribute casing)
3745 If the letter a appears in the string after @option{-gnaty} then
3746 attribute names, including the case of keywords such as @code{digits}
3747 used as attributes names, must be written in mixed case, that is, the
3748 initial letter and any letter following an underscore must be uppercase.
3749 All other letters must be lowercase.
3750
3751 @item b (blanks not allowed at statement end)
3752 If the letter b appears in the string after @option{-gnaty} then
3753 trailing blanks are not allowed at the end of statements. The purpose of this
3754 rule, together with h (no horizontal tabs), is to enforce a canonical format
3755 for the use of blanks to separate source tokens.
3756
3757 @item c (check comments)
3758 If the letter c appears in the string after @option{-gnaty} then
3759 comments must meet the following set of rules:
3760
3761 @itemize @bullet
3762
3763 @item
3764 The "--" that starts the column must either start in column one, or else
3765 at least one blank must precede this sequence.
3766
3767 @item
3768 Comments that follow other tokens on a line must have at least one blank
3769 following the "--" at the start of the comment.
3770
3771 @item
3772 Full line comments must have two blanks following the "--" that starts
3773 the comment, with the following exceptions.
3774
3775 @item
3776 A line consisting only of the "--" characters, possibly preceded by blanks
3777 is permitted.
3778
3779 @item
3780 A comment starting with "--x" where x is a special character is permitted.
3781 This alows proper processing of the output generated by specialized tools
3782 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3783 language (where --# is used). For the purposes of this rule, a special
3784 character is defined as being in one of the ASCII ranges
3785 16#21#..16#2F# or 16#3A#..16#3F#.
3786
3787 @item
3788 A line consisting entirely of minus signs, possibly preceded by blanks, is
3789 permitted. This allows the construction of box comments where lines of minus
3790 signs are used to form the top and bottom of the box.
3791
3792 @item
3793 If a comment starts and ends with "--" is permitted as long as at least
3794 one blank follows the initial "--". Together with the preceding rule,
3795 this allows the construction of box comments, as shown in the following
3796 example:
3797 @smallexample
3798 ---------------------------
3799 -- This is a box comment --
3800 -- with two text lines.  --
3801 ---------------------------
3802 @end smallexample
3803 @end itemize
3804
3805 @item e (check end/exit labels)
3806 If the letter e appears in the string after @option{-gnaty} then
3807 optional labels on @code{end} statements ending subprograms and on
3808 @code{exit} statements exiting named loops, are required to be present.
3809
3810 @item f (no form feeds or vertical tabs)
3811 If the letter f appears in the string after @option{-gnaty} then
3812 neither form feeds nor vertical tab characters are not permitted
3813 in the source text.
3814
3815 @item h (no horizontal tabs)
3816 If the letter h appears in the string after @option{-gnaty} then
3817 horizontal tab characters are not permitted in the source text.
3818 Together with the b (no blanks at end of line) check, this
3819 enforces a canonical form for the use of blanks to separate
3820 source tokens.
3821
3822 @item i (check if-then layout)
3823 If the letter i appears in the string after @option{-gnaty},
3824 then the keyword @code{then} must appear either on the same
3825 line as corresponding @code{if}, or on a line on its own, lined
3826 up under the @code{if} with at least one non-blank line in between
3827 containing all or part of the condition to be tested.
3828
3829 @item k (check keyword casing)
3830 If the letter k appears in the string after @option{-gnaty} then
3831 all keywords must be in lower case (with the exception of keywords
3832 such as @code{digits} used as attribute names to which this check
3833 does not apply).
3834
3835 @item l (check layout)
3836 If the letter l appears in the string after @option{-gnaty} then
3837 layout of statement and declaration constructs must follow the
3838 recommendations in the Ada Reference Manual, as indicated by the
3839 form of the syntax rules. For example an @code{else} keyword must
3840 be lined up with the corresponding @code{if} keyword.
3841
3842 There are two respects in which the style rule enforced by this check
3843 option are more liberal than those in the Ada Reference Manual. First
3844 in the case of record declarations, it is permissible to put the
3845 @code{record} keyword on the same line as the @code{type} keyword, and
3846 then the @code{end} in @code{end record} must line up under @code{type}.
3847 For example, either of the following two layouts is acceptable:
3848
3849 @smallexample
3850 @group
3851 @cartouche
3852 @b{type} q @b{is record}
3853    a : integer;
3854    b : integer;
3855 @b{end record};
3856
3857 @b{type} q @b{is}
3858    @b{record}
3859       a : integer;
3860       b : integer;
3861    @b{end record};
3862 @end cartouche
3863 @end group
3864 @end smallexample
3865
3866 @noindent
3867 Second, in the case of a block statement, a permitted alternative
3868 is to put the block label on the same line as the @code{declare} or
3869 @code{begin} keyword, and then line the @code{end} keyword up under
3870 the block label. For example both the following are permitted:
3871
3872 @smallexample
3873 @group
3874 @cartouche
3875 Block : @b{declare}
3876    A : Integer := 3;
3877 @b{begin}
3878    Proc (A, A);
3879 @b{end} Block;
3880
3881 Block :
3882    @b{declare}
3883       A : Integer := 3;
3884    @b{begin}
3885       Proc (A, A);
3886    @b{end} Block;
3887 @end cartouche
3888 @end group
3889 @end smallexample
3890
3891 @noindent
3892 The same alternative format is allowed for loops. For example, both of
3893 the following are permitted:
3894
3895 @smallexample
3896 @group
3897 @cartouche
3898 Clear : @b{while} J < 10 @b{loop}
3899    A (J) := 0;
3900 @b{end loop} Clear;
3901
3902 Clear :
3903    @b{while} J < 10 @b{loop}
3904       A (J) := 0;
3905    @b{end loop} Clear;
3906 @end cartouche
3907 @end group
3908 @end smallexample
3909
3910 @item m (check maximum line length)
3911 If the letter m appears in the string after @option{-gnaty}
3912 then the length of source lines must not exceed 79 characters, including
3913 any trailing blanks. The value of 79 allows convenient display on an
3914 80 character wide device or window, allowing for possible special
3915 treatment of 80 character lines.
3916
3917 @item Mnnn (set maximum line length)
3918 If the sequence Mnnn, where nnn is a decimal number, appears in
3919 the string after @option{-gnaty} then the length of lines must not exceed the
3920 given value.
3921
3922 @item n (check casing of entities in Standard)
3923 If the letter n appears in the string
3924 after @option{-gnaty} then any identifier from Standard must be cased
3925 to match the presentation in the Ada Reference Manual (for example,
3926 @code{Integer} and @code{ASCII.NUL}).
3927
3928 @item o (check order of subprogram bodies)
3929 If the letter o appears in the string
3930 after @option{-gnaty} then all subprogram bodies in a given scope
3931 (e.g. a package body) must be in alphabetical order. The ordering
3932 rule uses normal Ada rules for comparing strings, ignoring casing
3933 of letters, except that if there is a trailing numeric suffix, then
3934 the value of this suffix is used in the ordering (e.g. Junk2 comes
3935 before Junk10).
3936
3937 @item p (check pragma casing)
3938 If the letter p appears in the string after @option{-gnaty} then
3939 pragma names must be written in mixed case, that is, the
3940 initial letter and any letter following an underscore must be uppercase.
3941 All other letters must be lowercase.
3942
3943 @item r (check references)
3944 If the letter r appears in the string after @option{-gnaty}
3945 then all identifier references must be cased in the same way as the
3946 corresponding declaration. No specific casing style is imposed on
3947 identifiers. The only requirement is for consistency of references
3948 with declarations.
3949
3950 @item s (check separate specs)
3951 If the letter s appears in the string after @option{-gnaty} then
3952 separate declarations ("specs") are required for subprograms (a
3953 body is not allowed to serve as its own declaration). The only
3954 exception is that parameterless library level procedures are
3955 not required to have a separate declaration. This exception covers
3956 the most frequent form of main program procedures.
3957
3958 @item t (check token spacing)
3959 If the letter t appears in the string after @option{-gnaty} then
3960 the following token spacing rules are enforced:
3961
3962 @itemize @bullet
3963
3964 @item
3965 The keywords @code{abs} and @code{not} must be followed by a space.
3966
3967 @item
3968 The token @code{=>} must be surrounded by spaces.
3969
3970 @item
3971 The token @code{<>} must be preceded by a space or a left parenthesis.
3972
3973 @item
3974 Binary operators other than @code{**} must be surrounded by spaces.
3975 There is no restriction on the layout of the @code{**} binary operator.
3976
3977 @item
3978 Colon must be surrounded by spaces.
3979
3980 @item
3981 Colon-equal (assignment) must be surrounded by spaces.
3982
3983 @item
3984 Comma must be the first non-blank character on the line, or be
3985 immediately preceded by a non-blank character, and must be followed
3986 by a space.
3987
3988 @item
3989 If the token preceding a left paren ends with a letter or digit, then
3990 a space must separate the two tokens.
3991
3992 @item
3993 A right parenthesis must either be the first non-blank character on
3994 a line, or it must be preceded by a non-blank character.
3995
3996 @item
3997 A semicolon must not be preceded by a space, and must not be followed by
3998 a non-blank character.
3999
4000 @item
4001 A unary plus or minus may not be followed by a space.
4002
4003 @item
4004 A vertical bar must be surrounded by spaces.
4005 @end itemize
4006
4007 @noindent
4008 In the above rules, appearing in column one is always permitted, that is,
4009 counts as meeting either a requirement for a required preceding space,
4010 or as meeting a requirement for no preceding space.
4011
4012 Appearing at the end of a line is also always permitted, that is, counts
4013 as meeting either a requirement for a following space, or as meeting
4014 a requirement for no following space.
4015
4016 @end table
4017
4018 @noindent
4019 If any of these style rules is violated, a message is generated giving
4020 details on the violation. The initial characters of such messages are
4021 always "(style)". Note that these messages are treated as warning
4022 messages, so they normally do not prevent the generation of an object
4023 file. The @option{-gnatwe} switch can be used to treat warning messages,
4024 including style messages, as fatal errors.
4025
4026 @noindent
4027 The switch
4028 @option{-gnaty} on its own (that is not followed by any letters or digits),
4029 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4030 options are enabled with
4031 the exception of -gnatyo,
4032 with an indentation level of 3. This is the standard
4033 checking option that is used for the GNAT sources.
4034
4035 @node Run-Time Checks
4036 @subsection Run-Time Checks
4037 @cindex Division by zero
4038 @cindex Access before elaboration
4039 @cindex Checks, division by zero
4040 @cindex Checks, access before elaboration
4041
4042 @noindent
4043 If you compile with the default options, GNAT will insert many run-time
4044 checks into the compiled code, including code that performs range
4045 checking against constraints, but not arithmetic overflow checking for
4046 integer operations (including division by zero) or checks for access
4047 before elaboration on subprogram calls. All other run-time checks, as
4048 required by the Ada 95 Reference Manual, are generated by default.
4049 The following @code{gcc} switches refine this default behavior:
4050
4051 @table @code
4052 @item -gnatp
4053 @cindex @option{-gnatp} (@code{gcc})
4054 @cindex Suppressing checks
4055 @cindex Checks, suppressing
4056 @findex Suppress
4057 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4058 had been present in the source. Validity checks are also suppressed (in
4059 other words @option{-gnatp} also implies @option{-gnatVn}.
4060 Use this switch to improve the performance
4061 of the code at the expense of safety in the presence of invalid data or
4062 program bugs.
4063
4064 @item -gnato
4065 @cindex @option{-gnato} (@code{gcc})
4066 @cindex Overflow checks
4067 @cindex Check, overflow
4068 Enables overflow checking for integer operations.
4069 This causes GNAT to generate slower and larger executable
4070 programs by adding code to check for overflow (resulting in raising
4071 @code{Constraint_Error} as required by standard Ada
4072 semantics). These overflow checks correspond to situations in which
4073 the true value of the result of an operation may be outside the base
4074 range of the result type. The following example shows the distinction:
4075
4076 @smallexample
4077 X1 : Integer := Integer'Last;
4078 X2 : Integer range 1 .. 5 := 5;
4079 ...
4080 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4081 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4082 @end smallexample
4083
4084 @noindent
4085 Here the first addition results in a value that is outside the base range
4086 of Integer, and hence requires an overflow check for detection of the
4087 constraint error. The second increment operation results in a violation
4088 of the explicit range constraint, and such range checks are always
4089 performed. Basically the compiler can assume that in the absence of
4090 the @option{-gnato} switch that any value of type @code{xxx} is
4091 in range of the base type of @code{xxx}.
4092
4093 @findex Machine_Overflows
4094 Note that the @option{-gnato} switch does not affect the code generated
4095 for any floating-point operations; it applies only to integer
4096 semantics).
4097 For floating-point, GNAT has the @code{Machine_Overflows}
4098 attribute set to @code{False} and the normal mode of operation is to
4099 generate IEEE NaN and infinite values on overflow or invalid operations
4100 (such as dividing 0.0 by 0.0).
4101
4102 The reason that we distinguish overflow checking from other kinds of
4103 range constraint checking is that a failure of an overflow check can
4104 generate an incorrect value, but cannot cause erroneous behavior. This
4105 is unlike the situation with a constraint check on an array subscript,
4106 where failure to perform the check can result in random memory description,
4107 or the range check on a case statement, where failure to perform the check
4108 can cause a wild jump.
4109
4110 Note again that @option{-gnato} is off by default, so overflow checking is
4111 not performed in default mode. This means that out of the box, with the
4112 default settings, GNAT does not do all the checks expected from the
4113 language description in the Ada Reference Manual. If you want all constraint
4114 checks to be performed, as described in this Manual, then you must
4115 explicitly use the -gnato switch either on the @code{gnatmake} or
4116 @code{gcc} command.
4117
4118 @item -gnatE
4119 @cindex @option{-gnatE} (@code{gcc})
4120 @cindex Elaboration checks
4121 @cindex Check, elaboration
4122 Enables dynamic checks for access-before-elaboration
4123 on subprogram calls and generic instantiations.
4124 For full details of the effect and use of this switch,
4125 @xref{Compiling Using gcc}.
4126 @end table
4127
4128 @findex Unsuppress
4129 @noindent
4130 The setting of these switches only controls the default setting of the
4131 checks. You may modify them using either @code{Suppress} (to remove
4132 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4133 the program source.
4134
4135 @node Stack Overflow Checking
4136 @subsection Stack Overflow Checking
4137 @cindex Stack Overflow Checking
4138 @cindex -fstack-check
4139
4140 @noindent
4141 For most operating systems, @code{gcc} does not perform stack overflow
4142 checking by default. This means that if the main environment task or
4143 some other task exceeds the available stack space, then unpredictable
4144 behavior will occur.
4145
4146 To activate stack checking, compile all units with the gcc option
4147 @code{-fstack-check}. For example:
4148
4149 @smallexample
4150 gcc -c -fstack-check package1.adb
4151 @end smallexample
4152
4153 @noindent
4154 Units compiled with this option will generate extra instructions to check
4155 that any use of the stack (for procedure calls or for declaring local
4156 variables in declare blocks) do not exceed the available stack space.
4157 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4158
4159 For declared tasks, the stack size is always controlled by the size
4160 given in an applicable @code{Storage_Size} pragma (or is set to
4161 the default size if no pragma is used.
4162
4163 For the environment task, the stack size depends on
4164 system defaults and is unknown to the compiler. The stack
4165 may even dynamically grow on some systems, precluding the
4166 normal Ada semantics for stack overflow. In the worst case,
4167 unbounded stack usage, causes unbounded stack expansion
4168 resulting in the system running out of virtual memory.
4169
4170 The stack checking may still work correctly if a fixed
4171 size stack is allocated, but this cannot be guaranteed.
4172 To ensure that a clean exception is signalled for stack
4173 overflow, set the environment variable
4174 @code{GNAT_STACK_LIMIT} to indicate the maximum
4175 stack area that can be used, as in:
4176 @cindex GNAT_STACK_LIMIT
4177
4178 @smallexample
4179 SET GNAT_STACK_LIMIT 1600
4180 @end smallexample
4181
4182 @noindent
4183 The limit is given in kilobytes, so the above declaration would
4184 set the stack limit of the environment task to 1.6 megabytes.
4185 Note that the only purpose of this usage is to limit the amount
4186 of stack used by the environment task. If it is necessary to
4187 increase the amount of stack for the environment task, then this
4188 is an operating systems issue, and must be addressed with the
4189 appropriate operating systems commands.
4190
4191 @node Run-Time Control
4192 @subsection Run-Time Control
4193
4194 @table @code
4195 @item -gnatT nnn
4196 @cindex @option{-gnatT} (@code{gcc})
4197 @cindex Time Slicing
4198
4199 @noindent
4200 The @code{gnatT} switch can be used to specify the time-slicing value
4201 to be used for task switching between equal priority tasks. The value
4202 @code{nnn} is given in microseconds as a decimal integer.
4203
4204 Setting the time-slicing value is only effective if the underlying thread
4205 control system can accommodate time slicing. Check the documentation of
4206 your operating system for details. Note that the time-slicing value can
4207 also be set by use of pragma @code{Time_Slice} or by use of the
4208 @code{t} switch in the gnatbind step. The pragma overrides a command
4209 line argument if both are present, and the @code{t} switch for gnatbind
4210 overrides both the pragma and the @code{gcc} command line switch.
4211 @end table
4212
4213 @node Using gcc for Syntax Checking
4214 @subsection Using @code{gcc} for Syntax Checking
4215 @table @code
4216 @item -gnats
4217 @cindex @option{-gnats} (@code{gcc})
4218
4219 @noindent
4220 The @code{s} stands for syntax.
4221
4222 Run GNAT in syntax checking only mode. For
4223 example, the command
4224
4225 @smallexample
4226 $ gcc -c -gnats x.adb
4227 @end smallexample
4228
4229 @noindent
4230 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4231 series of files in a single command
4232 , and can use wild cards to specify such a group of files.
4233 Note that you must specify the @code{-c} (compile
4234 only) flag in addition to the @option{-gnats} flag.
4235 .
4236
4237 You may use other switches in conjunction with @option{-gnats}. In
4238 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4239 format of any generated error messages.
4240
4241 The output is simply the error messages, if any. No object file or ALI
4242 file is generated by a syntax-only compilation. Also, no units other
4243 than the one specified are accessed. For example, if a unit @code{X}
4244 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4245 check only mode does not access the source file containing unit
4246 @code{Y}.
4247
4248 @cindex Multiple units, syntax checking
4249 Normally, GNAT allows only a single unit in a source file. However, this
4250 restriction does not apply in syntax-check-only mode, and it is possible
4251 to check a file containing multiple compilation units concatenated
4252 together. This is primarily used by the @code{gnatchop} utility
4253 (@pxref{Renaming Files Using gnatchop}).
4254 @end table
4255
4256 @node Using gcc for Semantic Checking
4257 @subsection Using @code{gcc} for Semantic Checking
4258 @table @code
4259 @item -gnatc
4260 @cindex @option{-gnatc} (@code{gcc})
4261
4262 @noindent
4263 The @code{c} stands for check.
4264 Causes the compiler to operate in semantic check mode,
4265 with full checking for all illegalities specified in the
4266 Ada 95 Reference Manual, but without generation of any object code
4267 (no object file is generated).
4268
4269 Because dependent files must be accessed, you must follow the GNAT
4270 semantic restrictions on file structuring to operate in this mode:
4271
4272 @itemize @bullet
4273 @item
4274 The needed source files must be accessible
4275 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4276
4277 @item
4278 Each file must contain only one compilation unit.
4279
4280 @item
4281 The file name and unit name must match (@pxref{File Naming Rules}).
4282 @end itemize
4283
4284 The output consists of error messages as appropriate. No object file is
4285 generated. An @file{ALI} file is generated for use in the context of
4286 cross-reference tools, but this file is marked as not being suitable
4287 for binding (since no object file is generated).
4288 The checking corresponds exactly to the notion of
4289 legality in the Ada 95 Reference Manual.
4290
4291 Any unit can be compiled in semantics-checking-only mode, including
4292 units that would not normally be compiled (subunits,
4293 and specifications where a separate body is present).
4294 @end table
4295
4296 @node Compiling Ada 83 Programs
4297 @subsection Compiling Ada 83 Programs
4298 @table @code
4299 @cindex Ada 83 compatibility
4300 @item -gnat83
4301 @cindex @option{-gnat83} (@code{gcc})
4302 @cindex ACVC, Ada 83 tests
4303
4304 @noindent
4305 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4306 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4307 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4308 where this can be done easily.
4309 It is not possible to guarantee this switch does a perfect
4310 job; for example, some subtle tests, such as are
4311 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4312 95), may not compile correctly. However, for most purposes, using
4313 this switch should help to ensure that programs that compile correctly
4314 under the @option{-gnat83} switch can be ported easily to an Ada 83
4315 compiler. This is the main use of the switch.
4316
4317 With few exceptions (most notably the need to use @code{<>} on
4318 @cindex Generic formal parameters
4319 unconstrained generic formal parameters, the use of the new Ada 95
4320 keywords, and the use of packages
4321 with optional bodies), it is not necessary to use the
4322 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4323 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4324 means that a correct Ada 83 program is usually also a correct Ada 95
4325 program.
4326
4327 @end table
4328
4329 @node Character Set Control
4330 @subsection Character Set Control
4331 @table @code
4332 @item -gnati@var{c}
4333 @cindex @code{-gnati} (@code{gcc})
4334
4335 @noindent
4336 Normally GNAT recognizes the Latin-1 character set in source program
4337 identifiers, as described in the Ada 95 Reference Manual.
4338 This switch causes
4339 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4340 single character  indicating the character set, as follows:
4341
4342 @table @code
4343 @item 1
4344 Latin-1 identifiers
4345
4346 @item 2
4347 Latin-2 letters allowed in identifiers
4348
4349 @item 3
4350 Latin-3 letters allowed in identifiers
4351
4352 @item 4
4353 Latin-4 letters allowed in identifiers
4354
4355 @item 5
4356 Latin-5 (Cyrillic) letters allowed in identifiers
4357
4358 @item 9
4359 Latin-9 letters allowed in identifiers
4360
4361 @item p
4362 IBM PC letters (code page 437) allowed in identifiers
4363
4364 @item 8
4365 IBM PC letters (code page 850) allowed in identifiers
4366
4367 @item f
4368 Full upper-half codes allowed in identifiers
4369
4370 @item n
4371 No upper-half codes allowed in identifiers
4372
4373 @item w
4374 Wide-character codes (that is, codes greater than 255)
4375 allowed in identifiers
4376 @end table
4377
4378 @xref{Foreign Language Representation}, for full details on the
4379 implementation of these character sets.
4380
4381 @item -gnatW@var{e}
4382 @cindex @code{-gnatW} (@code{gcc})
4383 Specify the method of encoding for wide characters.
4384 @var{e} is one of the following:
4385
4386 @table @code
4387
4388 @item h
4389 Hex encoding (brackets coding also recognized)
4390
4391 @item u
4392 Upper half encoding (brackets encoding also recognized)
4393
4394 @item s
4395 Shift/JIS encoding (brackets encoding also recognized)
4396
4397 @item e
4398 EUC encoding (brackets encoding also recognized)
4399
4400 @item 8
4401 UTF-8 encoding (brackets encoding also recognized)
4402
4403 @item b
4404 Brackets encoding only (default value)
4405 @end table
4406 For full details on the these encoding
4407 methods see @xref{Wide Character Encodings}.
4408 Note that brackets coding is always accepted, even if one of the other
4409 options is specified, so for example @option{-gnatW8} specifies that both
4410 brackets and @code{UTF-8} encodings will be recognized. The units that are
4411 with'ed directly or indirectly will be scanned using the specified
4412 representation scheme, and so if one of the non-brackets scheme is
4413 used, it must be used consistently throughout the program. However,
4414 since brackets encoding is always recognized, it may be conveniently
4415 used in standard libraries, allowing these libraries to be used with
4416 any of the available coding schemes.
4417 scheme. If no @option{-gnatW?} parameter is present, then the default
4418 representation is Brackets encoding only.
4419
4420 Note that the wide character representation that is specified (explicitly
4421 or by default) for the main program also acts as the default encoding used
4422 for Wide_Text_IO files if not specifically overridden by a WCEM form
4423 parameter.
4424
4425 @end table
4426 @node File Naming Control
4427 @subsection File Naming Control
4428
4429 @table @code
4430 @item -gnatk@var{n}
4431 @cindex @option{-gnatk} (@code{gcc})
4432 Activates file name "krunching". @var{n}, a decimal integer in the range
4433 1-999, indicates the maximum allowable length of a file name (not
4434 including the @file{.ads} or @file{.adb} extension). The default is not
4435 to enable file name krunching.
4436
4437 For the source file naming rules, @xref{File Naming Rules}.
4438 @end table
4439
4440 @node Subprogram Inlining Control
4441 @subsection Subprogram Inlining Control
4442
4443 @table @code
4444 @item -gnatn
4445 @cindex @option{-gnatn} (@code{gcc})
4446 The @code{n} here is intended to suggest the first syllable of the
4447 word "inline".
4448 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4449 inlining to actually occur, optimization must be enabled. To enable
4450 inlining across unit boundaries, this is, inlining a call in one unit of
4451 a subprogram declared in a @code{with}'ed unit, you must also specify
4452 this switch.
4453 In the absence of this switch, GNAT does not attempt
4454 inlining across units and does not need to access the bodies of
4455 subprograms for which @code{pragma Inline} is specified if they are not
4456 in the current unit.
4457
4458 If you specify this switch the compiler will access these bodies,
4459 creating an extra source dependency for the resulting object file, and
4460 where possible, the call will be inlined.
4461 For further details on when inlining is possible
4462 see @xref{Inlining of Subprograms}.
4463
4464 @item -gnatN
4465 @cindex @option{-gnatN} (@code{gcc})
4466 The front end inlining activated by this switch is generally more extensive,
4467 and quite often more effective than the standard @option{-gnatn} inlining mode.
4468 It will also generate additional dependencies.
4469
4470 @end table
4471
4472 @node Auxiliary Output Control
4473 @subsection Auxiliary Output Control
4474
4475 @table @code
4476 @item -gnatt
4477 @cindex @option{-gnatt} (@code{gcc})
4478 @cindex Writing internal trees
4479 @cindex Internal trees, writing to file
4480 Causes GNAT to write the internal tree for a unit to a file (with the
4481 extension @file{.adt}.
4482 This not normally required, but is used by separate analysis tools.
4483 Typically
4484 these tools do the necessary compilations automatically, so you should
4485 not have to specify this switch in normal operation.
4486
4487 @item -gnatu
4488 @cindex @option{-gnatu} (@code{gcc})
4489 Print a list of units required by this compilation on @file{stdout}.
4490 The listing includes all units on which the unit being compiled depends
4491 either directly or indirectly.
4492
4493 @item -pass-exit-codes
4494 @cindex @code{-pass-exit-codes} (@code{gcc})
4495 If this switch is not used, the exit code returned by @code{gcc} when
4496 compiling multiple files indicates whether all source files have
4497 been successfully used to generate object files or not.
4498
4499 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4500 exit status and allows an integrated development environment to better
4501 react to a compilation failure. Those exit status are:
4502
4503 @table @asis
4504 @item 5
4505 There was an error in at least one source file.
4506 @item 3
4507 At least one source file did not generate an object file.
4508 @item 2
4509 The compiler died unexpectedly (internal error for example).
4510 @item 0
4511 An object file has been generated for every source file.
4512 @end table
4513 @end table
4514
4515 @node Debugging Control
4516 @subsection Debugging Control
4517
4518 @table @code
4519 @cindex Debugging options
4520 @item -gnatd@var{x}
4521 Activate internal debugging switches. @var{x} is a letter or digit, or
4522 string of letters or digits, which specifies the type of debugging
4523 outputs desired. Normally these are used only for internal development
4524 or system debugging purposes. You can find full documentation for these
4525 switches in the body of the @code{Debug} unit in the compiler source
4526 file @file{debug.adb}.
4527
4528 @item -gnatG
4529 @cindex @option{-gnatG} (@code{gcc})
4530 This switch causes the compiler to generate auxiliary output containing
4531 a pseudo-source listing of the generated expanded code. Like most Ada
4532 compilers, GNAT works by first transforming the high level Ada code into
4533 lower level constructs. For example, tasking operations are transformed
4534 into calls to the tasking run-time routines. A unique capability of GNAT
4535 is to list this expanded code in a form very close to normal Ada source.
4536 This is very useful in understanding the implications of various Ada
4537 usage on the efficiency of the generated code. There are many cases in
4538 Ada (e.g. the use of controlled types), where simple Ada statements can
4539 generate a lot of run-time code. By using @option{-gnatG} you can identify
4540 these cases, and consider whether it may be desirable to modify the coding
4541 approach to improve efficiency.
4542
4543 The format of the output is very similar to standard Ada source, and is
4544 easily understood by an Ada programmer. The following special syntactic
4545 additions correspond to low level features used in the generated code that
4546 do not have any exact analogies in pure Ada source form. The following
4547 is a partial list of these special constructions. See the specification
4548 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4549
4550 @table @code
4551 @item new @var{xxx} [storage_pool = @var{yyy}]
4552 Shows the storage pool being used for an allocator.
4553
4554 @item at end @var{procedure-name};
4555 Shows the finalization (cleanup) procedure for a scope.
4556
4557 @item (if @var{expr} then @var{expr} else @var{expr})
4558 Conditional expression equivalent to the @code{x?y:z} construction in C.
4559
4560 @item @var{target}^(@var{source})
4561 A conversion with floating-point truncation instead of rounding.
4562
4563 @item @var{target}?(@var{source})
4564 A conversion that bypasses normal Ada semantic checking. In particular
4565 enumeration types and fixed-point types are treated simply as integers.
4566
4567 @item @var{target}?^(@var{source})
4568 Combines the above two cases.
4569
4570 @item @var{x} #/ @var{y}
4571 @itemx @var{x} #mod @var{y}
4572 @itemx @var{x} #* @var{y}
4573 @itemx @var{x} #rem @var{y}
4574 A division or multiplication of fixed-point values which are treated as
4575 integers without any kind of scaling.
4576
4577 @item free @var{expr} [storage_pool = @var{xxx}]
4578 Shows the storage pool associated with a @code{free} statement.
4579
4580 @item freeze @var{typename} [@var{actions}]
4581 Shows the point at which @var{typename} is frozen, with possible
4582 associated actions to be performed at the freeze point.
4583
4584 @item reference @var{itype}
4585 Reference (and hence definition) to internal type @var{itype}.
4586
4587 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4588 Intrinsic function call.
4589
4590 @item @var{labelname} : label
4591 Declaration of label @var{labelname}.
4592
4593 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4594 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4595 @var{expr}, but handled more efficiently).
4596
4597 @item [constraint_error]
4598 Raise the @code{Constraint_Error} exception.
4599
4600 @item @var{expression}'reference
4601 A pointer to the result of evaluating @var{expression}.
4602
4603 @item @var{target-type}!(@var{source-expression})
4604 An unchecked conversion of @var{source-expression} to @var{target-type}.
4605
4606 @item [@var{numerator}/@var{denominator}]
4607 Used to represent internal real literals (that) have no exact
4608 representation in base 2-16 (for example, the result of compile time
4609 evaluation of the expression 1.0/27.0).
4610
4611 @item -gnatD
4612 @cindex @option{-gnatD} (@code{gcc})
4613 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4614 source, as described above to be written to files with names
4615 @file{xxx.dg}, where @file{xxx} is the normal file name,
4616 for example, if the source file name is @file{hello.adb},
4617 then a file @file{hello.adb.dg} will be written.
4618 The debugging information generated
4619 by the @code{gcc} @code{-g} switch will refer to the generated
4620 @file{xxx.dg} file. This allows you to do source level debugging using
4621 the generated code which is sometimes useful for complex code, for example
4622 to find out exactly which part of a complex construction raised an
4623 exception. This switch also suppress generation of cross-reference
4624 information (see -gnatx).
4625
4626 @item -gnatC
4627 @cindex @option{-gnatE} (@code{gcc})
4628 In the generated debugging information, and also in the case of long external
4629 names, the compiler uses a compression mechanism if the name is very long.
4630 This compression method uses a checksum, and avoids trouble on some operating
4631 systems which have difficulty with very long names. The @option{-gnatC} switch
4632 forces this compression approach to be used on all external names and names
4633 in the debugging information tables. This reduces the size of the generated
4634 executable, at the expense of making the naming scheme more complex. The
4635 compression only affects the qualification of the name. Thus a name in
4636 the source:
4637
4638 @smallexample
4639 Very_Long_Package.Very_Long_Inner_Package.Var
4640 @end smallexample
4641
4642 @noindent
4643 would normally appear in these tables as:
4644
4645 @smallexample
4646 very_long_package__very_long_inner_package__var
4647 @end smallexample
4648
4649 @noindent
4650 but if the @option{-gnatC} switch is used, then the name appears as
4651
4652 @smallexample
4653 XCb7e0c705__var
4654 @end smallexample
4655
4656 @noindent
4657 Here b7e0c705 is a compressed encoding of the qualification prefix.
4658 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4659 debugger is used, the encoding is largely hidden from the user of the compiler.
4660
4661 @end table
4662
4663 @item -gnatR[0|1|2|3][s]
4664 @cindex @option{-gnatR} (@code{gcc})
4665 This switch controls output from the compiler of a listing showing
4666 representation information for declared types and objects. For
4667 @option{-gnatR0}, no information is output (equivalent to omitting
4668 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4669 so @option{-gnatR} with no parameter has the same effect), size and alignment
4670 information is listed for declared array and record types. For
4671 @option{-gnatR2}, size and alignment information is listed for all
4672 expression information for values that are computed at run time for
4673 variant records. These symbolic expressions have a mostly obvious
4674 format with #n being used to represent the value of the n'th
4675 discriminant. See source files @file{repinfo.ads/adb} in the
4676 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4677 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4678 the output is to a file with the name @file{file.rep} where
4679 file is the name of the corresponding source file.
4680
4681 @item -gnatx
4682 @cindex @option{-gnatx} (@code{gcc})
4683 Normally the compiler generates full cross-referencing information in
4684 the @file{ALI} file. This information is used by a number of tools,
4685 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4686 suppresses this information. This saves some space and may slightly
4687 speed up compilation, but means that these tools cannot be used.
4688 @end table
4689
4690 @node Units to Sources Mapping Files
4691 @subsection Units to Sources Mapping Files
4692
4693 @table @code
4694
4695 @item -gnatem@var{path}
4696 @cindex @option{-gnatem} (@code{gcc})
4697 A mapping file is a way to communicate to the compiler two mappings:
4698 from unit names to file names (without any directory information) and from
4699 file names to path names (with full directory information). These mappings
4700 are used by the compiler to short-circuit the path search.
4701
4702 A mapping file is a sequence of sets of three lines. In each set,
4703 the first line is the unit name, in lower case, with "%s" appended for
4704 specifications and "%b" appended for bodies; the second line is the file
4705 name; and the third line is the path name.
4706
4707 Example:
4708 @smallexample
4709    main%b
4710    main.2.ada
4711    /gnat/project1/sources/main.2.ada
4712 @end smallexample
4713
4714 When the switch @option{-gnatem} is specified, the compiler will create
4715 in memory the two mappings from the specified file. If there is any problem
4716 (non existent file, truncated file or duplicate entries), no mapping
4717 will be created.
4718
4719 Several @option{-gnatem} switches may be specified; however, only the last
4720 one on the command line will be taken into account.
4721
4722 When using a project file, @code{gnatmake} create a temporary mapping file
4723 and communicates it to the compiler using this switch.
4724
4725 @end table
4726
4727 @node Search Paths and the Run-Time Library (RTL)
4728 @section Search Paths and the Run-Time Library (RTL)
4729
4730 @noindent
4731 With the GNAT source-based library system, the compiler must be able to
4732 find source files for units that are needed by the unit being compiled.
4733 Search paths are used to guide this process.
4734
4735 The compiler compiles one source file whose name must be given
4736 explicitly on the command line. In other words, no searching is done
4737 for this file. To find all other source files that are needed (the most
4738 common being the specs of units), the compiler examines the following
4739 directories, in the following order:
4740
4741 @enumerate
4742 @item
4743 The directory containing the source file of the main unit being compiled
4744 (the file name on the command line).
4745
4746 @item
4747 Each directory named by an @code{-I} switch given on the @code{gcc}
4748 command line, in the order given.
4749
4750 @item
4751 @findex ADA_INCLUDE_PATH
4752 Each of the directories listed in the value of the
4753 @code{ADA_INCLUDE_PATH} environment variable.
4754 Construct this value
4755 exactly as the @code{PATH} environment variable: a list of directory
4756 names separated by colons (semicolons when working with the NT version).
4757 @item
4758 The content of the "ada_source_path" file which is part of the GNAT
4759 installation tree and is used to store standard libraries such as the
4760 GNAT Run Time Library (RTL) source files.
4761 @ref{Installing an Ada Library}
4762 @end enumerate
4763
4764 @noindent
4765 Specifying the switch @code{-I-}
4766 inhibits the use of the directory
4767 containing the source file named in the command line. You can still
4768 have this directory on your search path, but in this case it must be
4769 explicitly requested with a @code{-I} switch.
4770
4771 Specifying the switch @code{-nostdinc}
4772 inhibits the search of the default location for the GNAT Run Time
4773 Library (RTL) source files.
4774
4775 The compiler outputs its object files and ALI files in the current
4776 working directory.
4777 Caution: The object file can be redirected with the @code{-o} switch;
4778 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4779 so the ALI file will not go to the right place. Therefore, you should
4780 avoid using the @code{-o} switch.
4781
4782 @findex System.IO
4783 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4784 children make up the GNAT RTL, together with the simple @code{System.IO}
4785 package used in the "Hello World" example. The sources for these units
4786 are needed by the compiler and are kept together in one directory. Not
4787 all of the bodies are needed, but all of the sources are kept together
4788 anyway. In a normal installation, you need not specify these directory
4789 names when compiling or binding. Either the environment variables or
4790 the built-in defaults cause these files to be found.
4791
4792 In addition to the language-defined hierarchies (System, Ada and
4793 Interfaces), the GNAT distribution provides a fourth hierarchy,
4794 consisting of child units of GNAT. This is a collection of generally
4795 useful routines. See the GNAT Reference Manual for further details.
4796
4797 Besides simplifying access to the RTL, a major use of search paths is
4798 in compiling sources from multiple directories. This can make
4799 development environments much more flexible.
4800
4801 @node Order of Compilation Issues
4802 @section Order of Compilation Issues
4803
4804 @noindent
4805 If, in our earlier example, there was a spec for the @code{hello}
4806 procedure, it would be contained in the file @file{hello.ads}; yet this
4807 file would not have to be explicitly compiled. This is the result of the
4808 model we chose to implement library management. Some of the consequences
4809 of this model are as follows:
4810
4811 @itemize @bullet
4812 @item
4813 There is no point in compiling specs (except for package
4814 specs with no bodies) because these are compiled as needed by clients. If
4815 you attempt a useless compilation, you will receive an error message.
4816 It is also useless to compile subunits because they are compiled as needed
4817 by the parent.
4818
4819 @item
4820 There are no order of compilation requirements: performing a
4821 compilation never obsoletes anything. The only way you can obsolete
4822 something and require recompilations is to modify one of the
4823 source files on which it depends.
4824
4825 @item
4826 There is no library as such, apart from the ALI files
4827 (@pxref{The Ada Library Information Files}, for information on the format of these
4828 files). For now we find it convenient to create separate ALI files, but
4829 eventually the information therein may be incorporated into the object
4830 file directly.
4831
4832 @item
4833 When you compile a unit, the source files for the specs of all units
4834 that it @code{with}'s, all its subunits, and the bodies of any generics it
4835 instantiates must be available (reachable by the search-paths mechanism
4836 described above), or you will receive a fatal error message.
4837 @end itemize
4838
4839 @node Examples
4840 @section Examples
4841
4842 @noindent
4843 The following are some typical Ada compilation command line examples:
4844
4845 @table @code
4846 @item $ gcc -c xyz.adb
4847 Compile body in file @file{xyz.adb} with all default options.
4848
4849 @item $ gcc -c -O2 -gnata xyz-def.adb
4850
4851 Compile the child unit package in file @file{xyz-def.adb} with extensive
4852 optimizations, and pragma @code{Assert}/@code{Debug} statements
4853 enabled.
4854
4855 @item $ gcc -c -gnatc abc-def.adb
4856 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4857 mode.
4858 @end table
4859
4860 @node Binding Using gnatbind
4861 @chapter Binding Using @code{gnatbind}
4862 @findex gnatbind
4863
4864 @menu
4865 * Running gnatbind::
4866 * Generating the Binder Program in C::
4867 * Consistency-Checking Modes::
4868 * Binder Error Message Control::
4869 * Elaboration Control::
4870 * Output Control::
4871 * Binding with Non-Ada Main Programs::
4872 * Binding Programs with No Main Subprogram::
4873 * Summary of Binder Switches::
4874 * Command-Line Access::
4875 * Search Paths for gnatbind::
4876 * Examples of gnatbind Usage::
4877 @end menu
4878
4879 @noindent
4880 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4881 to bind compiled GNAT objects. The @code{gnatbind} program performs
4882 four separate functions:
4883
4884 @enumerate
4885 @item
4886 Checks that a program is consistent, in accordance with the rules in
4887 Chapter 10 of the Ada 95 Reference Manual. In particular, error
4888 messages are generated if a program uses inconsistent versions of a
4889 given unit.
4890
4891 @item
4892 Checks that an acceptable order of elaboration exists for the program
4893 and issues an error message if it cannot find an order of elaboration
4894 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
4895
4896 @item
4897 Generates a main program incorporating the given elaboration order.
4898 This program is a small Ada package (body and spec) that
4899 must be subsequently compiled
4900 using the GNAT compiler. The necessary compilation step is usually
4901 performed automatically by @code{gnatlink}. The two most important
4902 functions of this program
4903 are to call the elaboration routines of units in an appropriate order
4904 and to call the main program.
4905
4906 @item
4907 Determines the set of object files required by the given main program.
4908 This information is output in the forms of comments in the generated program,
4909 to be read by the @code{gnatlink} utility used to link the Ada application.
4910 @end enumerate
4911
4912 @node Running gnatbind
4913 @section Running @code{gnatbind}
4914
4915 @noindent
4916 The form of the @code{gnatbind} command is
4917
4918 @smallexample
4919 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
4920 @end smallexample
4921
4922 @noindent
4923 where @var{mainprog}.adb is the Ada file containing the main program
4924 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
4925 package in two files which names are
4926 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
4927 For example, if given the
4928 parameter @samp{hello.ali}, for a main program contained in file
4929 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
4930 and @file{b~hello.adb}.
4931
4932 When doing consistency checking, the binder takes into consideration
4933 any source files it can locate. For example, if the binder determines
4934 that the given main program requires the package @code{Pack}, whose
4935 @file{.ali}
4936 file is @file{pack.ali} and whose corresponding source spec file is
4937 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
4938 (using the same search path conventions as previously described for the
4939 @code{gcc} command). If it can locate this source file, it checks that
4940 the time stamps
4941 or source checksums of the source and its references to in @file{ali} files
4942 match. In other words, any @file{ali} files that mentions this spec must have
4943 resulted from compiling this version of the source file (or in the case
4944 where the source checksums match, a version close enough that the
4945 difference does not matter).
4946
4947 @cindex Source files, use by binder
4948 The effect of this consistency checking, which includes source files, is
4949 that the binder ensures that the program is consistent with the latest
4950 version of the source files that can be located at bind time. Editing a
4951 source file without compiling files that depend on the source file cause
4952 error messages to be generated by the binder.
4953
4954 For example, suppose you have a main program @file{hello.adb} and a
4955 package @code{P}, from file @file{p.ads} and you perform the following
4956 steps:
4957
4958 @enumerate
4959 @item
4960 Enter @code{gcc -c hello.adb} to compile the main program.
4961
4962 @item
4963 Enter @code{gcc -c p.ads} to compile package @code{P}.
4964
4965 @item
4966 Edit file @file{p.ads}.
4967
4968 @item
4969 Enter @code{gnatbind hello}.
4970 @end enumerate
4971
4972 At this point, the file @file{p.ali} contains an out-of-date time stamp
4973 because the file @file{p.ads} has been edited. The attempt at binding
4974 fails, and the binder generates the following error messages:
4975
4976 @smallexample
4977 error: "hello.adb" must be recompiled ("p.ads" has been modified)
4978 error: "p.ads" has been modified and must be recompiled
4979 @end smallexample
4980
4981 @noindent
4982 Now both files must be recompiled as indicated, and then the bind can
4983 succeed, generating a main program. You need not normally be concerned
4984 with the contents of this file, but it is similar to the following which
4985 is the binder file generated for a simple "hello world" program.
4986
4987 @smallexample
4988 @iftex
4989 @leftskip=0cm
4990 @end iftex
4991 --  The package is called Ada_Main unless this name is actually used
4992 --  as a unit name in the partition, in which case some other unique
4993 --  name is used.
4994
4995 with System;
4996 package ada_main is
4997
4998    Elab_Final_Code : Integer;
4999    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5000
5001    --  The main program saves the parameters (argument count,
5002    --  argument values, environment pointer) in global variables
5003    --  for later access by other units including
5004    --  Ada.Command_Line.
5005
5006    gnat_argc : Integer;
5007    gnat_argv : System.Address;
5008    gnat_envp : System.Address;
5009
5010    --  The actual variables are stored in a library routine. This
5011    --  is useful for some shared library situations, where there
5012    --  are problems if variables are not in the library.
5013
5014    pragma Import (C, gnat_argc);
5015    pragma Import (C, gnat_argv);
5016    pragma Import (C, gnat_envp);
5017
5018    --  The exit status is similarly an external location
5019
5020    gnat_exit_status : Integer;
5021    pragma Import (C, gnat_exit_status);
5022
5023    GNAT_Version : constant String :=
5024                     "GNAT Version: 3.15w (20010315)";
5025    pragma Export (C, GNAT_Version, "__gnat_version");
5026
5027    --  This is the generated adafinal routine that performs
5028    --  finalization at the end of execution. In the case where
5029    --  Ada is the main program, this main program makes a call
5030    --  to adafinal at program termination.
5031
5032    procedure adafinal;
5033    pragma Export (C, adafinal, "adafinal");
5034
5035    --  This is the generated adainit routine that performs
5036    --  initialization at the start of execution. In the case
5037    --  where Ada is the main program, this main program makes
5038    --  a call to adainit at program startup.
5039
5040    procedure adainit;
5041    pragma Export (C, adainit, "adainit");
5042
5043    --  This routine is called at the start of execution. It is
5044    --  a dummy routine that is used by the debugger to breakpoint
5045    --  at the start of execution.
5046
5047    procedure Break_Start;
5048    pragma Import (C, Break_Start, "__gnat_break_start");
5049
5050    --  This is the actual generated main program (it would be
5051    --  suppressed if the no main program switch were used). As
5052    --  required by standard system conventions, this program has
5053    --  the external name main.
5054
5055    function main
5056      (argc : Integer;
5057       argv : System.Address;
5058       envp : System.Address)
5059       return Integer;
5060    pragma Export (C, main, "main");
5061
5062    --  The following set of constants give the version
5063    --  identification values for every unit in the bound
5064    --  partition. This identification is computed from all
5065    --  dependent semantic units, and corresponds to the
5066    --  string that would be returned by use of the
5067    --  Body_Version or Version attributes.
5068
5069    type Version_32 is mod 2 ** 32;
5070    u00001 : constant Version_32 := 16#7880BEB3#;
5071    u00002 : constant Version_32 := 16#0D24CBD0#;
5072    u00003 : constant Version_32 := 16#3283DBEB#;
5073    u00004 : constant Version_32 := 16#2359F9ED#;
5074    u00005 : constant Version_32 := 16#664FB847#;
5075    u00006 : constant Version_32 := 16#68E803DF#;
5076    u00007 : constant Version_32 := 16#5572E604#;
5077    u00008 : constant Version_32 := 16#46B173D8#;
5078    u00009 : constant Version_32 := 16#156A40CF#;
5079    u00010 : constant Version_32 := 16#033DABE0#;
5080    u00011 : constant Version_32 := 16#6AB38FEA#;
5081    u00012 : constant Version_32 := 16#22B6217D#;
5082    u00013 : constant Version_32 := 16#68A22947#;
5083    u00014 : constant Version_32 := 16#18CC4A56#;
5084    u00015 : constant Version_32 := 16#08258E1B#;
5085    u00016 : constant Version_32 := 16#367D5222#;
5086    u00017 : constant Version_32 := 16#20C9ECA4#;
5087    u00018 : constant Version_32 := 16#50D32CB6#;
5088    u00019 : constant Version_32 := 16#39A8BB77#;
5089    u00020 : constant Version_32 := 16#5CF8FA2B#;
5090    u00021 : constant Version_32 := 16#2F1EB794#;
5091    u00022 : constant Version_32 := 16#31AB6444#;
5092    u00023 : constant Version_32 := 16#1574B6E9#;
5093    u00024 : constant Version_32 := 16#5109C189#;
5094    u00025 : constant Version_32 := 16#56D770CD#;
5095    u00026 : constant Version_32 := 16#02F9DE3D#;
5096    u00027 : constant Version_32 := 16#08AB6B2C#;
5097    u00028 : constant Version_32 := 16#3FA37670#;
5098    u00029 : constant Version_32 := 16#476457A0#;
5099    u00030 : constant Version_32 := 16#731E1B6E#;
5100    u00031 : constant Version_32 := 16#23C2E789#;
5101    u00032 : constant Version_32 := 16#0F1BD6A1#;
5102    u00033 : constant Version_32 := 16#7C25DE96#;
5103    u00034 : constant Version_32 := 16#39ADFFA2#;
5104    u00035 : constant Version_32 := 16#571DE3E7#;
5105    u00036 : constant Version_32 := 16#5EB646AB#;
5106    u00037 : constant Version_32 := 16#4249379B#;
5107    u00038 : constant Version_32 := 16#0357E00A#;
5108    u00039 : constant Version_32 := 16#3784FB72#;
5109    u00040 : constant Version_32 := 16#2E723019#;
5110    u00041 : constant Version_32 := 16#623358EA#;
5111    u00042 : constant Version_32 := 16#107F9465#;
5112    u00043 : constant Version_32 := 16#6843F68A#;
5113    u00044 : constant Version_32 := 16#63305874#;
5114    u00045 : constant Version_32 := 16#31E56CE1#;
5115    u00046 : constant Version_32 := 16#02917970#;
5116    u00047 : constant Version_32 := 16#6CCBA70E#;
5117    u00048 : constant Version_32 := 16#41CD4204#;
5118    u00049 : constant Version_32 := 16#572E3F58#;
5119    u00050 : constant Version_32 := 16#20729FF5#;
5120    u00051 : constant Version_32 := 16#1D4F93E8#;
5121    u00052 : constant Version_32 := 16#30B2EC3D#;
5122    u00053 : constant Version_32 := 16#34054F96#;
5123    u00054 : constant Version_32 := 16#5A199860#;
5124    u00055 : constant Version_32 := 16#0E7F912B#;
5125    u00056 : constant Version_32 := 16#5760634A#;
5126    u00057 : constant Version_32 := 16#5D851835#;
5127
5128    --  The following Export pragmas export the version numbers
5129    --  with symbolic names ending in B (for body) or S
5130    --  (for spec) so that they can be located in a link. The
5131    --  information provided here is sufficient to track down
5132    --  the exact versions of units used in a given build.
5133
5134    pragma Export (C, u00001, "helloB");
5135    pragma Export (C, u00002, "system__standard_libraryB");
5136    pragma Export (C, u00003, "system__standard_libraryS");
5137    pragma Export (C, u00004, "adaS");
5138    pragma Export (C, u00005, "ada__text_ioB");
5139    pragma Export (C, u00006, "ada__text_ioS");
5140    pragma Export (C, u00007, "ada__exceptionsB");
5141    pragma Export (C, u00008, "ada__exceptionsS");
5142    pragma Export (C, u00009, "gnatS");
5143    pragma Export (C, u00010, "gnat__heap_sort_aB");
5144    pragma Export (C, u00011, "gnat__heap_sort_aS");
5145    pragma Export (C, u00012, "systemS");
5146    pragma Export (C, u00013, "system__exception_tableB");
5147    pragma Export (C, u00014, "system__exception_tableS");
5148    pragma Export (C, u00015, "gnat__htableB");
5149    pragma Export (C, u00016, "gnat__htableS");
5150    pragma Export (C, u00017, "system__exceptionsS");
5151    pragma Export (C, u00018, "system__machine_state_operationsB");
5152    pragma Export (C, u00019, "system__machine_state_operationsS");
5153    pragma Export (C, u00020, "system__machine_codeS");
5154    pragma Export (C, u00021, "system__storage_elementsB");
5155    pragma Export (C, u00022, "system__storage_elementsS");
5156    pragma Export (C, u00023, "system__secondary_stackB");
5157    pragma Export (C, u00024, "system__secondary_stackS");
5158    pragma Export (C, u00025, "system__parametersB");
5159    pragma Export (C, u00026, "system__parametersS");
5160    pragma Export (C, u00027, "system__soft_linksB");
5161    pragma Export (C, u00028, "system__soft_linksS");
5162    pragma Export (C, u00029, "system__stack_checkingB");
5163    pragma Export (C, u00030, "system__stack_checkingS");
5164    pragma Export (C, u00031, "system__tracebackB");
5165    pragma Export (C, u00032, "system__tracebackS");
5166    pragma Export (C, u00033, "ada__streamsS");
5167    pragma Export (C, u00034, "ada__tagsB");
5168    pragma Export (C, u00035, "ada__tagsS");
5169    pragma Export (C, u00036, "system__string_opsB");
5170    pragma Export (C, u00037, "system__string_opsS");
5171    pragma Export (C, u00038, "interfacesS");
5172    pragma Export (C, u00039, "interfaces__c_streamsB");
5173    pragma Export (C, u00040, "interfaces__c_streamsS");
5174    pragma Export (C, u00041, "system__file_ioB");
5175    pragma Export (C, u00042, "system__file_ioS");
5176    pragma Export (C, u00043, "ada__finalizationB");
5177    pragma Export (C, u00044, "ada__finalizationS");
5178    pragma Export (C, u00045, "system__finalization_rootB");
5179    pragma Export (C, u00046, "system__finalization_rootS");
5180    pragma Export (C, u00047, "system__finalization_implementationB");
5181    pragma Export (C, u00048, "system__finalization_implementationS");
5182    pragma Export (C, u00049, "system__string_ops_concat_3B");
5183    pragma Export (C, u00050, "system__string_ops_concat_3S");
5184    pragma Export (C, u00051, "system__stream_attributesB");
5185    pragma Export (C, u00052, "system__stream_attributesS");
5186    pragma Export (C, u00053, "ada__io_exceptionsS");
5187    pragma Export (C, u00054, "system__unsigned_typesS");
5188    pragma Export (C, u00055, "system__file_control_blockS");
5189    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5190    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5191
5192    -- BEGIN ELABORATION ORDER
5193    -- ada (spec)
5194    -- gnat (spec)
5195    -- gnat.heap_sort_a (spec)
5196    -- gnat.heap_sort_a (body)
5197    -- gnat.htable (spec)
5198    -- gnat.htable (body)
5199    -- interfaces (spec)
5200    -- system (spec)
5201    -- system.machine_code (spec)
5202    -- system.parameters (spec)
5203    -- system.parameters (body)
5204    -- interfaces.c_streams (spec)
5205    -- interfaces.c_streams (body)
5206    -- system.standard_library (spec)
5207    -- ada.exceptions (spec)
5208    -- system.exception_table (spec)
5209    -- system.exception_table (body)
5210    -- ada.io_exceptions (spec)
5211    -- system.exceptions (spec)
5212    -- system.storage_elements (spec)
5213    -- system.storage_elements (body)
5214    -- system.machine_state_operations (spec)
5215    -- system.machine_state_operations (body)
5216    -- system.secondary_stack (spec)
5217    -- system.stack_checking (spec)
5218    -- system.soft_links (spec)
5219    -- system.soft_links (body)
5220    -- system.stack_checking (body)
5221    -- system.secondary_stack (body)
5222    -- system.standard_library (body)
5223    -- system.string_ops (spec)
5224    -- system.string_ops (body)
5225    -- ada.tags (spec)
5226    -- ada.tags (body)
5227    -- ada.streams (spec)
5228    -- system.finalization_root (spec)
5229    -- system.finalization_root (body)
5230    -- system.string_ops_concat_3 (spec)
5231    -- system.string_ops_concat_3 (body)
5232    -- system.traceback (spec)
5233    -- system.traceback (body)
5234    -- ada.exceptions (body)
5235    -- system.unsigned_types (spec)
5236    -- system.stream_attributes (spec)
5237    -- system.stream_attributes (body)
5238    -- system.finalization_implementation (spec)
5239    -- system.finalization_implementation (body)
5240    -- ada.finalization (spec)
5241    -- ada.finalization (body)
5242    -- ada.finalization.list_controller (spec)
5243    -- ada.finalization.list_controller (body)
5244    -- system.file_control_block (spec)
5245    -- system.file_io (spec)
5246    -- system.file_io (body)
5247    -- ada.text_io (spec)
5248    -- ada.text_io (body)
5249    -- hello (body)
5250    -- END ELABORATION ORDER
5251
5252 end ada_main;
5253
5254 --  The following source file name pragmas allow the generated file
5255 --  names to be unique for different main programs. They are needed
5256 --  since the package name will always be Ada_Main.
5257
5258 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5259 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5260
5261 --  Generated package body for Ada_Main starts here
5262
5263 package body ada_main is
5264
5265    --  The actual finalization is performed by calling the
5266    --  library routine in System.Standard_Library.Adafinal
5267
5268    procedure Do_Finalize;
5269    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5270
5271    -------------
5272    -- adainit --
5273    -------------
5274
5275 @findex adainit
5276    procedure adainit is
5277
5278       --  These booleans are set to True once the associated unit has
5279       --  been elaborated. It is also used to avoid elaborating the
5280       --  same unit twice.
5281
5282       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5283       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5284       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5285       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5286       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5287       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5288       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5289       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5290       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5291       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5292       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5293       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5294       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5295       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5296       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5297       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5298       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5299
5300       --  Set_Globals is a library routine that stores away the
5301       --  value of the indicated set of global values in global
5302       --  variables within the library.
5303
5304       procedure Set_Globals
5305         (Main_Priority            : Integer;
5306          Time_Slice_Value         : Integer;
5307          WC_Encoding              : Character;
5308          Locking_Policy           : Character;
5309          Queuing_Policy           : Character;
5310          Task_Dispatching_Policy  : Character;
5311          Adafinal                 : System.Address;
5312          Unreserve_All_Interrupts : Integer;
5313          Exception_Tracebacks     : Integer);
5314 @findex __gnat_set_globals
5315       pragma Import (C, Set_Globals, "__gnat_set_globals");
5316
5317       --  SDP_Table_Build is a library routine used to build the
5318       --  exception tables. See unit Ada.Exceptions in files
5319       --  a-except.ads/adb for full details of how zero cost
5320       --  exception handling works. This procedure, the call to
5321       --  it, and the two following tables are all omitted if the
5322       --  build is in longjmp/setjump exception mode.
5323
5324 @findex SDP_Table_Build
5325 @findex Zero Cost Exceptions
5326       procedure SDP_Table_Build
5327         (SDP_Addresses   : System.Address;
5328          SDP_Count       : Natural;
5329          Elab_Addresses  : System.Address;
5330          Elab_Addr_Count : Natural);
5331       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5332
5333       --  Table of Unit_Exception_Table addresses. Used for zero
5334       --  cost exception handling to build the top level table.
5335
5336       ST : aliased constant array (1 .. 23) of System.Address := (
5337         Hello'UET_Address,
5338         Ada.Text_Io'UET_Address,
5339         Ada.Exceptions'UET_Address,
5340         Gnat.Heap_Sort_A'UET_Address,
5341         System.Exception_Table'UET_Address,
5342         System.Machine_State_Operations'UET_Address,
5343         System.Secondary_Stack'UET_Address,
5344         System.Parameters'UET_Address,
5345         System.Soft_Links'UET_Address,
5346         System.Stack_Checking'UET_Address,
5347         System.Traceback'UET_Address,
5348         Ada.Streams'UET_Address,
5349         Ada.Tags'UET_Address,
5350         System.String_Ops'UET_Address,
5351         Interfaces.C_Streams'UET_Address,
5352         System.File_Io'UET_Address,
5353         Ada.Finalization'UET_Address,
5354         System.Finalization_Root'UET_Address,
5355         System.Finalization_Implementation'UET_Address,
5356         System.String_Ops_Concat_3'UET_Address,
5357         System.Stream_Attributes'UET_Address,
5358         System.File_Control_Block'UET_Address,
5359         Ada.Finalization.List_Controller'UET_Address);
5360
5361       --  Table of addresses of elaboration routines. Used for
5362       --  zero cost exception handling to make sure these
5363       --  addresses are included in the top level procedure
5364       --  address table.
5365
5366       EA : aliased constant array (1 .. 23) of System.Address := (
5367         adainit'Code_Address,
5368         Do_Finalize'Code_Address,
5369         Ada.Exceptions'Elab_Spec'Address,
5370         System.Exceptions'Elab_Spec'Address,
5371         Interfaces.C_Streams'Elab_Spec'Address,
5372         System.Exception_Table'Elab_Body'Address,
5373         Ada.Io_Exceptions'Elab_Spec'Address,
5374         System.Stack_Checking'Elab_Spec'Address,
5375         System.Soft_Links'Elab_Body'Address,
5376         System.Secondary_Stack'Elab_Body'Address,
5377         Ada.Tags'Elab_Spec'Address,
5378         Ada.Tags'Elab_Body'Address,
5379         Ada.Streams'Elab_Spec'Address,
5380         System.Finalization_Root'Elab_Spec'Address,
5381         Ada.Exceptions'Elab_Body'Address,
5382         System.Finalization_Implementation'Elab_Spec'Address,
5383         System.Finalization_Implementation'Elab_Body'Address,
5384         Ada.Finalization'Elab_Spec'Address,
5385         Ada.Finalization.List_Controller'Elab_Spec'Address,
5386         System.File_Control_Block'Elab_Spec'Address,
5387         System.File_Io'Elab_Body'Address,
5388         Ada.Text_Io'Elab_Spec'Address,
5389         Ada.Text_Io'Elab_Body'Address);
5390
5391    --  Start of processing for adainit
5392
5393    begin
5394
5395       --  Call SDP_Table_Build to build the top level procedure
5396       --  table for zero cost exception handling (omitted in
5397       --  longjmp/setjump mode).
5398
5399       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5400
5401       --  Call Set_Globals to record various information for
5402       --  this partition.  The values are derived by the binder
5403       --  from information stored in the ali files by the compiler.
5404
5405 @findex __gnat_set_globals
5406       Set_Globals
5407         (Main_Priority            => -1,
5408          --  Priority of main program, -1 if no pragma Priority used
5409
5410          Time_Slice_Value         => -1,
5411          --  Time slice from Time_Slice pragma, -1 if none used
5412
5413          WC_Encoding              => 'b',
5414          --  Wide_Character encoding used, default is brackets
5415
5416          Locking_Policy           => ' ',
5417          --  Locking_Policy used, default of space means not
5418          --  specified, otherwise it is the first character of
5419          --  the policy name.
5420
5421          Queuing_Policy           => ' ',
5422          --  Queuing_Policy used, default of space means not
5423          --  specified, otherwise it is the first character of
5424          --  the policy name.
5425
5426          Task_Dispatching_Policy  => ' ',
5427          --  Task_Dispatching_Policy used, default of space means
5428          --  not specified, otherwise first character of the
5429          --  policy name.
5430
5431          Adafinal                 => System.Null_Address,
5432          --  Address of Adafinal routine, not used anymore
5433
5434          Unreserve_All_Interrupts => 0,
5435          --  Set true if pragma Unreserve_All_Interrupts was used
5436
5437          Exception_Tracebacks     => 0);
5438          --  Indicates if exception tracebacks are enabled
5439
5440       Elab_Final_Code := 1;
5441
5442       --  Now we have the elaboration calls for all units in the partition.
5443       --  The Elab_Spec and Elab_Body attributes generate references to the
5444       --  implicit elaboration procedures generated by the compiler for
5445       --  each unit that requires elaboration.
5446
5447       if not E040 then
5448          Interfaces.C_Streams'Elab_Spec;
5449       end if;
5450       E040 := True;
5451       if not E008 then
5452          Ada.Exceptions'Elab_Spec;
5453       end if;
5454       if not E014 then
5455          System.Exception_Table'Elab_Body;
5456          E014 := True;
5457       end if;
5458       if not E053 then
5459          Ada.Io_Exceptions'Elab_Spec;
5460          E053 := True;
5461       end if;
5462       if not E017 then
5463          System.Exceptions'Elab_Spec;
5464          E017 := True;
5465       end if;
5466       if not E030 then
5467          System.Stack_Checking'Elab_Spec;
5468       end if;
5469       if not E028 then
5470          System.Soft_Links'Elab_Body;
5471          E028 := True;
5472       end if;
5473       E030 := True;
5474       if not E024 then
5475          System.Secondary_Stack'Elab_Body;
5476          E024 := True;
5477       end if;
5478       if not E035 then
5479          Ada.Tags'Elab_Spec;
5480       end if;
5481       if not E035 then
5482          Ada.Tags'Elab_Body;
5483          E035 := True;
5484       end if;
5485       if not E033 then
5486          Ada.Streams'Elab_Spec;
5487          E033 := True;
5488       end if;
5489       if not E046 then
5490          System.Finalization_Root'Elab_Spec;
5491       end if;
5492       E046 := True;
5493       if not E008 then
5494          Ada.Exceptions'Elab_Body;
5495          E008 := True;
5496       end if;
5497       if not E048 then
5498          System.Finalization_Implementation'Elab_Spec;
5499       end if;
5500       if not E048 then
5501          System.Finalization_Implementation'Elab_Body;
5502          E048 := True;
5503       end if;
5504       if not E044 then
5505          Ada.Finalization'Elab_Spec;
5506       end if;
5507       E044 := True;
5508       if not E057 then
5509          Ada.Finalization.List_Controller'Elab_Spec;
5510       end if;
5511       E057 := True;
5512       if not E055 then
5513          System.File_Control_Block'Elab_Spec;
5514          E055 := True;
5515       end if;
5516       if not E042 then
5517          System.File_Io'Elab_Body;
5518          E042 := True;
5519       end if;
5520       if not E006 then
5521          Ada.Text_Io'Elab_Spec;
5522       end if;
5523       if not E006 then
5524          Ada.Text_Io'Elab_Body;
5525          E006 := True;
5526       end if;
5527
5528       Elab_Final_Code := 0;
5529    end adainit;
5530
5531    --------------
5532    -- adafinal --
5533    --------------
5534
5535 @findex adafinal
5536    procedure adafinal is
5537    begin
5538       Do_Finalize;
5539    end adafinal;
5540
5541    ----------
5542    -- main --
5543    ----------
5544
5545    --  main is actually a function, as in the ANSI C standard,
5546    --  defined to return the exit status. The three parameters
5547    --  are the argument count, argument values and environment
5548    --  pointer.
5549
5550 @findex Main Program
5551    function main
5552      (argc : Integer;
5553       argv : System.Address;
5554       envp : System.Address)
5555       return Integer
5556    is
5557       --  The initialize routine performs low level system
5558       --  initialization using a standard library routine which
5559       --  sets up signal handling and performs any other
5560       --  required setup. The routine can be found in file
5561       --  a-init.c.
5562
5563 @findex __gnat_initialize
5564       procedure initialize;
5565       pragma Import (C, initialize, "__gnat_initialize");
5566
5567       --  The finalize routine performs low level system
5568       --  finalization using a standard library routine. The
5569       --  routine is found in file a-final.c and in the standard
5570       --  distribution is a dummy routine that does nothing, so
5571       --  really this is a hook for special user finalization.
5572
5573 @findex __gnat_finalize
5574       procedure finalize;
5575       pragma Import (C, finalize, "__gnat_finalize");
5576
5577       --  We get to the main program of the partition by using
5578       --  pragma Import because if we try to with the unit and
5579       --  call it Ada style, then not only do we waste time
5580       --  recompiling it, but also, we don't really know the right
5581       --  switches (e.g. identifier character set) to be used
5582       --  to compile it.
5583
5584       procedure Ada_Main_Program;
5585       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5586
5587    --  Start of processing for main
5588
5589    begin
5590       --  Save global variables
5591
5592       gnat_argc := argc;
5593       gnat_argv := argv;
5594       gnat_envp := envp;
5595
5596       --  Call low level system initialization
5597
5598       Initialize;
5599
5600       --  Call our generated Ada initialization routine
5601
5602       adainit;
5603
5604       --  This is the point at which we want the debugger to get
5605       --  control
5606
5607       Break_Start;
5608
5609       --  Now we call the main program of the partition
5610
5611       Ada_Main_Program;
5612
5613       --  Perform Ada finalization
5614
5615       adafinal;
5616
5617       --  Perform low level system finalization
5618
5619       Finalize;
5620
5621       --  Return the proper exit status
5622       return (gnat_exit_status);
5623    end;
5624
5625 --  This section is entirely comments, so it has no effect on the
5626 --  compilation of the Ada_Main package. It provides the list of
5627 --  object files and linker options, as well as some standard
5628 --  libraries needed for the link. The gnatlink utility parses
5629 --  this b~hello.adb file to read these comment lines to generate
5630 --  the appropriate command line arguments for the call to the
5631 --  system linker. The BEGIN/END lines are used for sentinels for
5632 --  this parsing operation.
5633
5634 --  The exact file names will of course depend on the environment,
5635 --  host/target and location of files on the host system.
5636
5637 @findex Object file list
5638 -- BEGIN Object file/option list
5639    --   ./hello.o
5640    --   -L./
5641    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5642    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5643 -- END Object file/option list
5644
5645 end ada_main;
5646
5647 @end smallexample
5648
5649 @noindent
5650 The Ada code in the above example is exactly what is generated by the
5651 binder. We have added comments to more clearly indicate the function
5652 of each part of the generated @code{Ada_Main} package.
5653
5654 The code is standard Ada in all respects, and can be processed by any
5655 tools that handle Ada. In particular, it is possible to use the debugger
5656 in Ada mode to debug the generated Ada_Main package. For example, suppose
5657 that for reasons that you do not understand, your program is blowing up
5658 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5659 down, you can place a breakpoint on the call:
5660
5661 @smallexample
5662 Ada.Text_Io'Elab_Body;
5663 @end smallexample
5664
5665 @noindent
5666 and trace the elaboration routine for this package to find out where
5667 the problem might be (more usually of course you would be debugging
5668 elaboration code in your own application).
5669
5670 @node Generating the Binder Program in C
5671 @section Generating the Binder Program in C
5672 @noindent
5673 In most normal usage, the default mode of @code{gnatbind} which is to
5674 generate the main package in Ada, as described in the previous section.
5675 In particular, this means that any Ada programmer can read and understand
5676 the generated main program. It can also be debugged just like any other
5677 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5678 and @code{gnatlink}.
5679
5680 However for some purposes it may be convenient to generate the main
5681 program in C rather than Ada. This may for example be helpful when you
5682 are generating a mixed language program with the main program in C. The
5683 GNAT compiler itself is an example. The use of the @code{-C} switch
5684 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5685 be generated in C (and compiled using the gnu C compiler). The
5686 following shows the C code generated for the same "Hello World"
5687 program:
5688
5689 @smallexample
5690
5691 #ifdef __STDC__
5692 #define PARAMS(paramlist) paramlist
5693 #else
5694 #define PARAMS(paramlist) ()
5695 #endif
5696
5697 extern void __gnat_set_globals
5698  PARAMS ((int, int, int, int, int, int,
5699           void (*) PARAMS ((void)), int, int));
5700 extern void adafinal PARAMS ((void));
5701 extern void adainit PARAMS ((void));
5702 extern void system__standard_library__adafinal PARAMS ((void));
5703 extern int main PARAMS ((int, char **, char **));
5704 extern void exit PARAMS ((int));
5705 extern void __gnat_break_start PARAMS ((void));
5706 extern void _ada_hello PARAMS ((void));
5707 extern void __gnat_initialize PARAMS ((void));
5708 extern void __gnat_finalize PARAMS ((void));
5709
5710 extern void ada__exceptions___elabs PARAMS ((void));
5711 extern void system__exceptions___elabs PARAMS ((void));
5712 extern void interfaces__c_streams___elabs PARAMS ((void));
5713 extern void system__exception_table___elabb PARAMS ((void));
5714 extern void ada__io_exceptions___elabs PARAMS ((void));
5715 extern void system__stack_checking___elabs PARAMS ((void));
5716 extern void system__soft_links___elabb PARAMS ((void));
5717 extern void system__secondary_stack___elabb PARAMS ((void));
5718 extern void ada__tags___elabs PARAMS ((void));
5719 extern void ada__tags___elabb PARAMS ((void));
5720 extern void ada__streams___elabs PARAMS ((void));
5721 extern void system__finalization_root___elabs PARAMS ((void));
5722 extern void ada__exceptions___elabb PARAMS ((void));
5723 extern void system__finalization_implementation___elabs PARAMS ((void));
5724 extern void system__finalization_implementation___elabb PARAMS ((void));
5725 extern void ada__finalization___elabs PARAMS ((void));
5726 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5727 extern void system__file_control_block___elabs PARAMS ((void));
5728 extern void system__file_io___elabb PARAMS ((void));
5729 extern void ada__text_io___elabs PARAMS ((void));
5730 extern void ada__text_io___elabb PARAMS ((void));
5731
5732 extern int __gnat_inside_elab_final_code;
5733
5734 extern int gnat_argc;
5735 extern char **gnat_argv;
5736 extern char **gnat_envp;
5737 extern int gnat_exit_status;
5738
5739 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5740 void adafinal () @{
5741    system__standard_library__adafinal ();
5742 @}
5743
5744 void adainit ()
5745 @{
5746    extern char ada__exceptions_E;
5747    extern char system__exceptions_E;
5748    extern char interfaces__c_streams_E;
5749    extern char system__exception_table_E;
5750    extern char ada__io_exceptions_E;
5751    extern char system__secondary_stack_E;
5752    extern char system__stack_checking_E;
5753    extern char system__soft_links_E;
5754    extern char ada__tags_E;
5755    extern char ada__streams_E;
5756    extern char system__finalization_root_E;
5757    extern char system__finalization_implementation_E;
5758    extern char ada__finalization_E;
5759    extern char ada__finalization__list_controller_E;
5760    extern char system__file_control_block_E;
5761    extern char system__file_io_E;
5762    extern char ada__text_io_E;
5763
5764    extern void *__gnat_hello__SDP;
5765    extern void *__gnat_ada__text_io__SDP;
5766    extern void *__gnat_ada__exceptions__SDP;
5767    extern void *__gnat_gnat__heap_sort_a__SDP;
5768    extern void *__gnat_system__exception_table__SDP;
5769    extern void *__gnat_system__machine_state_operations__SDP;
5770    extern void *__gnat_system__secondary_stack__SDP;
5771    extern void *__gnat_system__parameters__SDP;
5772    extern void *__gnat_system__soft_links__SDP;
5773    extern void *__gnat_system__stack_checking__SDP;
5774    extern void *__gnat_system__traceback__SDP;
5775    extern void *__gnat_ada__streams__SDP;
5776    extern void *__gnat_ada__tags__SDP;
5777    extern void *__gnat_system__string_ops__SDP;
5778    extern void *__gnat_interfaces__c_streams__SDP;
5779    extern void *__gnat_system__file_io__SDP;
5780    extern void *__gnat_ada__finalization__SDP;
5781    extern void *__gnat_system__finalization_root__SDP;
5782    extern void *__gnat_system__finalization_implementation__SDP;
5783    extern void *__gnat_system__string_ops_concat_3__SDP;
5784    extern void *__gnat_system__stream_attributes__SDP;
5785    extern void *__gnat_system__file_control_block__SDP;
5786    extern void *__gnat_ada__finalization__list_controller__SDP;
5787
5788    void **st[23] = @{
5789      &__gnat_hello__SDP,
5790      &__gnat_ada__text_io__SDP,
5791      &__gnat_ada__exceptions__SDP,
5792      &__gnat_gnat__heap_sort_a__SDP,
5793      &__gnat_system__exception_table__SDP,
5794      &__gnat_system__machine_state_operations__SDP,
5795      &__gnat_system__secondary_stack__SDP,
5796      &__gnat_system__parameters__SDP,
5797      &__gnat_system__soft_links__SDP,
5798      &__gnat_system__stack_checking__SDP,
5799      &__gnat_system__traceback__SDP,
5800      &__gnat_ada__streams__SDP,
5801      &__gnat_ada__tags__SDP,
5802      &__gnat_system__string_ops__SDP,
5803      &__gnat_interfaces__c_streams__SDP,
5804      &__gnat_system__file_io__SDP,
5805      &__gnat_ada__finalization__SDP,
5806      &__gnat_system__finalization_root__SDP,
5807      &__gnat_system__finalization_implementation__SDP,
5808      &__gnat_system__string_ops_concat_3__SDP,
5809      &__gnat_system__stream_attributes__SDP,
5810      &__gnat_system__file_control_block__SDP,
5811      &__gnat_ada__finalization__list_controller__SDP@};
5812
5813    extern void ada__exceptions___elabs ();
5814    extern void system__exceptions___elabs ();
5815    extern void interfaces__c_streams___elabs ();
5816    extern void system__exception_table___elabb ();
5817    extern void ada__io_exceptions___elabs ();
5818    extern void system__stack_checking___elabs ();
5819    extern void system__soft_links___elabb ();
5820    extern void system__secondary_stack___elabb ();
5821    extern void ada__tags___elabs ();
5822    extern void ada__tags___elabb ();
5823    extern void ada__streams___elabs ();
5824    extern void system__finalization_root___elabs ();
5825    extern void ada__exceptions___elabb ();
5826    extern void system__finalization_implementation___elabs ();
5827    extern void system__finalization_implementation___elabb ();
5828    extern void ada__finalization___elabs ();
5829    extern void ada__finalization__list_controller___elabs ();
5830    extern void system__file_control_block___elabs ();
5831    extern void system__file_io___elabb ();
5832    extern void ada__text_io___elabs ();
5833    extern void ada__text_io___elabb ();
5834
5835    void (*ea[23]) () = @{
5836      adainit,
5837      system__standard_library__adafinal,
5838      ada__exceptions___elabs,
5839      system__exceptions___elabs,
5840      interfaces__c_streams___elabs,
5841      system__exception_table___elabb,
5842      ada__io_exceptions___elabs,
5843      system__stack_checking___elabs,
5844      system__soft_links___elabb,
5845      system__secondary_stack___elabb,
5846      ada__tags___elabs,
5847      ada__tags___elabb,
5848      ada__streams___elabs,
5849      system__finalization_root___elabs,
5850      ada__exceptions___elabb,
5851      system__finalization_implementation___elabs,
5852      system__finalization_implementation___elabb,
5853      ada__finalization___elabs,
5854      ada__finalization__list_controller___elabs,
5855      system__file_control_block___elabs,
5856      system__file_io___elabb,
5857      ada__text_io___elabs,
5858      ada__text_io___elabb@};
5859
5860    __gnat_SDP_Table_Build (&st, 23, ea, 23);
5861    __gnat_set_globals (
5862       -1,      /* Main_Priority              */
5863       -1,      /* Time_Slice_Value           */
5864       'b',     /* WC_Encoding                */
5865       ' ',     /* Locking_Policy             */
5866       ' ',     /* Queuing_Policy             */
5867       ' ',     /* Tasking_Dispatching_Policy */
5868       0,       /* Finalization routine address, not used anymore */
5869       0,       /* Unreserve_All_Interrupts */
5870       0);      /* Exception_Tracebacks */
5871
5872    __gnat_inside_elab_final_code = 1;
5873
5874    if (ada__exceptions_E == 0) @{
5875       ada__exceptions___elabs ();
5876    @}
5877    if (system__exceptions_E == 0) @{
5878       system__exceptions___elabs ();
5879       system__exceptions_E++;
5880    @}
5881    if (interfaces__c_streams_E == 0) @{
5882       interfaces__c_streams___elabs ();
5883    @}
5884    interfaces__c_streams_E = 1;
5885    if (system__exception_table_E == 0) @{
5886       system__exception_table___elabb ();
5887       system__exception_table_E++;
5888    @}
5889    if (ada__io_exceptions_E == 0) @{
5890       ada__io_exceptions___elabs ();
5891       ada__io_exceptions_E++;
5892    @}
5893    if (system__stack_checking_E == 0) @{
5894       system__stack_checking___elabs ();
5895    @}
5896    if (system__soft_links_E == 0) @{
5897       system__soft_links___elabb ();
5898       system__soft_links_E++;
5899    @}
5900    system__stack_checking_E = 1;
5901    if (system__secondary_stack_E == 0) @{
5902       system__secondary_stack___elabb ();
5903       system__secondary_stack_E++;
5904    @}
5905    if (ada__tags_E == 0) @{
5906       ada__tags___elabs ();
5907    @}
5908    if (ada__tags_E == 0) @{
5909       ada__tags___elabb ();
5910       ada__tags_E++;
5911    @}
5912    if (ada__streams_E == 0) @{
5913       ada__streams___elabs ();
5914       ada__streams_E++;
5915    @}
5916    if (system__finalization_root_E == 0) @{
5917       system__finalization_root___elabs ();
5918    @}
5919    system__finalization_root_E = 1;
5920    if (ada__exceptions_E == 0) @{
5921       ada__exceptions___elabb ();
5922       ada__exceptions_E++;
5923    @}
5924    if (system__finalization_implementation_E == 0) @{
5925       system__finalization_implementation___elabs ();
5926    @}
5927    if (system__finalization_implementation_E == 0) @{
5928       system__finalization_implementation___elabb ();
5929       system__finalization_implementation_E++;
5930    @}
5931    if (ada__finalization_E == 0) @{
5932       ada__finalization___elabs ();
5933    @}
5934    ada__finalization_E = 1;
5935    if (ada__finalization__list_controller_E == 0) @{
5936       ada__finalization__list_controller___elabs ();
5937    @}
5938    ada__finalization__list_controller_E = 1;
5939    if (system__file_control_block_E == 0) @{
5940       system__file_control_block___elabs ();
5941       system__file_control_block_E++;
5942    @}
5943    if (system__file_io_E == 0) @{
5944       system__file_io___elabb ();
5945       system__file_io_E++;
5946    @}
5947    if (ada__text_io_E == 0) @{
5948       ada__text_io___elabs ();
5949    @}
5950    if (ada__text_io_E == 0) @{
5951       ada__text_io___elabb ();
5952       ada__text_io_E++;
5953    @}
5954
5955    __gnat_inside_elab_final_code = 0;
5956 @}
5957 int main (argc, argv, envp)
5958     int argc;
5959     char **argv;
5960     char **envp;
5961 @{
5962    gnat_argc = argc;
5963    gnat_argv = argv;
5964    gnat_envp = envp;
5965
5966    __gnat_initialize ();
5967    adainit ();
5968    __gnat_break_start ();
5969
5970    _ada_hello ();
5971
5972    system__standard_library__adafinal ();
5973    __gnat_finalize ();
5974    exit (gnat_exit_status);
5975 @}
5976 unsigned helloB = 0x7880BEB3;
5977 unsigned system__standard_libraryB = 0x0D24CBD0;
5978 unsigned system__standard_libraryS = 0x3283DBEB;
5979 unsigned adaS = 0x2359F9ED;
5980 unsigned ada__text_ioB = 0x47C85FC4;
5981 unsigned ada__text_ioS = 0x496FE45C;
5982 unsigned ada__exceptionsB = 0x74F50187;
5983 unsigned ada__exceptionsS = 0x6736945B;
5984 unsigned gnatS = 0x156A40CF;
5985 unsigned gnat__heap_sort_aB = 0x033DABE0;
5986 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
5987 unsigned systemS = 0x0331C6FE;
5988 unsigned system__exceptionsS = 0x20C9ECA4;
5989 unsigned system__exception_tableB = 0x68A22947;
5990 unsigned system__exception_tableS = 0x394BADD5;
5991 unsigned gnat__htableB = 0x08258E1B;
5992 unsigned gnat__htableS = 0x367D5222;
5993 unsigned system__machine_state_operationsB = 0x4F3B7492;
5994 unsigned system__machine_state_operationsS = 0x182F5CF4;
5995 unsigned system__storage_elementsB = 0x2F1EB794;
5996 unsigned system__storage_elementsS = 0x102C83C7;
5997 unsigned system__secondary_stackB = 0x1574B6E9;
5998 unsigned system__secondary_stackS = 0x708E260A;
5999 unsigned system__parametersB = 0x56D770CD;
6000 unsigned system__parametersS = 0x237E39BE;
6001 unsigned system__soft_linksB = 0x08AB6B2C;
6002 unsigned system__soft_linksS = 0x1E2491F3;
6003 unsigned system__stack_checkingB = 0x476457A0;
6004 unsigned system__stack_checkingS = 0x5299FCED;
6005 unsigned system__tracebackB = 0x2971EBDE;
6006 unsigned system__tracebackS = 0x2E9C3122;
6007 unsigned ada__streamsS = 0x7C25DE96;
6008 unsigned ada__tagsB = 0x39ADFFA2;
6009 unsigned ada__tagsS = 0x769A0464;
6010 unsigned system__string_opsB = 0x5EB646AB;
6011 unsigned system__string_opsS = 0x63CED018;
6012 unsigned interfacesS = 0x0357E00A;
6013 unsigned interfaces__c_streamsB = 0x3784FB72;
6014 unsigned interfaces__c_streamsS = 0x2E723019;
6015 unsigned system__file_ioB = 0x623358EA;
6016 unsigned system__file_ioS = 0x31F873E6;
6017 unsigned ada__finalizationB = 0x6843F68A;
6018 unsigned ada__finalizationS = 0x63305874;
6019 unsigned system__finalization_rootB = 0x31E56CE1;
6020 unsigned system__finalization_rootS = 0x23169EF3;
6021 unsigned system__finalization_implementationB = 0x6CCBA70E;
6022 unsigned system__finalization_implementationS = 0x604AA587;
6023 unsigned system__string_ops_concat_3B = 0x572E3F58;
6024 unsigned system__string_ops_concat_3S = 0x01F57876;
6025 unsigned system__stream_attributesB = 0x1D4F93E8;
6026 unsigned system__stream_attributesS = 0x30B2EC3D;
6027 unsigned ada__io_exceptionsS = 0x34054F96;
6028 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6029 unsigned system__file_control_blockS = 0x2FF876A8;
6030 unsigned ada__finalization__list_controllerB = 0x5760634A;
6031 unsigned ada__finalization__list_controllerS = 0x5D851835;
6032
6033 /* BEGIN ELABORATION ORDER
6034 ada (spec)
6035 gnat (spec)
6036 gnat.heap_sort_a (spec)
6037 gnat.htable (spec)
6038 gnat.htable (body)
6039 interfaces (spec)
6040 system (spec)
6041 system.parameters (spec)
6042 system.standard_library (spec)
6043 ada.exceptions (spec)
6044 system.exceptions (spec)
6045 system.parameters (body)
6046 gnat.heap_sort_a (body)
6047 interfaces.c_streams (spec)
6048 interfaces.c_streams (body)
6049 system.exception_table (spec)
6050 system.exception_table (body)
6051 ada.io_exceptions (spec)
6052 system.storage_elements (spec)
6053 system.storage_elements (body)
6054 system.machine_state_operations (spec)
6055 system.machine_state_operations (body)
6056 system.secondary_stack (spec)
6057 system.stack_checking (spec)
6058 system.soft_links (spec)
6059 system.soft_links (body)
6060 system.stack_checking (body)
6061 system.secondary_stack (body)
6062 system.standard_library (body)
6063 system.string_ops (spec)
6064 system.string_ops (body)
6065 ada.tags (spec)
6066 ada.tags (body)
6067 ada.streams (spec)
6068 system.finalization_root (spec)
6069 system.finalization_root (body)
6070 system.string_ops_concat_3 (spec)
6071 system.string_ops_concat_3 (body)
6072 system.traceback (spec)
6073 system.traceback (body)
6074 ada.exceptions (body)
6075 system.unsigned_types (spec)
6076 system.stream_attributes (spec)
6077 system.stream_attributes (body)
6078 system.finalization_implementation (spec)
6079 system.finalization_implementation (body)
6080 ada.finalization (spec)
6081 ada.finalization (body)
6082 ada.finalization.list_controller (spec)
6083 ada.finalization.list_controller (body)
6084 system.file_control_block (spec)
6085 system.file_io (spec)
6086 system.file_io (body)
6087 ada.text_io (spec)
6088 ada.text_io (body)
6089 hello (body)
6090    END ELABORATION ORDER */
6091
6092 /* BEGIN Object file/option list
6093 ./hello.o
6094 -L./
6095 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6096 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6097 -lexc
6098    END Object file/option list */
6099
6100 @end smallexample
6101
6102 @noindent
6103 Here again, the C code is exactly what is generated by the binder. The
6104 functions of the various parts of this code correspond in an obvious
6105 manner with the commented Ada code shown in the example in the previous
6106 section.
6107
6108 @node Consistency-Checking Modes
6109 @section Consistency-Checking Modes
6110
6111 @noindent
6112 As described in the previous section, by default @code{gnatbind} checks
6113 that object files are consistent with one another and are consistent
6114 with any source files it can locate. The following switches control binder
6115 access to sources.
6116
6117 @table @code
6118 @item -s
6119 @cindex @code{-s} (@code{gnatbind})
6120 Require source files to be present. In this mode, the binder must be
6121 able to locate all source files that are referenced, in order to check
6122 their consistency. In normal mode, if a source file cannot be located it
6123 is simply ignored. If you specify this switch, a missing source
6124 file is an error.
6125
6126 @item -x
6127 @cindex @code{-x} (@code{gnatbind})
6128 Exclude source files. In this mode, the binder only checks that ALI
6129 files are consistent with one another. Source files are not accessed.
6130 The binder runs faster in this mode, and there is still a guarantee that
6131 the resulting program is self-consistent.
6132 If a source file has been edited since it was last compiled, and you
6133 specify this switch, the binder will not detect that the object
6134 file is out of date with respect to the source file. Note that this is the
6135 mode that is automatically used by @code{gnatmake} because in this
6136 case the checking against sources has already been performed by
6137 @code{gnatmake} in the course of compilation (i.e. before binding).
6138
6139 @end table
6140
6141 @node Binder Error Message Control
6142 @section Binder Error Message Control
6143
6144 @noindent
6145 The following switches provide control over the generation of error
6146 messages from the binder:
6147
6148 @table @code
6149 @item -v
6150 @cindex @code{-v} (@code{gnatbind})
6151 Verbose mode. In the normal mode, brief error messages are generated to
6152 @file{stderr}. If this switch is present, a header is written
6153 to @file{stdout} and any error messages are directed to @file{stdout}.
6154 All that is written to @file{stderr} is a brief summary message.
6155
6156 @item -b
6157 @cindex @code{-b} (@code{gnatbind})
6158 Generate brief error messages to @file{stderr} even if verbose mode is
6159 specified. This is relevant only when used with the
6160 @code{-v} switch.
6161
6162 @item -m@var{n}
6163 @cindex @code{-m} (@code{gnatbind})
6164 Limits the number of error messages to @var{n}, a decimal integer in the
6165 range 1-999. The binder terminates immediately if this limit is reached.
6166
6167 @item -M@var{xxx}
6168 @cindex @code{-M} (@code{gnatbind})
6169 Renames the generated main program from @code{main} to @code{xxx}.
6170 This is useful in the case of some cross-building environments, where
6171 the actual main program is separate from the one generated
6172 by @code{gnatbind}.
6173
6174 @item -ws
6175 @cindex @code{-ws} (@code{gnatbind})
6176 @cindex Warnings
6177 Suppress all warning messages.
6178
6179 @item -we
6180 @cindex @code{-we} (@code{gnatbind})
6181 Treat any warning messages as fatal errors.
6182
6183
6184 @item -t
6185 @cindex @code{-t} (@code{gnatbind})
6186 @cindex Time stamp checks, in binder
6187 @cindex Binder consistency checks
6188 @cindex Consistency checks, in binder
6189 The binder performs a number of consistency checks including:
6190
6191 @itemize @bullet
6192 @item
6193 Check that time stamps of a given source unit are consistent
6194 @item
6195 Check that checksums of a given source unit are consistent
6196 @item
6197 Check that consistent versions of @code{GNAT} were used for compilation
6198 @item
6199 Check consistency of configuration pragmas as required
6200 @end itemize
6201
6202 @noindent
6203 Normally failure of such checks, in accordance with the consistency
6204 requirements of the Ada Reference Manual, causes error messages to be
6205 generated which abort the binder and prevent the output of a binder
6206 file and subsequent link to obtain an executable.
6207
6208 The @code{-t} switch converts these error messages
6209 into warnings, so that
6210 binding and linking can continue to completion even in the presence of such
6211 errors. The result may be a failed link (due to missing symbols), or a
6212 non-functional executable which has undefined semantics.
6213 @emph{This means that
6214 @code{-t} should be used only in unusual situations,
6215 with extreme care.}
6216 @end table
6217
6218 @node Elaboration Control
6219 @section Elaboration Control
6220
6221 @noindent
6222 The following switches provide additional control over the elaboration
6223 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6224
6225 @table @code
6226 @item -p
6227 @cindex @code{-h} (@code{gnatbind})
6228 Normally the binder attempts to choose an elaboration order that is
6229 likely to minimize the likelihood of an elaboration order error resulting
6230 in raising a @code{Program_Error} exception. This switch reverses the
6231 action of the binder, and requests that it deliberately choose an order
6232 that is likely to maximize the likelihood of an elaboration error.
6233 This is useful in ensuring portability and avoiding dependence on
6234 accidental fortuitous elaboration ordering.
6235
6236 Normally it only makes sense to use the @code{-p} switch if dynamic
6237 elaboration checking is used (@option{-gnatE} switch used for compilation).
6238 This is because in the default static elaboration mode, all necessary
6239 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6240 pragmas are still respected by the binder in @code{-p} mode, so a
6241 safe elaboration order is assured.
6242 @end table
6243
6244 @node Output Control
6245 @section Output Control
6246
6247 @noindent
6248 The following switches allow additional control over the output
6249 generated by the binder.
6250
6251 @table @code
6252
6253 @item -A
6254 @cindex @code{-A} (@code{gnatbind})
6255 Generate binder program in Ada (default). The binder program is named
6256 @file{b~@var{mainprog}.adb} by default. This can be changed with
6257 @code{-o} @code{gnatbind} option.
6258
6259 @item -c
6260 @cindex @code{-c} (@code{gnatbind})
6261 Check only. Do not generate the binder output file. In this mode the
6262 binder performs all error checks but does not generate an output file.
6263
6264 @item -C
6265 @cindex @code{-C} (@code{gnatbind})
6266 Generate binder program in C. The binder program is named
6267 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6268 option.
6269
6270 @item -e
6271 @cindex @code{-e} (@code{gnatbind})
6272 Output complete list of elaboration-order dependencies, showing the
6273 reason for each dependency. This output can be rather extensive but may
6274 be useful in diagnosing problems with elaboration order. The output is
6275 written to @file{stdout}.
6276
6277 @item -h
6278 @cindex @code{-h} (@code{gnatbind})
6279 Output usage information. The output is written to @file{stdout}.
6280
6281 @item -K
6282 @cindex @code{-K} (@code{gnatbind})
6283 Output linker options to @file{stdout}. Includes library search paths,
6284 contents of pragmas Ident and Linker_Options, and libraries added
6285 by @code{gnatbind}.
6286
6287 @item -l
6288 @cindex @code{-l} (@code{gnatbind})
6289 Output chosen elaboration order. The output is written to @file{stdout}.
6290
6291 @item -O
6292 @cindex @code{-O} (@code{gnatbind})
6293 Output full names of all the object files that must be linked to provide
6294 the Ada component of the program. The output is written to @file{stdout}.
6295 This list includes the files explicitly supplied and referenced by the user
6296 as well as implicitly referenced run-time unit files. The latter are
6297 omitted if the corresponding units reside in shared libraries. The
6298 directory names for the run-time units depend on the system configuration.
6299
6300 @item -o @var{file}
6301 @cindex @code{-o} (@code{gnatbind})
6302 Set name of output file to @var{file} instead of the normal
6303 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6304 binder generated body filename. In C mode you would normally give
6305 @var{file} an extension of @file{.c} because it will be a C source program.
6306 Note that if this option is used, then linking must be done manually.
6307 It is not possible to use gnatlink in this case, since it cannot locate
6308 the binder file.
6309
6310 @item -r
6311 @cindex @code{-r} (@code{gnatbind})
6312 Generate list of @code{pragma Rerstrictions} that could be applied to
6313 the current unit. This is useful for code audit purposes, and also may
6314 be used to improve code generation in some cases.
6315
6316 @end table
6317
6318 @node Binding with Non-Ada Main Programs
6319 @section Binding with Non-Ada Main Programs
6320
6321 @noindent
6322 In our description so far we have assumed that the main
6323 program is in Ada, and that the task of the binder is to generate a
6324 corresponding function @code{main} that invokes this Ada main
6325 program. GNAT also supports the building of executable programs where
6326 the main program is not in Ada, but some of the called routines are
6327 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6328 The following switch is used in this situation:
6329
6330 @table @code
6331 @item -n
6332 @cindex @code{-n} (@code{gnatbind})
6333 No main program. The main program is not in Ada.
6334 @end table
6335
6336 @noindent
6337 In this case, most of the functions of the binder are still required,
6338 but instead of generating a main program, the binder generates a file
6339 containing the following callable routines:
6340
6341 @table @code
6342 @item adainit
6343 @findex adainit
6344 You must call this routine to initialize the Ada part of the program by
6345 calling the necessary elaboration routines. A call to @code{adainit} is
6346 required before the first call to an Ada subprogram.
6347
6348 Note that it is assumed that the basic execution environment must be setup
6349 to be appropriate for Ada execution at the point where the first Ada
6350 subprogram is called. In particular, if the Ada code will do any
6351 floating-point operations, then the FPU must be setup in an appropriate
6352 manner. For the case of the x86, for example, full precision mode is
6353 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6354 that the FPU is in the right state.
6355
6356 @item adafinal
6357 @findex adafinal
6358 You must call this routine to perform any library-level finalization
6359 required by the Ada subprograms. A call to @code{adafinal} is required
6360 after the last call to an Ada subprogram, and before the program
6361 terminates.
6362 @end table
6363
6364 @noindent
6365 If the @code{-n} switch
6366 @cindex Binder, multiple input files
6367 is given, more than one ALI file may appear on
6368 the command line for @code{gnatbind}. The normal @dfn{closure}
6369 calculation is performed for each of the specified units. Calculating
6370 the closure means finding out the set of units involved by tracing
6371 @code{with} references. The reason it is necessary to be able to
6372 specify more than one ALI file is that a given program may invoke two or
6373 more quite separate groups of Ada units.
6374
6375 The binder takes the name of its output file from the last specified ALI
6376 file, unless overridden by the use of the @code{-o file}.
6377 The output is an Ada unit in source form that can
6378 be compiled with GNAT unless the -C switch is used in which case the
6379 output is a C source file, which must be compiled using the C compiler.
6380 This compilation occurs automatically as part of the @code{gnatlink}
6381 processing.
6382
6383 Currently the GNAT run time requires a FPU using 80 bits mode
6384 precision. Under targets where this is not the default it is required to
6385 call GNAT.Float_Control.Reset before using floating point numbers (this
6386 include float computation, float input and output) in the Ada code. A
6387 side effect is that this could be the wrong mode for the foreign code
6388 where floating point computation could be broken after this call.
6389
6390 @node Binding Programs with No Main Subprogram
6391 @section Binding Programs with No Main Subprogram
6392
6393 @noindent
6394 It is possible to have an Ada program which does not have a main
6395 subprogram. This program will call the elaboration routines of all the
6396 packages, then the finalization routines.
6397
6398 The following switch is used to bind programs organized in this manner:
6399
6400 @table @code
6401 @item -z
6402 @cindex @code{-z} (@code{gnatbind})
6403 Normally the binder checks that the unit name given on the command line
6404 corresponds to a suitable main subprogram. When this switch is used,
6405 a list of ALI files can be given, and the execution of the program
6406 consists of elaboration of these units in an appropriate order.
6407 @end table
6408
6409 @node Summary of Binder Switches
6410 @section Summary of Binder Switches
6411
6412 @noindent
6413 The following are the switches available with @code{gnatbind}:
6414
6415 @table @code
6416 @item -aO
6417 Specify directory to be searched for ALI files.
6418
6419 @item -aI
6420 Specify directory to be searched for source file.
6421
6422 @item -A
6423 Generate binder program in Ada (default)
6424
6425 @item -b
6426 Generate brief messages to @file{stderr} even if verbose mode set.
6427
6428 @item -c
6429 Check only, no generation of binder output file.
6430
6431 @item -C
6432 Generate binder program in C
6433
6434 @item -e
6435 Output complete list of elaboration-order dependencies.
6436
6437 @item -E
6438 Store tracebacks in exception occurrences when the target supports it.
6439 This is the default with the zero cost exception mechanism.
6440 This option is currently supported on the following targets:
6441 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6442 See also the packages @code{GNAT.Traceback} and
6443 @code{GNAT.Traceback.Symbolic} for more information.
6444 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6445 @code{gcc} option.
6446
6447 @item -h
6448 Output usage (help) information
6449
6450 @item -I
6451 Specify directory to be searched for source and ALI files.
6452
6453 @item -I-
6454 Do not look for sources in the current directory where @code{gnatbind} was
6455 invoked, and do not look for ALI files in the directory containing the
6456 ALI file named in the @code{gnatbind} command line.
6457
6458 @item -l
6459 Output chosen elaboration order.
6460
6461 @item -Lxxx
6462 Binds the units for library building. In this case the adainit and
6463 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6464 are renamed to xxxinit and xxxfinal. Implies -n.
6465 See @pxref{GNAT and Libraries} for more details.
6466
6467 @item -Mxyz
6468 Rename generated main program from main to xyz
6469
6470 @item -m@var{n}
6471 Limit number of detected errors to @var{n} (1-999).
6472 Furthermore, under Windows, the sources pointed to by the libraries path
6473 set in the registry are not searched for.
6474
6475 @item -n
6476 No main program.
6477
6478 @item -nostdinc
6479 Do not look for sources in the system default directory.
6480
6481 @item -nostdlib
6482 Do not look for library files in the system default directory.
6483
6484 @item --RTS=@var{rts-path}
6485 @cindex @code{--RTS} (@code{gnatbind})
6486 Specifies the default location of the runtime library. Same meaning as the
6487 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6488
6489 @item -o @var{file}
6490 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6491 Note that if this option is used, then linking must be done manually,
6492 gnatlink cannot be used.
6493
6494 @item -O
6495 Output object list.
6496
6497 @item -p
6498 Pessimistic (worst-case) elaboration order
6499
6500 @item -s
6501 Require all source files to be present.
6502
6503 @item -static
6504 Link against a static GNAT run time.
6505
6506 @item -shared
6507 Link against a shared GNAT run time when available.
6508
6509 @item -t
6510 Tolerate time stamp and other consistency errors
6511
6512 @item -T@var{n}
6513 Set the time slice value to n microseconds. A value of zero means no time
6514 slicing and also indicates to the tasking run time to match as close as
6515 possible to the annex D requirements of the RM.
6516
6517 @item -v
6518 Verbose mode. Write error messages, header, summary output to
6519 @file{stdout}.
6520
6521 @item -w@var{x}
6522 Warning mode (@var{x}=s/e for suppress/treat as error)
6523
6524
6525 @item -x
6526 Exclude source files (check object consistency only).
6527
6528
6529 @item -z
6530 No main subprogram.
6531
6532 @end table
6533
6534 You may obtain this listing by running the program @code{gnatbind} with
6535 no arguments.
6536
6537 @node Command-Line Access
6538 @section Command-Line Access
6539
6540 @noindent
6541 The package @code{Ada.Command_Line} provides access to the command-line
6542 arguments and program name. In order for this interface to operate
6543 correctly, the two variables
6544
6545 @smallexample
6546 @group
6547 @cartouche
6548 int gnat_argc;
6549 char **gnat_argv;
6550 @end cartouche
6551 @end group
6552 @end smallexample
6553
6554 @noindent
6555 @findex gnat_argv
6556 @findex gnat_argc
6557 are declared in one of the GNAT library routines. These variables must
6558 be set from the actual @code{argc} and @code{argv} values passed to the
6559 main program. With no @code{n} present, @code{gnatbind}
6560 generates the C main program to automatically set these variables.
6561 If the @code{n} switch is used, there is no automatic way to
6562 set these variables. If they are not set, the procedures in
6563 @code{Ada.Command_Line} will not be available, and any attempt to use
6564 them will raise @code{Constraint_Error}. If command line access is
6565 required, your main program must set @code{gnat_argc} and
6566 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6567 it.
6568
6569 @node Search Paths for gnatbind
6570 @section Search Paths for @code{gnatbind}
6571
6572 @noindent
6573 The binder takes the name of an ALI file as its argument and needs to
6574 locate source files as well as other ALI files to verify object consistency.
6575
6576 For source files, it follows exactly the same search rules as @code{gcc}
6577 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6578 directories searched are:
6579
6580 @enumerate
6581 @item
6582 The directory containing the ALI file named in the command line, unless
6583 the switch @code{-I-} is specified.
6584
6585 @item
6586 All directories specified by @code{-I}
6587 switches on the @code{gnatbind}
6588 command line, in the order given.
6589
6590 @item
6591 @findex ADA_OBJECTS_PATH
6592 Each of the directories listed in the value of the
6593 @code{ADA_OBJECTS_PATH} environment variable.
6594 Construct this value
6595 exactly as the @code{PATH} environment variable: a list of directory
6596 names separated by colons (semicolons when working with the NT version
6597 of GNAT).
6598
6599 @item
6600 The content of the "ada_object_path" file which is part of the GNAT
6601 installation tree and is used to store standard libraries such as the
6602 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6603 specified.
6604 @ref{Installing an Ada Library}
6605 @end enumerate
6606
6607 @noindent
6608 In the binder the switch @code{-I}
6609 is used to specify both source and
6610 library file paths. Use @code{-aI}
6611 instead if you want to specify
6612 source paths only, and @code{-aO}
6613 if you want to specify library paths
6614 only. This means that for the binder
6615 @code{-I}@var{dir} is equivalent to
6616 @code{-aI}@var{dir}
6617 @code{-aO}@var{dir}.
6618 The binder generates the bind file (a C language source file) in the
6619 current working directory.
6620
6621 @findex Ada
6622 @findex System
6623 @findex Interfaces
6624 @findex GNAT
6625 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6626 children make up the GNAT Run-Time Library, together with the package
6627 GNAT and its children, which contain a set of useful additional
6628 library functions provided by GNAT. The sources for these units are
6629 needed by the compiler and are kept together in one directory. The ALI
6630 files and object files generated by compiling the RTL are needed by the
6631 binder and the linker and are kept together in one directory, typically
6632 different from the directory containing the sources. In a normal
6633 installation, you need not specify these directory names when compiling
6634 or binding. Either the environment variables or the built-in defaults
6635 cause these files to be found.
6636
6637 Besides simplifying access to the RTL, a major use of search paths is
6638 in compiling sources from multiple directories. This can make
6639 development environments much more flexible.
6640
6641 @node Examples of gnatbind Usage
6642 @section Examples of @code{gnatbind} Usage
6643
6644 @noindent
6645 This section contains a number of examples of using the GNAT binding
6646 utility @code{gnatbind}.
6647
6648 @table @code
6649 @item gnatbind hello
6650 The main program @code{Hello} (source program in @file{hello.adb}) is
6651 bound using the standard switch settings. The generated main program is
6652 @file{b~hello.adb}. This is the normal, default use of the binder.
6653
6654 @item gnatbind hello -o mainprog.adb
6655 The main program @code{Hello} (source program in @file{hello.adb}) is
6656 bound using the standard switch settings. The generated main program is
6657 @file{mainprog.adb} with the associated spec in
6658 @file{mainprog.ads}. Note that you must specify the body here not the
6659 spec, in the case where the output is in Ada. Note that if this option
6660 is used, then linking must be done manually, since gnatlink will not
6661 be able to find the generated file.
6662
6663 @item gnatbind main -C -o mainprog.c -x
6664 The main program @code{Main} (source program in
6665 @file{main.adb}) is bound, excluding source files from the
6666 consistency checking, generating
6667 the file @file{mainprog.c}.
6668
6669 @item gnatbind -x main_program -C -o mainprog.c
6670 This command is exactly the same as the previous example. Switches may
6671 appear anywhere in the command line, and single letter switches may be
6672 combined into a single switch.
6673
6674 @item gnatbind -n math dbase -C -o ada-control.c
6675 The main program is in a language other than Ada, but calls to
6676 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6677 to @code{gnatbind} generates the file @file{ada-control.c} containing
6678 the @code{adainit} and @code{adafinal} routines to be called before and
6679 after accessing the Ada units.
6680 @end table
6681
6682 @node Linking Using gnatlink
6683 @chapter Linking Using @code{gnatlink}
6684 @findex gnatlink
6685
6686 @noindent
6687 This chapter discusses @code{gnatlink}, a utility program used to link
6688 Ada programs and build an executable file. This is a simple program
6689 that invokes the Unix linker (via the @code{gcc}
6690 command) with a correct list of object files and library references.
6691 @code{gnatlink} automatically determines the list of files and
6692 references for the Ada part of a program. It uses the binder file
6693 generated by the binder to determine this list.
6694
6695 @menu
6696 * Running gnatlink::
6697 * Switches for gnatlink::
6698 * Setting Stack Size from gnatlink::
6699 * Setting Heap Size from gnatlink::
6700 @end menu
6701
6702 @node Running gnatlink
6703 @section Running @code{gnatlink}
6704
6705 @noindent
6706 The form of the @code{gnatlink} command is
6707
6708 @smallexample
6709 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6710       [@var{linker options}]
6711 @end smallexample
6712
6713 @noindent
6714 @file{@var{mainprog}.ali} references the ALI file of the main program.
6715 The @file{.ali} extension of this file can be omitted. From this
6716 reference, @code{gnatlink} locates the corresponding binder file
6717 @file{b~@var{mainprog}.adb} and, using the information in this file along
6718 with the list of non-Ada objects and linker options, constructs a Unix
6719 linker command file to create the executable.
6720
6721 The arguments following @file{@var{mainprog}.ali} are passed to the
6722 linker uninterpreted. They typically include the names of object files
6723 for units written in other languages than Ada and any library references
6724 required to resolve references in any of these foreign language units,
6725 or in @code{pragma Import} statements in any Ada units.
6726
6727 @var{linker options} is an optional list of linker specific
6728 switches. The default linker called by gnatlink is @var{gcc} which in
6729 turn calls the appropriate system linker usually called
6730 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6731 @code{-Ldir} can be added as is. For options that are not recognized by
6732 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6733 @code{-Wl,} shall be used. Refer to the GCC documentation for
6734 details. Here is an example showing how to generate a linker map
6735 assuming that the underlying linker is GNU ld:
6736
6737 @smallexample
6738 $ gnatlink my_prog -Wl,-Map,MAPFILE
6739 @end smallexample
6740
6741 Using @var{linker options} it is possible to set the program stack and
6742 heap size. See @pxref{Setting Stack Size from gnatlink} and
6743 @pxref{Setting Heap Size from gnatlink}.
6744
6745 @code{gnatlink} determines the list of objects required by the Ada
6746 program and prepends them to the list of objects passed to the linker.
6747 @code{gnatlink} also gathers any arguments set by the use of
6748 @code{pragma Linker_Options} and adds them to the list of arguments
6749 presented to the linker.
6750
6751
6752 @node Switches for gnatlink
6753 @section Switches for @code{gnatlink}
6754
6755 @noindent
6756 The following switches are available with the @code{gnatlink} utility:
6757
6758 @table @code
6759
6760 @item -A
6761 @cindex @code{-A} (@code{gnatlink})
6762 The binder has generated code in Ada. This is the default.
6763
6764 @item -C
6765 @cindex @code{-C} (@code{gnatlink})
6766 If instead of generating a file in Ada, the binder has generated one in
6767 C, then the linker needs to know about it. Use this switch to signal
6768 to @code{gnatlink} that the binder has generated C code rather than
6769 Ada code.
6770
6771 @item -f
6772 @cindex Command line length
6773 @cindex @code{-f} (@code{gnatlink})
6774 On some targets, the command line length is limited, and @code{gnatlink}
6775 will generate a separate file for the linker if the list of object files
6776 is too long. The @code{-f} flag forces this file to be generated even if
6777 the limit is not exceeded. This is useful in some cases to deal with
6778 special situations where the command line length is exceeded.
6779
6780 @item -g
6781 @cindex Debugging information, including
6782 @cindex @code{-g} (@code{gnatlink})
6783 The option to include debugging information causes the Ada bind file (in
6784 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6785 @code{-g}.
6786 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6787 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6788 Without @code{-g}, the binder removes these files by
6789 default. The same procedure apply if a C bind file was generated using
6790 @code{-C} @code{gnatbind} option, in this case the filenames are
6791 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6792
6793 @item -n
6794 @cindex @code{-n} (@code{gnatlink})
6795 Do not compile the file generated by the binder. This may be used when
6796 a link is rerun with different options, but there is no need to recompile
6797 the binder file.
6798
6799 @item -v
6800 @cindex @code{-v} (@code{gnatlink})
6801 Causes additional information to be output, including a full list of the
6802 included object files. This switch option is most useful when you want
6803 to see what set of object files are being used in the link step.
6804
6805 @item -v -v
6806 @cindex @code{-v -v} (@code{gnatlink})
6807 Very verbose mode. Requests that the compiler operate in verbose mode when
6808 it compiles the binder file, and that the system linker run in verbose mode.
6809
6810 @item -o @var{exec-name}
6811 @cindex @code{-o} (@code{gnatlink})
6812 @var{exec-name} specifies an alternate name for the generated
6813 executable program. If this switch is omitted, the executable has the same
6814 name as the main unit. For example, @code{gnatlink try.ali} creates
6815 an executable called @file{try}.
6816
6817 @item -b @var{target}
6818 @cindex @code{-b} (@code{gnatlink})
6819 Compile your program to run on @var{target}, which is the name of a
6820 system configuration. You must have a GNAT cross-compiler built if
6821 @var{target} is not the same as your host system.
6822
6823 @item -B@var{dir}
6824 @cindex @code{-B} (@code{gnatlink})
6825 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6826 from @var{dir} instead of the default location. Only use this switch
6827 when multiple versions of the GNAT compiler are available. See the
6828 @code{gcc} manual page for further details. You would normally use the
6829 @code{-b} or @code{-V} switch instead.
6830
6831 @item --GCC=@var{compiler_name}
6832 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6833 Program used for compiling the binder file. The default is
6834 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6835 @code{compiler_name} contains spaces or other separator characters. As
6836 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6837 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6838 inserted after your command name. Thus in the above example the compiler
6839 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6840 If several @code{--GCC=compiler_name} are used, only the last
6841 @var{compiler_name} is taken into account. However, all the additional
6842 switches are also taken into account. Thus,
6843 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6844 @code{--GCC="bar -x -y -z -t"}.
6845
6846 @item --LINK=@var{name}
6847 @cindex @code{--LINK=} (@code{gnatlink})
6848 @var{name} is the name of the linker to be invoked. This is especially
6849 useful in mixed language programs since languages such as c++ require
6850 their own linker to be used. When this switch is omitted, the default
6851 name for the linker is (@file{gcc}). When this switch is used, the
6852 specified linker is called instead of (@file{gcc}) with exactly the same
6853 parameters that would have been passed to (@file{gcc}) so if the desired
6854 linker requires different parameters it is necessary to use a wrapper
6855 script that massages the parameters before invoking the real linker. It
6856 may be useful to control the exact invocation by using the verbose
6857 switch.
6858
6859
6860
6861 @end table
6862
6863 @node Setting Stack Size from gnatlink
6864 @section Setting Stack Size from @code{gnatlink}
6865
6866 @noindent
6867 It is possible to specify the program stack size from @code{gnatlink}.
6868 Assuming that the underlying linker is GNU ld there is two ways to do so:
6869
6870 @itemize @bullet
6871
6872 @item using @code{-Xlinker} linker option
6873
6874 @smallexample
6875 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6876 @end smallexample
6877
6878 This set the stack reserve size to 0x10000 bytes and the stack commit
6879 size to 0x1000 bytes.
6880
6881 @item using @code{-Wl} linker option
6882
6883 @smallexample
6884 $ gnatlink hello -Wl,--stack=0x1000000
6885 @end smallexample
6886
6887 This set the stack reserve size to 0x1000000 bytes. Note that with
6888 @code{-Wl} option it is not possible to set the stack commit size
6889 because the coma is a separator for this option.
6890
6891 @end itemize
6892
6893 @node Setting Heap Size from gnatlink
6894 @section Setting Heap Size from @code{gnatlink}
6895
6896 @noindent
6897 It is possible to specify the program heap size from @code{gnatlink}.
6898 Assuming that the underlying linker is GNU ld there is two ways to do so:
6899
6900 @itemize @bullet
6901
6902 @item using @code{-Xlinker} linker option
6903
6904 @smallexample
6905 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
6906 @end smallexample
6907
6908 This set the heap reserve size to 0x10000 bytes and the heap commit
6909 size to 0x1000 bytes.
6910
6911 @item using @code{-Wl} linker option
6912
6913 @smallexample
6914 $ gnatlink hello -Wl,--heap=0x1000000
6915 @end smallexample
6916
6917 This set the heap reserve size to 0x1000000 bytes. Note that with
6918 @code{-Wl} option it is not possible to set the heap commit size
6919 because the coma is a separator for this option.
6920
6921 @end itemize
6922
6923 @node The GNAT Make Program gnatmake
6924 @chapter The GNAT Make Program @code{gnatmake}
6925 @findex gnatmake
6926
6927 @menu
6928 * Running gnatmake::
6929 * Switches for gnatmake::
6930 * Mode Switches for gnatmake::
6931 * Notes on the Command Line::
6932 * How gnatmake Works::
6933 * Examples of gnatmake Usage::
6934 @end menu
6935 @noindent
6936 A typical development cycle when working on an Ada program consists of
6937 the following steps:
6938
6939 @enumerate
6940 @item
6941 Edit some sources to fix bugs.
6942
6943 @item
6944 Add enhancements.
6945
6946 @item
6947 Compile all sources affected.
6948
6949 @item
6950 Rebind and relink.
6951
6952 @item
6953 Test.
6954 @end enumerate
6955
6956 @noindent
6957 The third step can be tricky, because not only do the modified files
6958 @cindex Dependency rules
6959 have to be compiled, but any files depending on these files must also be
6960 recompiled. The dependency rules in Ada can be quite complex, especially
6961 in the presence of overloading, @code{use} clauses, generics and inlined
6962 subprograms.
6963
6964 @code{gnatmake} automatically takes care of the third and fourth steps
6965 of this process. It determines which sources need to be compiled,
6966 compiles them, and binds and links the resulting object files.
6967
6968 Unlike some other Ada make programs, the dependencies are always
6969 accurately recomputed from the new sources. The source based approach of
6970 the GNAT compilation model makes this possible. This means that if
6971 changes to the source program cause corresponding changes in
6972 dependencies, they will always be tracked exactly correctly by
6973 @code{gnatmake}.
6974
6975 @node Running gnatmake
6976 @section Running @code{gnatmake}
6977
6978 @noindent
6979 The usual form of the @code{gnatmake} command is
6980
6981 @smallexample
6982 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
6983 @end smallexample
6984
6985 @noindent
6986 The only required argument is one @var{file_name}, which specifies
6987 a compilation unit that is a main program. Several @var{file_names} can be
6988 specified: this will result in several executables being built.
6989 If @code{switches} are present, they can be placed before the first
6990 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
6991 If @var{mode_switches} are present, they must always be placed after
6992 the last @var{file_name} and all @code{switches}.
6993
6994 If you are using standard file extensions (.adb and .ads), then the
6995 extension may be omitted from the @var{file_name} arguments. However, if
6996 you are using non-standard extensions, then it is required that the
6997 extension be given. A relative or absolute directory path can be
6998 specified in a @var{file_name}, in which case, the input source file will
6999 be searched for in the specified directory only. Otherwise, the input
7000 source file will first be searched in the directory where
7001 @code{gnatmake} was invoked and if it is not found, it will be search on
7002 the source path of the compiler as described in
7003 @ref{Search Paths and the Run-Time Library (RTL)}.
7004
7005 When several @var{file_names} are specified, if an executable needs to be
7006 rebuilt and relinked, all subsequent executables will be rebuilt and
7007 relinked, even if this would not be absolutely necessary.
7008
7009 All @code{gnatmake} output (except when you specify
7010 @code{-M}) is to
7011 @file{stderr}. The output produced by the
7012 @code{-M} switch is send to
7013 @file{stdout}.
7014
7015 @node Switches for gnatmake
7016 @section Switches for @code{gnatmake}
7017
7018 @noindent
7019 You may specify any of the following switches to @code{gnatmake}:
7020
7021 @table @code
7022 @item --GCC=@var{compiler_name}
7023 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7024 Program used for compiling. The default is `@code{gcc}'. You need to use
7025 quotes around @var{compiler_name} if @code{compiler_name} contains
7026 spaces or other separator characters. As an example @code{--GCC="foo -x
7027 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7028 compiler. Note that switch @code{-c} is always inserted after your
7029 command name. Thus in the above example the compiler command that will
7030 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7031 If several @code{--GCC=compiler_name} are used, only the last
7032 @var{compiler_name} is taken into account. However, all the additional
7033 switches are also taken into account. Thus,
7034 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7035 @code{--GCC="bar -x -y -z -t"}.
7036
7037 @item --GNATBIND=@var{binder_name}
7038 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7039 Program used for binding. The default is `@code{gnatbind}'. You need to
7040 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7041 or other separator characters. As an example @code{--GNATBIND="bar -x
7042 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7043 binder. Binder switches that are normally appended by @code{gnatmake} to
7044 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7045
7046 @item --GNATLINK=@var{linker_name}
7047 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7048 Program used for linking. The default is `@code{gnatlink}'. You need to
7049 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7050 or other separator characters. As an example @code{--GNATLINK="lan -x
7051 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7052 linker. Linker switches that are normally appended by @code{gnatmake} to
7053 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7054
7055
7056 @item -a
7057 @cindex @code{-a} (@code{gnatmake})
7058 Consider all files in the make process, even the GNAT internal system
7059 files (for example, the predefined Ada library files), as well as any
7060 locked files. Locked files are files whose ALI file is write-protected.
7061 By default,
7062 @code{gnatmake} does not check these files,
7063 because the assumption is that the GNAT internal files are properly up
7064 to date, and also that any write protected ALI files have been properly
7065 installed. Note that if there is an installation problem, such that one
7066 of these files is not up to date, it will be properly caught by the
7067 binder.
7068 You may have to specify this switch if you are working on GNAT
7069 itself. @code{-a} is also useful in conjunction with
7070 @code{-f}
7071 if you need to recompile an entire application,
7072 including run-time files, using special configuration pragma settings,
7073 such as a non-standard @code{Float_Representation} pragma.
7074 By default
7075 @code{gnatmake -a} compiles all GNAT
7076 internal files with
7077 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7078
7079 @item -b
7080 @cindex @code{-b} (@code{gnatmake})
7081 Bind only. Can be combined with @code{-c} to do compilation
7082 and binding, but no link. Can be combined with @code{-l}
7083 to do binding and linking. When not combined with @code{-c}
7084 all the units in the closure of the main program must have been previously
7085 compiled and must be up to date. The root unit specified by @var{file_name}
7086 may be given without extension, with the source extension or, if no GNAT
7087 Project File is specified, with the ALI file extension.
7088
7089 @item -c
7090 @cindex @code{-c} (@code{gnatmake})
7091 Compile only. Do not perform binding, except when @code{-b}
7092 is also specified. Do not perform linking, except if both
7093 @code{-b} and
7094  @code{-l} are also specified.
7095 If the root unit specified by @var{file_name} is not a main unit, this is the
7096 default. Otherwise @code{gnatmake} will attempt binding and linking
7097 unless all objects are up to date and the executable is more recent than
7098 the objects.
7099
7100 @item -C
7101 @cindex @code{-C} (@code{gnatmake})
7102 Use a mapping file. A mapping file is a way to communicate to the compiler
7103 two mappings: from unit names to file names (without any directory information)
7104 and from file names to path names (with full directory information).
7105 These mappings are used by the compiler to short-circuit the path search.
7106 When @code{gnatmake} is invoked with this switch, it will create a mapping
7107 file, initially populated by the project manager, if @code{-P} is used,
7108 otherwise initially empty. Each invocation of the compiler will add the newly
7109 accessed sources to the mapping file. This will improve the source search
7110 during the next invocation of the compiler.
7111
7112 @item -f
7113 @cindex @code{-f} (@code{gnatmake})
7114 Force recompilations. Recompile all sources, even though some object
7115 files may be up to date, but don't recompile predefined or GNAT internal
7116 files or locked files (files with a write-protected ALI file),
7117 unless the @code{-a} switch is also specified.
7118
7119 @item
7120 @item -i
7121 @cindex @code{-i} (@code{gnatmake})
7122 In normal mode, @code{gnatmake} compiles all object files and ALI files
7123 into the current directory. If the @code{-i} switch is used,
7124 then instead object files and ALI files that already exist are overwritten
7125 in place. This means that once a large project is organized into separate
7126 directories in the desired manner, then @code{gnatmake} will automatically
7127 maintain and update this organization. If no ALI files are found on the
7128 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7129 the new object and ALI files are created in the
7130 directory containing the source being compiled. If another organization
7131 is desired, where objects and sources are kept in different directories,
7132 a useful technique is to create dummy ALI files in the desired directories.
7133 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7134 the corresponding source file, and it will be put the resulting object
7135 and ALI files in the directory where it found the dummy file.
7136
7137 @item -j@var{n}
7138 @cindex @code{-j} (@code{gnatmake})
7139 @cindex Parallel make
7140 Use @var{n} processes to carry out the (re)compilations. On a
7141 multiprocessor machine compilations will occur in parallel. In the
7142 event of compilation errors, messages from various compilations might
7143 get interspersed (but @code{gnatmake} will give you the full ordered
7144 list of failing compiles at the end). If this is problematic, rerun
7145 the make process with n set to 1 to get a clean list of messages.
7146
7147 @item -k
7148 @cindex @code{-k} (@code{gnatmake})
7149 Keep going. Continue as much as possible after a compilation error. To
7150 ease the programmer's task in case of compilation errors, the list of
7151 sources for which the compile fails is given when @code{gnatmake}
7152 terminates.
7153
7154 If @code{gnatmake} is invoked with several @file{file_names} and with this
7155 switch, if there are compilation errors when building an executable,
7156 @code{gnatmake} will not attempt to build the following executables.
7157
7158 @item -l
7159 @cindex @code{-l} (@code{gnatmake})
7160 Link only. Can be combined with @code{-b} to binding
7161 and linking. Linking will not be performed if combined with
7162 @code{-c}
7163 but not with @code{-b}.
7164 When not combined with @code{-b}
7165 all the units in the closure of the main program must have been previously
7166 compiled and must be up to date, and the main program need to have been bound.
7167 The root unit specified by @var{file_name}
7168 may be given without extension, with the source extension or, if no GNAT
7169 Project File is specified, with the ALI file extension.
7170
7171 @item -m
7172 @cindex @code{-m} (@code{gnatmake})
7173 Specifies that the minimum necessary amount of recompilations
7174 be performed. In this mode @code{gnatmake} ignores time
7175 stamp differences when the only
7176 modifications to a source file consist in adding/removing comments,
7177 empty lines, spaces or tabs. This means that if you have changed the
7178 comments in a source file or have simply reformatted it, using this
7179 switch will tell gnatmake not to recompile files that depend on it
7180 (provided other sources on which these files depend have undergone no
7181 semantic modifications). Note that the debugging information may be
7182 out of date with respect to the sources if the @code{-m} switch causes
7183 a compilation to be switched, so the use of this switch represents a
7184 trade-off between compilation time and accurate debugging information.
7185
7186 @item -M
7187 @cindex Dependencies, producing list
7188 @cindex @code{-M} (@code{gnatmake})
7189 Check if all objects are up to date. If they are, output the object
7190 dependences to @file{stdout} in a form that can be directly exploited in
7191 a @file{Makefile}. By default, each source file is prefixed with its
7192 (relative or absolute) directory name. This name is whatever you
7193 specified in the various @code{-aI}
7194 and @code{-I} switches. If you use
7195 @code{gnatmake -M}
7196 @code{-q}
7197 (see below), only the source file names,
7198 without relative paths, are output. If you just specify the
7199 @code{-M}
7200 switch, dependencies of the GNAT internal system files are omitted. This
7201 is typically what you want. If you also specify
7202 the @code{-a} switch,
7203 dependencies of the GNAT internal files are also listed. Note that
7204 dependencies of the objects in external Ada libraries (see switch
7205 @code{-aL}@var{dir} in the following list) are never reported.
7206
7207 @item -n
7208 @cindex @code{-n} (@code{gnatmake})
7209 Don't compile, bind, or link. Checks if all objects are up to date.
7210 If they are not, the full name of the first file that needs to be
7211 recompiled is printed.
7212 Repeated use of this option, followed by compiling the indicated source
7213 file, will eventually result in recompiling all required units.
7214
7215 @item -o @var{exec_name}
7216 @cindex @code{-o} (@code{gnatmake})
7217 Output executable name. The name of the final executable program will be
7218 @var{exec_name}. If the @code{-o} switch is omitted the default
7219 name for the executable will be the name of the input file in appropriate form
7220 for an executable file on the host system.
7221
7222 This switch cannot be used when invoking @code{gnatmake} with several
7223 @file{file_names}.
7224
7225 @item -q
7226 @cindex @code{-q} (@code{gnatmake})
7227 Quiet. When this flag is not set, the commands carried out by
7228 @code{gnatmake} are displayed.
7229
7230 @item -s
7231 @cindex @code{-s} (@code{gnatmake})
7232 Recompile if compiler switches have changed since last compilation.
7233 All compiler switches but -I and -o are taken into account in the
7234 following way:
7235 orders between different ``first letter'' switches are ignored, but
7236 orders between same switches are taken into account. For example,
7237 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7238 to @code{-O -g}.
7239
7240 @item -u
7241 @cindex @code{-u} (@code{gnatmake})
7242 Unique. Recompile at most the main file. It implies -c. Combined with
7243 -f, it is equivalent to calling the compiler directly.
7244
7245 @item -v
7246 @cindex @code{-v} (@code{gnatmake})
7247 Verbose. Displays the reason for all recompilations @code{gnatmake}
7248 decides are necessary.
7249
7250 @item -z
7251 @cindex @code{-z} (@code{gnatmake})
7252 No main subprogram. Bind and link the program even if the unit name
7253 given on the command line is a package name. The resulting executable
7254 will execute the elaboration routines of the package and its closure,
7255 then the finalization routines.
7256
7257 @item @code{gcc} @asis{switches}
7258 The switch @code{-g} or any uppercase switch (other than @code{-A},
7259 @code{-L} or
7260 @code{-S}) or any switch that is more than one character is passed to
7261 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7262 @end table
7263
7264 @noindent
7265 Source and library search path switches:
7266
7267 @table @code
7268 @item -aI@var{dir}
7269 @cindex @code{-aI} (@code{gnatmake})
7270 When looking for source files also look in directory @var{dir}.
7271 The order in which source files search is undertaken is
7272 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7273
7274 @item -aL@var{dir}
7275 @cindex @code{-aL} (@code{gnatmake})
7276 Consider @var{dir} as being an externally provided Ada library.
7277 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7278 files have been located in directory @var{dir}. This allows you to have
7279 missing bodies for the units in @var{dir} and to ignore out of date bodies
7280 for the same units. You still need to specify
7281 the location of the specs for these units by using the switches
7282 @code{-aI@var{dir}}
7283 or @code{-I@var{dir}}.
7284 Note: this switch is provided for compatibility with previous versions
7285 of @code{gnatmake}. The easier method of causing standard libraries
7286 to be excluded from consideration is to write-protect the corresponding
7287 ALI files.
7288
7289 @item -aO@var{dir}
7290 @cindex @code{-aO} (@code{gnatmake})
7291 When searching for library and object files, look in directory
7292 @var{dir}. The order in which library files are searched is described in
7293 @ref{Search Paths for gnatbind}.
7294
7295 @item -A@var{dir}
7296 @cindex Search paths, for @code{gnatmake}
7297 @cindex @code{-A} (@code{gnatmake})
7298 Equivalent to @code{-aL@var{dir}
7299 -aI@var{dir}}.
7300
7301 @item -I@var{dir}
7302 @cindex @code{-I} (@code{gnatmake})
7303 Equivalent to @code{-aO@var{dir}
7304 -aI@var{dir}}.
7305
7306 @item -I-
7307 @cindex @code{-I-} (@code{gnatmake})
7308 @cindex Source files, suppressing search
7309 Do not look for source files in the directory containing the source
7310 file named in the command line.
7311 Do not look for ALI or object files in the directory
7312 where @code{gnatmake} was invoked.
7313
7314 @item -L@var{dir}
7315 @cindex @code{-L} (@code{gnatmake})
7316 @cindex Linker libraries
7317 Add directory @var{dir} to the list of directories in which the linker
7318 Furthermore, under Windows, the sources pointed to by the libraries path
7319 set in the registry are not searched for.
7320 will search for libraries. This is equivalent to
7321 @code{-largs -L}@var{dir}.
7322
7323 @item -nostdinc
7324 @cindex @code{-nostdinc} (@code{gnatmake})
7325 Do not look for source files in the system default directory.
7326
7327 @item -nostdlib
7328 @cindex @code{-nostdlib} (@code{gnatmake})
7329 Do not look for library files in the system default directory.
7330
7331 @item --RTS=@var{rts-path}
7332 @cindex @code{--RTS} (@code{gnatmake})
7333 Specifies the default location of the runtime library. We look for the runtime
7334 in the following directories, and stop as soon as a valid runtime is found
7335 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7336
7337 @itemize @bullet
7338 @item <current directory>/$rts_path
7339
7340 @item <default-search-dir>/$rts_path
7341
7342 @item <default-search-dir>/rts-$rts_path
7343 @end itemize
7344
7345 @noindent
7346 The selected path is handled like a normal RTS path.
7347
7348 @end table
7349
7350 @node Mode Switches for gnatmake
7351 @section Mode Switches for @code{gnatmake}
7352
7353 @noindent
7354 The mode switches (referred to as @code{mode_switches}) allow the
7355 inclusion of switches that are to be passed to the compiler itself, the
7356 binder or the linker. The effect of a mode switch is to cause all
7357 subsequent switches up to the end of the switch list, or up to the next
7358 mode switch, to be interpreted as switches to be passed on to the
7359 designated component of GNAT.
7360
7361 @table @code
7362 @item -cargs @var{switches}
7363 @cindex @code{-cargs} (@code{gnatmake})
7364 Compiler switches. Here @var{switches} is a list of switches
7365 that are valid switches for @code{gcc}. They will be passed on to
7366 all compile steps performed by @code{gnatmake}.
7367
7368 @item -bargs @var{switches}
7369 @cindex @code{-bargs} (@code{gnatmake})
7370 Binder switches. Here @var{switches} is a list of switches
7371 that are valid switches for @code{gcc}. They will be passed on to
7372 all bind steps performed by @code{gnatmake}.
7373
7374 @item -largs @var{switches}
7375 @cindex @code{-largs} (@code{gnatmake})
7376 Linker switches. Here @var{switches} is a list of switches
7377 that are valid switches for @code{gcc}. They will be passed on to
7378 all link steps performed by @code{gnatmake}.
7379 @end table
7380
7381 @node Notes on the Command Line
7382 @section Notes on the Command Line
7383
7384 @noindent
7385 This section contains some additional useful notes on the operation
7386 of the @code{gnatmake} command.
7387
7388 @itemize @bullet
7389 @item
7390 @cindex Recompilation, by @code{gnatmake}
7391 If @code{gnatmake} finds no ALI files, it recompiles the main program
7392 and all other units required by the main program.
7393 This means that @code{gnatmake}
7394 can be used for the initial compile, as well as during subsequent steps of
7395 the development cycle.
7396
7397 @item
7398 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7399 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7400 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7401 warning.
7402
7403 @item
7404 In @code{gnatmake} the switch @code{-I}
7405 is used to specify both source and
7406 library file paths. Use @code{-aI}
7407 instead if you just want to specify
7408 source paths only and @code{-aO}
7409 if you want to specify library paths
7410 only.
7411
7412 @item
7413 @code{gnatmake} examines both an ALI file and its corresponding object file
7414 for consistency. If an ALI is more recent than its corresponding object,
7415 or if the object file is missing, the corresponding source will be recompiled.
7416 Note that @code{gnatmake} expects an ALI and the corresponding object file
7417 to be in the same directory.
7418
7419 @item
7420 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7421 This may conveniently be used to exclude standard libraries from
7422 consideration and in particular it means that the use of the
7423 @code{-f} switch will not recompile these files
7424 unless @code{-a} is also specified.
7425
7426 @item
7427 @code{gnatmake} has been designed to make the use of Ada libraries
7428 particularly convenient. Assume you have an Ada library organized
7429 as follows: @var{obj-dir} contains the objects and ALI files for
7430 of your Ada compilation units,
7431 whereas @var{include-dir} contains the
7432 specs of these units, but no bodies. Then to compile a unit
7433 stored in @code{main.adb}, which uses this Ada library you would just type
7434
7435 @smallexample
7436 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
7437 @end smallexample
7438
7439 @item
7440 Using @code{gnatmake} along with the
7441 @code{-m (minimal recompilation)}
7442 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7443 this switch,
7444 you can update the comments/format of your
7445 source files without having to recompile everything. Note, however, that
7446 adding or deleting lines in a source files may render its debugging
7447 info obsolete. If the file in question is a spec, the impact is rather
7448 limited, as that debugging info will only be useful during the
7449 elaboration phase of your program. For bodies the impact can be more
7450 significant. In all events, your debugger will warn you if a source file
7451 is more recent than the corresponding object, and alert you to the fact
7452 that the debugging information may be out of date.
7453 @end itemize
7454
7455 @node How gnatmake Works
7456 @section How @code{gnatmake} Works
7457
7458 @noindent
7459 Generally @code{gnatmake} automatically performs all necessary
7460 recompilations and you don't need to worry about how it works. However,
7461 it may be useful to have some basic understanding of the @code{gnatmake}
7462 approach and in particular to understand how it uses the results of
7463 previous compilations without incorrectly depending on them.
7464
7465 First a definition: an object file is considered @dfn{up to date} if the
7466 corresponding ALI file exists and its time stamp predates that of the
7467 object file and if all the source files listed in the
7468 dependency section of this ALI file have time stamps matching those in
7469 the ALI file. This means that neither the source file itself nor any
7470 files that it depends on have been modified, and hence there is no need
7471 to recompile this file.
7472
7473 @code{gnatmake} works by first checking if the specified main unit is up
7474 to date. If so, no compilations are required for the main unit. If not,
7475 @code{gnatmake} compiles the main program to build a new ALI file that
7476 reflects the latest sources. Then the ALI file of the main unit is
7477 examined to find all the source files on which the main program depends,
7478 and @code{gnatmake} recursively applies the above procedure on all these files.
7479
7480 This process ensures that @code{gnatmake} only trusts the dependencies
7481 in an existing ALI file if they are known to be correct. Otherwise it
7482 always recompiles to determine a new, guaranteed accurate set of
7483 dependencies. As a result the program is compiled "upside down" from what may
7484 be more familiar as the required order of compilation in some other Ada
7485 systems. In particular, clients are compiled before the units on which
7486 they depend. The ability of GNAT to compile in any order is critical in
7487 allowing an order of compilation to be chosen that guarantees that
7488 @code{gnatmake} will recompute a correct set of new dependencies if
7489 necessary.
7490
7491 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7492 imported by several of the executables, it will be recompiled at most once.
7493
7494 @node Examples of gnatmake Usage
7495 @section Examples of @code{gnatmake} Usage
7496
7497 @table @code
7498 @item gnatmake hello.adb
7499 Compile all files necessary to bind and link the main program
7500 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7501 resulting object files to generate an executable file @file{hello}.
7502
7503 @item gnatmake main1 main2 main3
7504 Compile all files necessary to bind and link the main programs
7505 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7506 (containing unit @code{Main2}) and @file{main3.adb}
7507 (containing unit @code{Main3}) and bind and link the resulting object files
7508 to generate three executable files @file{main1},
7509 @file{main2}
7510 and @file{main3}.
7511
7512 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7513
7514 Compile all files necessary to bind and link the main program unit
7515 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7516 be done with optimization level 2 and the order of elaboration will be
7517 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7518 displaying commands it is executing.
7519 @end table
7520
7521 @node Renaming Files Using gnatchop
7522 @chapter Renaming Files Using @code{gnatchop}
7523 @findex gnatchop
7524
7525 @noindent
7526 This chapter discusses how to handle files with multiple units by using
7527 the @code{gnatchop} utility. This utility is also useful in renaming
7528 files to meet the standard GNAT default file naming conventions.
7529
7530 @menu
7531 * Handling Files with Multiple Units::
7532 * Operating gnatchop in Compilation Mode::
7533 * Command Line for gnatchop::
7534 * Switches for gnatchop::
7535 * Examples of gnatchop Usage::
7536 @end menu
7537
7538 @node Handling Files with Multiple Units
7539 @section Handling Files with Multiple Units
7540
7541 @noindent
7542 The basic compilation model of GNAT requires that a file submitted to the
7543 compiler have only one unit and there be a strict correspondence
7544 between the file name and the unit name.
7545
7546 The @code{gnatchop} utility allows both of these rules to be relaxed,
7547 allowing GNAT to process files which contain multiple compilation units
7548 and files with arbitrary file names. @code{gnatchop}
7549 reads the specified file and generates one or more output files,
7550 containing one unit per file. The unit and the file name correspond,
7551 as required by GNAT.
7552
7553 If you want to permanently restructure a set of "foreign" files so that
7554 they match the GNAT rules, and do the remaining development using the
7555 GNAT structure, you can simply use @code{gnatchop} once, generate the
7556 new set of files and work with them from that point on.
7557
7558 Alternatively, if you want to keep your files in the "foreign" format,
7559 perhaps to maintain compatibility with some other Ada compilation
7560 system, you can set up a procedure where you use @code{gnatchop} each
7561 time you compile, regarding the source files that it writes as temporary
7562 files that you throw away.
7563
7564 @node Operating gnatchop in Compilation Mode
7565 @section Operating gnatchop in Compilation Mode
7566
7567 @noindent
7568 The basic function of @code{gnatchop} is to take a file with multiple units
7569 and split it into separate files. The boundary between files is reasonably
7570 clear, except for the issue of comments and pragmas. In default mode, the
7571 rule is that any pragmas between units belong to the previous unit, except
7572 that configuration pragmas always belong to the following unit. Any comments
7573 belong to the following unit. These rules
7574 almost always result in the right choice of
7575 the split point without needing to mark it explicitly and most users will
7576 find this default to be what they want. In this default mode it is incorrect to
7577 submit a file containing only configuration pragmas, or one that ends in
7578 configuration pragmas, to @code{gnatchop}.
7579
7580 However, using a special option to activate "compilation mode",
7581 @code{gnatchop}
7582 can perform another function, which is to provide exactly the semantics
7583 required by the RM for handling of configuration pragmas in a compilation.
7584 In the absence of configuration pragmas (at the main file level), this
7585 option has no effect, but it causes such configuration pragmas to be handled
7586 in a quite different manner.
7587
7588 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7589 only configuration pragmas, then this file is appended to the
7590 @file{gnat.adc} file in the current directory. This behavior provides
7591 the required behavior described in the RM for the actions to be taken
7592 on submitting such a file to the compiler, namely that these pragmas
7593 should apply to all subsequent compilations in the same compilation
7594 environment. Using GNAT, the current directory, possibly containing a
7595 @file{gnat.adc} file is the representation
7596 of a compilation environment. For more information on the
7597 @file{gnat.adc} file, see the section on handling of configuration
7598 pragmas @pxref{Handling of Configuration Pragmas}.
7599
7600 Second, in compilation mode, if @code{gnatchop}
7601 is given a file that starts with
7602 configuration pragmas, and contains one or more units, then these
7603 configuration pragmas are prepended to each of the chopped files. This
7604 behavior provides the required behavior described in the RM for the
7605 actions to be taken on compiling such a file, namely that the pragmas
7606 apply to all units in the compilation, but not to subsequently compiled
7607 units.
7608
7609 Finally, if configuration pragmas appear between units, they are appended
7610 to the previous unit. This results in the previous unit being illegal,
7611 since the compiler does not accept configuration pragmas that follow
7612 a unit. This provides the required RM behavior that forbids configuration
7613 pragmas other than those preceding the first compilation unit of a
7614 compilation.
7615
7616 For most purposes, @code{gnatchop} will be used in default mode. The
7617 compilation mode described above is used only if you need exactly
7618 accurate behavior with respect to compilations, and you have files
7619 that contain multiple units and configuration pragmas. In this
7620 circumstance the use of @code{gnatchop} with the compilation mode
7621 switch provides the required behavior, and is for example the mode
7622 in which GNAT processes the ACVC tests.
7623
7624 @node Command Line for gnatchop
7625 @section Command Line for @code{gnatchop}
7626
7627 @noindent
7628 The @code{gnatchop} command has the form:
7629
7630 @smallexample
7631 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7632       [@var{directory}]
7633 @end smallexample
7634
7635 @noindent
7636 The only required argument is the file name of the file to be chopped.
7637 There are no restrictions on the form of this file name. The file itself
7638 contains one or more Ada units, in normal GNAT format, concatenated
7639 together. As shown, more than one file may be presented to be chopped.
7640
7641 When run in default mode, @code{gnatchop} generates one output file in
7642 the current directory for each unit in each of the files.
7643
7644 @var{directory}, if specified, gives the name of the directory to which
7645 the output files will be written. If it is not specified, all files are
7646 written to the current directory.
7647
7648 For example, given a
7649 file called @file{hellofiles} containing
7650
7651 @smallexample
7652 @group
7653 @cartouche
7654 @b{procedure} hello;
7655
7656 @b{with} Text_IO; @b{use} Text_IO;
7657 @b{procedure} hello @b{is}
7658 @b{begin}
7659    Put_Line ("Hello");
7660 @b{end} hello;
7661 @end cartouche
7662 @end group
7663 @end smallexample
7664
7665 @noindent
7666 the command
7667
7668 @smallexample
7669 $ gnatchop hellofiles
7670 @end smallexample
7671
7672 @noindent
7673 generates two files in the current directory, one called
7674 @file{hello.ads} containing the single line that is the procedure spec,
7675 and the other called @file{hello.adb} containing the remaining text. The
7676 original file is not affected. The generated files can be compiled in
7677 the normal manner.
7678
7679 @node Switches for gnatchop
7680 @section Switches for @code{gnatchop}
7681
7682 @noindent
7683 @code{gnatchop} recognizes the following switches:
7684
7685 @table @code
7686
7687 @item -c
7688 @cindex @code{-c} (@code{gnatchop})
7689 Causes @code{gnatchop} to operate in compilation mode, in which
7690 configuration pragmas are handled according to strict RM rules. See
7691 previous section for a full description of this mode.
7692
7693 @item -gnatxxx
7694 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7695 used to parse the given file. Not all @code{xxx} options make sense,
7696 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7697 process a source file that uses Latin-2 coding for identifiers.
7698
7699 @item -h
7700 Causes @code{gnatchop} to generate a brief help summary to the standard
7701 output file showing usage information.
7702
7703 @item -k@var{mm}
7704 @cindex @code{-k} (@code{gnatchop})
7705 Limit generated file names to the specified number @code{mm}
7706 of characters.
7707 This is useful if the
7708 resulting set of files is required to be interoperable with systems
7709 which limit the length of file names.
7710 No space is allowed between the @code{-k} and the numeric value. The numeric
7711 value may be omitted in which case a default of @code{-k8},
7712 suitable for use
7713 with DOS-like file systems, is used. If no @code{-k} switch
7714 is present then
7715 there is no limit on the length of file names.
7716
7717 @item -p
7718 @cindex @code{-p} (@code{gnatchop})
7719 Causes the file modification time stamp of the input file to be
7720 preserved and used for the time stamp of the output file(s). This may be
7721 useful for preserving coherency of time stamps in an enviroment where
7722 @code{gnatchop} is used as part of a standard build process.
7723
7724 @item -q
7725 @cindex @code{-q} (@code{gnatchop})
7726 Causes output of informational messages indicating the set of generated
7727 files to be suppressed. Warnings and error messages are unaffected.
7728
7729 @item -r
7730 @cindex @code{-r} (@code{gnatchop})
7731 @findex Source_Reference
7732 Generate @code{Source_Reference} pragmas. Use this switch if the output
7733 files are regarded as temporary and development is to be done in terms
7734 of the original unchopped file. This switch causes
7735 @code{Source_Reference} pragmas to be inserted into each of the
7736 generated files to refers back to the original file name and line number.
7737 The result is that all error messages refer back to the original
7738 unchopped file.
7739 In addition, the debugging information placed into the object file (when
7740 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7741 refers back to this original file so that tools like profilers and
7742 debuggers will give information in terms of the original unchopped file.
7743
7744 If the original file to be chopped itself contains
7745 a @code{Source_Reference}
7746 pragma referencing a third file, then gnatchop respects
7747 this pragma, and the generated @code{Source_Reference} pragmas
7748 in the chopped file refer to the original file, with appropriate
7749 line numbers. This is particularly useful when @code{gnatchop}
7750 is used in conjunction with @code{gnatprep} to compile files that
7751 contain preprocessing statements and multiple units.
7752
7753 @item -v
7754 @cindex @code{-v} (@code{gnatchop})
7755 Causes @code{gnatchop} to operate in verbose mode. The version
7756 number and copyright notice are output, as well as exact copies of
7757 the gnat1 commands spawned to obtain the chop control information.
7758
7759 @item -w
7760 @cindex @code{-w} (@code{gnatchop})
7761 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7762 fatal error if there is already a file with the same name as a
7763 file it would otherwise output, in other words if the files to be
7764 chopped contain duplicated units. This switch bypasses this
7765 check, and causes all but the last instance of such duplicated
7766 units to be skipped.
7767
7768 @item --GCC=xxxx
7769 @cindex @code{--GCC=} (@code{gnatchop})
7770 Specify the path of the GNAT parser to be used. When this switch is used,
7771 no attempt is made to add the prefix to the GNAT parser executable.
7772 @end table
7773
7774 @node Examples of gnatchop Usage
7775 @section Examples of @code{gnatchop} Usage
7776
7777 @table @code
7778 @item gnatchop -w hello_s.ada ichbiah/files
7779
7780 Chops the source file @file{hello_s.ada}. The output files will be
7781 placed in the directory @file{ichbiah/files},
7782 overwriting any
7783 files with matching names in that directory (no files in the current
7784 directory are modified).
7785
7786 @item gnatchop archive
7787 Chops the source file @file{archive}
7788 into the current directory. One
7789 useful application of @code{gnatchop} is in sending sets of sources
7790 around, for example in email messages. The required sources are simply
7791 concatenated (for example, using a Unix @code{cat}
7792 command), and then
7793 @code{gnatchop} is used at the other end to reconstitute the original
7794 file names.
7795
7796 @item gnatchop file1 file2 file3 direc
7797 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7798 the resulting files in the directory @file{direc}. Note that if any units
7799 occur more than once anywhere within this set of files, an error message
7800 is generated, and no files are written. To override this check, use the
7801 @code{-w} switch,
7802 in which case the last occurrence in the last file will
7803 be the one that is output, and earlier duplicate occurrences for a given
7804 unit will be skipped.
7805 @end table
7806
7807 @node Configuration Pragmas
7808 @chapter Configuration Pragmas
7809 @cindex Configuration pragmas
7810 @cindex Pragmas, configuration
7811
7812 @noindent
7813 In Ada 95, configuration pragmas include those pragmas described as
7814 such in the Ada 95 Reference Manual, as well as
7815 implementation-dependent pragmas that are configuration pragmas. See the
7816 individual descriptions of pragmas in the GNAT Reference Manual for
7817 details on these additional GNAT-specific configuration pragmas. Most
7818 notably, the pragma @code{Source_File_Name}, which allows
7819 specifying non-default names for source files, is a configuration
7820 pragma. The following is a complete list of configuration pragmas
7821 recognized by @code{GNAT}:
7822
7823 @smallexample
7824    Ada_83
7825    Ada_95
7826    C_Pass_By_Copy
7827    Component_Alignment
7828    Discard_Names
7829    Elaboration_Checks
7830    Eliminate
7831    Extend_System
7832    Extensions_Allowed
7833    External_Name_Casing
7834    Float_Representation
7835    Initialize_Scalars
7836    License
7837    Locking_Policy
7838    Long_Float
7839    No_Run_Time
7840    Normalize_Scalars
7841    Polling
7842    Propagate_Exceptions
7843    Queuing_Policy
7844    Ravenscar
7845    Restricted_Run_Time
7846    Restrictions
7847    Reviewable
7848    Source_File_Name
7849    Style_Checks
7850    Suppress
7851    Task_Dispatching_Policy
7852    Unsuppress
7853    Use_VADS_Size
7854    Warnings
7855    Validity_Checks
7856 @end smallexample
7857
7858 @menu
7859 * Handling of Configuration Pragmas::
7860 * The Configuration Pragmas Files::
7861 @end menu
7862
7863 @node Handling of Configuration Pragmas
7864 @section Handling of Configuration Pragmas
7865
7866 Configuration pragmas may either appear at the start of a compilation
7867 unit, in which case they apply only to that unit, or they may apply to
7868 all compilations performed in a given compilation environment.
7869
7870 GNAT also provides the @code{gnatchop} utility to provide an automatic
7871 way to handle configuration pragmas following the semantics for
7872 compilations (that is, files with multiple units), described in the RM.
7873 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7874 However, for most purposes, it will be more convenient to edit the
7875 @file{gnat.adc} file that contains configuration pragmas directly,
7876 as described in the following section.
7877
7878 @node The Configuration Pragmas Files
7879 @section The Configuration Pragmas Files
7880 @cindex @file{gnat.adc}
7881
7882 @noindent
7883 In GNAT a compilation environment is defined by the current
7884 directory at the time that a compile command is given. This current
7885 directory is searched for a file whose name is @file{gnat.adc}. If
7886 this file is present, it is expected to contain one or more
7887 configuration pragmas that will be applied to the current compilation.
7888 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7889 considered.
7890
7891 Configuration pragmas may be entered into the @file{gnat.adc} file
7892 either by running @code{gnatchop} on a source file that consists only of
7893 configuration pragmas, or more conveniently  by
7894 direct editing of the @file{gnat.adc} file, which is a standard format
7895 source file.
7896
7897 In addition to @file{gnat.adc}, one additional file containing configuration
7898 pragmas may be applied to the current compilation using the switch
7899 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
7900 contains only configuration pragmas. These configuration pragmas are
7901 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
7902 is present and switch @option{-gnatA} is not used).
7903
7904 It is allowed to specify several switches @option{-gnatec}, however only
7905 the last one on the command line will be taken into account.
7906
7907
7908 @node Handling Arbitrary File Naming Conventions Using gnatname
7909 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
7910 @cindex Arbitrary File Naming Conventions
7911
7912 @menu
7913 * Arbitrary File Naming Conventions::
7914 * Running gnatname::
7915 * Switches for gnatname::
7916 * Examples of gnatname Usage::
7917 @end menu
7918
7919 @node Arbitrary File Naming Conventions
7920 @section Arbitrary File Naming Conventions
7921
7922 @noindent
7923 The GNAT compiler must be able to know the source file name of a compilation unit.
7924 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
7925 @code{.adb} for bodies), the GNAT compiler does not need additional information.
7926
7927 @noindent
7928 When the source file names do not follow the standard GNAT default file naming
7929 conventions, the GNAT compiler must be given additional information through
7930 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
7931 When the non standard file naming conventions are well-defined, a small number of
7932 pragmas @code{Source_File_Name} specifying a naming pattern
7933 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
7934 if the file naming conventions are irregular or arbitrary, a number
7935 of pragma @code{Source_File_Name} for individual compilation units must be defined.
7936 To help maintain the correspondence between compilation unit names and
7937 source file names within the compiler,
7938 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
7939 set of files.
7940
7941 @node Running gnatname
7942 @section Running @code{gnatname}
7943
7944 @noindent
7945 The usual form of the @code{gnatname} command is
7946
7947 @smallexample
7948 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
7949 @end smallexample
7950
7951 @noindent
7952 All of the arguments are optional. If invoked without any argument,
7953 @code{gnatname} will display its usage.
7954
7955 @noindent
7956 When used with at least one naming pattern, @code{gnatname} will attempt to
7957 find all the compilation units in files that follow at least one of the
7958 naming patterns. To find these compilation units,
7959 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
7960 regular files.
7961
7962 @noindent
7963 One or several Naming Patterns may be given as arguments to @code{gnatname}.
7964 Each Naming Pattern is enclosed between double quotes.
7965 A Naming Pattern is a regular expression similar to the wildcard patterns
7966 used in file names by the Unix shells or the DOS prompt.
7967
7968 @noindent
7969 Examples of Naming Patterns are
7970
7971 @smallexample
7972    "*.[12].ada"
7973    "*.ad[sb]*"
7974    "body_*"    "spec_*"
7975 @end smallexample
7976
7977 @noindent
7978 For a more complete description of the syntax of Naming Patterns, see the second kind
7979 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
7980 expressions).
7981
7982 @noindent
7983 When invoked with no switches, @code{gnatname} will create a configuration
7984 pragmas file @file{gnat.adc} in the current working directory, with pragmas
7985 @code{Source_File_Name} for each file that contains a valid Ada unit.
7986
7987 @node Switches for gnatname
7988 @section Switches for @code{gnatname}
7989
7990 @noindent
7991 Switches for @code{gnatname} must precede any specified Naming Pattern.
7992
7993 @noindent
7994 You may specify any of the following switches to @code{gnatname}:
7995
7996 @table @code
7997
7998 @item -c@file{file}
7999 @cindex @code{-c} (@code{gnatname})
8000 Create a configuration pragmas file @file{file} (instead of the default
8001 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8002 @file{file}. @file{file} may include directory information. @file{file} must be
8003 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8004 specified, no switch @code{-P} may be specified (see below).
8005
8006 @item -d@file{dir}
8007 @cindex @code{-d} (@code{gnatname})
8008 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8009 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8010 the current working directory will not be searched for source files, unless it
8011 is explictly
8012 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8013 specified. If @file{dir} is a relative path, it is relative to the directory of
8014 the configuration pragmas file specified with switch @code{-c}, or to the directory
8015 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8016 nor switch @code{-P} are specified, it is relative to the current working
8017 directory. The directory
8018 specified with switch @code{-c} must exist and be readable.
8019
8020 @item -D@file{file}
8021 @cindex @code{-D} (@code{gnatname})
8022 Look for source files in all directories listed in text file @file{file}. There may be
8023 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8024 must be an existing, readable text file. Each non empty line in @file{file} must be
8025 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8026 @code{-d} as there are non empty lines in @file{file}.
8027
8028 @item -h
8029 @cindex @code{-h} (@code{gnatname})
8030 Output usage (help) information. The output is written to @file{stdout}.
8031
8032 @item -P@file{proj}
8033 @cindex @code{-P} (@code{gnatname})
8034 Create or update project file @file{proj}. There may be zero, one or more space
8035 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8036 @file{proj} must be writeable. There may be only one switch @code{-P}.
8037 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8038
8039 @item -v
8040 @cindex @code{-v} (@code{gnatname})
8041 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8042 name of the file written, the name of the directories to search and, for each file
8043 in those directories whose name matches at least one of the Naming Patterns, an
8044 indication of whether the file contains a unit, and if so the name of the unit.
8045
8046 @item -v -v
8047 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8048 in the searched directories whose name matches none of the Naming Patterns, an
8049 indication is given that there is no match.
8050
8051 @item -x@file{pattern}
8052 Excluded patterns. Using this switch, it is possible to exclude some files
8053 that would match the name patterns. For example,
8054 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8055 with the @file{.ada} extension, except those whose names end with
8056 @file{_nt.ada}.
8057
8058 @end table
8059
8060 @node Examples of gnatname Usage
8061 @section Examples of @code{gnatname} Usage
8062
8063 @smallexample
8064 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8065 @end smallexample
8066
8067 In this example, the directory @file{/home/me} must already exist and be
8068 writeable. In addition, the directory @file{/home/me/sources} (specified by
8069 @code{-d sources}) must exist and be readable. Note the optional spaces after
8070 @code{-c} and @code{-d}.
8071
8072 @smallexample
8073 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8074 @end smallexample
8075
8076 Note that several switches @code{-d} may be used, even in conjunction with one
8077 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8078 are used in this example.
8079
8080
8081 @c *****************************************
8082 @c * G N A T  P r o j e c t  M a n a g e r *
8083 @c *****************************************
8084 @node GNAT Project Manager
8085 @chapter GNAT Project Manager
8086
8087 @menu
8088 * Introduction::
8089 * Examples of Project Files::
8090 * Project File Syntax::
8091 * Objects and Sources in Project Files::
8092 * Importing Projects::
8093 * Project Extension::
8094 * External References in Project Files::
8095 * Packages in Project Files::
8096 * Variables from Imported Projects::
8097 * Naming Schemes::
8098 * Library Projects::
8099 * Switches Related to Project Files::
8100 * Tools Supporting Project Files::
8101 * An Extended Example::
8102 * Project File Complete Syntax::
8103 @end menu
8104
8105
8106 @c ****************
8107 @c * Introduction *
8108 @c ****************
8109
8110 @node Introduction
8111 @section Introduction
8112
8113 @noindent
8114 This chapter describes GNAT's @emph{Project Manager}, a facility that
8115 lets you configure various properties for a collection of source files.  In
8116 particular, you can specify:
8117 @itemize @bullet
8118 @item
8119 The directory or set of directories containing the source files, and/or the
8120 names of the specific source files themselves
8121 @item
8122 The directory in which the compiler's output
8123 (@file{ALI} files, object files, tree files) will be placed
8124 @item
8125 The directory in which the executable programs will be placed
8126 @item
8127 Switch settings for any of the project-enabled tools (@command{gnatmake},
8128 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8129 you can apply these settings either globally or to individual units
8130 @item
8131 The source files containing the main subprogram(s) to be built
8132 @item
8133 The source programming language(s) (currently Ada and/or C)
8134 @item
8135 Source file naming conventions; you can specify these either globally or for
8136 individual units
8137 @end itemize
8138
8139 @menu
8140 * Project Files::
8141 @end menu
8142
8143 @node Project Files
8144 @subsection Project Files
8145
8146 @noindent
8147 A @dfn{project} is a specific set of values for these properties.  You can
8148 define a project's settings in a @dfn{project file}, a text file with an
8149 Ada-like syntax; a property value is either a string or a list of strings.
8150 Properties that are not explicitly set receive default values.  A project
8151 file may interrogate the values of @dfn{external variables} (user-defined
8152 command-line switches or environment variables), and it may specify property
8153 settings conditionally, based on the value of such variables.
8154
8155 In simple cases, a project's source files depend only on other source files
8156 in the same project, or on the predefined libraries.  ("Dependence" is in
8157 the technical sense; for example, one Ada unit "with"ing another.)  However,
8158 the Project Manager also allows much more sophisticated arrangements,
8159 with the source files in one project depending on source files in other
8160 projects:
8161 @itemize @bullet
8162 @item
8163 One project can @emph{import} other projects containing needed source files.
8164 @item
8165 You can organize GNAT projects in a hierarchy: a @emph{child} project
8166 can extend a @emph{parent} project, inheriting the parent's source files and
8167 optionally overriding any of them with alternative versions
8168 @end itemize
8169
8170 @noindent
8171 More generally, the Project Manager lets you structure large development
8172 efforts into hierarchical subsystems, with build decisions deferred to the
8173 subsystem level and thus different compilation environments (switch settings)
8174 used for different subsystems.
8175
8176 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8177 switch to @command{gnatmake} or to the @command{gnat} front driver.
8178 If you want to define (on the command line) an external variable that is
8179 queried by the project file, additionally use the
8180 @option{-X@emph{vbl}=@emph{value}} switch.
8181 The Project Manager parses and interprets the project file, and drives the
8182 invoked tool based on the project settings.
8183
8184 The Project Manager supports a wide range of development strategies,
8185 for systems of all sizes.  Some typical practices that are easily handled:
8186 @itemize @bullet
8187 @item
8188 Using a common set of source files, but generating object files in different
8189 directories via different switch settings
8190 @item
8191 Using a mostly-shared set of source files, but with different versions of
8192 some unit or units
8193 @end itemize
8194
8195 @noindent
8196 The destination of an executable can be controlled inside a project file
8197 using the @option{-o} switch. In the absence of such a switch either inside
8198 the project file or on the command line, any executable files generated by
8199 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8200 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8201 in the object directory of the project.
8202
8203 You can use project files to achieve some of the effects of a source
8204 versioning system (for example, defining separate projects for
8205 the different sets of sources that comprise different releases) but the
8206 Project Manager is independent of any source configuration management tools
8207 that might be used by the developers.
8208
8209 The next section introduces the main features of GNAT's project facility
8210 through a sequence of examples; subsequent sections will present the syntax
8211 and semantics in more detail.
8212
8213
8214 @c *****************************
8215 @c * Examples of Project Files *
8216 @c *****************************
8217
8218 @node Examples of Project Files
8219 @section Examples of Project Files
8220 @noindent
8221 This section illustrates some of the typical uses of project files and
8222 explains their basic structure and behavior.
8223
8224 @menu
8225 * Common Sources with Different Switches and Different Output Directories::
8226 * Using External Variables::
8227 * Importing Other Projects::
8228 * Extending a Project::
8229 @end menu
8230
8231 @node Common Sources with Different Switches and Different Output Directories
8232 @subsection Common Sources with Different Switches and Different Output Directories
8233
8234 @menu
8235 * Source Files::
8236 * Specifying the Object Directory::
8237 * Specifying the Exec Directory::
8238 * Project File Packages::
8239 * Specifying Switch Settings::
8240 * Main Subprograms::
8241 * Source File Naming Conventions::
8242 * Source Language(s)::
8243 @end menu
8244
8245 @noindent
8246 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8247 @file{proc.adb} are in the @file{/common} directory.  The file
8248 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8249 package @code{Pack}.  We want to compile these source files under two sets
8250 of switches:
8251 @itemize @bullet
8252 @item
8253 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8254 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8255 compiler; the compiler's output is to appear in @file{/common/debug}
8256 @item
8257 When preparing a release version, we want to pass the @option{-O2} switch to
8258 the compiler; the compiler's output is to appear in @file{/common/release}
8259 @end itemize
8260
8261 @noindent
8262 The GNAT project files shown below, respectively @file{debug.gpr} and
8263 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8264
8265 Diagrammatically:
8266 @smallexample
8267 @group
8268 /common
8269   debug.gpr
8270   release.gpr
8271   pack.ads
8272   pack.adb
8273   proc.adb
8274 @end group
8275 @group
8276 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8277   proc.ali, proc.o
8278   pack.ali, pack.o
8279 @end group
8280 @group
8281 /common/release @{-O2@}
8282   proc.ali, proc.o
8283   pack.ali, pack.o
8284 @end group
8285 @end smallexample
8286 Here are the project files:
8287 @smallexample
8288 @group
8289 project Debug is
8290   for Object_Dir use "debug";
8291   for Main use ("proc");
8292
8293   package Builder is
8294     for Default_Switches ("Ada") use ("-g");
8295   end Builder;
8296 @end group
8297
8298 @group
8299   package Compiler is
8300     for Default_Switches ("Ada")
8301        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8302   end Compiler;
8303 end Debug;
8304 @end group
8305 @end smallexample
8306
8307 @smallexample
8308 @group
8309 project Release is
8310   for Object_Dir use "release";
8311   for Exec_Dir use ".";
8312   for Main use ("proc");
8313
8314   package Compiler is
8315     for Default_Switches ("Ada") use ("-O2");
8316   end Compiler;
8317 end Release;
8318 @end group
8319 @end smallexample
8320
8321 @noindent
8322 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8323 insensitive), and analogously the project defined by @file{release.gpr} is
8324 @code{"Release"}.  For consistency the file should have the same name as the
8325 project, and the project file's extension should be @code{"gpr"}. These
8326 conventions are not required, but a warning is issued if they are not followed.
8327
8328 If the current directory is @file{/temp}, then the command
8329 @smallexample
8330 gnatmake -P/common/debug.gpr
8331 @end smallexample
8332
8333 @noindent
8334 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8335 executable also in @file{/common/debug}, using the switch settings defined in
8336 the project file.
8337
8338 Likewise, the command
8339 @smallexample
8340 gnatmake -P/common/release.gpr
8341 @end smallexample
8342
8343 @noindent
8344 generates object and ALI files in @file{/common/release}, and the @code{proc}
8345 executable in @file{/common}, using the switch settings from the project file.
8346
8347 @node Source Files
8348 @unnumberedsubsubsec Source Files
8349
8350 @noindent
8351 If a project file does not explicitly specify a set of source directories or
8352 a set of source files, then by default the project's source files are the
8353 Ada source files in the project file directory.  Thus @file{pack.ads},
8354 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8355
8356 @node Specifying the Object Directory
8357 @unnumberedsubsubsec Specifying the Object Directory
8358
8359 @noindent
8360 Several project properties are modeled by Ada-style @emph{attributes};
8361 you define the property by supplying the equivalent of an Ada attribute
8362 definition clause in the project file.
8363 A project's object directory is such a property; the corresponding
8364 attribute is @code{Object_Dir}, and its value is a string expression.  A
8365 directory may be specified either as absolute or as relative; in the latter
8366 case, it is relative to the project file directory.  Thus the compiler's
8367 output is directed to @file{/common/debug} (for the @code{Debug} project)
8368 and to @file{/common/release} (for the @code{Release} project).  If
8369 @code{Object_Dir} is not specified, then the default is the project file
8370 directory.
8371
8372 @node Specifying the Exec Directory
8373 @unnumberedsubsubsec Specifying the Exec Directory
8374
8375 @noindent
8376 A project's exec directory is another property; the corresponding
8377 attribute is @code{Exec_Dir}, and its value is also a string expression,
8378 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8379 then the default is the object directory (which may also be the project file
8380 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8381 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8382 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8383 project.
8384
8385 @node Project File Packages
8386 @unnumberedsubsubsec Project File Packages
8387
8388 @noindent
8389 A GNAT tool integrated with the Project Manager is modeled by a
8390 corresponding package in the project file.
8391 The @code{Debug} project defines the packages @code{Builder}
8392 (for @command{gnatmake}) and @code{Compiler};
8393 the @code{Release} project defines only the @code{Compiler} package.
8394
8395 The Ada package syntax is not to be taken literally.  Although packages in
8396 project files bear a surface resemblance to packages in Ada source code, the
8397 notation is simply a way to convey a grouping of properties for a named
8398 entity.  Indeed, the package names permitted in project files are restricted
8399 to a predefined set, corresponding to the project-aware tools, and the contents
8400 of packages are limited to a small set of constructs.
8401 The packages in the example above contain attribute definitions.
8402
8403
8404 @node Specifying Switch Settings
8405 @unnumberedsubsubsec Specifying Switch Settings
8406
8407 @noindent
8408 Switch settings for a project-aware tool can be specified through attributes
8409 in the package corresponding to the tool.
8410 The example above illustrates one of the relevant attributes,
8411 @code{Default_Switches}, defined in the packages in both project files.
8412 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8413 known as an @emph{associative array}.  When you define this attribute, you must
8414 supply an "index" (a literal string), and the effect of the attribute
8415 definition is to set the value of the "array" at the specified "index".
8416 For the @code{Default_Switches} attribute, the index is a programming
8417 language (in our case, Ada) , and the value specified (after @code{use})
8418 must be a list of string expressions.
8419
8420 The attributes permitted in project files are restricted to a predefined set.
8421 Some may appear at project level, others in packages.
8422 For any attribute that is an associate array, the index must always be a
8423 literal string, but the restrictions on this string (e.g., a file name or a
8424 language name) depend on the individual attribute.
8425 Also depending on the attribute, its specified value will need to be either a
8426 string or a string list.
8427
8428 In the @code{Debug} project, we set the switches for two tools,
8429 @command{gnatmake} and the compiler, and thus we include corresponding
8430 packages, with each package defining the @code{Default_Switches} attribute
8431 with index @code{"Ada"}.
8432 Note that the package corresponding to
8433 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
8434 similar, but with just the @code{Compiler} package.
8435
8436 In project @code{Debug} above the switches starting with @option{-gnat} that
8437 are specified in package @code{Compiler} could have been placed in package
8438 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8439 compiler.
8440
8441 @node Main Subprograms
8442 @unnumberedsubsubsec Main Subprograms
8443
8444 @noindent
8445 One of the properties of a project is its list of main subprograms (actually
8446 a list of names of source files containing main subprograms, with the file
8447 extension optional.  This property is captured in the @code{Main} attribute,
8448 whose value is a list of strings.  If a project defines the @code{Main}
8449 attribute, then you do not need to identify the main subprogram(s) when
8450 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8451
8452 @node Source File Naming Conventions
8453 @unnumberedsubsubsec Source File Naming Conventions
8454
8455 @noindent
8456 Since the project files do not specify any source file naming conventions,
8457 the GNAT defaults are used.  The mechanism for defining source file naming
8458 conventions -- a package named @code{Naming} -- will be described below
8459 (@pxref{Naming Schemes}).
8460
8461 @node Source Language(s)
8462 @unnumberedsubsubsec Source Language(s)
8463
8464 @noindent
8465 Since the project files do not specify a @code{Languages} attribute, by
8466 default the GNAT tools assume that the language of the project file is Ada.
8467 More generally, a project can comprise source files
8468 in Ada, C, and/or other languages.
8469
8470 @node Using External Variables
8471 @subsection Using External Variables
8472
8473 @noindent
8474 Instead of supplying different project files for debug and release, we can
8475 define a single project file that queries an external variable (set either
8476 on the command line or via an environment variable) in order to
8477 conditionally define the appropriate settings.  Again, assume that the
8478 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8479 located in directory @file{/common}.  The following project file,
8480 @file{build.gpr}, queries the external variable named @code{STYLE} and
8481 defines an object directory and switch settings based on whether the value
8482 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8483 @code{"deb"}.
8484
8485 @smallexample
8486 @group
8487 project Build is
8488   for Main use ("proc");
8489
8490   type Style_Type is ("deb", "rel");
8491   Style : Style_Type := external ("STYLE", "deb");
8492
8493   case Style is
8494     when "deb" =>
8495       for Object_Dir use "debug";
8496
8497     when "rel" =>
8498       for Object_Dir use "release";
8499       for Exec_Dir use ".";
8500   end case;
8501 @end group
8502
8503 @group
8504   package Builder is
8505
8506     case Style is
8507       when "deb" =>
8508         for Default_Switches ("Ada") use ("-g");
8509     end case;
8510
8511   end Builder;
8512 @end group
8513
8514 @group
8515   package Compiler is
8516
8517     case Style is
8518       when "deb" =>
8519         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8520
8521       when "rel" =>
8522         for Default_Switches ("Ada") use ("-O2");
8523     end case;
8524
8525   end Compiler;
8526
8527 end Build;
8528 @end group
8529 @end smallexample
8530
8531 @noindent
8532 @code{Style_Type} is an example of a @emph{string type}, which is the project
8533 file analog of an Ada enumeration type but containing string literals rather
8534 than identifiers.  @code{Style} is declared as a variable of this type.
8535
8536 The form @code{external("STYLE", "deb")} is known as an
8537 @emph{external reference}; its first argument is the name of an
8538 @emph{external variable}, and the second argument is a default value to be
8539 used if the external variable doesn't exist.  You can define an external
8540 variable on the command line via the @option{-X} switch, or you can use an
8541 environment variable as an external variable.
8542
8543 Each @code{case} construct is expanded by the Project Manager based on the
8544 value of @code{Style}. Thus the command
8545 @smallexample
8546 gnatmake -P/common/build.gpr -XSTYLE=deb
8547 @end smallexample
8548
8549 @noindent
8550 is equivalent to the @command{gnatmake} invocation using the project file
8551 @file{debug.gpr} in the earlier example.  So is the command
8552 @smallexample
8553 gnatmake -P/common/build.gpr
8554 @end smallexample
8555
8556 @noindent
8557 since @code{"deb"} is the default for @code{STYLE}.
8558
8559 Analogously,
8560 @smallexample
8561 gnatmake -P/common/build.gpr -XSTYLE=rel
8562 @end smallexample
8563
8564 @noindent
8565 is equivalent to the @command{gnatmake} invocation using the project file
8566 @file{release.gpr} in the earlier example.
8567
8568
8569 @node Importing Other Projects
8570 @subsection Importing Other Projects
8571
8572 @noindent
8573 A compilation unit in a source file in one project may depend on compilation
8574 units in source files in other projects.  To obtain this behavior, the
8575 dependent project must @emph{import} the projects containing the needed source
8576 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
8577 but the "with"ed entities are strings denoting project files.
8578
8579 As an example, suppose that the two projects @code{GUI_Proj} and
8580 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8581 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8582 respectively.  Assume that the source files for @code{GUI_Proj} are
8583 @file{gui.ads} and @file{gui.adb}, and that the source files for
8584 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8585 files located in its respective project file directory.  Diagrammatically:
8586
8587 @smallexample
8588 @group
8589 /gui
8590   gui_proj.gpr
8591   gui.ads
8592   gui.adb
8593 @end group
8594
8595 @group
8596 /comm
8597   comm_proj.gpr
8598   comm.ads
8599   comm.adb
8600 @end group
8601 @end smallexample
8602
8603 @noindent
8604 We want to develop an application in directory @file{/app} that "with"s the
8605 packages @code{GUI} and @code{Comm}, using the properties of the
8606 corresponding project files (e.g. the switch settings and object directory).
8607 Skeletal code for a main procedure might be something like the following:
8608
8609 @smallexample
8610 @group
8611 with GUI, Comm;
8612 procedure App_Main is
8613    ...
8614 begin
8615    ...
8616 end App_Main;
8617 @end group
8618 @end smallexample
8619
8620 @noindent
8621 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8622 effect:
8623
8624 @smallexample
8625 @group
8626 with "/gui/gui_proj", "/comm/comm_proj";
8627 project App_Proj is
8628    for Main use ("app_main");
8629 end App_Proj;
8630 @end group
8631 @end smallexample
8632
8633 @noindent
8634 Building an executable is achieved through the command:
8635 @smallexample
8636 gnatmake -P/app/app_proj
8637 @end smallexample
8638 @noindent
8639 which will generate the @code{app_main} executable in the directory where
8640 @file{app_proj.gpr} resides.
8641
8642 If an imported project file uses the standard extension (@code{gpr}) then
8643 (as illustrated above) the @code{with} clause can omit the extension.
8644
8645 Our example specified an absolute path for each imported project file.
8646 Alternatively, you can omit the directory if either
8647 @itemize @bullet
8648 @item
8649 The imported project file is in the same directory as the importing project
8650 file, or
8651 @item
8652 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8653 includes the directory containing the needed project file.
8654 @end itemize
8655
8656 @noindent
8657 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8658 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8659 follows:
8660
8661 @smallexample
8662 @group
8663 with "gui_proj", "comm_proj";
8664 project App_Proj is
8665    for Main use ("app_main");
8666 end App_Proj;
8667 @end group
8668 @end smallexample
8669
8670 @noindent
8671 Importing other projects raises the possibility of ambiguities.  For
8672 example, the same unit might be present in different imported projects, or
8673 it might be present in both the importing project and an imported project.
8674 Both of these conditions are errors.  Note that in the current version of
8675 the Project Manager, it is illegal to have an ambiguous unit even if the
8676 unit is never referenced by the importing project.  This restriction may be
8677 relaxed in a future release.
8678
8679 @node Extending a Project
8680 @subsection Extending a Project
8681
8682 @noindent
8683 A common situation in large software systems is to have multiple
8684 implementations for a common interface; in Ada terms, multiple versions of a
8685 package body for the same specification.  For example, one implementation
8686 might be safe for use in tasking programs, while another might only be used
8687 in sequential applications.  This can be modeled in GNAT using the concept
8688 of @emph{project extension}.  If one project (the "child") @emph{extends}
8689 another project (the "parent") then by default all source files of the
8690 parent project are inherited by the child, but the child project can
8691 override any of the parent's source files with new versions, and can also
8692 add new files.  This facility is the project analog of extension in
8693 Object-Oriented Programming.  Project hierarchies are permitted (a child
8694 project may be the parent of yet another project), and a project that
8695 inherits one project can also import other projects.
8696
8697 As an example, suppose that directory @file{/seq} contains the project file
8698 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8699 and @file{proc.adb}:
8700
8701 @smallexample
8702 @group
8703 /seq
8704   pack.ads
8705   pack.adb
8706   proc.adb
8707   seq_proj.gpr
8708 @end group
8709 @end smallexample
8710
8711 @noindent
8712 Note that the project file can simply be empty (that is, no attribute or
8713 package is defined):
8714
8715 @smallexample
8716 @group
8717 project Seq_Proj is
8718 end Seq_Proj;
8719 @end group
8720 @end smallexample
8721
8722 @noindent
8723 implying that its source files are all the Ada source files in the project
8724 directory.
8725
8726 Suppose we want to supply an alternate version of @file{pack.adb}, in
8727 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8728 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
8729 inherits @code{Seq_Proj}:
8730
8731 @smallexample
8732 @group
8733 /tasking
8734   pack.adb
8735   tasking_proj.gpr
8736 @end group
8737
8738 @group
8739 project Tasking_Proj extends "/seq/seq_proj" is
8740 end Tasking_Proj;
8741 @end group
8742 @end smallexample
8743
8744 @noindent
8745 The version of @file{pack.adb} used in a build depends on which project file
8746 is specified.
8747
8748 Note that we could have designed this using project import rather than
8749 project inheritance; a @code{base} project would contain the sources for
8750 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8751 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8752 import @code{base} and add a different version of @file{pack.adb}.  The
8753 choice depends on whether other sources in the original project need to be
8754 overridden.  If they do, then project extension is necessary, otherwise,
8755 importing is sufficient.
8756
8757
8758 @c ***********************
8759 @c * Project File Syntax *
8760 @c ***********************
8761
8762 @node Project File Syntax
8763 @section Project File Syntax
8764
8765 @menu
8766 * Basic Syntax::
8767 * Packages::
8768 * Expressions::
8769 * String Types::
8770 * Variables::
8771 * Attributes::
8772 * Associative Array Attributes::
8773 * case Constructions::
8774 @end menu
8775
8776 @noindent
8777 This section describes the structure of project files.
8778
8779 A project may be an @emph{independent project}, entirely defined by a single
8780 project file. Any Ada source file in an independent project depends only
8781 on the predefined library and other Ada source files in the same project.
8782
8783 @noindent
8784 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8785 @itemize @bullet
8786 @item It may import any number of projects
8787 @item It may extend at most one other project
8788 @end itemize
8789
8790 @noindent
8791 The dependence relation is a directed acyclic graph (the subgraph reflecting
8792 the "extends" relation is a tree).
8793
8794 A project's @dfn{immediate sources} are the source files directly defined by
8795 that project, either implicitly by residing in the project file's directory,
8796 or explicitly through any of the source-related attributes described below.
8797 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8798 of @var{proj} together with the immediate sources (unless overridden) of any
8799 project on which @var{proj} depends (either directly or indirectly).
8800
8801 @node Basic Syntax
8802 @subsection Basic Syntax
8803
8804 @noindent
8805 As seen in the earlier examples, project files have an Ada-like syntax.
8806 The minimal project file is:
8807 @smallexample
8808 @group
8809 project Empty is
8810
8811 end Empty;
8812 @end group
8813 @end smallexample
8814
8815 @noindent
8816 The identifier @code{Empty} is the name of the project.
8817 This project name must be present after the reserved
8818 word @code{end} at the end of the project file, followed by a semi-colon.
8819
8820 Any name in a project file, such as the project name or a variable name,
8821 has the same syntax as an Ada identifier.
8822
8823 The reserved words of project files are the Ada reserved words plus
8824 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
8825 reserved words currently used in project file syntax are:
8826
8827 @itemize @bullet
8828 @item
8829 @code{case}
8830 @item
8831 @code{end}
8832 @item
8833 @code{for}
8834 @item
8835 @code{is}
8836 @item
8837 @code{others}
8838 @item
8839 @code{package}
8840 @item
8841 @code{renames}
8842 @item
8843 @code{type}
8844 @item
8845 @code{use}
8846 @item
8847 @code{when}
8848 @item
8849 @code{with}
8850 @end itemize
8851
8852 @noindent
8853 Comments in project files have the same syntax as in Ada, two consecutives
8854 hyphens through the end of the line.
8855
8856 @node Packages
8857 @subsection Packages
8858
8859 @noindent
8860 A project file may contain @emph{packages}. The name of a package must be one
8861 of the identifiers (case insensitive) from a predefined list, and a package
8862 with a given name may only appear once in a project file. The predefined list
8863 includes the following packages:
8864
8865 @itemize @bullet
8866 @item
8867 @code{Naming}
8868 @item
8869 @code{Builder}
8870 @item
8871 @code{Compiler}
8872 @item
8873 @code{Binder}
8874 @item
8875 @code{Linker}
8876 @item
8877 @code{Finder}
8878 @item
8879 @code{Cross_Reference}
8880 @item
8881 @code{gnatls}
8882 @end itemize
8883
8884 @noindent
8885 (The complete list of the package names and their attributes can be found
8886 in file @file{prj-attr.adb}).
8887
8888 @noindent
8889 In its simplest form, a package may be empty:
8890
8891 @smallexample
8892 @group
8893 project Simple is
8894   package Builder is
8895   end Builder;
8896 end Simple;
8897 @end group
8898 @end smallexample
8899
8900 @noindent
8901 A package may contain @emph{attribute declarations},
8902 @emph{variable declarations} and @emph{case constructions}, as will be
8903 described below.
8904
8905 When there is ambiguity between a project name and a package name,
8906 the name always designates the project. To avoid possible confusion, it is
8907 always a good idea to avoid naming a project with one of the
8908 names allowed for packages or any name that starts with @code{gnat}.
8909
8910
8911 @node Expressions
8912 @subsection Expressions
8913
8914 @noindent
8915 An @emph{expression} is either a @emph{string expression} or a
8916 @emph{string list expression}.
8917
8918 A @emph{string expression} is either a @emph{simple string expression} or a
8919 @emph{compound string expression}.
8920
8921 A @emph{simple string expression} is one of the following:
8922 @itemize @bullet
8923 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
8924 @item A string-valued variable reference (see @ref{Variables})
8925 @item A string-valued attribute reference (see @ref{Attributes})
8926 @item An external reference (see @ref{External References in Project Files})
8927 @end itemize
8928
8929 @noindent
8930 A @emph{compound string expression} is a concatenation of string expressions,
8931 using @code{"&"}
8932 @smallexample
8933        Path & "/" & File_Name & ".ads"
8934 @end smallexample
8935
8936 @noindent
8937 A @emph{string list expression} is either a
8938 @emph{simple string list expression} or a
8939 @emph{compound string list expression}.
8940
8941 A @emph{simple string list expression} is one of the following:
8942 @itemize @bullet
8943 @item A parenthesized list of zero or more string expressions, separated by commas
8944 @smallexample
8945    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
8946    Empty_List := ();
8947 @end smallexample
8948 @item A string list-valued variable reference
8949 @item A string list-valued attribute reference
8950 @end itemize
8951
8952 @noindent
8953 A @emph{compound string list expression} is the concatenation (using
8954 @code{"&"}) of a simple string list expression and an expression.  Note that
8955 each term in a compound string list expression, except the first, may be
8956 either a string expression or a string list expression.
8957
8958 @smallexample
8959 @group
8960    File_Name_List := () & File_Name; --  One string in this list
8961    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
8962    --  Two strings
8963    Big_List := File_Name_List & Extended_File_Name_List;
8964    --  Concatenation of two string lists: three strings
8965    Illegal_List := "gnat.adc" & Extended_File_Name_List;
8966    --  Illegal: must start with a string list
8967 @end group
8968 @end smallexample
8969
8970
8971 @node String Types
8972 @subsection String Types
8973
8974 @noindent
8975 The value of a variable may be restricted to a list of string literals.
8976 The restricted list of string literals is given in a
8977 @emph{string type declaration}.
8978
8979 Here is an example of a string type declaration:
8980
8981 @smallexample
8982    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
8983 @end smallexample
8984
8985 @noindent
8986 Variables of a string type are called @emph{typed variables}; all other
8987 variables are called @emph{untyped variables}. Typed variables are
8988 particularly useful in @code{case} constructions
8989 (see @ref{case Constructions}).
8990
8991 A string type declaration starts with the reserved word @code{type}, followed
8992 by the name of the string type (case-insensitive), followed by the reserved
8993 word @code{is}, followed by a parenthesized list of one or more string literals
8994 separated by commas, followed by a semicolon.
8995
8996 The string literals in the list are case sensitive and must all be different.
8997 They may include any graphic characters allowed in Ada, including spaces.
8998
8999 A string type may only be declared at the project level, not inside a package.
9000
9001 A string type may be referenced by its name if it has been declared in the same
9002 project file, or by its project name, followed by a dot,
9003 followed by the string type name.
9004
9005
9006 @node Variables
9007 @subsection Variables
9008
9009 @noindent
9010 A variable may be declared at the project file level, or in a package.
9011 Here are some examples of variable declarations:
9012
9013 @smallexample
9014 @group
9015    This_OS : OS := external ("OS"); --  a typed variable declaration
9016    That_OS := "Linux";              --  an untyped variable declaration
9017 @end group
9018 @end smallexample
9019
9020 @noindent
9021 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9022 followed by the name of a string type, followed by @code{:=}, followed by
9023 a simple string expression.
9024
9025 An @emph{untyped variable declaration} includes the variable name,
9026 followed by @code{:=}, followed by an expression.  Note that, despite the
9027 terminology, this form of "declaration" resembles more an assignment
9028 than a declaration in Ada.  It is a declaration in several senses:
9029 @itemize @bullet
9030 @item
9031 The variable name does not need to be defined previously
9032 @item
9033 The declaration establishes the @emph{kind} (string versus string list) of the
9034 variable, and later declarations of the same variable need to be consistent
9035 with this
9036 @end itemize
9037
9038 @noindent
9039 A string variable declaration (typed or untyped) declares a variable
9040 whose value is a string. This variable may be used as a string expression.
9041 @smallexample
9042    File_Name       := "readme.txt";
9043    Saved_File_Name := File_Name & ".saved";
9044 @end smallexample
9045
9046 @noindent
9047 A string list variable declaration declares a variable whose value is a list
9048 of strings. The list may contain any number (zero or more) of strings.
9049
9050 @smallexample
9051    Empty_List := ();
9052    List_With_One_Element := ("-gnaty");
9053    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9054    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9055                  "pack2.ada", "util_.ada", "util.ada");
9056 @end smallexample
9057
9058 @noindent
9059 The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable.
9060
9061 The same untyped variable may be declared several times.
9062 In this case, the new value replaces the old one,
9063 and any subsequent reference to the variable uses the new value.
9064 However, as noted above, if a variable has been declared as a string, all subsequent
9065 declarations must give it a string value. Similarly, if a variable has
9066 been declared as a string list, all subsequent declarations
9067 must give it a string list value.
9068
9069 A @emph{variable reference} may take several forms:
9070
9071 @itemize @bullet
9072 @item The simple variable name, for a variable in the current package (if any) or in the current project
9073 @item A context name, followed by a dot, followed by the variable name.
9074 @end itemize
9075
9076 @noindent
9077 A @emph{context} may be one of the following:
9078
9079 @itemize @bullet
9080 @item The name of an existing package in the current project
9081 @item The name of an imported project of the current project
9082 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9083 @item An imported/parent project name, followed by a dot, followed by a package name
9084 @end itemize
9085
9086 @noindent
9087 A variable reference may be used in an expression.
9088
9089
9090 @node Attributes
9091 @subsection Attributes
9092
9093 @noindent
9094 A project (and its packages) may have @emph{attributes} that define the project's properties.
9095 Some attributes have values that are strings;
9096 others have values that are string lists.
9097
9098 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9099 (see @ref{Associative Array Attributes}).
9100
9101 The names of the attributes are restricted; there is a list of project
9102 attributes, and a list of package attributes for each package.
9103 The names are not case sensitive.
9104
9105 The project attributes are as follows (all are simple attributes):
9106
9107 @multitable @columnfractions .4 .3
9108 @item @emph{Attribute Name}
9109 @tab @emph{Value}
9110 @item @code{Source_Files}
9111 @tab string list
9112 @item @code{Source_Dirs}
9113 @tab string list
9114 @item @code{Source_List_File}
9115 @tab string
9116 @item @code{Object_Dir}
9117 @tab string
9118 @item @code{Exec_Dir}
9119 @tab string
9120 @item @code{Main}
9121 @tab string list
9122 @item @code{Languages}
9123 @tab string list
9124 @item @code{Library_Dir}
9125 @tab string
9126 @item @code{Library_Name}
9127 @tab string
9128 @item @code{Library_Kind}
9129 @tab string
9130 @item @code{Library_Elaboration}
9131 @tab string
9132 @item @code{Library_Version}
9133 @tab string
9134 @end multitable
9135
9136 @noindent
9137 The attributes for package @code{Naming} are as follows
9138 (see @ref{Naming Schemes}):
9139
9140 @multitable @columnfractions .4 .2 .2 .2
9141 @item Attribute Name @tab Category @tab Index @tab Value
9142 @item @code{Specification_Suffix}
9143 @tab associative array
9144 @tab language name
9145 @tab string
9146 @item @code{Implementation_Suffix}
9147 @tab associative array
9148 @tab language name
9149 @tab string
9150 @item @code{Separate_Suffix}
9151 @tab simple attribute
9152 @tab n/a
9153 @tab string
9154 @item @code{Casing}
9155 @tab simple attribute
9156 @tab n/a
9157 @tab string
9158 @item @code{Dot_Replacement}
9159 @tab simple attribute
9160 @tab n/a
9161 @tab string
9162 @item @code{Specification}
9163 @tab associative array
9164 @tab Ada unit name
9165 @tab string
9166 @item @code{Implementation}
9167 @tab associative array
9168 @tab Ada unit name
9169 @tab string
9170 @item @code{Specification_Exceptions}
9171 @tab associative array
9172 @tab language name
9173 @tab string list
9174 @item @code{Implementation_Exceptions}
9175 @tab associative array
9176 @tab language name
9177 @tab string list
9178 @end multitable
9179
9180 @noindent
9181 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9182 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9183 are as follows (see @ref{Switches and Project Files}).
9184
9185 @multitable @columnfractions .4 .2 .2 .2
9186 @item Attribute Name @tab Category @tab Index @tab Value
9187 @item @code{Default_Switches}
9188 @tab associative array
9189 @tab language name
9190 @tab string list
9191 @item @code{Switches}
9192 @tab associative array
9193 @tab file name
9194 @tab string list
9195 @end multitable
9196
9197 @noindent
9198 In addition, package @code{Builder} has a single string attribute
9199 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9200 string attribute @code{Global_Configuration_Pragmas}.
9201
9202 @noindent
9203 The attribute for package @code{Glide} are not documented: they are for
9204 internal use only.
9205
9206 @noindent
9207 Each simple attribute has a default value: the empty string (for string-valued
9208 attributes) and the empty list (for string list-valued attributes).
9209
9210 Similar to variable declarations, an attribute declaration defines a new value
9211 for an attribute.
9212
9213 Examples of simple attribute declarations:
9214
9215 @smallexample
9216    for Object_Dir use "objects";
9217    for Source_Dirs use ("units", "test/drivers");
9218 @end smallexample
9219
9220 @noindent
9221 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9222 followed by the name of the attribute, followed by the reserved word
9223 @code{use}, followed by an expression (whose kind depends on the attribute),
9224 followed by a semicolon.
9225
9226 Attributes may be referenced in expressions.
9227 The general form for such a reference is @code{<entity>'<attribute>}:
9228 the entity for which the attribute is defined,
9229 followed by an apostrophe, followed by the name of the attribute.
9230 For associative array attributes, a litteral string between parentheses
9231 need to be supplied as index.
9232
9233 Examples are:
9234
9235 @smallexample
9236   project'Object_Dir
9237   Naming'Dot_Replacement
9238   Imported_Project'Source_Dirs
9239   Imported_Project.Naming'Casing
9240   Builder'Default_Switches("Ada")
9241 @end smallexample
9242
9243 @noindent
9244 The entity may be:
9245 @itemize @bullet
9246 @item @code{project} for an attribute of the current project
9247 @item The name of an existing package of the current project
9248 @item The name of an imported project
9249 @item The name of a parent project (extended by the current project)
9250 @item An imported/parent project name, followed by a dot,
9251       followed by a package name
9252 @end itemize
9253
9254 @noindent
9255 Example:
9256 @smallexample
9257 @group
9258    project Prj is
9259      for Source_Dirs use project'Source_Dirs & "units";
9260      for Source_Dirs use project'Source_Dirs & "test/drivers"
9261    end Prj;
9262 @end group
9263 @end smallexample
9264
9265 @noindent
9266 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9267 has the default value: an empty string list. After this declaration,
9268 @code{Source_Dirs} is a string list of one element: "units".
9269 After the second attribute declaration @code{Source_Dirs} is a string list of
9270 two elements: "units" and "test/drivers".
9271
9272 Note: this example is for illustration only. In practice,
9273 the project file would contain only one attribute declaration:
9274
9275 @smallexample
9276    for Source_Dirs use ("units", "test/drivers");
9277 @end smallexample
9278
9279
9280 @node Associative Array Attributes
9281 @subsection Associative Array Attributes
9282
9283 @noindent
9284 Some attributes are defined as @emph{associative arrays}. An associative
9285 array may be regarded as a function that takes a string as a parameter
9286 and delivers a string or string list value as its result.
9287
9288 Here are some examples of associative array attribute declarations:
9289
9290 @smallexample
9291    for Implementation ("main") use "Main.ada";
9292    for Switches ("main.ada") use ("-v", "-gnatv");
9293    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9294 @end smallexample
9295
9296 @noindent
9297 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9298 attribute, replacing the previous setting.
9299
9300
9301 @node case Constructions
9302 @subsection @code{case} Constructions
9303
9304 @noindent
9305 A @code{case} construction is used in a project file to effect conditional
9306 behavior.
9307 Here is a typical example:
9308
9309 @smallexample
9310 @group
9311 project MyProj is
9312    type OS_Type is ("Linux", "Unix", "NT", "VMS");
9313
9314    OS : OS_Type := external ("OS", "Linux");
9315 @end group
9316
9317 @group
9318    package Compiler is
9319      case OS is
9320        when "Linux" | "Unix" =>
9321          for Default_Switches ("Ada") use ("-gnath");
9322        when "NT" =>
9323          for Default_Switches ("Ada") use ("-gnatP");
9324        when others =>
9325      end case;
9326    end Compiler;
9327 end MyProj;
9328 @end group
9329 @end smallexample
9330
9331 @noindent
9332 The syntax of a @code{case} construction is based on the Ada case statement
9333 (although there is no @code{null} construction for empty alternatives).
9334
9335 Following the reserved word @code{case} there is the case variable (a typed
9336 string variable), the reserved word @code{is}, and then a sequence of one or
9337 more alternatives.
9338 Each alternative comprises the reserved word @code{when}, either a list of
9339 literal strings separated by the @code{"|"} character or the reserved word
9340 @code{others},  and the @code{"=>"} token.
9341 Each literal string must belong to the string type that is the type of the
9342 case variable.
9343 An @code{others} alternative, if present, must occur last.
9344 The @code{end case;} sequence terminates the case construction.
9345
9346 After each @code{=>}, there are zero or more constructions.  The only
9347 constructions allowed in a case construction are other case constructions and
9348 attribute declarations. String type declarations, variable declarations and
9349 package declarations are not allowed.
9350
9351 The value of the case variable is often given by an external reference
9352 (see @ref{External References in Project Files}).
9353
9354
9355 @c ****************************************
9356 @c * Objects and Sources in Project Files *
9357 @c ****************************************
9358
9359 @node Objects and Sources in Project Files
9360 @section Objects and Sources in Project Files
9361
9362 @menu
9363 * Object Directory::
9364 * Exec Directory::
9365 * Source Directories::
9366 * Source File Names::
9367 @end menu
9368
9369 @noindent
9370 Each project has exactly one object directory and one or more source
9371 directories. The source directories must contain at least one source file,
9372 unless  the project file explicitly specifies that no source files are present
9373 (see @ref{Source File Names}).
9374
9375
9376 @node Object Directory
9377 @subsection Object Directory
9378
9379 @noindent
9380 The object directory for a project is the directory containing the compiler's
9381 output (such as @file{ALI} files and object files) for the project's immediate
9382 sources. Note that for inherited sources (when extending a parent project) the
9383 parent project's object directory is used.
9384
9385 The object directory is given by the value of the attribute @code{Object_Dir}
9386 in the project file.
9387
9388 @smallexample
9389    for Object_Dir use "objects";
9390 @end smallexample
9391
9392 @noindent
9393 The attribute @var{Object_Dir} has a string value, the path name of the object
9394 directory. The path name may be absolute or relative to the directory of the
9395 project file. This directory must already exist, and be readable and writable.
9396
9397 By default, when the attribute @code{Object_Dir} is not given an explicit value
9398 or when its value is the empty string, the object directory is the same as the
9399 directory containing the project file.
9400
9401
9402 @node Exec Directory
9403 @subsection Exec Directory
9404
9405 @noindent
9406 The exec directory for a project is the directory containing the executables
9407 for the project's main subprograms.
9408
9409 The exec directory is given by the value of the attribute @code{Exec_Dir}
9410 in the project file.
9411
9412 @smallexample
9413    for Exec_Dir use "executables";
9414 @end smallexample
9415
9416 @noindent
9417 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9418 directory. The path name may be absolute or relative to the directory of the
9419 project file. This directory must already exist, and be writable.
9420
9421 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9422 or when its value is the empty string, the exec directory is the same as the
9423 object directory of the project file.
9424
9425
9426 @node Source Directories
9427 @subsection Source Directories
9428
9429 @noindent
9430 The source directories of a project are specified by the project file
9431 attribute @code{Source_Dirs}.
9432
9433 This attribute's value is a string list. If the attribute is not given an
9434 explicit value, then there is only one source directory, the one where the
9435 project file resides.
9436
9437 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9438 as in
9439
9440 @smallexample
9441     for Source_Dirs use ();
9442 @end smallexample
9443
9444 @noindent
9445 indicates that the project contains no source files.
9446
9447 Otherwise, each string in the string list designates one or more
9448 source directories.
9449
9450 @smallexample
9451    for Source_Dirs use ("sources", "test/drivers");
9452 @end smallexample
9453
9454 @noindent
9455 If a string in the list ends with @code{"/**"},  then the directory whose path
9456 name precedes the two asterisks, as well as all its subdirectories
9457 (recursively), are source directories.
9458
9459 @smallexample
9460    for Source_Dirs use ("/system/sources/**");
9461 @end smallexample
9462
9463 @noindent
9464 Here the directory @code{/system/sources} and all of its subdirectories
9465 (recursively) are source directories.
9466
9467 To specify that the source directories are the directory of the project file
9468 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9469 @smallexample
9470    for Source_Dirs use ("./**");
9471 @end smallexample
9472
9473 @noindent
9474 Each of the source directories must exist and be readable.
9475
9476
9477 @node Source File Names
9478 @subsection Source File Names
9479
9480 @noindent
9481 In a project that contains source files, their names may be specified by the
9482 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9483 (a string). Source file names never include any directory information.
9484
9485 If the attribute @code{Source_Files} is given an explicit value, then each
9486 element of the list is a source file name.
9487
9488 @smallexample
9489    for Source_Files use ("main.adb");
9490    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9491 @end smallexample
9492
9493 @noindent
9494 If the attribute @code{Source_Files} is not given an explicit value,
9495 but the attribute @code{Source_List_File} is given a string value,
9496 then the source file names are contained in the text file whose path name
9497 (absolute or relative to the directory of the project file) is the
9498 value of the attribute @code{Source_List_File}.
9499
9500 Each line in the file that is not empty or is not a comment
9501 contains a source file name. A comment line starts with two hyphens.
9502
9503 @smallexample
9504    for Source_List_File use "source_list.txt";
9505 @end smallexample
9506
9507 @noindent
9508 By default, if neither the attribute @code{Source_Files} nor the attribute
9509 @code{Source_List_File} is given an explicit value, then each file in the
9510 source directories that conforms to the project's naming scheme
9511 (see @ref{Naming Schemes}) is an immediate source of the project.
9512
9513 A warning is issued if both attributes @code{Source_Files} and
9514 @code{Source_List_File} are given explicit values. In this case, the attribute
9515 @code{Source_Files} prevails.
9516
9517 Each source file name must be the name of one and only one existing source file
9518 in one of the source directories.
9519
9520 A @code{Source_Files} attribute defined with an empty list as its value
9521 indicates that there are no source files in the project.
9522
9523 Except for projects that are clearly specified as containing no Ada source
9524 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9525 or @code{Languages} specified without @code{"Ada"} in the list)
9526 @smallexample
9527    for Source_Dirs use ();
9528    for Source_Files use ();
9529    for Languages use ("C", "C++");
9530 @end smallexample
9531
9532 @noindent
9533 a project must contain at least one immediate source.
9534
9535 Projects with no source files are useful as template packages
9536 (see @ref{Packages in Project Files}) for other projects; in particular to
9537 define a package @code{Naming} (see @ref{Naming Schemes}).
9538
9539
9540 @c ****************************
9541 @c * Importing Projects *
9542 @c ****************************
9543
9544 @node  Importing Projects
9545 @section Importing Projects
9546
9547 @noindent
9548 An immediate source of a project P may depend on source files that
9549 are neither immediate sources of P nor in the predefined library.
9550 To get this effect, P must @emph{import} the projects that contain the needed
9551 source files.
9552
9553 @smallexample
9554 @group
9555   with "project1", "utilities.gpr";
9556   with "/namings/apex.gpr";
9557   project Main is
9558     ...
9559 @end group
9560 @end smallexample
9561
9562 @noindent
9563 As can be seen in this example, the syntax for importing projects is similar
9564 to the syntax for importing compilation units in Ada. However, project files
9565 use literal strings instead of names, and the @code{with} clause identifies
9566 project files rather than packages.
9567
9568 Each literal string is the file name or path name (absolute or relative) of a
9569 project file. If a string is simply a file name, with no path, then its
9570 location is determined by the @emph{project path}:
9571
9572 @itemize @bullet
9573 @item
9574 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9575 path includes all the directories in this environment variable, plus the
9576 directory of the project file.
9577
9578 @item
9579 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9580 then the project path contains only one directory, namely the one where
9581 the project file is located.
9582 @end itemize
9583
9584 @noindent
9585 If a relative pathname is used as in
9586
9587 @smallexample
9588   with "tests/proj";
9589 @end smallexample
9590
9591 @noindent
9592 then the path is relative to the directory where the importing project file is
9593 located. Any symbolic link will be fully resolved in the directory
9594 of the importing project file before the imported project file is looked up.
9595
9596 When the @code{with}'ed project file name does not have an extension,
9597 the default is @file{.gpr}. If a file with this extension is not found, then
9598 the file name as specified in the @code{with} clause (no extension) will be
9599 used. In the above example, if a file @code{project1.gpr} is found, then it
9600 will be used; otherwise, if a file @code{project1} exists then it will be used;
9601 if neither file exists, this is an error.
9602
9603 A warning is issued if the name of the project file does not match the
9604 name of the project; this check is case insensitive.
9605
9606 Any source file that is an immediate source of the imported project can be
9607 used by the immediate sources of the importing project, and recursively. Thus
9608 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9609 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9610 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9611 because if and when @code{B} ceases to import @code{C}, some sources in
9612 @code{A} will no longer compile.
9613
9614 A side effect of this capability is that cyclic dependences are not permitted:
9615 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9616 allowed to import @code{A}.
9617
9618
9619 @c *********************
9620 @c * Project Extension *
9621 @c *********************
9622
9623 @node Project Extension
9624 @section Project Extension
9625
9626 @noindent
9627 During development of a large system, it is sometimes necessary to use
9628 modified versions of some of the source files without changing the original
9629 sources. This can be achieved through a facility known as
9630 @emph{project extension}.
9631
9632 @smallexample
9633    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9634 @end smallexample
9635
9636 @noindent
9637 The project file for the project being extended (the @emph{parent}) is
9638 identified by the literal string that follows the reserved word @code{extends},
9639 which itself follows the name of the extending project (the @emph{child}).
9640
9641 By default, a child project inherits all the sources of its parent.
9642 However, inherited sources can be overridden: a unit with the same name as one
9643 in the parent will hide the original unit.
9644 Inherited sources are considered to be sources (but not immediate sources)
9645 of the child project; see @ref{Project File Syntax}.
9646
9647 An inherited source file retains any switches specified in the parent project.
9648
9649 For example if the project @code{Utilities} contains the specification and the
9650 body of an Ada package @code{Util_IO}, then the project
9651 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9652 The original body of @code{Util_IO} will not be considered in program builds.
9653 However, the package specification will still be found in the project
9654 @code{Utilities}.
9655
9656 A child project can have only one parent but it may import any number of other
9657 projects.
9658
9659 A project is not allowed to import directly or indirectly at the same time a
9660 child project and any of its ancestors.
9661
9662
9663 @c ****************************************
9664 @c * External References in Project Files *
9665 @c ****************************************
9666
9667 @node  External References in Project Files
9668 @section External References in Project Files
9669
9670 @noindent
9671 A project file may contain references to external variables; such references
9672 are called @emph{external references}.
9673
9674 An external variable is either defined as part of the environment (an
9675 environment variable in Unix, for example) or else specified on the command
9676 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9677 command line value is used.
9678
9679 An external reference is denoted by the built-in function
9680 @code{external}, which returns a string value.  This function has two forms:
9681 @itemize @bullet
9682 @item @code{external (external_variable_name)}
9683 @item @code{external (external_variable_name, default_value)}
9684 @end itemize
9685
9686 @noindent
9687 Each parameter must be a string literal.  For example:
9688
9689 @smallexample
9690    external ("USER")
9691    external ("OS", "Linux")
9692 @end smallexample
9693
9694 @noindent
9695 In the form with one parameter, the function returns the value of
9696 the external variable given as parameter. If this name is not present in the
9697 environment, then the returned value is an empty string.
9698
9699 In the form with two string parameters, the second parameter is
9700 the value returned when the variable given as the first parameter is not
9701 present in the environment. In the example above, if @code{"OS"} is not
9702 the name of an environment variable and is not passed on the command line,
9703 then the returned value will be @code{"Linux"}.
9704
9705 An external reference may be part of a string expression or of a string
9706 list expression, to define variables or attributes.
9707
9708 @smallexample
9709 @group
9710    type Mode_Type is ("Debug", "Release");
9711    Mode : Mode_Type := external ("MODE");
9712    case Mode is
9713      when "Debug" =>
9714         ...
9715 @end group
9716 @end smallexample
9717
9718
9719 @c *****************************
9720 @c * Packages in Project Files *
9721 @c *****************************
9722
9723 @node  Packages in Project Files
9724 @section Packages in Project Files
9725
9726 @noindent
9727 The @emph{package} is the project file feature that defines the settings for
9728 project-aware tools.
9729 For each such tool you can declare a corresponding package; the names for these
9730 packages are preset (see @ref{Packages}) but are not case sensitive.
9731 A package may contain variable declarations, attribute declarations, and case
9732 constructions.
9733
9734 @smallexample
9735 @group
9736    project Proj is
9737       package Builder is  -- used by gnatmake
9738          for Default_Switches ("Ada") use ("-v", "-g");
9739       end Builder;
9740    end Proj;
9741 @end group
9742 @end smallexample
9743
9744 @noindent
9745 A package declaration starts with the reserved word @code{package},
9746 followed by the package name (case insensitive), followed by the reserved word
9747 @code{is}. It ends with the reserved word @code{end}, followed by the package
9748 name, finally followed by a semi-colon.
9749
9750 Most of the packages have an attribute @code{Default_Switches}.
9751 This attribute is an associative array, and its value is a string list.
9752 The index of the associative array is the name of a programming language (case
9753 insensitive). This attribute indicates the switch or switches to be used
9754 with the corresponding tool.
9755
9756 Some packages also have another attribute, @code{Switches}, an associative
9757 array whose value is a string list. The index is the name of a source file.
9758 This attribute indicates the switch or switches to be used by the corresponding
9759 tool when dealing with this specific file.
9760
9761 Further information on these switch-related attributes is found in
9762 @ref{Switches and Project Files}.
9763
9764 A package may be declared as a @emph{renaming} of another package; e.g., from
9765 the project file for an imported project.
9766
9767 @smallexample
9768 @group
9769   with "/global/apex.gpr";
9770   project Example is
9771     package Naming renames Apex.Naming;
9772     ...
9773   end Example;
9774 @end group
9775 @end smallexample
9776
9777 @noindent
9778 Packages that are renamed in other project files often come from project files
9779 that have no sources: they are just used as templates. Any modification in the
9780 template will be reflected automatically in all the project files that rename
9781 a package from the template.
9782
9783 In addition to the tool-oriented packages, you can also declare a package
9784 named @code{Naming} to establish specialized source file naming conventions
9785 (see @ref{Naming Schemes}).
9786
9787
9788 @c ************************************
9789 @c * Variables from Imported Projects *
9790 @c ************************************
9791
9792 @node Variables from Imported Projects
9793 @section Variables from Imported Projects
9794
9795 @noindent
9796 An attribute or variable defined in an imported or parent project can
9797 be used in expressions in the importing / extending project.
9798 Such an attribute or variable is prefixed with the name of the project
9799 and (if relevant) the name of package where it is defined.
9800
9801 @smallexample
9802 @group
9803   with "imported";
9804   project Main extends "base" is
9805      Var1 := Imported.Var;
9806      Var2 := Base.Var & ".new";
9807 @end group
9808
9809 @group
9810      package Builder is
9811         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9812                          "-gnatg" & "-v";
9813      end Builder;
9814 @end group
9815
9816 @group
9817      package Compiler is
9818         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9819      end Compiler;
9820   end Main;
9821 @end group
9822 @end smallexample
9823
9824 @noindent
9825 In this example:
9826
9827 @itemize @bullet
9828 @item
9829 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9830 @file{"imported.gpr"}
9831 @item
9832 the value of @code{Var2} is a copy of the value of variable @code{Var}
9833 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9834 @item
9835 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9836 is a string list that includes in its value a copy of variable
9837 @code{Ada_Switches} defined in the @code{Builder} package in project file
9838 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9839 @item
9840 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9841 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9842 package in project file @file{base.gpr}, the project being extended.
9843 @end itemize
9844
9845
9846 @c ******************
9847 @c * Naming Schemes *
9848 @c ******************
9849
9850 @node  Naming Schemes
9851 @section Naming Schemes
9852
9853 @noindent
9854 Sometimes an Ada software system is ported from a foreign compilation
9855 environment to GNAT, with file names that do not use the default GNAT
9856 conventions. Instead of changing all the file names (which for a variety of
9857 reasons might not be possible), you can define the relevant file naming scheme
9858 in the @code{Naming} package in your project file.  For example, the following
9859 package models the Apex file naming rules:
9860
9861 @smallexample
9862 @group
9863   package Naming is
9864     for Casing                        use "lowercase";
9865     for Dot_Replacement               use ".";
9866     for Specification_Suffix ("Ada")  use ".1.ada";
9867     for Implementation_Suffix ("Ada") use ".2.ada";
9868   end Naming;
9869 @end group
9870 @end smallexample
9871
9872 @noindent
9873 You can define the following attributes in package @code{Naming}:
9874
9875 @table @code
9876
9877 @item @var{Casing}
9878 This must be a string with one of the three values @code{"lowercase"},
9879 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9880
9881 @noindent
9882 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9883
9884 @item @var{Dot_Replacement}
9885 This must be a string whose value satisfies the following conditions:
9886
9887 @itemize @bullet
9888 @item It must not be empty
9889 @item It cannot start or end with an alphanumeric character
9890 @item It cannot be a single underscore
9891 @item It cannot start with an underscore followed by an alphanumeric
9892 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
9893 @end itemize
9894
9895 @noindent
9896 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
9897
9898 @item @var{Specification_Suffix}
9899 This is an associative array (indexed by the programming language name, case
9900 insensitive) whose value is a string that must satisfy the following
9901 conditions:
9902
9903 @itemize @bullet
9904 @item It must not be empty
9905 @item It cannot start with an alphanumeric character
9906 @item It cannot start with an underscore followed by an alphanumeric character
9907 @end itemize
9908 @noindent
9909 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
9910 @code{".ads"}.
9911
9912 @item @var{Implementation_Suffix}
9913 This is an associative array (indexed by the programming language name, case
9914 insensitive) whose value is a string that must satisfy the following
9915 conditions:
9916
9917 @itemize @bullet
9918 @item It must not be empty
9919 @item It cannot start with an alphanumeric character
9920 @item It cannot start with an underscore followed by an alphanumeric character
9921 @item It cannot be a suffix of @code{Specification_Suffix}
9922 @end itemize
9923 @noindent
9924 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
9925 @code{".adb"}.
9926
9927 @item @var{Separate_Suffix}
9928 This must be a string whose value satisfies the same conditions as
9929 @code{Implementation_Suffix}.
9930
9931 @noindent
9932 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
9933 value as @code{Implementation_Suffix ("Ada")}.
9934
9935 @item @var{Specification}
9936 @noindent
9937 You can use the @code{Specification} attribute, an associative array, to define
9938 the source file name for an individual Ada compilation unit's spec. The array
9939 index must be a string literal that identifies the Ada unit (case insensitive).
9940 The value of this attribute must be a string that identifies the file that
9941 contains this unit's spec (case sensitive or insensitive depending on the
9942 operating system).
9943
9944 @smallexample
9945    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
9946 @end smallexample
9947
9948 @item @var{Implementation}
9949
9950 You can use the @code{Implementation} attribute, an associative array, to
9951 define the source file name for an individual Ada compilation unit's body
9952 (possibly a subunit).  The array index must be a string literal that identifies
9953 the Ada unit (case insensitive).  The value of this attribute must be a string
9954 that identifies the file that contains this unit's body or subunit (case
9955 sensitive or insensitive depending on the operating system).
9956
9957 @smallexample
9958    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
9959 @end smallexample
9960 @end table
9961
9962
9963 @c ********************
9964 @c * Library Projects *
9965 @c ********************
9966
9967 @node Library Projects
9968 @section Library Projects
9969
9970 @noindent
9971 @emph{Library projects} are projects whose object code is placed in a library.
9972 (Note that this facility is not yet supported on all platforms)
9973
9974 To create a library project, you need to define in its project file
9975 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
9976 Additionally, you may define the library-related attributes
9977 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
9978
9979 The @code{Library_Name} attribute has a string value that must start with a
9980 letter and include only letters and digits.
9981
9982 The @code{Library_Dir} attribute has a string value that designates the path
9983 (absolute or relative) of the directory where the library will reside.
9984 It must designate an existing directory, and this directory needs to be
9985 different from the project's object directory. It also needs to be writable.
9986
9987 If both @code{Library_Name} and @code{Library_Dir} are specified and
9988 are legal, then the project file defines a library project.  The optional
9989 library-related attributes are checked only for such project files.
9990
9991 The @code{Library_Kind} attribute has a string value that must be one of the
9992 following (case insensitive): @code{"static"}, @code{"dynamic"} or
9993 @code{"relocatable"}. If this attribute is not specified, the library is a
9994 static library. Otherwise, the library may be dynamic or relocatable.
9995 Depending on the operating system, there may or may not be a distinction
9996 between dynamic and relocatable libraries. For example, on Unix there is no
9997 such distinction.
9998
9999 The @code{Library_Version} attribute has a string value whose interpretation
10000 is platform dependent. On Unix, it is used only for dynamic/relocatable
10001 libraries as the internal name of the library (the @code{"soname"}). If the
10002 library file name (built from the @code{Library_Name}) is different from the
10003 @code{Library_Version}, then the library file will be a symbolic link to the
10004 actual file whose name will be @code{Library_Version}.
10005
10006 Example (on Unix):
10007
10008 @smallexample
10009 @group
10010 project Plib is
10011
10012    Version := "1";
10013
10014    for Library_Dir use "lib_dir";
10015    for Library_Name use "dummy";
10016    for Library_Kind use "relocatable";
10017    for Library_Version use "libdummy.so." & Version;
10018
10019 end Plib;
10020 @end group
10021 @end smallexample
10022
10023 @noindent
10024 Directory @file{lib_dir} will contain the internal library file whose name
10025 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10026 @file{libdummy.so.1}.
10027
10028 When @command{gnatmake} detects that a project file (not the main project file)
10029 is a library project file, it will check all immediate sources of the project
10030 and rebuild the library if any of the sources have been recompiled.
10031 All @file{ALI} files will also be copied from the object directory to the
10032 library directory. To build executables, @command{gnatmake} will use the
10033 library rather than the individual object files.
10034
10035
10036 @c *************************************
10037 @c * Switches Related to Project Files *
10038 @c *************************************
10039 @node Switches Related to Project Files
10040 @section Switches Related to Project Files
10041
10042 @noindent
10043 The following switches are used by GNAT tools that support project files:
10044
10045 @table @code
10046
10047 @item @option{-P@var{project}}
10048 Indicates the name of a project file. This project file will be parsed with
10049 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10050 references indicated by @option{-X} switches, if any.
10051
10052 @noindent
10053 There must be only one @option{-P} switch on the command line.
10054
10055 @noindent
10056 Since the Project Manager parses the project file only after all the switches
10057 on the command line are checked, the order of the switches @option{-P},
10058 @option{-Vp@emph{x}} or @option{-X} is not significant.
10059
10060 @item @option{-X@var{name=value}}
10061 Indicates that external variable @var{name} has the value @var{value}.
10062 The Project Manager will use this value for occurrences of
10063 @code{external(name)} when parsing the project file.
10064
10065 @noindent
10066 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10067 put between quotes.
10068 @smallexample
10069   -XOS=NT
10070   -X"user=John Doe"
10071 @end smallexample
10072
10073 @noindent
10074 Several @option{-X} switches can be used simultaneously.
10075 If several @option{-X} switches specify the same @var{name}, only the last one
10076 is used.
10077
10078 @noindent
10079 An external variable specified with a @option{-X} switch takes precedence
10080 over the value of the same name in the environment.
10081
10082 @item @option{-vP@emph{x}}
10083 Indicates the verbosity of the parsing of GNAT project files.
10084 @option{-vP0} means Default (no output for syntactically correct project
10085 files);
10086 @option{-vP1} means Medium;
10087 @option{-vP2} means High.
10088 @noindent
10089 The default is Default.
10090 @noindent
10091 If several @option{-vP@emph{x}} switches are present, only the last one is
10092 used.
10093
10094 @end table
10095
10096
10097 @c **********************************
10098 @c * Tools Supporting Project Files *
10099 @c **********************************
10100
10101 @node  Tools Supporting Project Files
10102 @section Tools Supporting Project Files
10103
10104 @menu
10105 * gnatmake and Project Files::
10106 * The GNAT Driver and Project Files::
10107 * Glide and Project Files::
10108 @end menu
10109
10110 @node gnatmake and Project Files
10111 @subsection gnatmake and Project Files
10112
10113 @noindent
10114 This section covers two topics related to @command{gnatmake} and project files:
10115 defining switches for @command{gnatmake} and for the tools that it invokes;
10116 and the use of the @code{Main} attribute.
10117
10118 @menu
10119 * Switches and Project Files::
10120 * Project Files and Main Subprograms::
10121 @end menu
10122
10123 @node Switches and Project Files
10124 @subsubsection Switches and Project Files
10125
10126 @noindent
10127 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10128 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10129 @code{Switches} attribute, or both; as their names imply, these switch-related
10130 attributes affect which switches are used for which files when
10131 @command{gnatmake} is invoked.  As will be explained below, these
10132 package-contributed switches precede the switches passed on the
10133 @command{gnatmake} command line.
10134
10135 The @code{Default_Switches} attribute is an associative array indexed by
10136 language name (case insensitive) and returning a string list.  For example:
10137
10138 @smallexample
10139 @group
10140 package Compiler is
10141   for Default_Switches ("Ada") use ("-gnaty", "-v");
10142 end Compiler;
10143 @end group
10144 @end smallexample
10145
10146 @noindent
10147 The @code{Switches} attribute is also an associative array, indexed by a file
10148 name (which may or may not be case sensitive, depending on the operating
10149 system) and returning a string list.  For example:
10150
10151 @smallexample
10152 @group
10153 package Builder is
10154    for Switches ("main1.adb") use ("-O2");
10155    for Switches ("main2.adb") use ("-g");
10156 end Builder;
10157 @end group
10158 @end smallexample
10159
10160 @noindent
10161 For the @code{Builder} package, the file names should designate source files
10162 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10163 file names should designate @file{ALI} or source files for main subprograms.
10164 In each case just the file name (without explicit extension) is acceptable.
10165
10166 For each tool used in a program build (@command{gnatmake}, the compiler, the
10167 binder, and the linker), its corresponding package @dfn{contributes} a set of
10168 switches for each file on which the tool is invoked, based on the
10169 switch-related attributes defined in the package. In particular, the switches
10170 that each of these packages contributes for a given file @var{f} comprise:
10171
10172 @itemize @bullet
10173 @item
10174 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10175 package for the given file,
10176 @item
10177 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10178 the package.
10179 @end itemize
10180
10181 @noindent
10182 If neither of these attributes is defined in the package, then the package does
10183 not contribute any switches for the given file.
10184
10185 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10186 in the following order: those contributed for the file by the @code{Builder}
10187 package; and the switches passed on the command line.
10188
10189 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10190 the switches passed to the tool comprise three sets, in the following order:
10191
10192 @enumerate
10193 @item
10194 the applicable switches contributed for the file by the @code{Builder} package
10195 in the project file supplied on the command line;
10196
10197 @item
10198 those contributed for the file by the package (in the relevant project file --
10199 see below) corresponding to the tool; and
10200
10201 @item
10202 the applicable switches passed on the command line.
10203 @end enumerate
10204
10205 @noindent
10206 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10207 switches may or may not be passed to individual tools, depending on the
10208 individual switch.
10209
10210 @command{gnatmake} may invoke the compiler on source files from different
10211 projects. The Project Manager will use the appropriate project file to
10212 determine the @code{Compiler} package for each source file being compiled.
10213 Likewise for the @code{Binder} and @code{Linker} packages.
10214
10215 As an example, consider the following package in a project file:
10216
10217 @smallexample
10218 @group
10219 project Proj1 is
10220    package Compiler is
10221       for Default_Switches ("Ada") use ("-g");
10222       for Switches ("a.adb") use ("-O1");
10223       for Switches ("b.adb") use ("-O2", "-gnaty");
10224    end Compiler;
10225 end Proj1;
10226 @end group
10227 @end smallexample
10228
10229 @noindent
10230 If @command{gnatmake} is invoked with this project file, and it needs to
10231 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10232 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10233 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10234 @option{-g}.
10235
10236 Another example illustrates the ordering of the switches contributed by
10237 different packages:
10238
10239 @smallexample
10240 @group
10241 project Proj2 is
10242    package Builder is
10243       for Switches ("main.adb") use ("-g", "-O1", "-f");
10244    end Builder;
10245 @end group
10246
10247 @group
10248    package Compiler is
10249       for Switches ("main.adb") use ("-O2");
10250    end Compiler;
10251 end Proj2;
10252 @end group
10253 @end smallexample
10254
10255 @noindent
10256 If you issue the command:
10257
10258 @smallexample
10259     gnatmake -PProj2 -O0 main
10260 @end smallexample
10261
10262 @noindent
10263 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10264
10265 @smallexample
10266    -g -O1 -O2 -O0
10267 @end smallexample
10268
10269 with the last @option{-O} switch having precedence over the earlier ones;
10270 several other switches (such as @option{-c}) are added implicitly.
10271
10272 The switches @option{-g} and @option{-O1} are contributed by package
10273 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
10274 and @option{-O0} comes from the command line.
10275
10276 The @option{-g} switch will also be passed in the invocation of
10277 @command{gnatlink.}
10278
10279 A final example illustrates switch contributions from packages in different
10280 project files:
10281
10282 @smallexample
10283 @group
10284 project Proj3 is
10285    for Source_Files use ("pack.ads", "pack.adb");
10286    package Compiler is
10287       for Default_Switches ("Ada") use ("-gnata");
10288    end Compiler;
10289 end Proj3;
10290 @end group
10291
10292 @group
10293 with "Proj3";
10294 project Proj4 is
10295    for Source_Files use ("foo_main.adb", "bar_main.adb");
10296    package Builder is
10297       for Switches ("foo_main.adb") use ("-s", "-g");
10298    end Builder;
10299 end Proj4;
10300 @end group
10301
10302 @group
10303 -- Ada source file:
10304 with Pack;
10305 procedure Foo_Main is
10306    ...
10307 end Foo_Main;
10308 @end group
10309 @end smallexample
10310
10311 If the command is
10312 @smallexample
10313 gnatmake -PProj4 foo_main.adb -cargs -gnato
10314 @end smallexample
10315
10316 @noindent
10317 then the switches passed to the compiler for @file{foo_main.adb} are
10318 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10319 @option{-gnato} (passed on the command line).
10320 When the imported package @code{Pack} is compiled, the switches used are
10321 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10322 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10323
10324
10325 @node Project Files and Main Subprograms
10326 @subsubsection Project Files and Main Subprograms
10327
10328 @noindent
10329 When using a project file, you can invoke @command{gnatmake}
10330 with several main subprograms, by specifying their source files on the command
10331 line.  Each of these needs to be an immediate source file of the project.
10332
10333 @smallexample
10334     gnatmake -Pprj main1 main2 main3
10335 @end smallexample
10336
10337 @noindent
10338 When using a project file, you can also invoke @command{gnatmake} without
10339 explicitly specifying any main, and the effect depends on whether you have
10340 defined the @code{Main} attribute.  This attribute has a string list value,
10341 where each element in the list is the name of a source file (the file
10342 extension is optional) containing a main subprogram.
10343
10344 If the @code{Main} attribute is defined in a project file as a non-empty
10345 string list and the switch @option{-u} is not used on the command line, then
10346 invoking @command{gnatmake} with this project file but without any main on the
10347 command line is equivalent to invoking @command{gnatmake} with all the file
10348 names in the @code{Main} attribute on the command line.
10349
10350 Example:
10351 @smallexample
10352 @group
10353    project Prj is
10354       for Main use ("main1", "main2", "main3");
10355    end Prj;
10356 @end group
10357 @end smallexample
10358
10359 @noindent
10360 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10361 @code{"gnatmake -Pprj main1 main2 main3"}.
10362
10363 When the project attribute @code{Main} is not specified, or is specified
10364 as an empty string list, or when the switch @option{-u} is used on the command
10365 line, then invoking @command{gnatmake} with no main on the command line will
10366 result in all immediate sources of the project file being checked, and
10367 potentially recompiled. Depending on the presence of the switch @option{-u},
10368 sources from other project files on which the immediate sources of the main
10369 project file depend are also checked and potentially recompiled. In other
10370 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10371
10372
10373 @node The GNAT Driver and Project Files
10374 @subsection The GNAT Driver and Project Files
10375
10376 @noindent
10377 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10378 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10379 and @command{gnatxref}. However, none of these tools can be invoked directly
10380 with a project file switch (@code{-P}). They need to be invoke through the
10381 @command{gnat} driver.
10382
10383 The @command{gnat} driver is a front-end that accepts a number of commands and
10384 call the corresponding tool. It has been designed initially for VMS to convert
10385 VMS style qualifiers to Unix style switches, but it is now available to all
10386 the GNAT supported platforms.
10387
10388 On non VMS platforms, the @command{gnat} driver accepts the following commands
10389 (case insensitive):
10390
10391 @itemize @bullet
10392 @item
10393 BIND to invoke @command{gnatbind}
10394 @item
10395 CHOP to invoke @command{gnatchop}
10396 @item
10397 COMP or COMPILE to invoke the compiler
10398 @item
10399 ELIM to invoke @command{gnatelim}
10400 @item
10401 FIND to invoke @command{gnatfind}
10402 @item
10403 KR or KRUNCH to invoke @command{gnatkr}
10404 @item
10405 LINK to invoke @command{gnatlink}
10406 @item
10407 LS or LIST to invoke @command{gnatls}
10408 @item
10409 MAKE to invoke @command{gnatmake}
10410 @item
10411 NAME to invoke @command{gnatname}
10412 @item
10413 PREP or PREPROCESS to invoke @command{gnatprep}
10414 @item
10415 PSTA or STANDARD to invoke @command{gnatpsta}
10416 @item
10417 STUB to invoke @command{gnatstub}
10418 @item
10419 XREF to invoke @command{gnatxref}
10420 @end itemize
10421
10422 @noindent
10423 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10424
10425 @noindent
10426 Following the command, you may put switches and arguments for the invoked
10427 tool.
10428
10429 @smallexample
10430   gnat bind -C main.ali
10431   gnat ls -a main
10432   gnat chop foo.txt
10433 @end smallexample
10434
10435 @noindent
10436 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10437 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10438 addition to the switches of the invoking tool.
10439
10440 @noindent
10441 For each of these command, there is possibly a package in the main project that
10442 corresponds to the invoked tool.
10443
10444 @itemize @bullet
10445 @item
10446 package @code{Binder} for command BIND (invoking @code{gnatbind})
10447
10448 @item
10449 package @code{Finder} for command FIND (invoking @code{gnatfind})
10450
10451 @item
10452 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10453
10454 @item
10455 package @code{Linker} for command LINK (invoking @code{gnatlink})
10456
10457 @item
10458 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10459
10460 @end itemize
10461
10462 @noindent
10463 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10464 with a string list value. It contains switches for the invocation of
10465 @code{gnatls}.
10466
10467 @smallexample
10468 @group
10469 project Proj1 is
10470    package gnatls is
10471       for Switches use ("-a", "-v");
10472    end gnatls;
10473 end Proj1;
10474 @end group
10475 @end smallexample
10476
10477 @noindent
10478 All other packages contains a switch @code{Default_Switches}, an associative
10479 array, indexed by the programming language (case insensitive) and having a
10480 string list value. @code{Default_Switches ("Ada")} contains the switches for
10481 the invocation of the tool corresponding to the package.
10482
10483 @smallexample
10484 @group
10485 project Proj is
10486
10487    for Source_Dirs use ("./**");
10488
10489    package gnatls is
10490       for Switches use ("-a", "-v");
10491    end gnatls;
10492 @end group
10493 @group
10494
10495    package Binder is
10496       for Default_Switches ("Ada") use ("-C", "-e");
10497    end Binder;
10498 @end group
10499 @group
10500
10501    package Linker is
10502       for Default_Switches ("Ada") use ("-C");
10503    end Linker;
10504 @end group
10505 @group
10506
10507    package Finder is
10508       for Default_Switches ("Ada") use ("-a", "-f");
10509    end Finder;
10510 @end group
10511 @group
10512
10513    package Cross_Reference is
10514       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10515    end Cross_Reference;
10516 end Proj;
10517 @end group
10518 @end smallexample
10519
10520 @noindent
10521 With the above project file, commands such as
10522
10523 @smallexample
10524    gnat ls -Pproj main
10525    gnat xref -Pproj main
10526    gnat bind -Pproj main.ali
10527 @end smallexample
10528
10529 @noindent
10530 will set up the environment properly and invoke the tool with the switches
10531 found in the package corresponding to the tool.
10532
10533
10534 @node Glide and Project Files
10535 @subsection Glide and Project Files
10536
10537 @noindent
10538 Glide will automatically recognize the @file{.gpr} extension for
10539 project files, and will
10540 convert them to its own internal format automatically. However, it
10541 doesn't provide a syntax-oriented editor for modifying these
10542 files.
10543 The project file will be loaded as text when you select the menu item
10544 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10545 You can edit this text and save the @file{gpr} file;
10546 when you next select this project file in Glide it
10547 will be automatically reloaded.
10548
10549
10550
10551 @node An Extended Example
10552 @section An Extended Example
10553
10554 @noindent
10555 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10556 in the respective directories. We would like to build them with a single
10557 @command{gnatmake} command, and we would like to place their object files into
10558 @file{.build} subdirectories of the source directories. Furthermore, we would
10559 like to have to have two separate subdirectories in @file{.build}  --
10560 @file{release} and @file{debug} -- which will contain the object files compiled with
10561 different set of compilation flags.
10562
10563 In other words, we have the following structure:
10564
10565 @smallexample
10566 @group
10567    main
10568      |- prog1
10569      |    |- .build
10570      |         | debug
10571      |         | release
10572      |- prog2
10573           |- .build
10574                | debug
10575                | release
10576 @end group
10577 @end smallexample
10578
10579 @noindent
10580 Here are the project files that we need to create in a directory @file{main}
10581 to maintain this structure:
10582
10583 @enumerate
10584
10585 @item We create a @code{Common} project with a package @code{Compiler} that
10586 specifies the compilation switches:
10587
10588 @smallexample
10589 File "common.gpr":
10590 @group
10591 @b{project} Common @b{is}
10592
10593    @b{for} Source_Dirs @b{use} (); -- No source files
10594 @end group
10595
10596 @group
10597    @b{type} Build_Type @b{is} ("release", "debug");
10598    Build : Build_Type := External ("BUILD", "debug");
10599 @end group
10600 @group
10601    @b{package} Compiler @b{is}
10602       @b{case} Build @b{is}
10603          @b{when} "release" =>
10604            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10605          @b{when} "debug"   =>
10606            @b{for} Default_Switches ("Ada") @b{use} ("-g");
10607       @b{end case};
10608    @b{end} Compiler;
10609
10610 @b{end} Common;
10611 @end group
10612 @end smallexample
10613
10614 @item We create separate projects for the two programs:
10615
10616 @smallexample
10617 @group
10618 File "prog1.gpr":
10619
10620 @b{with} "common";
10621 @b{project} Prog1 @b{is}
10622
10623     @b{for} Source_Dirs @b{use} ("prog1");
10624     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
10625
10626     @b{package} Compiler @b{renames} Common.Compiler;
10627
10628 @b{end} Prog1;
10629 @end group
10630 @end smallexample
10631
10632 @smallexample
10633 @group
10634 File "prog2.gpr":
10635
10636 @b{with} "common";
10637 @b{project} Prog2 @b{is}
10638
10639     @b{for} Source_Dirs @b{use} ("prog2");
10640     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
10641
10642     @b{package} Compiler @b{renames} Common.Compiler;
10643
10644 @end group
10645 @b{end} Prog2;
10646 @end smallexample
10647
10648 @item We create a wrapping project @var{Main}:
10649
10650 @smallexample
10651 @group
10652 File "main.gpr":
10653
10654 @b{with} "common";
10655 @b{with} "prog1";
10656 @b{with} "prog2";
10657 @b{project} Main @b{is}
10658
10659    @b{package} Compiler @b{renames} Common.Compiler;
10660
10661 @b{end} Main;
10662 @end group
10663 @end smallexample
10664
10665 @item Finally we need to create a dummy procedure that @code{with}s (either
10666 explicitly or implicitly) all the sources of our two programs.
10667
10668 @end enumerate
10669
10670 @noindent
10671 Now we can build the programs using the command
10672
10673 @smallexample
10674    gnatmake -Pmain dummy
10675 @end smallexample
10676
10677 @noindent
10678 for the Debug mode, or
10679
10680 @smallexample
10681    gnatmake -Pmain -XBUILD=release
10682 @end smallexample
10683
10684 @noindent
10685 for the Release mode.
10686
10687
10688 @c ********************************
10689 @c * Project File Complete Syntax *
10690 @c ********************************
10691
10692 @node Project File Complete Syntax
10693 @section Project File Complete Syntax
10694
10695 @smallexample
10696 project ::=
10697   context_clause project_declaration
10698
10699 context_clause ::=
10700   @{with_clause@}
10701
10702 with_clause ::=
10703   @b{with} literal_string @{ , literal_string @} ;
10704
10705 project_declaration ::=
10706   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10707     @{declarative_item@}
10708   @b{end} <project_>simple_name;
10709
10710 declarative_item ::=
10711   package_declaration |
10712   typed_string_declaration |
10713   other_declarative_item
10714
10715 package_declaration ::=
10716   @b{package} <package_>simple_name package_completion
10717
10718 package_completion ::=
10719   package_body | package_renaming
10720
10721 package body ::=
10722   @b{is}
10723     @{other_declarative_item@}
10724   @b{end} <package_>simple_name ;
10725
10726 package_renaming ::==
10727   @b{renames} <project_>simple_name.<package_>simple_name ;
10728
10729 typed_string_declaration ::=
10730   @b{type} <typed_string_>_simple_name @b{is}
10731    ( literal_string @{, literal_string@} );
10732
10733 other_declarative_item ::=
10734   attribute_declaration |
10735   typed_variable_declaration |
10736   variable_declaration |
10737   case_construction
10738
10739 attribute_declaration ::=
10740   @b{for} attribute @b{use} expression ;
10741
10742 attribute ::=
10743   <simple_attribute_>simple_name |
10744   <associative_array_attribute_>simple_name ( literal_string )
10745
10746 typed_variable_declaration ::=
10747   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
10748
10749 variable_declaration ::=
10750   <variable_>simple_name := expression;
10751
10752 expression ::=
10753   term @{& term@}
10754
10755 term ::=
10756   literal_string |
10757   string_list |
10758   <variable_>name |
10759   external_value |
10760   attribute_reference
10761
10762 literal_string ::=
10763   (same as Ada)
10764
10765 string_list ::=
10766   ( <string_>expression @{ , <string_>expression @} )
10767
10768 external_value ::=
10769   @b{external} ( literal_string [, literal_string] )
10770
10771 attribute_reference ::=
10772   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10773
10774 attribute_parent ::=
10775   @b{project} |
10776   <project_or_package>simple_name |
10777   <project_>simple_name . <package_>simple_name
10778
10779 case_construction ::=
10780   @b{case} <typed_variable_>name @b{is}
10781     @{case_item@}
10782   @b{end case} ;
10783
10784 case_item ::=
10785   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10786
10787 discrete_choice_list ::=
10788   literal_string @{| literal_string@}
10789
10790 name ::=
10791   simple_name @{. simple_name@}
10792
10793 simple_name ::=
10794   identifier (same as Ada)
10795
10796 @end smallexample
10797
10798
10799 @node Elaboration Order Handling in GNAT
10800 @chapter Elaboration Order Handling in GNAT
10801 @cindex Order of elaboration
10802 @cindex Elaboration control
10803
10804 @menu
10805 * Elaboration Code in Ada 95::
10806 * Checking the Elaboration Order in Ada 95::
10807 * Controlling the Elaboration Order in Ada 95::
10808 * Controlling Elaboration in GNAT - Internal Calls::
10809 * Controlling Elaboration in GNAT - External Calls::
10810 * Default Behavior in GNAT - Ensuring Safety::
10811 * Elaboration Issues for Library Tasks::
10812 * Mixing Elaboration Models::
10813 * What to Do If the Default Elaboration Behavior Fails::
10814 * Elaboration for Access-to-Subprogram Values::
10815 * Summary of Procedures for Elaboration Control::
10816 * Other Elaboration Order Considerations::
10817 @end menu
10818
10819 @noindent
10820 This chapter describes the handling of elaboration code in Ada 95 and
10821 in GNAT, and discusses how the order of elaboration of program units can
10822 be controlled in GNAT, either automatically or with explicit programming
10823 features.
10824
10825 @node Elaboration Code in Ada 95
10826 @section Elaboration Code in Ada 95
10827
10828 @noindent
10829 Ada 95 provides rather general mechanisms for executing code at elaboration
10830 time, that is to say before the main program starts executing. Such code arises
10831 in three contexts:
10832
10833 @table @asis
10834 @item Initializers for variables.
10835 Variables declared at the library level, in package specs or bodies, can
10836 require initialization that is performed at elaboration time, as in:
10837 @smallexample
10838 @cartouche
10839 Sqrt_Half : Float := Sqrt (0.5);
10840 @end cartouche
10841 @end smallexample
10842
10843 @item Package initialization code
10844 Code in a @code{BEGIN-END} section at the outer level of a package body is
10845 executed as part of the package body elaboration code.
10846
10847 @item Library level task allocators
10848 Tasks that are declared using task allocators at the library level
10849 start executing immediately and hence can execute at elaboration time.
10850 @end table
10851
10852 @noindent
10853 Subprogram calls are possible in any of these contexts, which means that
10854 any arbitrary part of the program may be executed as part of the elaboration
10855 code. It is even possible to write a program which does all its work at
10856 elaboration time, with a null main program, although stylistically this
10857 would usually be considered an inappropriate way to structure
10858 a program.
10859
10860 An important concern arises in the context of elaboration code:
10861 we have to be sure that it is executed in an appropriate order. What we
10862 have is a series of elaboration code sections, potentially one section
10863 for each unit in the program. It is important that these execute
10864 in the correct order. Correctness here means that, taking the above
10865 example of the declaration of @code{Sqrt_Half},
10866 if some other piece of
10867 elaboration code references @code{Sqrt_Half},
10868 then it must run after the
10869 section of elaboration code that contains the declaration of
10870 @code{Sqrt_Half}.
10871
10872 There would never be any order of elaboration problem if we made a rule
10873 that whenever you @code{with} a unit, you must elaborate both the spec and body
10874 of that unit before elaborating the unit doing the @code{with}'ing:
10875
10876 @smallexample
10877 @group
10878 @cartouche
10879 @b{with} Unit_1;
10880 @b{package} Unit_2 @b{is} ...
10881 @end cartouche
10882 @end group
10883 @end smallexample
10884
10885 @noindent
10886 would require that both the body and spec of @code{Unit_1} be elaborated
10887 before the spec of @code{Unit_2}. However, a rule like that would be far too
10888 restrictive. In particular, it would make it impossible to have routines
10889 in separate packages that were mutually recursive.
10890
10891 You might think that a clever enough compiler could look at the actual
10892 elaboration code and determine an appropriate correct order of elaboration,
10893 but in the general case, this is not possible. Consider the following
10894 example.
10895
10896 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
10897 that references
10898 the variable @code{Sqrt_1}, which is declared in the elaboration code
10899 of the body of @code{Unit_1}:
10900
10901 @smallexample
10902 @cartouche
10903 Sqrt_1 : Float := Sqrt (0.1);
10904 @end cartouche
10905 @end smallexample
10906
10907 @noindent
10908 The elaboration code of the body of @code{Unit_1} also contains:
10909
10910 @smallexample
10911 @group
10912 @cartouche
10913 @b{if} expression_1 = 1 @b{then}
10914    Q := Unit_2.Func_2;
10915 @b{end if};
10916 @end cartouche
10917 @end group
10918 @end smallexample
10919
10920 @noindent
10921 @code{Unit_2} is exactly parallel,
10922 it has a procedure @code{Func_2} that references
10923 the variable @code{Sqrt_2}, which is declared in the elaboration code of
10924 the body @code{Unit_2}:
10925
10926 @smallexample
10927 @cartouche
10928 Sqrt_2 : Float := Sqrt (0.1);
10929 @end cartouche
10930 @end smallexample
10931
10932 @noindent
10933 The elaboration code of the body of @code{Unit_2} also contains:
10934
10935 @smallexample
10936 @group
10937 @cartouche
10938 @b{if} expression_2 = 2 @b{then}
10939    Q := Unit_1.Func_1;
10940 @b{end if};
10941 @end cartouche
10942 @end group
10943 @end smallexample
10944
10945 @noindent
10946 Now the question is, which of the following orders of elaboration is
10947 acceptable:
10948
10949 @smallexample
10950 @group
10951 Spec of Unit_1
10952 Spec of Unit_2
10953 Body of Unit_1
10954 Body of Unit_2
10955 @end group
10956 @end smallexample
10957
10958 @noindent
10959 or
10960
10961 @smallexample
10962 @group
10963 Spec of Unit_2
10964 Spec of Unit_1
10965 Body of Unit_2
10966 Body of Unit_1
10967 @end group
10968 @end smallexample
10969
10970 @noindent
10971 If you carefully analyze the flow here, you will see that you cannot tell
10972 at compile time the answer to this question.
10973 If @code{expression_1} is not equal to 1,
10974 and @code{expression_2} is not equal to 2,
10975 then either order is acceptable, because neither of the function calls is
10976 executed. If both tests evaluate to true, then neither order is acceptable
10977 and in fact there is no correct order.
10978
10979 If one of the two expressions is true, and the other is false, then one
10980 of the above orders is correct, and the other is incorrect. For example,
10981 if @code{expression_1} = 1 and @code{expression_2} /= 2,
10982 then the call to @code{Func_2}
10983 will occur, but not the call to @code{Func_1.}
10984 This means that it is essential
10985 to elaborate the body of @code{Unit_1} before
10986 the body of @code{Unit_2}, so the first
10987 order of elaboration is correct and the second is wrong.
10988
10989 By making @code{expression_1} and @code{expression_2}
10990 depend on input data, or perhaps
10991 the time of day, we can make it impossible for the compiler or binder
10992 to figure out which of these expressions will be true, and hence it
10993 is impossible to guarantee a safe order of elaboration at run time.
10994
10995 @node Checking the Elaboration Order in Ada 95
10996 @section Checking the Elaboration Order in Ada 95
10997
10998 @noindent
10999 In some languages that involve the same kind of elaboration problems,
11000 e.g. Java and C++, the programmer is expected to worry about these
11001 ordering problems himself, and it is common to
11002 write a program in which an incorrect elaboration order  gives
11003 surprising results, because it references variables before they
11004 are initialized.
11005 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11006 clearly not sufficient. Consequently, the language provides three lines
11007 of defense:
11008
11009 @table @asis
11010 @item Standard rules
11011 Some standard rules restrict the possible choice of elaboration
11012 order. In particular, if you @code{with} a unit, then its spec is always
11013 elaborated before the unit doing the @code{with}. Similarly, a parent
11014 spec is always elaborated before the child spec, and finally
11015 a spec is always elaborated before its corresponding body.
11016
11017 @item Dynamic elaboration checks
11018 @cindex Elaboration checks
11019 @cindex Checks, elaboration
11020 Dynamic checks are made at run time, so that if some entity is accessed
11021 before it is elaborated (typically  by means of a subprogram call)
11022 then the exception (@code{Program_Error}) is raised.
11023
11024 @item Elaboration control
11025 Facilities are provided for the programmer to specify the desired order
11026 of elaboration.
11027 @end table
11028
11029 Let's look at these facilities in more detail. First, the rules for
11030 dynamic checking. One possible rule would be simply to say that the
11031 exception is raised if you access a variable which has not yet been
11032 elaborated. The trouble with this approach is that it could require
11033 expensive checks on every variable reference. Instead Ada 95 has two
11034 rules which are a little more restrictive, but easier to check, and
11035 easier to state:
11036
11037 @table @asis
11038 @item Restrictions on calls
11039 A subprogram can only be called at elaboration time if its body
11040 has been elaborated. The rules for elaboration given above guarantee
11041 that the spec of the subprogram has been elaborated before the
11042 call, but not the body. If this rule is violated, then the
11043 exception @code{Program_Error} is raised.
11044
11045 @item Restrictions on instantiations
11046 A generic unit can only be instantiated if the body of the generic
11047 unit has been elaborated. Again, the rules for elaboration given above
11048 guarantee that the spec of the generic unit has been elaborated
11049 before the instantiation, but not the body. If this rule is
11050 violated, then the exception @code{Program_Error} is raised.
11051 @end table
11052
11053 @noindent
11054 The idea is that if the body has been elaborated, then any variables
11055 it references must have been elaborated; by checking for the body being
11056 elaborated we guarantee that none of its references causes any
11057 trouble. As we noted above, this is a little too restrictive, because a
11058 subprogram that has no non-local references in its body may in fact be safe
11059 to call. However, it really would be unsafe to rely on this, because
11060 it would mean that the caller was aware of details of the implementation
11061 in the body. This goes against the basic tenets of Ada.
11062
11063 A plausible implementation can be described as follows.
11064 A Boolean variable is associated with each subprogram
11065 and each generic unit. This variable is initialized to False, and is set to
11066 True at the point body is elaborated. Every call or instantiation checks the
11067 variable, and raises @code{Program_Error} if the variable is False.
11068
11069 Note that one might think that it would be good enough to have one Boolean
11070 variable for each package, but that would not deal with cases of trying
11071 to call a body in the same package as the call
11072 that has not been elaborated yet.
11073 Of course a compiler may be able to do enough analysis to optimize away
11074 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11075 does such optimizations, but still the easiest conceptual model is to
11076 think of there being one variable per subprogram.
11077
11078 @node Controlling the Elaboration Order in Ada 95
11079 @section Controlling the Elaboration Order in Ada 95
11080
11081 @noindent
11082 In the previous section we discussed the rules in Ada 95 which ensure
11083 that @code{Program_Error} is raised if an incorrect elaboration order is
11084 chosen. This prevents erroneous executions, but we need mechanisms to
11085 specify a correct execution and avoid the exception altogether.
11086 To achieve this, Ada 95 provides a number of features for controlling
11087 the order of elaboration. We discuss these features in this section.
11088
11089 First, there are several ways of indicating to the compiler that a given
11090 unit has no elaboration problems:
11091
11092 @table @asis
11093 @item packages that do not require a body
11094 In Ada 95, a library package that does not require a body does not permit
11095 a body. This means that if we have a such a package, as in:
11096
11097 @smallexample
11098 @group
11099 @cartouche
11100 @b{package} Definitions @b{is}
11101    @b{generic}
11102       @b{type} m @b{is new} integer;
11103    @b{package} Subp @b{is}
11104       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11105       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11106    @b{end} Subp;
11107 @b{end} Definitions;
11108 @end cartouche
11109 @end group
11110 @end smallexample
11111
11112 @noindent
11113 A package that @code{with}'s @code{Definitions} may safely instantiate
11114 @code{Definitions.Subp} because the compiler can determine that there
11115 definitely is no package body to worry about in this case
11116
11117 @item pragma Pure
11118 @cindex pragma Pure
11119 @findex Pure
11120 Places sufficient restrictions on a unit to guarantee that
11121 no call to any subprogram in the unit can result in an
11122 elaboration problem. This means that the compiler does not need
11123 to worry about the point of elaboration of such units, and in
11124 particular, does not need to check any calls to any subprograms
11125 in this unit.
11126
11127 @item pragma Preelaborate
11128 @findex Preelaborate
11129 @cindex pragma Preelaborate
11130 This pragma places slightly less stringent restrictions on a unit than
11131 does pragma Pure,
11132 but these restrictions are still sufficient to ensure that there
11133 are no elaboration problems with any calls to the unit.
11134
11135 @item pragma Elaborate_Body
11136 @findex Elaborate_Body
11137 @cindex pragma Elaborate_Body
11138 This pragma requires that the body of a unit be elaborated immediately
11139 after its spec. Suppose a unit @code{A} has such a pragma,
11140 and unit @code{B} does
11141 a @code{with} of unit @code{A}. Recall that the standard rules require
11142 the spec of unit @code{A}
11143 to be elaborated before the @code{with}'ing unit; given the pragma in
11144 @code{A}, we also know that the body of @code{A}
11145 will be elaborated before @code{B}, so
11146 that calls to @code{A} are safe and do not need a check.
11147 @end table
11148
11149 @noindent
11150 Note that,
11151 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11152 the use of
11153 @code{Elaborate_Body} does not guarantee that the program is
11154 free of elaboration problems, because it may not be possible
11155 to satisfy the requested elaboration order.
11156 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11157 If a programmer
11158 marks @code{Unit_1} as @code{Elaborate_Body},
11159 and not @code{Unit_2,} then the order of
11160 elaboration will be:
11161
11162 @smallexample
11163 @group
11164 Spec of Unit_2
11165 Spec of Unit_1
11166 Body of Unit_1
11167 Body of Unit_2
11168 @end group
11169 @end smallexample
11170
11171 @noindent
11172 Now that means that the call to @code{Func_1} in @code{Unit_2}
11173 need not be checked,
11174 it must be safe. But the call to @code{Func_2} in
11175 @code{Unit_1} may still fail if
11176 @code{Expression_1} is equal to 1,
11177 and the programmer must still take
11178 responsibility for this not being the case.
11179
11180 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11181 eliminated, except for calls entirely within a body, which are
11182 in any case fully under programmer control. However, using the pragma
11183 everywhere is not always possible.
11184 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11185 we marked both of them as having pragma @code{Elaborate_Body}, then
11186 clearly there would be no possible elaboration order.
11187
11188 The above pragmas allow a server to guarantee safe use by clients, and
11189 clearly this is the preferable approach. Consequently a good rule in
11190 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11191 and if this is not possible,
11192 mark them as @code{Elaborate_Body} if possible.
11193 As we have seen, there are situations where neither of these
11194 three pragmas can be used.
11195 So we also provide methods for clients to control the
11196 order of elaboration of the servers on which they depend:
11197
11198 @table @asis
11199 @item pragma Elaborate (unit)
11200 @findex Elaborate
11201 @cindex pragma Elaborate
11202 This pragma is placed in the context clause, after a @code{with} clause,
11203 and it requires that the body of the named unit be elaborated before
11204 the unit in which the pragma occurs. The idea is to use this pragma
11205 if the current unit calls at elaboration time, directly or indirectly,
11206 some subprogram in the named unit.
11207
11208 @item pragma Elaborate_All (unit)
11209 @findex Elaborate_All
11210 @cindex pragma Elaborate_All
11211 This is a stronger version of the Elaborate pragma. Consider the
11212 following example:
11213
11214 @smallexample
11215 Unit A @code{with}'s unit B and calls B.Func in elab code
11216 Unit B @code{with}'s unit C, and B.Func calls C.Func
11217 @end smallexample
11218
11219 @noindent
11220 Now if we put a pragma @code{Elaborate (B)}
11221 in unit @code{A}, this ensures that the
11222 body of @code{B} is elaborated before the call, but not the
11223 body of @code{C}, so
11224 the call to @code{C.Func} could still cause @code{Program_Error} to
11225 be raised.
11226
11227 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11228 not only that the body of the named unit be elaborated before the
11229 unit doing the @code{with}, but also the bodies of all units that the
11230 named unit uses, following @code{with} links transitively. For example,
11231 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11232 then it requires
11233 not only that the body of @code{B} be elaborated before @code{A},
11234 but also the
11235 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11236 @end table
11237
11238 @noindent
11239 We are now in a position to give a usage rule in Ada 95 for avoiding
11240 elaboration problems, at least if dynamic dispatching and access to
11241 subprogram values are not used. We will handle these cases separately
11242 later.
11243
11244 The rule is simple. If a unit has elaboration code that can directly or
11245 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11246 a generic unit in a @code{with}'ed unit,
11247 then if the @code{with}'ed unit does not have
11248 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11249 a pragma @code{Elaborate_All}
11250 for the @code{with}'ed unit. By following this rule a client is
11251 assured that calls can be made without risk of an exception.
11252 If this rule is not followed, then a program may be in one of four
11253 states:
11254
11255 @table @asis
11256 @item No order exists
11257 No order of elaboration exists which follows the rules, taking into
11258 account any @code{Elaborate}, @code{Elaborate_All},
11259 or @code{Elaborate_Body} pragmas. In
11260 this case, an Ada 95 compiler must diagnose the situation at bind
11261 time, and refuse to build an executable program.
11262
11263 @item One or more orders exist, all incorrect
11264 One or more acceptable elaboration orders exists, and all of them
11265 generate an elaboration order problem. In this case, the binder
11266 can build an executable program, but @code{Program_Error} will be raised
11267 when the program is run.
11268
11269 @item Several orders exist, some right, some incorrect
11270 One or more acceptable elaboration orders exists, and some of them
11271 work, and some do not. The programmer has not controlled
11272 the order of elaboration, so the binder may or may not pick one of
11273 the correct orders, and the program may or may not raise an
11274 exception when it is run. This is the worst case, because it means
11275 that the program may fail when moved to another compiler, or even
11276 another version of the same compiler.
11277
11278 @item One or more orders exists, all correct
11279 One ore more acceptable elaboration orders exist, and all of them
11280 work. In this case the program runs successfully. This state of
11281 affairs can be guaranteed by following the rule we gave above, but
11282 may be true even if the rule is not followed.
11283 @end table
11284
11285 @noindent
11286 Note that one additional advantage of following our Elaborate_All rule
11287 is that the program continues to stay in the ideal (all orders OK) state
11288 even if maintenance
11289 changes some bodies of some subprograms. Conversely, if a program that does
11290 not follow this rule happens to be safe at some point, this state of affairs
11291 may deteriorate silently as a result of maintenance changes.
11292
11293 You may have noticed that the above discussion did not mention
11294 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11295 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11296 code in the body makes calls to some other unit, so it is still necessary
11297 to use @code{Elaborate_All} on such units.
11298
11299 @node Controlling Elaboration in GNAT - Internal Calls
11300 @section Controlling Elaboration in GNAT - Internal Calls
11301
11302 @noindent
11303 In the case of internal calls, i.e. calls within a single package, the
11304 programmer has full control over the order of elaboration, and it is up
11305 to the programmer to elaborate declarations in an appropriate order. For
11306 example writing:
11307
11308 @smallexample
11309 @group
11310 @cartouche
11311 @b{function} One @b{return} Float;
11312
11313 Q : Float := One;
11314
11315 @b{function} One @b{return} Float @b{is}
11316 @b{begin}
11317      return 1.0;
11318 @b{end} One;
11319 @end cartouche
11320 @end group
11321 @end smallexample
11322
11323 @noindent
11324 will obviously raise @code{Program_Error} at run time, because function
11325 One will be called before its body is elaborated. In this case GNAT will
11326 generate a warning that the call will raise @code{Program_Error}:
11327
11328 @smallexample
11329 @group
11330 @cartouche
11331  1. procedure y is
11332  2.    function One return Float;
11333  3.
11334  4.    Q : Float := One;
11335                     |
11336     >>> warning: cannot call "One" before body is elaborated
11337     >>> warning: Program_Error will be raised at run time
11338
11339  5.
11340  6.    function One return Float is
11341  7.    begin
11342  8.         return 1.0;
11343  9.    end One;
11344 10.
11345 11. begin
11346 12.    null;
11347 13. end;
11348 @end cartouche
11349 @end group
11350 @end smallexample
11351
11352 @noindent
11353 Note that in this particular case, it is likely that the call is safe, because
11354 the function @code{One} does not access any global variables.
11355 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11356 the contents of the body (think about the separate compilation case), so this
11357 is still wrong, as we discussed in the previous sections.
11358
11359 The error is easily corrected by rearranging the declarations so that the
11360 body of One appears before the declaration containing the call
11361 (note that in Ada 95,
11362 declarations can appear in any order, so there is no restriction that
11363 would prevent this reordering, and if we write:
11364
11365 @smallexample
11366 @group
11367 @cartouche
11368 @b{function} One @b{return} Float;
11369
11370 @b{function} One @b{return} Float @b{is}
11371 @b{begin}
11372      return 1.0;
11373 @b{end} One;
11374
11375 Q : Float := One;
11376 @end cartouche
11377 @end group
11378 @end smallexample
11379
11380 @noindent
11381 then all is well, no warning is generated, and no
11382 @code{Program_Error} exception
11383 will be raised.
11384 Things are more complicated when a chain of subprograms is executed:
11385
11386 @smallexample
11387 @group
11388 @cartouche
11389 @b{function} A @b{return} Integer;
11390 @b{function} B @b{return} Integer;
11391 @b{function} C @b{return} Integer;
11392
11393 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11394 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11395
11396 X : Integer := C;
11397
11398 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11399 @end cartouche
11400 @end group
11401 @end smallexample
11402
11403 @noindent
11404 Now the call to @code{C}
11405 at elaboration time in the declaration of @code{X} is correct, because
11406 the body of @code{C} is already elaborated,
11407 and the call to @code{B} within the body of
11408 @code{C} is correct, but the call
11409 to @code{A} within the body of @code{B} is incorrect, because the body
11410 of @code{A} has not been elaborated, so @code{Program_Error}
11411 will be raised on the call to @code{A}.
11412 In this case GNAT will generate a
11413 warning that @code{Program_Error} may be
11414 raised at the point of the call. Let's look at the warning:
11415
11416 @smallexample
11417 @group
11418 @cartouche
11419  1. procedure x is
11420  2.    function A return Integer;
11421  3.    function B return Integer;
11422  4.    function C return Integer;
11423  5.
11424  6.    function B return Integer is begin return A; end;
11425                                                     |
11426     >>> warning: call to "A" before body is elaborated may
11427                  raise Program_Error
11428     >>> warning: "B" called at line 7
11429     >>> warning: "C" called at line 9
11430
11431  7.    function C return Integer is begin return B; end;
11432  8.
11433  9.    X : Integer := C;
11434 10.
11435 11.    function A return Integer is begin return 1; end;
11436 12.
11437 13. begin
11438 14.    null;
11439 15. end;
11440 @end cartouche
11441 @end group
11442 @end smallexample
11443
11444 @noindent
11445 Note that the message here says "may raise", instead of the direct case,
11446 where the message says "will be raised". That's because whether
11447 @code{A} is
11448 actually called depends in general on run-time flow of control.
11449 For example, if the body of @code{B} said
11450
11451 @smallexample
11452 @group
11453 @cartouche
11454 @b{function} B @b{return} Integer @b{is}
11455 @b{begin}
11456    @b{if} some-condition-depending-on-input-data @b{then}
11457       @b{return} A;
11458    @b{else}
11459       @b{return} 1;
11460    @b{end if};
11461 @b{end} B;
11462 @end cartouche
11463 @end group
11464 @end smallexample
11465
11466 @noindent
11467 then we could not know until run time whether the incorrect call to A would
11468 actually occur, so @code{Program_Error} might
11469 or might not be raised. It is possible for a compiler to
11470 do a better job of analyzing bodies, to
11471 determine whether or not @code{Program_Error}
11472 might be raised, but it certainly
11473 couldn't do a perfect job (that would require solving the halting problem
11474 and is provably impossible), and because this is a warning anyway, it does
11475 not seem worth the effort to do the analysis. Cases in which it
11476 would be relevant are rare.
11477
11478 In practice, warnings of either of the forms given
11479 above will usually correspond to
11480 real errors, and should be examined carefully and eliminated.
11481 In the rare case where a warning is bogus, it can be suppressed by any of
11482 the following methods:
11483
11484 @itemize @bullet
11485 @item
11486 Compile with the @option{-gnatws} switch set
11487
11488 @item
11489 Suppress @code{Elaboration_Checks} for the called subprogram
11490
11491 @item
11492 Use pragma @code{Warnings_Off} to turn warnings off for the call
11493 @end itemize
11494
11495 @noindent
11496 For the internal elaboration check case,
11497 GNAT by default generates the
11498 necessary run-time checks to ensure
11499 that @code{Program_Error} is raised if any
11500 call fails an elaboration check. Of course this can only happen if a
11501 warning has been issued as described above. The use of pragma
11502 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11503 some of these checks, meaning that it may be possible (but is not
11504 guaranteed) for a program to be able to call a subprogram whose body
11505 is not yet elaborated, without raising a @code{Program_Error} exception.
11506
11507 @node Controlling Elaboration in GNAT - External Calls
11508 @section Controlling Elaboration in GNAT - External Calls
11509
11510 @noindent
11511 The previous section discussed the case in which the execution of a
11512 particular thread of elaboration code occurred entirely within a
11513 single unit. This is the easy case to handle, because a programmer
11514 has direct and total control over the order of elaboration, and
11515 furthermore, checks need only be generated in cases which are rare
11516 and which the compiler can easily detect.
11517 The situation is more complex when separate compilation is taken into account.
11518 Consider the following:
11519
11520 @smallexample
11521 @cartouche
11522 @group
11523 @b{package} Math @b{is}
11524    @b{function} Sqrt (Arg : Float) @b{return} Float;
11525 @b{end} Math;
11526
11527 @b{package body} Math @b{is}
11528    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11529    @b{begin}
11530          ...
11531    @b{end} Sqrt;
11532 @b{end} Math;
11533 @end group
11534 @group
11535 @b{with} Math;
11536 @b{package} Stuff @b{is}
11537    X : Float := Math.Sqrt (0.5);
11538 @b{end} Stuff;
11539
11540 @b{with} Stuff;
11541 @b{procedure} Main @b{is}
11542 @b{begin}
11543    ...
11544 @b{end} Main;
11545 @end group
11546 @end cartouche
11547 @end smallexample
11548
11549 @noindent
11550 where @code{Main} is the main program. When this program is executed, the
11551 elaboration code must first be executed, and one of the jobs of the
11552 binder is to determine the order in which the units of a program are
11553 to be elaborated. In this case we have four units: the spec and body
11554 of @code{Math},
11555 the spec of @code{Stuff} and the body of @code{Main}).
11556 In what order should the four separate sections of elaboration code
11557 be executed?
11558
11559 There are some restrictions in the order of elaboration that the binder
11560 can choose. In particular, if unit U has a @code{with}
11561 for a package @code{X}, then you
11562 are assured that the spec of @code{X}
11563 is elaborated before U , but you are
11564 not assured that the body of @code{X}
11565 is elaborated before U.
11566 This means that in the above case, the binder is allowed to choose the
11567 order:
11568
11569 @smallexample
11570 spec of Math
11571 spec of Stuff
11572 body of Math
11573 body of Main
11574 @end smallexample
11575
11576 @noindent
11577 but that's not good, because now the call to @code{Math.Sqrt}
11578 that happens during
11579 the elaboration of the @code{Stuff}
11580 spec happens before the body of @code{Math.Sqrt} is
11581 elaborated, and hence causes @code{Program_Error} exception to be raised.
11582 At first glance, one might say that the binder is misbehaving, because
11583 obviously you want to elaborate the body of something you @code{with}
11584 first, but
11585 that is not a general rule that can be followed in all cases. Consider
11586
11587 @smallexample
11588 @group
11589 @cartouche
11590 @b{package} X @b{is} ...
11591
11592 @b{package} Y @b{is} ...
11593
11594 @b{with} X;
11595 @b{package body} Y @b{is} ...
11596
11597 @b{with} Y;
11598 @b{package body} X @b{is} ...
11599 @end cartouche
11600 @end group
11601 @end smallexample
11602
11603 @noindent
11604 This is a common arrangement, and, apart from the order of elaboration
11605 problems that might arise in connection with elaboration code, this works fine.
11606 A rule that says that you must first elaborate the body of anything you
11607 @code{with} cannot work in this case:
11608 the body of @code{X} @code{with}'s @code{Y},
11609 which means you would have to
11610 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11611 which means
11612 you have to elaborate the body of @code{X} first, but ... and we have a
11613 loop that cannot be broken.
11614
11615 It is true that the binder can in many cases guess an order of elaboration
11616 that is unlikely to cause a @code{Program_Error}
11617 exception to be raised, and it tries to do so (in the
11618 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11619 by default
11620 elaborate the body of @code{Math} right after its spec, so all will be well).
11621
11622 However, a program that blindly relies on the binder to be helpful can
11623 get into trouble, as we discussed in the previous sections, so
11624 GNAT
11625 provides a number of facilities for assisting the programmer in
11626 developing programs that are robust with respect to elaboration order.
11627
11628 @node Default Behavior in GNAT - Ensuring Safety
11629 @section Default Behavior in GNAT - Ensuring Safety
11630
11631 @noindent
11632 The default behavior in GNAT ensures elaboration safety. In its
11633 default mode GNAT implements the
11634 rule we previously described as the right approach. Let's restate it:
11635
11636 @itemize
11637 @item
11638 @emph{If a unit has elaboration code that can directly or indirectly make a
11639 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11640 in a @code{with}'ed unit, then if the @code{with}'ed unit
11641 does not have pragma @code{Pure} or
11642 @code{Preelaborate}, then the client should have an
11643 @code{Elaborate_All} for the @code{with}'ed unit.}
11644 @end itemize
11645
11646 @noindent
11647 By following this rule a client
11648 is assured that calls and instantiations can be made without risk of an exception.
11649
11650 In this mode GNAT traces all calls that are potentially made from
11651 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11652 pragmas.
11653 The advantage of this approach is that no elaboration problems
11654 are possible if the binder can find an elaboration order that is
11655 consistent with these implicit @code{Elaborate_All} pragmas. The
11656 disadvantage of this approach is that no such order may exist.
11657
11658 If the binder does not generate any diagnostics, then it means that it
11659 has found an elaboration order that is guaranteed to be safe. However,
11660 the binder may still be relying on implicitly generated
11661 @code{Elaborate_All} pragmas so portability to other compilers than
11662 GNAT is not guaranteed.
11663
11664 If it is important to guarantee portability, then the compilations should
11665 use the
11666 @option{-gnatwl}
11667 (warn on elaboration problems) switch. This will cause warning messages
11668 to be generated indicating the missing @code{Elaborate_All} pragmas.
11669 Consider the following source program:
11670
11671 @smallexample
11672 @group
11673 @cartouche
11674 @b{with} k;
11675 @b{package} j @b{is}
11676   m : integer := k.r;
11677 @b{end};
11678 @end cartouche
11679 @end group
11680 @end smallexample
11681
11682 @noindent
11683 where it is clear that there
11684 should be a pragma @code{Elaborate_All}
11685 for unit @code{k}. An implicit pragma will be generated, and it is
11686 likely that the binder will be able to honor it. However,
11687 it is safer to include the pragma explicitly in the source. If this
11688 unit is compiled with the
11689 @option{-gnatwl}
11690 switch, then the compiler outputs a warning:
11691
11692 @smallexample
11693 @group
11694 @cartouche
11695 1. with k;
11696 2. package j is
11697 3.   m : integer := k.r;
11698                      |
11699    >>> warning: call to "r" may raise Program_Error
11700    >>> warning: missing pragma Elaborate_All for "k"
11701
11702 4. end;
11703 @end cartouche
11704 @end group
11705 @end smallexample
11706
11707 @noindent
11708 and these warnings can be used as a guide for supplying manually
11709 the missing pragmas.
11710
11711 This default mode is more restrictive than the Ada Reference
11712 Manual, and it is possible to construct programs which will compile
11713 using the dynamic model described there, but will run into a
11714 circularity using the safer static model we have described.
11715
11716 Of course any Ada compiler must be able to operate in a mode
11717 consistent with the requirements of the Ada Reference Manual,
11718 and in particular must have the capability of implementing the
11719 standard dynamic model of elaboration with run-time checks.
11720
11721 In GNAT, this standard mode can be achieved either by the use of
11722 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11723 command, or by the use of the configuration pragma:
11724
11725 @smallexample
11726 pragma Elaboration_Checks (RM);
11727 @end smallexample
11728
11729 @noindent
11730 Either approach will cause the unit affected to be compiled using the
11731 standard dynamic run-time elaboration checks described in the Ada
11732 Reference Manual. The static model is generally preferable, since it
11733 is clearly safer to rely on compile and link time checks rather than
11734 run-time checks. However, in the case of legacy code, it may be
11735 difficult to meet the requirements of the static model. This
11736 issue is further discussed in
11737 @ref{What to Do If the Default Elaboration Behavior Fails}.
11738
11739 Note that the static model provides a strict subset of the allowed
11740 behavior and programs of the Ada Reference Manual, so if you do
11741 adhere to the static model and no circularities exist,
11742 then you are assured that your program will
11743 work using the dynamic model.
11744
11745 @node Elaboration Issues for Library Tasks
11746 @section Elaboration Issues for Library Tasks
11747 @cindex Library tasks, elaboration issues
11748 @cindex Elaboration of library tasks
11749
11750 @noindent
11751 In this section we examine special elaboration issues that arise for
11752 programs that declare library level tasks.
11753
11754 Generally the model of execution of an Ada program is that all units are
11755 elaborated, and then execution of the program starts. However, the
11756 declaration of library tasks definitely does not fit this model. The
11757 reason for this is that library tasks start as soon as they are declared
11758 (more precisely, as soon as the statement part of the enclosing package
11759 body is reached), that is to say before elaboration
11760 of the program is complete. This means that if such a task calls a
11761 subprogram, or an entry in another task, the callee may or may not be
11762 elaborated yet, and in the standard
11763 Reference Manual model of dynamic elaboration checks, you can even
11764 get timing dependent Program_Error exceptions, since there can be
11765 a race between the elaboration code and the task code.
11766
11767 The static model of elaboration in GNAT seeks to avoid all such
11768 dynamic behavior, by being conservative, and the conservative
11769 approach in this particular case is to assume that all the code
11770 in a task body is potentially executed at elaboration time if
11771 a task is declared at the library level.
11772
11773 This can definitely result in unexpected circularities. Consider
11774 the following example
11775
11776 @smallexample
11777 package Decls is
11778   task Lib_Task is
11779      entry Start;
11780   end Lib_Task;
11781
11782   type My_Int is new Integer;
11783
11784   function Ident (M : My_Int) return My_Int;
11785 end Decls;
11786
11787 with Utils;
11788 package body Decls is
11789   task body Lib_Task is
11790   begin
11791      accept Start;
11792      Utils.Put_Val (2);
11793   end Lib_Task;
11794
11795   function Ident (M : My_Int) return My_Int is
11796   begin
11797      return M;
11798   end Ident;
11799 end Decls;
11800
11801 with Decls;
11802 package Utils is
11803   procedure Put_Val (Arg : Decls.My_Int);
11804 end Utils;
11805
11806 with Text_IO;
11807 package body Utils is
11808   procedure Put_Val (Arg : Decls.My_Int) is
11809   begin
11810      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11811   end Put_Val;
11812 end Utils;
11813
11814 with Decls;
11815 procedure Main is
11816 begin
11817    Decls.Lib_Task.Start;
11818 end;
11819 @end smallexample
11820
11821 @noindent
11822 If the above example is compiled in the default static elaboration
11823 mode, then a circularity occurs. The circularity comes from the call
11824 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11825 this call occurs in elaboration code, we need an implicit pragma
11826 @code{Elaborate_All} for @code{Utils}. This means that not only must
11827 the spec and body of @code{Utils} be elaborated before the body
11828 of @code{Decls}, but also the spec and body of any unit that is
11829 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11830 the body of @code{Decls}. This is the transitive implication of
11831 pragma @code{Elaborate_All} and it makes sense, because in general
11832 the body of @code{Put_Val} might have a call to something in a
11833 @code{with'ed} unit.
11834
11835 In this case, the body of Utils (actually its spec) @code{with's}
11836 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11837 must be elaborated before itself, in case there is a call from the
11838 body of @code{Utils}.
11839
11840 Here is the exact chain of events we are worrying about:
11841
11842 @enumerate
11843 @item
11844 In the body of @code{Decls} a call is made from within the body of a library
11845 task to a subprogram in the package @code{Utils}. Since this call may
11846 occur at elaboration time (given that the task is activated at elaboration
11847 time), we have to assume the worst, i.e. that the
11848 call does happen at elaboration time.
11849
11850 @item
11851 This means that the body and spec of @code{Util} must be elaborated before
11852 the body of @code{Decls} so that this call does not cause an access before
11853 elaboration.
11854
11855 @item
11856 Within the body of @code{Util}, specifically within the body of
11857 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11858 by this package.
11859
11860 @item
11861 One such @code{with}'ed package is package @code{Decls}, so there
11862 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11863 In fact there is such a call in this example, but we would have to
11864 assume that there was such a call even if it were not there, since
11865 we are not supposed to write the body of @code{Decls} knowing what
11866 is in the body of @code{Utils}; certainly in the case of the
11867 static elaboration model, the compiler does not know what is in
11868 other bodies and must assume the worst.
11869
11870 @item
11871 This means that the spec and body of @code{Decls} must also be
11872 elaborated before we elaborate the unit containing the call, but
11873 that unit is @code{Decls}! This means that the body of @code{Decls}
11874 must be elaborated before itself, and that's a circularity.
11875 @end enumerate
11876
11877 @noindent
11878 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11879 the body of @code{Decls} you will get a true Ada Reference Manual
11880 circularity that makes the program illegal.
11881
11882 In practice, we have found that problems with the static model of
11883 elaboration in existing code often arise from library tasks, so
11884 we must address this particular situation.
11885
11886 Note that if we compile and run the program above, using the dynamic model of
11887 elaboration (that is to say use the @option{-gnatE} switch),
11888 then it compiles, binds,
11889 links, and runs, printing the expected result of 2. Therefore in some sense
11890 the circularity here is only apparent, and we need to capture
11891 the properties of this program that  distinguish it from other library-level
11892 tasks that have real elaboration problems.
11893
11894 We have four possible answers to this question:
11895
11896 @itemize @bullet
11897
11898 @item
11899 Use the dynamic model of elaboration.
11900
11901 If we use the @option{-gnatE} switch, then as noted above, the program works.
11902 Why is this? If we examine the task body, it is apparent that the task cannot
11903 proceed past the
11904 @code{accept} statement until after elaboration has been completed, because
11905 the corresponding entry call comes from the main program, not earlier.
11906 This is why the dynamic model works here. But that's really giving
11907 up on a precise analysis, and we prefer to take this approach only if we cannot
11908 solve the
11909 problem in any other manner. So let us examine two ways to reorganize
11910 the program to avoid the potential elaboration problem.
11911
11912 @item
11913 Split library tasks into separate packages.
11914
11915 Write separate packages, so that library tasks are isolated from
11916 other declarations as much as possible. Let us look at a variation on
11917 the above program.
11918
11919 @smallexample
11920 package Decls1 is
11921   task Lib_Task is
11922      entry Start;
11923   end Lib_Task;
11924 end Decls1;
11925
11926 with Utils;
11927 package body Decls1 is
11928   task body Lib_Task is
11929   begin
11930      accept Start;
11931      Utils.Put_Val (2);
11932   end Lib_Task;
11933 end Decls1;
11934
11935 package Decls2 is
11936   type My_Int is new Integer;
11937   function Ident (M : My_Int) return My_Int;
11938 end Decls2;
11939
11940 with Utils;
11941 package body Decls2 is
11942   function Ident (M : My_Int) return My_Int is
11943   begin
11944      return M;
11945   end Ident;
11946 end Decls2;
11947
11948 with Decls2;
11949 package Utils is
11950   procedure Put_Val (Arg : Decls2.My_Int);
11951 end Utils;
11952
11953 with Text_IO;
11954 package body Utils is
11955   procedure Put_Val (Arg : Decls2.My_Int) is
11956   begin
11957      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
11958   end Put_Val;
11959 end Utils;
11960
11961 with Decls1;
11962 procedure Main is
11963 begin
11964    Decls1.Lib_Task.Start;
11965 end;
11966 @end smallexample
11967
11968 @noindent
11969 All we have done is to split @code{Decls} into two packages, one
11970 containing the library task, and one containing everything else. Now
11971 there is no cycle, and the program compiles, binds, links and executes
11972 using the default static model of elaboration.
11973
11974 @item
11975 Declare separate task types.
11976
11977 A significant part of the problem arises because of the use of the
11978 single task declaration form. This means that the elaboration of
11979 the task type, and the elaboration of the task itself (i.e. the
11980 creation of the task) happen at the same time. A good rule
11981 of style in Ada 95 is to always create explicit task types. By
11982 following the additional step of placing task objects in separate
11983 packages from the task type declaration, many elaboration problems
11984 are avoided. Here is another modified example of the example program:
11985
11986 @smallexample
11987 package Decls is
11988   task type Lib_Task_Type is
11989      entry Start;
11990   end Lib_Task_Type;
11991
11992   type My_Int is new Integer;
11993
11994   function Ident (M : My_Int) return My_Int;
11995 end Decls;
11996
11997 with Utils;
11998 package body Decls is
11999   task body Lib_Task_Type is
12000   begin
12001      accept Start;
12002      Utils.Put_Val (2);
12003   end Lib_Task_Type;
12004
12005   function Ident (M : My_Int) return My_Int is
12006   begin
12007      return M;
12008   end Ident;
12009 end Decls;
12010
12011 with Decls;
12012 package Utils is
12013   procedure Put_Val (Arg : Decls.My_Int);
12014 end Utils;
12015
12016 with Text_IO;
12017 package body Utils is
12018   procedure Put_Val (Arg : Decls.My_Int) is
12019   begin
12020      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12021   end Put_Val;
12022 end Utils;
12023
12024 with Decls;
12025 package Declst is
12026    Lib_Task : Decls.Lib_Task_Type;
12027 end Declst;
12028
12029 with Declst;
12030 procedure Main is
12031 begin
12032    Declst.Lib_Task.Start;
12033 end;
12034 @end smallexample
12035
12036 @noindent
12037 What we have done here is to replace the @code{task} declaration in
12038 package @code{Decls} with a @code{task type} declaration. Then we
12039 introduce a separate package @code{Declst} to contain the actual
12040 task object. This separates the elaboration issues for
12041 the @code{task type}
12042 declaration, which causes no trouble, from the elaboration issues
12043 of the task object, which is also unproblematic, since it is now independent
12044 of the elaboration of  @code{Utils}.
12045 This separation of concerns also corresponds to
12046 a generally sound engineering principle of separating declarations
12047 from instances. This version of the program also compiles, binds, links,
12048 and executes, generating the expected output.
12049
12050 @item
12051 Use No_Entry_Calls_In_Elaboration_Code restriction.
12052 @cindex No_Entry_Calls_In_Elaboration_Code
12053
12054 The previous two approaches described how a program can be restructured
12055 to avoid the special problems caused by library task bodies. in practice,
12056 however, such restructuring may be difficult to apply to existing legacy code,
12057 so we must consider solutions that do not require massive rewriting.
12058
12059 Let us consider more carefully why our original sample program works
12060 under the dynamic model of elaboration. The reason is that the code
12061 in the task body blocks immediately on the @code{accept}
12062 statement. Now of course there is nothing to prohibit elaboration
12063 code from making entry calls (for example from another library level task),
12064 so we cannot tell in isolation that
12065 the task will not execute the accept statement  during elaboration.
12066
12067 However, in practice it is very unusual to see elaboration code
12068 make any entry calls, and the pattern of tasks starting
12069 at elaboration time and then immediately blocking on @code{accept} or
12070 @code{select} statements is very common. What this means is that
12071 the compiler is being too pessimistic when it analyzes the
12072 whole package body as though it might be executed at elaboration
12073 time.
12074
12075 If we know that the elaboration code contains no entry calls, (a very safe
12076 assumption most of the time, that could almost be made the default
12077 behavior), then we can compile all units of the program under control
12078 of the following configuration pragma:
12079
12080 @smallexample
12081 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12082 @end smallexample
12083
12084 @noindent
12085 This pragma can be placed in the @file{gnat.adc} file in the usual
12086 manner. If we take our original unmodified program and compile it
12087 in the presence of a @file{gnat.adc} containing the above pragma,
12088 then once again, we can compile, bind, link, and execute, obtaining
12089 the expected result. In the presence of this pragma, the compiler does
12090 not trace calls in a task body, that appear after the first @code{accept}
12091 or @code{select} statement, and therefore does not report a potential
12092 circularity in the original program.
12093
12094 The compiler will check to the extent it can that the above
12095 restriction is not violated, but it is not always possible to do a
12096 complete check at compile time, so it is important to use this
12097 pragma only if the stated restriction is in fact met, that is to say
12098 no task receives an entry call before elaboration of all units is completed.
12099
12100 @end itemize
12101
12102 @node Mixing Elaboration Models
12103 @section Mixing Elaboration Models
12104 @noindent
12105 So far, we have assumed that the entire program is either compiled
12106 using the dynamic model or static model, ensuring consistency. It
12107 is possible to mix the two models, but rules have to be followed
12108 if this mixing is done to ensure that elaboration checks are not
12109 omitted.
12110
12111 The basic rule is that @emph{a unit compiled with the static model cannot
12112 be @code{with'ed} by a unit compiled with the dynamic model}. The
12113 reason for this is that in the static model, a unit assumes that
12114 its clients guarantee to use (the equivalent of) pragma
12115 @code{Elaborate_All} so that no elaboration checks are required
12116 in inner subprograms, and this assumption is violated if the
12117 client is compiled with dynamic checks.
12118
12119 The precise rule is as follows. A unit that is compiled with dynamic
12120 checks can only @code{with} a unit that meets at least one of the
12121 following criteria:
12122
12123 @itemize @bullet
12124
12125 @item
12126 The @code{with'ed} unit is itself compiled with dynamic elaboration
12127 checks (that is with the @option{-gnatE} switch.
12128
12129 @item
12130 The @code{with'ed} unit is an internal GNAT implementation unit from
12131 the System, Interfaces, Ada, or GNAT hierarchies.
12132
12133 @item
12134 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12135
12136 @item
12137 The @code{with'ing} unit (that is the client) has an explicit pragma
12138 @code{Elaborate_All} for the @code{with'ed} unit.
12139
12140 @end itemize
12141
12142 @noindent
12143 If this rule is violated, that is if a unit with dynamic elaboration
12144 checks @code{with's} a unit that does not meet one of the above four
12145 criteria, then the binder (@code{gnatbind}) will issue a warning
12146 similar to that in the following example:
12147
12148 @smallexample
12149 warning: "x.ads" has dynamic elaboration checks and with's
12150 warning:   "y.ads" which has static elaboration checks
12151 @end smallexample
12152
12153 @noindent
12154 These warnings indicate that the rule has been violated, and that as a result
12155 elaboration checks may be missed in the resulting executable file.
12156 This warning may be suppressed using the @code{-ws} binder switch
12157 in the usual manner.
12158
12159 One useful application of this mixing rule is in the case of a subsystem
12160 which does not itself @code{with} units from the remainder of the
12161 application. In this case, the entire subsystem can be compiled with
12162 dynamic checks to resolve a circularity in the subsystem, while
12163 allowing the main application that uses this subsystem to be compiled
12164 using the more reliable default static model.
12165
12166 @node What to Do If the Default Elaboration Behavior Fails
12167 @section What to Do If the Default Elaboration Behavior Fails
12168
12169 @noindent
12170 If the binder cannot find an acceptable order, it outputs detailed
12171 diagnostics. For example:
12172 @smallexample
12173 @group
12174 @iftex
12175 @leftskip=0cm
12176 @end iftex
12177 error: elaboration circularity detected
12178 info:   "proc (body)" must be elaborated before "pack (body)"
12179 info:     reason: Elaborate_All probably needed in unit "pack (body)"
12180 info:     recompile "pack (body)" with -gnatwl
12181 info:                             for full details
12182 info:       "proc (body)"
12183 info:         is needed by its spec:
12184 info:       "proc (spec)"
12185 info:         which is withed by:
12186 info:       "pack (body)"
12187 info:  "pack (body)" must be elaborated before "proc (body)"
12188 info:     reason: pragma Elaborate in unit "proc (body)"
12189 @end group
12190
12191 @end smallexample
12192
12193 @noindent
12194 In this case we have a cycle that the binder cannot break. On the one
12195 hand, there is an explicit pragma Elaborate in @code{proc} for
12196 @code{pack}. This means that the body of @code{pack} must be elaborated
12197 before the body of @code{proc}. On the other hand, there is elaboration
12198 code in @code{pack} that calls a subprogram in @code{proc}. This means
12199 that for maximum safety, there should really be a pragma
12200 Elaborate_All in @code{pack} for @code{proc} which would require that
12201 the body of @code{proc} be elaborated before the body of
12202 @code{pack}. Clearly both requirements cannot be satisfied.
12203 Faced with a circularity of this kind, you have three different options.
12204
12205 @table @asis
12206 @item Fix the program
12207 The most desirable option from the point of view of long-term maintenance
12208 is to rearrange the program so that the elaboration problems are avoided.
12209 One useful technique is to place the elaboration code into separate
12210 child packages. Another is to move some of the initialization code to
12211 explicitly called subprograms, where the program controls the order
12212 of initialization explicitly. Although this is the most desirable option,
12213 it may be impractical and involve too much modification, especially in
12214 the case of complex legacy code.
12215
12216 @item Perform dynamic checks
12217 If the compilations are done using the
12218 @option{-gnatE}
12219 (dynamic elaboration check) switch, then GNAT behaves in
12220 a quite different manner. Dynamic checks are generated for all calls
12221 that could possibly result in raising an exception. With this switch,
12222 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12223 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12224 The binder will generate an executable program that may or may not
12225 raise @code{Program_Error}, and then it is the programmer's job to ensure
12226 that it does not raise an exception. Note that it is important to
12227 compile all units with the switch, it cannot be used selectively.
12228
12229 @item Suppress checks
12230 The drawback of dynamic checks is that they generate a
12231 significant overhead at run time, both in space and time. If you
12232 are absolutely sure that your program cannot raise any elaboration
12233 exceptions, and you still want to use the dynamic elaboration model,
12234 then you can use the configuration pragma
12235 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12236 example this pragma could be placed in the @file{gnat.adc} file.
12237
12238 @item Suppress checks selectively
12239 When you know that certain calls in elaboration code cannot possibly
12240 lead to an elaboration error, and the binder nevertheless generates warnings
12241 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12242 circularities, it is possible to remove those warnings locally and obtain
12243 a program that will bind. Clearly this can be unsafe, and it is the
12244 responsibility of the programmer to make sure that the resulting program has
12245 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12246 be used with different granularity to suppress warnings and break
12247 elaboration circularities:
12248
12249 @itemize @bullet
12250 @item
12251 Place the pragma that names the called subprogram in the declarative part
12252 that contains the call.
12253
12254 @item
12255 Place the pragma in the declarative part, without naming an entity. This
12256 disables warnings on all calls in the corresponding  declarative region.
12257
12258 @item
12259 Place the pragma in the package spec that declares the called subprogram,
12260 and name the subprogram. This disables warnings on all elaboration calls to
12261 that subprogram.
12262
12263 @item
12264 Place the pragma in the package spec that declares the called subprogram,
12265 without naming any entity. This disables warnings on all elaboration calls to
12266 all subprograms declared in this spec.
12267 @end itemize
12268
12269 @noindent
12270 These four cases are listed in order of decreasing safety, and therefore
12271 require increasing programmer care in their application. Consider the
12272 following program:
12273 @smallexample
12274
12275 package Pack1 is
12276   function F1 return Integer;
12277   X1 : Integer;
12278 end Pack1;
12279
12280 package Pack2 is
12281   function F2 return Integer;
12282   function Pure (x : integer) return integer;
12283   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
12284   --  pragma Suppress (Elaboration_Check);              -- (4)
12285 end Pack2;
12286
12287 with Pack2;
12288 package body Pack1 is
12289   function F1 return Integer is
12290   begin
12291     return 100;
12292   end F1;
12293   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
12294 begin
12295   declare
12296     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
12297     --  pragma Suppress(Elaboration_Check);             -- (2)
12298   begin
12299     X1 := Pack2.F2 + 1;                --  Elab. call (2)
12300   end;
12301 end Pack1;
12302
12303 with Pack1;
12304 package body Pack2 is
12305   function F2 return Integer is
12306   begin
12307      return Pack1.F1;
12308   end F2;
12309   function Pure (x : integer) return integer is
12310   begin
12311      return x ** 3 - 3 * x;
12312   end;
12313 end Pack2;
12314
12315 with Pack1, Ada.Text_IO;
12316 procedure Proc3 is
12317 begin
12318   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12319 end Proc3;
12320 @end smallexample
12321 In the absence of any pragmas, an attempt to bind this program produces
12322 the following diagnostics:
12323 @smallexample
12324 @group
12325 @iftex
12326 @leftskip=.5cm
12327 @end iftex
12328 error: elaboration circularity detected
12329 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
12330 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
12331 info:       recompile "pack1 (body)" with -gnatwl for full details
12332 info:          "pack1 (body)"
12333 info:             must be elaborated along with its spec:
12334 info:          "pack1 (spec)"
12335 info:             which is withed by:
12336 info:          "pack2 (body)"
12337 info:             which must be elaborated along with its spec:
12338 info:          "pack2 (spec)"
12339 info:             which is withed by:
12340 info:          "pack1 (body)"
12341 @end group
12342 @end smallexample
12343 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12344 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12345 F2 is safe, even though F2 calls F1, because the call appears after the
12346 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12347 remove the warning on the call. It is also possible to use pragma (2)
12348 because there are no other potentially unsafe calls in the block.
12349
12350 @noindent
12351 The call to @code{Pure} is safe because this function does not depend on the
12352 state of @code{Pack2}. Therefore any call to this function is safe, and it
12353 is correct to place pragma (3) in the corresponding package spec.
12354
12355 @noindent
12356 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12357 warnings on all calls to functions declared therein. Note that this is not
12358 necessarily safe, and requires more detailed examination of the subprogram
12359 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12360 be already elaborated.
12361 @end table
12362
12363 @noindent
12364 It is hard to generalize on which of these four approaches should be
12365 taken. Obviously if it is possible to fix the program so that the default
12366 treatment works, this is preferable, but this may not always be practical.
12367 It is certainly simple enough to use
12368 @option{-gnatE}
12369 but the danger in this case is that, even if the GNAT binder
12370 finds a correct elaboration order, it may not always do so,
12371 and certainly a binder from another Ada compiler might not. A
12372 combination of testing and analysis (for which the warnings generated
12373 with the
12374 @option{-gnatwl}
12375 switch can be useful) must be used to ensure that the program is free
12376 of errors. One switch that is useful in this testing is the
12377 @code{-p (pessimistic elaboration order)}
12378 switch for
12379 @code{gnatbind}.
12380 Normally the binder tries to find an order that has the best chance of
12381 of avoiding elaboration problems. With this switch, the binder
12382 plays a devil's advocate role, and tries to choose the order that
12383 has the best chance of failing. If your program works even with this
12384 switch, then it has a better chance of being error free, but this is still
12385 not a guarantee.
12386
12387 For an example of this approach in action, consider the C-tests (executable
12388 tests) from the ACVC suite. If these are compiled and run with the default
12389 treatment, then all but one of them succeed without generating any error
12390 diagnostics from the binder. However, there is one test that fails, and
12391 this is not surprising, because the whole point of this test is to ensure
12392 that the compiler can handle cases where it is impossible to determine
12393 a correct order statically, and it checks that an exception is indeed
12394 raised at run time.
12395
12396 This one test must be compiled and run using the
12397 @option{-gnatE}
12398 switch, and then it passes. Alternatively, the entire suite can
12399 be run using this switch. It is never wrong to run with the dynamic
12400 elaboration switch if your code is correct, and we assume that the
12401 C-tests are indeed correct (it is less efficient, but efficiency is
12402 not a factor in running the ACVC tests.)
12403
12404 @node Elaboration for Access-to-Subprogram Values
12405 @section Elaboration for Access-to-Subprogram Values
12406 @cindex Access-to-subprogram
12407
12408 @noindent
12409 The introduction of access-to-subprogram types in Ada 95 complicates
12410 the handling of elaboration. The trouble is that it becomes
12411 impossible to tell at compile time which procedure
12412 is being called. This means that it is not possible for the binder
12413 to analyze the elaboration requirements in this case.
12414
12415 If at the point at which the access value is created
12416 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12417 the body of the subprogram is
12418 known to have been elaborated, then the access value is safe, and its use
12419 does not require a check. This may be achieved by appropriate arrangement
12420 of the order of declarations if the subprogram is in the current unit,
12421 or, if the subprogram is in another unit, by using pragma
12422 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12423 on the referenced unit.
12424
12425 If the referenced body is not known to have been elaborated at the point
12426 the access value is created, then any use of the access value must do a
12427 dynamic check, and this dynamic check will fail and raise a
12428 @code{Program_Error} exception if the body has not been elaborated yet.
12429 GNAT will generate the necessary checks, and in addition, if the
12430 @option{-gnatwl}
12431 switch is set, will generate warnings that such checks are required.
12432
12433 The use of dynamic dispatching for tagged types similarly generates
12434 a requirement for dynamic checks, and premature calls to any primitive
12435 operation of a tagged type before the body of the operation has been elaborated,
12436 will result in the raising of @code{Program_Error}.
12437
12438 @node Summary of Procedures for Elaboration Control
12439 @section Summary of Procedures for Elaboration Control
12440 @cindex Elaboration control
12441
12442 @noindent
12443 First, compile your program with the default options, using none of
12444 the special elaboration control switches. If the binder successfully
12445 binds your program, then you can be confident that, apart from issues
12446 raised by the use of access-to-subprogram types and dynamic dispatching,
12447 the program is free of elaboration errors. If it is important that the
12448 program be portable, then use the
12449 @option{-gnatwl}
12450 switch to generate warnings about missing @code{Elaborate_All}
12451 pragmas, and supply the missing pragmas.
12452
12453 If the program fails to bind using the default static elaboration
12454 handling, then you can fix the program to eliminate the binder
12455 message, or recompile the entire program with the
12456 @option{-gnatE} switch to generate dynamic elaboration checks,
12457 and, if you are sure there really are no elaboration problems,
12458 use a global pragma @code{Suppress (Elaboration_Checks)}.
12459
12460 @node Other Elaboration Order Considerations
12461 @section Other Elaboration Order Considerations
12462 @noindent
12463 This section has been entirely concerned with the issue of finding a valid
12464 elaboration order, as defined by the Ada Reference Manual. In a case
12465 where several elaboration orders are valid, the task is to find one
12466 of the possible valid elaboration orders (and the static model in GNAT
12467 will ensure that this is achieved).
12468
12469 The purpose of the elaboration rules in the Ada Reference Manual is to
12470 make sure that no entity is accessed before it has been elaborated. For
12471 a subprogram, this means that the spec and body must have been elaborated
12472 before the subprogram is called. For an object, this means that the object
12473 must have been elaborated before its value is read or written. A violation
12474 of either of these two requirements is an access before elaboration order,
12475 and this section has been all about avoiding such errors.
12476
12477 In the case where more than one order of elaboration is possible, in the
12478 sense that access before elaboration errors are avoided, then any one of
12479 the orders is "correct" in the sense that it meets the requirements of
12480 the Ada Reference Manual, and no such error occurs.
12481
12482 However, it may be the case for a given program, that there are
12483 constraints on the order of elaboration that come not from consideration
12484 of avoiding elaboration errors, but rather from extra-lingual logic
12485 requirements. Consider this example:
12486
12487 @smallexample
12488 with Init_Constants;
12489 package Constants is
12490    X : Integer := 0;
12491    Y : Integer := 0;
12492 end Constants;
12493
12494 package Init_Constants is
12495    procedure Calc;
12496 end Init_Constants;
12497
12498 with Constants;
12499 package body Init_Constants is
12500    procedure Calc is begin null; end;
12501 begin
12502    Constants.X := 3;
12503    Constants.Y := 4;
12504 end Init_Constants;
12505
12506 with Constants;
12507 package Calc is
12508    Z : Integer := Constants.X + Constants.Y;
12509 end Calc;
12510
12511 with Calc;
12512 with Text_IO; use Text_IO;
12513 procedure Main is
12514 begin
12515    Put_Line (Calc.Z'Img);
12516 end Main;
12517 @end smallexample
12518
12519 @noindent
12520 In this example, there is more than one valid order of elaboration. For
12521 example both the following are correct orders:
12522
12523 @smallexample
12524 Init_Constants spec
12525 Constants spec
12526 Calc spec
12527 Main body
12528 Init_Constants body
12529
12530   and
12531
12532 Init_Constants spec
12533 Init_Constants body
12534 Constants spec
12535 Calc spec
12536 Main body
12537 @end smallexample
12538
12539 @noindent
12540 There is no language rule to prefer one or the other, both are correct
12541 from an order of elaboration point of view. But the programmatic effects
12542 of the two orders are very different. In the first, the elaboration routine
12543 of @code{Calc} initializes @code{Z} to zero, and then the main program
12544 runs with this value of zero. But in the second order, the elaboration
12545 routine of @code{Calc} runs after the body of Init_Constants has set
12546 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12547 runs.
12548
12549 One could perhaps by applying pretty clever non-artificial intelligence
12550 to the situation guess that it is more likely that the second order of
12551 elaboration is the one desired, but there is no formal linguistic reason
12552 to prefer one over the other. In fact in this particular case, GNAT will
12553 prefer the second order, because of the rule that bodies are elaborated
12554 as soon as possible, but it's just luck that this is what was wanted
12555 (if indeed the second order was preferred).
12556
12557 If the program cares about the order of elaboration routines in a case like
12558 this, it is important to specify the order required. In this particular
12559 case, that could have been achieved by adding to the spec of Calc:
12560
12561 @smallexample
12562 pragma Elaborate_All (Constants);
12563 @end smallexample
12564
12565 @noindent
12566 which requires that the body (if any) and spec of @code{Constants},
12567 as well as the body and spec of any unit @code{with}'ed by
12568 @code{Constants} be elaborated before @code{Calc} is elaborated.
12569
12570 Clearly no automatic method can always guess which alternative you require,
12571 and if you are working with legacy code that had constraints of this kind
12572 which were not properly specified by adding @code{Elaborate} or
12573 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12574 compilers can choose different orders.
12575
12576 The @code{gnatbind}
12577 @code{-p} switch may be useful in smoking
12578 out problems. This switch causes bodies to be elaborated as late as possible
12579 instead of as early as possible. In the example above, it would have forced
12580 the choice of the first elaboration order. If you get different results
12581 when using this switch, and particularly if one set of results is right,
12582 and one is wrong as far as you are concerned, it shows that you have some
12583 missing @code{Elaborate} pragmas. For the example above, we have the
12584 following output:
12585
12586 @smallexample
12587 gnatmake -f -q main
12588 main
12589  7
12590 gnatmake -f -q main -bargs -p
12591 main
12592  0
12593 @end smallexample
12594
12595 @noindent
12596 It is of course quite unlikely that both these results are correct, so
12597 it is up to you in a case like this to investigate the source of the
12598 difference, by looking at the two elaboration orders that are chosen,
12599 and figuring out which is correct, and then adding the necessary
12600 @code{Elaborate_All} pragmas to ensure the desired order.
12601
12602 @node The Cross-Referencing Tools gnatxref and gnatfind
12603 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12604 @findex gnatxref
12605 @findex gnatfind
12606
12607 @noindent
12608 The compiler generates cross-referencing information (unless
12609 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12610 This information indicates where in the source each entity is declared and
12611 referenced. Note that entities in package Standard are not included, but
12612 entities in all other predefined units are included in the output.
12613
12614 Before using any of these two tools, you need to compile successfully your
12615 application, so that GNAT gets a chance to generate the cross-referencing
12616 information.
12617
12618 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12619 information to provide the user with the capability to easily locate the
12620 declaration and references to an entity. These tools are quite similar,
12621 the difference being that @code{gnatfind} is intended for locating
12622 definitions and/or references to a specified entity or entities, whereas
12623 @code{gnatxref} is oriented to generating a full report of all
12624 cross-references.
12625
12626 To use these tools, you must not compile your application using the
12627 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12628 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12629 information will not be generated.
12630
12631 @menu
12632 * gnatxref Switches::
12633 * gnatfind Switches::
12634 * Project Files for gnatxref and gnatfind::
12635 * Regular Expressions in gnatfind and gnatxref::
12636 * Examples of gnatxref Usage::
12637 * Examples of gnatfind Usage::
12638 @end menu
12639
12640 @node gnatxref Switches
12641 @section @code{gnatxref} Switches
12642
12643 @noindent
12644 The command lines for @code{gnatxref} is:
12645 @smallexample
12646 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12647 @end smallexample
12648
12649 @noindent
12650 where
12651
12652 @table @code
12653 @item sourcefile1, sourcefile2
12654 identifies the source files for which a report is to be generated. The
12655 'with'ed units will be processed too. You must provide at least one file.
12656
12657 These file names are considered to be regular expressions, so for instance
12658 specifying 'source*.adb' is the same as giving every file in the current
12659 directory whose name starts with 'source' and whose extension is 'adb'.
12660
12661 @end table
12662
12663 @noindent
12664 The switches can be :
12665 @table @code
12666 @item -a
12667 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12668 the read-only files found in the library search path. Otherwise, these files
12669 will be ignored. This option can be used to protect Gnat sources or your own
12670 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12671 much faster, and their output much smaller.
12672
12673 @item -aIDIR
12674 When looking for source files also look in directory DIR. The order in which
12675 source file search is undertaken is the same as for @file{gnatmake}.
12676
12677 @item -aODIR
12678 When searching for library and object files, look in directory
12679 DIR. The order in which library files are searched is the same as for
12680 @file{gnatmake}.
12681
12682 @item -nostdinc
12683 Do not look for sources in the system default directory.
12684
12685 @item -nostdlib
12686 Do not look for library files in the system default directory.
12687
12688 @item --RTS=@var{rts-path}
12689 @cindex @code{--RTS} (@code{gnatxref})
12690 Specifies the default location of the runtime library. Same meaning as the
12691 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12692
12693 @item -d
12694 If this switch is set @code{gnatxref} will output the parent type
12695 reference for each matching derived types.
12696
12697 @item -f
12698 If this switch is set, the output file names will be preceded by their
12699 directory (if the file was found in the search path). If this switch is
12700 not set, the directory will not be printed.
12701
12702 @item -g
12703 If this switch is set, information is output only for library-level
12704 entities, ignoring local entities. The use of this switch may accelerate
12705 @code{gnatfind} and @code{gnatxref}.
12706
12707 @item -IDIR
12708 Equivalent to @samp{-aODIR -aIDIR}.
12709
12710 @item -pFILE
12711 Specify a project file to use @xref{Project Files}.
12712 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12713 project file in the current directory.
12714
12715 If a project file is either specified or found by the tools, then the content
12716 of the source directory and object directory lines are added as if they
12717 had been specified respectively by @samp{-aI}
12718 and @samp{-aO}.
12719 @item -u
12720 Output only unused symbols. This may be really useful if you give your
12721 main compilation unit on the command line, as @code{gnatxref} will then
12722 display every unused entity and 'with'ed package.
12723
12724 @item -v
12725 Instead of producing the default output, @code{gnatxref} will generate a
12726 @file{tags} file that can be used by vi. For examples how to use this
12727 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12728 to the standard output, thus you will have to redirect it to a file.
12729
12730 @end table
12731
12732 All these switches may be in any order on the command line, and may even
12733 appear after the file names. They need not be separated by spaces, thus
12734 you can say @samp{gnatxref -ag} instead of
12735 @samp{gnatxref -a -g}.
12736
12737 @node gnatfind Switches
12738 @section @code{gnatfind} Switches
12739
12740 @noindent
12741 The command line for @code{gnatfind} is:
12742
12743 @smallexample
12744 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12745       [file1 file2 ...]
12746 @end smallexample
12747
12748 @noindent
12749 where
12750
12751 @table @code
12752 @item pattern
12753 An entity will be output only if it matches the regular expression found
12754 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12755
12756 Omitting the pattern is equivalent to specifying @samp{*}, which
12757 will match any entity. Note that if you do not provide a pattern, you
12758 have to provide both a sourcefile and a line.
12759
12760 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12761 for matching purposes. At the current time there is no support for
12762 8-bit codes other than Latin-1, or for wide characters in identifiers.
12763
12764 @item sourcefile
12765 @code{gnatfind} will look for references, bodies or declarations
12766 of symbols referenced in @file{sourcefile}, at line @samp{line}
12767 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12768 for syntax examples.
12769
12770 @item line
12771 is a decimal integer identifying the line number containing
12772 the reference to the entity (or entities) to be located.
12773
12774 @item column
12775 is a decimal integer identifying the exact location on the
12776 line of the first character of the identifier for the
12777 entity reference. Columns are numbered from 1.
12778
12779 @item file1 file2 ...
12780 The search will be restricted to these files. If none are given, then
12781 the search will be done for every library file in the search path.
12782 These file must appear only after the pattern or sourcefile.
12783
12784 These file names are considered to be regular expressions, so for instance
12785 specifying 'source*.adb' is the same as giving every file in the current
12786 directory whose name starts with 'source' and whose extension is 'adb'.
12787
12788 Not that if you specify at least one file in this part, @code{gnatfind} may
12789 sometimes not be able to find the body of the subprograms...
12790
12791 @end table
12792
12793 At least one of 'sourcefile' or 'pattern' has to be present on
12794 the command line.
12795
12796 The following switches are available:
12797 @table @code
12798
12799 @item -a
12800 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12801 the read-only files found in the library search path. Otherwise, these files
12802 will be ignored. This option can be used to protect Gnat sources or your own
12803 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12804 much faster, and their output much smaller.
12805
12806 @item -aIDIR
12807 When looking for source files also look in directory DIR. The order in which
12808 source file search is undertaken is the same as for @file{gnatmake}.
12809
12810 @item -aODIR
12811 When searching for library and object files, look in directory
12812 DIR. The order in which library files are searched is the same as for
12813 @file{gnatmake}.
12814
12815 @item -nostdinc
12816 Do not look for sources in the system default directory.
12817
12818 @item -nostdlib
12819 Do not look for library files in the system default directory.
12820
12821 @item --RTS=@var{rts-path}
12822 @cindex @code{--RTS} (@code{gnatfind})
12823 Specifies the default location of the runtime library. Same meaning as the
12824 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12825
12826 @item -d
12827 If this switch is set, then @code{gnatfind} will output the parent type
12828 reference for each matching derived types.
12829
12830 @item -e
12831 By default, @code{gnatfind} accept the simple regular expression set for
12832 @samp{pattern}. If this switch is set, then the pattern will be
12833 considered as full Unix-style regular expression.
12834
12835 @item -f
12836 If this switch is set, the output file names will be preceded by their
12837 directory (if the file was found in the search path). If this switch is
12838 not set, the directory will not be printed.
12839
12840 @item -g
12841 If this switch is set, information is output only for library-level
12842 entities, ignoring local entities. The use of this switch may accelerate
12843 @code{gnatfind} and @code{gnatxref}.
12844
12845 @item -IDIR
12846 Equivalent to @samp{-aODIR -aIDIR}.
12847
12848 @item -pFILE
12849 Specify a project file (@pxref{Project Files}) to use.
12850 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12851 project file in the current directory.
12852
12853 If a project file is either specified or found by the tools, then the content
12854 of the source directory and object directory lines are added as if they
12855 had been specified respectively by @samp{-aI} and
12856 @samp{-aO}.
12857
12858 @item -r
12859 By default, @code{gnatfind} will output only the information about the
12860 declaration, body or type completion of the entities. If this switch is
12861 set, the @code{gnatfind} will locate every reference to the entities in
12862 the files specified on the command line (or in every file in the search
12863 path if no file is given on the command line).
12864
12865 @item -s
12866 If this switch is set, then @code{gnatfind} will output the content
12867 of the Ada source file lines were the entity was found.
12868
12869 @item -t
12870 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12871 the specified type. It act like -d option but recursively from parent
12872 type to parent type. When this switch is set it is not possible to
12873 specify more than one file.
12874
12875 @end table
12876
12877 All these switches may be in any order on the command line, and may even
12878 appear after the file names. They need not be separated by spaces, thus
12879 you can say @samp{gnatxref -ag} instead of
12880 @samp{gnatxref -a -g}.
12881
12882 As stated previously, gnatfind will search in every directory in the
12883 search path. You can force it to look only in the current directory if
12884 you specify @code{*} at the end of the command line.
12885
12886
12887 @node Project Files for gnatxref and gnatfind
12888 @section Project Files for @command{gnatxref} and @command{gnatfind}
12889
12890 @noindent
12891 Project files allow a programmer to specify how to compile its
12892 application, where to find sources,... These files are used primarily by
12893 the Glide Ada mode, but they can also be used by the two tools
12894 @code{gnatxref} and @code{gnatfind}.
12895
12896 A project file name must end with @file{.adp}. If a single one is
12897 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12898 extract the information from it. If multiple project files are found, none of
12899 them is read, and you have to use the @samp{-p} switch to specify the one
12900 you want to use.
12901
12902 The following lines can be included, even though most of them have default
12903 values which can be used in most cases.
12904 The lines can be entered in any order in the file.
12905 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
12906 each line. If you have multiple instances, only the last one is taken into
12907 account.
12908
12909 @table @code
12910 @item src_dir=DIR         [default: "./"]
12911 specifies a directory where to look for source files. Multiple src_dir lines
12912 can be specified and they will be searched in the order they
12913 are specified.
12914
12915 @item obj_dir=DIR         [default: "./"]
12916 specifies a directory where to look for object and library files. Multiple
12917 obj_dir lines can be specified and they will be searched in the order they
12918 are specified
12919
12920 @item comp_opt=SWITCHES   [default: ""]
12921 creates a variable which can be referred to subsequently by using
12922 the @samp{$@{comp_opt@}} notation. This is intended to store the default
12923 switches given to @file{gnatmake} and @file{gcc}.
12924
12925 @item bind_opt=SWITCHES   [default: ""]
12926 creates a variable which can be referred to subsequently by using
12927 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12928 switches given to @file{gnatbind}.
12929
12930 @item link_opt=SWITCHES   [default: ""]
12931 creates a variable which can be referred to subsequently by using
12932 the @samp{$@{link_opt@}} notation. This is intended to store the default
12933 switches given to @file{gnatlink}.
12934
12935 @item main=EXECUTABLE     [default: ""]
12936 specifies the name of the executable for the application. This variable can
12937 be referred to in the following lines by using the @samp{$@{main@}} notation.
12938
12939 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
12940 specifies the command used to compile a single file in the application.
12941
12942 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
12943 specifies the command used to recompile the whole application.
12944
12945 @item run_cmd=COMMAND     [default: "$@{main@}"]
12946 specifies the command used to run the application.
12947
12948 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
12949 specifies the command used to debug the application
12950
12951 @end table
12952
12953 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
12954 and @samp{obj_dir} lines, and ignore the others.
12955
12956 @node Regular Expressions in gnatfind and gnatxref
12957 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12958
12959 @noindent
12960 As specified in the section about @code{gnatfind}, the pattern can be a
12961 regular expression. Actually, there are to set of regular expressions
12962 which are recognized by the program :
12963
12964 @table @code
12965 @item globbing patterns
12966 These are the most usual regular expression. They are the same that you
12967 generally used in a Unix shell command line, or in a DOS session.
12968
12969 Here is a more formal grammar :
12970 @smallexample
12971 @group
12972 @iftex
12973 @leftskip=.5cm
12974 @end iftex
12975 regexp ::= term
12976 term   ::= elmt            -- matches elmt
12977 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12978 term   ::= *               -- any string of 0 or more characters
12979 term   ::= ?               -- matches any character
12980 term   ::= [char @{char@}] -- matches any character listed
12981 term   ::= [char - char]   -- matches any character in range
12982 @end group
12983 @end smallexample
12984
12985 @item full regular expression
12986 The second set of regular expressions is much more powerful. This is the
12987 type of regular expressions recognized by utilities such a @file{grep}.
12988
12989 The following is the form of a regular expression, expressed in Ada
12990 reference manual style BNF is as follows
12991
12992 @smallexample
12993 @iftex
12994 @leftskip=.5cm
12995 @end iftex
12996 @group
12997 regexp ::= term @{| term@} -- alternation (term or term ...)
12998
12999 term ::= item @{item@}     -- concatenation (item then item)
13000
13001 item ::= elmt              -- match elmt
13002 item ::= elmt *            -- zero or more elmt's
13003 item ::= elmt +            -- one or more elmt's
13004 item ::= elmt ?            -- matches elmt or nothing
13005 @end group
13006 @group
13007 elmt ::= nschar            -- matches given character
13008 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13009 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13010 elmt ::= [char - char]     -- matches chars in given range
13011 elmt ::= \ char            -- matches given character
13012 elmt ::= .                 -- matches any single character
13013 elmt ::= ( regexp )        -- parens used for grouping
13014
13015 char ::= any character, including special characters
13016 nschar ::= any character except ()[].*+?^
13017 @end group
13018 @end smallexample
13019
13020 Following are a few examples :
13021
13022 @table @samp
13023 @item abcde|fghi
13024 will match any of the two strings 'abcde' and 'fghi'.
13025
13026 @item abc*d
13027 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13028
13029 @item [a-z]+
13030 will match any string which has only lowercase characters in it (and at
13031 least one character
13032
13033 @end table
13034 @end table
13035
13036 @node Examples of gnatxref Usage
13037 @section Examples of @code{gnatxref} Usage
13038
13039 @subsection General Usage
13040
13041 @noindent
13042 For the following examples, we will consider the following units :
13043
13044 @smallexample
13045 @group
13046 @cartouche
13047 main.ads:
13048 1: @b{with} Bar;
13049 2: @b{package} Main @b{is}
13050 3:     @b{procedure} Foo (B : @b{in} Integer);
13051 4:     C : Integer;
13052 5: @b{private}
13053 6:     D : Integer;
13054 7: @b{end} Main;
13055
13056 main.adb:
13057 1: @b{package body} Main @b{is}
13058 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13059 3:     @b{begin}
13060 4:        C := B;
13061 5:        D := B;
13062 6:        Bar.Print (B);
13063 7:        Bar.Print (C);
13064 8:     @b{end} Foo;
13065 9: @b{end} Main;
13066
13067 bar.ads:
13068 1: @b{package} Bar @b{is}
13069 2:     @b{procedure} Print (B : Integer);
13070 3: @b{end} bar;
13071 @end cartouche
13072 @end group
13073 @end smallexample
13074
13075 @table @code
13076
13077 @noindent
13078 The first thing to do is to recompile your application (for instance, in
13079 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13080 the cross-referencing information.
13081 You can then issue any of the following commands:
13082
13083 @item gnatxref main.adb
13084 @code{gnatxref} generates cross-reference information for main.adb
13085 and every unit 'with'ed by main.adb.
13086
13087 The output would be:
13088 @smallexample
13089 @iftex
13090 @leftskip=0cm
13091 @end iftex
13092 B                                                      Type: Integer
13093   Decl: bar.ads           2:22
13094 B                                                      Type: Integer
13095   Decl: main.ads          3:20
13096   Body: main.adb          2:20
13097   Ref:  main.adb          4:13     5:13     6:19
13098 Bar                                                    Type: Unit
13099   Decl: bar.ads           1:9
13100   Ref:  main.adb          6:8      7:8
13101        main.ads           1:6
13102 C                                                      Type: Integer
13103   Decl: main.ads          4:5
13104   Modi: main.adb          4:8
13105   Ref:  main.adb          7:19
13106 D                                                      Type: Integer
13107   Decl: main.ads          6:5
13108   Modi: main.adb          5:8
13109 Foo                                                    Type: Unit
13110   Decl: main.ads          3:15
13111   Body: main.adb          2:15
13112 Main                                                    Type: Unit
13113   Decl: main.ads          2:9
13114   Body: main.adb          1:14
13115 Print                                                   Type: Unit
13116   Decl: bar.ads           2:15
13117   Ref:  main.adb          6:12     7:12
13118 @end smallexample
13119
13120 @noindent
13121 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13122 its body is in main.adb, line 1, column 14 and is not referenced any where.
13123
13124 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13125 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13126
13127 @item gnatxref package1.adb package2.ads
13128 @code{gnatxref} will generates cross-reference information for
13129 package1.adb, package2.ads and any other package 'with'ed by any
13130 of these.
13131
13132 @end table
13133
13134 @subsection Using gnatxref with vi
13135
13136 @code{gnatxref} can generate a tags file output, which can be used
13137 directly from @file{vi}. Note that the standard version of @file{vi}
13138 will not work properly with overloaded symbols. Consider using another
13139 free implementation of @file{vi}, such as @file{vim}.
13140
13141 @smallexample
13142 $ gnatxref -v gnatfind.adb > tags
13143 @end smallexample
13144
13145 @noindent
13146 will generate the tags file for @code{gnatfind} itself (if the sources
13147 are in the search path!).
13148
13149 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13150 (replacing @i{entity} by whatever you are looking for), and vi will
13151 display a new file with the corresponding declaration of entity.
13152
13153 @node Examples of gnatfind Usage
13154 @section Examples of @code{gnatfind} Usage
13155
13156 @table @code
13157
13158 @item gnatfind -f xyz:main.adb
13159 Find declarations for all entities xyz referenced at least once in
13160 main.adb. The references are search in every library file in the search
13161 path.
13162
13163 The directories will be printed as well (as the @samp{-f}
13164 switch is set)
13165
13166 The output will look like:
13167 @smallexample
13168 directory/main.ads:106:14: xyz <= declaration
13169 directory/main.adb:24:10: xyz <= body
13170 directory/foo.ads:45:23: xyz <= declaration
13171 @end smallexample
13172
13173 @noindent
13174 that is to say, one of the entities xyz found in main.adb is declared at
13175 line 12 of main.ads (and its body is in main.adb), and another one is
13176 declared at line 45 of foo.ads
13177
13178 @item gnatfind -fs xyz:main.adb
13179 This is the same command as the previous one, instead @code{gnatfind} will
13180 display the content of the Ada source file lines.
13181
13182 The output will look like:
13183
13184 @smallexample
13185 directory/main.ads:106:14: xyz <= declaration
13186    procedure xyz;
13187 directory/main.adb:24:10: xyz <= body
13188    procedure xyz is
13189 directory/foo.ads:45:23: xyz <= declaration
13190    xyz : Integer;
13191 @end smallexample
13192
13193 @noindent
13194 This can make it easier to find exactly the location your are looking
13195 for.
13196
13197 @item gnatfind -r "*x*":main.ads:123 foo.adb
13198 Find references to all entities containing an x that are
13199 referenced on line 123 of main.ads.
13200 The references will be searched only in main.adb and foo.adb.
13201
13202 @item gnatfind main.ads:123
13203 Find declarations and bodies for all entities that are referenced on
13204 line 123 of main.ads.
13205
13206 This is the same as @code{gnatfind "*":main.adb:123}.
13207
13208 @item gnatfind mydir/main.adb:123:45
13209 Find the declaration for the entity referenced at column 45 in
13210 line 123 of file main.adb in directory mydir. Note that it
13211 is usual to omit the identifier name when the column is given,
13212 since the column position identifies a unique reference.
13213
13214 The column has to be the beginning of the identifier, and should not
13215 point to any character in the middle of the identifier.
13216
13217 @end table
13218
13219 @node File Name Krunching Using gnatkr
13220 @chapter File Name Krunching Using @code{gnatkr}
13221 @findex gnatkr
13222
13223 @noindent
13224 This chapter discusses the method used by the compiler to shorten
13225 the default file names chosen for Ada units so that they do not
13226 exceed the maximum length permitted. It also describes the
13227 @code{gnatkr} utility that can be used to determine the result of
13228 applying this shortening.
13229 @menu
13230 * About gnatkr::
13231 * Using gnatkr::
13232 * Krunching Method::
13233 * Examples of gnatkr Usage::
13234 @end menu
13235
13236 @node About gnatkr
13237 @section About @code{gnatkr}
13238
13239 @noindent
13240 The default file naming rule in GNAT
13241 is that the file name must be derived from
13242 the unit name. The exact default rule is as follows:
13243 @itemize @bullet
13244 @item
13245 Take the unit name and replace all dots by hyphens.
13246 @item
13247 If such a replacement occurs in the
13248 second character position of a name, and the first character is
13249 a, g, s, or i then replace the dot by the character
13250 ~ (tilde)
13251 instead of a minus.
13252 @end itemize
13253 The reason for this exception is to avoid clashes
13254 with the standard names for children of System, Ada, Interfaces,
13255 and GNAT, which use the prefixes s- a- i- and g-
13256 respectively.
13257
13258 The @code{-gnatk@var{nn}}
13259 switch of the compiler activates a "krunching"
13260 circuit that limits file names to nn characters (where nn is a decimal
13261 integer). For example, using OpenVMS,
13262 where the maximum file name length is
13263 39, the value of nn is usually set to 39, but if you want to generate
13264 a set of files that would be usable if ported to a system with some
13265 different maximum file length, then a different value can be specified.
13266 The default value of 39 for OpenVMS need not be specified.
13267
13268 The @code{gnatkr} utility can be used to determine the krunched name for
13269 a given file, when krunched to a specified maximum length.
13270
13271 @node Using gnatkr
13272 @section Using @code{gnatkr}
13273
13274 @noindent
13275 The @code{gnatkr} command has the form
13276
13277 @smallexample
13278 $ gnatkr @var{name} [@var{length}]
13279 @end smallexample
13280
13281
13282 @noindent
13283 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13284 where the dots representing child units or subunit are replaced by
13285 hyphens. The only confusion arises if a name ends in @code{.ads} or
13286 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13287 no other dots in the name and the whole name is in lowercase.
13288
13289 @var{length} represents the length of the krunched name. The default
13290 when no argument is given is 8 characters. A length of zero stands for
13291 unlimited, in other words do not chop except for system files which are
13292 always 8.
13293
13294 @noindent
13295 The output is the krunched name. The output has an extension only if the
13296 original argument was a file name with an extension.
13297
13298 @node Krunching Method
13299 @section Krunching Method
13300
13301 @noindent
13302 The initial file name is determined by the name of the unit that the file
13303 contains. The name is formed by taking the full expanded name of the
13304 unit and replacing the separating dots with hyphens and
13305 using lowercase
13306 for all letters, except that a hyphen in the second character position is
13307 replaced by a tilde if the first character is
13308 a, i, g, or s.
13309 The extension is @code{.ads} for a
13310 specification and @code{.adb} for a body.
13311 Krunching does not affect the extension, but the file name is shortened to
13312 the specified length by following these rules:
13313
13314 @itemize @bullet
13315 @item
13316 The name is divided into segments separated by hyphens, tildes or
13317 underscores and all hyphens, tildes, and underscores are
13318 eliminated. If this leaves the name short enough, we are done.
13319
13320 @item
13321 If the name is too long, the longest segment is located (left-most if there are two
13322 of equal length), and shortened by dropping its last character. This is
13323 repeated until the name is short enough.
13324
13325 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13326 to fit the name into 8 characters as required by some operating systems.
13327
13328 @smallexample
13329 our-strings-wide_fixed 22
13330 our strings wide fixed 19
13331 our string  wide fixed 18
13332 our strin   wide fixed 17
13333 our stri    wide fixed 16
13334 our stri    wide fixe  15
13335 our str     wide fixe  14
13336 our str     wid  fixe  13
13337 our str     wid  fix   12
13338 ou  str     wid  fix   11
13339 ou  st      wid  fix   10
13340 ou  st      wi   fix   9
13341 ou  st      wi   fi    8
13342 Final file name: oustwifi.adb
13343 @end smallexample
13344
13345 @item
13346 The file names for all predefined units are always krunched to eight
13347 characters. The krunching of these predefined units uses the following
13348 special prefix replacements:
13349
13350 @table @file
13351 @item ada-
13352 replaced by @file{a-}
13353
13354 @item gnat-
13355 replaced by @file{g-}
13356
13357 @item interfaces-
13358 replaced by @file{i-}
13359
13360 @item system-
13361 replaced by @file{s-}
13362 @end table
13363
13364 These system files have a hyphen in the second character position. That
13365 is why normal user files replace such a character with a
13366 tilde, to
13367 avoid confusion with system file names.
13368
13369 As an example of this special rule, consider
13370 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13371
13372 @smallexample
13373 ada-strings-wide_fixed 22
13374 a-  strings wide fixed 18
13375 a-  string  wide fixed 17
13376 a-  strin   wide fixed 16
13377 a-  stri    wide fixed 15
13378 a-  stri    wide fixe  14
13379 a-  str     wide fixe  13
13380 a-  str     wid  fixe  12
13381 a-  str     wid  fix   11
13382 a-  st      wid  fix   10
13383 a-  st      wi   fix   9
13384 a-  st      wi   fi    8
13385 Final file name: a-stwifi.adb
13386 @end smallexample
13387 @end itemize
13388
13389 Of course no file shortening algorithm can guarantee uniqueness over all
13390 possible unit names, and if file name krunching is used then it is your
13391 responsibility to ensure that no name clashes occur. The utility
13392 program @code{gnatkr} is supplied for conveniently determining the
13393 krunched name of a file.
13394
13395 @node Examples of gnatkr Usage
13396 @section Examples of @code{gnatkr} Usage
13397
13398 @smallexample
13399 @iftex
13400 @leftskip=0cm
13401 @end iftex
13402 $ gnatkr very_long_unit_name.ads      --> velounna.ads
13403 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13404 $ gnatkr Grandparent.Parent.Child     --> grparchi
13405 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13406 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13407 @end smallexample
13408
13409 @node Preprocessing Using gnatprep
13410 @chapter Preprocessing Using @code{gnatprep}
13411 @findex gnatprep
13412
13413 @noindent
13414 The @code{gnatprep} utility provides
13415 a simple preprocessing capability for Ada programs.
13416 It is designed for use with GNAT, but is not dependent on any special
13417 features of GNAT.
13418
13419 @menu
13420 * Using gnatprep::
13421 * Switches for gnatprep::
13422 * Form of Definitions File::
13423 * Form of Input Text for gnatprep::
13424 @end menu
13425
13426 @node Using gnatprep
13427 @section Using @code{gnatprep}
13428
13429 @noindent
13430 To call @code{gnatprep} use
13431
13432 @smallexample
13433 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13434 @end smallexample
13435
13436 @noindent
13437 where
13438 @table @code
13439 @item infile
13440 is the full name of the input file, which is an Ada source
13441 file containing preprocessor directives.
13442
13443 @item outfile
13444 is the full name of the output file, which is an Ada source
13445 in standard Ada form. When used with GNAT, this file name will
13446 normally have an ads or adb suffix.
13447
13448 @item deffile
13449 is the full name of a text file containing definitions of
13450 symbols to be referenced by the preprocessor. This argument is
13451 optional, and can be replaced by the use of the @code{-D} switch.
13452
13453 @item switches
13454 is an optional sequence of switches as described in the next section.
13455 @end table
13456
13457 @node Switches for gnatprep
13458 @section Switches for @code{gnatprep}
13459
13460 @table @code
13461
13462 @item -b
13463 Causes both preprocessor lines and the lines deleted by
13464 preprocessing to be replaced by blank lines in the output source file,
13465 preserving line numbers in the output file.
13466
13467 @item -c
13468 Causes both preprocessor lines and the lines deleted
13469 by preprocessing to be retained in the output source as comments marked
13470 with the special string "--! ". This option will result in line numbers
13471 being preserved in the output file.
13472
13473 @item -Dsymbol=value
13474 Defines a new symbol, associated with value. If no value is given on the
13475 command line, then symbol is considered to be @code{True}. This switch
13476 can be used in place of a definition file.
13477
13478
13479 @item -r
13480 Causes a @code{Source_Reference} pragma to be generated that
13481 references the original input file, so that error messages will use
13482 the file name of this original file. The use of this switch implies
13483 that preprocessor lines are not to be removed from the file, so its
13484 use will force @code{-b} mode if
13485 @code{-c}
13486 has not been specified explicitly.
13487
13488 Note that if the file to be preprocessed contains multiple units, then
13489 it will be necessary to @code{gnatchop} the output file from
13490 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13491 in the preprocessed file, it will be respected by
13492 @code{gnatchop -r}
13493 so that the final chopped files will correctly refer to the original
13494 input source file for @code{gnatprep}.
13495
13496 @item -s
13497 Causes a sorted list of symbol names and values to be
13498 listed on the standard output file.
13499
13500 @item -u
13501 Causes undefined symbols to be treated as having the value FALSE in the context
13502 of a preprocessor test. In the absence of this option, an undefined symbol in
13503 a @code{#if} or @code{#elsif} test will be treated as an error.
13504
13505 @end table
13506
13507 @noindent
13508 Note: if neither @code{-b} nor @code{-c} is present,
13509 then preprocessor lines and
13510 deleted lines are completely removed from the output, unless -r is
13511 specified, in which case -b is assumed.
13512
13513 @node Form of Definitions File
13514 @section Form of Definitions File
13515
13516 @noindent
13517 The definitions file contains lines of the form
13518
13519 @smallexample
13520 symbol := value
13521 @end smallexample
13522
13523 @noindent
13524 where symbol is an identifier, following normal Ada (case-insensitive)
13525 rules for its syntax, and value is one of the following:
13526
13527 @itemize @bullet
13528 @item
13529 Empty, corresponding to a null substitution
13530 @item
13531 A string literal using normal Ada syntax
13532 @item
13533 Any sequence of characters from the set
13534 (letters, digits, period, underline).
13535 @end itemize
13536
13537 @noindent
13538 Comment lines may also appear in the definitions file, starting with
13539 the usual @code{--},
13540 and comments may be added to the definitions lines.
13541
13542 @node Form of Input Text for gnatprep
13543 @section Form of Input Text for @code{gnatprep}
13544
13545 @noindent
13546 The input text may contain preprocessor conditional inclusion lines,
13547 as well as general symbol substitution sequences.
13548
13549 The preprocessor conditional inclusion commands have the form
13550
13551 @smallexample
13552 @group
13553 @cartouche
13554 #if @i{expression} [then]
13555    lines
13556 #elsif @i{expression} [then]
13557    lines
13558 #elsif @i{expression} [then]
13559    lines
13560 ...
13561 #else
13562    lines
13563 #end if;
13564 @end cartouche
13565 @end group
13566 @end smallexample
13567
13568 @noindent
13569 In this example, @i{expression} is defined by the following grammar:
13570 @smallexample
13571 @i{expression} ::=  <symbol>
13572 @i{expression} ::=  <symbol> = "<value>"
13573 @i{expression} ::=  <symbol> = <symbol>
13574 @i{expression} ::=  <symbol> 'Defined
13575 @i{expression} ::=  not @i{expression}
13576 @i{expression} ::=  @i{expression} and @i{expression}
13577 @i{expression} ::=  @i{expression} or @i{expression}
13578 @i{expression} ::=  @i{expression} and then @i{expression}
13579 @i{expression} ::=  @i{expression} or else @i{expression}
13580 @i{expression} ::=  ( @i{expression} )
13581 @end smallexample
13582
13583 @noindent
13584 For the first test (@i{expression} ::= <symbol>) the symbol must have
13585 either the value true or false, that is to say the right-hand of the
13586 symbol definition must be one of the (case-insensitive) literals
13587 @code{True} or @code{False}. If the value is true, then the
13588 corresponding lines are included, and if the value is false, they are
13589 excluded.
13590
13591 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13592 the symbol has been defined in the definition file or by a @code{-D}
13593 switch on the command line. Otherwise, the test is false.
13594
13595 The equality tests are case insensitive, as are all the preprocessor lines.
13596
13597 If the symbol referenced is not defined in the symbol definitions file,
13598 then the effect depends on whether or not switch @code{-u}
13599 is specified. If so, then the symbol is treated as if it had the value
13600 false and the test fails. If this switch is not specified, then
13601 it is an error to reference an undefined symbol. It is also an error to
13602 reference a symbol that is defined with a value other than @code{True}
13603 or @code{False}.
13604
13605 The use of the @code{not} operator inverts the sense of this logical test, so
13606 that the lines are included only if the symbol is not defined.
13607 The @code{then} keyword is optional as shown
13608
13609 The @code{#} must be the first non-blank character on a line, but
13610 otherwise the format is free form. Spaces or tabs may appear between
13611 the @code{#} and the keyword. The keywords and the symbols are case
13612 insensitive as in normal Ada code. Comments may be used on a
13613 preprocessor line, but other than that, no other tokens may appear on a
13614 preprocessor line. Any number of @code{elsif} clauses can be present,
13615 including none at all. The @code{else} is optional, as in Ada.
13616
13617 The @code{#} marking the start of a preprocessor line must be the first
13618 non-blank character on the line, i.e. it must be preceded only by
13619 spaces or horizontal tabs.
13620
13621 Symbol substitution outside of preprocessor lines is obtained by using
13622 the sequence
13623
13624 @smallexample
13625 $symbol
13626 @end smallexample
13627
13628 @noindent
13629 anywhere within a source line, except in a comment or within a
13630 string literal. The identifier
13631 following the @code{$} must match one of the symbols defined in the symbol
13632 definition file, and the result is to substitute the value of the
13633 symbol in place of @code{$symbol} in the output file.
13634
13635 Note that although the substitution of strings within a string literal
13636 is not possible, it is possible to have a symbol whose defined value is
13637 a string literal. So instead of setting XYZ to @code{hello} and writing:
13638
13639 @smallexample
13640 Header : String := "$XYZ";
13641 @end smallexample
13642
13643 @noindent
13644 you should set XYZ to @code{"hello"} and write:
13645
13646 @smallexample
13647 Header : String := $XYZ;
13648 @end smallexample
13649
13650 @noindent
13651 and then the substitution will occur as desired.
13652
13653
13654 @node The GNAT Library Browser gnatls
13655 @chapter The GNAT Library Browser @code{gnatls}
13656 @findex gnatls
13657 @cindex Library browser
13658
13659 @noindent
13660 @code{gnatls} is a tool that outputs information about compiled
13661 units. It gives the relationship between objects, unit names and source
13662 files. It can also be used to check the source dependencies of a unit
13663 as well as various characteristics.
13664
13665 @menu
13666 * Running gnatls::
13667 * Switches for gnatls::
13668 * Examples of gnatls Usage::
13669 @end menu
13670
13671 @node Running gnatls
13672 @section Running @code{gnatls}
13673
13674 @noindent
13675 The @code{gnatls} command has the form
13676
13677 @smallexample
13678 $ gnatls switches @var{object_or_ali_file}
13679 @end smallexample
13680
13681 @noindent
13682 The main argument is the list of object or @file{ali} files
13683 (@pxref{The Ada Library Information Files})
13684 for which information is requested.
13685
13686 In normal mode, without additional option, @code{gnatls} produces a
13687 four-column listing. Each line represents information for a specific
13688 object. The first column gives the full path of the object, the second
13689 column gives the name of the principal unit in this object, the third
13690 column gives the status of the source and the fourth column gives the
13691 full path of the source representing this unit.
13692 Here is a simple example of use:
13693
13694 @smallexample
13695 $ gnatls *.o
13696 ./demo1.o            demo1            DIF demo1.adb
13697 ./demo2.o            demo2             OK demo2.adb
13698 ./hello.o            h1                OK hello.adb
13699 ./instr-child.o      instr.child      MOK instr-child.adb
13700 ./instr.o            instr             OK instr.adb
13701 ./tef.o              tef              DIF tef.adb
13702 ./text_io_example.o  text_io_example   OK text_io_example.adb
13703 ./tgef.o             tgef             DIF tgef.adb
13704 @end smallexample
13705
13706 @noindent
13707 The first line can be interpreted as follows: the main unit which is
13708 contained in
13709 object file @file{demo1.o} is demo1, whose main source is in
13710 @file{demo1.adb}. Furthermore, the version of the source used for the
13711 compilation of demo1 has been modified (DIF). Each source file has a status
13712 qualifier which can be:
13713
13714 @table @code
13715 @item OK (unchanged)
13716 The version of the source file used for the compilation of the
13717 specified unit corresponds exactly to the actual source file.
13718
13719 @item MOK (slightly modified)
13720 The version of the source file used for the compilation of the
13721 specified unit differs from the actual source file but not enough to
13722 require recompilation. If you use gnatmake with the qualifier
13723 @code{-m (minimal recompilation)}, a file marked
13724 MOK will not be recompiled.
13725
13726 @item DIF (modified)
13727 No version of the source found on the path corresponds to the source
13728 used to build this object.
13729
13730 @item ??? (file not found)
13731 No source file was found for this unit.
13732
13733 @item HID (hidden,  unchanged version not first on PATH)
13734 The version of the source that corresponds exactly to the source used
13735 for compilation has been found on the path but it is hidden by another
13736 version of the same source that has been modified.
13737
13738 @end table
13739
13740 @node Switches for gnatls
13741 @section Switches for @code{gnatls}
13742
13743 @noindent
13744 @code{gnatls} recognizes the following switches:
13745
13746 @table @code
13747 @item -a
13748 @cindex @code{-a} (@code{gnatls})
13749 Consider all units, including those of the predefined Ada library.
13750 Especially useful with @code{-d}.
13751
13752 @item -d
13753 @cindex @code{-d} (@code{gnatls})
13754 List sources from which specified units depend on.
13755
13756 @item -h
13757 @cindex @code{-h} (@code{gnatls})
13758 Output the list of options.
13759
13760 @item -o
13761 @cindex @code{-o} (@code{gnatls})
13762 Only output information about object files.
13763
13764 @item -s
13765 @cindex @code{-s} (@code{gnatls})
13766 Only output information about source files.
13767
13768 @item -u
13769 @cindex @code{-u} (@code{gnatls})
13770 Only output information about compilation units.
13771
13772 @item -aO@var{dir}
13773 @itemx -aI@var{dir}
13774 @itemx -I@var{dir}
13775 @itemx  -I-
13776 @itemx -nostdinc
13777 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13778 (see @ref{Switches for gnatmake}).
13779
13780 @item --RTS=@var{rts-path}
13781 @cindex @code{--RTS} (@code{gnatls})
13782 Specifies the default location of the runtime library. Same meaning as the
13783 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13784
13785 @item -v
13786 @cindex @code{-s} (@code{gnatls})
13787 Verbose mode. Output the complete source and object paths. Do not use
13788 the default column layout but instead use long format giving as much as
13789 information possible on each requested units, including special
13790 characteristics such as:
13791
13792 @table @code
13793 @item  Preelaborable
13794 The unit is preelaborable in the Ada 95 sense.
13795
13796 @item No_Elab_Code
13797 No elaboration code has been produced by the compiler for this unit.
13798
13799 @item Pure
13800 The unit is pure in the Ada 95 sense.
13801
13802 @item Elaborate_Body
13803 The unit contains a pragma Elaborate_Body.
13804
13805 @item Remote_Types
13806 The unit contains a pragma Remote_Types.
13807
13808 @item Shared_Passive
13809 The unit contains a pragma Shared_Passive.
13810
13811 @item Predefined
13812 This unit is part of the predefined environment and cannot be modified
13813 by the user.
13814
13815 @item Remote_Call_Interface
13816 The unit contains a pragma Remote_Call_Interface.
13817
13818 @end table
13819
13820 @end table
13821
13822 @node Examples of gnatls Usage
13823 @section Example of @code{gnatls} Usage
13824
13825 @noindent
13826 Example of using the verbose switch. Note how the source and
13827 object paths are affected by the -I switch.
13828
13829 @smallexample
13830 $ gnatls -v -I.. demo1.o
13831
13832 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13833
13834 Source Search Path:
13835    <Current_Directory>
13836    ../
13837    /home/comar/local/adainclude/
13838
13839 Object Search Path:
13840    <Current_Directory>
13841    ../
13842    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13843
13844 ./demo1.o
13845    Unit =>
13846      Name   => demo1
13847      Kind   => subprogram body
13848      Flags  => No_Elab_Code
13849      Source => demo1.adb    modified
13850 @end smallexample
13851
13852 @noindent
13853 The following is an example of use of the dependency list.
13854 Note the use of the -s switch
13855 which gives a straight list of source files. This can be useful for
13856 building specialized scripts.
13857
13858 @smallexample
13859 $ gnatls -d demo2.o
13860 ./demo2.o   demo2        OK demo2.adb
13861                          OK gen_list.ads
13862                          OK gen_list.adb
13863                          OK instr.ads
13864                          OK instr-child.ads
13865
13866 $ gnatls -d -s -a demo1.o
13867 demo1.adb
13868 /home/comar/local/adainclude/ada.ads
13869 /home/comar/local/adainclude/a-finali.ads
13870 /home/comar/local/adainclude/a-filico.ads
13871 /home/comar/local/adainclude/a-stream.ads
13872 /home/comar/local/adainclude/a-tags.ads
13873 gen_list.ads
13874 gen_list.adb
13875 /home/comar/local/adainclude/gnat.ads
13876 /home/comar/local/adainclude/g-io.ads
13877 instr.ads
13878 /home/comar/local/adainclude/system.ads
13879 /home/comar/local/adainclude/s-exctab.ads
13880 /home/comar/local/adainclude/s-finimp.ads
13881 /home/comar/local/adainclude/s-finroo.ads
13882 /home/comar/local/adainclude/s-secsta.ads
13883 /home/comar/local/adainclude/s-stalib.ads
13884 /home/comar/local/adainclude/s-stoele.ads
13885 /home/comar/local/adainclude/s-stratt.ads
13886 /home/comar/local/adainclude/s-tasoli.ads
13887 /home/comar/local/adainclude/s-unstyp.ads
13888 /home/comar/local/adainclude/unchconv.ads
13889 @end smallexample
13890
13891
13892 @node GNAT and Libraries
13893 @chapter GNAT and Libraries
13894 @cindex Library, building, installing
13895
13896 @noindent
13897 This chapter addresses some of the issues related to building and using
13898 a library with GNAT. It also shows how the GNAT run-time library can be
13899 recompiled.
13900
13901 @menu
13902 * Creating an Ada Library::
13903 * Installing an Ada Library::
13904 * Using an Ada Library::
13905 * Creating an Ada Library to be Used in a Non-Ada Context::
13906 * Rebuilding the GNAT Run-Time Library::
13907 @end menu
13908
13909 @node Creating an Ada Library
13910 @section Creating an Ada Library
13911
13912 @noindent
13913 In the GNAT environment, a library has two components:
13914 @itemize @bullet
13915 @item
13916 Source files.
13917 @item
13918 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
13919 @end itemize
13920
13921 @noindent
13922 In order to use other packages @ref{The GNAT Compilation Model}
13923 requires a certain number of sources to be available to the compiler.
13924 The minimal set of
13925 sources required includes the specs of all the packages that make up the
13926 visible part of the library as well as all the sources upon which they
13927 depend. The bodies of all visible generic units must also be provided.
13928 @noindent
13929 Although it is not strictly mandatory, it is recommended that all sources
13930 needed to recompile the library be provided, so that the user can make
13931 full use of inter-unit inlining and source-level debugging. This can also
13932 make the situation easier for users that need to upgrade their compilation
13933 toolchain and thus need to recompile the library from sources.
13934
13935 @noindent
13936 The compiled code can be provided in different ways. The simplest way is
13937 to provide directly the set of objects produced by the compiler during
13938 the compilation of the library. It is also possible to group the objects
13939 into an archive using whatever commands are provided by the operating
13940 system. Finally, it is also possible to create a shared library (see
13941 option -shared in the GCC manual).
13942
13943 @noindent
13944 There are various possibilities for compiling the units that make up the
13945 library: for example with a Makefile @ref{Using the GNU make Utility},
13946 or with a conventional script.
13947 For simple libraries, it is also possible to create a
13948 dummy main program which depends upon all the packages that comprise the
13949 interface of the library. This dummy main program can then be given to
13950 gnatmake, in order to build all the necessary objects. Here is an example
13951 of such a dummy program and the generic commands used to build an
13952 archive or a shared library.
13953
13954 @smallexample
13955 @iftex
13956 @leftskip=.7cm
13957 @end iftex
13958 @b{with} My_Lib.Service1;
13959 @b{with} My_Lib.Service2;
13960 @b{with} My_Lib.Service3;
13961 @b{procedure} My_Lib_Dummy @b{is}
13962 @b{begin}
13963    @b{null};
13964 @b{end};
13965
13966 # compiling the library
13967 $ gnatmake -c my_lib_dummy.adb
13968
13969 # we don't need the dummy object itself
13970 $ rm my_lib_dummy.o my_lib_dummy.ali
13971
13972 # create an archive with the remaining objects
13973 $ ar rc libmy_lib.a *.o
13974 # some systems may require "ranlib" to be run as well
13975
13976 # or create a shared library
13977 $ gcc -shared -o libmy_lib.so *.o
13978 # some systems may require the code to have been compiled with -fPIC
13979 @end smallexample
13980
13981 @noindent
13982 When the objects are grouped in an archive or a shared library, the user
13983 needs to specify the desired library at link time, unless a pragma
13984 linker_options has been used in one of the sources:
13985 @smallexample
13986 @b{pragma} Linker_Options ("-lmy_lib");
13987 @end smallexample
13988
13989 @node Installing an Ada Library
13990 @section Installing an Ada Library
13991
13992 @noindent
13993 In the GNAT model, installing a library consists in copying into a specific
13994 location the files that make up this library. It is possible to install
13995 the sources in a different directory from the other files (ALI, objects,
13996 archives) since the source path and the object path can easily be
13997 specified separately.
13998
13999 @noindent
14000 For general purpose libraries, it is possible for the system
14001 administrator to put those libraries in the default compiler paths. To
14002 achieve this, he must specify their location in the configuration files
14003 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14004 installation tree at the same place as the gcc spec file. The location of
14005 the gcc spec file can be determined as follows:
14006 @smallexample
14007 $ gcc -v
14008 @end smallexample
14009
14010 @noindent
14011 The configuration files mentioned above have simple format: each line in them
14012 must contain one unique
14013 directory name. Those names are added to the corresponding path
14014 in their order of appearance in the file. The names can be either absolute
14015 or relative, in the latter case, they are relative to where theses files
14016 are located.
14017
14018 @noindent
14019 "ada_source_path" and "ada_object_path" might actually not be present in a
14020 GNAT installation, in which case, GNAT will look for its run-time library in
14021 the directories "adainclude" for the sources and "adalib" for the
14022 objects and ALI files. When the files exist, the compiler does not
14023 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14024 must contain the location for the GNAT run-time sources (which can simply
14025 be "adainclude"). In the same way, the "ada_object_path" file must contain
14026 the location for the GNAT run-time objects (which can simply
14027 be "adalib").
14028
14029 @noindent
14030 You can also specify a new default path to the runtime library at compilation
14031 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14032 the runtime you want your program to be compiled with. This switch is
14033 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14034
14035 @noindent
14036 It is possible to install a library before or after the standard GNAT
14037 library, by reordering the lines in the configuration files. In general, a
14038 library must be installed before the GNAT library if it redefines any part of it.
14039
14040 @node Using an Ada Library
14041 @section Using an Ada Library
14042
14043 @noindent
14044 In order to use a Ada library, you need to make sure that this
14045 library is on both your source and object path
14046 @ref{Search Paths and the Run-Time Library (RTL)}
14047 and @ref{Search Paths for gnatbind}. For
14048 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14049 and "/dir/my_lib_obj" with the following commands:
14050
14051 @smallexample
14052 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14053   -largs -lmy_lib
14054 @end smallexample
14055
14056 @noindent
14057 This can be simplified down to the following:
14058 @smallexample
14059 $ gnatmake my_appl
14060 @end smallexample
14061 when the following conditions are met:
14062 @itemize @bullet
14063 @item
14064 "/dir/my_lib_src" has been added by the user to the environment
14065 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14066 "ada_source_path"
14067 @item
14068 "/dir/my_lib_obj" has been added by the user to the environment
14069 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14070 "ada_object_path"
14071 @item
14072 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14073 as been added to the sources.
14074 @end itemize
14075 @noindent
14076
14077 @node Creating an Ada Library to be Used in a Non-Ada Context
14078 @section Creating an Ada Library to be Used in a Non-Ada Context
14079
14080 @noindent
14081 The previous sections detailed how to create and install a library that
14082 was usable from an Ada main program. Using this library in a non-Ada
14083 context is not possible, because the elaboration of the library is
14084 automatically done as part of the main program elaboration.
14085
14086 GNAT also provides the ability to build libraries that can be used both
14087 in an Ada and non-Ada context.  This section describes how to build such
14088 a library, and then how to use it from a C program. The method for
14089 interfacing with the library from other languages such as Fortran for
14090 instance remains the same.
14091
14092 @subsection Creating the Library
14093
14094 @itemize @bullet
14095 @item Identify the units representing the interface of the library.
14096
14097 Here is an example of simple library interface:
14098
14099 @smallexample
14100 package Interface is
14101
14102    procedure Do_Something;
14103
14104    procedure Do_Something_Else;
14105
14106 end Interface;
14107 @end smallexample
14108
14109 @item Use @code{pragma Export} or @code{pragma Convention} for the
14110 exported entities.
14111
14112 Our package @code{Interface} is then updated as follow:
14113 @smallexample
14114 package Interface is
14115
14116    procedure Do_Something;
14117    pragma Export (C, Do_Something, "do_something");
14118
14119    procedure Do_Something_Else;
14120    pragma Export (C, Do_Something_Else, "do_something_else");
14121
14122 end Interface;
14123 @end smallexample
14124
14125 @item Compile all the units composing the library.
14126
14127 @item Bind the library objects.
14128
14129 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14130 switch. @code{gnatbind} will then generate the library elaboration
14131 procedure (named @code{<prefix>init}) and the run-time finalization
14132 procedure (named @code{<prefix>final}).
14133
14134 @smallexample
14135 # generate the binder file in Ada
14136 $ gnatbind -Lmylib interface
14137
14138 # generate the binder file in C
14139 $ gnatbind -C -Lmylib interface
14140 @end smallexample
14141
14142 @item Compile the files generated by the binder
14143
14144 @smallexample
14145 $ gcc -c b~interface.adb
14146 @end smallexample
14147
14148 @item Create the library;
14149
14150 The procedure is identical to the procedure explained in
14151 @ref{Creating an Ada Library},
14152 except that @file{b~interface.o} needs to be added to
14153 the list of objects.
14154
14155 @smallexample
14156 # create an archive file
14157 $ ar cr libmylib.a b~interface.o <other object files>
14158
14159 # create a shared library
14160 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14161 @end smallexample
14162
14163 @item Provide a "foreign" view of the library interface;
14164
14165 The example below shows the content of @code{mylib_interface.h} (note
14166 that there is no rule for the naming of this file, any name can be used)
14167 @smallexample
14168 /* the library elaboration procedure */
14169 extern void mylibinit (void);
14170
14171 /* the library finalization procedure */
14172 extern void mylibfinal (void);
14173
14174 /* the interface exported by the library */
14175 extern void do_something (void);
14176 extern void do_something_else (void);
14177 @end smallexample
14178 @end itemize
14179
14180 @subsection Using the Library
14181
14182 @noindent
14183 Libraries built as explained above can be used from any program, provided
14184 that the elaboration procedures (named @code{mylibinit} in the previous
14185 example) are called before the library services are used. Any number of
14186 libraries can be used simultaneously, as long as the elaboration
14187 procedure of each library is called.
14188
14189 Below is an example of C program that uses our @code{mylib} library.
14190
14191 @smallexample
14192 #include "mylib_interface.h"
14193
14194 int
14195 main (void)
14196 @{
14197    /* First, elaborate the library before using it */
14198    mylibinit ();
14199
14200    /* Main program, using the library exported entities */
14201    do_something ();
14202    do_something_else ();
14203
14204    /* Library finalization at the end of the program */
14205    mylibfinal ();
14206    return 0;
14207 @}
14208 @end smallexample
14209
14210 @noindent
14211 Note that this same library can be used from an equivalent Ada main
14212 program. In addition, if the libraries are installed as detailed in
14213 @ref{Installing an Ada Library}, it is not necessary to invoke the
14214 library elaboration and finalization routines. The binder will ensure
14215 that this is done as part of the main program elaboration and
14216 finalization phases.
14217
14218 @subsection The Finalization Phase
14219
14220 @noindent
14221 Invoking any library finalization procedure generated by @code{gnatbind}
14222 shuts down the Ada run time permanently. Consequently, the finalization
14223 of all Ada libraries must be performed at the end of the program. No
14224 call to these libraries nor the Ada run time should be made past the
14225 finalization phase.
14226
14227 @subsection Restrictions in Libraries
14228
14229 @noindent
14230 The pragmas listed below should be used with caution inside libraries,
14231 as they can create incompatibilities with other Ada libraries:
14232 @itemize @bullet
14233 @item pragma @code{Locking_Policy}
14234 @item pragma @code{Queuing_Policy}
14235 @item pragma @code{Task_Dispatching_Policy}
14236 @item pragma @code{Unreserve_All_Interrupts}
14237 @end itemize
14238 When using a library that contains such pragmas, the user must make sure
14239 that all libraries use the same pragmas with the same values. Otherwise,
14240 a @code{Program_Error} will
14241 be raised during the elaboration of the conflicting
14242 libraries. The usage of these pragmas and its consequences for the user
14243 should therefore be well documented.
14244
14245 Similarly, the traceback in exception occurrences mechanism should be
14246 enabled or disabled in a consistent manner across all libraries.
14247 Otherwise, a Program_Error will be raised during the elaboration of the
14248 conflicting libraries.
14249
14250 If the @code{'Version} and @code{'Body_Version}
14251 attributes are used inside a library, then it is necessary to
14252 perform a @code{gnatbind} step that mentions all ali files in all
14253 libraries, so that version identifiers can be properly computed.
14254 In practice these attributes are rarely used, so this is unlikely
14255 to be a consideration.
14256
14257 @node  Rebuilding the GNAT Run-Time Library
14258 @section Rebuilding the GNAT Run-Time Library
14259
14260 @noindent
14261 It may be useful to recompile the GNAT library in various contexts, the
14262 most important one being the use of partition-wide configuration pragmas
14263 such as Normalize_Scalar. A special Makefile called
14264 @code{Makefile.adalib} is provided to that effect and can be found in
14265 the directory containing the GNAT library. The location of this
14266 directory depends on the way the GNAT environment has been installed and can
14267 be determined by means of the command:
14268
14269 @smallexample
14270 $ gnatls -v
14271 @end smallexample
14272
14273 @noindent
14274 The last entry in the object search path usually contains the
14275 gnat library. This Makefile contains its own documentation and in
14276 particular the set of instructions needed to rebuild a new library and
14277 to use it.
14278
14279 @node Using the GNU make Utility
14280 @chapter Using the GNU @code{make} Utility
14281 @findex make
14282
14283 @noindent
14284 This chapter offers some examples of makefiles that solve specific
14285 problems. It does not explain how to write a makefile (see the GNU make
14286 documentation), nor does it try to replace the @code{gnatmake} utility
14287 (@pxref{The GNAT Make Program gnatmake}).
14288
14289 All the examples in this section are specific to the GNU version of
14290 make. Although @code{make} is a standard utility, and the basic language
14291 is the same, these examples use some advanced features found only in
14292 @code{GNU make}.
14293
14294 @menu
14295 * Using gnatmake in a Makefile::
14296 * Automatically Creating a List of Directories::
14297 * Generating the Command Line Switches::
14298 * Overcoming Command Line Length Limits::
14299 @end menu
14300
14301 @node Using gnatmake in a Makefile
14302 @section Using gnatmake in a Makefile
14303 @findex makefile
14304 @cindex GNU make
14305
14306 @noindent
14307 Complex project organizations can be handled in a very powerful way by
14308 using GNU make combined with gnatmake. For instance, here is a Makefile
14309 which allows you to build each subsystem of a big project into a separate
14310 shared library. Such a makefile allows you to significantly reduce the link
14311 time of very big applications while maintaining full coherence at
14312 each step of the build process.
14313
14314 The list of dependencies are handled automatically by
14315 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14316 the appropriate directories.
14317
14318 Note that you should also read the example on how to automatically
14319 create the list of directories (@pxref{Automatically Creating a List of Directories})
14320 which might help you in case your project has a lot of
14321 subdirectories.
14322
14323 @smallexample
14324 @iftex
14325 @leftskip=0cm
14326 @font@heightrm=cmr8
14327 @heightrm
14328 @end iftex
14329 ## This Makefile is intended to be used with the following directory
14330 ## configuration:
14331 ##  - The sources are split into a series of csc (computer software components)
14332 ##    Each of these csc is put in its own directory.
14333 ##    Their name are referenced by the directory names.
14334 ##    They will be compiled into shared library (although this would also work
14335 ##    with static libraries
14336 ##  - The main program (and possibly other packages that do not belong to any
14337 ##    csc is put in the top level directory (where the Makefile is).
14338 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
14339 ##                    \_ second_csc (sources) __ lib (will contain the library)
14340 ##                    \_ ...
14341 ## Although this Makefile is build for shared library, it is easy to modify
14342 ## to build partial link objects instead (modify the lines with -shared and
14343 ## gnatlink below)
14344 ##
14345 ## With this makefile, you can change any file in the system or add any new
14346 ## file, and everything will be recompiled correctly (only the relevant shared
14347 ## objects will be recompiled, and the main program will be re-linked).
14348
14349 # The list of computer software component for your project. This might be
14350 # generated automatically.
14351 CSC_LIST=aa bb cc
14352
14353 # Name of the main program (no extension)
14354 MAIN=main
14355
14356 # If we need to build objects with -fPIC, uncomment the following line
14357 #NEED_FPIC=-fPIC
14358
14359 # The following variable should give the directory containing libgnat.so
14360 # You can get this directory through 'gnatls -v'. This is usually the last
14361 # directory in the Object_Path.
14362 GLIB=...
14363
14364 # The directories for the libraries
14365 # (This macro expands the list of CSC to the list of shared libraries, you
14366 # could simply use the expanded form :
14367 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14368 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14369
14370 $@{MAIN@}: objects $@{LIB_DIR@}
14371     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14372     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14373
14374 objects::
14375     # recompile the sources
14376     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14377
14378 # Note: In a future version of GNAT, the following commands will be simplified
14379 # by a new tool, gnatmlib
14380 $@{LIB_DIR@}:
14381     mkdir -p $@{dir $@@ @}
14382     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14383     cd $@{dir $@@ @}; cp -f ../*.ali .
14384
14385 # The dependencies for the modules
14386 # Note that we have to force the expansion of *.o, since in some cases make won't
14387 # be able to do it itself.
14388 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14389 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14390 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14391
14392 # Make sure all of the shared libraries are in the path before starting the
14393 # program
14394 run::
14395     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14396
14397 clean::
14398     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14399     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14400     $@{RM@} $@{CSC_LIST:%=%/*.o@}
14401     $@{RM@} *.o *.ali $@{MAIN@}
14402 @end smallexample
14403
14404 @node Automatically Creating a List of Directories
14405 @section Automatically Creating a List of Directories
14406
14407 @noindent
14408 In most makefiles, you will have to specify a list of directories, and
14409 store it in a variable. For small projects, it is often easier to
14410 specify each of them by hand, since you then have full control over what
14411 is the proper order for these directories, which ones should be
14412 included...
14413
14414 However, in larger projects, which might involve hundreds of
14415 subdirectories, it might be more convenient to generate this list
14416 automatically.
14417
14418 The example below presents two methods. The first one, although less
14419 general, gives you more control over the list. It involves wildcard
14420 characters, that are automatically expanded by @code{make}. Its
14421 shortcoming is that you need to explicitly specify some of the
14422 organization of your project, such as for instance the directory tree
14423 depth, whether some directories are found in a separate tree,...
14424
14425 The second method is the most general one. It requires an external
14426 program, called @code{find}, which is standard on all Unix systems. All
14427 the directories found under a given root directory will be added to the
14428 list.
14429
14430 @smallexample
14431 @iftex
14432 @leftskip=0cm
14433 @font@heightrm=cmr8
14434 @heightrm
14435 @end iftex
14436 # The examples below are based on the following directory hierarchy:
14437 # All the directories can contain any number of files
14438 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
14439 #                       ->  ab
14440 #                       ->  ac
14441 #                ->  b  ->  ba  ->  baa
14442 #                       ->  bb
14443 #                       ->  bc
14444 # This Makefile creates a variable called DIRS, that can be reused any time
14445 # you need this list (see the other examples in this section)
14446
14447 # The root of your project's directory hierarchy
14448 ROOT_DIRECTORY=.
14449
14450 ####
14451 # First method: specify explicitly the list of directories
14452 # This allows you to specify any subset of all the directories you need.
14453 ####
14454
14455 DIRS := a/aa/ a/ab/ b/ba/
14456
14457 ####
14458 # Second method: use wildcards
14459 # Note that the argument(s) to wildcard below should end with a '/'.
14460 # Since wildcards also return file names, we have to filter them out
14461 # to avoid duplicate directory names.
14462 # We thus use make's @code{dir} and @code{sort} functions.
14463 # It sets DIRs to the following value (note that the directories aaa and baa
14464 # are not given, unless you change the arguments to wildcard).
14465 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14466 ####
14467
14468 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14469
14470 ####
14471 # Third method: use an external program
14472 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14473 # This is the most complete command: it sets DIRs to the following value:
14474 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14475 ####
14476
14477 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14478
14479 @end smallexample
14480
14481 @node Generating the Command Line Switches
14482 @section Generating the Command Line Switches
14483
14484 @noindent
14485 Once you have created the list of directories as explained in the
14486 previous section (@pxref{Automatically Creating a List of Directories}),
14487 you can easily generate the command line arguments to pass to gnatmake.
14488
14489 For the sake of completeness, this example assumes that the source path
14490 is not the same as the object path, and that you have two separate lists
14491 of directories.
14492
14493 @smallexample
14494 # see "Automatically creating a list of directories" to create
14495 # these variables
14496 SOURCE_DIRS=
14497 OBJECT_DIRS=
14498
14499 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14500 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14501
14502 all:
14503         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14504 @end smallexample
14505
14506 @node Overcoming Command Line Length Limits
14507 @section Overcoming Command Line Length Limits
14508
14509 @noindent
14510 One problem that might be encountered on big projects is that many
14511 operating systems limit the length of the command line. It is thus hard to give
14512 gnatmake the list of source and object directories.
14513
14514 This example shows how you can set up environment variables, which will
14515 make @code{gnatmake} behave exactly as if the directories had been
14516 specified on the command line, but have a much higher length limit (or
14517 even none on most systems).
14518
14519 It assumes that you have created a list of directories in your Makefile,
14520 using one of the methods presented in
14521 @ref{Automatically Creating a List of Directories}.
14522 For the sake of completeness, we assume that the object
14523 path (where the ALI files are found) is different from the sources patch.
14524
14525 Note a small trick in the Makefile below: for efficiency reasons, we
14526 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14527 expanded immediately by @code{make}. This way we overcome the standard
14528 make behavior which is to expand the variables only when they are
14529 actually used.
14530
14531 @smallexample
14532 @iftex
14533 @leftskip=0cm
14534 @font@heightrm=cmr8
14535 @heightrm
14536 @end iftex
14537 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14538 # This is the same thing as putting the -I arguments on the command line.
14539 # (the equivalent of using -aI on the command line would be to define
14540 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14541 # You can of course have different values for these variables.
14542 #
14543 # Note also that we need to keep the previous values of these variables, since
14544 # they might have been set before running 'make' to specify where the GNAT
14545 # library is installed.
14546
14547 # see "Automatically creating a list of directories" to create these
14548 # variables
14549 SOURCE_DIRS=
14550 OBJECT_DIRS=
14551
14552 empty:=
14553 space:=$@{empty@} $@{empty@}
14554 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14555 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14556 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14557 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14558 export ADA_INCLUDE_PATH
14559 export ADA_OBJECT_PATH
14560
14561 all:
14562         gnatmake main_unit
14563 @end smallexample
14564
14565 @node Finding Memory Problems with gnatmem
14566 @chapter Finding Memory Problems with @code{gnatmem}
14567 @findex gnatmem
14568
14569 @noindent
14570 @code{gnatmem}, is a tool that monitors dynamic allocation and
14571 deallocation activity in a program, and displays information about
14572 incorrect deallocations and possible sources of memory leaks. Gnatmem
14573 provides three type of information:
14574 @itemize @bullet
14575 @item
14576 General information concerning memory management, such as the total
14577 number of allocations and deallocations, the amount of allocated
14578 memory and the high water mark, i.e. the largest amount of allocated
14579 memory in the course of program execution.
14580
14581 @item
14582 Backtraces for all incorrect deallocations, that is to say deallocations
14583 which do not correspond to a valid allocation.
14584
14585 @item
14586 Information on each allocation that is potentially the origin of a memory
14587 leak.
14588 @end itemize
14589
14590 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
14591 or with instrumented allocation and deallocation routines. The later
14592 mode is called the @code{GMEM} mode. Both modes produce the very same
14593 output.
14594
14595 @menu
14596 * Running gnatmem (GDB Mode)::
14597 * Running gnatmem (GMEM Mode)::
14598 * Switches for gnatmem::
14599 * Examples of gnatmem Usage::
14600 * GDB and GMEM Modes::
14601 * Implementation Note::
14602 @end menu
14603
14604 @node Running gnatmem (GDB Mode)
14605 @section Running @code{gnatmem} (GDB Mode)
14606
14607 @noindent
14608 The @code{gnatmem} command has the form
14609
14610 @smallexample
14611    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
14612 or
14613    $ gnatmem [-q] [n] -i file
14614 @end smallexample
14615
14616 @noindent
14617 Gnatmem must be supplied with the executable to examine, followed by its
14618 run-time inputs. For example, if a program is executed with the command:
14619 @smallexample
14620 $ my_program arg1 arg2
14621 @end smallexample
14622 then it can be run under @code{gnatmem} control using the command:
14623 @smallexample
14624 $ gnatmem my_program arg1 arg2
14625 @end smallexample
14626
14627 The program is transparently executed under the control of the debugger
14628 @ref{The GNAT Debugger GDB}. This does not affect the behavior
14629 of the program, except for sensitive real-time programs. When the program
14630 has completed execution, @code{gnatmem} outputs a report containing general
14631 allocation/deallocation information and potential memory leak.
14632 For better results, the user program should be compiled with
14633 debugging options @ref{Switches for gcc}.
14634
14635 Here is a simple example of use:
14636
14637 *************** debut cc
14638 @smallexample
14639 $ gnatmem test_gm
14640
14641 Global information
14642 ------------------
14643    Total number of allocations        :  45
14644    Total number of deallocations      :   6
14645    Final Water Mark (non freed mem)   :  11.29 Kilobytes
14646    High Water Mark                    :  11.40 Kilobytes
14647
14648 .
14649 .
14650 .
14651 Allocation Root # 2
14652 -------------------
14653  Number of non freed allocations    :  11
14654  Final Water Mark (non freed mem)   :   1.16 Kilobytes
14655  High Water Mark                    :   1.27 Kilobytes
14656  Backtrace                          :
14657    test_gm.adb:23 test_gm.alloc
14658 .
14659 .
14660 .
14661 @end smallexample
14662
14663 The first block of output give general information. In this case, the
14664 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
14665 unchecked deallocation routine occurred.
14666
14667 Subsequent paragraphs display  information on all allocation roots.
14668 An allocation root is a specific point in the execution of the program
14669 that generates some dynamic allocation, such as a "@b{new}" construct. This
14670 root is represented by an execution backtrace (or subprogram call
14671 stack). By default the backtrace depth for allocations roots is 1, so
14672 that a root corresponds exactly to a source location. The backtrace can
14673 be made deeper, to make the root more specific.
14674
14675 @node Running gnatmem (GMEM Mode)
14676 @section Running @code{gnatmem} (GMEM Mode)
14677 @cindex @code{GMEM} (@code{gnatmem})
14678
14679 @noindent
14680 The @code{gnatmem} command has the form
14681
14682 @smallexample
14683    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
14684 @end smallexample
14685
14686 The program must have been linked with the instrumented version of the
14687 allocation and deallocation routines. This is done with linking with the
14688 @file{libgmem.a} library. For better results, the user program should be
14689 compiled with debugging options @ref{Switches for gcc}. For example to
14690 build @file{my_program}:
14691
14692 @smallexample
14693 $ gnatmake -g my_program -largs -lgmem
14694 @end smallexample
14695
14696 @noindent
14697 When running @file{my_program} the file @file{gmem.out} is produced. This file
14698 contains information about all allocations and deallocations done by the
14699 program. It is produced by the instrumented allocations and
14700 deallocations routines and will be used by @code{gnatmem}.
14701
14702 @noindent
14703 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
14704 examine followed by its run-time inputs. For example, if a program is
14705 executed with the command:
14706 @smallexample
14707 $ my_program arg1 arg2
14708 @end smallexample
14709 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
14710 @smallexample
14711 $ gnatmem -i gmem.out my_program arg1 arg2
14712 @end smallexample
14713
14714 @node Switches for gnatmem
14715 @section Switches for @code{gnatmem}
14716
14717 @noindent
14718 @code{gnatmem} recognizes the following switches:
14719
14720 @table @code
14721
14722 @item @code{-q}
14723 @cindex @code{-q} (@code{gnatmem})
14724 Quiet. Gives the minimum output needed to identify the origin of the
14725 memory leaks. Omit statistical information.
14726
14727 @item @code{n}
14728 @cindex @code{n} (@code{gnatmem})
14729 N is an integer literal (usually between 1 and 10) which controls the
14730 depth of the backtraces defining allocation root. The default value for
14731 N is 1. The deeper the backtrace, the more precise the localization of
14732 the root. Note that the total number of roots can depend on this
14733 parameter.
14734
14735 @item @code{-o file}
14736 @cindex @code{-o} (@code{gnatmem})
14737 Direct the gdb output to the specified file. The @code{gdb} script used
14738 to generate this output is also saved in the file @file{gnatmem.tmp}.
14739
14740 @item @code{-i file}
14741 @cindex @code{-i} (@code{gnatmem})
14742 Do the @code{gnatmem} processing starting from @file{file} which has
14743 been generated by a previous call to @code{gnatmem} with the -o
14744 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
14745 for post mortem processing.
14746
14747 @end table
14748
14749 @node Examples of gnatmem Usage
14750 @section Example of @code{gnatmem} Usage
14751
14752 @noindent
14753 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
14754 results can be achieved using @code{GMEM} mode. See section
14755 @ref{Running gnatmem (GMEM Mode)}.
14756
14757 @noindent
14758 The first example shows the use of @code{gnatmem}
14759 on a simple leaking program.
14760 Suppose that we have the following Ada program:
14761
14762 @smallexample
14763 @group
14764 @cartouche
14765 @b{with} Unchecked_Deallocation;
14766 @b{procedure} Test_Gm @b{is}
14767
14768    @b{type} T @b{is array} (1..1000) @b{of} Integer;
14769    @b{type} Ptr @b{is access} T;
14770    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
14771    A : Ptr;
14772
14773    @b{procedure} My_Alloc @b{is}
14774    @b{begin}
14775       A := @b{new} T;
14776    @b{end} My_Alloc;
14777
14778    @b{procedure} My_DeAlloc @b{is}
14779       B : Ptr := A;
14780    @b{begin}
14781       Free (B);
14782    @b{end} My_DeAlloc;
14783
14784 @b{begin}
14785    My_Alloc;
14786    @b{for} I @b{in} 1 .. 5 @b{loop}
14787       @b{for} J @b{in} I .. 5 @b{loop}
14788          My_Alloc;
14789       @b{end loop};
14790       My_Dealloc;
14791    @b{end loop};
14792 @b{end};
14793 @end cartouche
14794 @end group
14795 @end smallexample
14796
14797 @noindent
14798 The program needs to be compiled with debugging option:
14799
14800 @smallexample
14801 $ gnatmake -g test_gm
14802 @end smallexample
14803
14804 @code{gnatmem} is invoked simply with
14805 @smallexample
14806 $ gnatmem test_gm
14807 @end smallexample
14808
14809 @noindent
14810 which produces the following output:
14811
14812 @smallexample
14813 Global information
14814 ------------------
14815    Total number of allocations        :  18
14816    Total number of deallocations      :   5
14817    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14818    High Water Mark                    :  56.90 Kilobytes
14819
14820 Allocation Root # 1
14821 -------------------
14822  Number of non freed allocations    :  11
14823  Final Water Mark (non freed mem)   :  42.97 Kilobytes
14824  High Water Mark                    :  46.88 Kilobytes
14825  Backtrace                          :
14826    test_gm.adb:11 test_gm.my_alloc
14827
14828 Allocation Root # 2
14829 -------------------
14830  Number of non freed allocations    :   1
14831  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14832  High Water Mark                    :  10.02 Kilobytes
14833  Backtrace                          :
14834    s-secsta.adb:81 system.secondary_stack.ss_init
14835
14836 Allocation Root # 3
14837 -------------------
14838  Number of non freed allocations    :   1
14839  Final Water Mark (non freed mem)   :  12 Bytes
14840  High Water Mark                    :  12 Bytes
14841  Backtrace                          :
14842    s-secsta.adb:181 system.secondary_stack.ss_init
14843 @end smallexample
14844
14845 @noindent
14846 Note that the GNAT run time contains itself a certain number of
14847 allocations that have no  corresponding deallocation,
14848 as shown here for root #2 and root
14849 #1. This is a normal behavior when the number of non freed allocations
14850 is one, it locates dynamic data structures that the run time needs for
14851 the complete lifetime of the program. Note also that there is only one
14852 allocation root in the user program with a single line back trace:
14853 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
14854 program shows that 'My_Alloc' is called at 2 different points in the
14855 source (line 21 and line 24). If those two allocation roots need to be
14856 distinguished, the backtrace depth parameter can be used:
14857
14858 @smallexample
14859 $ gnatmem 3 test_gm
14860 @end smallexample
14861
14862 @noindent
14863 which will give the following output:
14864
14865 @smallexample
14866 Global information
14867 ------------------
14868    Total number of allocations        :  18
14869    Total number of deallocations      :   5
14870    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14871    High Water Mark                    :  56.90 Kilobytes
14872
14873 Allocation Root # 1
14874 -------------------
14875  Number of non freed allocations    :  10
14876  Final Water Mark (non freed mem)   :  39.06 Kilobytes
14877  High Water Mark                    :  42.97 Kilobytes
14878  Backtrace                          :
14879    test_gm.adb:11 test_gm.my_alloc
14880    test_gm.adb:24 test_gm
14881    b_test_gm.c:52 main
14882
14883 Allocation Root # 2
14884 -------------------
14885  Number of non freed allocations    :   1
14886  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14887  High Water Mark                    :  10.02 Kilobytes
14888  Backtrace                          :
14889    s-secsta.adb:81  system.secondary_stack.ss_init
14890    s-secsta.adb:283 <system__secondary_stack___elabb>
14891    b_test_gm.c:33   adainit
14892
14893 Allocation Root # 3
14894 -------------------
14895  Number of non freed allocations    :   1
14896  Final Water Mark (non freed mem)   :   3.91 Kilobytes
14897  High Water Mark                    :   3.91 Kilobytes
14898  Backtrace                          :
14899    test_gm.adb:11 test_gm.my_alloc
14900    test_gm.adb:21 test_gm
14901    b_test_gm.c:52 main
14902
14903 Allocation Root # 4
14904 -------------------
14905  Number of non freed allocations    :   1
14906  Final Water Mark (non freed mem)   :  12 Bytes
14907  High Water Mark                    :  12 Bytes
14908  Backtrace                          :
14909    s-secsta.adb:181 system.secondary_stack.ss_init
14910    s-secsta.adb:283 <system__secondary_stack___elabb>
14911    b_test_gm.c:33   adainit
14912 @end smallexample
14913
14914 @noindent
14915 The allocation root #1 of the first example has been split in 2 roots #1
14916 and #3 thanks to the more precise associated backtrace.
14917
14918 @node GDB and GMEM Modes
14919 @section GDB and GMEM Modes
14920
14921 @noindent
14922 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
14923 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
14924 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
14925 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
14926
14927 @noindent
14928 The main advantage of the @code{GDB} mode is that it is available on all
14929 supported platforms. But it can be very slow if the application does a
14930 lot of allocations and deallocations.
14931
14932 @node Implementation Note
14933 @section Implementation Note
14934
14935 @menu
14936 * gnatmem Using GDB Mode::
14937 * gnatmem Using GMEM Mode::
14938 @end menu
14939
14940 @node gnatmem Using GDB Mode
14941 @subsection @code{gnatmem} Using @code{GDB} Mode
14942
14943 @noindent
14944 @code{gnatmem} executes the user program under the control of @code{GDB} using
14945 a script that sets breakpoints and gathers information on each dynamic
14946 allocation and deallocation. The output of the script is then analyzed
14947 by @code{gnatmem}
14948 in order to locate memory leaks and their origin in the
14949 program. Gnatmem works by recording each address returned by the
14950 allocation procedure (@code{__gnat_malloc})
14951 along with the backtrace at the
14952 allocation point. On each deallocation, the deallocated address is
14953 matched with the corresponding allocation. At the end of the processing,
14954 the unmatched allocations are considered potential leaks. All the
14955 allocations associated with the same backtrace are grouped together and
14956 form an allocation root. The allocation roots are then sorted so that
14957 those with the biggest number of unmatched allocation are printed
14958 first. A delicate aspect of this technique is to distinguish between the
14959 data produced by the user program and the data produced by the gdb
14960 script. Currently, on systems that allow probing the terminal, the gdb
14961 command "tty" is used to force the program output to be redirected to the
14962 current terminal while the @code{gdb} output is directed to a file or to a
14963 pipe in order to be processed subsequently by @code{gnatmem}.
14964
14965 @node gnatmem Using GMEM Mode
14966 @subsection @code{gnatmem} Using @code{GMEM} Mode
14967
14968 @noindent
14969 This mode use the same algorithm to detect memory leak as the @code{GDB}
14970 mode of @code{gnatmem}, the only difference is in the way data are
14971 gathered. In @code{GMEM} mode the program is linked with instrumented
14972 version of @code{__gnat_malloc} and @code{__gnat_free}
14973 routines. Information needed to find memory leak are recorded by these
14974 routines in file @file{gmem.out}. This mode also require that the stack
14975 traceback be available, this is only implemented on some platforms
14976 @ref{GDB and GMEM Modes}.
14977
14978
14979 @node Finding Memory Problems with GNAT Debug Pool
14980 @chapter Finding Memory Problems with GNAT Debug Pool
14981 @findex Debug Pool
14982 @cindex storage, pool, memory corruption
14983
14984 @noindent
14985 The use of unchecked deallocation and unchecked conversion can easily
14986 lead to incorrect memory references. The problems generated by such
14987 references are usually difficult to tackle because the symptoms can be
14988 very remote from the origin of the problem. In such cases, it is
14989 very helpful to detect the problem as early as possible. This is the
14990 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14991
14992 @noindent
14993 In order to use the GNAT specific debugging pool, the user must
14994 associate a debug pool object with each of the access types that may be
14995 related to suspected memory problems. See Ada Reference Manual
14996 13.11.
14997 @smallexample
14998 @b{type} Ptr @b{is} @b{access} Some_Type;
14999 Pool : GNAT.Debug_Pools.Debug_Pool;
15000 @b{for} Ptr'Storage_Pool @b{use} Pool;
15001 @end smallexample
15002
15003 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15004 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15005 allow the user to redefine allocation and deallocation strategies. They
15006 also provide a checkpoint for each dereference, through the use of
15007 the primitive operation @code{Dereference} which is implicitly called at
15008 each dereference of an access value.
15009
15010 Once an access type has been associated with a debug pool, operations on
15011 values of the type may raise four distinct exceptions,
15012 which correspond to four potential kinds of memory corruption:
15013 @itemize @bullet
15014 @item
15015 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15016 @item
15017 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15018 @item
15019 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15020 @item
15021 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15022 @end itemize
15023
15024 @noindent
15025 For types associated with a Debug_Pool, dynamic allocation is performed using
15026 the standard
15027 GNAT allocation routine. References to all allocated chunks of memory
15028 are kept in an internal dictionary. The deallocation strategy consists
15029 in not releasing the memory to the underlying system but rather to fill
15030 it with a memory pattern easily recognizable during debugging sessions:
15031 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15032 Upon each dereference, a check is made that the access value denotes a properly
15033 allocated memory location. Here is a complete example of use of
15034 @code{Debug_Pools}, that includes typical instances of  memory corruption:
15035 @smallexample
15036 @iftex
15037 @leftskip=0cm
15038 @end iftex
15039 @b{with} Gnat.Io; @b{use} Gnat.Io;
15040 @b{with} Unchecked_Deallocation;
15041 @b{with} Unchecked_Conversion;
15042 @b{with} GNAT.Debug_Pools;
15043 @b{with} System.Storage_Elements;
15044 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
15045 @b{procedure} Debug_Pool_Test @b{is}
15046
15047    @b{type} T @b{is} @b{access} Integer;
15048    @b{type} U @b{is} @b{access} @b{all} T;
15049
15050    P : GNAT.Debug_Pools.Debug_Pool;
15051    @b{for} T'Storage_Pool @b{use} P;
15052
15053    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
15054    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
15055    A, B : @b{aliased} T;
15056
15057    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
15058
15059 @b{begin}
15060    Info (P);
15061    A := @b{new} Integer;
15062    B := @b{new} Integer;
15063    B := A;
15064    Info (P);
15065    Free (A);
15066    @b{begin}
15067       Put_Line (Integer'Image(B.@b{all}));
15068    @b{exception}
15069       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15070    @b{end};
15071    @b{begin}
15072       Free (B);
15073    @b{exception}
15074       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15075    @b{end};
15076    B := UC(A'Access);
15077    @b{begin}
15078       Put_Line (Integer'Image(B.@b{all}));
15079    @b{exception}
15080       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15081    @b{end};
15082    @b{begin}
15083       Free (B);
15084    @b{exception}
15085       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15086    @b{end};
15087    Info (P);
15088 @b{end} Debug_Pool_Test;
15089 @end smallexample
15090 @noindent
15091 The debug pool mechanism provides the following precise diagnostics on the
15092 execution of this erroneous program:
15093 @smallexample
15094 Debug Pool info:
15095   Total allocated bytes :  0
15096   Total deallocated bytes :  0
15097   Current Water Mark:  0
15098   High Water Mark:  0
15099
15100 Debug Pool info:
15101   Total allocated bytes :  8
15102   Total deallocated bytes :  0
15103   Current Water Mark:  8
15104   High Water Mark:  8
15105
15106 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
15107 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
15108 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
15109 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
15110 Debug Pool info:
15111   Total allocated bytes :  8
15112   Total deallocated bytes :  4
15113   Current Water Mark:  4
15114   High Water Mark:  8
15115
15116 @end smallexample
15117
15118 @node Creating Sample Bodies Using gnatstub
15119 @chapter Creating Sample Bodies Using @code{gnatstub}
15120 @findex gnatstub
15121
15122 @noindent
15123 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
15124 for library unit declarations.
15125
15126 To create a body stub, @code{gnatstub} has to compile the library
15127 unit declaration. Therefore, bodies can be created only for legal
15128 library units. Moreover, if a library unit depends semantically upon
15129 units located outside the current directory, you have to provide
15130 the source search path when calling @code{gnatstub}, see the description
15131 of @code{gnatstub} switches below.
15132
15133 @menu
15134 * Running gnatstub::
15135 * Switches for gnatstub::
15136 @end menu
15137
15138 @node Running gnatstub
15139 @section Running @code{gnatstub}
15140
15141 @noindent
15142 @code{gnatstub} has the command-line interface of the form
15143
15144 @smallexample
15145 $ gnatstub [switches] filename [directory]
15146 @end smallexample
15147
15148 @noindent
15149 where
15150 @table @code
15151 @item filename
15152 is the name of the source file that contains a library unit declaration
15153 for which a body must be created. This name should follow the GNAT file name
15154 conventions. No crunching is allowed for this file name. The file
15155 name may contain the path information.
15156
15157 @item directory
15158 indicates the directory to place a body stub (default is the
15159 current directory)
15160
15161 @item switches
15162 is an optional sequence of switches as described in the next section
15163 @end table
15164
15165 @node Switches for gnatstub
15166 @section Switches for @code{gnatstub}
15167
15168 @table @code
15169
15170 @item -f
15171 If the destination directory already contains a file with a name of the body file
15172 for the argument spec file, replace it with the generated body stub.
15173
15174 @item -hs
15175 Put the comment header (i.e. all the comments preceding the
15176 compilation unit) from the source of the library unit declaration
15177 into the body stub.
15178
15179 @item -hg
15180 Put a sample comment header into the body stub.
15181
15182 @item -IDIR
15183 @itemx -I-
15184 These switches have the same meaning as in calls to gcc.
15185 They define the source search path in the call to gcc issued
15186 by @code{gnatstub} to compile an argument source file.
15187
15188 @item -i@var{n}
15189 (@var{n} is a decimal natural number). Set the indentation level in the
15190 generated body sample to n, '-i0' means "no indentation",
15191 the default indentation is 3.
15192
15193 @item -k
15194 Do not remove the tree file (i.e. the snapshot of the compiler internal
15195 structures used by @code{gnatstub}) after creating the body stub.
15196
15197 @item -l@var{n}
15198 (@var{n} is a decimal positive number) Set the maximum line length in the
15199 body stub to n, the default is 78.
15200
15201 @item -q
15202 Quiet mode: do not generate a confirmation when a body is
15203 successfully created or a message when a body is not required for an
15204 argument unit.
15205
15206 @item -r
15207 Reuse the tree file (if it exists) instead of creating it: instead of
15208 creating the tree file for the library unit declaration, gnatstub
15209 tries to find it in the current directory and use it for creating
15210 a body. If the tree file is not found, no body is created. @code{-r}
15211 also implies @code{-k}, whether or not
15212 @code{-k} is set explicitly.
15213
15214 @item -t
15215 Overwrite the existing tree file: if the current directory already
15216 contains the file which, according to the GNAT file name rules should
15217 be considered as a tree file for the argument source file, gnatstub
15218 will refuse to create the tree file needed to create a body sampler,
15219 unless @code{-t} option is set
15220
15221 @item -v
15222 Verbose mode: generate version information.
15223
15224 @end table
15225
15226 @node Reducing the Size of Ada Executables with gnatelim
15227 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
15228 @findex gnatelim
15229
15230 @menu
15231 * About gnatelim::
15232 * Eliminate Pragma::
15233 * Tree Files::
15234 * Preparing Tree and Bind Files for gnatelim::
15235 * Running gnatelim::
15236 * Correcting the List of Eliminate Pragmas::
15237 * Making Your Executables Smaller::
15238 * Summary of the gnatelim Usage Cycle::
15239 @end menu
15240
15241 @node About gnatelim
15242 @section About @code{gnatelim}
15243
15244 @noindent
15245 When a program shares a set of Ada
15246 packages with other programs, it may happen that this program uses
15247 only a fraction of the subprograms defined in these packages. The code
15248 created for these unused subprograms increases the size of the executable.
15249
15250 @code{gnatelim} tracks unused subprograms in an Ada program and
15251 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
15252 section) marking all the subprograms that are declared but never called.
15253 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
15254 file @file{gnat.adc} and recompiling your program, you may decrease the
15255 size of its executable, because the compiler will not generate the code
15256 for 'eliminated' subprograms.
15257
15258 @code{gnatelim} needs as its input data a set of tree files
15259 (see @ref{Tree Files}) representing all the components of a program to
15260 process and a bind file for a main subprogram (see
15261 @ref{Preparing Tree and Bind Files for gnatelim}).
15262
15263 @node Eliminate Pragma
15264 @section @code{Eliminate} Pragma
15265 @findex Eliminate
15266
15267 @noindent
15268 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
15269
15270 @smallexample
15271 @cartouche
15272 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
15273 @end cartouche
15274 @end smallexample
15275
15276 @noindent
15277 where
15278 @table @code
15279 @item Library_Unit_Name
15280 full expanded Ada name of a library unit
15281
15282 @item Subprogram_Name
15283 a simple or expanded name of a subprogram declared within this
15284 compilation unit
15285
15286 @end table
15287
15288 @noindent
15289 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
15290 file @file{gnat.adc} is:
15291
15292 @itemize @bullet
15293
15294 @item
15295 If the subprogram @code{Subprogram_Name} is declared within
15296 the library unit @code{Library_Unit_Name}, the compiler will not generate
15297 code for this subprogram. This applies to all overloaded subprograms denoted
15298 by @code{Subprogram_Name}.
15299
15300 @item
15301 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15302 in a program, the compiler will produce an error message in the place where
15303 it is called.
15304 @end itemize
15305
15306 @node Tree Files
15307 @section Tree Files
15308 @cindex Tree file
15309
15310 @noindent
15311 A tree file stores a snapshot of the compiler internal data
15312 structures at the very end of a successful compilation. It contains all the
15313 syntactic and semantic information for the compiled unit and all the
15314 units upon which it depends semantically.
15315 To use tools that make use of tree files, you
15316 need to first produce the right set of tree files.
15317
15318 GNAT produces correct tree files when -gnatt -gnatc options are set
15319 in a gcc call. The tree files have an .adt extension.
15320 Therefore, to produce a tree file for the compilation unit contained in a file
15321 named @file{foo.adb}, you must use the command
15322
15323 @smallexample
15324 $ gcc -c -gnatc -gnatt foo.adb
15325 @end smallexample
15326
15327 @noindent
15328 and you will get the tree file @file{foo.adt}.
15329 compilation.
15330
15331 @node Preparing Tree and Bind Files for gnatelim
15332 @section Preparing Tree and Bind Files for @code{gnatelim}
15333
15334 @noindent
15335 A set of tree files covering the program to be analyzed with
15336 @code{gnatelim} and
15337 the bind file for the main subprogram does not have to
15338 be in the current directory.
15339 '-T' gnatelim option may be used to provide
15340 the search path for tree files, and '-b'
15341 option may be used to point to the bind
15342 file to process (see @ref{Running gnatelim})
15343
15344 If you do not have the appropriate set of tree
15345 files and the right bind file, you
15346 may create them in the current directory using the following procedure.
15347
15348 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15349 this subprogram is in a file named @file{main_prog.adb}.
15350
15351 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15352 the main subprogram. @code{gnatelim} can work with both Ada and C
15353 bind files; when both are present, it uses the Ada bind file.
15354 The following commands will build the program and create the bind file:
15355
15356 @smallexample
15357 $ gnatmake -c Main_Prog
15358 $ gnatbind main_prog
15359 @end smallexample
15360
15361 @noindent
15362 To create a minimal set of tree files covering the whole program, call
15363 @code{gnatmake} for this program as follows:
15364
15365 @smallexample
15366 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15367 @end smallexample
15368
15369 @noindent
15370 The @code{-c} gnatmake option turns off the bind and link
15371 steps, that are useless anyway because the sources are compiled with
15372 @option{-gnatc} option which turns off code generation.
15373
15374 The @code{-f} gnatmake option forces
15375 recompilation of all the needed sources.
15376
15377 This sequence of actions will create all the data needed by @code{gnatelim}
15378 from scratch and therefore guarantee its consistency. If you would like to
15379 use some existing set of files as @code{gnatelim} output, you must make
15380 sure that the set of files is complete and consistent. You can use the
15381 @code{-m} switch to check if there are missed tree files
15382
15383 Note, that @code{gnatelim} needs neither object nor ALI files.
15384
15385 @node Running gnatelim
15386 @section Running @code{gnatelim}
15387
15388 @noindent
15389 @code{gnatelim} has the following command-line interface:
15390
15391 @smallexample
15392 $ gnatelim [options] name
15393 @end smallexample
15394
15395 @noindent
15396 @code{name} should be a full expanded Ada name of a main subprogram
15397 of a program (partition).
15398
15399 @code{gnatelim} options:
15400
15401 @table @code
15402 @item -q
15403 Quiet mode: by default @code{gnatelim} generates to the standard error
15404 stream a trace of the source file names of the compilation units being
15405 processed. This option turns this trace off.
15406
15407 @item -v
15408 Verbose mode: @code{gnatelim} version information is printed as Ada
15409 comments to the standard output stream.
15410
15411 @item -a
15412 Also look for subprograms from the GNAT run time that can be eliminated.
15413
15414 @item -m
15415 Check if any tree files are missing for an accurate result.
15416
15417 @item -T@var{dir}
15418 When looking for tree files also look in directory @var{dir}
15419
15420 @item -b@var{bind_file}
15421 Specifies @var{bind_file} as the bind file to process. If not set, the name
15422 of the bind file is computed from the full expanded Ada name of a main subprogram.
15423
15424 @item -d@var{x}
15425 Activate internal debugging switches. @var{x} is a letter or digit, or
15426 string of letters or digits, which specifies the type of debugging
15427 mode desired.  Normally these are used only for internal development
15428 or system debugging purposes. You can find full documentation for these
15429 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15430 source file @file{gnatelim-options.adb}.
15431 @end table
15432
15433 @noindent
15434 @code{gnatelim} sends its output to the standard output stream, and all the
15435 tracing and debug information is sent to the standard error stream.
15436 In order to produce a proper GNAT configuration file
15437 @file{gnat.adc}, redirection must be used:
15438
15439 @smallexample
15440 $ gnatelim Main_Prog > gnat.adc
15441 @end smallexample
15442
15443 @noindent
15444 or
15445
15446 @smallexample
15447 $ gnatelim Main_Prog >> gnat.adc
15448 @end smallexample
15449
15450 @noindent
15451 In order to append the @code{gnatelim} output to the existing contents of
15452 @file{gnat.adc}.
15453
15454 @node Correcting the List of Eliminate Pragmas
15455 @section Correcting the List of Eliminate Pragmas
15456
15457 @noindent
15458 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15459 subprograms which are actually called in the program. In this case, the
15460 compiler will generate an error message of the form:
15461
15462 @smallexample
15463 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15464 @end smallexample
15465
15466 @noindent
15467 You will need to manually remove the wrong @code{Eliminate} pragmas from
15468 the @file{gnat.adc} file. It is advised that you recompile your program
15469 from scratch after that because you need a consistent @file{gnat.adc} file
15470 during the entire compilation.
15471
15472 @node Making Your Executables Smaller
15473 @section Making Your Executables Smaller
15474
15475 @noindent
15476 In order to get a smaller executable for your program you now have to
15477 recompile the program completely with the new @file{gnat.adc} file
15478 created by @code{gnatelim} in your current directory:
15479
15480 @smallexample
15481 $ gnatmake -f Main_Prog
15482 @end smallexample
15483
15484 @noindent
15485 (you will need @code{-f} option for gnatmake to
15486 recompile everything
15487 with the set of pragmas @code{Eliminate} you have obtained with
15488 @code{gnatelim}).
15489
15490 Be aware that the set of @code{Eliminate} pragmas is specific to each
15491 program. It is not recommended to merge sets of @code{Eliminate}
15492 pragmas created for different programs in one @file{gnat.adc} file.
15493
15494 @node Summary of the gnatelim Usage Cycle
15495 @section Summary of the gnatelim Usage Cycle
15496
15497 @noindent
15498 Here is a quick summary of the steps to be taken in order to reduce
15499 the size of your executables with @code{gnatelim}. You may use
15500 other GNAT options to control the optimization level,
15501 to produce the debugging information, to set search path, etc.
15502
15503 @enumerate
15504 @item
15505 Produce a bind file and a set of tree files
15506
15507 @smallexample
15508 $ gnatmake -c Main_Prog
15509 $ gnatbind main_prog
15510 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15511 @end smallexample
15512
15513 @item
15514 Generate a list of @code{Eliminate} pragmas
15515 @smallexample
15516 $ gnatelim Main_Prog >[>] gnat.adc
15517 @end smallexample
15518
15519 @item
15520 Recompile the application
15521
15522 @smallexample
15523 $ gnatmake -f Main_Prog
15524 @end smallexample
15525
15526 @end enumerate
15527
15528 @node Other Utility Programs
15529 @chapter Other Utility Programs
15530
15531 @noindent
15532 This chapter discusses some other utility programs available in the Ada
15533 environment.
15534
15535 @menu
15536 * Using Other Utility Programs with GNAT::
15537 * The gnatpsta Utility Program::
15538 * The External Symbol Naming Scheme of GNAT::
15539 * Ada Mode for Glide::
15540 * Converting Ada Files to html with gnathtml::
15541 * Installing gnathtml::
15542 @end menu
15543
15544 @node Using Other Utility Programs with GNAT
15545 @section Using Other Utility Programs with GNAT
15546
15547 @noindent
15548 The object files generated by GNAT are in standard system format and in
15549 particular the debugging information uses this format. This means
15550 programs generated by GNAT can be used with existing utilities that
15551 depend on these formats.
15552
15553 In general, any utility program that works with C will also often work with
15554 Ada programs generated by GNAT. This includes software utilities such as
15555 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15556 as Purify.
15557
15558 @node The gnatpsta Utility Program
15559 @section The @code{gnatpsta} Utility Program
15560
15561 @noindent
15562 Many of the definitions in package Standard are implementation-dependent.
15563 However, the source of this package does not exist as an Ada source
15564 file, so these values cannot be determined by inspecting the source.
15565 They can be determined by examining in detail the coding of
15566 @file{cstand.adb} which creates the image of Standard in the compiler,
15567 but this is awkward and requires a great deal of internal knowledge
15568 about the system.
15569
15570 The @code{gnatpsta} utility is designed to deal with this situation.
15571 It is an Ada program that dynamically determines the
15572 values of all the relevant parameters in Standard, and prints them
15573 out in the form of an Ada source listing for Standard, displaying all
15574 the values of interest. This output is generated to
15575 @file{stdout}.
15576
15577 To determine the value of any parameter in package Standard, simply
15578 run @code{gnatpsta} with no qualifiers or arguments, and examine
15579 the output. This is preferable to consulting documentation, because
15580 you know that the values you are getting are the actual ones provided
15581 by the executing system.
15582
15583 @node The External Symbol Naming Scheme of GNAT
15584 @section The External Symbol Naming Scheme of GNAT
15585
15586 @noindent
15587 In order to interpret the output from GNAT, when using tools that are
15588 originally intended for use with other languages, it is useful to
15589 understand the conventions used to generate link names from the Ada
15590 entity names.
15591
15592 All link names are in all lowercase letters. With the exception of library
15593 procedure names, the mechanism used is simply to use the full expanded
15594 Ada name with dots replaced by double underscores. For example, suppose
15595 we have the following package spec:
15596
15597 @smallexample
15598 @group
15599 @cartouche
15600 @b{package} QRS @b{is}
15601    MN : Integer;
15602 @b{end} QRS;
15603 @end cartouche
15604 @end group
15605 @end smallexample
15606
15607 @noindent
15608 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15609 the corresponding link name is @code{qrs__mn}.
15610 @findex Export
15611 Of course if a @code{pragma Export} is used this may be overridden:
15612
15613 @smallexample
15614 @group
15615 @cartouche
15616 @b{package} Exports @b{is}
15617    Var1 : Integer;
15618    @b{pragma} Export (Var1, C, External_Name => "var1_name");
15619    Var2 : Integer;
15620    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15621 @b{end} Exports;
15622 @end cartouche
15623 @end group
15624 @end smallexample
15625
15626 @noindent
15627 In this case, the link name for @var{Var1} is whatever link name the
15628 C compiler would assign for the C function @var{var1_name}. This typically
15629 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15630 system conventions, but other possibilities exist. The link name for
15631 @var{Var2} is @var{var2_link_name}, and this is not operating system
15632 dependent.
15633
15634 @findex _main
15635 One exception occurs for library level procedures. A potential ambiguity
15636 arises between the required name @code{_main} for the C main program,
15637 and the name we would otherwise assign to an Ada library level procedure
15638 called @code{Main} (which might well not be the main program).
15639
15640 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15641 names. So if we have a library level procedure such as
15642
15643 @smallexample
15644 @group
15645 @cartouche
15646 @b{procedure} Hello (S : String);
15647 @end cartouche
15648 @end group
15649 @end smallexample
15650
15651 @noindent
15652 the external name of this procedure will be @var{_ada_hello}.
15653
15654 @node Ada Mode for Glide
15655 @section Ada Mode for @code{Glide}
15656
15657 @noindent
15658 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15659 user in understanding existing code and facilitates writing new code. It
15660 furthermore provides some utility functions for easier integration of
15661 standard Emacs features when programming in Ada.
15662
15663 @subsection General Features:
15664
15665 @itemize @bullet
15666 @item
15667 Full Integrated Development Environment :
15668
15669 @itemize @bullet
15670 @item
15671 support of 'project files' for the configuration (directories,
15672 compilation options,...)
15673
15674 @item
15675 compiling and stepping through error messages.
15676
15677 @item
15678 running and debugging your applications within Glide.
15679 @end itemize
15680
15681 @item
15682 easy to use for beginners by pull-down menus,
15683
15684 @item
15685 user configurable by many user-option variables.
15686 @end itemize
15687
15688 @subsection Ada Mode Features That Help Understanding Code:
15689
15690 @itemize @bullet
15691 @item
15692 functions for easy and quick stepping through Ada code,
15693
15694 @item
15695 getting cross reference information for identifiers (e.g. find the
15696 defining place by a keystroke),
15697
15698 @item
15699 displaying an index menu of types and subprograms and move point to
15700 the chosen one,
15701
15702 @item
15703 automatic color highlighting of the various entities in Ada code.
15704 @end itemize
15705
15706 @subsection Glide Support for Writing Ada Code:
15707
15708 @itemize @bullet
15709 @item
15710 switching between spec and body files with possible
15711 autogeneration of body files,
15712
15713 @item
15714 automatic formating of subprograms parameter lists.
15715
15716 @item
15717 automatic smart indentation according to Ada syntax,
15718
15719 @item
15720 automatic completion of identifiers,
15721
15722 @item
15723 automatic casing of identifiers, keywords, and attributes,
15724
15725 @item
15726 insertion of statement templates,
15727
15728 @item
15729 filling comment paragraphs like filling normal text,
15730 @end itemize
15731
15732 For more information, please refer to the online Glide documentation
15733 available in the Glide --> Help Menu.
15734
15735 @node Converting Ada Files to html with gnathtml
15736 @section Converting Ada Files to html with @code{gnathtml}
15737
15738 @noindent
15739 This @code{Perl} script allows Ada source files to be browsed using
15740 standard Web browsers. For installation procedure, see the section
15741 @xref{Installing gnathtml}.
15742
15743 Ada reserved keywords are highlighted in a bold font and Ada comments in
15744 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15745 switch to suppress the generation of cross-referencing information, user
15746 defined variables and types will appear in a different color; you will
15747 be able to click on any identifier and go to its declaration.
15748
15749 The command line is as follow:
15750 @smallexample
15751 $ perl gnathtml.pl [switches] ada-files
15752 @end smallexample
15753
15754 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15755 an html file for every ada file, and a global file called @file{index.htm}.
15756 This file is an index of every identifier defined in the files.
15757
15758 The available switches are the following ones :
15759
15760 @table @code
15761 @item -83
15762 @cindex @code{-83} (@code{gnathtml})
15763 Only the subset on the Ada 83 keywords will be highlighted, not the full
15764 Ada 95 keywords set.
15765
15766 @item -cc @var{color}
15767 This option allows you to change the color used for comments. The default
15768 value is green. The color argument can be any name accepted by html.
15769
15770 @item -d
15771 @cindex @code{-d} (@code{gnathtml})
15772 If the ada files depend on some other files (using for instance the
15773 @code{with} command, the latter will also be converted to html.
15774 Only the files in the user project will be converted to html, not the files
15775 in the run-time library itself.
15776
15777 @item -D
15778 This command is the same as -d above, but @code{gnathtml} will also look
15779 for files in the run-time library, and generate html files for them.
15780
15781 @item -f
15782 @cindex @code{-f} (@code{gnathtml})
15783 By default, gnathtml will generate html links only for global entities
15784 ('with'ed units, global variables and types,...). If you specify the
15785 @code{-f} on the command line, then links will be generated for local
15786 entities too.
15787
15788 @item -l @var{number}
15789 @cindex @code{-l} (@code{gnathtml})
15790 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15791 will number the html files every @var{number} line.
15792
15793 @item -I @var{dir}
15794 @cindex @code{-I} (@code{gnathtml})
15795 Specify a directory to search for library files (@file{.ali} files) and
15796 source files. You can provide several -I switches on the command line,
15797 and the directories will be parsed in the order of the command line.
15798
15799 @item -o @var{dir}
15800 @cindex @code{-o} (@code{gnathtml})
15801 Specify the output directory for html files. By default, gnathtml will
15802 saved the generated html files in a subdirectory named @file{html/}.
15803
15804 @item -p @var{file}
15805 @cindex @code{-p} (@code{gnathtml})
15806 If you are using Emacs and the most recent Emacs Ada mode, which provides
15807 a full Integrated Development Environment for compiling, checking,
15808 running and debugging applications, you may be using @file{.adp} files
15809 to give the directories where Emacs can find sources and object files.
15810
15811 Using this switch, you can tell gnathtml to use these files. This allows
15812 you to get an html version of your application, even if it is spread
15813 over multiple directories.
15814
15815 @item -sc @var{color}
15816 @cindex @code{-sc} (@code{gnathtml})
15817 This option allows you to change the color used for symbol definitions.
15818 The default value is red. The color argument can be any name accepted by html.
15819
15820 @item -t @var{file}
15821 @cindex @code{-t} (@code{gnathtml})
15822 This switch provides the name of a file. This file contains a list of
15823 file names to be converted, and the effect is exactly as though they had
15824 appeared explicitly on the command line. This
15825 is the recommended way to work around the command line length limit on some
15826 systems.
15827
15828 @end table
15829
15830 @node Installing gnathtml
15831 @section Installing @code{gnathtml}
15832
15833 @noindent
15834 @code{Perl} needs to be installed on your machine to run this script.
15835 @code{Perl} is freely available for almost every architecture and
15836 Operating System via the Internet.
15837
15838 On Unix systems, you  may want to modify  the  first line of  the script
15839 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
15840 is. The syntax of this line is :
15841 @smallexample
15842 #!full_path_name_to_perl
15843 @end smallexample
15844
15845 @noindent
15846 Alternatively, you may run the script using the following command line:
15847
15848 @smallexample
15849 $ perl gnathtml.pl [switches] files
15850 @end smallexample
15851
15852
15853 @node Running and Debugging Ada Programs
15854 @chapter Running and Debugging Ada Programs
15855 @cindex Debugging
15856
15857 @noindent
15858 This chapter discusses how to debug Ada programs. An incorrect Ada program
15859 may be handled in three ways by the GNAT compiler:
15860
15861 @enumerate
15862 @item
15863 The illegality may be a violation of the static semantics of Ada. In
15864 that case GNAT diagnoses the constructs in the program that are illegal.
15865 It is then a straightforward matter for the user to modify those parts of
15866 the program.
15867
15868 @item
15869 The illegality may be a violation of the dynamic semantics of Ada. In
15870 that case the program compiles and executes, but may generate incorrect
15871 results, or may terminate abnormally with some exception.
15872
15873 @item
15874 When presented with a program that contains convoluted errors, GNAT
15875 itself may terminate abnormally without providing full diagnostics on
15876 the incorrect user program.
15877 @end enumerate
15878
15879 @menu
15880 * The GNAT Debugger GDB::
15881 * Running GDB::
15882 * Introduction to GDB Commands::
15883 * Using Ada Expressions::
15884 * Calling User-Defined Subprograms::
15885 * Using the Next Command in a Function::
15886 * Ada Exceptions::
15887 * Ada Tasks::
15888 * Debugging Generic Units::
15889 * GNAT Abnormal Termination or Failure to Terminate::
15890 * Naming Conventions for GNAT Source Files::
15891 * Getting Internal Debugging Information::
15892 * Stack Traceback::
15893 @end menu
15894
15895 @cindex Debugger
15896 @findex gdb
15897
15898 @node The GNAT Debugger GDB
15899 @section The GNAT Debugger GDB
15900
15901 @noindent
15902 @code{GDB} is a general purpose, platform-independent debugger that
15903 can be used to debug mixed-language programs compiled with @code{GCC},
15904 and in particular is capable of debugging Ada programs compiled with
15905 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15906 complex Ada data structures.
15907
15908 The manual @cite{Debugging with GDB}
15909 contains full details on the usage of @code{GDB}, including a section on
15910 its usage on programs. This manual should be consulted for full
15911 details. The section that follows is a brief introduction to the
15912 philosophy and use of @code{GDB}.
15913
15914 When GNAT programs are compiled, the compiler optionally writes debugging
15915 information into the generated object file, including information on
15916 line numbers, and on declared types and variables. This information is
15917 separate from the generated code. It makes the object files considerably
15918 larger, but it does not add to the size of the actual executable that
15919 will be loaded into memory, and has no impact on run-time performance. The
15920 generation of debug information is triggered by the use of the
15921 -g switch in the gcc or gnatmake command used to carry out
15922 the compilations. It is important to emphasize that the use of these
15923 options does not change the generated code.
15924
15925 The debugging information is written in standard system formats that
15926 are used by many tools, including debuggers and profilers. The format
15927 of the information is typically designed to describe C types and
15928 semantics, but GNAT implements a translation scheme which allows full
15929 details about Ada types and variables to be encoded into these
15930 standard C formats. Details of this encoding scheme may be found in
15931 the file exp_dbug.ads in the GNAT source distribution. However, the
15932 details of this encoding are, in general, of no interest to a user,
15933 since @code{GDB} automatically performs the necessary decoding.
15934
15935 When a program is bound and linked, the debugging information is
15936 collected from the object files, and stored in the executable image of
15937 the program. Again, this process significantly increases the size of
15938 the generated executable file, but it does not increase the size of
15939 the executable program itself. Furthermore, if this program is run in
15940 the normal manner, it runs exactly as if the debug information were
15941 not present, and takes no more actual memory.
15942
15943 However, if the program is run under control of @code{GDB}, the
15944 debugger is activated.  The image of the program is loaded, at which
15945 point it is ready to run.  If a run command is given, then the program
15946 will run exactly as it would have if @code{GDB} were not present. This
15947 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
15948 entirely non-intrusive until a breakpoint is encountered.  If no
15949 breakpoint is ever hit, the program will run exactly as it would if no
15950 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15951 the debugging information and can respond to user commands to inspect
15952 variables, and more generally to report on the state of execution.
15953
15954 @node Running GDB
15955 @section Running GDB
15956
15957 @noindent
15958 The debugger can be launched directly and simply from @code{glide} or
15959 through its graphical interface: @code{gvd}. It can also be used
15960 directly in text mode. Here is described the basic use of @code{GDB}
15961 in text mode. All the commands described below can be used in the
15962 @code{gvd} console window eventhough there is usually other more
15963 graphical ways to achieve the same goals.
15964
15965 @noindent
15966 The command to run de graphical interface of the debugger is
15967 @smallexample
15968 $ gvd program
15969 @end smallexample
15970
15971 @noindent
15972 The command to run @code{GDB} in text mode is
15973
15974 @smallexample
15975 $ gdb program
15976 @end smallexample
15977
15978 @noindent
15979 where @code{program} is the name of the executable file. This
15980 activates the debugger and results in a prompt for debugger commands.
15981 The simplest command is simply @code{run}, which causes the program to run
15982 exactly as if the debugger were not present. The following section
15983 describes some of the additional commands that can be given to @code{GDB}.
15984
15985
15986 @node Introduction to GDB Commands
15987 @section Introduction to GDB Commands
15988
15989 @noindent
15990 @code{GDB} contains a large repertoire of commands. The manual
15991 @cite{Debugging with GDB}
15992 includes extensive documentation on the use
15993 of these commands, together with examples of their use. Furthermore,
15994 the command @var{help} invoked from within @code{GDB} activates a simple help
15995 facility which summarizes the available commands and their options.
15996 In this section we summarize a few of the most commonly
15997 used commands to give an idea of what @code{GDB} is about. You should create
15998 a simple program with debugging information and experiment with the use of
15999 these @code{GDB} commands on the program as you read through the
16000 following section.
16001
16002 @table @code
16003 @item set args @var{arguments}
16004 The @var{arguments} list above is a list of arguments to be passed to
16005 the program on a subsequent run command, just as though the arguments
16006 had been entered on a normal invocation of the program. The @code{set args}
16007 command is not needed if the program does not require arguments.
16008
16009 @item run
16010 The @code{run} command causes execution of the program to start from
16011 the beginning. If the program is already running, that is to say if
16012 you are currently positioned at a breakpoint, then a prompt will ask
16013 for confirmation that you want to abandon the current execution and
16014 restart.
16015
16016 @item breakpoint @var{location}
16017 The breakpoint command sets a breakpoint, that is to say a point at which
16018 execution will halt and @code{GDB} will await further
16019 commands. @var{location} is
16020 either a line number within a file, given in the format @code{file:linenumber},
16021 or it is the name of a subprogram. If you request that a breakpoint be set on
16022 a subprogram that is overloaded, a prompt will ask you to specify on which of
16023 those subprograms you want to breakpoint. You can also
16024 specify that all of them should be breakpointed. If the program is run
16025 and execution encounters the breakpoint, then the program
16026 stops and @code{GDB} signals that the breakpoint was encountered by
16027 printing the line of code before which the program is halted.
16028
16029 @item breakpoint exception @var{name}
16030 A special form of the breakpoint command which breakpoints whenever
16031 exception @var{name} is raised.
16032 If @var{name} is omitted,
16033 then a breakpoint will occur when any exception is raised.
16034
16035 @item print @var{expression}
16036 This will print the value of the given expression. Most simple
16037 Ada expression formats are properly handled by @code{GDB}, so the expression
16038 can contain function calls, variables, operators, and attribute references.
16039
16040 @item continue
16041 Continues execution following a breakpoint, until the next breakpoint or the
16042 termination of the program.
16043
16044 @item step
16045 Executes a single line after a breakpoint. If the next statement is a subprogram
16046 call, execution continues into (the first statement of) the
16047 called subprogram.
16048
16049 @item next
16050 Executes a single line. If this line is a subprogram call, executes and
16051 returns from the call.
16052
16053 @item list
16054 Lists a few lines around the current source location. In practice, it
16055 is usually more convenient to have a separate edit window open with the
16056 relevant source file displayed. Successive applications of this command
16057 print subsequent lines. The command can be given an argument which is a
16058 line number, in which case it displays a few lines around the specified one.
16059
16060 @item backtrace
16061 Displays a backtrace of the call chain. This command is typically
16062 used after a breakpoint has occurred, to examine the sequence of calls that
16063 leads to the current breakpoint. The display includes one line for each
16064 activation record (frame) corresponding to an active subprogram.
16065
16066 @item up
16067 At a breakpoint, @code{GDB} can display the values of variables local
16068 to the current frame. The command @code{up} can be used to
16069 examine the contents of other active frames, by moving the focus up
16070 the stack, that is to say from callee to caller, one frame at a time.
16071
16072 @item down
16073 Moves the focus of @code{GDB} down from the frame currently being
16074 examined to the frame of its callee (the reverse of the previous command),
16075
16076 @item frame @var{n}
16077 Inspect the frame with the given number. The value 0 denotes the frame
16078 of the current breakpoint, that is to say the top of the call stack.
16079
16080 @end table
16081
16082 The above list is a very short introduction to the commands that
16083 @code{GDB} provides. Important additional capabilities, including conditional
16084 breakpoints, the ability to execute command sequences on a breakpoint,
16085 the ability to debug at the machine instruction level and many other
16086 features are described in detail in @cite{Debugging with GDB}.
16087 Note that most commands can be abbreviated
16088 (for example, c for continue, bt for backtrace).
16089
16090 @node Using Ada Expressions
16091 @section Using Ada Expressions
16092 @cindex Ada expressions
16093
16094 @noindent
16095 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
16096 extensions. The philosophy behind the design of this subset is
16097
16098 @itemize @bullet
16099 @item
16100 That @code{GDB} should provide basic literals and access to operations for
16101 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
16102 leaving more sophisticated computations to subprograms written into the
16103 program (which therefore may be called from @code{GDB}).
16104
16105 @item
16106 That type safety and strict adherence to Ada language restrictions
16107 are not particularly important to the @code{GDB} user.
16108
16109 @item
16110 That brevity is important to the @code{GDB} user.
16111 @end itemize
16112
16113 Thus, for brevity, the debugger acts as if there were
16114 implicit @code{with} and @code{use} clauses in effect for all user-written
16115 packages, thus making it unnecessary to fully qualify most names with
16116 their packages, regardless of context. Where this causes ambiguity,
16117 @code{GDB} asks the user's intent.
16118
16119 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
16120
16121 @node Calling User-Defined Subprograms
16122 @section Calling User-Defined Subprograms
16123
16124 @noindent
16125 An important capability of @code{GDB} is the ability to call user-defined
16126 subprograms while debugging. This is achieved simply by entering
16127 a subprogram call statement in the form:
16128
16129 @smallexample
16130 call subprogram-name (parameters)
16131 @end smallexample
16132
16133 @noindent
16134 The keyword @code{call} can be omitted in the normal case where the
16135 @code{subprogram-name} does not coincide with any of the predefined
16136 @code{GDB} commands.
16137
16138 The effect is to invoke the given subprogram, passing it the
16139 list of parameters that is supplied. The parameters can be expressions and
16140 can include variables from the program being debugged. The
16141 subprogram must be defined
16142 at the library level within your program, and @code{GDB} will call the
16143 subprogram within the environment of your program execution (which
16144 means that the subprogram is free to access or even modify variables
16145 within your program).
16146
16147 The most important use of this facility is in allowing the inclusion of
16148 debugging routines that are tailored to particular data structures
16149 in your program. Such debugging routines can be written to provide a suitably
16150 high-level description of an abstract type, rather than a low-level dump
16151 of its physical layout. After all, the standard
16152 @code{GDB print} command only knows the physical layout of your
16153 types, not their abstract meaning. Debugging routines can provide information
16154 at the desired semantic level and are thus enormously useful.
16155
16156 For example, when debugging GNAT itself, it is crucial to have access to
16157 the contents of the tree nodes used to represent the program internally.
16158 But tree nodes are represented simply by an integer value (which in turn
16159 is an index into a table of nodes).
16160 Using the @code{print} command on a tree node would simply print this integer
16161 value, which is not very useful. But the PN routine (defined in file
16162 treepr.adb in the GNAT sources) takes a tree node as input, and displays
16163 a useful high level representation of the tree node, which includes the
16164 syntactic category of the node, its position in the source, the integers
16165 that denote descendant nodes and parent node, as well as varied
16166 semantic information. To study this example in more detail, you might want to
16167 look at the body of the PN procedure in the stated file.
16168
16169 @node Using the Next Command in a Function
16170 @section Using the Next Command in a Function
16171
16172 @noindent
16173 When you use the @code{next} command in a function, the current source
16174 location will advance to the next statement as usual. A special case
16175 arises in the case of a @code{return} statement.
16176
16177 Part of the code for a return statement is the "epilog" of the function.
16178 This is the code that returns to the caller. There is only one copy of
16179 this epilog code, and it is typically associated with the last return
16180 statement in the function if there is more than one return. In some
16181 implementations, this epilog is associated with the first statement
16182 of the function.
16183
16184 The result is that if you use the @code{next} command from a return
16185 statement that is not the last return statement of the function you
16186 may see a strange apparent jump to the last return statement or to
16187 the start of the function. You should simply ignore this odd jump.
16188 The value returned is always that from the first return statement
16189 that was stepped through.
16190
16191 @node Ada Exceptions
16192 @section Breaking on Ada Exceptions
16193 @cindex Exceptions
16194
16195 @noindent
16196 You can set breakpoints that trip when your program raises
16197 selected exceptions.
16198
16199 @table @code
16200 @item break exception
16201 Set a breakpoint that trips whenever (any task in the) program raises
16202 any exception.
16203
16204 @item break exception @var{name}
16205 Set a breakpoint that trips whenever (any task in the) program raises
16206 the exception @var{name}.
16207
16208 @item break exception unhandled
16209 Set a breakpoint that trips whenever (any task in the) program raises an
16210 exception for which there is no handler.
16211
16212 @item info exceptions
16213 @itemx info exceptions @var{regexp}
16214 The @code{info exceptions} command permits the user to examine all defined
16215 exceptions within Ada programs. With a regular expression, @var{regexp}, as
16216 argument, prints out only those exceptions whose name matches @var{regexp}.
16217 @end table
16218
16219 @node Ada Tasks
16220 @section Ada Tasks
16221 @cindex Tasks
16222
16223 @noindent
16224 @code{GDB} allows the following task-related commands:
16225
16226 @table @code
16227 @item info tasks
16228 This command shows a list of current Ada tasks, as in the following example:
16229
16230 @smallexample
16231 @iftex
16232 @leftskip=0cm
16233 @end iftex
16234 (gdb) info tasks
16235   ID       TID P-ID   Thread Pri State                 Name
16236    1   8088000   0   807e000  15 Child Activation Wait main_task
16237    2   80a4000   1   80ae000  15 Accept/Select Wait    b
16238    3   809a800   1   80a4800  15 Child Activation Wait a
16239 *  4   80ae800   3   80b8000  15 Running               c
16240 @end smallexample
16241
16242 @noindent
16243 In this listing, the asterisk before the first task indicates it to be the
16244 currently running task. The first column lists the task ID that is used
16245 to refer to tasks in the following commands.
16246
16247 @item break @var{linespec} task @var{taskid}
16248 @itemx break @var{linespec} task @var{taskid} if @dots{}
16249 @cindex Breakpoints and tasks
16250 These commands are like the @code{break @dots{} thread @dots{}}.
16251 @var{linespec} specifies source lines.
16252
16253 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
16254 to specify that you only want @code{GDB} to stop the program when a
16255 particular Ada task reaches this breakpoint. @var{taskid} is one of the
16256 numeric task identifiers assigned by @code{GDB}, shown in the first
16257 column of the @samp{info tasks} display.
16258
16259 If you do not specify @samp{task @var{taskid}} when you set a
16260 breakpoint, the breakpoint applies to @emph{all} tasks of your
16261 program.
16262
16263 You can use the @code{task} qualifier on conditional breakpoints as
16264 well; in this case, place @samp{task @var{taskid}} before the
16265 breakpoint condition (before the @code{if}).
16266
16267 @item task @var{taskno}
16268 @cindex Task switching
16269
16270 This command allows to switch to the task referred by @var{taskno}. In
16271 particular, This allows to browse the backtrace of the specified
16272 task. It is advised to switch back to the original task before
16273 continuing execution otherwise the scheduling of the program may be
16274 perturbated.
16275 @end table
16276
16277 @noindent
16278 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
16279
16280 @node Debugging Generic Units
16281 @section Debugging Generic Units
16282 @cindex Debugging Generic Units
16283 @cindex Generics
16284
16285 @noindent
16286 GNAT always uses code expansion for generic instantiation. This means that
16287 each time an instantiation occurs, a complete copy of the original code is
16288 made, with appropriate substitutions of formals by actuals.
16289
16290 It is not possible to refer to the original generic entities in
16291 @code{GDB}, but it is always possible to debug a particular instance of
16292 a generic, by using the appropriate expanded names. For example, if we have
16293
16294 @smallexample
16295 @group
16296 @cartouche
16297 @b{procedure} g @b{is}
16298
16299    @b{generic package} k @b{is}
16300       @b{procedure} kp (v1 : @b{in out} integer);
16301    @b{end} k;
16302
16303    @b{package body} k @b{is}
16304       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
16305       @b{begin}
16306          v1 := v1 + 1;
16307       @b{end} kp;
16308    @b{end} k;
16309
16310    @b{package} k1 @b{is new} k;
16311    @b{package} k2 @b{is new} k;
16312
16313    var : integer := 1;
16314
16315 @b{begin}
16316    k1.kp (var);
16317    k2.kp (var);
16318    k1.kp (var);
16319    k2.kp (var);
16320 @b{end};
16321 @end cartouche
16322 @end group
16323 @end smallexample
16324
16325 @noindent
16326 Then to break on a call to procedure kp in the k2 instance, simply
16327 use the command:
16328
16329 @smallexample
16330 (gdb) break g.k2.kp
16331 @end smallexample
16332
16333 @noindent
16334 When the breakpoint occurs, you can step through the code of the
16335 instance in the normal manner and examine the values of local variables, as for
16336 other units.
16337
16338 @node GNAT Abnormal Termination or Failure to Terminate
16339 @section GNAT Abnormal Termination or Failure to Terminate
16340 @cindex GNAT Abnormal Termination or Failure to Terminate
16341
16342 @noindent
16343 When presented with programs that contain serious errors in syntax
16344 or semantics,
16345 GNAT may on rare occasions  experience problems in operation, such
16346 as aborting with a
16347 segmentation fault or illegal memory access, raising an internal
16348 exception, terminating abnormally, or failing to terminate at all.
16349 In such cases, you can activate
16350 various features of GNAT that can help you pinpoint the construct in your
16351 program that is the likely source of the problem.
16352
16353 The following strategies are presented in increasing order of
16354 difficulty, corresponding to your experience in using GNAT and your
16355 familiarity with compiler internals.
16356
16357 @enumerate
16358 @item
16359 Run @code{gcc} with the @option{-gnatf}. This first
16360 switch causes all errors on a given line to be reported. In its absence,
16361 only the first error on a line is displayed.
16362
16363 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16364 are encountered, rather than after compilation is terminated. If GNAT
16365 terminates prematurely or goes into an infinite loop, the last error
16366 message displayed may help to pinpoint the culprit.
16367
16368 @item
16369 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16370 @code{gcc} produces ongoing information about the progress of the
16371 compilation and provides the name of each procedure as code is
16372 generated. This switch allows you to find which Ada procedure was being
16373 compiled when it encountered a code generation problem.
16374
16375 @item
16376 @cindex @option{-gnatdc} switch
16377 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16378 switch that does for the front-end what @code{-v} does for the back end.
16379 The system prints the name of each unit, either a compilation unit or
16380 nested unit, as it is being analyzed.
16381 @item
16382 Finally, you can start
16383 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16384 front-end of GNAT, and can be run independently (normally it is just
16385 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16386 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16387 @code{where} command is the first line of attack; the variable
16388 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16389 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16390 which the execution stopped, and @code{input_file name} indicates the name of
16391 the source file.
16392 @end enumerate
16393
16394 @node Naming Conventions for GNAT Source Files
16395 @section Naming Conventions for GNAT Source Files
16396
16397 @noindent
16398 In order to examine the workings of the GNAT system, the following
16399 brief description of its organization may be helpful:
16400
16401 @itemize @bullet
16402 @item
16403 Files with prefix @file{sc} contain the lexical scanner.
16404
16405 @item
16406 All files prefixed with @file{par} are components of the parser. The
16407 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16408 parsing of select statements can be found in @file{par-ch9.adb}.
16409
16410 @item
16411 All files prefixed with @file{sem} perform semantic analysis. The
16412 numbers correspond to chapters of the Ada standard. For example, all
16413 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16414 addition, some features of the language require sufficient special processing
16415 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16416 dynamic dispatching, etc.
16417
16418 @item
16419 All files prefixed with @file{exp} perform normalization and
16420 expansion of the intermediate representation (abstract syntax tree, or AST).
16421 these files use the same numbering scheme as the parser and semantics files.
16422 For example, the construction of record initialization procedures is done in
16423 @file{exp_ch3.adb}.
16424
16425 @item
16426 The files prefixed with @file{bind} implement the binder, which
16427 verifies the consistency of the compilation, determines an order of
16428 elaboration, and generates the bind file.
16429
16430 @item
16431 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16432 data structures used by the front-end.
16433
16434 @item
16435 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16436 the abstract syntax tree as produced by the parser.
16437
16438 @item
16439 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16440 all entities, computed during semantic analysis.
16441
16442 @item
16443 Library management issues are dealt with in files with prefix
16444 @file{lib}.
16445
16446 @item
16447 @findex Ada
16448 @cindex Annex A
16449 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16450 defined in Annex A.
16451
16452 @item
16453 @findex Interfaces
16454 @cindex Annex B
16455 Files with prefix @file{i-} are children of @code{Interfaces}, as
16456 defined in Annex B.
16457
16458 @item
16459 @findex System
16460 Files with prefix @file{s-} are children of @code{System}. This includes
16461 both language-defined children and GNAT run-time routines.
16462
16463 @item
16464 @findex GNAT
16465 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16466 general-purpose packages, fully documented in their specifications. All
16467 the other @file{.c} files are modifications of common @code{gcc} files.
16468 @end itemize
16469
16470 @node Getting Internal Debugging Information
16471 @section Getting Internal Debugging Information
16472
16473 @noindent
16474 Most compilers have internal debugging switches and modes. GNAT
16475 does also, except GNAT internal debugging switches and modes are not
16476 secret. A summary and full description of all the compiler and binder
16477 debug flags are in the file @file{debug.adb}. You must obtain the
16478 sources of the compiler to see the full detailed effects of these flags.
16479
16480 The switches that print the source of the program (reconstructed from
16481 the internal tree) are of general interest for user programs, as are the
16482 options to print
16483 the full internal tree, and the entity table (the symbol table
16484 information). The reconstructed source provides a readable version of the
16485 program after the front-end has completed analysis and  expansion, and is useful
16486 when studying the performance of specific constructs. For example, constraint
16487 checks are indicated, complex aggregates are replaced with loops and
16488 assignments, and tasking primitives are replaced with run-time calls.
16489
16490 @node Stack Traceback
16491 @section Stack Traceback
16492 @cindex traceback
16493 @cindex stack traceback
16494 @cindex stack unwinding
16495
16496 @noindent
16497 Traceback is a mechanism to display the sequence of subprogram calls that
16498 leads to a specified execution point in a program. Often (but not always)
16499 the execution point is an instruction at which an exception has been raised.
16500 This mechanism is also known as @i{stack unwinding} because it obtains
16501 its information by scanning the run-time stack and recovering the activation
16502 records of all active subprograms. Stack unwinding is one of the most
16503 important tools for program debugging.
16504
16505 @noindent
16506 The first entry stored in traceback corresponds to the deepest calling level,
16507 that is to say the subprogram currently executing the instruction
16508 from which we want to obtain the traceback.
16509
16510 @noindent
16511 Note that there is no runtime performance penalty when stack traceback
16512 is enabled and no exception are raised during program execution.
16513
16514 @menu
16515 * Non-Symbolic Traceback::
16516 * Symbolic Traceback::
16517 @end menu
16518
16519 @node Non-Symbolic Traceback
16520 @subsection Non-Symbolic Traceback
16521 @cindex traceback, non-symbolic
16522
16523 @noindent
16524 Note: this feature is not supported on all platforms. See
16525 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16526 platforms.
16527
16528 @menu
16529 * Tracebacks From an Unhandled Exception::
16530 * Tracebacks From Exception Occurrences (non-symbolic)::
16531 * Tracebacks From Anywhere in a Program (non-symbolic)::
16532 @end menu
16533
16534 @node Tracebacks From an Unhandled Exception
16535 @subsubsection Tracebacks From an Unhandled Exception
16536
16537 @noindent
16538 A runtime non-symbolic traceback is a list of addresses of call instructions.
16539 To enable this feature you must use the @code{-E}
16540 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16541 of exception information. It is possible to retrieve this information using the
16542 standard @code{Ada.Exception.Exception_Information} routine.
16543
16544 @noindent
16545 Let's have a look at a simple example:
16546
16547 @smallexample
16548 @cartouche
16549 @group
16550 procedure STB is
16551
16552    procedure P1 is
16553    begin
16554       raise Constraint_Error;
16555    end P1;
16556
16557    procedure P2 is
16558    begin
16559       P1;
16560    end P2;
16561
16562 begin
16563    P2;
16564 end STB;
16565 @end group
16566 @end cartouche
16567 @end smallexample
16568
16569 @smallexample
16570 $ gnatmake stb -bargs -E
16571 $ stb
16572
16573 Execution terminated by unhandled exception
16574 Exception name: CONSTRAINT_ERROR
16575 Message: stb.adb:5
16576 Call stack traceback locations:
16577 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16578 @end smallexample
16579
16580 @noindent
16581 As we see the traceback lists a sequence of addresses for the unhandled
16582 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16583 guess that this exception come from procedure P1. To translate these
16584 addresses into the source lines where the calls appear, the
16585 @code{addr2line} tool, described below, is invaluable. The use of this tool
16586 requires the program to be compiled with debug information.
16587
16588 @smallexample
16589 $ gnatmake -g stb -bargs -E
16590 $ stb
16591
16592 Execution terminated by unhandled exception
16593 Exception name: CONSTRAINT_ERROR
16594 Message: stb.adb:5
16595 Call stack traceback locations:
16596 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16597
16598 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16599    0x4011f1 0x77e892a4
16600
16601 00401373 at d:/stb/stb.adb:5
16602 0040138B at d:/stb/stb.adb:10
16603 0040139C at d:/stb/stb.adb:14
16604 00401335 at d:/stb/b~stb.adb:104
16605 004011C4 at /build/.../crt1.c:200
16606 004011F1 at /build/.../crt1.c:222
16607 77E892A4 in ?? at ??:0
16608 @end smallexample
16609
16610 @noindent
16611 @code{addr2line} has a number of other useful options:
16612
16613 @table @code
16614 @item --functions
16615 to get the function name corresponding to any location
16616
16617 @item --demangle=gnat
16618 to use the @b{gnat} decoding mode for the function names. Note that
16619 for binutils version 2.9.x the option is simply @code{--demangle}.
16620 @end table
16621
16622 @smallexample
16623 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16624    0x40139c 0x401335 0x4011c4 0x4011f1
16625
16626 00401373 in stb.p1 at d:/stb/stb.adb:5
16627 0040138B in stb.p2 at d:/stb/stb.adb:10
16628 0040139C in stb at d:/stb/stb.adb:14
16629 00401335 in main at d:/stb/b~stb.adb:104
16630 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16631 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16632 @end smallexample
16633
16634 @noindent
16635 From this traceback we can see that the exception was raised in
16636 @file{stb.adb} at line 5, which was reached from a procedure call in
16637 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16638 which contains the call to the main program.
16639 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16640 and the output will vary from platform to platform.
16641
16642 @noindent
16643 It is also possible to use @code{GDB} with these traceback addresses to debug
16644 the program. For example, we can break at a given code location, as reported
16645 in the stack traceback:
16646
16647 @smallexample
16648 $ gdb -nw stb
16649 @noindent
16650 Furthermore, this feature is not implemented inside Windows DLL. Only
16651 the non-symbolic traceback is reported in this case.
16652
16653 (gdb) break *0x401373
16654 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16655 @end smallexample
16656
16657 @noindent
16658 It is important to note that the stack traceback addresses
16659 do not change when debug information is included. This is particularly useful
16660 because it makes it possible to release software without debug information (to
16661 minimize object size), get a field report that includes a stack traceback
16662 whenever an internal bug occurs, and then be able to retrieve the sequence
16663 of calls with the same program compiled with debug information.
16664
16665 @node Tracebacks From Exception Occurrences (non-symbolic)
16666 @subsubsection Tracebacks From Exception Occurrences
16667
16668 @noindent
16669 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16670 The stack traceback is attached to the exception information string, and can
16671 be retrieved in an exception handler within the Ada program, by means of the
16672 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16673
16674 @smallexample
16675 @cartouche
16676 @group
16677 with Ada.Text_IO;
16678 with Ada.Exceptions;
16679
16680 procedure STB is
16681
16682    use Ada;
16683    use Ada.Exceptions;
16684
16685    procedure P1 is
16686       K : Positive := 1;
16687    begin
16688       K := K - 1;
16689    exception
16690       when E : others =>
16691          Text_IO.Put_Line (Exception_Information (E));
16692    end P1;
16693
16694    procedure P2 is
16695    begin
16696       P1;
16697    end P2;
16698
16699 begin
16700    P2;
16701 end STB;
16702 @end group
16703 @end cartouche
16704 @end smallexample
16705
16706 @noindent
16707 This program will output:
16708
16709 @smallexample
16710 $ stb
16711
16712 Exception name: CONSTRAINT_ERROR
16713 Message: stb.adb:12
16714 Call stack traceback locations:
16715 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16716 @end smallexample
16717
16718 @node Tracebacks From Anywhere in a Program (non-symbolic)
16719 @subsubsection Tracebacks From Anywhere in a Program
16720
16721 @noindent
16722 It is also possible to retrieve a stack traceback from anywhere in a
16723 program. For this you need to
16724 use the @code{GNAT.Traceback} API. This package includes a procedure called
16725 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16726 display procedures described below. It is not necessary to use the
16727 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16728 is invoked explicitly.
16729
16730 @noindent
16731 In the following example we compute a traceback at a specific location in
16732 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16733 convert addresses to strings:
16734
16735 @smallexample
16736 @cartouche
16737 @group
16738 with Ada.Text_IO;
16739 with GNAT.Traceback;
16740 with GNAT.Debug_Utilities;
16741
16742 procedure STB is
16743
16744    use Ada;
16745    use GNAT;
16746    use GNAT.Traceback;
16747
16748    procedure P1 is
16749       TB  : Tracebacks_Array (1 .. 10);
16750       --  We are asking for a maximum of 10 stack frames.
16751       Len : Natural;
16752       --  Len will receive the actual number of stack frames returned.
16753    begin
16754       Call_Chain (TB, Len);
16755
16756       Text_IO.Put ("In STB.P1 : ");
16757
16758       for K in 1 .. Len loop
16759          Text_IO.Put (Debug_Utilities.Image (TB (K)));
16760          Text_IO.Put (' ');
16761       end loop;
16762
16763       Text_IO.New_Line;
16764    end P1;
16765
16766    procedure P2 is
16767    begin
16768       P1;
16769    end P2;
16770
16771 begin
16772    P2;
16773 end STB;
16774 @end group
16775 @end cartouche
16776 @end smallexample
16777
16778 @smallexample
16779 $ gnatmake stb
16780 $ stb
16781
16782 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16783 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16784 @end smallexample
16785
16786 @node Symbolic Traceback
16787 @subsection Symbolic Traceback
16788 @cindex traceback, symbolic
16789
16790 @noindent
16791 A symbolic traceback is a stack traceback in which procedure names are
16792 associated with each code location.
16793
16794 @noindent
16795 Note that this feature is not supported on all platforms. See
16796 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16797 list of currently supported platforms.
16798
16799 @noindent
16800 Note that the symbolic traceback requires that the program be compiled
16801 with debug information. If it is not compiled with debug information
16802 only the non-symbolic information will be valid.
16803
16804 @menu
16805 * Tracebacks From Exception Occurrences (symbolic)::
16806 * Tracebacks From Anywhere in a Program (symbolic)::
16807 @end menu
16808
16809 @node Tracebacks From Exception Occurrences (symbolic)
16810 @subsubsection Tracebacks From Exception Occurrences
16811
16812 @smallexample
16813 @cartouche
16814 @group
16815 with Ada.Text_IO;
16816 with GNAT.Traceback.Symbolic;
16817
16818 procedure STB is
16819
16820    procedure P1 is
16821    begin
16822       raise Constraint_Error;
16823    end P1;
16824
16825    procedure P2 is
16826    begin
16827       P1;
16828    end P2;
16829
16830    procedure P3 is
16831    begin
16832       P2;
16833    end P3;
16834
16835 begin
16836    P3;
16837 exception
16838    when E : others =>
16839       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16840 end STB;
16841 @end group
16842 @end cartouche
16843 @end smallexample
16844
16845 @smallexample
16846 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16847 $ stb
16848
16849 0040149F in stb.p1 at stb.adb:8
16850 004014B7 in stb.p2 at stb.adb:13
16851 004014CF in stb.p3 at stb.adb:18
16852 004015DD in ada.stb at stb.adb:22
16853 00401461 in main at b~stb.adb:168
16854 004011C4 in __mingw_CRTStartup at crt1.c:200
16855 004011F1 in mainCRTStartup at crt1.c:222
16856 77E892A4 in ?? at ??:0
16857 @end smallexample
16858
16859 @noindent
16860 The exact sequence of linker options may vary from platform to platform.
16861 The above @code{-largs} section is for Windows platforms. By contrast,
16862 under Unix there is no need for the @code{-largs} section.
16863 Differences across platforms are due to details of linker implementation.
16864
16865 @node Tracebacks From Anywhere in a Program (symbolic)
16866 @subsubsection Tracebacks From Anywhere in a Program
16867
16868 @noindent
16869 It is possible to get a symbolic stack traceback
16870 from anywhere in a program, just as for non-symbolic tracebacks.
16871 The first step is to obtain a non-symbolic
16872 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16873 information. Here is an example:
16874
16875 @smallexample
16876 @cartouche
16877 @group
16878 with Ada.Text_IO;
16879 with GNAT.Traceback;
16880 with GNAT.Traceback.Symbolic;
16881
16882 procedure STB is
16883
16884    use Ada;
16885    use GNAT.Traceback;
16886    use GNAT.Traceback.Symbolic;
16887
16888    procedure P1 is
16889       TB  : Tracebacks_Array (1 .. 10);
16890       --  We are asking for a maximum of 10 stack frames.
16891       Len : Natural;
16892       --  Len will receive the actual number of stack frames returned.
16893    begin
16894       Call_Chain (TB, Len);
16895       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16896    end P1;
16897
16898    procedure P2 is
16899    begin
16900       P1;
16901    end P2;
16902
16903 begin
16904    P2;
16905 end STB;
16906 @end group
16907 @end cartouche
16908 @end smallexample
16909
16910
16911 @node Inline Assembler
16912 @chapter Inline Assembler
16913
16914 @noindent
16915 If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program.  First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT.  However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler.  The Inline Assembler approach offers a number of advantages, including the following:
16916
16917 @itemize @bullet
16918 @item No need to use non-Ada tools
16919 @item Consistent interface over different targets
16920 @item Automatic usage of the proper calling conventions
16921 @item Access to Ada constants and variables
16922 @item Definition of intrinsic routines
16923 @item Possibility of inlining a subprogram comprising assembler code
16924 @item Code optimizer can take Inline Assembler code into account
16925 @end itemize
16926
16927 This chapter presents a series of examples to show you how to use the Inline Assembler.  Although it focuses on the Intel x86, the general approach applies also to other processors.  It is assumed that you are familiar with Ada and with assembly language programming.
16928
16929 @menu
16930 * Basic Assembler Syntax::
16931 * A Simple Example of Inline Assembler::
16932 * Output Variables in Inline Assembler::
16933 * Input Variables in Inline Assembler::
16934 * Inlining Inline Assembler Code::
16935 * Other Asm Functionality::
16936 * A Complete Example::
16937 @end menu
16938
16939 @c ---------------------------------------------------------------------------
16940 @node Basic Assembler Syntax
16941 @section Basic Assembler Syntax
16942
16943 @noindent
16944 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16945 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16946 referred to as ``AT&T syntax'').
16947 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16948 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16949 pre-processor) documentation for further information.
16950
16951 @table @asis
16952 @item Register names
16953 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16954 @*
16955 Intel: No extra punctuation; for example @code{eax}
16956
16957 @item Immediate operand
16958 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16959 @*
16960 Intel: No extra punctuation; for example @code{4}
16961
16962 @item Address
16963 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16964 @*
16965 Intel: No extra punctuation; for example @code{loc}
16966
16967 @item Memory contents
16968 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16969 @*
16970 Intel: Square brackets; for example @code{[loc]}
16971
16972 @item Register contents
16973 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16974 @*
16975 Intel: Square brackets; for example @code{[eax]}
16976
16977 @item Hexadecimal numbers
16978 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16979 @*
16980 Intel: Trailing ``h''; for example @code{A0h}
16981
16982 @item Operand size
16983 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16984 @*
16985 Intel: Implicit, deduced by assembler; for example @code{mov}
16986
16987 @item Instruction repetition
16988 gcc / @emph{as}: Split into two lines; for example
16989 @*
16990 @code{rep}
16991 @*
16992 @code{stosl}
16993 @*
16994 Intel: Keep on one line; for example @code{rep stosl}
16995
16996 @item Order of operands
16997 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
16998 @*
16999 Intel: Destination first; for example @code{mov eax, 4}
17000 @end table
17001
17002 @c ---------------------------------------------------------------------------
17003 @node A Simple Example of Inline Assembler
17004 @section A Simple Example of Inline Assembler
17005
17006 @noindent
17007 The following example will generate a single assembly language statement, @code{nop}, which does nothing.  Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility.
17008
17009 @smallexample
17010 @group
17011 with System.Machine_Code; use System.Machine_Code;
17012 procedure Nothing is
17013 begin
17014    Asm ("nop");
17015 end Nothing;
17016 @end group
17017 @end smallexample
17018
17019 @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction.
17020 @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions.
17021
17022 The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}.
17023
17024 Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}.  You can build the executable in the usual way:
17025 @smallexample
17026 gnatmake nothing
17027 @end smallexample
17028 However, the interesting aspect of this example is not its run-time behavior but rather the
17029 generated assembly code.  To see this output, invoke the compiler as follows:
17030 @smallexample
17031    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
17032 @end smallexample
17033 where the options are:
17034
17035 @table @code
17036 @item -c
17037 compile only (no bind or link)
17038 @item -S
17039 generate assembler listing
17040 @item -fomit-frame-pointer
17041 do not set up separate stack frames
17042 @item -gnatp
17043 do not add runtime checks
17044 @end table
17045
17046 This gives a human-readable assembler version of the code. The resulting
17047 file will have the same name as the Ada source file, but with a @code{.s} extension.
17048 In our example, the file @file{nothing.s} has the following contents:
17049
17050 @smallexample
17051 @group
17052 .file "nothing.adb"
17053 gcc2_compiled.:
17054 ___gnu_compiled_ada:
17055 .text
17056    .align 4
17057 .globl __ada_nothing
17058 __ada_nothing:
17059 #APP
17060    nop
17061 #NO_APP
17062    jmp L1
17063    .align 2,0x90
17064 L1:
17065    ret
17066 @end group
17067 @end smallexample
17068
17069 The assembly code you included is clearly indicated by
17070 the compiler, between the @code{#APP} and @code{#NO_APP}
17071 delimiters. The character before the 'APP' and 'NOAPP'
17072 can differ on different targets. For example, Linux uses '#APP' while
17073 on NT you will see '/APP'.
17074
17075 If you make a mistake in your assembler code (such as using the
17076 wrong size modifier, or using a wrong operand for the instruction) GNAT
17077 will report this error in a temporary file, which will be deleted when
17078 the compilation is finished.  Generating an assembler file will help
17079 in such cases, since you can assemble this file separately using the
17080 @emph{as} assembler that comes with gcc.
17081
17082 Assembling the file using the command
17083
17084 @smallexample
17085 as @file{nothing.s}
17086 @end smallexample
17087 @noindent
17088 will give you error messages whose lines correspond to the assembler
17089 input file, so you can easily find and correct any mistakes you made.
17090 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
17091
17092 @c ---------------------------------------------------------------------------
17093 @node Output Variables in Inline Assembler
17094 @section Output Variables in Inline Assembler
17095
17096 @noindent
17097 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
17098
17099 @smallexample
17100 @group
17101 with Interfaces; use Interfaces;
17102 with Ada.Text_IO; use Ada.Text_IO;
17103 with System.Machine_Code; use System.Machine_Code;
17104 procedure Get_Flags is
17105    Flags : Unsigned_32;
17106    use ASCII;
17107 begin
17108    Asm ("pushfl"          & LF & HT & -- push flags on stack
17109         "popl %%eax"      & LF & HT & -- load eax with flags
17110         "movl %%eax, %0",             -- store flags in variable
17111         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17112    Put_Line ("Flags register:" & Flags'Img);
17113 end Get_Flags;
17114 @end group
17115 @end smallexample
17116
17117 In order to have a nicely aligned assembly listing, we have separated
17118 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
17119 and horizontal tab (ASCII.HT) characters.  The resulting section of the
17120 assembly output file is:
17121
17122 @smallexample
17123 @group
17124 #APP
17125    pushfl
17126    popl %eax
17127    movl %eax, -40(%ebp)
17128 #NO_APP
17129 @end group
17130 @end smallexample
17131
17132 It would have been legal to write the Asm invocation as:
17133
17134 @smallexample
17135 Asm ("pushfl popl %%eax movl %%eax, %0")
17136 @end smallexample
17137
17138 but in the generated assembler file, this would come out as:
17139
17140 @smallexample
17141 #APP
17142    pushfl popl %eax movl %eax, -40(%ebp)
17143 #NO_APP
17144 @end smallexample
17145
17146 which is not so convenient for the human reader.
17147
17148 We use Ada comments
17149 at the end of each line to explain what the assembler instructions
17150 actually do.  This is a useful convention.
17151
17152 When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign.  Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}.  In the generated assembly code, one of the percent signs will be stripped off.
17153
17154 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}.
17155 An output variable is illustrated in
17156 the third statement in the Asm template string:
17157 @smallexample
17158 movl %%eax, %0
17159 @end smallexample
17160 The intent is to store the contents of the eax register in a variable that can be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization.  The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable.
17161
17162 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
17163 @smallexample
17164 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17165 @end smallexample
17166
17167 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
17168 @smallexample
17169 Type'Asm_Output (constraint_string, variable_name)
17170 @end smallexample
17171
17172 The constraint string directs the compiler how
17173 to store/access the associated variable.  In the example
17174 @smallexample
17175 Unsigned_32'Asm_Output ("=m", Flags);
17176 @end smallexample
17177 the @code{"m"} (memory) constraint tells the compiler that the variable
17178 @code{Flags} should be stored in a memory variable, thus preventing
17179 the optimizer from keeping it in a register.  In contrast,
17180 @smallexample
17181 Unsigned_32'Asm_Output ("=r", Flags);
17182 @end smallexample
17183 uses the @code{"r"} (register) constraint, telling the compiler to
17184 store the variable in a register.
17185
17186 If the constraint is preceded by the equal character (@strong{=}), it tells the
17187 compiler that the variable will be used to store data into it.
17188
17189 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
17190 to choose whatever it deems best.
17191
17192 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
17193
17194 @table @code
17195 @item =
17196 output constraint
17197 @item g
17198 global (i.e. can be stored anywhere)
17199 @item m
17200 in memory
17201 @item I
17202 a constant
17203 @item a
17204 use eax
17205 @item b
17206 use ebx
17207 @item c
17208 use ecx
17209 @item d
17210 use edx
17211 @item S
17212 use esi
17213 @item D
17214 use edi
17215 @item r
17216 use one of eax, ebx, ecx or edx
17217 @item q
17218 use one of eax, ebx, ecx, edx, esi or edi
17219 @end table
17220
17221 The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string.
17222
17223 You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer.  Thus in
17224 @smallexample
17225 @group
17226 Asm ("pushfl"          & LF & HT & -- push flags on stack
17227      "popl %%eax"      & LF & HT & -- load eax with flags
17228      "movl %%eax, %0",             -- store flags in variable
17229      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17230 @end group
17231 @end smallexample
17232 @noindent
17233 @code{%0} will be replaced in the expanded code by the appropriate operand,
17234 whatever
17235 the compiler decided for the @code{Flags} variable.
17236
17237 In general, you may have any number of output variables:
17238 @itemize @bullet
17239 @item
17240 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
17241 @item
17242 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
17243 @end itemize
17244
17245 For example:
17246 @smallexample
17247 @group
17248 Asm ("movl %%eax, %0" & LF & HT &
17249      "movl %%ebx, %1" & LF & HT &
17250      "movl %%ecx, %2",
17251      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
17252                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
17253                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
17254 @end group
17255 @end smallexample
17256 @noindent
17257 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
17258
17259 As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string:
17260
17261 @smallexample
17262 @group
17263 with Interfaces; use Interfaces;
17264 with Ada.Text_IO; use Ada.Text_IO;
17265 with System.Machine_Code; use System.Machine_Code;
17266 procedure Get_Flags_2 is
17267    Flags : Unsigned_32;
17268    use ASCII;
17269 begin
17270    Asm ("pushfl"      & LF & HT & -- push flags on stack
17271         "popl %%eax",             -- save flags in eax
17272         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
17273    Put_Line ("Flags register:" & Flags'Img);
17274 end Get_Flags_2;
17275 @end group
17276 @end smallexample
17277
17278 @noindent
17279 The @code{"a"} constraint tells the compiler that the @code{Flags}
17280 variable will come from the eax register. Here is the resulting code:
17281
17282 @smallexample
17283 @group
17284 #APP
17285    pushfl
17286    popl %eax
17287 #NO_APP
17288    movl %eax,-40(%ebp)
17289 @end group
17290 @end smallexample
17291
17292 @noindent
17293 The compiler generated the store of eax into Flags after
17294 expanding the assembler code.
17295
17296 Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable:
17297
17298 @smallexample
17299 @group
17300 with Interfaces; use Interfaces;
17301 with Ada.Text_IO; use Ada.Text_IO;
17302 with System.Machine_Code; use System.Machine_Code;
17303 procedure Get_Flags_3 is
17304    Flags : Unsigned_32;
17305    use ASCII;
17306 begin
17307    Asm ("pushfl"  & LF & HT & -- push flags on stack
17308         "pop %0",             -- save flags in Flags
17309         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17310    Put_Line ("Flags register:" & Flags'Img);
17311 end Get_Flags_3;
17312 @end group
17313 @end smallexample
17314
17315 @c ---------------------------------------------------------------------------
17316 @node Input Variables in Inline Assembler
17317 @section Input Variables in Inline Assembler
17318
17319 @noindent
17320 The example in this section illustrates how to specify the source operands for assembly language statements.  The program simply increments its input value by 1:
17321
17322 @smallexample
17323 @group
17324 with Interfaces; use Interfaces;
17325 with Ada.Text_IO; use Ada.Text_IO;
17326 with System.Machine_Code; use System.Machine_Code;
17327 procedure Increment is
17328
17329    function Incr (Value : Unsigned_32) return Unsigned_32 is
17330       Result : Unsigned_32;
17331    begin
17332       Asm ("incl %0",
17333            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17334            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17335       return Result;
17336    end Incr;
17337
17338    Value : Unsigned_32;
17339
17340 begin
17341    Value := 5;
17342    Put_Line ("Value before is" & Value'Img);
17343    Value := Incr (Value);
17344    Put_Line ("Value after is" & Value'Img);
17345 end Increment;
17346 @end group
17347 @end smallexample
17348
17349 The @code{Outputs} parameter to @code{Asm} specifies
17350 that the result will be in the eax register and that it is to be stored in the @code{Result}
17351 variable.
17352
17353 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17354 @code{Asm_Input} attribute. The
17355 @code{"="} constraint, indicating an output value, is not present.
17356
17357 You can have multiple input variables, in the same way that you can have more
17358 than one output variable.
17359
17360 The parameter count (%0, %1) etc, now starts at the first input
17361 statement, and continues with the output statements.
17362 When both parameters use the same variable, the
17363 compiler will treat them as the same %n operand, which is the case here.
17364
17365 Just as the @code{Outputs} parameter causes the register to be stored into the
17366 target variable after execution of the assembler statements, so does the
17367 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17368 of the
17369 assembler statements.
17370
17371 Thus the effect of the @code{Asm} invocation is:
17372 @enumerate
17373 @item load the 32-bit value of @code{Value} into eax
17374 @item execute the @code{incl %eax} instruction
17375 @item store the contents of eax into the @code{Result} variable
17376 @end enumerate
17377
17378 The resulting assembler file (with @code{-O2} optimization) contains:
17379 @smallexample
17380 @group
17381 _increment__incr.1:
17382    subl $4,%esp
17383    movl 8(%esp),%eax
17384 #APP
17385    incl %eax
17386 #NO_APP
17387    movl %eax,%edx
17388    movl %ecx,(%esp)
17389    addl $4,%esp
17390    ret
17391 @end group
17392 @end smallexample
17393
17394 @c ---------------------------------------------------------------------------
17395 @node Inlining Inline Assembler Code
17396 @section Inlining Inline Assembler Code
17397
17398 @noindent
17399 For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame)
17400 can be significant, compared to the amount of code in the subprogram body.
17401 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17402 which directs the compiler to expand invocations of the subprogram at the point(s)
17403 of call, instead of setting up a stack frame for out-of-line calls.
17404 Here is the resulting program:
17405
17406 @smallexample
17407 @group
17408 with Interfaces; use Interfaces;
17409 with Ada.Text_IO; use Ada.Text_IO;
17410 with System.Machine_Code; use System.Machine_Code;
17411 procedure Increment_2 is
17412
17413    function Incr (Value : Unsigned_32) return Unsigned_32 is
17414       Result : Unsigned_32;
17415    begin
17416       Asm ("incl %0",
17417            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17418            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17419       return Result;
17420    end Incr;
17421    pragma Inline (Increment);
17422
17423    Value : Unsigned_32;
17424
17425 begin
17426    Value := 5;
17427    Put_Line ("Value before is" & Value'Img);
17428    Value := Increment (Value);
17429    Put_Line ("Value after is" & Value'Img);
17430 end Increment_2;
17431 @end group
17432 @end smallexample
17433
17434 Compile the program with both optimization (@code{-O2}) and inlining
17435 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17436
17437 The @code{Incr} function is still compiled as usual, but at the
17438 point in @code{Increment} where our function used to be called:
17439
17440 @smallexample
17441 @group
17442 pushl %edi
17443 call _increment__incr.1
17444 @end group
17445 @end smallexample
17446
17447 @noindent
17448 the code for the function body directly appears:
17449
17450 @smallexample
17451 @group
17452 movl %esi,%eax
17453 #APP
17454    incl %eax
17455 #NO_APP
17456    movl %eax,%edx
17457 @end group
17458 @end smallexample
17459
17460 @noindent
17461 thus saving the overhead of stack frame setup and an out-of-line call.
17462
17463 @c ---------------------------------------------------------------------------
17464 @node Other Asm Functionality
17465 @section Other @code{Asm} Functionality
17466
17467 @noindent
17468 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17469
17470 @menu
17471 * The Clobber Parameter::
17472 * The Volatile Parameter::
17473 @end menu
17474
17475 @c ---------------------------------------------------------------------------
17476 @node The Clobber Parameter
17477 @subsection The @code{Clobber} Parameter
17478
17479 @noindent
17480 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17481 that the compiler needs to be aware of which registers are being used by the assembly code.
17482 In some cases, such as the earlier examples, the constraint string is sufficient to
17483 indicate register usage (e.g. "a" for the eax register).  But more generally, the
17484 compiler needs an explicit identification of the registers that are used by the Inline
17485 Assembly statements.
17486
17487 Using a register that the compiler doesn't know about
17488 could be a side effect of an instruction (like @code{mull}
17489 storing its result in both eax and edx).
17490 It can also arise from explicit register usage in your
17491 assembly code; for example:
17492 @smallexample
17493 @group
17494 Asm ("movl %0, %%ebx" & LF & HT &
17495      "movl %%ebx, %1",
17496      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17497      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17498 @end group
17499 @end smallexample
17500 @noindent
17501 where the compiler (since it does not analyze the @code{Asm} template string)
17502 does not know you are using the ebx register.
17503
17504 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17505 to identify the registers that will be used by your assembly code:
17506
17507 @smallexample
17508 @group
17509 Asm ("movl %0, %%ebx" & LF & HT &
17510      "movl %%ebx, %1",
17511      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17512      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17513      Clobber => "ebx");
17514 @end group
17515 @end smallexample
17516
17517 The Clobber parameter is a static string expression specifying the
17518 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
17519 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17520
17521 The @code{Clobber} parameter has several additional uses:
17522 @enumerate
17523 @item Use the "register" name @code{cc} to indicate that flags might have changed
17524 @item Use the "register" name @code{memory} if you changed a memory location
17525 @end enumerate
17526
17527 @c ---------------------------------------------------------------------------
17528 @node The Volatile Parameter
17529 @subsection The @code{Volatile} Parameter
17530 @cindex Volatile parameter
17531
17532 @noindent
17533 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17534 For example, when
17535 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17536 the loading of the input variable outside the loop, regarding it as a
17537 one-time initialization.
17538
17539 If this effect is not desired, you can disable such optimizations by setting the
17540 @code{Volatile} parameter to @code{True}; for example:
17541
17542 @smallexample
17543 @group
17544 Asm ("movl %0, %%ebx" & LF & HT &
17545      "movl %%ebx, %1",
17546      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
17547      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
17548      Clobber  => "ebx",
17549      Volatile => True);
17550 @end group
17551 @end smallexample
17552
17553 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17554 parameter.
17555
17556 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17557 it will also disable other optimizations that might be important for efficiency.
17558 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17559 optimizations have created problems.
17560
17561 @c ---------------------------------------------------------------------------
17562 @node A Complete Example
17563 @section A Complete Example
17564
17565 @noindent
17566 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17567 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17568 The package declares a collection of functions that detect the properties of the 32-bit
17569 x86 processor that is running the program.  The main procedure invokes these functions
17570 and displays the information.
17571
17572 The Intel_CPU package could be enhanced by adding functions to
17573 detect the type of x386 co-processor, the processor caching options and
17574 special operations such as the SIMD extensions.
17575
17576 Although the Intel_CPU package has been written for 32-bit Intel
17577 compatible CPUs, it is OS neutral. It has been tested on DOS,
17578 Windows/NT and Linux.
17579
17580 @menu
17581 * Check_CPU Procedure::
17582 * Intel_CPU Package Specification::
17583 * Intel_CPU Package Body::
17584 @end menu
17585
17586 @c ---------------------------------------------------------------------------
17587 @node Check_CPU Procedure
17588 @subsection @code{Check_CPU} Procedure
17589 @cindex Check_CPU procedure
17590
17591 @smallexample
17592 ---------------------------------------------------------------------
17593 --                                                                 --
17594 --  Uses the Intel_CPU package to identify the CPU the program is  --
17595 --  running on, and some of the features it supports.              --
17596 --                                                                 --
17597 ---------------------------------------------------------------------
17598
17599 with Intel_CPU;                     --  Intel CPU detection functions
17600 with Ada.Text_IO;                   --  Standard text I/O
17601 with Ada.Command_Line;              --  To set the exit status
17602
17603 procedure Check_CPU is
17604
17605    Type_Found : Boolean := False;
17606    --  Flag to indicate that processor was identified
17607
17608    Features   : Intel_CPU.Processor_Features;
17609    --  The processor features
17610
17611    Signature  : Intel_CPU.Processor_Signature;
17612    --  The processor type signature
17613
17614 begin
17615
17616    -----------------------------------
17617    --  Display the program banner.  --
17618    -----------------------------------
17619
17620    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17621                          ": check Intel CPU version and features, v1.0");
17622    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17623    Ada.Text_IO.New_Line;
17624
17625    -----------------------------------------------------------------------
17626    --  We can safely start with the assumption that we are on at least  --
17627    --  a x386 processor. If the CPUID instruction is present, then we   --
17628    --  have a later processor type.                                     --
17629    -----------------------------------------------------------------------
17630
17631    if Intel_CPU.Has_CPUID = False then
17632
17633       --  No CPUID instruction, so we assume this is indeed a x386
17634       --  processor. We can still check if it has a FP co-processor.
17635       if Intel_CPU.Has_FPU then
17636          Ada.Text_IO.Put_Line
17637            ("x386-type processor with a FP co-processor");
17638       else
17639          Ada.Text_IO.Put_Line
17640            ("x386-type processor without a FP co-processor");
17641       end if;  --  check for FPU
17642
17643       --  Program done
17644       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17645       return;
17646
17647    end if;  --  check for CPUID
17648
17649    -----------------------------------------------------------------------
17650    --  If CPUID is supported, check if this is a true Intel processor,  --
17651    --  if it is not, display a warning.                                 --
17652    -----------------------------------------------------------------------
17653
17654    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17655       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17656       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17657    end if;  --  check if Intel
17658
17659    ----------------------------------------------------------------------
17660    --  With the CPUID instruction present, we can assume at least a    --
17661    --  x486 processor. If the CPUID support level is < 1 then we have  --
17662    --  to leave it at that.                                            --
17663    ----------------------------------------------------------------------
17664
17665    if Intel_CPU.CPUID_Level < 1 then
17666
17667       --  Ok, this is a x486 processor. we still can get the Vendor ID
17668       Ada.Text_IO.Put_Line ("x486-type processor");
17669       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17670
17671       --  We can also check if there is a FPU present
17672       if Intel_CPU.Has_FPU then
17673          Ada.Text_IO.Put_Line ("Floating-Point support");
17674       else
17675          Ada.Text_IO.Put_Line ("No Floating-Point support");
17676       end if;  --  check for FPU
17677
17678       --  Program done
17679       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17680       return;
17681
17682    end if;  --  check CPUID level
17683
17684    ---------------------------------------------------------------------
17685    --  With a CPUID level of 1 we can use the processor signature to  --
17686    --  determine it's exact type.                                     --
17687    ---------------------------------------------------------------------
17688
17689    Signature := Intel_CPU.Signature;
17690
17691    ----------------------------------------------------------------------
17692    --  Ok, now we go into a lot of messy comparisons to get the        --
17693    --  processor type. For clarity, no attememt to try to optimize the --
17694    --  comparisons has been made. Note that since Intel_CPU does not   --
17695    --  support getting cache info, we cannot distinguish between P5    --
17696    --  and Celeron types yet.                                          --
17697    ----------------------------------------------------------------------
17698
17699    --  x486SL
17700    if Signature.Processor_Type = 2#00#   and
17701      Signature.Family          = 2#0100# and
17702      Signature.Model           = 2#0100# then
17703       Type_Found := True;
17704       Ada.Text_IO.Put_Line ("x486SL processor");
17705    end if;
17706
17707    --  x486DX2 Write-Back
17708    if Signature.Processor_Type = 2#00#   and
17709      Signature.Family          = 2#0100# and
17710      Signature.Model           = 2#0111# then
17711       Type_Found := True;
17712       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17713    end if;
17714
17715    --  x486DX4
17716    if Signature.Processor_Type = 2#00#   and
17717      Signature.Family          = 2#0100# and
17718      Signature.Model           = 2#1000# then
17719       Type_Found := True;
17720       Ada.Text_IO.Put_Line ("x486DX4 processor");
17721    end if;
17722
17723    --  x486DX4 Overdrive
17724    if Signature.Processor_Type = 2#01#   and
17725      Signature.Family          = 2#0100# and
17726      Signature.Model           = 2#1000# then
17727       Type_Found := True;
17728       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17729    end if;
17730
17731    --  Pentium (60, 66)
17732    if Signature.Processor_Type = 2#00#   and
17733      Signature.Family          = 2#0101# and
17734      Signature.Model           = 2#0001# then
17735       Type_Found := True;
17736       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17737    end if;
17738
17739    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17740    if Signature.Processor_Type = 2#00#   and
17741      Signature.Family          = 2#0101# and
17742      Signature.Model           = 2#0010# then
17743       Type_Found := True;
17744       Ada.Text_IO.Put_Line
17745         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17746    end if;
17747
17748    --  Pentium OverDrive (60, 66)
17749    if Signature.Processor_Type = 2#01#   and
17750      Signature.Family          = 2#0101# and
17751      Signature.Model           = 2#0001# then
17752       Type_Found := True;
17753       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17754    end if;
17755
17756    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17757    if Signature.Processor_Type = 2#01#   and
17758      Signature.Family          = 2#0101# and
17759      Signature.Model           = 2#0010# then
17760       Type_Found := True;
17761       Ada.Text_IO.Put_Line
17762         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17763    end if;
17764
17765    --  Pentium OverDrive processor for x486 processor-based systems
17766    if Signature.Processor_Type = 2#01#   and
17767      Signature.Family          = 2#0101# and
17768      Signature.Model           = 2#0011# then
17769       Type_Found := True;
17770       Ada.Text_IO.Put_Line
17771         ("Pentium OverDrive processor for x486 processor-based systems");
17772    end if;
17773
17774    --  Pentium processor with MMX technology (166, 200)
17775    if Signature.Processor_Type = 2#00#   and
17776      Signature.Family          = 2#0101# and
17777      Signature.Model           = 2#0100# then
17778       Type_Found := True;
17779       Ada.Text_IO.Put_Line
17780         ("Pentium processor with MMX technology (166, 200)");
17781    end if;
17782
17783    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17784    if Signature.Processor_Type = 2#01#   and
17785      Signature.Family          = 2#0101# and
17786      Signature.Model           = 2#0100# then
17787       Type_Found := True;
17788       Ada.Text_IO.Put_Line
17789         ("Pentium OverDrive processor with MMX " &
17790          "technology for Pentium processor (75, 90, 100, 120, 133)");
17791    end if;
17792
17793    --  Pentium Pro processor
17794    if Signature.Processor_Type = 2#00#   and
17795      Signature.Family          = 2#0110# and
17796      Signature.Model           = 2#0001# then
17797       Type_Found := True;
17798       Ada.Text_IO.Put_Line ("Pentium Pro processor");
17799    end if;
17800
17801    --  Pentium II processor, model 3
17802    if Signature.Processor_Type = 2#00#   and
17803      Signature.Family          = 2#0110# and
17804      Signature.Model           = 2#0011# then
17805       Type_Found := True;
17806       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17807    end if;
17808
17809    --  Pentium II processor, model 5 or Celeron processor
17810    if Signature.Processor_Type = 2#00#   and
17811      Signature.Family          = 2#0110# and
17812      Signature.Model           = 2#0101# then
17813       Type_Found := True;
17814       Ada.Text_IO.Put_Line
17815         ("Pentium II processor, model 5 or Celeron processor");
17816    end if;
17817
17818    --  Pentium Pro OverDrive processor
17819    if Signature.Processor_Type = 2#01#   and
17820      Signature.Family          = 2#0110# and
17821      Signature.Model           = 2#0011# then
17822       Type_Found := True;
17823       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17824    end if;
17825
17826    --  If no type recognized, we have an unknown. Display what
17827    --  we _do_ know
17828    if Type_Found = False then
17829       Ada.Text_IO.Put_Line ("Unknown processor");
17830    end if;
17831
17832    -----------------------------------------
17833    --  Display processor stepping level.  --
17834    -----------------------------------------
17835
17836    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17837
17838    ---------------------------------
17839    --  Display vendor ID string.  --
17840    ---------------------------------
17841
17842    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17843
17844    ------------------------------------
17845    --  Get the processors features.  --
17846    ------------------------------------
17847
17848    Features := Intel_CPU.Features;
17849
17850    -----------------------------
17851    --  Check for a FPU unit.  --
17852    -----------------------------
17853
17854    if Features.FPU = True then
17855       Ada.Text_IO.Put_Line ("Floating-Point unit available");
17856    else
17857       Ada.Text_IO.Put_Line ("no Floating-Point unit");
17858    end if;  --  check for FPU
17859
17860    --------------------------------
17861    --  List processor features.  --
17862    --------------------------------
17863
17864    Ada.Text_IO.Put_Line ("Supported features: ");
17865
17866    --  Virtual Mode Extension
17867    if Features.VME = True then
17868       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
17869    end if;
17870
17871    --  Debugging Extension
17872    if Features.DE = True then
17873       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
17874    end if;
17875
17876    --  Page Size Extension
17877    if Features.PSE = True then
17878       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
17879    end if;
17880
17881    --  Time Stamp Counter
17882    if Features.TSC = True then
17883       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
17884    end if;
17885
17886    --  Model Specific Registers
17887    if Features.MSR = True then
17888       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
17889    end if;
17890
17891    --  Physical Address Extension
17892    if Features.PAE = True then
17893       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
17894    end if;
17895
17896    --  Machine Check Extension
17897    if Features.MCE = True then
17898       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
17899    end if;
17900
17901    --  CMPXCHG8 instruction supported
17902    if Features.CX8 = True then
17903       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
17904    end if;
17905
17906    --  on-chip APIC hardware support
17907    if Features.APIC = True then
17908       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
17909    end if;
17910
17911    --  Fast System Call
17912    if Features.SEP = True then
17913       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
17914    end if;
17915
17916    --  Memory Type Range Registers
17917    if Features.MTRR = True then
17918       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
17919    end if;
17920
17921    --  Page Global Enable
17922    if Features.PGE = True then
17923       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
17924    end if;
17925
17926    --  Machine Check Architecture
17927    if Features.MCA = True then
17928       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
17929    end if;
17930
17931    --  Conditional Move Instruction Supported
17932    if Features.CMOV = True then
17933       Ada.Text_IO.Put_Line
17934         ("    CMOV   - Conditional Move Instruction Supported");
17935    end if;
17936
17937    --  Page Attribute Table
17938    if Features.PAT = True then
17939       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
17940    end if;
17941
17942    --  36-bit Page Size Extension
17943    if Features.PSE_36 = True then
17944       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
17945    end if;
17946
17947    --  MMX technology supported
17948    if Features.MMX = True then
17949       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
17950    end if;
17951
17952    --  Fast FP Save and Restore
17953    if Features.FXSR = True then
17954       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
17955    end if;
17956
17957    ---------------------
17958    --  Program done.  --
17959    ---------------------
17960
17961    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17962
17963 exception
17964
17965    when others =>
17966       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17967       raise;
17968
17969 end Check_CPU;
17970 @end smallexample
17971
17972 @c ---------------------------------------------------------------------------
17973 @node Intel_CPU Package Specification
17974 @subsection @code{Intel_CPU} Package Specification
17975 @cindex Intel_CPU package specification
17976
17977 @smallexample
17978 -------------------------------------------------------------------------
17979 --                                                                     --
17980 --  file: intel_cpu.ads                                                --
17981 --                                                                     --
17982 --           *********************************************             --
17983 --           * WARNING: for 32-bit Intel processors only *             --
17984 --           *********************************************             --
17985 --                                                                     --
17986 --  This package contains a number of subprograms that are useful in   --
17987 --  determining the Intel x86 CPU (and the features it supports) on    --
17988 --  which the program is running.                                      --
17989 --                                                                     --
17990 --  The package is based upon the information given in the Intel       --
17991 --  Application Note AP-485: "Intel Processor Identification and the   --
17992 --  CPUID Instruction" as of April 1998. This application note can be  --
17993 --  found on www.intel.com.                                            --
17994 --                                                                     --
17995 --  It currently deals with 32-bit processors only, will not detect    --
17996 --  features added after april 1998, and does not guarantee proper     --
17997 --  results on Intel-compatible processors.                            --
17998 --                                                                     --
17999 --  Cache info and x386 fpu type detection are not supported.          --
18000 --                                                                     --
18001 --  This package does not use any privileged instructions, so should   --
18002 --  work on any OS running on a 32-bit Intel processor.                --
18003 --                                                                     --
18004 -------------------------------------------------------------------------
18005
18006 with Interfaces;             use Interfaces;
18007 --  for using unsigned types
18008
18009 with System.Machine_Code;    use System.Machine_Code;
18010 --  for using inline assembler code
18011
18012 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
18013 --  for inserting control characters
18014
18015 package Intel_CPU is
18016
18017    ----------------------
18018    --  Processor bits  --
18019    ----------------------
18020
18021    subtype Num_Bits is Natural range 0 .. 31;
18022    --  the number of processor bits (32)
18023
18024    --------------------------
18025    --  Processor register  --
18026    --------------------------
18027
18028    --  define a processor register type for easy access to
18029    --  the individual bits
18030
18031    type Processor_Register is array (Num_Bits) of Boolean;
18032    pragma Pack (Processor_Register);
18033    for Processor_Register'Size use 32;
18034
18035    -------------------------
18036    --  Unsigned register  --
18037    -------------------------
18038
18039    --  define a processor register type for easy access to
18040    --  the individual bytes
18041
18042    type Unsigned_Register is
18043       record
18044          L1 : Unsigned_8;
18045          H1 : Unsigned_8;
18046          L2 : Unsigned_8;
18047          H2 : Unsigned_8;
18048       end record;
18049
18050    for Unsigned_Register use
18051       record
18052          L1 at 0 range  0 ..  7;
18053          H1 at 0 range  8 .. 15;
18054          L2 at 0 range 16 .. 23;
18055          H2 at 0 range 24 .. 31;
18056       end record;
18057
18058    for Unsigned_Register'Size use 32;
18059
18060    ---------------------------------
18061    --  Intel processor vendor ID  --
18062    ---------------------------------
18063
18064    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
18065    --  indicates an Intel manufactured processor
18066
18067    ------------------------------------
18068    --  Processor signature register  --
18069    ------------------------------------
18070
18071    --  a register type to hold the processor signature
18072
18073    type Processor_Signature is
18074       record
18075          Stepping       : Natural range 0 .. 15;
18076          Model          : Natural range 0 .. 15;
18077          Family         : Natural range 0 .. 15;
18078          Processor_Type : Natural range 0 .. 3;
18079          Reserved       : Natural range 0 .. 262143;
18080       end record;
18081
18082    for Processor_Signature use
18083       record
18084          Stepping       at 0 range  0 ..  3;
18085          Model          at 0 range  4 ..  7;
18086          Family         at 0 range  8 .. 11;
18087          Processor_Type at 0 range 12 .. 13;
18088          Reserved       at 0 range 14 .. 31;
18089       end record;
18090
18091    for Processor_Signature'Size use 32;
18092
18093    -----------------------------------
18094    --  Processor features register  --
18095    -----------------------------------
18096
18097    --  a processor register to hold the processor feature flags
18098
18099    type Processor_Features is
18100       record
18101          FPU    : Boolean;                --  floating point unit on chip
18102          VME    : Boolean;                --  virtual mode extension
18103          DE     : Boolean;                --  debugging extension
18104          PSE    : Boolean;                --  page size extension
18105          TSC    : Boolean;                --  time stamp counter
18106          MSR    : Boolean;                --  model specific registers
18107          PAE    : Boolean;                --  physical address extension
18108          MCE    : Boolean;                --  machine check extension
18109          CX8    : Boolean;                --  cmpxchg8 instruction
18110          APIC   : Boolean;                --  on-chip apic hardware
18111          Res_1  : Boolean;                --  reserved for extensions
18112          SEP    : Boolean;                --  fast system call
18113          MTRR   : Boolean;                --  memory type range registers
18114          PGE    : Boolean;                --  page global enable
18115          MCA    : Boolean;                --  machine check architecture
18116          CMOV   : Boolean;                --  conditional move supported
18117          PAT    : Boolean;                --  page attribute table
18118          PSE_36 : Boolean;                --  36-bit page size extension
18119          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
18120          MMX    : Boolean;                --  MMX technology supported
18121          FXSR   : Boolean;                --  fast FP save and restore
18122          Res_3  : Natural range 0 .. 127; --  reserved for extensions
18123       end record;
18124
18125    for Processor_Features use
18126       record
18127          FPU    at 0 range  0 ..  0;
18128          VME    at 0 range  1 ..  1;
18129          DE     at 0 range  2 ..  2;
18130          PSE    at 0 range  3 ..  3;
18131          TSC    at 0 range  4 ..  4;
18132          MSR    at 0 range  5 ..  5;
18133          PAE    at 0 range  6 ..  6;
18134          MCE    at 0 range  7 ..  7;
18135          CX8    at 0 range  8 ..  8;
18136          APIC   at 0 range  9 ..  9;
18137          Res_1  at 0 range 10 .. 10;
18138          SEP    at 0 range 11 .. 11;
18139          MTRR   at 0 range 12 .. 12;
18140          PGE    at 0 range 13 .. 13;
18141          MCA    at 0 range 14 .. 14;
18142          CMOV   at 0 range 15 .. 15;
18143          PAT    at 0 range 16 .. 16;
18144          PSE_36 at 0 range 17 .. 17;
18145          Res_2  at 0 range 18 .. 22;
18146          MMX    at 0 range 23 .. 23;
18147          FXSR   at 0 range 24 .. 24;
18148          Res_3  at 0 range 25 .. 31;
18149       end record;
18150
18151    for Processor_Features'Size use 32;
18152
18153    -------------------
18154    --  Subprograms  --
18155    -------------------
18156
18157    function Has_FPU return Boolean;
18158    --  return True if a FPU is found
18159    --  use only if CPUID is not supported
18160
18161    function Has_CPUID return Boolean;
18162    --  return True if the processor supports the CPUID instruction
18163
18164    function CPUID_Level return Natural;
18165    --  return the CPUID support level (0, 1 or 2)
18166    --  can only be called if the CPUID instruction is supported
18167
18168    function Vendor_ID return String;
18169    --  return the processor vendor identification string
18170    --  can only be called if the CPUID instruction is supported
18171
18172    function Signature return Processor_Signature;
18173    --  return the processor signature
18174    --  can only be called if the CPUID instruction is supported
18175
18176    function Features return Processor_Features;
18177    --  return the processors features
18178    --  can only be called if the CPUID instruction is supported
18179
18180 private
18181
18182    ------------------------
18183    --  EFLAGS bit names  --
18184    ------------------------
18185
18186    ID_Flag : constant Num_Bits := 21;
18187    --  ID flag bit
18188
18189 end Intel_CPU;
18190 @end smallexample
18191
18192 @c ---------------------------------------------------------------------------
18193 @node Intel_CPU Package Body
18194 @subsection @code{Intel_CPU} Package Body
18195 @cindex Intel_CPU package body
18196
18197 @smallexample
18198 package body Intel_CPU is
18199
18200    ---------------------------
18201    --  Detect FPU presence  --
18202    ---------------------------
18203
18204    --  There is a FPU present if we can set values to the FPU Status
18205    --  and Control Words.
18206
18207    function Has_FPU return Boolean is
18208
18209       Register : Unsigned_16;
18210       --  processor register to store a word
18211
18212    begin
18213
18214       --  check if we can change the status word
18215       Asm (
18216
18217            --  the assembler code
18218            "finit"              & LF & HT &    --  reset status word
18219            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
18220            "fnstsw %0"          & LF & HT &    --  save status word
18221            "movw %%ax, %0",                    --  store status word
18222
18223            --  output stored in Register
18224            --  register must be a memory location
18225            Outputs => Unsigned_16'Asm_output ("=m", Register),
18226
18227            --  tell compiler that we used eax
18228            Clobber => "eax");
18229
18230       --  if the status word is zero, there is no FPU
18231       if Register = 0 then
18232          return False;   --  no status word
18233       end if;  --  check status word value
18234
18235       --  check if we can get the control word
18236       Asm (
18237
18238            --  the assembler code
18239            "fnstcw %0",   --  save the control word
18240
18241            --  output into Register
18242            --  register must be a memory location
18243            Outputs => Unsigned_16'Asm_output ("=m", Register));
18244
18245       --  check the relevant bits
18246       if (Register and 16#103F#) /= 16#003F# then
18247          return False;   --  no control word
18248       end if;  --  check control word value
18249
18250       --  FPU found
18251       return True;
18252
18253    end Has_FPU;
18254
18255    --------------------------------
18256    --  Detect CPUID instruction  --
18257    --------------------------------
18258
18259    --  The processor supports the CPUID instruction if it is possible
18260    --  to change the value of ID flag bit in the EFLAGS register.
18261
18262    function Has_CPUID return Boolean is
18263
18264       Original_Flags, Modified_Flags : Processor_Register;
18265       --  EFLAG contents before and after changing the ID flag
18266
18267    begin
18268
18269       --  try flipping the ID flag in the EFLAGS register
18270       Asm (
18271
18272            --  the assembler code
18273            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18274            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
18275            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
18276            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
18277            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
18278            "popfl"                & LF & HT &     --  load EFLAGS register
18279            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18280            "pop %1",                              --  save EFLAGS content
18281
18282            --  output values, may be anything
18283            --  Original_Flags is %0
18284            --  Modified_Flags is %1
18285            Outputs =>
18286               (Processor_Register'Asm_output ("=g", Original_Flags),
18287                Processor_Register'Asm_output ("=g", Modified_Flags)),
18288
18289            --  tell compiler eax is destroyed
18290            Clobber => "eax");
18291
18292       --  check if CPUID is supported
18293       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
18294          return True;   --  ID flag was modified
18295       else
18296          return False;  --  ID flag unchanged
18297       end if;  --  check for CPUID
18298
18299    end Has_CPUID;
18300
18301    -------------------------------
18302    --  Get CPUID support level  --
18303    -------------------------------
18304
18305    function CPUID_Level return Natural is
18306
18307       Level : Unsigned_32;
18308       --  returned support level
18309
18310    begin
18311
18312       --  execute CPUID, storing the results in the Level register
18313       Asm (
18314
18315            --  the assembler code
18316            "cpuid",    --  execute CPUID
18317
18318            --  zero is stored in eax
18319            --  returning the support level in eax
18320            Inputs => Unsigned_32'Asm_input ("a", 0),
18321
18322            --  eax is stored in Level
18323            Outputs => Unsigned_32'Asm_output ("=a", Level),
18324
18325            --  tell compiler ebx, ecx and edx registers are destroyed
18326            Clobber => "ebx, ecx, edx");
18327
18328       --  return the support level
18329       return Natural (Level);
18330
18331    end CPUID_Level;
18332
18333    --------------------------------
18334    --  Get CPU Vendor ID String  --
18335    --------------------------------
18336
18337    --  The vendor ID string is returned in the ebx, ecx and edx register
18338    --  after executing the CPUID instruction with eax set to zero.
18339    --  In case of a true Intel processor the string returned is
18340    --  "GenuineIntel"
18341
18342    function Vendor_ID return String is
18343
18344       Ebx, Ecx, Edx : Unsigned_Register;
18345       --  registers containing the vendor ID string
18346
18347       Vendor_ID : String (1 .. 12);
18348       -- the vendor ID string
18349
18350    begin
18351
18352       --  execute CPUID, storing the results in the processor registers
18353       Asm (
18354
18355            --  the assembler code
18356            "cpuid",    --  execute CPUID
18357
18358            --  zero stored in eax
18359            --  vendor ID string returned in ebx, ecx and edx
18360            Inputs => Unsigned_32'Asm_input ("a", 0),
18361
18362            --  ebx is stored in Ebx
18363            --  ecx is stored in Ecx
18364            --  edx is stored in Edx
18365            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18366                        Unsigned_Register'Asm_output ("=c", Ecx),
18367                        Unsigned_Register'Asm_output ("=d", Edx)));
18368
18369       --  now build the vendor ID string
18370       Vendor_ID( 1) := Character'Val (Ebx.L1);
18371       Vendor_ID( 2) := Character'Val (Ebx.H1);
18372       Vendor_ID( 3) := Character'Val (Ebx.L2);
18373       Vendor_ID( 4) := Character'Val (Ebx.H2);
18374       Vendor_ID( 5) := Character'Val (Edx.L1);
18375       Vendor_ID( 6) := Character'Val (Edx.H1);
18376       Vendor_ID( 7) := Character'Val (Edx.L2);
18377       Vendor_ID( 8) := Character'Val (Edx.H2);
18378       Vendor_ID( 9) := Character'Val (Ecx.L1);
18379       Vendor_ID(10) := Character'Val (Ecx.H1);
18380       Vendor_ID(11) := Character'Val (Ecx.L2);
18381       Vendor_ID(12) := Character'Val (Ecx.H2);
18382
18383       --  return string
18384       return Vendor_ID;
18385
18386    end Vendor_ID;
18387
18388    -------------------------------
18389    --  Get processor signature  --
18390    -------------------------------
18391
18392    function Signature return Processor_Signature is
18393
18394       Result : Processor_Signature;
18395       --  processor signature returned
18396
18397    begin
18398
18399       --  execute CPUID, storing the results in the Result variable
18400       Asm (
18401
18402            --  the assembler code
18403            "cpuid",    --  execute CPUID
18404
18405            --  one is stored in eax
18406            --  processor signature returned in eax
18407            Inputs => Unsigned_32'Asm_input ("a", 1),
18408
18409            --  eax is stored in Result
18410            Outputs => Processor_Signature'Asm_output ("=a", Result),
18411
18412            --  tell compiler that ebx, ecx and edx are also destroyed
18413            Clobber => "ebx, ecx, edx");
18414
18415       --  return processor signature
18416       return Result;
18417
18418    end Signature;
18419
18420    ------------------------------
18421    --  Get processor features  --
18422    ------------------------------
18423
18424    function Features return Processor_Features is
18425
18426       Result : Processor_Features;
18427       --  processor features returned
18428
18429    begin
18430
18431       --  execute CPUID, storing the results in the Result variable
18432       Asm (
18433
18434            --  the assembler code
18435            "cpuid",    --  execute CPUID
18436
18437            --  one stored in eax
18438            --  processor features returned in edx
18439            Inputs => Unsigned_32'Asm_input ("a", 1),
18440
18441            --  edx is stored in Result
18442            Outputs => Processor_Features'Asm_output ("=d", Result),
18443
18444            --  tell compiler that ebx and ecx are also destroyed
18445            Clobber => "ebx, ecx");
18446
18447       --  return processor signature
18448       return Result;
18449
18450    end Features;
18451
18452 end Intel_CPU;
18453 @end smallexample
18454 @c END OF INLINE ASSEMBLER CHAPTER
18455 @c ===============================
18456
18457 @node Microsoft Windows Topics
18458 @chapter Microsoft Windows Topics
18459 @cindex Windows NT
18460 @cindex Windows 95
18461 @cindex Windows 98
18462
18463 @noindent
18464 This chapter describes topics that are specific to the Microsoft Windows
18465 platforms (NT, 95 and 98).
18466
18467 @menu
18468 * Using GNAT on Windows::
18469 * GNAT Setup Tool::
18470 * CONSOLE and WINDOWS subsystems::
18471 * Temporary Files::
18472 * Mixed-Language Programming on Windows::
18473 * Windows Calling Conventions::
18474 * Introduction to Dynamic Link Libraries (DLLs)::
18475 * Using DLLs with GNAT::
18476 * Building DLLs with GNAT::
18477 * GNAT and Windows Resources::
18478 * Debugging a DLL::
18479 * GNAT and COM/DCOM Objects::
18480 @end menu
18481
18482 @node Using GNAT on Windows
18483 @section Using GNAT on Windows
18484
18485 @noindent
18486 One of the strengths of the GNAT technology is that its tool set
18487 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
18488 @code{gdb} debugger, etc.) is used in the same way regardless of the
18489 platform.
18490
18491 On Windows this tool set is complemented by a number of Microsoft-specific
18492 tools that have been provided to facilitate interoperability with Windows
18493 when this is required. With these tools:
18494
18495 @itemize @bullet
18496
18497 @item
18498 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
18499 subsystems.
18500
18501 @item
18502 You can use any Dynamically Linked Library (DLL) in your Ada code (both
18503 relocatable and non-relocatable DLLs are supported).
18504
18505 @item
18506 You can build Ada DLLs for use in other applications. These applications
18507 can be written in a language other than Ada (e.g., C, C++, etc). Again both
18508 relocatable and non-relocatable Ada DLLs are supported.
18509
18510 @item
18511 You can include Windows resources in your Ada application.
18512
18513 @item
18514 You can use or create COM/DCOM objects.
18515 @end itemize
18516
18517 @noindent
18518 Immediately below are listed all known general GNAT-for-Windows restrictions.
18519 Other restrictions about specific features like Windows Resources and DLLs
18520 are listed in separate sections below.
18521
18522 @itemize @bullet
18523
18524 @item
18525 It is not possible to use @code{GetLastError} and @code{SetLastError}
18526 when tasking, protected records, or exceptions are used. In these
18527 cases, in order to implement Ada semantics, the GNAT run-time system
18528 calls certain Win32 routines that set the last error variable to 0 upon
18529 success. It should be possible to use @code{GetLastError} and
18530 @code{SetLastError} when tasking, protected record, and exception
18531 features are not used, but it is not guaranteed to work.
18532 @end itemize
18533
18534 @node GNAT Setup Tool
18535 @section GNAT Setup Tool
18536 @cindex GNAT Setup Tool
18537 @cindex Setup Tool
18538 @cindex gnatreg
18539
18540 @menu
18541 * Command-line arguments::
18542 * Creating a network installation of GNAT::
18543 * Registering and unregistering additional libraries::
18544 @end menu
18545
18546 @noindent
18547 GNAT installation on Windows is using the Windows registry in order to
18548 locate proper executables and standard libraries. GNAT setup tool, called
18549 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
18550 registry entries, allowing to create network GNAT installations, modify the
18551 locations of GNAT components, as well as register and unregister additional
18552 libraries for use with GNAT.
18553
18554 @node Command-line arguments
18555 @subsection Command-line arguments
18556
18557 @noindent
18558 @code{gnatreg [switches] [parameter]}
18559
18560 @noindent
18561 Specifying no arguments causes gnatreg to display current configuration.
18562
18563 @noindent
18564 The switches understood by gnatreg are:
18565 @table @asis
18566 @item  -h
18567        print the help message
18568 @item  -a
18569        add a standard library
18570 @item  -r
18571        remove a standard library
18572 @item  -f
18573        force creation of keys if they don't exist
18574 @item  -q
18575        be quiet/terse
18576 @end table
18577
18578 @node Creating a network installation of GNAT
18579 @subsection Creating a network installation of GNAT
18580
18581 @noindent
18582 Make sure the system on which GNAT is installed is accessible from the
18583 current machine.
18584
18585 Use the command
18586
18587 @code{@ @ @ gnatreg -f \\server\sharename\path}
18588
18589 in order to setup the registry entries on a current machine.
18590
18591 For example, if GNAT is installed in @file{\GNAT} directory of a share location
18592 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
18593 other machines to allow the remote use of GNAT is,
18594
18595 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
18596
18597 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
18598
18599 Be aware that every compilation using the network installation results in the
18600 transfer of large amounts of data across the network and may cause serious
18601 performance penalty.
18602
18603 @node Registering and unregistering additional libraries
18604 @subsection Registering and unregistering additional libraries
18605
18606 @noindent
18607 To register a standard library use a command:
18608
18609 @code{@ @ @ gnatreg -a <library_name>=<path>}
18610
18611 For example:
18612
18613 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
18614
18615 The libraries registered in this manner will be treated like standard libraries
18616 by the compiler (i.e. they don't have to be specified in -I and -l switches to
18617 various GNAT tools).
18618
18619 To unregister a library, enter
18620 @code{   gnatreg -r <library_name>}
18621
18622 e.g.,
18623 @code{   gnatreg -r WIN32ADA}
18624
18625 @node CONSOLE and WINDOWS subsystems
18626 @section CONSOLE and WINDOWS subsystems
18627 @cindex CONSOLE Subsystem
18628 @cindex WINDOWS Subsystem
18629 @cindex -mwindows
18630
18631 @noindent
18632 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
18633 (which is the default subsystem) will always create a console when
18634 launching the application. This is not something desirable when the
18635 application has a Windows GUI. To get rid of this console the
18636 application must be using the @code{WINDOWS} subsystem. To do so
18637 the @code{-mwindows} linker option must be specified.
18638
18639 @smallexample
18640 $ gnatmake winprog -largs -mwindows
18641 @end smallexample
18642
18643 @node Temporary Files
18644 @section Temporary Files
18645 @cindex Temporary files
18646
18647 @noindent
18648 It is possible to control where temporary files gets created by setting
18649 the TMP environment variable. The file will be created:
18650
18651 @itemize
18652 @item Under the directory pointed to by the TMP environment variable if
18653 this directory exists.
18654
18655 @item Under c:\temp, if the TMP environment variable is not set (or not
18656 pointing to a directory) and if this directory exists.
18657
18658 @item Under the current working directory otherwise.
18659 @end itemize
18660
18661 @noindent
18662 This allows you to determine exactly where the temporary
18663 file will be created. This is particularly useful in networked
18664 environments where you may not have write access to some
18665 directories.
18666
18667 @node Mixed-Language Programming on Windows
18668 @section Mixed-Language Programming on Windows
18669
18670 @noindent
18671 Developing pure Ada applications on Windows is no different than on
18672 other GNAT-supported platforms. However, when developing or porting an
18673 application that contains a mix of Ada and C/C++, the choice of your
18674 Windows C/C++ development environment conditions your overall
18675 interoperability strategy.
18676
18677 If you use @code{gcc} to compile the non-Ada part of your application,
18678 there are no Windows-specific restrictions that affect the overall
18679 interoperability with your Ada code. If you plan to use
18680 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
18681 the following limitations:
18682
18683 @itemize @bullet
18684 @item
18685 You cannot link your Ada code with an object or library generated with
18686 Microsoft tools if these use the @code{.tls} section (Thread Local
18687 Storage section) since the GNAT linker does not yet support this section.
18688
18689 @item
18690 You cannot link your Ada code with an object or library generated with
18691 Microsoft tools if these use I/O routines other than those provided in
18692 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
18693 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
18694 libraries can cause a conflict with @code{msvcrt.dll} services. For
18695 instance Visual C++ I/O stream routines conflict with those in
18696 @code{msvcrt.dll}.
18697 @end itemize
18698
18699 @noindent
18700 If you do want to use the Microsoft tools for your non-Ada code and hit one
18701 of the above limitations, you have two choices:
18702
18703 @enumerate
18704 @item
18705 Encapsulate your non Ada code in a DLL to be linked with your Ada
18706 application. In this case, use the Microsoft or whatever environment to
18707 build the DLL and use GNAT to build your executable
18708 (@pxref{Using DLLs with GNAT}).
18709
18710 @item
18711 Or you can encapsulate your Ada code in a DLL to be linked with the
18712 other part of your application. In this case, use GNAT to build the DLL
18713 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
18714 environment to build your executable.
18715 @end enumerate
18716
18717 @node Windows Calling Conventions
18718 @section Windows Calling Conventions
18719 @findex Stdcall
18720 @findex APIENTRY
18721
18722 @menu
18723 * C Calling Convention::
18724 * Stdcall Calling Convention::
18725 * DLL Calling Convention::
18726 @end menu
18727
18728 @noindent
18729 When a subprogram @code{F} (caller) calls a subprogram @code{G}
18730 (callee), there are several ways to push @code{G}'s parameters on the
18731 stack and there are several possible scenarios to clean up the stack
18732 upon @code{G}'s return. A calling convention is an agreed upon software
18733 protocol whereby the responsibilities between the caller (@code{F}) and
18734 the callee (@code{G}) are clearly defined. Several calling conventions
18735 are available for Windows:
18736
18737 @itemize @bullet
18738 @item
18739 @code{C} (Microsoft defined)
18740
18741 @item
18742 @code{Stdcall} (Microsoft defined)
18743
18744 @item
18745 @code{DLL} (GNAT specific)
18746 @end itemize
18747
18748 @node C Calling Convention
18749 @subsection @code{C} Calling Convention
18750
18751 @noindent
18752 This is the default calling convention used when interfacing to C/C++
18753 routines compiled with either @code{gcc} or Microsoft Visual C++.
18754
18755 In the @code{C} calling convention subprogram parameters are pushed on the
18756 stack by the caller from right to left. The caller itself is in charge of
18757 cleaning up the stack after the call. In addition, the name of a routine
18758 with @code{C} calling convention is mangled by adding a leading underscore.
18759
18760 The name to use on the Ada side when importing (or exporting) a routine
18761 with @code{C} calling convention is the name of the routine. For
18762 instance the C function:
18763
18764 @smallexample
18765 int get_val (long);
18766 @end smallexample
18767
18768 @noindent
18769 should be imported from Ada as follows:
18770
18771 @smallexample
18772 @group
18773 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18774 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
18775 @end group
18776 @end smallexample
18777
18778 @noindent
18779 Note that in this particular case the @code{External_Name} parameter could
18780 have been omitted since, when missing, this parameter is taken to be the
18781 name of the Ada entity in lower case. When the @code{Link_Name} parameter
18782 is missing, as in the above example, this parameter is set to be the
18783 @code{External_Name} with a leading underscore.
18784
18785 When importing a variable defined in C, you should always use the @code{C}
18786 calling convention unless the object containing the variable is part of a
18787 DLL (in which case you should use the @code{DLL} calling convention,
18788 @pxref{DLL Calling Convention}).
18789
18790 @node Stdcall Calling Convention
18791 @subsection @code{Stdcall} Calling Convention
18792
18793 @noindent
18794 This convention, which was the calling convention used for Pascal
18795 programs, is used by Microsoft for all the routines in the Win32 API for
18796 efficiency reasons. It must be used to import any routine for which this
18797 convention was specified.
18798
18799 In the @code{Stdcall} calling convention subprogram parameters are pushed
18800 on the stack by the caller from right to left. The callee (and not the
18801 caller) is in charge of cleaning the stack on routine exit. In addition,
18802 the name of a routine with @code{Stdcall} calling convention is mangled by
18803 adding a leading underscore (as for the @code{C} calling convention) and a
18804 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
18805 bytes) of the parameters passed to the routine.
18806
18807 The name to use on the Ada side when importing a C routine with a
18808 @code{Stdcall} calling convention is the name of the C routine. The leading
18809 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
18810 the compiler. For instance the Win32 function:
18811
18812 @smallexample
18813 @b{APIENTRY} int get_val (long);
18814 @end smallexample
18815
18816 @noindent
18817 should be imported from Ada as follows:
18818
18819 @smallexample
18820 @group
18821 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18822 @b{pragma} Import (Stdcall, Get_Val);
18823 --  @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
18824 @end group
18825 @end smallexample
18826
18827 @noindent
18828 As for the @code{C} calling convention, when the @code{External_Name}
18829 parameter is missing, it is taken to be the name of the Ada entity in lower
18830 case. If instead of writing the above import pragma you write:
18831
18832 @smallexample
18833 @group
18834 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18835 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
18836 @end group
18837 @end smallexample
18838
18839 @noindent
18840 then the imported routine is @code{_retrieve_val@@4}. However, if instead
18841 of specifying the @code{External_Name} parameter you specify the
18842 @code{Link_Name} as in the following example:
18843
18844 @smallexample
18845 @group
18846 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18847 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
18848 @end group
18849 @end smallexample
18850
18851 @noindent
18852 then the imported routine is @code{retrieve_val@@4}, that is, there is no
18853 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
18854 added at the end of the @code{Link_Name} by the compiler.
18855
18856 @noindent
18857 Note, that in some special cases a DLL's entry point name lacks a trailing
18858 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
18859 The @code{gnatdll} tool, which creates the import library for the DLL, is able
18860 to handle those cases (see the description of the switches in
18861 @pxref{Using gnatdll} section).
18862
18863 @node DLL Calling Convention
18864 @subsection @code{DLL} Calling Convention
18865
18866 @noindent
18867 This convention, which is GNAT-specific, must be used when you want to
18868 import in Ada a variables defined in a DLL. For functions and procedures
18869 this convention is equivalent to the @code{Stdcall} convention. As an
18870 example, if a DLL contains a variable defined as:
18871
18872 @smallexample
18873 int my_var;
18874 @end smallexample
18875
18876 @noindent
18877 then, to access this variable from Ada you should write:
18878
18879 @smallexample
18880 @group
18881 My_Var : Interfaces.C.int;
18882 @b{pragma} Import (DLL, My_Var);
18883 @end group
18884 @end smallexample
18885
18886 The remarks concerning the @code{External_Name} and @code{Link_Name}
18887 parameters given in the previous sections equally apply to the @code{DLL}
18888 calling convention.
18889
18890 @node Introduction to Dynamic Link Libraries (DLLs)
18891 @section Introduction to Dynamic Link Libraries (DLLs)
18892 @findex DLL
18893
18894 @noindent
18895 A Dynamically Linked Library (DLL) is a library that can be shared by
18896 several applications running under Windows. A DLL can contain any number of
18897 routines and variables.
18898
18899 One advantage of DLLs is that you can change and enhance them without
18900 forcing all the applications that depend on them to be relinked or
18901 recompiled. However, you should be aware than all calls to DLL routines are
18902 slower since, as you will understand below, such calls are indirect.
18903
18904 To illustrate the remainder of this section, suppose that an application
18905 wants to use the services of a DLL @file{API.dll}. To use the services
18906 provided by @file{API.dll} you must statically link against an import
18907 library which contains a jump table with an entry for each routine and
18908 variable exported by the DLL. In the Microsoft world this import library is
18909 called @file{API.lib}. When using GNAT this import library is called either
18910 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
18911
18912 After you have statically linked your application with the import library
18913 and you run your application, here is what happens:
18914
18915 @enumerate
18916 @item
18917 Your application is loaded into memory.
18918
18919 @item
18920 The DLL @file{API.dll} is mapped into the address space of your
18921 application. This means that:
18922
18923 @itemize @bullet
18924 @item
18925 The DLL will use the stack of the calling thread.
18926
18927 @item
18928 The DLL will use the virtual address space of the calling process.
18929
18930 @item
18931 The DLL will allocate memory from the virtual address space of the calling
18932 process.
18933
18934 @item
18935 Handles (pointers) can be safely exchanged between routines in the DLL
18936 routines and routines in the application using the DLL.
18937 @end itemize
18938
18939 @item
18940 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
18941 part of your application are initialized with the addresses of the routines
18942 and variables in @file{API.dll}.
18943
18944 @item
18945 If present in @file{API.dll}, routines @code{DllMain} or
18946 @code{DllMainCRTStartup} are invoked. These routines typically contain
18947 the initialization code needed for the well-being of the routines and
18948 variables exported by the DLL.
18949 @end enumerate
18950
18951 @noindent
18952 There is an additional point which is worth mentioning. In the Windows
18953 world there are two kind of DLLs: relocatable and non-relocatable
18954 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
18955 in the target application address space. If the addresses of two
18956 non-relocatable DLLs overlap and these happen to be used by the same
18957 application, a conflict will occur and the application will run
18958 incorrectly. Hence, when possible, it is always preferable to use and
18959 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
18960 supported by GNAT.
18961
18962 As a side note, an interesting difference between Microsoft DLLs and
18963 Unix shared libraries, is the fact that on most Unix systems all public
18964 routines are exported by default in a Unix shared library, while under
18965 Windows the exported routines must be listed explicitly in a definition
18966 file (@pxref{The Definition File}).
18967
18968 @node Using DLLs with GNAT
18969 @section Using DLLs with GNAT
18970
18971 @menu
18972 * Creating an Ada Spec for the DLL Services::
18973 * Creating an Import Library::
18974 @end menu
18975
18976 @noindent
18977 To use the services of a DLL, say @file{API.dll}, in your Ada application
18978 you must have:
18979
18980 @enumerate
18981 @item
18982 The Ada spec for the routines and/or variables you want to access in
18983 @file{API.dll}. If not available this Ada spec must be built from the C/C++
18984 header files provided with the DLL.
18985
18986 @item
18987 The import library (@file{libAPI.a} or @file{API.lib}). As previously
18988 mentioned an import library is a statically linked library containing the
18989 import table which will be filled at load time to point to the actual
18990 @file{API.dll} routines. Sometimes you don't have an import library for the
18991 DLL you want to use. The following sections will explain how to build one.
18992
18993 @item
18994 The actual DLL, @file{API.dll}.
18995 @end enumerate
18996
18997 @noindent
18998 Once you have all the above, to compile an Ada application that uses the
18999 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
19000 you simply issue the command
19001
19002 @smallexample
19003 $ gnatmake my_ada_app -largs -lAPI
19004 @end smallexample
19005
19006 @noindent
19007 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
19008 tells the GNAT linker to look first for a library named @file{API.lib}
19009 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
19010 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
19011 contains the following pragma
19012
19013 @smallexample
19014 @b{pragma} Linker_Options ("-lAPI");
19015 @end smallexample
19016
19017 @noindent
19018 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
19019 command.
19020
19021 If any one of the items above is missing you will have to create it
19022 yourself. The following sections explain how to do so using as an
19023 example a fictitious DLL called @file{API.dll}.
19024
19025 @node Creating an Ada Spec for the DLL Services
19026 @subsection Creating an Ada Spec for the DLL Services
19027
19028 @noindent
19029 A DLL typically comes with a C/C++ header file which provides the
19030 definitions of the routines and variables exported by the DLL. The Ada
19031 equivalent of this header file is a package spec that contains definitions
19032 for the imported entities. If the DLL you intend to use does not come with
19033 an Ada spec you have to generate one such spec yourself. For example if
19034 the header file of @file{API.dll} is a file @file{api.h} containing the
19035 following two definitions:
19036
19037 @smallexample
19038 @group
19039 @cartouche
19040 int some_var;
19041 int get (char *);
19042 @end cartouche
19043 @end group
19044 @end smallexample
19045
19046 @noindent
19047 then the equivalent Ada spec could be:
19048
19049 @smallexample
19050 @group
19051 @cartouche
19052 @b{with} Interfaces.C.Strings;
19053 @b{package} API @b{is}
19054    @b{use} Interfaces;
19055
19056    Some_Var : C.int;
19057    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
19058
19059 @b{private}
19060    @b{pragma} Import (C, Get);
19061    @b{pragma} Import (DLL, Some_Var);
19062 @b{end} API;
19063 @end cartouche
19064 @end group
19065 @end smallexample
19066
19067 @noindent
19068 Note that a variable is @strong{always imported with a DLL convention}. A
19069 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
19070 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
19071 (@pxref{Windows Calling Conventions}).
19072
19073 @node Creating an Import Library
19074 @subsection Creating an Import Library
19075 @cindex Import library
19076
19077 @menu
19078 * The Definition File::
19079 * GNAT-Style Import Library::
19080 * Microsoft-Style Import Library::
19081 @end menu
19082
19083 @noindent
19084 If a Microsoft-style import library @file{API.lib} or a GNAT-style
19085 import library @file{libAPI.a} is available with @file{API.dll} you
19086 can skip this section. Otherwise read on.
19087
19088 @node The Definition File
19089 @subsubsection The Definition File
19090 @cindex Definition file
19091 @findex .def
19092
19093 @noindent
19094 As previously mentioned, and unlike Unix systems, the list of symbols
19095 that are exported from a DLL must be provided explicitly in Windows.
19096 The main goal of a definition file is precisely that: list the symbols
19097 exported by a DLL. A definition file (usually a file with a @code{.def}
19098 suffix) has the following structure:
19099
19100 @smallexample
19101 @group
19102 @cartouche
19103 [LIBRARY @i{name}]
19104 [DESCRIPTION @i{string}]
19105 EXPORTS
19106    @i{symbol1}
19107    @i{symbol2}
19108    ...
19109 @end cartouche
19110 @end group
19111 @end smallexample
19112
19113 @table @code
19114 @item LIBRARY @i{name}
19115 This section, which is optional, gives the name of the DLL.
19116
19117 @item DESCRIPTION @i{string}
19118 This section, which is optional, gives a description string that will be
19119 embedded in the import library.
19120
19121 @item EXPORTS
19122 This section gives the list of exported symbols (procedures, functions or
19123 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
19124 section of @file{API.def} looks like:
19125
19126 @smallexample
19127 @group
19128 @cartouche
19129 EXPORTS
19130    some_var
19131    get
19132 @end cartouche
19133 @end group
19134 @end smallexample
19135 @end table
19136
19137 @noindent
19138 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
19139 (@pxref{Windows Calling Conventions}) for a Stdcall
19140 calling convention function in the exported symbols list.
19141
19142 @noindent
19143 There can actually be other sections in a definition file, but these
19144 sections are not relevant to the discussion at hand.
19145
19146 @node GNAT-Style Import Library
19147 @subsubsection GNAT-Style Import Library
19148
19149 @noindent
19150 To create a static import library from @file{API.dll} with the GNAT tools
19151 you should proceed as follows:
19152
19153 @enumerate
19154 @item
19155 Create the definition file @file{API.def} (@pxref{The Definition File}).
19156 For that use the @code{dll2def} tool as follows:
19157
19158 @smallexample
19159 $ dll2def API.dll > API.def
19160 @end smallexample
19161
19162 @noindent
19163 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
19164 to standard output the list of entry points in the DLL. Note that if
19165 some routines in the DLL have the @code{Stdcall} convention
19166 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
19167 suffix then you'll have to edit @file{api.def} to add it.
19168
19169 @noindent
19170 Here are some hints to find the right @code{@@}@i{nn} suffix.
19171
19172 @enumerate
19173 @item
19174 If you have the Microsoft import library (.lib), it is possible to get
19175 the right symbols by using Microsoft @code{dumpbin} tool (see the
19176 corresponding Microsoft documentation for further details).
19177
19178 @smallexample
19179 $ dumpbin /exports api.lib
19180 @end smallexample
19181
19182 @item
19183 If you have a message about a missing symbol at link time the compiler
19184 tells you what symbol is expected. You just have to go back to the
19185 definition file and add the right suffix.
19186 @end enumerate
19187
19188 @item
19189 Build the import library @code{libAPI.a}, using @code{gnatdll}
19190 (@pxref{Using gnatdll}) as follows:
19191
19192 @smallexample
19193 $ gnatdll -e API.def -d API.dll
19194 @end smallexample
19195
19196 @noindent
19197 @code{gnatdll} takes as input a definition file @file{API.def} and the
19198 name of the DLL containing the services listed in the definition file
19199 @file{API.dll}. The name of the static import library generated is
19200 computed from the name of the definition file as follows: if the
19201 definition file name is @i{xyz}@code{.def}, the import library name will
19202 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
19203 @code{-e} could have been removed because the name of the definition
19204 file (before the "@code{.def}" suffix) is the same as the name of the
19205 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
19206 @end enumerate
19207
19208 @node Microsoft-Style Import Library
19209 @subsubsection Microsoft-Style Import Library
19210
19211 @noindent
19212 With GNAT you can either use a GNAT-style or Microsoft-style import
19213 library. A Microsoft import library is needed only if you plan to make an
19214 Ada DLL available to applications developed with Microsoft
19215 tools (@pxref{Mixed-Language Programming on Windows}).
19216
19217 To create a Microsoft-style import library for @file{API.dll} you
19218 should proceed as follows:
19219
19220 @enumerate
19221 @item
19222 Create the definition file @file{API.def} from the DLL. For this use either
19223 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
19224 tool (see the corresponding Microsoft documentation for further details).
19225
19226 @item
19227 Build the actual import library using Microsoft's @code{lib} utility:
19228
19229 @smallexample
19230 $ lib -machine:IX86 -def:API.def -out:API.lib
19231 @end smallexample
19232
19233 @noindent
19234 If you use the above command the definition file @file{API.def} must
19235 contain a line giving the name of the DLL:
19236
19237 @smallexample
19238 LIBRARY      "API"
19239 @end smallexample
19240
19241 @noindent
19242 See the Microsoft documentation for further details about the usage of
19243 @code{lib}.
19244 @end enumerate
19245
19246 @node Building DLLs with GNAT
19247 @section Building DLLs with GNAT
19248 @cindex DLLs, building
19249
19250 @menu
19251 * Limitations When Using Ada DLLs from Ada::
19252 * Exporting Ada Entities::
19253 * Ada DLLs and Elaboration::
19254 * Ada DLLs and Finalization::
19255 * Creating a Spec for Ada DLLs::
19256 * Creating the Definition File::
19257 * Using gnatdll::
19258 @end menu
19259
19260 @noindent
19261 This section explains how to build DLLs containing Ada code. These DLLs
19262 will be referred to as Ada DLLs in the remainder of this section.
19263
19264 The steps required to build an Ada DLL that is to be used by Ada as well as
19265 non-Ada applications are as follows:
19266
19267 @enumerate
19268 @item
19269 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
19270 @code{Stdcall} calling convention to avoid any Ada name mangling for the
19271 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
19272 skip this step if you plan to use the Ada DLL only from Ada applications.
19273
19274 @item
19275 Your Ada code must export an initialization routine which calls the routine
19276 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
19277 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
19278 routine exported by the Ada DLL must be invoked by the clients of the DLL
19279 to initialize the DLL.
19280
19281 @item
19282 When useful, the DLL should also export a finalization routine which calls
19283 routine @code{adafinal} generated by @code{gnatbind} to perform the
19284 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
19285 The finalization routine exported by the Ada DLL must be invoked by the
19286 clients of the DLL when the DLL services are no further needed.
19287
19288 @item
19289 You must provide a spec for the services exported by the Ada DLL in each
19290 of the programming languages to which you plan to make the DLL available.
19291
19292 @item
19293 You must provide a definition file listing the exported entities
19294 (@pxref{The Definition File}).
19295
19296 @item
19297 Finally you must use @code{gnatdll} to produce the DLL and the import
19298 library (@pxref{Using gnatdll}).
19299 @end enumerate
19300
19301 @node Limitations When Using Ada DLLs from Ada
19302 @subsection Limitations When Using Ada DLLs from Ada
19303
19304 @noindent
19305 When using Ada DLLs from Ada applications there is a limitation users
19306 should be aware of. Because on Windows the GNAT run time is not in a DLL of
19307 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
19308 each Ada DLL includes the services of the GNAT run time that are necessary
19309 to the Ada code inside the DLL. As a result, when an Ada program uses an
19310 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
19311 one in the main program.
19312
19313 It is therefore not possible to exchange GNAT run-time objects between the
19314 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
19315 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
19316 types, etc.
19317
19318 It is completely safe to exchange plain elementary, array or record types,
19319 Windows object handles, etc.
19320
19321 @node Exporting Ada Entities
19322 @subsection Exporting Ada Entities
19323 @cindex Export table
19324
19325 @noindent
19326 Building a DLL is a way to encapsulate a set of services usable from any
19327 application. As a result, the Ada entities exported by a DLL should be
19328 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
19329 any Ada name mangling. Please note that the @code{Stdcall} convention
19330 should only be used for subprograms, not for variables. As an example here
19331 is an Ada package @code{API}, spec and body, exporting two procedures, a
19332 function, and a variable:
19333
19334 @smallexample
19335 @group
19336 @cartouche
19337 @b{with} Interfaces.C; @b{use} Interfaces;
19338 @b{package} API @b{is}
19339    Count : C.int := 0;
19340    @b{function} Factorial (Val : C.int) @b{return} C.int;
19341
19342    @b{procedure} Initialize_API;
19343    @b{procedure} Finalize_API;
19344    --  @i{Initialization & Finalization routines. More in the next section.}
19345 @b{private}
19346    @b{pragma} Export (C, Initialize_API);
19347    @b{pragma} Export (C, Finalize_API);
19348    @b{pragma} Export (C, Count);
19349    @b{pragma} Export (C, Factorial);
19350 @b{end} API;
19351 @end cartouche
19352 @end group
19353 @end smallexample
19354
19355 @smallexample
19356 @group
19357 @cartouche
19358 @b{package body} API @b{is}
19359    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
19360       Fact : C.int := 1;
19361    @b{begin}
19362       Count := Count + 1;
19363       @b{for} K @b{in} 1 .. Val @b{loop}
19364          Fact := Fact * K;
19365       @b{end loop};
19366       @b{return} Fact;
19367    @b{end} Factorial;
19368
19369    @b{procedure} Initialize_API @b{is}
19370       @b{procedure} Adainit;
19371       @b{pragma} Import (C, Adainit);
19372    @b{begin}
19373       Adainit;
19374    @b{end} Initialize_API;
19375
19376    @b{procedure} Finalize_API @b{is}
19377       @b{procedure} Adafinal;
19378       @b{pragma} Import (C, Adafinal);
19379    @b{begin}
19380       Adafinal;
19381    @b{end} Finalize_API;
19382 @b{end} API;
19383 @end cartouche
19384 @end group
19385 @end smallexample
19386
19387 @noindent
19388 If the Ada DLL you are building will only be used by Ada applications
19389 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
19390 convention. As an example, the previous package could be written as
19391 follows:
19392
19393 @smallexample
19394 @group
19395 @cartouche
19396 @b{package} API @b{is}
19397    Count : Integer := 0;
19398    @b{function} Factorial (Val : Integer) @b{return} Integer;
19399
19400    @b{procedure} Initialize_API;
19401    @b{procedure} Finalize_API;
19402    --  @i{Initialization and Finalization routines.}
19403 @b{end} API;
19404 @end cartouche
19405 @end group
19406 @end smallexample
19407
19408 @smallexample
19409 @group
19410 @cartouche
19411 @b{package body} API @b{is}
19412    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
19413       Fact : Integer := 1;
19414    @b{begin}
19415       Count := Count + 1;
19416       @b{for} K @b{in} 1 .. Val @b{loop}
19417          Fact := Fact * K;
19418       @b{end loop};
19419       @b{return} Fact;
19420       @b{end} Factorial;
19421
19422    ...
19423    --  @i{The remainder of this package body is unchanged.}
19424 @b{end} API;
19425 @end cartouche
19426 @end group
19427 @end smallexample
19428
19429 @noindent
19430 Note that if you do not export the Ada entities with a @code{C} or
19431 @code{Stdcall} convention you will have to provide the mangled Ada names
19432 in the definition file of the Ada DLL
19433 (@pxref{Creating the Definition File}).
19434
19435 @node Ada DLLs and Elaboration
19436 @subsection Ada DLLs and Elaboration
19437 @cindex DLLs and elaboration
19438
19439 @noindent
19440 The DLL that you are building contains your Ada code as well as all the
19441 routines in the Ada library that are needed by it. The first thing a
19442 user of your DLL must do is elaborate the Ada code
19443 (@pxref{Elaboration Order Handling in GNAT}).
19444
19445 To achieve this you must export an initialization routine
19446 (@code{Initialize_API} in the previous example), which must be invoked
19447 before using any of the DLL services. This elaboration routine must call
19448 the Ada elaboration routine @code{adainit} generated by the GNAT binder
19449 (@pxref{Binding with Non-Ada Main Programs}). See the body of
19450 @code{Initialize_Api} for an example. Note that the GNAT binder is
19451 automatically invoked during the DLL build process by the @code{gnatdll}
19452 tool (@pxref{Using gnatdll}).
19453
19454 When a DLL is loaded, Windows systematically invokes a routine called
19455 @code{DllMain}. It would therefore be possible to call @code{adainit}
19456 directly from @code{DllMain} without having to provide an explicit
19457 initialization routine. Unfortunately, it is not possible to call
19458 @code{adainit} from the @code{DllMain} if your program has library level
19459 tasks because access to the @code{DllMain} entry point is serialized by
19460 the system (that is, only a single thread can execute "through" it at a
19461 time), which means that the GNAT run time will deadlock waiting for the
19462 newly created task to complete its initialization.
19463
19464 @node Ada DLLs and Finalization
19465 @subsection Ada DLLs and Finalization
19466 @cindex DLLs and finalization
19467
19468 @noindent
19469 When the services of an Ada DLL are no longer needed, the client code should
19470 invoke the DLL finalization routine, if available. The DLL finalization
19471 routine is in charge of releasing all resources acquired by the DLL. In the
19472 case of the Ada code contained in the DLL, this is achieved by calling
19473 routine @code{adafinal} generated by the GNAT binder
19474 (@pxref{Binding with Non-Ada Main Programs}).
19475 See the body of @code{Finalize_Api} for an
19476 example. As already pointed out the GNAT binder is automatically invoked
19477 during the DLL build process by the @code{gnatdll} tool
19478 (@pxref{Using gnatdll}).
19479
19480 @code{-g}
19481 @cindex @code{-g} (@code{gnatdll})
19482 @*
19483 Generate debugging information. This information is stored in the object
19484 file and copied from there to the final DLL file by the linker,
19485 where it can be read by the debugger. You must use the
19486 @code{-g} switch if you plan on using the debugger or the symbolic
19487 stack traceback.
19488
19489 @node Creating a Spec for Ada DLLs
19490 @subsection Creating a Spec for Ada DLLs
19491
19492 @noindent
19493 To use the services exported by the Ada DLL from another programming
19494 language (e.g. C), you have to translate the specs of the exported Ada
19495 entities in that language. For instance in the case of @code{API.dll},
19496 the corresponding C header file could look like:
19497
19498 @smallexample
19499 @group
19500 @cartouche
19501 extern int *__imp__count;
19502 #define count (*__imp__count)
19503 int factorial (int);
19504 @end cartouche
19505 @end group
19506 @end smallexample
19507
19508 @noindent
19509 It is important to understand that when building an Ada DLL to be used by
19510 other Ada applications, you need two different specs for the packages
19511 contained in the DLL: one for building the DLL and the other for using
19512 the DLL. This is because the @code{DLL} calling convention is needed to
19513 use a variable defined in a DLL, but when building the DLL, the variable
19514 must have either the @code{Ada} or @code{C} calling convention. As an
19515 example consider a DLL comprising the following package @code{API}:
19516
19517 @smallexample
19518 @group
19519 @cartouche
19520 @b{package} API @b{is}
19521    Count : Integer := 0;
19522    ...
19523    --  @i{Remainder of the package omitted.}
19524 @b{end} API;
19525 @end cartouche
19526 @end group
19527 @end smallexample
19528
19529 @noindent
19530 After producing a DLL containing package @code{API}, the spec that
19531 must be used to import @code{API.Count} from Ada code outside of the
19532 DLL is:
19533
19534 @smallexample
19535 @group
19536 @cartouche
19537 @b{package} API @b{is}
19538    Count : Integer;
19539    @b{pragma} Import (DLL, Count);
19540 @b{end} API;
19541 @end cartouche
19542 @end group
19543 @end smallexample
19544
19545 @node Creating the Definition File
19546 @subsection Creating the Definition File
19547
19548 @noindent
19549 The definition file is the last file needed to build the DLL. It lists
19550 the exported symbols. As an example, the definition file for a DLL
19551 containing only package @code{API} (where all the entities are exported
19552 with a @code{C} calling convention) is:
19553
19554 @smallexample
19555 @group
19556 @cartouche
19557 EXPORTS
19558     count
19559     factorial
19560     finalize_api
19561     initialize_api
19562 @end cartouche
19563 @end group
19564 @end smallexample
19565
19566 @noindent
19567 If the @code{C} calling convention is missing from package @code{API},
19568 then the definition file contains the mangled Ada names of the above
19569 entities, which in this case are:
19570
19571 @smallexample
19572 @group
19573 @cartouche
19574 EXPORTS
19575     api__count
19576     api__factorial
19577     api__finalize_api
19578     api__initialize_api
19579 @end cartouche
19580 @end group
19581 @end smallexample
19582
19583 @node Using gnatdll
19584 @subsection Using @code{gnatdll}
19585 @findex gnatdll
19586
19587 @menu
19588 * gnatdll Example::
19589 * gnatdll behind the Scenes::
19590 * Using dlltool::
19591 @end menu
19592
19593 @noindent
19594 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
19595 and non-Ada sources that make up your DLL have been compiled.
19596 @code{gnatdll} is actually in charge of two distinct tasks: build the
19597 static import library for the DLL and the actual DLL. The form of the
19598 @code{gnatdll} command is
19599
19600 @smallexample
19601 @cartouche
19602 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
19603 @end cartouche
19604 @end smallexample
19605
19606 @noindent
19607 where @i{list-of-files} is a list of ALI and object files. The object
19608 file list must be the exact list of objects corresponding to the non-Ada
19609 sources whose services are to be included in the DLL. The ALI file list
19610 must be the exact list of ALI files for the corresponding Ada sources
19611 whose services are to be included in the DLL. If @i{list-of-files} is
19612 missing, only the static import library is generated.
19613
19614 @noindent
19615 You may specify any of the following switches to @code{gnatdll}:
19616
19617 @table @code
19618 @item -a[@var{address}]
19619 @cindex @code{-a} (@code{gnatdll})
19620 Build a non-relocatable DLL at @var{address}. If @var{address} is not
19621 specified the default address @var{0x11000000} will be used. By default,
19622 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
19623 advise the reader to build relocatable DLL.
19624
19625 @item -b @var{address}
19626 @cindex @code{-b} (@code{gnatdll})
19627 Set the relocatable DLL base address. By default the address is
19628 @var{0x11000000}.
19629
19630 @item -d @var{dllfile}
19631 @cindex @code{-d} (@code{gnatdll})
19632 @var{dllfile} is the name of the DLL. This switch must be present for
19633 @code{gnatdll} to do anything. The name of the generated import library is
19634 obtained algorithmically from @var{dllfile} as shown in the following
19635 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
19636 @code{libxyz.a}. The name of the definition file to use (if not specified
19637 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
19638 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
19639 file used is @code{xyz.def}.
19640
19641 @item -e @var{deffile}
19642 @cindex @code{-e} (@code{gnatdll})
19643 @var{deffile} is the name of the definition file.
19644
19645 @item -h
19646 @cindex @code{-h} (@code{gnatdll})
19647 Help mode. Displays @code{gnatdll} switch usage information.
19648
19649 @item -Idir
19650 Direct @code{gnatdll} to search the @var{dir} directory for source and
19651 object files needed to build the DLL.
19652 (@pxref{Search Paths and the Run-Time Library (RTL)}).
19653
19654 @item -k
19655 Removes the @code{@@}@i{nn} suffix from the import library's exported
19656 names. You must specified this option if you want to use a
19657 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
19658 has been removed. This is the case for most of the Windows NT DLL for
19659 example. This option has no effect when @code{-n} option is specified.
19660
19661 @item -l @var{file}
19662 @cindex @code{-l} (@code{gnatdll})
19663 The list of ALI and object files used to build the DLL are listed in
19664 @var{file}, instead of being given in the command line. Each line in
19665 @var{file} contains the name of an ALI or object file.
19666
19667 @item -n
19668 @cindex @code{-n} (@code{gnatdll})
19669 No Import. Do not create the import library.
19670
19671 @item -q
19672 @cindex @code{-q} (@code{gnatdll})
19673 Quiet mode. Do not display unnecessary messages.
19674
19675 @item -v
19676 @cindex @code{-v} (@code{gnatdll})
19677 Verbose mode. Display extra information.
19678
19679 @item -largs @var{opts}
19680 @cindex @code{-largs} (@code{gnatdll})
19681 Linker options. Pass @var{opts} to the linker.
19682 @end table
19683
19684 @node gnatdll Example
19685 @subsubsection @code{gnatdll} Example
19686
19687 @noindent
19688 As an example the command to build a relocatable DLL from @file{api.adb}
19689 once @file{api.adb} has been compiled and @file{api.def} created is
19690
19691 @smallexample
19692 $ gnatdll -d api.dll api.ali
19693 @end smallexample
19694
19695 @noindent
19696 The above command creates two files: @file{libapi.a} (the import
19697 library) and @file{api.dll} (the actual DLL). If you want to create
19698 only the DLL, just type:
19699
19700 @smallexample
19701 $ gnatdll -d api.dll -n api.ali
19702 @end smallexample
19703
19704 @noindent
19705 Alternatively if you want to create just the import library, type:
19706
19707 @smallexample
19708 $ gnatdll -d api.dll
19709 @end smallexample
19710
19711 @node gnatdll behind the Scenes
19712 @subsubsection @code{gnatdll} behind the Scenes
19713
19714 @noindent
19715 This section details the steps involved in creating a DLL. @code{gnatdll}
19716 does these steps for you. Unless you are interested in understanding what
19717 goes on behind the scenes, you should skip this section.
19718
19719 We use the previous example of a DLL containing the Ada package @code{API},
19720 to illustrate the steps necessary to build a DLL. The starting point is a
19721 set of objects that will make up the DLL and the corresponding ALI
19722 files. In the case of this example this means that @file{api.o} and
19723 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
19724 the following:
19725
19726 @enumerate
19727 @item
19728 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
19729 the information necessary to generate relocation information for the
19730 DLL.
19731
19732 @smallexample
19733 @group
19734 $ gnatbind -n api
19735 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
19736 @end group
19737 @end smallexample
19738
19739 @noindent
19740 In addition to the base file, the @code{gnatlink} command generates an
19741 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
19742 asks @code{gnatlink} to generate the routines @code{DllMain} and
19743 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
19744 is loaded into memory.
19745
19746 @item
19747 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
19748 export table (@file{api.exp}). The export table contains the relocation
19749 information in a form which can be used during the final link to ensure
19750 that the Windows loader is able to place the DLL anywhere in memory.
19751
19752 @smallexample
19753 @group
19754 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19755           --output-exp api.exp
19756 @end group
19757 @end smallexample
19758
19759 @item
19760 @code{gnatdll} builds the base file using the new export table. Note that
19761 @code{gnatbind} must be called once again since the binder generated file
19762 has been deleted during the previous call to @code{gnatlink}.
19763
19764 @smallexample
19765 @group
19766 $ gnatbind -n api
19767 $ gnatlink api -o api.jnk api.exp -mdll
19768       -Wl,--base-file,api.base
19769 @end group
19770 @end smallexample
19771
19772 @item
19773 @code{gnatdll} builds the new export table using the new base file and
19774 generates the DLL import library @file{libAPI.a}.
19775
19776 @smallexample
19777 @group
19778 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19779           --output-exp api.exp --output-lib libAPI.a
19780 @end group
19781 @end smallexample
19782
19783 @item
19784 Finally @code{gnatdll} builds the relocatable DLL using the final export
19785 table.
19786
19787 @smallexample
19788 @group
19789 $ gnatbind -n api
19790 $ gnatlink api api.exp -o api.dll -mdll
19791 @end group
19792 @end smallexample
19793 @end enumerate
19794
19795 @node Using dlltool
19796 @subsubsection Using @code{dlltool}
19797
19798 @noindent
19799 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
19800 DLLs and static import libraries. This section summarizes the most
19801 common @code{dlltool} switches. The form of the @code{dlltool} command
19802 is
19803
19804 @smallexample
19805 $ dlltool [@var{switches}]
19806 @end smallexample
19807
19808 @noindent
19809 @code{dlltool} switches include:
19810
19811 @table @code
19812 @item --base-file @var{basefile}
19813 Read the base file @var{basefile} generated by the linker. This switch
19814 is used to create a relocatable DLL.
19815
19816 @item --def @var{deffile}
19817 Read the definition file.
19818
19819 @item --dllname @var{name}
19820 Gives the name of the DLL. This switch is used to embed the name of the
19821 DLL in the static import library generated by @code{dlltool} with switch
19822 @code{--output-lib}.
19823
19824 @item -k
19825 Kill @code{@@}@i{nn} from exported names
19826 (@pxref{Windows Calling Conventions}
19827 for a discussion about @code{Stdcall}-style symbols.
19828
19829 @item --help
19830 Prints the @code{dlltool} switches with a concise description.
19831
19832 @item --output-exp @var{exportfile}
19833 Generate an export file @var{exportfile}. The export file contains the
19834 export table (list of symbols in the DLL) and is used to create the DLL.
19835
19836 @item --output-lib @i{libfile}
19837 Generate a static import library @var{libfile}.
19838
19839 @item -v
19840 Verbose mode.
19841
19842 @item --as @i{assembler-name}
19843 Use @i{assembler-name} as the assembler. The default is @code{as}.
19844 @end table
19845
19846 @node GNAT and Windows Resources
19847 @section GNAT and Windows Resources
19848 @cindex Resources, windows
19849
19850 @menu
19851 * Building Resources::
19852 * Compiling Resources::
19853 * Using Resources::
19854 * Limitations::
19855 @end menu
19856
19857 @noindent
19858 Resources are an easy way to add Windows specific objects to your
19859 application. The objects that can be added as resources include:
19860
19861 @itemize @bullet
19862 @item
19863 menus
19864
19865 @item
19866 accelerators
19867
19868 @item
19869 dialog boxes
19870
19871 @item
19872 string tables
19873
19874 @item
19875 bitmaps
19876
19877 @item
19878 cursors
19879
19880 @item
19881 icons
19882
19883 @item
19884 fonts
19885 @end itemize
19886
19887 @noindent
19888 This section explains how to build, compile and use resources.
19889
19890 @node Building Resources
19891 @subsection Building Resources
19892 @cindex Resources, building
19893
19894 @noindent
19895 A resource file is an ASCII file. By convention resource files have an
19896 @file{.rc} extension.
19897 The easiest way to build a resource file is to use Microsoft tools
19898 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
19899 @code{dlgedit.exe} to build dialogs.
19900 It is always possible to build an @file{.rc} file yourself by writing a
19901 resource script.
19902
19903 It is not our objective to explain how to write a resource file. A
19904 complete description of the resource script language can be found in the
19905 Microsoft documentation.
19906
19907 @node Compiling Resources
19908 @subsection Compiling Resources
19909 @findex rc
19910 @findex rcl
19911 @findex res2coff
19912 @cindex Resources, compiling
19913
19914 @noindent
19915 This section describes how to build a GNAT-compatible (COFF) object file
19916 containing the resources. This is done using the Resource Compiler
19917 @code{rcl} as follows:
19918
19919 @smallexample
19920 $ rcl -i myres.rc -o myres.o
19921 @end smallexample
19922
19923 @noindent
19924 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
19925 file. You can specify an alternate preprocessor (usually named
19926 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
19927 all possible options may be obtained by entering the command @code{rcl}
19928 with no parameters.
19929
19930 It is also possible to use the Microsoft resource compiler @code{rc.exe}
19931 to produce a @file{.res} file (binary resource file). See the
19932 corresponding Microsoft documentation for further details. In this case
19933 you need to use @code{res2coff} to translate the @file{.res} file to a
19934 GNAT-compatible object file as follows:
19935
19936 @smallexample
19937 $ res2coff -i myres.res -o myres.o
19938 @end smallexample
19939
19940 @node Using Resources
19941 @subsection Using Resources
19942 @cindex Resources, using
19943
19944 @noindent
19945 To include the resource file in your program just add the
19946 GNAT-compatible object file for the resource(s) to the linker
19947 arguments. With @code{gnatmake} this is done by using the @code{-largs}
19948 option:
19949
19950 @smallexample
19951 $ gnatmake myprog -largs myres.o
19952 @end smallexample
19953
19954 @node Limitations
19955 @subsection Limitations
19956 @cindex Resources, limitations
19957
19958 @noindent
19959 In this section we describe the current limitations together with
19960 suggestions for workarounds.
19961
19962 @itemize @bullet
19963 @item
19964 @code{rcl} does not handle the @code{RCINCLUDE} directive.
19965 @*
19966 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
19967
19968 @item
19969 @code{rcl} does not handle the brackets as block delimiters.
19970 @*
19971 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
19972 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
19973 delimiters.
19974
19975 @item
19976 @code{rcl} does not handle @code{TypeLib} resources. This type of
19977 resource is used to build COM, DCOM or ActiveX objects.
19978 @*
19979 Workaround: use @code{rc}, the Microsoft resource compiler.
19980
19981 @item
19982 It is not possible to use @code{strip} to remove the debugging symbols
19983 from a program with resources.
19984 @*
19985 Workaround: use linker option @code{-s} to strip debugging symbols from
19986 the final executable.
19987 @end itemize
19988
19989 @node Debugging a DLL
19990 @section Debugging a DLL
19991 @cindex DLL debugging
19992
19993 @menu
19994 * The Program and the DLL Are Built with GCC/GNAT::
19995 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
19996 @end menu
19997
19998 @noindent
19999 Debugging a DLL is similar to debugging a standard program. But
20000 we have to deal with two different executable parts: the DLL and the
20001 program that uses it. We have the following four possibilities:
20002
20003 @enumerate 1
20004 @item
20005 The program and the DLL are built with @code{GCC/GNAT}.
20006 @item
20007 The program is built with foreign tools and the DLL is built with
20008 @code{GCC/GNAT}.
20009 @item
20010 The program is built with @code{GCC/GNAT} and the DLL is built with
20011 foreign tools.
20012 @item
20013 @end enumerate
20014
20015 @noindent
20016 In this section we address only cases one and two above.
20017 There is no point in trying to debug
20018 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
20019 information in it. To do so you must use a debugger compatible with the
20020 tools suite used to build the DLL.
20021
20022 @node The Program and the DLL Are Built with GCC/GNAT
20023 @subsection The Program and the DLL Are Built with GCC/GNAT
20024
20025 @noindent
20026 This is the simplest case. Both the DLL and the program have @code{GDB}
20027 compatible debugging information. It is then possible to break anywhere in
20028 the process. Let's suppose here that the main procedure is named
20029 @code{ada_main} and that in the DLL there is an entry point named
20030 @code{ada_dll}.
20031
20032 @noindent
20033 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
20034 program must have been built with the debugging information (see GNAT -g
20035 switch). Here are the step-by-step instructions for debugging it:
20036
20037 @enumerate 1
20038 @item Launch @code{GDB} on the main program.
20039
20040 @smallexample
20041 $ gdb -nw ada_main
20042 @end smallexample
20043
20044 @item Break on the main procedure and run the program.
20045
20046 @smallexample
20047 (gdb) break ada_main
20048 (gdb) run
20049 @end smallexample
20050
20051 @noindent
20052 This step is required to be able to set a breakpoint inside the DLL. As long
20053 as the program is not run, the DLL is not loaded. This has the
20054 consequence that the DLL debugging information is also not loaded, so it is not
20055 possible to set a breakpoint in the DLL.
20056
20057 @item Set a breakpoint inside the DLL
20058
20059 @smallexample
20060 (gdb) break ada_dll
20061 (gdb) run
20062 @end smallexample
20063
20064 @end enumerate
20065
20066 @noindent
20067 At this stage a breakpoint is set inside the DLL. From there on
20068 you can use the standard approach to debug the whole program
20069 (@pxref{Running and Debugging Ada Programs}).
20070
20071 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20072 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20073
20074 @menu
20075 * Debugging the DLL Directly::
20076 * Attaching to a Running Process::
20077 @end menu
20078
20079 @noindent
20080 In this case things are slightly more complex because it is not possible to
20081 start the main program and then break at the beginning to load the DLL and the
20082 associated DLL debugging information. It is not possible to break at the
20083 beginning of the program because there is no @code{GDB} debugging information,
20084 and therefore there is no direct way of getting initial control. This
20085 section addresses this issue by describing some methods that can be used
20086 to break somewhere in the DLL to debug it.
20087
20088 @noindent
20089 First suppose that the main procedure is named @code{main} (this is for
20090 example some C code built with Microsoft Visual C) and that there is a
20091 DLL named @code{test.dll} containing an Ada entry point named
20092 @code{ada_dll}.
20093
20094 @noindent
20095 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
20096 been built with debugging information (see GNAT -g option).
20097
20098 @node Debugging the DLL Directly
20099 @subsubsection Debugging the DLL Directly
20100
20101 @enumerate 1
20102 @item
20103 Launch the debugger on the DLL.
20104
20105 @smallexample
20106 $ gdb -nw test.dll
20107 @end smallexample
20108
20109 @item Set a breakpoint on a DLL subroutine.
20110
20111 @smallexample
20112 (gdb) break ada_dll
20113 @end smallexample
20114
20115 @item
20116 Specify the executable file to @code{GDB}.
20117
20118 @smallexample
20119 (gdb) exec-file main.exe
20120 @end smallexample
20121
20122 @item
20123 Run the program.
20124
20125 @smallexample
20126 (gdb) run
20127 @end smallexample
20128
20129 @noindent
20130 This will run the program until it reaches the breakpoint that has been
20131 set. From that point you can use the standard way to debug a program
20132 as described in (@pxref{Running and Debugging Ada Programs}).
20133
20134 @end enumerate
20135
20136 @noindent
20137 It is also possible to debug the DLL by attaching to a running process.
20138
20139 @node Attaching to a Running Process
20140 @subsubsection Attaching to a Running Process
20141 @cindex DLL debugging, attach to process
20142
20143 @noindent
20144 With @code{GDB} it is always possible to debug a running process by
20145 attaching to it. It is possible to debug a DLL this way. The limitation
20146 of this approach is that the DLL must run long enough to perform the
20147 attach operation. It may be useful for instance to insert a time wasting
20148 loop in the code of the DLL to meet this criterion.
20149
20150 @enumerate 1
20151
20152 @item Launch the main program @file{main.exe}.
20153
20154 @smallexample
20155 $ main
20156 @end smallexample
20157
20158 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
20159 that the process PID for @file{main.exe} is 208.
20160
20161 @item Launch gdb.
20162
20163 @smallexample
20164 $ gdb -nw
20165 @end smallexample
20166
20167 @item Attach to the running process to be debugged.
20168
20169 @smallexample
20170 (gdb) attach 208
20171 @end smallexample
20172
20173 @item Load the process debugging information.
20174
20175 @smallexample
20176 (gdb) symbol-file main.exe
20177 @end smallexample
20178
20179 @item Break somewhere in the DLL.
20180
20181 @smallexample
20182 (gdb) break ada_dll
20183 @end smallexample
20184
20185 @item Continue process execution.
20186
20187 @smallexample
20188 (gdb) continue
20189 @end smallexample
20190
20191 @end enumerate
20192
20193 @noindent
20194 This last step will resume the process execution, and stop at
20195 the breakpoint we have set. From there you can use the standard
20196 approach to debug a program as described in
20197 (@pxref{Running and Debugging Ada Programs}).
20198
20199 @node GNAT and COM/DCOM Objects
20200 @section GNAT and COM/DCOM Objects
20201 @findex COM
20202 @findex DCOM
20203
20204 @noindent
20205 This section is temporarily left blank.
20206
20207 @ignore
20208 @reread
20209 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
20210
20211 @node gnatreg : Registry Tool for NT
20212 @section @code{gnatreg} : Registry Tool for NT
20213 @findex gnatreg
20214 @cindex Registry
20215
20216 @menu
20217 * Changing the GNAT compiler to Use::
20218 * Adding/Changing a Library Path::
20219 * Removing a Library Path::
20220 * List Current Configuration::
20221 @end menu
20222
20223 @noindent
20224 This tool can be used to switch from one compiler to another and to manage
20225 the list of directories where GNAT must look to find packages. It is
20226 also a convenient way to do network installation of GNAT.
20227
20228 The form of the @code{gnatreg} command is
20229
20230 @smallexample
20231 $ gnatreg [@var{-hqcarf}] parameter
20232 @end smallexample
20233
20234 @noindent
20235 Commons options are
20236
20237 @table @code
20238
20239 @item -h
20240 print a usage message.
20241
20242 @item -q
20243 quiet/terse - display nothing, just do the job.
20244
20245 @item -f
20246 force mode - create the registry keys if they do not
20247 exist. @code{gnatreg} will exit with an error if this option is omitted
20248 and some registry keys are not setup correctly.
20249
20250 @end table
20251
20252 @subsection Changing the GNAT compiler to use
20253
20254 @smallexample
20255 $ gnatreg c:\gnatpro
20256 @end smallexample
20257
20258 @noindent
20259 This will setup the registry to use the GNAT compiler that has been
20260 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
20261 effectively a GNAT compiler. If you want to setup a network installation
20262 and if GNAT has never been installed on this computer you'll have to use
20263 the -f option.
20264
20265 @subsection Adding/Changing a library path
20266
20267 @smallexample
20268 $ gnatreg -a COMPNT=c:\ada\components
20269 @end smallexample
20270
20271 @noindent
20272 Add the directory c:\ada\components to the list of standards libraries. When
20273 running gnatmake the option -Ic:\ada\components is added automatically to the
20274 command line.
20275
20276 The directory c:\ada\components is associated with the name COMPNT. This
20277 name will be used to remove the library path.
20278
20279 @subsection Removing a library path
20280
20281 @smallexample
20282 $ gnatreg -r COMPNT
20283 @end smallexample
20284
20285 @noindent
20286 Remove the library path named COMPNT.
20287
20288 @subsection List current configuration
20289
20290 @smallexample
20291 $ gnatreg -c
20292 @end smallexample
20293
20294 @noindent
20295 @code{gnatreg} will display the GNAT and AdaGIDE path used and
20296 all the standards libraries and their associated names that have been set.
20297
20298 @end ignore
20299
20300
20301
20302 @node Performance Considerations
20303 @chapter Performance Considerations
20304 @cindex Performance
20305
20306 @noindent
20307 The GNAT system provides a number of options that allow a trade-off
20308 between
20309
20310 @itemize @bullet
20311 @item
20312 performance of the generated code
20313
20314 @item
20315 speed of compilation
20316
20317 @item
20318 minimization of dependences and recompilation
20319
20320 @item
20321 the degree of run-time checking.
20322 @end itemize
20323
20324 @noindent
20325 The defaults (if no options are selected) aim at improving the speed
20326 of compilation and minimizing dependences, at the expense of performance
20327 of the generated code:
20328
20329 @itemize @bullet
20330 @item
20331 no optimization
20332
20333 @item
20334 no inlining of subprogram calls
20335
20336 @item
20337 all run-time checks enabled except overflow and elaboration checks
20338 @end itemize
20339
20340 @noindent
20341 These options are suitable for most program development purposes. This
20342 chapter describes how you can modify these choices, and also provides
20343 some guidelines on debugging optimized code.
20344
20345 @menu
20346 * Controlling Run-Time Checks::
20347 * Optimization Levels::
20348 * Debugging Optimized Code::
20349 * Inlining of Subprograms::
20350 @end menu
20351
20352 @node Controlling Run-Time Checks
20353 @section Controlling Run-Time Checks
20354
20355 @noindent
20356 By default, GNAT generates all run-time checks, except arithmetic overflow
20357 checking for integer operations and checks for access before elaboration on
20358 subprogram calls. The latter are not required in default mode, because all
20359 necessary checking is done at compile time.
20360 @cindex @option{-gnatp} (@code{gcc})
20361 @cindex @option{-gnato} (@code{gcc})
20362 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
20363 be modified. @xref{Run-Time Checks}.
20364
20365 Our experience is that the default is suitable for most development
20366 purposes.
20367
20368 We treat integer overflow specially because these
20369 are quite expensive and in our experience are not as important as other
20370 run-time checks in the development process. Note that division by zero
20371 is not considered an overflow check, and divide by zero checks are
20372 generated where required by default.
20373
20374 Elaboration checks are off by default, and also not needed by default, since
20375 GNAT uses a static elaboration analysis approach that avoids the need for
20376 run-time checking. This manual contains a full chapter discussing the issue
20377 of elaboration checks, and if the default is not satisfactory for your use,
20378 you should read this chapter.
20379
20380 For validity checks, the minimal checks required by the Ada Reference
20381 Manual (for case statements and assignments to array elements) are on
20382 by default. These can be suppressed by use of the @option{-gnatVn} switch.
20383 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20384 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20385 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
20386 are also suppressed entirely if @option{-gnatp} is used.
20387
20388 @cindex Overflow checks
20389 @cindex Checks, overflow
20390 @findex Suppress
20391 @findex Unsuppress
20392 @cindex pragma Suppress
20393 @cindex pragma Unsuppress
20394 Note that the setting of the switches controls the default setting of
20395 the checks. They may be modified using either @code{pragma Suppress} (to
20396 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20397 checks) in the program source.
20398
20399 @node Optimization Levels
20400 @section Optimization Levels
20401 @cindex @code{-O} (@code{gcc})
20402
20403 @noindent
20404 The default is optimization off. This results in the fastest compile
20405 times, but GNAT makes absolutely no attempt to optimize, and the
20406 generated programs are considerably larger and slower than when
20407 optimization is enabled. You can use the
20408 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
20409 on the @code{gcc} command line to control the optimization level:
20410
20411 @table @code
20412 @item -O0
20413 no optimization (the default)
20414
20415 @item -O1
20416 medium level optimization
20417
20418 @item -O2
20419 full optimization
20420
20421 @item -O3
20422 full optimization, and also attempt automatic inlining of small
20423 subprograms within a unit (@pxref{Inlining of Subprograms}).
20424 @end table
20425
20426 Higher optimization levels perform more global transformations on the
20427 program and apply more expensive analysis algorithms in order to generate
20428 faster and more compact code. The price in compilation time, and the
20429 resulting improvement in execution time,
20430 both depend on the particular application and the hardware environment.
20431 You should experiment to find the best level for your application.
20432
20433 Note: Unlike some other compilation systems, @code{gcc} has
20434 been tested extensively at all optimization levels. There are some bugs
20435 which appear only with optimization turned on, but there have also been
20436 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20437 level of optimization does not improve the reliability of the code
20438 generator, which in practice is highly reliable at all optimization
20439 levels.
20440
20441 Note regarding the use of @code{-O3}: The use of this optimization level
20442 is generally discouraged with GNAT, since it often results in larger
20443 executables which run more slowly. See further discussion of this point
20444 in @pxref{Inlining of Subprograms}.
20445
20446 @node Debugging Optimized Code
20447 @section Debugging Optimized Code
20448
20449 @noindent
20450 Since the compiler generates debugging tables for a compilation unit before
20451 it performs optimizations, the optimizing transformations may invalidate some
20452 of the debugging data.  You therefore need to anticipate certain
20453 anomalous situations that may arise while debugging optimized code.  This
20454 section describes the most common cases.
20455
20456 @enumerate
20457 @item
20458 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
20459 bouncing back and forth in the code.  This may result from any of the following
20460 optimizations:
20461
20462 @itemize @bullet
20463 @item
20464 @i{Common subexpression elimination:} using a single instance of code for a
20465 quantity that the source computes several times.  As a result you
20466 may not be able to stop on what looks like a statement.
20467
20468 @item
20469 @i{Invariant code motion:} moving an expression that does not change within a
20470 loop, to the beginning of the loop.
20471
20472 @item
20473 @i{Instruction scheduling:} moving instructions so as to
20474 overlap loads and stores (typically) with other code, or in
20475 general to move computations of values closer to their uses. Often
20476 this causes you to pass an assignment statement without the assignment
20477 happening and then later bounce back to the statement when the
20478 value is actually needed.  Placing a breakpoint on a line of code
20479 and then stepping over it may, therefore, not always cause all the
20480 expected side-effects.
20481 @end itemize
20482
20483 @item
20484 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
20485 identical pieces of code are merged and the program counter suddenly
20486 jumps to a statement that is not supposed to be executed, simply because
20487 it (and the code following) translates to the same thing as the code
20488 that @emph{was} supposed to be executed.  This effect is typically seen in
20489 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20490 a @code{break} in a C @code{switch} statement.
20491
20492 @item
20493 @i{The "roving variable":} The symptom is an unexpected value in a variable.
20494 There are various reasons for this effect:
20495
20496 @itemize @bullet
20497 @item
20498 In a subprogram prologue, a parameter may not yet have been moved to its
20499 "home".
20500
20501 @item
20502 A variable may be dead, and its register re-used.  This is
20503 probably the most common cause.
20504
20505 @item
20506 As mentioned above, the assignment of a value to a variable may
20507 have been moved.
20508
20509 @item
20510 A variable may be eliminated entirely by value propagation or
20511 other means.  In this case, GCC may incorrectly generate debugging
20512 information for the variable
20513 @end itemize
20514
20515 @noindent
20516 In general, when an unexpected value appears for a local variable or parameter
20517 you should first ascertain if that value was actually computed by
20518 your program, as opposed to being incorrectly reported by the debugger.
20519 Record fields or
20520 array elements in an object designated by an access value
20521 are generally less of a problem, once you have ascertained that the access value
20522 is sensible.
20523 Typically, this means checking variables in the preceding code and in the
20524 calling subprogram to verify that the value observed is explainable from other
20525 values (one must apply the procedure recursively to those
20526 other values); or re-running the code and stopping a little earlier
20527 (perhaps before the call) and stepping to better see how the variable obtained
20528 the value in question; or continuing to step @emph{from} the point of the
20529 strange value to see if code motion had simply moved the variable's
20530 assignments later.
20531 @end enumerate
20532
20533 @node Inlining of Subprograms
20534 @section Inlining of Subprograms
20535
20536 @noindent
20537 A call to a subprogram in the current unit is inlined if all the
20538 following conditions are met:
20539
20540 @itemize @bullet
20541 @item
20542 The optimization level is at least @code{-O1}.
20543
20544 @item
20545 The called subprogram is suitable for inlining: It must be small enough
20546 and not contain nested subprograms or anything else that @code{gcc}
20547 cannot support in inlined subprograms.
20548
20549 @item
20550 The call occurs after the definition of the body of the subprogram.
20551
20552 @item
20553 @cindex pragma Inline
20554 @findex Inline
20555 Either @code{pragma Inline} applies to the subprogram or it is
20556 small and automatic inlining (optimization level @code{-O3}) is
20557 specified.
20558 @end itemize
20559
20560 @noindent
20561 Calls to subprograms in @code{with}'ed units are normally not inlined.
20562 To achieve this level of inlining, the following conditions must all be
20563 true:
20564
20565 @itemize @bullet
20566 @item
20567 The optimization level is at least @code{-O1}.
20568
20569 @item
20570 The called subprogram is suitable for inlining: It must be small enough
20571 and not contain nested subprograms or anything else @code{gcc} cannot
20572 support in inlined subprograms.
20573
20574 @item
20575 The call appears in a body (not in a package spec).
20576
20577 @item
20578 There is a @code{pragma Inline} for the subprogram.
20579
20580 @item
20581 @cindex @option{-gnatn} (@code{gcc})
20582 The @code{-gnatn} switch
20583 is used in the @code{gcc} command line
20584 @end itemize
20585
20586 Note that specifying the @option{-gnatn} switch causes additional
20587 compilation dependencies. Consider the following:
20588
20589 @smallexample
20590 @group
20591 @cartouche
20592 @b{package} R @b{is}
20593    @b{procedure} Q;
20594    @b{pragma} Inline (Q);
20595 @b{end} R;
20596 @b{package body} R @b{is}
20597    ...
20598 @b{end} R;
20599
20600 @b{with} R;
20601 @b{procedure} Main @b{is}
20602 @b{begin}
20603    ...
20604    R.Q;
20605 @b{end} Main;
20606 @end cartouche
20607 @end group
20608 @end smallexample
20609
20610 @noindent
20611 With the default behavior (no @option{-gnatn} switch specified), the
20612 compilation of the @code{Main} procedure depends only on its own source,
20613 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
20614 means that editing the body of @code{R} does not require recompiling
20615 @code{Main}.
20616
20617 On the other hand, the call @code{R.Q} is not inlined under these
20618 circumstances. If the @option{-gnatn} switch is present when @code{Main}
20619 is compiled, the call will be inlined if the body of @code{Q} is small
20620 enough, but now @code{Main} depends on the body of @code{R} in
20621 @file{r.adb} as well as on the spec. This means that if this body is edited,
20622 the main program must be recompiled. Note that this extra dependency
20623 occurs whether or not the call is in fact inlined by @code{gcc}.
20624
20625 The use of front end inlining with @option{-gnatN} generates similar
20626 additional dependencies.
20627
20628 @cindex @code{-fno-inline} (@code{gcc})
20629 Note: The @code{-fno-inline} switch
20630 can be used to prevent
20631 all inlining. This switch overrides all other conditions and ensures
20632 that no inlining occurs. The extra dependences resulting from
20633 @option{-gnatn} will still be active, even if
20634 this switch is used to suppress the resulting inlining actions.
20635
20636 Note regarding the use of @code{-O3}: There is no difference in inlining
20637 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
20638 pragma @code{Inline} assuming the use of @option{-gnatn}
20639 or @option{-gnatN} (the switches that activate inlining). If you have used
20640 pragma @code{Inline} in appropriate cases, then it is usually much better
20641 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
20642 in this case only has the effect of inlining subprograms you did not
20643 think should be inlined. We often find that the use of @code{-O3} slows
20644 down code by performing excessive inlining, leading to increased instruction
20645 cache pressure from the increased code size. So the bottom line here is
20646 that you should not automatically assume that @code{-O3} is better than
20647 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
20648 it actually improves performance.
20649
20650
20651 @include fdl.texi
20652 @c GNU Free Documentation License
20653
20654 @node Index,,GNU Free Documentation License, Top
20655 @unnumbered Index
20656
20657 @printindex cp
20658
20659 @contents
20660
20661 @bye